[pypy-svn] r29304 - in pypy/dist/pypy/translator/js/proxy/testme: . static/javascript

ericvrp at codespeak.net ericvrp at codespeak.net
Sun Jun 25 09:53:10 CEST 2006


Author: ericvrp
Date: Sun Jun 25 09:53:06 2006
New Revision: 29304

Modified:
   pypy/dist/pypy/translator/js/proxy/testme/controllers.py
   pypy/dist/pypy/translator/js/proxy/testme/servermessage.py
   pypy/dist/pypy/translator/js/proxy/testme/static/javascript/bnb.js
Log:
Let proxy generate alpha layer for png's and decouple polling from rendering.


Modified: pypy/dist/pypy/translator/js/proxy/testme/controllers.py
==============================================================================
--- pypy/dist/pypy/translator/js/proxy/testme/controllers.py	(original)
+++ pypy/dist/pypy/translator/js/proxy/testme/controllers.py	Sun Jun 25 09:53:06 2006
@@ -76,8 +76,13 @@
     def recv(self):
         #XXX hangs if not first sending CMSG_PING!
         sm   = self.serverMessage()
-        size = 10000 #XXX should really loop until all data is handled
-        data = sm.data + self.sessionSocket().recv(size)
+        data = sm.data
+        sock = self.sessionSocket()
+        while True:
+            try:
+                data += sock.recv(4096, socket.MSG_DONTWAIT)
+            except:    
+                break
         while sm.n_header_lines > 0 and '\n' in data:
             sm.n_header_lines -= 1
             header_line, data = data.split('\n',1)

Modified: pypy/dist/pypy/translator/js/proxy/testme/servermessage.py
==============================================================================
--- pypy/dist/pypy/translator/js/proxy/testme/servermessage.py	(original)
+++ pypy/dist/pypy/translator/js/proxy/testme/servermessage.py	Sun Jun 25 09:53:06 2006
@@ -38,7 +38,7 @@
     _def_icon_queue = {}
     base_gfx_dir = 'testme/static/images/'
     base_gfx_url = 'static/images/'
-    gfx_extension = 'gif'
+    gfx_extension = 'png'
 
     def __init__(self, base_gfx_dir = None):
         if base_gfx_dir:
@@ -93,9 +93,10 @@
         if len(rest) == 0:
             colorkey = None
         else:
-            colorkey = rest[0]
+            c = rest[0]
+            colorkey = (c & 255, (c >> 8) & 255, (c >> 16) & 255)
         #log('def_bitmap1 bitmap_code=%d, data=%d bytes, colorkey=%s' % (
-        #    bitmap_code, len(data), colokey))
+        #    bitmap_code, len(data), colorkey))
         gif_bitmap_filename = '%sbitmap%d.%s' % (self.gfx_dir, bitmap_code, self.gfx_extension)
         if exists(gif_bitmap_filename):
             #log('CACHED:%s' % gif_bitmap_filename)
@@ -117,14 +118,17 @@
                 raise BitmapCreationException('ERROR LOADING %s (%s)' % (
                     bitmap_filename, str(e)))
 
-            #create alpha layer that hopefully gets into the .gif...
-            #if colorkey is not None:
-            #    bitmap = bitmap.convert("RGBA")
-            #    pixel = bitmap.getpixel( (0,0) )
-            #    log('%s: colorkey=%s, pixel=%s' % (bitmap_filename, colorkey, str(pixel)))
-            #    colorkeyT = (1, 1, 1, 255)
-            #    alpha = [pixel == (1,1,1,255) for pixel in list(bitmap.getdata())]
-            #    bitmap.putalpha(alpha)
+            #create alpha layer (PIL export this correctly with png but not with gif)
+            if colorkey is not None:
+                bitmap = bitmap.convert("RGBA")
+                data   = bitmap.getdata()
+                c      = (colorkey[0], colorkey[1], colorkey[2], 255)
+                width, height = bitmap.size
+                for y in range(height): #this is slowish but gfx are cached, so...
+                    for x in range(width):
+                        p = data.getpixel((x,y))
+                        if p == c:
+                            data.putpixel((x,y), (0,0,0,0))
 
             try:
                 bitmap.save(gif_bitmap_filename)
@@ -194,7 +198,7 @@
         return messages
     
     def player_icon(self, player_id, icon_code):
-        log('player_icon player_id=%d, icon_code=%d' % (player_id, icon_code))
+        #log('player_icon player_id=%d, icon_code=%d' % (player_id, icon_code))
         return dict(type=PMSG_PLAYER_ICON, player_id=player_id, icon_code=icon_code)
 
     def player_join(self, player_id, client_is_self):
@@ -202,7 +206,7 @@
         return dict(type=PMSG_PLAYER_JOIN, player_id=player_id, client_is_self=client_is_self)
 
     def def_key(self, keyname, num, *icon_codes):
-        log('def_key keyname=%s, num=%d, icon_codes=%s' % (keyname, num, str(icon_codes)))
+        #log('def_key keyname=%s, num=%d, icon_codes=%s' % (keyname, num, str(icon_codes)))
         return dict(type=PMSG_DEF_KEY, keyname=keyname, num=num, icon_codes=icon_codes)
 
     def md5_file(self, fileid, protofilepath, offset, len_data, checksum):

