]> de.git.xonotic.org Git - xonotic/xonstat.git/blob - xonstat/batch/badges/render.py
Added rudimentary skin support to badges (also moved large parts of code outside...
[xonotic/xonstat.git] / xonstat / batch / badges / render.py
1 import re
2 import cairo as C
3 import sqlalchemy as sa
4 import sqlalchemy.sql.functions as func
5 from xonstat.models import *
6 from xonstat.util import qfont_decode, _all_colors
7
8 # similar to html_colors() from util.py
9 _contrast_threshold = 0.5
10
11 _dec_colors = [ (0.5,0.5,0.5),
12                 (1.0,0.0,0.0),
13                 (0.2,1.0,0.0),
14                 (1.0,1.0,0.0),
15                 (0.2,0.4,1.0),
16                 (0.2,1.0,1.0),
17                 (1.0,0.2,102),
18                 (1.0,1.0,1.0),
19                 (0.6,0.6,0.6),
20                 (0.5,0.5,0.5)
21             ]
22
23
24 class Skin:
25
26     # player data, will be filled by get_data()
27     data = {}
28
29     # skin parameters, can be overriden by init
30     params = {
31         'bg':               "dark_wall",    # None - plain; otherwise use given texture
32         'bgcolor':          None,           # transparent bg when bgcolor==None
33         'overlay':          None,           # add overlay graphic on top of bg
34         'font':             "Xolonium",
35         'width':            560,
36         'height':           70,
37         'nick_fontsize':    20,
38         'nick_pos':         (5,18),
39         'nick_maxwidth':    330,
40         'gametype_fontsize':12,
41         'gametype_pos':     (60,31),
42         'gametype_width':   110,
43         'gametype_height':  22,
44         'gametype_color':   (1.0, 1.0, 1.0),
45         'num_gametypes':    3,
46         'nostats_fontsize': 12,
47         'nostats_pos':      (60,59),
48         'nostats_color':    (0.8, 0.2, 0.2),
49         'nostats_angle':    -10,
50         'elo_pos':          (60,47),
51         'elo_fontsize':     10,
52         'elo_color':        (1.0, 1.0, 0.5),
53         'rank_fontsize':    8,
54         'rank_pos':         (60,57),
55         'rank_color':       (0.8, 0.8, 1.0),
56         'wintext_fontsize': 10,
57         'wintext_pos':      (508,3),
58         'wintext_width':    102,
59         'wintext_color':    (0.8, 0.8, 0.8),
60         'wintext_bg':       (0.8, 0.8, 0.8, 0.1),
61         'winp_fontsize':    12,
62         'winp_pos':         (508,19),
63         'winp_colortop':    (0.2, 1.0, 1.0),
64         'winp_colorbot':    (1.0, 1.0, 0.2),
65         'wins_fontsize':    8,
66         'wins_pos':         (508,33),
67         'wins_color':       (0.6, 0.8, 0.8),
68         'loss_fontsize':    8,
69         'loss_pos':         (508,43),
70         'loss_color':       (0.8, 0.8, 0.6),
71         'kdtext_fontsize':  10,
72         'kdtext_pos':       (390,3),
73         'kdtext_width':     102,
74         'kdtext_color':     (0.8, 0.8, 0.8),
75         'kdtext_bg':        (0.8, 0.8, 0.8, 0.1),
76         'kdr_fontsize':     12,
77         'kdr_pos':          (392,19),
78         'kdr_colortop':     (0.2, 1.0, 0.2),
79         'kdr_colorbot':     (1.0, 0.2, 0.2),
80         'kills_fontsize':   8,
81         'kills_pos':        (392,46),
82         'kills_color':      (0.6, 0.8, 0.6),
83         'deaths_fontsize':  8,
84         'deaths_pos':       (392,56),
85         'deaths_color':     (0.8, 0.6, 0.6),
86         'ptime_fontsize':   10,
87         'ptime_pos':        (451,60),
88         'ptime_width':      218,
89         'ptime_bg':         (0.8, 0.8, 0.8, 0.6),
90         'ptime_color':      (0.1, 0.1, 0.1),
91     }
92     
93     def __init__(self, **params):
94         for k,v in params.items():
95             if self.params.has_key(k):
96                 self.params[k] = v
97
98     def __getattr__(self, key):
99         if self.params.has_key(key):
100             return self.params[key]
101         return None
102
103     def render_image(self, output_filename):
104         """Render an image for the given player id."""
105
106         # setup variables
107
108         player = self.data['player']
109         total_stats = self.data['total_stats']
110         total_games = total_stats['games']
111         elos  = self.data["elos"]
112         ranks = self.data["ranks"]
113
114         font = "Xolonium"
115         if self.font == 1:
116             font = "DejaVu Sans"
117
118
119         # build image
120
121         surf = C.ImageSurface(C.FORMAT_ARGB32, self.width, self.height)
122         ctx = C.Context(surf)
123         ctx.set_antialias(C.ANTIALIAS_GRAY)
124         
125         # draw background
126         if self.bg == None:
127             if self.bgcolor == None:
128                 # transparent background
129                 ctx.save()
130                 ctx.set_operator(C.OPERATOR_SOURCE)
131                 ctx.set_source_rgba(1, 1, 1, 0)
132                 ctx.paint()
133                 ctx.restore()
134             else:
135                 # plain fillcolor
136                 ctx.rectangle(0, 0, self.width, self.height)
137                 ctx.set_source_rgb(self.bgcolor, self.bgcolor, self.bgcolor)
138                 ctx.fill()
139         else:
140             try:
141                 # background texture
142                 bg = C.ImageSurface.create_from_png("img/%s.png" % self.bg)
143                 
144                 # tile image
145                 if bg:
146                     bg_w, bg_h = bg.get_width(), bg.get_height()
147                     bg_xoff = 0
148                     while bg_xoff < self.width:
149                         bg_yoff = 0
150                         while bg_yoff < self.height:
151                             ctx.set_source_surface(bg, bg_xoff, bg_yoff)
152                             ctx.paint()
153                             bg_yoff += bg_h
154                         bg_xoff += bg_w
155             except:
156                 #print "Error: Can't load background texture: %s" % self.bg
157                 pass
158
159         # draw overlay graphic
160         if self.overlay:
161             overlay = None
162             try:
163                 overlay = C.ImageSurface.create_from_png("img/%s.png" % self.overlay)
164                 ctx.set_source_surface(overlay, 0, 0)
165                 ctx.mask_surface(overlay)
166                 ctx.paint()
167             except:
168                 #print "Error: Can't load overlay texture: %s" % self.overlay
169                 pass
170
171
172         ## draw player's nickname with fancy colors
173         
174         # deocde nick, strip all weird-looking characters
175         qstr = qfont_decode(player.nick).replace('^^', '^').replace(u'\x00', '')
176         chars = []
177         for c in qstr:
178             # replace weird characters that make problems - TODO
179             if ord(c) < 128:
180                 chars.append(c)
181         qstr = ''.join(chars)
182         stripped_nick = strip_colors(qstr.replace(' ', '_'))
183         
184         # fontsize is reduced if width gets too large
185         ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
186         shrinknick = 0
187         while shrinknick < 10:
188             ctx.set_font_size(self.nick_fontsize - shrinknick)
189             xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
190             if tw > self.nick_maxwidth:
191                 shrinknick += 2
192                 continue
193             break
194
195         # determine width of single whitespace for later use
196         xoff, yoff, tw, th = ctx.text_extents("_")[:4]
197         space_w = tw
198
199         # split nick into colored segments
200         xoffset = 0
201         _all_colors = re.compile(r'(\^\d|\^x[\dA-Fa-f]{3})')
202         parts = _all_colors.split(qstr)
203         while len(parts) > 0:
204             tag = None
205             txt = parts[0]
206             if _all_colors.match(txt):
207                 tag = txt[1:]  # strip leading '^'
208                 if len(parts) < 2:
209                     break
210                 txt = parts[1]
211                 del parts[1]
212             del parts[0]
213                 
214             if not txt or len(txt) == 0:
215                 # only colorcode and no real text, skip this
216                 continue
217                 
218             r,g,b = _dec_colors[7]
219             try:
220                 if tag.startswith('x'):
221                     r = int(tag[1] * 2, 16) / 255.0
222                     g = int(tag[2] * 2, 16) / 255.0
223                     b = int(tag[3] * 2, 16) / 255.0
224                     hue, light, satur = rgb_to_hls(r, g, b)
225                     if light < _contrast_threshold:
226                         light = _contrast_threshold
227                         r, g, b = hls_to_rgb(hue, light, satur)
228                 else:
229                     r,g,b = _dec_colors[int(tag[0])]
230             except:
231                 r,g,b = _dec_colors[7]
232             
233             ctx.set_source_rgb(r, g, b)
234             ctx.move_to(self.nick_pos[0] + xoffset, self.nick_pos[1])
235             ctx.show_text(txt)
236
237             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
238             tw += (len(txt)-len(txt.strip())) * space_w  # account for lost whitespaces
239             xoffset += tw + 2
240
241         ## print elos and ranks
242         
243         # show up to three gametypes the player has participated in
244         xoffset = 0
245         for gt in total_stats['gametypes'][:self.num_gametypes]:
246             ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
247             ctx.set_font_size(self.gametype_fontsize)
248             ctx.set_source_rgb(self.gametype_color[0],self.gametype_color[1],self.gametype_color[2])
249             txt = "[ %s ]" % gt.upper()
250             xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
251             ctx.move_to(self.gametype_pos[0]+xoffset-xoff-tw/2, self.gametype_pos[1]-yoff)
252             ctx.show_text(txt)
253             
254
255             # draw lines - TODO put this in overlay graphic
256             if not self.overlay:
257                 old_aa = ctx.get_antialias()
258                 ctx.set_antialias(C.ANTIALIAS_NONE)
259                 ctx.set_source_rgb(0.8, 0.8, 0.8)
260                 ctx.set_line_width(1)
261                 ctx.move_to(self.gametype_pos[0]+xoffset-self.gametype_width/2+5, self.gametype_pos[1]+14)
262                 ctx.line_to(self.gametype_pos[0]+xoffset+self.gametype_width/2-5, self.gametype_pos[1]+14)
263                 ctx.stroke()
264                 ctx.move_to(self.gametype_pos[0]+xoffset-self.gametype_width/2+5, self.gametype_pos[1]+self.gametype_height+14)
265                 ctx.line_to(self.gametype_pos[0]+xoffset+self.gametype_width/2-5, self.gametype_pos[1]+self.gametype_height+14)
266                 ctx.stroke()
267                 ctx.set_antialias(old_aa)
268
269             if not elos.has_key(gt) or not ranks.has_key(gt):
270                 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
271                 ctx.set_font_size(self.nostats_fontsize)
272                 ctx.set_source_rgb(self.nostats_color[0],self.nostats_color[1],self.nostats_color[2])
273                 txt = "no stats yet!"
274                 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
275                 ctx.move_to(self.nostats_pos[0]+xoffset-xoff-tw/2, self.nostats_pos[1]-yoff)
276                 ctx.save()
277                 ctx.rotate(math.radians(self.nostats_angle))
278                 ctx.show_text(txt)
279                 ctx.restore()
280             else:
281                 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
282                 ctx.set_font_size(self.elo_fontsize)
283                 ctx.set_source_rgb(self.elo_color[0], self.elo_color[1], self.elo_color[2])
284                 txt = "Elo: %.0f" % round(elos[gt], 0)
285                 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
286                 ctx.move_to(self.elo_pos[0]+xoffset-xoff-tw/2, self.elo_pos[1]-yoff)
287                 ctx.show_text(txt)
288                 
289                 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
290                 ctx.set_font_size(self.rank_fontsize)
291                 ctx.set_source_rgb(self.rank_color[0], self.rank_color[1], self.rank_color[2])
292                 txt = "Rank %d of %d" % ranks[gt]
293                 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
294                 ctx.move_to(self.rank_pos[0]+xoffset-xoff-tw/2, self.rank_pos[1]-yoff)
295                 ctx.show_text(txt)
296             
297             xoffset += self.gametype_width
298
299
300         # print win percentage
301
302         if not self.overlay:
303             ctx.rectangle(self.wintext_pos[0]-self.wintext_width/2, self.wintext_pos[1]-self.wintext_fontsize/2+1,
304                     self.wintext_width, self.wintext_fontsize+4)
305             ctx.set_source_rgba(self.wintext_bg[0], self.wintext_bg[1], self.wintext_bg[2], self.wintext_bg[3])
306             ctx.fill()
307
308         ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
309         ctx.set_font_size(self.wintext_fontsize)
310         ctx.set_source_rgb(self.wintext_color[0], self.wintext_color[1], self.wintext_color[2])
311         txt = "Win Percentage"
312         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
313         ctx.move_to(self.wintext_pos[0]-xoff-tw/2, self.wintext_pos[1]-yoff)
314         ctx.show_text(txt)
315         
316         wins, losses = total_stats["wins"], total_games-total_stats["wins"]
317         txt = "???"
318         try:
319             ratio = float(wins)/total_games
320             txt = "%.2f%%" % round(ratio * 100, 2)
321         except:
322             ratio = 0
323         ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
324         ctx.set_font_size(self.winp_fontsize)
325         r = ratio*self.winp_colortop[0] + (1-ratio)*self.winp_colorbot[0]
326         g = ratio*self.winp_colortop[1] + (1-ratio)*self.winp_colorbot[1]
327         b = ratio*self.winp_colortop[2] + (1-ratio)*self.winp_colorbot[2]
328         ctx.set_source_rgb(r, g, b)
329         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
330         ctx.move_to(self.winp_pos[0]-xoff-tw/2, self.winp_pos[1]-yoff)
331         ctx.show_text(txt)
332
333         ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
334         ctx.set_font_size(self.wins_fontsize)
335         ctx.set_source_rgb(self.wins_color[0], self.wins_color[1], self.wins_color[2])
336         txt = "%d win" % wins
337         if wins != 1:
338             txt += "s"
339         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
340         ctx.move_to(self.wins_pos[0]-xoff-tw/2, self.wins_pos[1]-yoff)
341         ctx.show_text(txt)
342
343         ctx.set_font_size(self.loss_fontsize)
344         ctx.set_source_rgb(self.loss_color[0], self.loss_color[1], self.loss_color[2])
345         txt = "%d loss" % losses
346         if losses != 1:
347             txt += "es"
348         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
349         ctx.move_to(self.loss_pos[0]-xoff-tw/2, self.loss_pos[1]-yoff)
350         ctx.show_text(txt)
351
352
353         # print kill/death ratio
354
355         if not self.overlay:
356             ctx.rectangle(self.kdtext_pos[0]-self.kdtext_width/2, self.kdtext_pos[1]-self.kdtext_fontsize/2+1,
357                     self.kdtext_width, self.kdtext_fontsize+4)
358             ctx.set_source_rgba(self.kdtext_bg[0], self.kdtext_bg[1], self.kdtext_bg[2], self.kdtext_bg[3])
359             ctx.fill()
360
361         ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
362         ctx.set_font_size(self.kdtext_fontsize)
363         ctx.set_source_rgb(self.kdtext_color[0], self.kdtext_color[1], self.kdtext_color[2])
364         txt = "Kill Ratio"
365         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
366         ctx.move_to(self.kdtext_pos[0]-xoff-tw/2, self.kdtext_pos[1]-yoff)
367         ctx.show_text(txt)
368         
369         kills, deaths = total_stats['kills'] , total_stats['deaths'] 
370         txt = "???"
371         try:
372             ratio = float(kills)/deaths
373             txt = "%.3f" % round(ratio, 3)
374         except:
375             ratio = 0
376
377         ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
378         ctx.set_font_size(self.kdr_fontsize)
379         nr = ratio / 2.0
380         if nr > 1:
381             nr = 1
382         r = nr*self.kdr_colortop[0] + (1-nr)*self.kdr_colorbot[0]
383         g = nr*self.kdr_colortop[1] + (1-nr)*self.kdr_colorbot[1]
384         b = nr*self.kdr_colortop[2] + (1-nr)*self.kdr_colorbot[2]
385         ctx.set_source_rgb(r, g, b)
386         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
387         ctx.move_to(self.kdr_pos[0]-xoff-tw/2, self.kdr_pos[1]-yoff)
388         ctx.show_text(txt)
389
390         ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
391         ctx.set_font_size(self.kills_fontsize)
392         ctx.set_source_rgb(self.kills_color[0], self.kills_color[1], self.kills_color[2])
393         txt = "%d kill" % kills
394         if kills != 1:
395             txt += "s"
396         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
397         ctx.move_to(self.kills_pos[0]-xoff-tw/2, self.kills_pos[1]+yoff)
398         ctx.show_text(txt)
399
400         ctx.set_font_size(self.deaths_fontsize)
401         ctx.set_source_rgb(self.deaths_color[0], self.deaths_color[1], self.deaths_color[2])
402         txt = "%d death" % deaths
403         if deaths != 1:
404             txt += "s"
405         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
406         ctx.move_to(self.deaths_pos[0]-xoff-tw/2, self.deaths_pos[1]+yoff)
407         ctx.show_text(txt)
408
409
410         # print playing time
411
412         if not self.overlay:
413             ctx.rectangle( self.ptime_pos[0]-self.ptime_width/2, self.ptime_pos[1]-self.ptime_fontsize/2+1,
414                     self.ptime_width, self.ptime_fontsize+4)
415             ctx.set_source_rgba(self.ptime_bg[0], self.ptime_bg[1], self.ptime_bg[2], self.ptime_bg[2])
416             ctx.fill()
417
418         ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
419         ctx.set_font_size(self.ptime_fontsize)
420         ctx.set_source_rgb(self.ptime_color[0], self.ptime_color[1], self.ptime_color[2])
421         txt = "Playing time: %s" % str(total_stats['alivetime'])
422         xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
423         ctx.move_to(self.ptime_pos[0]-xoff-tw/2, self.ptime_pos[1]-yoff)
424         ctx.show_text(txt)
425
426
427         # save to PNG
428         surf.write_to_png(output_filename)
429
430
431     def get_data(self, player):
432         """Return player data as dict.
433
434         This function is similar to the function in player.py but more optimized
435         for this purpose.
436         """
437
438         # total games
439         # wins/losses
440         # kills/deaths
441         # duel/dm/tdm/ctf elo + rank
442
443         player_id = player.player_id
444
445         games_played = DBSession.query(
446                 Game.game_type_cd, func.count(), func.sum(PlayerGameStat.alivetime)).\
447                 filter(Game.game_id == PlayerGameStat.game_id).\
448                 filter(PlayerGameStat.player_id == player_id).\
449                 group_by(Game.game_type_cd).\
450                 order_by(func.count().desc()).\
451                 limit(3).all()  # limit to 3 gametypes!
452
453         total_stats = {}
454         total_stats['games'] = 0
455         total_stats['games_breakdown'] = {}  # this is a dictionary inside a dictionary .. dictception?
456         total_stats['games_alivetime'] = {}
457         total_stats['gametypes'] = []
458         for (game_type_cd, games, alivetime) in games_played:
459             total_stats['games'] += games
460             total_stats['gametypes'].append(game_type_cd)
461             total_stats['games_breakdown'][game_type_cd] = games
462             total_stats['games_alivetime'][game_type_cd] = alivetime
463
464         (total_stats['kills'], total_stats['deaths'], total_stats['alivetime'],) = DBSession.query(
465                 func.sum(PlayerGameStat.kills),
466                 func.sum(PlayerGameStat.deaths),
467                 func.sum(PlayerGameStat.alivetime)).\
468                 filter(PlayerGameStat.player_id == player_id).\
469                 one()
470
471     #    (total_stats['wins'],) = DBSession.query(
472     #            func.count("*")).\
473     #            filter(Game.game_id == PlayerGameStat.game_id).\
474     #            filter(PlayerGameStat.player_id == player_id).\
475     #            filter(Game.winner == PlayerGameStat.team or PlayerGameStat.rank == 1).\
476     #            one()
477
478         (total_stats['wins'],) = DBSession.\
479                 query("total_wins").\
480                 from_statement(
481                     "select count(*) total_wins "
482                     "from games g, player_game_stats pgs "
483                     "where g.game_id = pgs.game_id "
484                     "and player_id=:player_id "
485                     "and (g.winner = pgs.team or pgs.rank = 1)"
486                 ).params(player_id=player_id).one()
487
488         ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
489                 from_statement(
490                     "select pr.game_type_cd, pr.rank, overall.max_rank "
491                     "from player_ranks pr,  "
492                        "(select game_type_cd, max(rank) max_rank "
493                         "from player_ranks  "
494                         "group by game_type_cd) overall "
495                     "where pr.game_type_cd = overall.game_type_cd  "
496                     "and player_id = :player_id "
497                     "order by rank").\
498                 params(player_id=player_id).all()
499
500         ranks_dict = {}
501         for gtc,rank,max_rank in ranks:
502             ranks_dict[gtc] = (rank, max_rank)
503
504         elos = DBSession.query(PlayerElo).\
505                 filter_by(player_id=player_id).\
506                 order_by(PlayerElo.elo.desc()).\
507                 all()
508
509         elos_dict = {}
510         for elo in elos:
511             if elo.games > 32:
512                 elos_dict[elo.game_type_cd] = elo.elo
513
514         self.data = {
515                 'player':player,
516                 'total_stats':total_stats,
517                 'ranks':ranks_dict,
518                 'elos':elos_dict,
519             }
520