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"
53 KILLDEATH_POS = (390,6)
56 PLAYTIME_POS = (452,64)
60 # parameters to affect the output, could be changed via URL
62 'bg': 8, # 0 - black, 1 - dark_wall, ...
63 'overlay': 0, # 0 - none, 1 - default overlay, ...
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")
205 elif params['bg'] == 8:
206 bg = C.ImageSurface.create_from_png("img/background_archer-v1.png")
210 bg_w, bg_h = bg.get_width(), bg.get_height()
212 while bg_xoff < WIDTH:
214 while bg_yoff < HEIGHT:
215 ctx.set_source_surface(bg, bg_xoff, bg_yoff)
220 # draw overlay graphic
221 if params['overlay'] > 0:
223 if params['overlay'] == 1:
224 overlay = C.ImageSurface.create_from_png("img/overlay.png")
226 ctx.set_source_surface(overlay, 0, 0)
227 ctx.mask_surface(overlay)
231 ## draw player's nickname with fancy colors
233 # deocde nick, strip all weird-looking characters
234 qstr = qfont_decode(player.nick).replace('^^', '^').replace(u'\x00', ' ')
239 qstr = ''.join(chars)
240 stripped_nick = strip_colors(qstr)
242 # fontsize is reduced if width gets too large
243 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
244 ctx.set_font_size(20)
245 xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
246 if tw > NICK_MAXWIDTH:
247 ctx.set_font_size(18)
248 xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
249 if tw > NICK_MAXWIDTH:
250 ctx.set_font_size(16)
251 xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
252 if tw > NICK_MAXWIDTH:
253 ctx.set_font_size(14)
254 xoff, yoff, tw, th = ctx.text_extents(stripped_nick)[:4]
255 if tw > NICK_MAXWIDTH:
256 ctx.set_font_size(12)
259 # split up nick into colored segments and draw each of them
261 # split nick into colored segments
265 npos = qstr.find('^', pos)
267 parts.append(qstr[pos-1:])
269 parts.append(qstr[pos-1:npos])
274 r,g,b = _dec_colors[7]
276 if txt.startswith('^'):
278 if txt.startswith('x'):
279 r = int(txt[1] * 2, 16) / 255.0
280 g = int(txt[2] * 2, 16) / 255.0
281 b = int(txt[3] * 2, 16) / 255.0
282 hue, light, satur = rgb_to_hls(r, g, b)
283 if light < _contrast_threshold:
284 light = _contrast_threshold
285 r, g, b = hls_to_rgb(hue, light, satur)
288 r,g,b = _dec_colors[int(txt[0])]
291 r,g,b = _dec_colors[7]
294 # only colorcode and no real text, skip this
297 ctx.set_source_rgb(r, g, b)
298 ctx.move_to(NICK_POS[0] + xoffset, NICK_POS[1])
301 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
305 ## print elos and ranks
307 # show up to three gametypes the player has participated in
309 for gt in total_stats['gametypes'][:3]:
310 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
311 ctx.set_font_size(10)
312 ctx.set_source_rgb(1.0, 1.0, 1.0)
313 txt = "[ %s ]" % gt.upper()
314 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
315 ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]-yoff-4)
318 old_aa = ctx.get_antialias()
319 ctx.set_antialias(C.ANTIALIAS_NONE)
320 ctx.set_source_rgb(0.8, 0.8, 0.8)
321 ctx.set_line_width(1)
322 ctx.move_to(GAMES_POS[0]+xoffset-GAMES_WIDTH/2+5, GAMES_POS[1]+8)
323 ctx.line_to(GAMES_POS[0]+xoffset+GAMES_WIDTH/2-5, GAMES_POS[1]+8)
325 ctx.move_to(GAMES_POS[0]+xoffset-GAMES_WIDTH/2+5, GAMES_POS[1]+32)
326 ctx.line_to(GAMES_POS[0]+xoffset+GAMES_WIDTH/2-5, GAMES_POS[1]+32)
328 ctx.set_antialias(old_aa)
330 if not elos.has_key(gt) or not ranks.has_key(gt):
331 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
332 ctx.set_font_size(12)
333 ctx.set_source_rgb(0.8, 0.2, 0.2)
334 txt = "no stats yet!"
335 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
336 ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+28-yoff-4)
338 ctx.rotate(math.radians(-10))
342 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
343 ctx.set_font_size(10)
344 ctx.set_source_rgb(1.0, 1.0, 0.5)
345 txt = "Elo: %.0f" % round(elos[gt], 0)
346 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
347 ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+15-yoff-4)
350 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
352 ctx.set_source_rgb(0.8, 0.8, 0.8)
353 txt = "Rank %d of %d" % ranks[gt]
354 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
355 ctx.move_to(GAMES_POS[0]+xoffset-xoff-tw/2, GAMES_POS[1]+25-yoff-3)
358 xoffset += GAMES_WIDTH
361 # print win percentage
363 ctx.rectangle(WINLOSS_POS[0]-WINLOSS_WIDTH/2, WINLOSS_POS[1]-7, WINLOSS_WIDTH, 15)
364 ctx.set_source_rgba(0.8, 0.8, 0.8, 0.1)
367 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
368 ctx.set_font_size(10)
369 ctx.set_source_rgb(0.8, 0.8, 0.8)
370 txt = "Win Percentage"
371 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
372 ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]-yoff-3)
375 wins, losses = total_stats["wins"], total_games-total_stats["wins"]
378 ratio = float(wins)/total_games
379 txt = "%.2f%%" % round(ratio * 100, 2)
382 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
383 ctx.set_font_size(12)
385 ctx.set_source_rgb(0.2, 1.0, 1.0)
387 ctx.set_source_rgb(0.5, 1.0, 1.0)
389 ctx.set_source_rgb(0.5, 1.0, 0.8)
391 ctx.set_source_rgb(0.8, 1.0, 0.5)
393 ctx.set_source_rgb(1.0, 1.0, 0.5)
394 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
395 ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+18-yoff-4)
398 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
400 ctx.set_source_rgb(0.6, 0.8, 0.8)
401 txt = "%d win" % wins
404 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
405 ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+30-yoff-3)
407 ctx.set_source_rgb(0.8, 0.8, 0.6)
408 txt = "%d loss" % losses
411 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
412 ctx.move_to(WINLOSS_POS[0]-xoff-tw/2, WINLOSS_POS[1]+40-yoff-3)
416 # print kill/death ratio
418 ctx.rectangle(KILLDEATH_POS[0]-KILLDEATH_WIDTH/2, KILLDEATH_POS[1]-7, KILLDEATH_WIDTH, 15)
419 ctx.set_source_rgba(0.8, 0.8, 0.8, 0.1)
422 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
423 ctx.set_font_size(10)
424 ctx.set_source_rgb(0.8, 0.8, 0.8)
426 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
427 ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]-yoff-3)
430 kills, deaths = total_stats['kills'] , total_stats['deaths']
433 ratio = float(kills)/deaths
434 txt = "%.3f" % round(ratio, 3)
437 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_BOLD)
438 ctx.set_font_size(12)
440 ctx.set_source_rgb(0.0, 1.0, 0.0)
442 ctx.set_source_rgb(0.2, 1.0, 0.2)
444 ctx.set_source_rgb(0.5, 1.0, 0.5)
446 ctx.set_source_rgb(1.0, 0.5, 0.5)
448 ctx.set_source_rgb(1.0, 0.2, 0.2)
449 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
450 ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+18-yoff-4)
453 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
455 ctx.set_source_rgb(0.6, 0.8, 0.6)
456 txt = "%d kill" % kills
459 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
460 ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+30-yoff-3)
462 ctx.set_source_rgb(0.8, 0.6, 0.6)
463 txt = "%d death" % deaths
466 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
467 ctx.move_to(KILLDEATH_POS[0]-xoff-tw/2, KILLDEATH_POS[1]+40-yoff-3)
473 ctx.rectangle( PLAYTIME_POS[0]-PLAYTIME_WIDTH/2, PLAYTIME_POS[1]-7, PLAYTIME_WIDTH, 14)
474 ctx.set_source_rgba(0.8, 0.8, 0.8, 0.6)
477 ctx.select_font_face(font, C.FONT_SLANT_NORMAL, C.FONT_WEIGHT_NORMAL)
478 ctx.set_font_size(10)
479 ctx.set_source_rgb(0.1, 0.1, 0.1)
480 txt = "Playing time: %s" % str(total_stats['alivetime'])
481 xoff, yoff, tw, th = ctx.text_extents(txt)[:4]
482 ctx.move_to(PLAYTIME_POS[0]-xoff-tw/2, PLAYTIME_POS[1]-yoff-4)
487 surf.write_to_png(OUTPUT % data['player'].player_id)
491 env = bootstrap('../../../development.ini')
493 req.matchdict = {'id':3}
495 print "Requesting player data from db ..."
496 start = datetime.now()
497 players = DBSession.query(Player).\
498 filter(Player.player_id == PlayerElo.player_id).\
499 filter(Player.nick != None).\
500 filter(Player.player_id > 2).\
501 filter(Player.active_ind == True).\
502 limit(NUM_PLAYERS).all()
503 stop = datetime.now()
504 print "Query took %.2f seconds" % (stop-start).total_seconds()
506 print "Creating badges for %d active players ..." % len(players)
507 start = datetime.now()
508 data_time, render_time = 0,0
509 for player in players:
510 req.matchdict['id'] = player.player_id
512 sstart = datetime.now()
513 #data = player_info_data(req)
514 data = get_data(player)
515 sstop = datetime.now()
516 data_time += (sstop-sstart).total_seconds()
518 print "\r #%-5d" % player.player_id,
521 sstart = datetime.now()
523 sstop = datetime.now()
524 render_time += (sstop-sstart).total_seconds()
527 stop = datetime.now()
528 print "Creating the badges took %.2f seconds (%.2f s per player)" % ((stop-start).total_seconds(), (stop-start).total_seconds()/float(len(players)))
529 print " Total time for getting data: %.2f s" % data_time
530 print " Total time for renering images: %.2f s" % render_time