Friday, May 7, 2010

Stop the Canvas Walker with Comet

‹prev | My Chain | next›

I continue working on my <canvas> / fab.js "game" tonight. After some more refactoring and DRYing up of the code, I am ready to tackle a nagging bug.

The bug is best illustrated in video:



The view-only mode works fine as long as I don't change direction mid-walk. In that case, my character on the view-only screen goes a bit haywire. After a bit of noodling, I think that the cause of this problem is that new walk-to-coordinate does not cancel the previous walk-to-coordinate. Both combine to speed the character off-screen.

The reason this does not happen on the interactive screen is that the event notification method explicitly cancels the previous walk:
Player.prototype.notify = function(evt) {
switch(evt.type) {
case "click":
if (this.walker) clearTimeout(this.walker);
this.walk_to(evt.offsetX, evt.offsetY);
this.notify_server({id:this.id,x:evt.offsetX, y:evt.offsetY});
break;
}
};
If I am correct, then I ought to be able to resolve this by moving the cancel-the-previous-walker code into a separate method that can be called by the comet code driving the view-only walker:
Player.prototype.notify = function(evt) {
switch(evt.type) {
case "click":
this.stop();
this.walk_to(evt.offsetX, evt.offsetY);
this.notify_server({id:this.id,x:evt.offsetX, y:evt.offsetY});
break;
}
};

Player.prototype.stop = function () {
if (this.walker) clearTimeout(this.walker);
};
The javascript code that I push via comet then needs to call this new stop() method:
function broadcast(obj) {
listeners.forEach(
function(listener) {
var body = '<script type="text/javascript">' + "\nconsole.debug('" + obj.body + "')\n</script>\n";
listener({body: body});

body = '<script type="text/javascript">' + "\nloc = " + obj.body + ";\nwindow.parent.me.stop();\nwindow.parent.me.walk_to(loc.x, loc.y);\n</script>\n";
listener({body: body});
}
);
}
With that, I restart my fab.js server and try again:



Ah, much better. Up tomorrow: combining the two <canvas> boards so that I can move around my room and see others as they move around as well.

Day #96

Thursday, May 6, 2010

Static HTTP Server in 4 Lines of Fab.js

‹prev | My Chain | next›

Building on my static fab.js file server from last night, I would like to ensure that it only serves up files from the html sub-directory. Right now, a URL that included ../../../etc/passwd might return something that I would prefer it not return:
  (fab.nodejs.fs)
(
function () {
var out = this;
return function (head) {
out({ body: "html/" + head.url.pathname.substr(1) + ".html" });
if (out) out();
};
}
)
Happily, I can make use of a fab.js RegExp app to accomplish this and make my static file server app even shorter:
  (/^\/([_\w]+)$/)
(fab.nodejs.fs)
( fab.tmpl, "html/<%= this %>.html" )
( fab.capture.at, 0 )
Fab.js puts the matched portion of the URL into the capture attribute of the request URL. The fab.capture.at app, with an argument of zero pulls out the zero element from the RegExp matched URL. That gets passed back upstream to the fab.tmpl app which uses micro-templating to build a file path.

I do something similar to serve up Javascript files:
  (/^\/javascript/)
(/^\/([_\w]+)\.js$/)
(fab.nodejs.fs)
( fab.tmpl, "javascript/<%= this %>.js" )
( fab.capture.at, 0 )
(404)
The trailing 404 is the second app for the ternary RegExp that tries to match the .js file. The HTML file app does something similar, but passes on to the next application.

With that, I re-organize some of my javascript and spend the rest of my night readying the code for release on github. No guarantees that it will work, especially with all of the changes fab.js is undergoing currently. Still, hopefully it will be of some use to others.

Day #95

Wednesday, May 5, 2010

Static HTTP Server in 6 Lines of Fab.js

‹prev | My Chain | next›

Tonight, I start the process of moving my <canvas>/fab.js game out of a "play" sandbox into a real code repository. So far, the game consists of moving a character about in one browser screen and watching the results in another browser:



At this point, the entire application consists of three files: game.js (script containing the fab.js backend) and two static HTML files. I create a repository:
cstrom@whitefall:~$ mkdir repos/my_fab_game/
I put game.js directly in that directory and the two static HTML files into an html sub-directory such that:
cstrom@whitefall:~/repos/my_fab_game$ find
.
./html
./html/board.html
./html/view_only.html
./game.js
With that, I need to make game.js aware of the fab.js library—preferably without hard-coding any paths. This is accomplished by putting the library node.js's load path. The easiest way to do this is to create a symbolic link to fab.js in the ~/.node_libraries directory:
cstrom@whitefall:~$ mkdir ~/.node_libraries
cstrom@whitefall:~$ cd .node_libraries/
cstrom@whitefall:~/.node_libraries$ ln -s ../repos/fab
Now, my fab.js script can start with:
with ( require( "fab" ) )
And it will find the fab.js library.

