5 import sqlalchemy as sa
6 import sqlalchemy.sql.functions as func
7 from datetime import datetime
8 from mako.template import Template
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
17 # similar to html_colors() from util.py
18 _contrast_threshold = 0.5
20 _dec_colors = [ (0.5,0.5,0.5),
33 # maximal number of query results (for testing, set to 0 to get all)
36 # image dimensions (likely breaks layout if changed)
40 # output filename, parameter is player id
41 OUTPUT = "output/%d.png"
50 WINLOSS_POS = (505,11)
53 KILLDEATH_POS = (395,11)
56 PLAYTIME_POS = (450,64)
60 # parameters to affect the output, could be changed via URL
62 'bg': 1, # 0 - black, 1 - dark_wall, ...
63 'overlay': 1, # 0 - none, 1 - Archer, ...
64 'font': 0, # 0 - xolonium, 1 - dejavu sans
68 # parse cmdline parameters (for testing)
69 for arg in sys.argv[1:]:
72 if params.has_key(k.lower()):
79 """Return player data as dict.
81 This function is similar to the function in player.py but more optimized
88 # duel/dm/tdm/ctf elo + rank
90 player_id = player.player_id
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!
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
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).\
119 (total_stats['wins'],) = DBSession.query(
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).\
126 ranks = DBSession.query("game_type_cd", "rank", "max_rank").\
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 "
132 "group by game_type_cd) overall "
133 "where pr.game_type_cd = overall.game_type_cd "
134 "and player_id = :player_id "
136 params(player_id=player_id).all()
139 for gtc,rank,max_rank in ranks:
140 ranks_dict[gtc] = (rank, max_rank)
142 elos = DBSession.query(PlayerElo).\
143 filter_by(player_id=player_id).\
144 order_by(PlayerElo.elo.desc()).\
150 elos_dict[elo.game_type_cd] = elo.elo
154 'total_stats':total_stats,
163 def render_image(data):
164 """Render an image from the given data fields."""
167 if params['font'] == 1:
170 total_stats = data['total_stats']
171 total_games = total_stats['games']
173 ranks = data["ranks"]
178 surf = C.ImageSurface(C.FORMAT_RGB24, WIDTH, HEIGHT)
179 ctx = C.Context(surf)
180 ctx.set_antialias(C.ANTIALIAS_GRAY)
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
188 # draw background image (try to get correct tiling, too)
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")
208 bg_w, bg_h = bg.get_width(), bg.get_height()
210 while bg_xoff < WIDTH:
212 while bg_yoff < HEIGHT:
213 ctx.set_source_surface(bg, bg_xoff, bg_yoff)
218 # draw overlay graphic
219 if params['overlay'] > 0:
221 if params['overlay'] == 1:
222 overlay = C.ImageSurface.create_from_png("img/overlay.png")
224 ctx.set_source_surface(overlay, 0, 0)
225 ctx.mask_surface(overlay)
229 ## draw player's nickname with fancy colors
231 # deocde nick, strip all weird-looking characters
232 qstr = qfont_decode(player.nick).replace('^^', '^').replace(u'\x00', ' ')
237 qstr = ''.join(chars)
238 stripped_nick = strip_colors(qstr)
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)
257 # split up nick into colored segments and draw each of them
259 # split nick into colored segments
263 npos = qstr.find('^', pos)
265 parts.append(qstr[pos-1:])
267 parts.append(qstr[pos-1:npos])
272 r,g,b = _dec_colors[7]
274 if txt.startswith('^'):
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)
286 r,g,b = _dec_colors[int(txt[0])]
289 r,g,b = _dec_colors[7]
292 # only colorcode and no real text, skip this
295 ctx.set_source_rgb(r, g, b)
296 ctx.move_to(NICK_POS[0] + xoffset, NICK_POS[1])
299 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
303 ## print elos and ranks
305 # show up to three gametypes the player has participated in
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)
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)
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)
326 ctx.set_antialias(old_aa)
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)
336 ctx.rotate(math.radians(-10))
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)
348 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
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)
356 xoffset += GAMES_WIDTH
359 # print win percentage
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)
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)
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)
380 ctx.set_source_rgb(0.2, 1.0, 1.0)
382 ctx.set_source_rgb(0.5, 1.0, 1.0)
384 ctx.set_source_rgb(0.5, 1.0, 0.8)
386 ctx.set_source_rgb(0.8, 1.0, 0.5)
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)
393 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
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)
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)
407 # print kill/death ratio
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)
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)
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)
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)
428 ctx.set_source_rgb(0.0, 1.0, 0.0)
430 ctx.set_source_rgb(0.2, 1.0, 0.2)
432 ctx.set_source_rgb(0.5, 1.0, 0.5)
434 ctx.set_source_rgb(1.0, 0.5, 0.5)
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)
441 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
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)
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)
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)
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)
471 surf.write_to_png(OUTPUT % data['player'].player_id)
475 env = bootstrap('../../../development.ini')
477 req.matchdict = {'id':3}
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()
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
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()
502 print "\r #%-5d" % player.player_id,
505 sstart = datetime.now()
507 sstop = datetime.now()
508 render_time += (sstop-sstart).total_seconds()
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