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
57 'bg': "dark_wall", # None - plain; otherwise use given texture
58 'bgcolor': None, # transparent bg when bgcolor==None
59 'overlay': None, # add overlay graphic on top of bg
66 'gametype_fontsize':12,
67 'gametype_pos': (60,31),
68 'gametype_width': 110,
69 'gametype_height': 22,
70 'gametype_color': (1.0, 1.0, 1.0),
72 'nostats_fontsize': 12,
73 'nostats_pos': (60,59),
74 'nostats_color': (0.8, 0.2, 0.2),
78 'elo_color': (1.0, 1.0, 0.5),
81 'rank_color': (0.8, 0.8, 1.0),
82 'wintext_fontsize': 10,
83 'wintext_pos': (508,3),
85 'wintext_color': (0.8, 0.8, 0.8),
86 'wintext_bg': (0.8, 0.8, 0.8, 0.1),
89 'winp_colortop': (0.2, 1.0, 1.0),
90 'winp_colorbot': (1.0, 1.0, 0.2),
93 'wins_color': (0.6, 0.8, 0.8),
96 'loss_color': (0.8, 0.8, 0.6),
97 'kdtext_fontsize': 10,
98 'kdtext_pos': (390,3),
100 'kdtext_color': (0.8, 0.8, 0.8),
101 'kdtext_bg': (0.8, 0.8, 0.8, 0.1),
104 'kdr_colortop': (0.2, 1.0, 0.2),
105 'kdr_colorbot': (1.0, 0.2, 0.2),
107 'kills_pos': (392,46),
108 'kills_color': (0.6, 0.8, 0.6),
109 'deaths_fontsize': 8,
110 'deaths_pos': (392,56),
111 'deaths_color': (0.8, 0.6, 0.6),
112 'ptime_fontsize': 10,
113 'ptime_pos': (451,60),
115 'ptime_bg': (0.8, 0.8, 0.8, 0.6),
116 'ptime_color': (0.1, 0.1, 0.1),
119 def __init__(self, **params):
120 for k,v in params.items():
121 if self.params.has_key(k):
124 def __getattr__(self, key):
125 if self.params.has_key(key):
126 return self.params[key]
129 def render_image(self, output_filename):
130 """Render an image for the given player id."""
134 player = self.data['player']
135 total_stats = self.data['total_stats']
136 total_games = total_stats['games']
137 elos = self.data["elos"]
138 ranks = self.data["ranks"]
147 surf = C.ImageSurface(C.FORMAT_ARGB32, self.width, self.height)
148 ctx = C.Context(surf)
149 ctx.set_antialias(C.ANTIALIAS_GRAY)
153 if self.bgcolor == None:
154 # transparent background
156 ctx.set_operator(C.OPERATOR_SOURCE)
157 ctx.set_source_rgba(1, 1, 1, 0)
162 ctx.rectangle(0, 0, self.width, self.height)
163 ctx.set_source_rgb(self.bgcolor, self.bgcolor, self.bgcolor)
168 bg = C.ImageSurface.create_from_png("img/%s.png" % self.bg)
172 bg_w, bg_h = bg.get_width(), bg.get_height()
174 while bg_xoff < self.width:
176 while bg_yoff < self.height:
177 ctx.set_source_surface(bg, bg_xoff, bg_yoff)
182 #print "Error: Can't load background texture: %s" % self.bg
185 # draw overlay graphic
189 overlay = C.ImageSurface.create_from_png("img/%s.png" % self.overlay)
190 ctx.set_source_surface(overlay, 0, 0)
191 ctx.mask_surface(overlay)
194 #print "Error: Can't load overlay texture: %s" % self.overlay
198 ## draw player's nickname with fancy colors
200 # deocde nick, strip all weird-looking characters
201 qstr = qfont_decode(player.nick).replace('^^', '^').replace(u'\x00', '')
204 # replace weird characters that make problems - TODO
207 qstr = ''.join(chars)
208 stripped_nick = strip_colors(qstr.replace(' ', '_'))
210 # fontsize is reduced if width gets too large
211 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
213 while shrinknick < 10:
214 ctx.set_font_size(self.nick_fontsize - shrinknick)
215 xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
216 if tw > self.nick_maxwidth:
221 # determine width of single whitespace for later use
222 xoff, yoff, tw, th = ctx.text_extents("_")[:4]
225 # split nick into colored segments
227 _all_colors = re.compile(r'(\^\d|\^x[\dA-Fa-f]{3})')
228 parts = _all_colors.split(qstr)
229 while len(parts) > 0:
232 if _all_colors.match(txt):
233 tag = txt[1:] # strip leading '^'
240 if not txt or len(txt) == 0:
241 # only colorcode and no real text, skip this
245 if tag.startswith('x'):
246 r = int(tag[1] * 2, 16) / 255.0
247 g = int(tag[2] * 2, 16) / 255.0
248 b = int(tag[3] * 2, 16) / 255.0
249 hue, light, satur = rgb_to_hls(r, g, b)
250 if light < _contrast_threshold:
251 light = _contrast_threshold
252 r, g, b = hls_to_rgb(hue, light, satur)
254 r,g,b = _dec_colors[int(tag[0])]
256 r,g,b = _dec_colors[7]
258 ctx.set_source_rgb(r, g, b)
259 ctx.move_to(self.nick_pos[0] + xoffset, self.nick_pos[1])
262 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
263 tw += (len(txt)-len(txt.strip())) * space_w # account for lost whitespaces
266 ## print elos and ranks
268 # show up to three gametypes the player has participated in
270 for gt in total_stats['gametypes'][:self.num_gametypes]:
271 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
272 ctx.set_font_size(self.gametype_fontsize)
273 ctx.set_source_rgb(self.gametype_color[0],self.gametype_color[1],self.gametype_color[2])
274 txt = "[ %s ]" % gt.upper()
275 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
276 ctx.move_to(self.gametype_pos[0]+xoffset-xoff-tw/2, self.gametype_pos[1]-yoff)
280 # draw lines - TODO put this in overlay graphic
282 old_aa = ctx.get_antialias()
283 ctx.set_antialias(C.ANTIALIAS_NONE)
284 ctx.set_source_rgb(0.8, 0.8, 0.8)
285 ctx.set_line_width(1)
286 ctx.move_to(self.gametype_pos[0]+xoffset-self.gametype_width/2+5, self.gametype_pos[1]+14)
287 ctx.line_to(self.gametype_pos[0]+xoffset+self.gametype_width/2-5, self.gametype_pos[1]+14)
289 ctx.move_to(self.gametype_pos[0]+xoffset-self.gametype_width/2+5, self.gametype_pos[1]+self.gametype_height+14)
290 ctx.line_to(self.gametype_pos[0]+xoffset+self.gametype_width/2-5, self.gametype_pos[1]+self.gametype_height+14)
292 ctx.set_antialias(old_aa)
294 if not elos.has_key(gt) or not ranks.has_key(gt):
295 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
296 ctx.set_font_size(self.nostats_fontsize)
297 ctx.set_source_rgb(self.nostats_color[0],self.nostats_color[1],self.nostats_color[2])
298 txt = "no stats yet!"
299 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
300 ctx.move_to(self.nostats_pos[0]+xoffset-xoff-tw/2, self.nostats_pos[1]-yoff)
302 ctx.rotate(math.radians(self.nostats_angle))
306 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
307 ctx.set_font_size(self.elo_fontsize)
308 ctx.set_source_rgb(self.elo_color[0], self.elo_color[1], self.elo_color[2])
309 txt = "Elo: %.0f" % round(elos[gt], 0)
310 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
311 ctx.move_to(self.elo_pos[0]+xoffset-xoff-tw/2, self.elo_pos[1]-yoff)
314 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
315 ctx.set_font_size(self.rank_fontsize)
316 ctx.set_source_rgb(self.rank_color[0], self.rank_color[1], self.rank_color[2])
317 txt = "Rank %d of %d" % ranks[gt]
318 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
319 ctx.move_to(self.rank_pos[0]+xoffset-xoff-tw/2, self.rank_pos[1]-yoff)
322 xoffset += self.gametype_width
325 # print win percentage
328 ctx.rectangle(self.wintext_pos[0]-self.wintext_width/2, self.wintext_pos[1]-self.wintext_fontsize/2+1,
329 self.wintext_width, self.wintext_fontsize+4)
330 ctx.set_source_rgba(self.wintext_bg[0], self.wintext_bg[1], self.wintext_bg[2], self.wintext_bg[3])
333 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
334 ctx.set_font_size(self.wintext_fontsize)
335 ctx.set_source_rgb(self.wintext_color[0], self.wintext_color[1], self.wintext_color[2])
336 txt = "Win Percentage"
337 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
338 ctx.move_to(self.wintext_pos[0]-xoff-tw/2, self.wintext_pos[1]-yoff)
341 wins, losses = total_stats["wins"], total_games-total_stats["wins"]
344 ratio = float(wins)/total_games
345 txt = "%.2f%%" % round(ratio * 100, 2)
348 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
349 ctx.set_font_size(self.winp_fontsize)
350 r = ratio*self.winp_colortop[0] + (1-ratio)*self.winp_colorbot[0]
351 g = ratio*self.winp_colortop[1] + (1-ratio)*self.winp_colorbot[1]
352 b = ratio*self.winp_colortop[2] + (1-ratio)*self.winp_colorbot[2]
353 ctx.set_source_rgb(r, g, b)
354 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
355 ctx.move_to(self.winp_pos[0]-xoff-tw/2, self.winp_pos[1]-yoff)
358 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
359 ctx.set_font_size(self.wins_fontsize)
360 ctx.set_source_rgb(self.wins_color[0], self.wins_color[1], self.wins_color[2])
361 txt = "%d win" % wins
364 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
365 ctx.move_to(self.wins_pos[0]-xoff-tw/2, self.wins_pos[1]-yoff)
368 ctx.set_font_size(self.loss_fontsize)
369 ctx.set_source_rgb(self.loss_color[0], self.loss_color[1], self.loss_color[2])
370 txt = "%d loss" % losses
373 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
374 ctx.move_to(self.loss_pos[0]-xoff-tw/2, self.loss_pos[1]-yoff)
378 # print kill/death ratio
381 ctx.rectangle(self.kdtext_pos[0]-self.kdtext_width/2, self.kdtext_pos[1]-self.kdtext_fontsize/2+1,
382 self.kdtext_width, self.kdtext_fontsize+4)
383 ctx.set_source_rgba(self.kdtext_bg[0], self.kdtext_bg[1], self.kdtext_bg[2], self.kdtext_bg[3])
386 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
387 ctx.set_font_size(self.kdtext_fontsize)
388 ctx.set_source_rgb(self.kdtext_color[0], self.kdtext_color[1], self.kdtext_color[2])
390 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
391 ctx.move_to(self.kdtext_pos[0]-xoff-tw/2, self.kdtext_pos[1]-yoff)
394 kills, deaths = total_stats['kills'] , total_stats['deaths']
397 ratio = float(kills)/deaths
398 txt = "%.3f" % round(ratio, 3)
402 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
403 ctx.set_font_size(self.kdr_fontsize)
407 r = nr*self.kdr_colortop[0] + (1-nr)*self.kdr_colorbot[0]
408 g = nr*self.kdr_colortop[1] + (1-nr)*self.kdr_colorbot[1]
409 b = nr*self.kdr_colortop[2] + (1-nr)*self.kdr_colorbot[2]
410 ctx.set_source_rgb(r, g, b)
411 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
412 ctx.move_to(self.kdr_pos[0]-xoff-tw/2, self.kdr_pos[1]-yoff)
415 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
416 ctx.set_font_size(self.kills_fontsize)
417 ctx.set_source_rgb(self.kills_color[0], self.kills_color[1], self.kills_color[2])
418 txt = "%d kill" % kills
421 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
422 ctx.move_to(self.kills_pos[0]-xoff-tw/2, self.kills_pos[1]+yoff)
425 ctx.set_font_size(self.deaths_fontsize)
426 ctx.set_source_rgb(self.deaths_color[0], self.deaths_color[1], self.deaths_color[2])
427 txt = "%d death" % deaths
430 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
431 ctx.move_to(self.deaths_pos[0]-xoff-tw/2, self.deaths_pos[1]+yoff)
438 ctx.rectangle( self.ptime_pos[0]-self.ptime_width/2, self.ptime_pos[1]-self.ptime_fontsize/2+1,
439 self.ptime_width, self.ptime_fontsize+4)
440 ctx.set_source_rgba(self.ptime_bg[0], self.ptime_bg[1], self.ptime_bg[2], self.ptime_bg[2])
443 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
444 ctx.set_font_size(self.ptime_fontsize)
445 ctx.set_source_rgb(self.ptime_color[0], self.ptime_color[1], self.ptime_color[2])
446 txt = "Playing time: %s" % str(total_stats['alivetime'])
447 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
448 ctx.move_to(self.ptime_pos[0]-xoff-tw/2, self.ptime_pos[1]-yoff)
453 #surf.write_to_png(output_filename)
455 imgdata = surf.get_data()
456 writepng(output_filename, imgdata, self.width, self.height)
459 def get_data(self, player):
460 """Return player data as dict.
462 This function is similar to the function in player.py but more optimized
469 # duel/dm/tdm/ctf elo + rank
471 player_id = player.player_id
473 games_played = DBSession.query(
474 Game.game_type_cd, func.count(), func.sum(PlayerGameStat.alivetime)).\
475 filter(Game.game_id == PlayerGameStat.game_id).\
476 filter(PlayerGameStat.player_id == player_id).\
477 group_by(Game.game_type_cd).\
478 order_by(func.count().desc()).\
479 limit(3).all() # limit to 3 gametypes!
482 total_stats['games'] = 0
483 total_stats['games_breakdown'] = {} # this is a dictionary inside a dictionary .. dictception?
484 total_stats['games_alivetime'] = {}
485 total_stats['gametypes'] = []
486 for (game_type_cd, games, alivetime) in games_played:
487 total_stats['games'] += games
488 total_stats['gametypes'].append(game_type_cd)
489 total_stats['games_breakdown'][game_type_cd] = games
490 total_stats['games_alivetime'][game_type_cd] = alivetime
492 (total_stats['kills'], total_stats['deaths'], total_stats['alivetime'],) = DBSession.query(
493 func.sum(PlayerGameStat.kills),
494 func.sum(PlayerGameStat.deaths),
495 func.sum(PlayerGameStat.alivetime)).\
496 filter(PlayerGameStat.player_id == player_id).\
499 # (total_stats['wins'],) = DBSession.query(
501 # filter(Game.game_id == PlayerGameStat.game_id).\
502 # filter(PlayerGameStat.player_id == player_id).\
503 # filter(Game.winner == PlayerGameStat.team or PlayerGameStat.rank == 1).\
506 (total_stats['wins'],) = DBSession.\
507 query("total_wins").\
509 "select count(*) total_wins "
510 "from games g, player_game_stats pgs "
511 "where g.game_id = pgs.game_id "
512 "and player_id=:player_id "
513 "and (g.winner = pgs.team or pgs.rank = 1)"
514 ).params(player_id=player_id).one()
516 ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
518 "select pr.game_type_cd, pr.rank, overall.max_rank "
519 "from player_ranks pr, "
520 "(select game_type_cd, max(rank) max_rank "
522 "group by game_type_cd) overall "
523 "where pr.game_type_cd = overall.game_type_cd "
524 "and player_id = :player_id "
526 params(player_id=player_id).all()
529 for gtc,rank,max_rank in ranks:
530 ranks_dict[gtc] = (rank, max_rank)
532 elos = DBSession.query(PlayerElo).\
533 filter_by(player_id=player_id).\
534 order_by(PlayerElo.elo.desc()).\
540 elos_dict[elo.game_type_cd] = elo.elo
544 'total_stats':total_stats,