Next up, how to serve those static files?

I had accomplished this during play-time by hard coding the fab.nodejs.fs call to the route. I would prefer something that took the requested URL and pulled the corresponding HTML file from the file system. Sure I could accomplish this in Apache, by why introduce that if I can do it stand alone?

This is the code that I settle on to accomplish just that:

(fab.nodejs.fs)
(
function () {
var out = this;
return function (head) {
out({ body: "html/" + head.url.pathname.substr(1) + ".html" });
if (out) out();
};
}
)
The anonymous upstream function uses the header information to tell fab.nodejs.fs where to find the correct file. This only works if I make a change to fab.nodejs.fs similar to the one I had to make to fab.nodeje.http—putting an upstream listener into fab.nodejs.fs so that my upstream, anonymous function will have access to the URL.

I fork fab.js on github to encapsulate these two changes. I don't know if these changes are needed for others (there are major changes on the way which might address this), but I need it now.

With that, I can run my fab.js app:
cstrom@whitefall:~/repos/my_fab_game$ node game.js 
And request my static files:
cstrom@whitefall:~/repos/my_fab_game$ curl http://localhost:4011/view_only -Ni
HTTP/1.1 200 OK
Connection: keep-alive
Transfer-Encoding: chunked

<html>
<head>
<style type="text/css">
#canvas {
...
That is a good stopping point for tonight. I will pick up tomorrow fixing a bug and re-organizing the <canvas> javascript code.

Day #94

Tuesday, May 4, 2010

Retrospective: Week Thirteen

‹prev | My Chain | next›

In an ongoing effort to make this chain as valuable as possible to myself (and possibly others), I perform a weekly retrospective of how the past week went (notes from last week). I do this on Tuesdays to avoid conflicts with B'more on Rails, which usually holds events then.

WHAT WENT WELL

  • Shifted off my application-to-update-CouchDB in favor of a fab.js application (at least for a little while). Fab.js is just that cool.
  • Solved a minor mystery with the fab.nodejs.http proxy app.
  • Started playing with the <canvas> tag. I have heard much about it, but never had the chance to do anything with it myself. It was quite easy and very fun.
  • Hooked said <canvas> tag up to fab.js both via AJAX and comet—both were quite easy to do in fab.js.

OBSTACLES / THINGS THAT WENT NOT SO WELL

  • Ran into a problem with comet and fab.js, which I eventually tracked down to oddness with Google Chrome.
  • I am spending a little too much time with this stuff some nights. Sleep is important.

WHAT I'LL TRY NEXT WEEK

  • I foresee no real changes next week, this one has been incredibly productive and I would be lucky to continue such a streak
  • I would like to figure out how test with fab.js. I have not even gotten the build suite to run at this point.


Day #93

Monday, May 3, 2010

Comet on Fab.js (Shakes Fist at Google Chrome)

‹prev | My Chain | next›

Last night I made great progress with comet and fab.js. Great progress that is until I tried it in an actual browser. Then I failed miserably.

So far, I can move a character about a <canvas> room by clicking anywhere in the room. In addition to the character walking to the mouse click, the character also sends the coordinate information to the fab.js server. That coordinate information is broadcasted to view-only listeners.

As of yesterday, this is what my curl client was seeing:
cstrom@whitefall:~/repos/fab$ curl http://localhost:4011/view -Ni
HTTP/1.1 200 OK
content-type: text/html
Connection: keep-alive
Transfer-Encoding: chunked

<html><body>
<script type="text/javascript">
alert('{"id":"me","x":370,"y":142}')
</script>
<script type="text/javascript">
alert('{"id":"me","x":206,"y":228}')
</script>
...
I have never really had need to do comet before, but it seems a simple enough concept. If I stick that output in a <iframe>, it ought to initiate javascript alerts. Much to my chagrin, there were no alerts.

I spent a good long time digging through chunked transfer encoding documentation and mucking with the output formats—all for naught. Finally, in a fit of frustration, I found myself clicking on the <canvas> room over and over and over again until... I finally saw an alert. And not just one alert, but every alert that I had expected to see in my frustration.

