]> de.git.xonotic.org Git - xonotic/xonstat.git/blob - xonstat/batch/badges/gen_badges.py
Added 1st version of Archer's background; some finetuning
[xonotic/xonstat.git] / xonstat / batch / badges / gen_badges.py
1 #-*- coding: utf-8 -*-
2
3 import sys
4 import cairo as C
5 import sqlalchemy as sa
6 import sqlalchemy.sql.functions as func
7 from datetime import datetime
8 from mako.template import Template
9 from os import system
10 from pyramid.paster import bootstrap
11 from xonstat.models import *
12 from xonstat.views.player import player_info_data
13 from xonstat.util import qfont_decode
14 from colorsys import rgb_to_hls, hls_to_rgb
15
16
17 # similar to html_colors() from util.py
18 _contrast_threshold = 0.5
19
20 _dec_colors = [ (0.5,0.5,0.5),
21                 (1.0,0.0,0.0),
22                 (0.2,1.0,0.0),
23                 (1.0,1.0,0.0),
24                 (0.2,0.4,1.0),
25                 (0.2,1.0,1.0),
26                 (1.0,0.2,102),
27                 (1.0,1.0,1.0),
28                 (0.6,0.6,0.6),
29                 (0.5,0.5,0.5)
30             ]
31
32
33 # maximal number of query results (for testing, set to 0 to get all)
34 NUM_PLAYERS = 100
35
36 # image dimensions (likely breaks layout if changed)
37 WIDTH   = 560
38 HEIGHT  = 70
39
40 # output filename, parameter is player id
41 OUTPUT = "output/%d.png"
42
43
44 NICK_POS        = (5,18)
45 NICK_MAXWIDTH   = 330
46
47 GAMES_POS       = (60,35)
48 GAMES_WIDTH     = 110
49
50 WINLOSS_POS     = (508,6)
51 WINLOSS_WIDTH   = 104
52
53 KILLDEATH_POS   = (390,6)
54 KILLDEATH_WIDTH = 104
55
56 PLAYTIME_POS    = (452,64)
57 PLAYTIME_WIDTH  = 218
58
59
60 # parameters to affect the output, could be changed via URL
61 params = {
62     'bg':           8,                      # 0 - black, 1 - dark_wall, ...
63     'overlay':      0,                      # 0 - none, 1 - default overlay, ...
64     'font':         0,                      # 0 - xolonium, 1 - dejavu sans
65 }
66
67
68 # parse cmdline parameters (for testing)
69 for arg in sys.argv[1:]:
70     try:
71         k,v = arg.split("=")
72         if params.has_key(k.lower()):
73             params[k] = int(v)
74     except:
75         continue
76
77
78 def get_data(player):
79     """Return player data as dict.
80     
81     This function is similar to the function in player.py but more optimized
82     for this purpose.
83     """
84
85     # total games
86     # wins/losses
87     # kills/deaths
88     # duel/dm/tdm/ctf elo + rank
89     
90     player_id = player.player_id
91     
92     total_stats = {}
93     
94     games_played = DBSession.query(
95             Game.game_type_cd, func.count(), func.sum(PlayerGameStat.alivetime)).\
96             filter(Game.game_id == PlayerGameStat.game_id).\
97             filter(PlayerGameStat.player_id == player_id).\
98             group_by(Game.game_type_cd).\
99             order_by(func.count().desc()).\
100             limit(3).all()  # limit to 3 gametypes!
101     
102     total_stats['games'] = 0
103     total_stats['games_breakdown'] = {}  # this is a dictionary inside a dictionary .. dictception?
104     total_stats['games_alivetime'] = {}
105     total_stats['gametypes'] = []
106     for (game_type_cd, games, alivetime) in games_played:
107         total_stats['games'] += games
108         total_stats['gametypes'].append(game_type_cd)
109         total_stats['games_breakdown'][game_type_cd] = games
110         total_stats['games_alivetime'][game_type_cd] = alivetime
111     
112     (total_stats['kills'], total_stats['deaths'], total_stats['alivetime'],) = DBSession.query(
113             func.sum(PlayerGameStat.kills),
114             func.sum(PlayerGameStat.deaths),
115             func.sum(PlayerGameStat.alivetime)).\
116             filter(PlayerGameStat.player_id == player_id).\
117             one()
118     
119     (total_stats['wins'],) = DBSession.query(
120             func.count("*")).\
121             filter(Game.game_id == PlayerGameStat.game_id).\
122             filter(PlayerGameStat.player_id == player_id).\
123             filter(Game.winner == PlayerGameStat.team or PlayerGameStat.rank == 1).\
124             one()
125     
126     ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
127             from_statement(
128                 "select pr.game_type_cd, pr.rank, overall.max_rank "
129                 "from player_ranks pr,  "
130                    "(select game_type_cd, max(rank) max_rank "
131                     "from player_ranks  "
132                     "group by game_type_cd) overall "
133                 "where pr.game_type_cd = overall.game_type_cd  "
134                 "and player_id = :player_id "
135                 "order by rank").\
136             params(player_id=player_id).all()
137     
138     ranks_dict = {}
139     for gtc,rank,max_rank in ranks:
140         ranks_dict[gtc] = (rank, max_rank)
141
142     elos = DBSession.query(PlayerElo).\
143             filter_by(player_id=player_id).\
144             order_by(PlayerElo.elo.desc()).\
145             all()
146     
147     elos_dict = {}
148     for elo in elos:
149         if elo.games > 32:
150             elos_dict[elo.game_type_cd] = elo.elo
151     
152     data = {
153             'player':player,
154             'total_stats':total_stats,
155             'ranks':ranks_dict,
156             'elos':elos_dict,
157         }
158         
159     #print data
160     return data
161
162
163 def render_image(data):
164     """Render an image from the given data fields."""
165     
166     font = "Xolonium"
167     if params['font'] == 1:
168         font = "DejaVu Sans"
169
170     total_stats = data['total_stats']
171     total_games = total_stats['games']
172     elos = data["elos"]
173     ranks = data["ranks"]
174
175
176     ## create background
177
178     surf = C.ImageSurface(C.FORMAT_RGB24, WIDTH, HEIGHT)
179     ctx = C.Context(surf)
180     ctx.set_antialias(C.ANTIALIAS_GRAY)
181
182     # draw background (just plain fillcolor)
183     if params['bg'] == 0:
184         ctx.rectangle(0, 0, WIDTH, HEIGHT)
185         ctx.set_source_rgb(0.04, 0.04, 0.04)  # bgcolor of Xonotic forum
186         ctx.fill()
187     
188     # draw background image (try to get correct tiling, too)
189     if params['bg'] > 0:
190         bg = None
191         if params['bg'] == 1:
192             bg = C.ImageSurface.create_from_png("img/dark_wall.png")
193         elif params['bg'] == 2:
194             bg = C.ImageSurface.create_from_png("img/asfalt.png")
195         elif params['bg'] == 3:
196             bg = C.ImageSurface.create_from_png("img/broken_noise.png")
197         elif params['bg'] == 4:
198             bg = C.ImageSurface.create_from_png("img/burried.png")
199         elif params['bg'] == 5:
200             bg = C.ImageSurface.create_from_png("img/dark_leather.png")
201         elif params['bg'] == 6:
202             bg = C.ImageSurface.create_from_png("img/txture.png")
203         elif params['bg'] == 7:
204             bg = C.ImageSurface.create_from_png("img/black_linen_v2.png")
205         elif params['bg'] == 8:
206             bg = C.ImageSurface.create_from_png("img/background_archer-v1.png")
207         
208         # tile image
209         if bg:
210             bg_w, bg_h = bg.get_width(), bg.get_height()
211             bg_xoff = 0
212             while bg_xoff < WIDTH:
213                 bg_yoff = 0
214                 while bg_yoff < HEIGHT:
215                     ctx.set_source_surface(bg, bg_xoff, bg_yoff)
216                     ctx.paint()
217                     bg_yoff += bg_h
218                 bg_xoff += bg_w
219     
220     # draw overlay graphic
221     if params['overlay'] > 0:
222         overlay = None
223         if params['overlay'] == 1:
224             overlay = C.ImageSurface.create_from_png("img/overlay.png")
225         if overlay:
226             ctx.set_source_surface(overlay, 0, 0)
227             ctx.mask_surface(overlay)
228             ctx.paint()
229
230
231     ## draw player's nickname with fancy colors
232     
233     # deocde nick, strip all weird-looking characters
234     qstr = qfont_decode(player.nick).replace('^^', '^').replace(u'\x00', ' ')
235     chars = []
236     for c in qstr:
237         if ord(c) < 128:
238             chars.append(c)
239     qstr = ''.join(chars)
240     stripped_nick = strip_colors(qstr)
241     
242     # fontsize is reduced if width gets too large
243     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
244     ctx.set_font_size(20)
245     xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
246     if tw > NICK_MAXWIDTH:
247         ctx.set_font_size(18)
248         xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
249         if tw > NICK_MAXWIDTH:
250             ctx.set_font_size(16)
251             xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
252             if tw > NICK_MAXWIDTH:
253                 ctx.set_font_size(14)
254                 xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
255                 if tw > NICK_MAXWIDTH:
256                     ctx.set_font_size(12)
257     
258     
259     # split up nick into colored segments and draw each of them
260     
261     # split nick into colored segments
262     parts = []
263     pos = 1
264     while True:
265         npos = qstr.find('^', pos)
266         if npos < 0:
267             parts.append(qstr[pos-1:])
268             break;
269         parts.append(qstr[pos-1:npos])
270         pos = npos+1
271     
272     xoffset = 0
273     for txt in parts:
274         r,g,b = _dec_colors[7]
275         try:
276             if txt.startswith('^'):
277                 txt = txt[1:]
278                 if txt.startswith('x'):
279                     r = int(txt[1] * 2, 16) / 255.0
280                     g = int(txt[2] * 2, 16) / 255.0
281                     b = int(txt[3] * 2, 16) / 255.0
282                     hue, light, satur = rgb_to_hls(r, g, b)
283                     if light < _contrast_threshold:
284                         light = _contrast_threshold
285                         r, g, b = hls_to_rgb(hue, light, satur)
286                     txt = txt[4:]
287                 else:
288                     r,g,b = _dec_colors[int(txt[0])]
289                     txt = txt[1:]
290         except:
291             r,g,b = _dec_colors[7]
292         
293         if len(txt) < 1:
294             # only colorcode and no real text, skip this
295             continue
296         
297         ctx.set_source_rgb(r, g, b)
298         ctx.move_to(NICK_POS[0] + xoffset, NICK_POS[1])
299         ctx.show_text(txt)
300
301         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
302         xoffset += tw + 2
303
304
305     ## print elos and ranks
306     
307     # show up to three gametypes the player has participated in
308     xoffset = 0
309     for gt in total_stats['gametypes'][:3]:
310         ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
311         ctx.set_font_size(10)
312         ctx.set_source_rgb(1.0, 1.0, 1.0)
313         txt = "[ %s ]" % gt.upper()
314         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
315         ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]-yoff-4)
316         ctx.show_text(txt)
317         
318         old_aa = ctx.get_antialias()
319         ctx.set_antialias(C.ANTIALIAS_NONE)
320         ctx.set_source_rgb(0.8, 0.8, 0.8)
321         ctx.set_line_width(1)
322         ctx.move_to(GAMES_POS[0]+xoffset-GAMES_WIDTH/2+5, GAMES_POS[1]+8)
323         ctx.line_to(GAMES_POS[0]+xoffset+GAMES_WIDTH/2-5, GAMES_POS[1]+8)
324         ctx.stroke()
325         ctx.move_to(GAMES_POS[0]+xoffset-GAMES_WIDTH/2+5, GAMES_POS[1]+32)
326         ctx.line_to(GAMES_POS[0]+xoffset+GAMES_WIDTH/2-5, GAMES_POS[1]+32)
327         ctx.stroke()
328         ctx.set_antialias(old_aa)
329         
330         if not elos.has_key(gt) or not ranks.has_key(gt):
331             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
332             ctx.set_font_size(12)
333             ctx.set_source_rgb(0.8, 0.2, 0.2)
334             txt = "no stats yet!"
335             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
336             ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+28-yoff-4)
337             ctx.save()
338             ctx.rotate(math.radians(-10))
339             ctx.show_text(txt)
340             ctx.restore()
341         else:
342             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
343             ctx.set_font_size(10)
344             ctx.set_source_rgb(1.0, 1.0, 0.5)
345             txt = "Elo: %.0f" % round(elos[gt], 0)
346             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
347             ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+15-yoff-4)
348             ctx.show_text(txt)
349             
350             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
351             ctx.set_font_size(8)
352             ctx.set_source_rgb(0.8, 0.8, 0.8)
353             txt = "Rank %d of %d" % ranks[gt]
354             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
355             ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+25-yoff-3)
356             ctx.show_text(txt)
357         
358         xoffset += GAMES_WIDTH
359
360
361     # print win percentage
362     
363     ctx.rectangle(WINLOSS_POS[0]-WINLOSS_WIDTH/2, WINLOSS_POS[1]-7, WINLOSS_WIDTH, 15)
364     ctx.set_source_rgba(0.8, 0.8, 0.8, 0.1)
365     ctx.fill();
366     
367     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
368     ctx.set_font_size(10)
369     ctx.set_source_rgb(0.8, 0.8, 0.8)
370     txt = "Win Percentage"
371     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
372     ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]-yoff-3)
373     ctx.show_text(txt)
374     
375     wins, losses = total_stats["wins"], total_games-total_stats["wins"]
376     txt = "???"
377     try:
378         ratio = float(wins)/total_games
379         txt = "%.2f%%" % round(ratio * 100, 2)
380     except:
381         ratio = 0
382     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
383     ctx.set_font_size(12)
384     if ratio >= 0.90:
385         ctx.set_source_rgb(0.2, 1.0, 1.0)
386     elif ratio >= 0.75:
387         ctx.set_source_rgb(0.5, 1.0, 1.0)
388     elif ratio >= 0.5:
389         ctx.set_source_rgb(0.5, 1.0, 0.8)
390     elif ratio >= 0.25:
391         ctx.set_source_rgb(0.8, 1.0, 0.5)
392     else:
393         ctx.set_source_rgb(1.0, 1.0, 0.5)
394     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
395     ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+18-yoff-4)
396     ctx.show_text(txt)
397     
398     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
399     ctx.set_font_size(8)
400     ctx.set_source_rgb(0.6, 0.8, 0.8)
401     txt = "%d win" % wins
402     if wins != 1:
403         txt += "s"
404     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
405     ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+30-yoff-3)
406     ctx.show_text(txt)
407     ctx.set_source_rgb(0.8, 0.8, 0.6)
408     txt = "%d loss" % losses
409     if losses != 1:
410         txt += "es"
411     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
412     ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+40-yoff-3)
413     ctx.show_text(txt)
414
415
416     # print kill/death ratio
417     
418     ctx.rectangle(KILLDEATH_POS[0]-KILLDEATH_WIDTH/2, KILLDEATH_POS[1]-7, KILLDEATH_WIDTH, 15)
419     ctx.set_source_rgba(0.8, 0.8, 0.8, 0.1)
420     ctx.fill()
421     
422     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
423     ctx.set_font_size(10)
424     ctx.set_source_rgb(0.8, 0.8, 0.8)
425     txt = "Kill Ratio"
426     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
427     ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]-yoff-3)
428     ctx.show_text(txt)
429     
430     kills, deaths = total_stats['kills'] , total_stats['deaths'] 
431     txt = "???"
432     try:
433         ratio = float(kills)/deaths
434         txt = "%.3f" % round(ratio, 3)
435     except:
436         ratio = 0
437     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
438     ctx.set_font_size(12)
439     if ratio >= 3:
440         ctx.set_source_rgb(0.0, 1.0, 0.0)
441     elif ratio >= 2:
442         ctx.set_source_rgb(0.2, 1.0, 0.2)
443     elif ratio >= 1:
444         ctx.set_source_rgb(0.5, 1.0, 0.5)
445     elif ratio >= 0.5:
446         ctx.set_source_rgb(1.0, 0.5, 0.5)
447     else:
448         ctx.set_source_rgb(1.0, 0.2, 0.2)
449     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
450     ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+18-yoff-4)
451     ctx.show_text(txt)
452
453     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
454     ctx.set_font_size(8)
455     ctx.set_source_rgb(0.6, 0.8, 0.6)
456     txt = "%d kill" % kills
457     if kills != 1:
458         txt += "s"
459     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
460     ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+30-yoff-3)
461     ctx.show_text(txt)
462     ctx.set_source_rgb(0.8, 0.6, 0.6)
463     txt = "%d death" % deaths
464     if deaths != 1:
465         txt += "s"
466     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
467     ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+40-yoff-3)
468     ctx.show_text(txt)
469
470
471     # print playing time
472     
473     ctx.rectangle( PLAYTIME_POS[0]-PLAYTIME_WIDTH/2, PLAYTIME_POS[1]-7, PLAYTIME_WIDTH, 14)
474     ctx.set_source_rgba(0.8, 0.8, 0.8, 0.6)
475     ctx.fill();
476     
477     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
478     ctx.set_font_size(10)
479     ctx.set_source_rgb(0.1, 0.1, 0.1)
480     txt = "Playing time: %s" % str(total_stats['alivetime'])
481     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
482     ctx.move_to(PLAYTIME_POS[0]-xoff-tw/2, PLAYTIME_POS[1]-yoff-4)
483     ctx.show_text(txt)
484
485
486     # save to PNG
487     surf.write_to_png(OUTPUT % data['player'].player_id)
488
489
490 # environment setup
491 env = bootstrap('../../../development.ini')
492 req = env['request']
493 req.matchdict = {'id':3}
494
495 print "Requesting player data from db ..."
496 start = datetime.now()
497 players = DBSession.query(Player).\
498         filter(Player.player_id == PlayerElo.player_id).\
499         filter(Player.nick != None).\
500         filter(Player.player_id > 2).\
501         filter(Player.active_ind == True).\
502         limit(NUM_PLAYERS).all()
503 stop = datetime.now()
504 print "Query took %.2f seconds" % (stop-start).total_seconds()
505
506 print "Creating badges for %d active players ..." % len(players)
507 start = datetime.now()
508 data_time, render_time = 0,0
509 for player in players:
510     req.matchdict['id'] = player.player_id
511     
512     sstart = datetime.now()
513     #data = player_info_data(req)
514     data = get_data(player)
515     sstop = datetime.now()
516     data_time += (sstop-sstart).total_seconds()
517     
518     print "\r  #%-5d" % player.player_id,
519     sys.stdout.flush()
520
521     sstart = datetime.now()
522     render_image(data)
523     sstop = datetime.now()
524     render_time += (sstop-sstart).total_seconds()
525 print
526
527 stop = datetime.now()
528 print "Creating the badges took %.2f seconds (%.2f s per player)" % ((stop-start).total_seconds(), (stop-start).total_seconds()/float(len(players)))
529 print " Total time for getting data: %.2f s" % data_time
530 print " Total time for renering images: %.2f s" % render_time
531