]> de.git.xonotic.org Git - xonotic/xonstat.git/blob - xonstat/batch/badges/gen_badges.py
More work on the badges generator
[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     = (505,11)
51 WINLOSS_WIDTH   = 100
52
53 KILLDEATH_POS   = (395,11)
54 KILLDEATH_WIDTH = 100
55
56 PLAYTIME_POS    = (450,64)
57 PLAYTIME_WIDTH  = 210
58
59
60 # parameters to affect the output, could be changed via URL
61 params = {
62     'bg':           1,                      # 0 - black, 1 - dark_wall, ...
63     'overlay':      1,                      # 0 - none, 1 - Archer, ...
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         
206         # tile image
207         if bg:
208             bg_w, bg_h = bg.get_width(), bg.get_height()
209             bg_xoff = 0
210             while bg_xoff < WIDTH:
211                 bg_yoff = 0
212                 while bg_yoff < HEIGHT:
213                     ctx.set_source_surface(bg, bg_xoff, bg_yoff)
214                     ctx.paint()
215                     bg_yoff += bg_h
216                 bg_xoff += bg_w
217     
218     # draw overlay graphic
219     if params['overlay'] > 0:
220         overlay = None
221         if params['overlay'] == 1:
222             overlay = C.ImageSurface.create_from_png("img/overlay.png")
223         if overlay:
224             ctx.set_source_surface(overlay, 0, 0)
225             ctx.mask_surface(overlay)
226             ctx.paint()
227
228
229     ## draw player's nickname with fancy colors
230     
231     # deocde nick, strip all weird-looking characters
232     qstr = qfont_decode(player.nick).replace('^^', '^').replace(u'\x00', ' ')
233     chars = []
234     for c in qstr:
235         if ord(c) < 128:
236             chars.append(c)
237     qstr = ''.join(chars)
238     stripped_nick = strip_colors(qstr)
239     
240     # fontsize is reduced if width gets too large
241     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
242     ctx.set_font_size(20)
243     xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
244     if tw > NICK_MAXWIDTH:
245         ctx.set_font_size(18)
246         xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
247         if tw > NICK_MAXWIDTH:
248             ctx.set_font_size(16)
249             xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
250             if tw > NICK_MAXWIDTH:
251                 ctx.set_font_size(14)
252                 xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
253                 if tw > NICK_MAXWIDTH:
254                     ctx.set_font_size(12)
255     
256     
257     # split up nick into colored segments and draw each of them
258     
259     # split nick into colored segments
260     parts = []
261     pos = 1
262     while True:
263         npos = qstr.find('^', pos)
264         if npos < 0:
265             parts.append(qstr[pos-1:])
266             break;
267         parts.append(qstr[pos-1:npos])
268         pos = npos+1
269     
270     xoffset = 0
271     for txt in parts:
272         r,g,b = _dec_colors[7]
273         try:
274             if txt.startswith('^'):
275                 txt = txt[1:]
276                 if txt.startswith('x'):
277                     r = int(txt[1] * 2, 16) / 255.0
278                     g = int(txt[2] * 2, 16) / 255.0
279                     b = int(txt[3] * 2, 16) / 255.0
280                     hue, light, satur = rgb_to_hls(r, g, b)
281                     if light < _contrast_threshold:
282                         light = _contrast_threshold
283                         r, g, b = hls_to_rgb(hue, light, satur)
284                     txt = txt[4:]
285                 else:
286                     r,g,b = _dec_colors[int(txt[0])]
287                     txt = txt[1:]
288         except:
289             r,g,b = _dec_colors[7]
290         
291         if len(txt) < 1:
292             # only colorcode and no real text, skip this
293             continue
294         
295         ctx.set_source_rgb(r, g, b)
296         ctx.move_to(NICK_POS[0] + xoffset, NICK_POS[1])
297         ctx.show_text(txt)
298
299         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
300         xoffset += tw + 2
301
302
303     ## print elos and ranks
304     
305     # show up to three gametypes the player has participated in
306     xoffset = 0
307     for gt in total_stats['gametypes'][:3]:
308         ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
309         ctx.set_font_size(10)
310         ctx.set_source_rgb(1.0, 1.0, 1.0)
311         txt = "[ %s ]" % gt.upper()
312         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
313         ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]-yoff-4)
314         ctx.show_text(txt)
315         
316         old_aa = ctx.get_antialias()
317         ctx.set_antialias(C.ANTIALIAS_NONE)
318         ctx.set_source_rgb(0.8, 0.8, 0.8)
319         ctx.set_line_width(1)
320         ctx.move_to(GAMES_POS[0]+xoffset-GAMES_WIDTH/2+5, GAMES_POS[1]+8)
321         ctx.line_to(GAMES_POS[0]+xoffset+GAMES_WIDTH/2-5, GAMES_POS[1]+8)
322         ctx.stroke()
323         ctx.move_to(GAMES_POS[0]+xoffset-GAMES_WIDTH/2+5, GAMES_POS[1]+32)
324         ctx.line_to(GAMES_POS[0]+xoffset+GAMES_WIDTH/2-5, GAMES_POS[1]+32)
325         ctx.stroke()
326         ctx.set_antialias(old_aa)
327         
328         if not elos.has_key(gt) or not ranks.has_key(gt):
329             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
330             ctx.set_font_size(12)
331             ctx.set_source_rgb(0.8, 0.2, 0.2)
332             txt = "no stats yet!"
333             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
334             ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+28-yoff-4)
335             ctx.save()
336             ctx.rotate(math.radians(-10))
337             ctx.show_text(txt)
338             ctx.restore()
339         else:
340             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
341             ctx.set_font_size(10)
342             ctx.set_source_rgb(1.0, 1.0, 0.5)
343             txt = "Elo: %.0f" % round(elos[gt], 0)
344             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
345             ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+15-yoff-4)
346             ctx.show_text(txt)
347             
348             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
349             ctx.set_font_size(8)
350             ctx.set_source_rgb(0.8, 0.8, 0.8)
351             txt = "Rank %d of %d" % ranks[gt]
352             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
353             ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+25-yoff-3)
354             ctx.show_text(txt)
355         
356         xoffset += GAMES_WIDTH
357
358
359     # print win percentage
360     
361     ctx.rectangle(WINLOSS_POS[0]-WINLOSS_WIDTH/2, WINLOSS_POS[1]-7, WINLOSS_WIDTH, 14)
362     ctx.set_source_rgba(0.8, 0.8, 0.8, 0.1)
363     ctx.fill();
364     
365     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
366     ctx.set_font_size(10)
367     ctx.set_source_rgb(0.8, 0.8, 0.8)
368     txt = "Win Percentage"
369     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
370     ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]-yoff-3)
371     ctx.show_text(txt)
372     
373     txt = "???"
374     if total_games > 0 and total_stats['wins'] is not None:
375         ratio = float(total_stats['wins'])/total_games
376         txt = "%.2f%%" % round(ratio * 100, 2)
377     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
378     ctx.set_font_size(12)
379     if ratio >= 0.90:
380         ctx.set_source_rgb(0.2, 1.0, 1.0)
381     elif ratio >= 0.75:
382         ctx.set_source_rgb(0.5, 1.0, 1.0)
383     elif ratio >= 0.5:
384         ctx.set_source_rgb(0.5, 1.0, 0.8)
385     elif ratio >= 0.25:
386         ctx.set_source_rgb(0.8, 1.0, 0.5)
387     else:
388         ctx.set_source_rgb(1.0, 1.0, 0.5)
389     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
390     ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+16-yoff-4)
391     ctx.show_text(txt)
392     
393     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
394     ctx.set_font_size(8)
395     ctx.set_source_rgb(0.6, 0.8, 0.6)
396     txt = "%d wins" % total_stats["wins"]
397     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
398     ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+28-yoff-3)
399     ctx.show_text(txt)
400     ctx.set_source_rgb(0.8, 0.6, 0.6)
401     txt = "%d losses" % (total_games-total_stats['wins'])
402     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
403     ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+38-yoff-3)
404     ctx.show_text(txt)
405
406
407     # print kill/death ratio
408     
409     ctx.rectangle(KILLDEATH_POS[0]-KILLDEATH_WIDTH/2, KILLDEATH_POS[1]-7, KILLDEATH_WIDTH, 14)
410     ctx.set_source_rgba(0.8, 0.8, 0.8, 0.1)
411     ctx.fill()
412     
413     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
414     ctx.set_font_size(10)
415     ctx.set_source_rgb(0.8, 0.8, 0.8)
416     txt = "Kill Ratio"
417     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
418     ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]-yoff-3)
419     ctx.show_text(txt)
420     
421     txt = "???"
422     if total_stats['deaths'] > 0 and total_stats['kills'] is not None:
423         ratio = float(total_stats['kills'])/total_stats['deaths']
424         txt = "%.3f" % round(ratio, 3)
425     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
426     ctx.set_font_size(12)
427     if ratio >= 3:
428         ctx.set_source_rgb(0.0, 1.0, 0.0)
429     elif ratio >= 2:
430         ctx.set_source_rgb(0.2, 1.0, 0.2)
431     elif ratio >= 1:
432         ctx.set_source_rgb(0.5, 1.0, 0.5)
433     elif ratio >= 0.5:
434         ctx.set_source_rgb(1.0, 0.5, 0.5)
435     else:
436         ctx.set_source_rgb(1.0, 0.2, 0.2)
437     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
438     ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+16-yoff-4)
439     ctx.show_text(txt)
440
441     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
442     ctx.set_font_size(8)
443     ctx.set_source_rgb(0.6, 0.8, 0.6)
444     txt = "%d kills" % total_stats["kills"]
445     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
446     ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+28-yoff-3)
447     ctx.show_text(txt)
448     ctx.set_source_rgb(0.8, 0.6, 0.6)
449     txt = "%d deaths" % total_stats['deaths']
450     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
451     ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+38-yoff-3)
452     ctx.show_text(txt)
453
454
455     # print playing time
456     
457     ctx.rectangle( PLAYTIME_POS[0]-PLAYTIME_WIDTH/2, PLAYTIME_POS[1]-7, PLAYTIME_WIDTH, 14)
458     ctx.set_source_rgba(0.8, 0.8, 0.8, 0.6)
459     ctx.fill();
460     
461     ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
462     ctx.set_font_size(10)
463     ctx.set_source_rgb(0.1, 0.1, 0.1)
464     txt = "Playing time: %s" % str(total_stats['alivetime'])
465     xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
466     ctx.move_to(PLAYTIME_POS[0]-xoff-tw/2, PLAYTIME_POS[1]-yoff-4)
467     ctx.show_text(txt)
468
469
470     # save to PNG
471     surf.write_to_png(OUTPUT % data['player'].player_id)
472
473
474 # environment setup
475 env = bootstrap('../../../development.ini')
476 req = env['request']
477 req.matchdict = {'id':3}
478
479 print "Requesting player data from db ..."
480 start = datetime.now()
481 players = DBSession.query(Player).\
482         filter(Player.player_id == PlayerElo.player_id).\
483         filter(Player.nick != None).\
484         filter(Player.player_id > 2).\
485         filter(Player.active_ind == True).\
486         limit(NUM_PLAYERS).all()
487 stop = datetime.now()
488 print "Query took %.2f seconds" % (stop-start).total_seconds()
489
490 print "Creating badges for %d active players ..." % len(players)
491 start = datetime.now()
492 data_time, render_time = 0,0
493 for player in players:
494     req.matchdict['id'] = player.player_id
495     
496     sstart = datetime.now()
497     #data = player_info_data(req)
498     data = get_data(player)
499     sstop = datetime.now()
500     data_time += (sstop-sstart).total_seconds()
501     
502     print "\r  #%-5d" % player.player_id,
503     sys.stdout.flush()
504
505     sstart = datetime.now()
506     render_image(data)
507     sstop = datetime.now()
508     render_time += (sstop-sstart).total_seconds()
509 print
510
511 stop = datetime.now()
512 print "Creating the badges took %.2f seconds (%.2f s per player)" % ((stop-start).total_seconds(), (stop-start).total_seconds()/float(len(players)))
513 print " Total time for getting data: %.2f s" % data_time
514 print " Total time for renering images: %.2f s" % render_time
515