It seems that Google Chrome buffers comet responses until a certain threshold is reached. After that threshold is reached, the all subsequent comet pushes are interpreted immediately. Since I want the first request to be interpreted by the browser immediately, I need to figure out what that threshold is. Ah, trial-and-error...

Eventually, I find that somewhere in the neighborhood of 1024 characters are needed before the Google Chrome flood gates open. The /view resource that works immediately:
  ( /view/ )
( function(){
listeners.push( this );
this({headers: { "content-type": "text/html"},
body: "<html><body>\n"})

({body: "<script type=\"text/javascript\">\"123456789 123456789 123456789 123456789 123456789 12345\";</script>\n"})
({body: "<script type=\"text/javascript\">\"123456789 123456789 123456789 123456789 123456789 12345\";</script>\n"})
({body: "<script type=\"text/javascript\">\"123456789 123456789 123456789 123456789 123456789 12345\";</script>\n"})
({body: "<script type=\"text/javascript\">\"123456789 123456789 123456789 123456789 123456789 12345\";</script>\n"})
({body: "<script type=\"text/javascript\">\"123456789 123456789 123456789 123456789 123456789 12345\";</script>\n"})

({body: "<script type=\"text/javascript\">\"123456789 123456789 123456789 123456789 123456789 12345\";</script>\n"})
({body: "<script type=\"text/javascript\">\"123456789 123456789 123456789 123456789 123456789 12345\";</script>\n"})
({body: "<script type=\"text/javascript\">\"123456789 123456789 123456789 123456789 123456789 12345\";</script>\n"})
({body: "<script type=\"text/javascript\">\"123456789 123456789 123456789 123456789 123456789 12345\";</script>\n"})
({body: "<script type=\"text/javascript\">\"123456789 123456789 123456789 123456789 123456789 12345\";</script>\n"});
} )
Each one of those 12345... script lines is exactly 100 bytes long. The original <html><body> is and additional 16 bytes. 1016 + any comet output always results in an alert() message. Also of note here is that the <html><body> line is required—there was no alert() without it.

With that, it is trivial for fab.js to tell a read-only player to walk in response to live movements:
  ( /move/ )

(
function () {
var out = this;
return function listener( obj ) {
if ( !obj ) out();
else if ( obj.body ) {
broadcast(obj);
}
return listener;
};
}
)


function broadcast(obj) {
listeners.forEach(
function(listener) {
var body = '<script type="text/javascript">' + "\nconsole.debug('" + obj.body + "')\n</script>\n";
listener({body: body});

body = '<script type="text/javascript">' + "\nloc = " + obj.body + ";\nwindow.parent.me.walk_to(loc.x, loc.y);\n</script>\n";
listener({body: body});
}
);
}
And just like that, I can make an event in one browser session show up in another:



I still have quite a bit of refactoring to do on the code (and some testing might be nice), but this is a very satisfying stopping point for the night.

Day #92

Sunday, May 2, 2010

Comet (sort of) and Fab.js

‹prev | My Chain | next›

Tonight, I explore comet with fab.js. I have my little <canvas> room sending coordinate events to fab.js. Now I'd like to push them to listening clients.

First up, I give a place for a client to access a view-only look at the room:
  ( /view/ )
( function(){
listeners.push( this );
} )
Very straight forward: the requesting client is stored in an array of listeners to be called later. That later time happens when I move my character around in the <canvas> room:
  ( /move/ )

(
function () {
var out = this;
return function listener( obj ) {
if ( !obj ) out();
else if ( obj.body ) {
broadcast(obj);
}
return listener;
};
}
)
The broadcast function should iterate over each listener and send the coordinates:
function broadcast(obj) {
listeners.forEach(
function(listener) {
listener(obj);
}
);
}
To test this out, I drop down to an unbuffered curl session:
strom@whitefall:~/repos/fab$ curl http://localhost:4011/view -Ni
HTTP/1.1 200 OK
Connection: keep-alive
Transfer-Encoding: chunked

{"id":"me","x":192,"y":360}{"id":"me","x":135,"y":226}{"id":"me","x":381,"y":317}
Cool! That seems to have done the trick. I am indeed broadcasting.

