4 from colorsys import rgb_to_hls, hls_to_rgb
5 import sqlalchemy as sa
6 import sqlalchemy.sql.functions as func
7 from xonstat.models import *
8 from xonstat.util import qfont_decode, _all_colors
10 # similar to html_colors() from util.py
11 _contrast_threshold = 0.5
13 _dec_colors = [ (0.5,0.5,0.5),
26 def writepng(filename, buf, width, height):
27 width_byte_4 = width * 4
28 # fix color ordering (BGR -> RGB)
29 for byte in xrange(width*height):
31 buf[pos:pos+4] = buf[pos+2] + buf[pos+1] + buf[pos+0] + buf[pos+3]
33 #raw_data = b"".join(b'\x00' + buf[span:span + width_byte_4] for span in xrange((height - 1) * width * 4, -1, - width_byte_4))
34 raw_data = b"".join(b'\x00' + buf[span:span + width_byte_4] for span in range(0, (height-1) * width * 4 + 1, width_byte_4))
35 def png_pack(png_tag, data):
36 chunk_head = png_tag + data
37 return struct.pack("!I", len(data)) + chunk_head + struct.pack("!I", 0xFFFFFFFF & zlib.crc32(chunk_head))
40 png_pack(b'IHDR', struct.pack("!2I5B", width, height, 8, 6, 0, 0, 0)),
41 png_pack(b'IDAT', zlib.compress(raw_data, 9)),
42 png_pack(b'IEND', b'')])
43 f = open(filename, "wb")
52 # player data, will be filled by get_data()
55 # skin parameters, can be overriden by init
58 def __init__(self, **params):
61 'bg': "dark_wall", # None - plain; otherwise use given texture
62 'bgcolor': None, # transparent bg when bgcolor==None
63 'overlay': None, # add overlay graphic on top of bg
70 'gametype_fontsize':12,
71 'gametype_pos': (60,31),
72 'gametype_width': 110,
73 'gametype_height': 22,
74 'gametype_color': (1.0, 1.0, 1.0),
75 'gametype_text': "[ %s ]",
77 'nostats_fontsize': 12,
78 'nostats_pos': (60,59),
79 'nostats_color': (0.8, 0.2, 0.2),
81 'nostats_text': "no stats yet!",
84 'elo_color': (1.0, 1.0, 0.5),
85 'elo_text': "Elo %.0f",
88 'rank_color': (0.8, 0.8, 1.0),
89 'rank_text': "Rank %d of %d",
90 'wintext_fontsize': 10,
91 'wintext_pos': (508,3),
93 'wintext_color': (0.8, 0.8, 0.8),
94 'wintext_bg': (0.8, 0.8, 0.8, 0.1),
95 'wintext_text': "Win Percentage",
98 'winp_colortop': (0.2, 1.0, 1.0),
99 'winp_colorbot': (1.0, 1.0, 0.2),
101 'wins_pos': (508,33),
102 'wins_color': (0.6, 0.8, 0.8),
104 'loss_pos': (508,43),
105 'loss_color': (0.8, 0.8, 0.6),
106 'kdtext_fontsize': 10,
107 'kdtext_pos': (390,3),
109 'kdtext_color': (0.8, 0.8, 0.8),
110 'kdtext_bg': (0.8, 0.8, 0.8, 0.1),
111 'kdtext_text': "Kill Ratio",
114 'kdr_colortop': (0.2, 1.0, 0.2),
115 'kdr_colorbot': (1.0, 0.2, 0.2),
117 'kills_pos': (392,46),
118 'kills_color': (0.6, 0.8, 0.6),
119 'deaths_fontsize': 8,
120 'deaths_pos': (392,56),
121 'deaths_color': (0.8, 0.6, 0.6),
122 'ptime_fontsize': 10,
123 'ptime_pos': (451,60),
125 'ptime_bg': (0.8, 0.8, 0.8, 0.5),
126 'ptime_color': (0.1, 0.1, 0.1),
127 'ptime_text': "Playing Time: %s",
130 for k,v in params.items():
131 if self.params.has_key(k):
134 def __getattr__(self, key):
135 if self.params.has_key(key):
136 return self.params[key]
139 def render_image(self, output_filename):
140 """Render an image for the given player id."""
144 player = self.data['player']
145 total_stats = self.data['total_stats']
146 total_games = total_stats['games']
147 elos = self.data["elos"]
148 ranks = self.data["ranks"]
157 surf = C.ImageSurface(C.FORMAT_ARGB32, self.width, self.height)
158 ctx = C.Context(surf)
159 ctx.set_antialias(C.ANTIALIAS_GRAY)
163 if self.bgcolor != None:
164 # plain fillcolor, full transparency possible with (1,1,1,0)
166 ctx.set_operator(C.OPERATOR_SOURCE)
167 ctx.rectangle(0, 0, self.width, self.height)
168 ctx.set_source_rgba(self.bgcolor[0], self.bgcolor[1], self.bgcolor[2], self.bgcolor[3])
174 bg = C.ImageSurface.create_from_png("img/%s.png" % self.bg)
178 bg_w, bg_h = bg.get_width(), bg.get_height()
180 while bg_xoff < self.width:
182 while bg_yoff < self.height:
183 ctx.set_source_surface(bg, bg_xoff, bg_yoff)
184 #ctx.mask_surface(bg)
189 #print "Error: Can't load background texture: %s" % self.bg
192 # draw overlay graphic
193 if self.overlay != None:
195 overlay = C.ImageSurface.create_from_png("img/%s.png" % self.overlay)
196 ctx.set_source_surface(overlay, 0, 0)
197 #ctx.mask_surface(overlay)
200 #print "Error: Can't load overlay texture: %s" % self.overlay
204 ## draw player's nickname with fancy colors
206 # deocde nick, strip all weird-looking characters
207 qstr = qfont_decode(player.nick).replace('^^', '^').replace(u'\x00', '')
210 # replace weird characters that make problems - TODO
213 qstr = ''.join(chars)
214 stripped_nick = strip_colors(qstr.replace(' ', '_'))
216 # fontsize is reduced if width gets too large
217 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
219 while shrinknick < 10:
220 ctx.set_font_size(self.nick_fontsize - shrinknick)
221 xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
222 if tw > self.nick_maxwidth:
227 # determine width of single whitespace for later use
228 xoff, yoff, tw, th = ctx.text_extents("_")[:4]
231 # split nick into colored segments
233 _all_colors = re.compile(r'(\^\d|\^x[\dA-Fa-f]{3})')
234 parts = _all_colors.split(qstr)
235 while len(parts) > 0:
238 if _all_colors.match(txt):
239 tag = txt[1:] # strip leading '^'
246 if not txt or len(txt) == 0:
247 # only colorcode and no real text, skip this
251 if tag.startswith('x'):
252 r = int(tag[1] * 2, 16) / 255.0
253 g = int(tag[2] * 2, 16) / 255.0
254 b = int(tag[3] * 2, 16) / 255.0
255 hue, light, satur = rgb_to_hls(r, g, b)
256 if light < _contrast_threshold:
257 light = _contrast_threshold
258 r, g, b = hls_to_rgb(hue, light, satur)
260 r,g,b = _dec_colors[int(tag[0])]
262 r,g,b = _dec_colors[7]
264 ctx.set_source_rgb(r, g, b)
265 ctx.move_to(self.nick_pos[0] + xoffset, self.nick_pos[1])
268 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
269 tw += (len(txt)-len(txt.strip())) * space_w # account for lost whitespaces
272 ## print elos and ranks
274 # show up to three gametypes the player has participated in
276 for gt in total_stats['gametypes'][:self.num_gametypes]:
277 if self.gametype_pos:
278 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
279 ctx.set_font_size(self.gametype_fontsize)
280 ctx.set_source_rgb(self.gametype_color[0],self.gametype_color[1],self.gametype_color[2])
281 txt = self.gametype_text % gt.upper()
282 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
283 ctx.move_to(self.gametype_pos[0]+xoffset-xoff-tw/2, self.gametype_pos[1]-yoff)
286 # draw lines - TODO put this in overlay graphic
287 if self.overlay == None:
288 old_aa = ctx.get_antialias()
289 ctx.set_antialias(C.ANTIALIAS_NONE)
290 ctx.set_source_rgb(0.8, 0.8, 0.8)
291 ctx.set_line_width(1)
292 ctx.move_to(self.gametype_pos[0]+xoffset-self.gametype_width/2+5, self.gametype_pos[1]+14)
293 ctx.line_to(self.gametype_pos[0]+xoffset+self.gametype_width/2-5, self.gametype_pos[1]+14)
295 ctx.move_to(self.gametype_pos[0]+xoffset-self.gametype_width/2+5, self.gametype_pos[1]+self.gametype_height+14)
296 ctx.line_to(self.gametype_pos[0]+xoffset+self.gametype_width/2-5, self.gametype_pos[1]+self.gametype_height+14)
298 ctx.set_antialias(old_aa)
300 if not elos.has_key(gt) or not ranks.has_key(gt):
302 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
303 ctx.set_font_size(self.nostats_fontsize)
304 ctx.set_source_rgb(self.nostats_color[0],self.nostats_color[1],self.nostats_color[2])
305 txt = self.nostats_text
306 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
307 ctx.move_to(self.nostats_pos[0]+xoffset-xoff-tw/2, self.nostats_pos[1]-yoff)
309 ctx.rotate(math.radians(self.nostats_angle))
314 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
315 ctx.set_font_size(self.elo_fontsize)
316 ctx.set_source_rgb(self.elo_color[0], self.elo_color[1], self.elo_color[2])
317 txt = self.elo_text % round(elos[gt], 0)
318 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
319 ctx.move_to(self.elo_pos[0]+xoffset-xoff-tw/2, self.elo_pos[1]-yoff)
322 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
323 ctx.set_font_size(self.rank_fontsize)
324 ctx.set_source_rgb(self.rank_color[0], self.rank_color[1], self.rank_color[2])
325 txt = self.rank_text % ranks[gt]
326 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
327 ctx.move_to(self.rank_pos[0]+xoffset-xoff-tw/2, self.rank_pos[1]-yoff)
330 xoffset += self.gametype_width
333 # print win percentage
336 if self.overlay == None:
337 ctx.rectangle(self.wintext_pos[0]-self.wintext_width/2, self.wintext_pos[1]-self.wintext_fontsize/2+1,
338 self.wintext_width, self.wintext_fontsize+4)
339 ctx.set_source_rgba(self.wintext_bg[0], self.wintext_bg[1], self.wintext_bg[2], self.wintext_bg[3])
342 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
343 ctx.set_font_size(self.wintext_fontsize)
344 ctx.set_source_rgb(self.wintext_color[0], self.wintext_color[1], self.wintext_color[2])
345 txt = self.wintext_text
346 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
347 ctx.move_to(self.wintext_pos[0]-xoff-tw/2, self.wintext_pos[1]-yoff)
350 wins, losses = total_stats["wins"], total_games-total_stats["wins"]
353 ratio = float(wins)/total_games
354 txt = "%.2f%%" % round(ratio * 100, 2)
359 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
360 ctx.set_font_size(self.winp_fontsize)
361 r = ratio*self.winp_colortop[0] + (1-ratio)*self.winp_colorbot[0]
362 g = ratio*self.winp_colortop[1] + (1-ratio)*self.winp_colorbot[1]
363 b = ratio*self.winp_colortop[2] + (1-ratio)*self.winp_colorbot[2]
364 ctx.set_source_rgb(r, g, b)
365 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
366 ctx.move_to(self.winp_pos[0]-xoff-tw/2, self.winp_pos[1]-yoff)
370 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
371 ctx.set_font_size(self.wins_fontsize)
372 ctx.set_source_rgb(self.wins_color[0], self.wins_color[1], self.wins_color[2])
373 txt = "%d win" % wins
376 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
377 ctx.move_to(self.wins_pos[0]-xoff-tw/2, self.wins_pos[1]-yoff)
381 ctx.set_font_size(self.loss_fontsize)
382 ctx.set_source_rgb(self.loss_color[0], self.loss_color[1], self.loss_color[2])
383 txt = "%d loss" % losses
386 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
387 ctx.move_to(self.loss_pos[0]-xoff-tw/2, self.loss_pos[1]-yoff)
391 # print kill/death ratio
394 if self.overlay == None:
395 ctx.rectangle(self.kdtext_pos[0]-self.kdtext_width/2, self.kdtext_pos[1]-self.kdtext_fontsize/2+1,
396 self.kdtext_width, self.kdtext_fontsize+4)
397 ctx.set_source_rgba(self.kdtext_bg[0], self.kdtext_bg[1], self.kdtext_bg[2], self.kdtext_bg[3])
400 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
401 ctx.set_font_size(self.kdtext_fontsize)
402 ctx.set_source_rgb(self.kdtext_color[0], self.kdtext_color[1], self.kdtext_color[2])
403 txt = self.kdtext_text
404 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
405 ctx.move_to(self.kdtext_pos[0]-xoff-tw/2, self.kdtext_pos[1]-yoff)
408 kills, deaths = total_stats['kills'] , total_stats['deaths']
411 ratio = float(kills)/deaths
412 txt = "%.3f" % round(ratio, 3)
417 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
418 ctx.set_font_size(self.kdr_fontsize)
422 r = nr*self.kdr_colortop[0] + (1-nr)*self.kdr_colorbot[0]
423 g = nr*self.kdr_colortop[1] + (1-nr)*self.kdr_colorbot[1]
424 b = nr*self.kdr_colortop[2] + (1-nr)*self.kdr_colorbot[2]
425 ctx.set_source_rgb(r, g, b)
426 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
427 ctx.move_to(self.kdr_pos[0]-xoff-tw/2, self.kdr_pos[1]-yoff)
431 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
432 ctx.set_font_size(self.kills_fontsize)
433 ctx.set_source_rgb(self.kills_color[0], self.kills_color[1], self.kills_color[2])
434 txt = "%d kill" % kills
437 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
438 ctx.move_to(self.kills_pos[0]-xoff-tw/2, self.kills_pos[1]+yoff)
442 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
443 ctx.set_font_size(self.deaths_fontsize)
444 ctx.set_source_rgb(self.deaths_color[0], self.deaths_color[1], self.deaths_color[2])
445 if deaths is not None:
446 txt = "%d death" % deaths
451 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
452 ctx.move_to(self.deaths_pos[0]-xoff-tw/2, self.deaths_pos[1]+yoff)
459 if self.overlay == None:
460 ctx.rectangle( self.ptime_pos[0]-self.ptime_width/2, self.ptime_pos[1]-self.ptime_fontsize/2+1,
461 self.ptime_width, self.ptime_fontsize+4)
462 ctx.set_source_rgba(self.ptime_bg[0], self.ptime_bg[1], self.ptime_bg[2], self.ptime_bg[2])
465 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
466 ctx.set_font_size(self.ptime_fontsize)
467 ctx.set_source_rgb(self.ptime_color[0], self.ptime_color[1], self.ptime_color[2])
468 txt = self.ptime_text % str(total_stats['alivetime'])
469 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
470 ctx.move_to(self.ptime_pos[0]-xoff-tw/2, self.ptime_pos[1]-yoff)
475 #surf.write_to_png(output_filename)
477 imgdata = surf.get_data()
478 writepng(output_filename, imgdata, self.width, self.height)
481 def get_data(self, player_id):
482 """Return player data as dict.
484 This function is similar to the function in player.py but more optimized
491 # duel/dm/tdm/ctf elo + rank
492 player = DBSession.query(Player).filter(Player.player_id == player_id).one()
494 games_played = DBSession.query(
495 Game.game_type_cd, func.count(), func.sum(PlayerGameStat.alivetime)).\
496 filter(Game.game_id == PlayerGameStat.game_id).\
497 filter(PlayerGameStat.player_id == player_id).\
498 group_by(Game.game_type_cd).\
499 order_by(func.count().desc()).\
500 limit(3).all() # limit to 3 gametypes!
503 total_stats['games'] = 0
504 total_stats['games_breakdown'] = {} # this is a dictionary inside a dictionary .. dictception?
505 total_stats['games_alivetime'] = {}
506 total_stats['gametypes'] = []
507 for (game_type_cd, games, alivetime) in games_played:
508 total_stats['games'] += games
509 total_stats['gametypes'].append(game_type_cd)
510 total_stats['games_breakdown'][game_type_cd] = games
511 total_stats['games_alivetime'][game_type_cd] = alivetime
513 (total_stats['kills'], total_stats['deaths'], total_stats['alivetime'],) = DBSession.query(
514 func.sum(PlayerGameStat.kills),
515 func.sum(PlayerGameStat.deaths),
516 func.sum(PlayerGameStat.alivetime)).\
517 filter(PlayerGameStat.player_id == player_id).\
520 # (total_stats['wins'],) = DBSession.query(
522 # filter(Game.game_id == PlayerGameStat.game_id).\
523 # filter(PlayerGameStat.player_id == player_id).\
524 # filter(Game.winner == PlayerGameStat.team or PlayerGameStat.rank == 1).\
527 (total_stats['wins'],) = DBSession.\
528 query("total_wins").\
530 "select count(*) total_wins "
531 "from games g, player_game_stats pgs "
532 "where g.game_id = pgs.game_id "
533 "and player_id=:player_id "
534 "and (g.winner = pgs.team or pgs.rank = 1)"
535 ).params(player_id=player_id).one()
537 ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
539 "select pr.game_type_cd, pr.rank, overall.max_rank "
540 "from player_ranks pr, "
541 "(select game_type_cd, max(rank) max_rank "
543 "group by game_type_cd) overall "
544 "where pr.game_type_cd = overall.game_type_cd "
545 "and player_id = :player_id "
547 params(player_id=player_id).all()
550 for gtc,rank,max_rank in ranks:
551 ranks_dict[gtc] = (rank, max_rank)
553 elos = DBSession.query(PlayerElo).\
554 filter_by(player_id=player_id).\
555 order_by(PlayerElo.elo.desc()).\
561 elos_dict[elo.game_type_cd] = elo.elo
565 'total_stats':total_stats,