4 import sqlalchemy as sa
5 import sqlalchemy.sql.functions as func
6 from datetime import datetime
7 from mako.template import Template
9 from pyramid.paster import bootstrap
10 from xonstat.models import *
11 from xonstat.views.player import player_info_data
12 from xonstat.util import qfont_decode
13 from colorsys import rgb_to_hls, hls_to_rgb
16 # similar to html_colors() from util.py
17 _contrast_threshold = 0.5
19 _dec_colors = [ (0.5,0.5,0.5),
32 # parameters to affect the output, could be changed via URL
36 'bg': 1, # 0 - black, 1 - dark_wall
37 'font': 0, # 0 - xolonium, 1 - dejavu sans
41 # maximal number of query results (for testing, set to 0 to get all)
46 """Return player data as dict.
48 This function is similar to the function in player.py but more optimized
55 # duel/dm/tdm/ctf elo + rank
57 player_id = player.player_id
61 games_played = DBSession.query(
62 Game.game_type_cd, func.count(), func.sum(PlayerGameStat.alivetime)).\
63 filter(Game.game_id == PlayerGameStat.game_id).\
64 filter(PlayerGameStat.player_id == player_id).\
65 group_by(Game.game_type_cd).\
66 order_by(func.count().desc()).\
67 limit(3).all() # limit to 3 gametypes!
69 total_stats['games'] = 0
70 total_stats['games_breakdown'] = {} # this is a dictionary inside a dictionary .. dictception?
71 total_stats['games_alivetime'] = {}
72 total_stats['gametypes'] = []
73 for (game_type_cd, games, alivetime) in games_played:
74 total_stats['games'] += games
75 total_stats['gametypes'].append(game_type_cd)
76 total_stats['games_breakdown'][game_type_cd] = games
77 total_stats['games_alivetime'][game_type_cd] = alivetime
79 (total_stats['kills'], total_stats['deaths'], total_stats['suicides'],
80 total_stats['alivetime'],) = DBSession.query(
81 func.sum(PlayerGameStat.kills),
82 func.sum(PlayerGameStat.deaths),
83 func.sum(PlayerGameStat.suicides),
84 func.sum(PlayerGameStat.alivetime)).\
85 filter(PlayerGameStat.player_id == player_id).\
88 (total_stats['wins'],) = DBSession.query(
90 filter(Game.game_id == PlayerGameStat.game_id).\
91 filter(PlayerGameStat.player_id == player_id).\
92 filter(Game.winner == PlayerGameStat.team or PlayerGameStat.rank == 1).\
95 ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
97 "select pr.game_type_cd, pr.rank, overall.max_rank "
98 "from player_ranks pr, "
99 "(select game_type_cd, max(rank) max_rank "
101 "group by game_type_cd) overall "
102 "where pr.game_type_cd = overall.game_type_cd "
103 "and player_id = :player_id "
105 params(player_id=player_id).all()
108 for gtc,rank,max_rank in ranks:
109 ranks_dict[gtc] = (rank, max_rank)
111 elos = DBSession.query(PlayerElo).\
112 filter_by(player_id=player_id).\
113 order_by(PlayerElo.elo.desc()).\
119 elos_dict[elo.game_type_cd] = elo.elo
123 'total_stats':total_stats,
132 def render_image(data):
133 """Render an image from the given data fields."""
135 width, height = params['width'], params['height']
136 output = "output/%s.png" % data['player'].player_id
139 if params['font'] == 1:
142 total_stats = data['total_stats']
143 total_games = total_stats['games']
145 ranks = data["ranks"]
150 surf = C.ImageSurface(C.FORMAT_RGB24, width, height)
151 ctx = C.Context(surf)
153 # draw background (just plain fillcolor)
154 if params['bg'] == 0:
155 ctx.rectangle(0, 0, 1, 1);
156 ctx.set_source_rgba(0.2, 0.2, 0.2, 1.0);
159 # draw background image (try to get correct tiling, too)
162 if params['bg'] == 1:
163 bg = C.ImageSurface.create_from_png("img/dark_wall.png");
166 bg_w, bg_h = bg.get_width(), bg.get_height()
168 while bg_xoff < width:
170 while bg_yoff < height:
171 ctx.set_source_surface(bg, bg_xoff, bg_yoff);
177 ## draw player's nickname with fancy colors
179 # fontsize is reduced if width gets too large - TODO: needs finetuning
180 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
181 ctx.set_font_size(18)
182 xoff, yoff, tw, th = ctx.text_extents(player.stripped_nick)[:4]
184 ctx.set_font_size(16)
185 xoff, yoff, tw, th = ctx.text_extents(player.stripped_nick)[:4]
187 ctx.set_font_size(14)
189 # split up nick into colored segments and draw each of them
190 qstr = qfont_decode(player.nick).replace('^^', '^').replace('\x00', '')
192 txt_xpos, txt_ypos = 5,18
194 # split nick into colored segments
198 npos = qstr.find('^', pos)
200 parts.append(qstr[pos-1:])
202 parts.append(qstr[pos-1:npos])
206 r,g,b = _dec_colors[7]
208 if txt.startswith('^'):
210 if txt.startswith('x'):
211 r = int(txt[1] * 2, 16) / 255.0
212 g = int(txt[2] * 2, 16) / 255.0
213 b = int(txt[3] * 2, 16) / 255.0
214 hue, light, satur = rgb_to_hls(r, g, b)
215 if light < _contrast_threshold:
216 light = _contrast_threshold
217 r, g, b = hls_to_rgb(hue, light, satur)
220 r,g,b = _dec_colors[int(txt[0])]
223 r,g,b = _dec_colors[7]
226 # only colorcode and no real text, skip this
229 ctx.set_source_rgb(r, g, b)
230 ctx.move_to(txt_xpos + txt_xoff, txt_ypos)
233 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
235 # only whitespaces, use some extra space
241 ## print elos and ranks
243 games_x, games_y = 60,35
244 games_w = 110 # width of each gametype field
246 # show up to three gametypes the player has participated in
247 for gt in total_stats['gametypes'][:3]:
248 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
249 ctx.set_font_size(10)
250 ctx.set_source_rgb(1.0, 1.0, 1.0)
251 txt = "[ %s ]" % gt.upper()
252 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
253 ctx.move_to(games_x-xoff-tw/2,games_y-yoff-th/2)
256 ctx.set_line_width(1)
257 ctx.move_to(games_x-games_w/2+5, games_y+8);
258 ctx.line_to(games_x+games_w/2-5, games_y+8);
260 ctx.move_to(games_x-games_w/2+5, games_y+32);
261 ctx.line_to(games_x+games_w/2-5, games_y+32);
264 if not elos.has_key(gt) or not ranks.has_key(gt):
265 ctx.select_font_face(font, C.FONT_SLANT_ITALIC, C.FONT_WEIGHT_NORMAL)
266 ctx.set_font_size(10)
267 ctx.set_source_rgb(0.6, 0.6, 0.6)
268 txt = "(no stats yet!)"
269 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
270 ctx.move_to(games_x-xoff-tw/2,games_y+22-yoff-th/2)
273 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
274 ctx.set_font_size(10)
275 ctx.set_source_rgb(1.0, 1.0, 0.5)
276 txt = "Elo: %.0f" % round(elos[gt], 0)
277 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
278 ctx.move_to(games_x-xoff-tw/2,games_y+15-yoff-th/2)
281 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
283 ctx.set_source_rgb(0.8, 0.8, 0.8)
284 txt = "Rank %d of %d" % ranks[gt]
285 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
286 ctx.move_to(games_x-xoff-tw/2,games_y+25-yoff-th/2)
292 # print win percentage
293 win_x, win_y = 500,18
295 if total_games > 0 and total_stats['wins'] is not None:
296 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
298 ctx.set_source_rgb(0.8, 0.8, 0.8)
299 txt = "Win Percentage"
300 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
301 ctx.move_to(win_x-xoff-tw/2,win_y-yoff-th/2)
304 ratio = float(total_stats['wins'])/total_games
305 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
306 ctx.set_font_size(12)
308 ctx.set_source_rgb(0.5, 1.0, 1.0)
310 ctx.set_source_rgb(0.6, 1.0, 0.8)
312 ctx.set_source_rgb(0.8, 1.0, 0.6)
314 ctx.set_source_rgb(1.0, 1.0, 0.5)
315 txt = "%.2f%%" % round(ratio * 100, 2)
316 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
317 ctx.move_to(win_x-xoff-tw/2,win_y+14-yoff-th/2)
320 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
322 ctx.set_source_rgb(0.6, 0.8, 0.6)
323 txt = "%d wins" % total_stats["wins"]
324 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
325 ctx.move_to(win_x-xoff-tw/2,win_y+28-yoff-th/2)
327 ctx.set_source_rgb(0.8, 0.6, 0.6)
328 txt = "%d losses" % (total_games-total_stats['wins'])
329 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
330 ctx.move_to(win_x-xoff-tw/2,win_y+38-yoff-th/2)
333 # print kill/death ratio
334 kill_x, kill_y = 400,18
335 if total_stats['kills'] > 0 and total_stats['deaths'] > 0:
336 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
338 ctx.set_source_rgb(0.8, 0.8, 0.8)
340 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
341 ctx.move_to(kill_x-xoff-tw/2,kill_y-yoff-th/2)
344 ratio = float(total_stats['kills'])/total_stats['deaths']
345 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
346 ctx.set_font_size(12)
348 ctx.set_source_rgb(0.2, 1.0, 0.2)
350 ctx.set_source_rgb(0.5, 1.0, 0.5)
352 ctx.set_source_rgb(1.0, 0.5, 0.5)
354 ctx.set_source_rgb(1.0, 0.2, 0.2)
355 txt = "%.3f" % round(ratio, 3)
356 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
357 ctx.move_to(kill_x-xoff-tw/2,kill_y+14-yoff-th/2)
360 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
362 ctx.set_source_rgb(0.6, 0.8, 0.6)
363 txt = "%d kills" % total_stats["kills"]
364 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
365 ctx.move_to(kill_x-xoff-tw/2,kill_y+28-yoff-th/2)
367 ctx.set_source_rgb(0.8, 0.6, 0.6)
368 txt = "%d deaths" % total_stats['deaths']
369 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
370 ctx.move_to(kill_x-xoff-tw/2,kill_y+38-yoff-th/2)
374 surf.write_to_png(output)
378 env = bootstrap('../../../development.ini')
380 req.matchdict = {'id':3}
382 print "Requesting player data from db ..."
383 start = datetime.now()
384 players = DBSession.query(Player).\
385 filter(Player.player_id == PlayerElo.player_id).\
386 filter(Player.nick != None).\
387 filter(Player.player_id > 2).\
388 filter(Player.active_ind == True).\
389 limit(NUM_PLAYERS).all()
390 stop = datetime.now()
391 print "Query took %.2f seconds" % (stop-start).total_seconds()
393 print "Creating badges for %d players ..." % len(players)
394 start = datetime.now()
395 data_time, render_time = 0,0
396 for player in players:
397 req.matchdict['id'] = player.player_id
399 sstart = datetime.now()
400 #data = player_info_data(req)
401 data = get_data(player)
402 sstop = datetime.now()
403 data_time += (sstop-sstart).total_seconds()
405 print "\t#%d (%s)" % (player.player_id, player.stripped_nick)
407 sstart = datetime.now()
409 sstop = datetime.now()
410 render_time += (sstop-sstart).total_seconds()
412 stop = datetime.now()
413 print "Creating the badges took %.2f seconds (%.2f s per player)" % ((stop-start).total_seconds(), (stop-start).total_seconds()/float(len(players)))
414 print "Total time for getting data: %.2f s" % data_time
415 print "Total time for redering images: %.2f s" % render_time