I run into a problem that I am unable to solve, however. I cannot use that information to have an effect in the browser. I change the broadcast function to debug the JSON in the browser's console:
function broadcast(obj) {
listeners.forEach(
function(listener) {
//listener(obj);
// puts("sending: " + obj.body);
listener({body:'<script type="text/javascript">console.debug(\'' + obj.body + '\')</script>'+"\n\n"});
}
);
}
My curl client sees this change:
cstrom@whitefall:~/repos/fab$ curl http://localhost:4011/view -Ni
HTTP/1.1 200 OK
Connection: keep-alive
Transfer-Encoding: chunked

<script type="text/javascript">console.debug('{"id":"me","x":276,"y":123}')</script>

<script type="text/javascript">console.debug('{"id":"me","x":365,"y":208}')</script>
But nothing happens in my browser's console. Ultimately, I will probably look into web sockets to accomplish this, but I would at least like to understand comet well enough to do something like this, so...

I will pick back up with this tomorrow.

Day #91

Saturday, May 1, 2010

Connecting Canvas Movements to Fab.js

‹prev | My Chain | next›

Tonight, I continue my exploration of <canvas>, this time with an eye toward hooking it up to fab.js. Last night, I was able to get a small dot representing my character to move about the <canvas> in response to key presses.

That will not work with the "game" my kids have in mind. They'd like a bunch of characters to meander about the board talking to each other. Moving dozens of characters about pixel-by-pixel is something that fab.js/node.js could probably handle, but dealing with network latency and hiccups is probably not worth the effort.

Instead, I will move the character around by having them walk after mouse click. The character will start in the middle of the canvas. A mouse click in the bottom right will result in a animation of my character moving from the middle of the board to the bottom right.

To accomplish this, I publish the clicks from the board to any subscribers interested in being notified. I have no expectation that anything else will be interested in mouse clicks, but pub-sub makes sense here not as a premature generalization, but rather to decouple the game board from my character. So, I establish my <canvas> listeners:
function init() {
var canvas = $("#canvas").get(0);
var ctx = canvas.getContext("2d");

var me = new Player();

canvas_events(canvas, [me]);
draw(ctx, me);
}
My only canvas event:
function canvas_events (canvas, listeners) {
$(canvas).click(function(evt) {
listeners.forEach(
function(listener) { listener.notify(evt) }
);
});
}
(as you may have noticed, I have started using jQuery for my events)

Great, so now I need a Player object that will encapsulate the position of my character and subscribe to the event publications. The instantiation of the class is straight-forward, defaulting to the middle of my 500x500 <canvas>:
var Player = function(options) {
if (!options) options = {};
this.x = options.x || 250;
this.y = options.y || 250;
}
Now, I establish my notify method:
Player.prototype.notify = function(evt) {
switch(evt.type) {
case "click":
this.walk_to(evt.offsetX, evt.offsetY);
break;
}
};
For now, I am only interested in click publications, which initiate a walk:
Player.prototype.walk_to = function(x, y) {
if (this.x < x) this.x = this.x + 1;
if (this.x > x) this.x = this.x - 1;
if (this.y < y) this.y = this.y + 1;
if (this.y > y) this.y = this.y - 1;

if (this.x != x || this.y != y) {
setTimeout(function(){self.walk_to(x,y)}, 25);
}
};
Easy enough!

Now, to tell fab.js what I am up to. I start with my skeleton app:
var puts = require( "sys" ).puts;

with ( require( ".." ) )

( fab )

( listen, 0xFAB )

( 404 );
For now, I am just going to print out the contents of posted location information. I will push that information to other clients later. The fab.js application to do this:
var puts = require( "sys" ).puts;

with ( require( ".." ) )

( fab )

( listen, 0xFAB )

( /move/ )

(
function () {
var out = this;
return function listener( obj ) {
if ( !obj ) out();
else if ( obj.body ) puts(obj.body);
return listener;
};
}
)


( 404 );
To tell my Player class to POST that information, I add a second action in notify():
Player.prototype.notify = function(evt) {
switch(evt.type) {
case "click":
this.walk_to(evt.offsetX, evt.offsetY);
this.notify_server({id:"me",x:evt.offsetX, y:evt.offsetY});
break;
}
};
The server_notify method make a simple jQuery POST:
Player.prototype.notify_server = function(change) {
$.post("http://localhost:4011/move", change);
};
Now, clicking on the board moves my character and tells fab.js:
cstrom@whitefall:~/repos/fab$ node ./play/game.js
id=me&x=322&y=184
id=me&x=364&y=352
id=me&x=199&y=198
id=me&x=350&y=401
Nice! That is a good stopping point for tonight. Tomorrow, I will work on pushing that information to other boards so that others can see my character move.

Day #90