Modified: pypy/dist/pypy/translator/js/proxy/testme/static/javascript/bnb.js
==============================================================================
--- pypy/dist/pypy/translator/js/proxy/testme/static/javascript/bnb.js	(original)
+++ pypy/dist/pypy/translator/js/proxy/testme/static/javascript/bnb.js	Sun Jun 25 09:53:06 2006
@@ -1,46 +1,62 @@
 function BnB() { //entrypoint to be called by body.onLoad
 	// init global data
-	playfield = DIV({'bgcolor':'red', 'width':42, 'height':42}); //updated with def_playfield
-	icon = {};
 	doc = currentDocument();
 	body = doc.body;
 
+	playfield = DIV({'bgcolor':'red', 'width':42, 'height':42}); //updated with def_playfield
+        max_images = 999;
+        images = [];
+        for (var n = 0;n < max_images;n++) { //why is firefox so F!@#King slow?
+            var img = IMG({
+                //'width':'0', 'height':'0',
+                'style':'position:absolute; top:-1000px; left:-1000px;'});
+            images.push(img);
+        }
+        replaceChildNodes(playfield, images);
+        appendChildNodes(body, playfield);
+            
+	icon = {};
         offsetx = 64;
         offsety = 64;
-        zoom = 1;
 
-        prev_sprites = [];
+        curr_sprites = [];  //current (most up-to-date) location of sprites
+        prev_sprites = [];  //previous rendered sprites
 
         spacebar     = 32;  //XXX hardcoded for now
         cursor_left  = 37;
         cursor_up    = 38;
         cursor_right = 39;
         cursor_down  = 40;
-        keycodes = [cursor_right, cursor_left, cursor_up, spacebar]
-        key_is_down = [false, false, false, false]
+        keycodes = [cursor_right, cursor_left, cursor_up, spacebar];
+        key_is_down = [false, false, false, false];
+        key_icon_codes = [];
+        player_icon_code = [];
+
+        stats = {
+            'starttime' : 0,
+            'n_received_inline_frames'   : 0,
+            'n_rendered_inline_frames'   : 0,
+            'n_rendered_dynamic_sprites' : 0
+            };
 
+        setupEventHandlers();
 	receiveData();
-        handleKeysEvents();
+        setInterval(renderSprites, 1000 / 25); //max fps
 }
 
 function BnBKeyDown(e) {
     var c = String.fromCharCode(e.charCode);
+
     if (c == 'a') {
         addPlayer(0);
         return;
     }
+
     if (c == 'r') {
         removePlayer(0);
         return;
     }
-    if (c == '-') {
-        newZoom(zoom / 2);
-        return;
-    }
-    if (c == '+') {
-        newZoom(zoom * 2);
-        return;
-    }
+
     for (var i = 0;i < 4;i++) {
         if (e.keyCode == keycodes[i]) {
             var player_id = 0;  //XXX hardcoded for now
@@ -77,82 +93,37 @@
     }
 }
 
-function handleKeysEvents() {
+function onUnload() {
+    //this doesn't get reached when the user presses the Escape key.
+    removePlayer(0);
+    return true;
+}
+
+function setupEventHandlers() {
     document.onkeydown = BnBKeyDown;
     document.onkeyup   = BnBKeyUp;
     document.onkeypress= BnBKeyDown;
-}
-
-function newZoom(z) {
-    for (var icon_code in icon) {
-        var ic = icon[icon_code];
-        ic.width  *= z / zoom;
-        ic.height *= z / zoom;
-    }
-    zoom = z;
-    prev_sprites = []; //force redraw
+    window.onunload = onUnload;
 }
 
 function BnBColorToHexString(c) {
-	var r = c;	//XXX should do the correct masking here
-	var g = c;
-	var b = c;
+	var r = c & 255;
+	var g = (c >> 8) & 255;
+	var b = (c >> 16) & 255;
 	return Color.fromRGB(r,g,b).toHexString();
 }
 
-function handleServerResponse(json_doc) {
-    //setTimeout(0, 'receiveData'); //do a new request a.s.a.p
-    receiveData();
-    for (var i in json_doc.messages) {
-        var msg = json_doc.messages[i];
-        if (msg.type == 'def_playfield') { //XXX refactor to helper functions
-            var bgcolor = BnBColorToHexString(msg.backcolor);
-            updateNodeAttributes(playfield,
-                {'bgcolor':bgcolor, 'width':msg.width, 'height':msg.height});
-            //replaceChildNodes(body, playfield);
-            body.setAttribute('bgcolor', bgcolor); //XXX hack!
-
-        } else if (msg.type == 'def_icon') {
-            icon[msg.icon_code] = msg;
-            icon[msg.icon_code].width  *= zoom;
-            icon[msg.icon_code].height *= zoom;
-
-        } else if (msg.type == 'inline_frame') { //msg.sounds, msg.sprites
-            if (!this.inline_frame_starttime) {
-                this.images = [];
-                this.max_images = 999;
-                for (var n = 0;n < this.max_images;n++) { //why is firefox so F!@#King slow?
-                    var img = IMG({
-                        'width':'0', 'height':'0',
-                        'style':'position:absolute; top:-1000px; left:0px;'});
-                    this.images.push(img);
-                }
-                //replaceChildNodes(playfield, this.images);
-                replaceChildNodes(body, this.images);
-
-                this.inline_frame_starttime = new Date();
-                this.n_inline_frames = 0;
-            } else {
-                this.n_inline_frames++;
-                var fps = 1000 / ((new Date() - this.inline_frame_starttime) / this.n_inline_frames);
-                document.title = fps + " fps, " +
-                    this.n_dynamic_sprites + "/" + prev_sprites.length;
-            }
+function renderSprites() {
 
             //XXX firefox isn't instant with changing img.src's!
             //Plus it is very slow when changing the .src attribute
             //So we might be better of keeping a list of animating images 
             //so we can just move those to the right location!
 
-            var sprite_data, icon_code, img, n, prev;
-            this.n_dynamic_sprites = 0;
-            for (n = 0;n < msg.sprites.length && n < this.max_images;n++) {
-                sprite_data = msg.sprites[n];
-                icon_code = sprite_data[0];
-                if (!(icon_code in icon)) {
-                    sprite_data[0] = -100; //force redraw when icon becomes avaliable
-                    continue;
-                }
+            var sprite_data, img, n, prev;
+            var n_dynamic = 0;
+            for (n = 0;n < curr_sprites.length && n < max_images;n++) {
+                sprite_data = curr_sprites[n];
                 if (n < prev_sprites.length) {
                     prev = prev_sprites[n];
                     if (sprite_data[0] == prev[0] && 
@@ -162,22 +133,63 @@
                 } else {
                     prev = [-200,-200,-200]; //always draw new sprites
                 }
-                this.n_dynamic_sprites++;
-                if (icon_code      != prev[0])
-                    this.images[n].src = icon[icon_code].filename;
-                this.images[n].width  = icon[icon_code].width;
-                this.images[n].height = icon[icon_code].height;
+                if (sprite_data[0] != prev[0])
+                    images[n].src = icon[sprite_data[0]].filename;
                 if (sprite_data[1] != prev[1])
-                    this.images[n].style.left = offsetx + sprite_data[1] * zoom + 'px'
+                    images[n].style.left = offsetx + sprite_data[1] + 'px';
                 if (sprite_data[2] != prev[2])
-                    this.images[n].style.top  = offsety + sprite_data[2] * zoom + 'px'
+                    images[n].style.top  = offsety + sprite_data[2] + 'px';
+                //images[n].width  = icon[sprite_data[0]].width;
+                //images[n].height = icon[sprite_data[0]].height;
+                n_dynamic++;
             }
             var n_max = prev_sprites.length;
-            if (n_max == 0) n_max = this.max_images;
+            if (n_max == 0) n_max = max_images;
             for (;n < n_max;n++) {
-                this.images[n].style.left = "-1000px";
+                images[n].style.left = "-1000px";
+            }
+            prev_sprites = curr_sprites;
+
+            if (n_dynamic > 0)
+                stats.n_rendered_dynamic_sprites = n_dynamic;
+            stats.n_rendered_inline_frames++;
+}
+
+function handleServerResponse(json_doc) {
+    receiveData();
+
+    for (var i in json_doc.messages) {
+        var msg = json_doc.messages[i];
+        if (msg.type == 'def_playfield') { //XXX refactor to helper functions
+            var bgcolor = BnBColorToHexString(msg.backcolor);
+            updateNodeAttributes(playfield,
+                {'bgcolor':bgcolor, 'width':msg.width, 'height':msg.height});
+            body.setAttribute('bgcolor', bgcolor); //XXX hack!
+
+        } else if (msg.type == 'def_key') {
+            if (msg.icon_codes.length > 0) {
+                key_icon_codes[msg.num] = msg.icon_codes;
             }
-            prev_sprites = msg.sprites;
+
+        } else if (msg.type == 'player_icon') {
+            player_icon_code[msg.player_id] = msg.icon_code;
+
+        } else if (msg.type == 'def_icon') {
+            icon[msg.icon_code] = msg;
+            //icon[msg.icon_code].image = new Image(); //preloading is too slow (too much data)
+            //icon[msg.icon_code].image.src = msg.filename; //note: it seems image.onload works!
+            
+        } else if (msg.type == 'inline_frame') { //msg.sounds, msg.sprites
+            if (!stats.starttime) 
+                stats.starttime = new Date();
+
+            stats.n_received_inline_frames++;
+            var t = new Date() - stats.starttime;
+            var fps = 1000 / (t / stats.n_rendered_inline_frames);
+            var ups = 1000 / (t / stats.n_received_inline_frames); //updates per second
+            document.title = fps + " fps, " + ups + " ups, " + stats.n_rendered_dynamic_sprites + "/" + prev_sprites.length;
+            curr_sprites = msg.sprites;
+
         } else {
             logWarning('unknown msg.type: ' + msg.type + ', msg: ' + items(msg));
         }



More information about the Pypy-commit mailing list