Friday, May 14, 2010

Iframe src and a Weird Object

‹prev | My Chain | next›

OK. Let's see if I can get state remembered properly in my (fab) game. Last night I got the fab.js backend ready to accept iframe query parameters describing a player. The first order of business tonight is to get the iframe actually sending said query parameters.

Easy enough. Currently the iframe resource is requested on page load:
<iframe src="/comet_view"></iframe>
I switch to a no-src iframe:
<iframe id="iframe"></iframe>
I only assign a src once the player is identified and when I do so I pass query parameter information that the server can use to link the player with the connection:
  if (kv[0] == 'player' && kv[1]) {
// There is a player
$('#login').hide();

var me = new Player(kv[1]);
$('#iframe')[0].src = '/comet_view?player=' + me.id + '&x=' + me.x + '&y=' + me.y;

player_list = new PlayerList(me);
new Room($("#canvas")[0], player_list);
}
To associate both position and connections with players, I convert the player list to a hash:
var players = {};
I then add players in the fab.js backend (taking advantage of the query-params-to-object app that I wrote last night):
function init_comet (app) {
return function () {
var out = this;

return app.call( function listener(obj) {
if (obj && obj.body) {
out({ headers: { "content-type": "text/html" },
body: "<html><body>\n" })

( // other comet connection initialization );

puts("adding: " + obj.body.id);
players[obj.body.id] = {status: obj.body, listener: out};

}
return listener;
});
};
}
With that working, I would like to keep track of players movements. In the /move app, I add:
  ( /move/ )
( function() {
var out = this;
return function listener( obj ) {
if ( !obj ) out();
else if ( obj.body ) {
broadcast(obj.body);
var status = JSON.parse(obj.body);
update_player_status(status);

}
return listener;
};
} )
Right after I broadcast the new position to all clients, I record it in the fab.js backend with update_player_status. Except I don't. My fab.js server crashes when my player moves:
cstrom@whitefall:~/repos/my_fab_game$ node game.js
HTTPParser.onBody (http:92:23)
Stream.ondata (http:524:30)
IOWatcher.callback (net:307:31)
node.js:748:9
That is not too helpful, but I would speculate that the HTTPParse in the stacktrace indicates that my JSON.parse is failing. With the help of print-stderr debugging, I eventually determine that the obj.body is not a string (although it behaves very much like one). This debugging code:
            puts("typeof"+typeof(obj.body));
puts("id: " + obj.body.id);
for (var prop in obj.body) {
puts("["+prop+"] " + obj.body[prop]);
}
...outputs the following:
typeofobject
id: undefined
[0] 123
[1] 34
[2] 105
[3] 100
[4] 34
[5] 58
[6] 34
[7] 98
[8] 111
...
So obj.body is an object. It is an object but not a player object because it does not respond to id. It also looks like an array... of characters. That is odd. Ultimately, I can cast it into a real string by concatenating it with an empty string:
  ( /move/ )
( function() {
var out = this;
return function listener( obj ) {
if ( !obj ) out();
else if ( obj.body ) {
broadcast(obj.body);
var status = JSON.parse("" + obj.body);
update_player_status(status);
}
return listener;
};
} )
That is a good stopping point for today. Tomorrow, I think I may explore raphaël.js a bit to make the room a bit nicer.

Day #103

Thursday, May 13, 2010

Refactoring a fab.js unary into a binary

‹prev | My Chain | next›

I still have a few problems in my (fab) game. When new players join the room, they do not see the existing players and when players quit (by closing the browser), they are not removed from room. To resolve this, I am going to need to add a bit more state into my fab.js backend.

I already retain a list of clients listening to comet broadcasts:
  ( /^\/comet_view/ )
( function() {
listeners.push( this );
this({headers: { "content-type": "text/html"},
body: "<html><body>\n"});

// Some padding to get Chrome initialized
} )
Unfortunately, I do not associate those listeners with players (so I can remove them from the player list) or collect the initial locations of those players.

Since comet is being served over an iframe, the request needs to be an HTTP GET. This means that the web client cannot send data in the request body. Thus I am stuck sending any player information in query parameters. To capture that information, I build a unary (fab) app:
function player_from_querystring() {
var out = this;
return function(head) {
if (head.url.search) {
var search = head.url.search.substring(1);
var q = require('querystring').parse(search);
var app = out({ body: {id: q.id, x: q.x || 0, y: q.y || 0} });
if ( app ) app();
}
else {
out();
}
};
}
This is a quick adaptation of some query string parsing I did when I was first learning fab.js.

Since this is fab.js and I have collected this in a unary app (upstream / farthest from the web client), I need to convert my comet function to middleware (or a binary app in fab.js speak). I am getting pretty good at doing this now. I just need to wrap the comet (fab) app above with a function that takes a single argument—the upstream app, player_from_query_string. To make the flow a bit clearer, I break the comet view into a named function:
function init_comet (app) {
return function () {
var out = this;

return app.call( function listener(obj) {
if (obj && obj.body) {
players.push(out);
out({ headers: { "content-type": "text/html" },
body: "<html><body>\n" })
// More code here to initialize comet in Chrome
}
return listener;
});
};
}
With that, the main flow of my (fab) game becomes quite readable:
  ( /^\/comet_view/ )
( init_comet )
( player_from_querystring )
At this point, I have changed no functionality in the game. Everything still responds like it did before—bugs and all. But tomorrow, I will be able to user the obj.body in comet_view(), which is being built from the iframe's query string in player_from_querystring, to build a list of players, their positions in the room and the associated clients.

(commit)

Day #102

Wednesday, May 12, 2010

Broadcast Comet

‹prev | My Chain | next›

Picking back up with my (fab) game, I need to figure out why it is not broadcasting movements. To be precise, some movements are being broadcast by fab.js, but not all of these broadcasts are reaching the iframe serving up the comet.

To illustrate, only one of these windows sees the movement of the other:



If this were working, both browsers would be able to see movement in the other (and all attached clients). My guess is that my fab.js code is only broadcasting to one client. To verify this, I leave my clients connected, then fire up curl:
cstrom@whitefall:~/repos/my_fab_game$ curl http://localhost:4011/comet_view

<script type="text/javascript">
var attrs = {"id":"Bob","x":386,"y":108};
window.parent.player_list.add_player(attrs);
var player = window.parent.player_list.get_player(attrs.id);if (typeof(player) != 'undefined') {
player.stop();
player.walk_to(attrs.x, attrs.y);
}</script>

<script type="text/javascript">
var attrs = {"id":"fred","x":358,"y":71};
window.parent.player_list.add_player(attrs);
var player = window.parent.player_list.get_player(attrs.id);if (typeof(player) != 'undefined') {
player.stop();
player.walk_to(attrs.x, attrs.y);
}</script>

<script type="text/javascript">
var attrs = {"id":"Bob","x":205,"y":63};
window.parent.player_list.add_player(attrs);
var player = window.parent.player_list.get_player(attrs.id);if (typeof(player) != 'undefined') {
player.stop();
player.walk_to(attrs.x, attrs.y);
}</script>
Weird. It is broadcasting. Even if I open up a second curl session, I still see the broadcast output. So why does it not reach the browser?

Although I am not exactly sure why, it turns out this works if two different hostnames are used (even if both refer to localhost):



So it worked all along! I am not going to concern myself with the vagaries of comet and single host broadcasting at this point. Instead, I take some time to reduce that broadcast payload to this:
<script type="text/javascript">
window.parent.player_list.walk_player({"id":"bob","x":101,"y":168});
</script>
I can do that by defining the walk_player method on PlayerList:
PlayerList.prototype.walk_player = function(attrs) {
this.add_player(attrs);
var player = this.get_player(attrs.id);
if (player) {
player.stop();
player.walk_to(attrs.x, attrs.y);
}
};
I clean up a few more minor things and call it a night. I still want to get to testing and raphaël, but first I think I'd like to improve state in my fab.js backend a bit. Specifically, I would like to remember everyone's position so that new players see old ones right away (currently pre-existing players would need to move first). It would also be good to remove players once the comet session ends. I will get started on that tomorrow.

Day #101

Tuesday, May 11, 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

  • Implemented a static file server in fab.js. It was easy! Yeah, yeah, it's easy to implement a static file server in any language, but it was fun with fab.js.
  • Got my (fab) game into a proper github repository. Try it!
  • Not really proper chain work, but I got a patch accepted into fab.js and accepted a patch to couch_docs. Hard-core forking action going on here!
  • Figured out how to include libraries (like fab.js) in node.js. Bottom line: use ~/.node_libraries.
  • Fixed a bug in my <canvas> watching code.
  • Made my room event handler browser independent (well at least in Chrome and Firefox).
  • Got initial support for multi-user rooms in place.

OBSTACLES / THINGS THAT WENT NOT SO WELL

  • Troubleshooting comet broadcast messages is brutal.
  • Lack of tests are really starting to hamper development.

WHAT I'LL TRY NEXT WEEK

  • I WILL test this week! A helpful reader commented with some pointers when I lamented my lack of fab.js testing last retrospective. This week, I will do something about it.
  • I might have a look at raphael.js to ease some of my <canvas> development.
  • Start winding up my fab.js / <canvas> experiment. I would like to hand something off to my kids that exposes something of an API for them to code animations and collision detection.


Day #100

Monday, May 10, 2010

Bad Javascript

‹prev | My Chain | next›

Now that I have my PlayerList object in each browser that encapsulates access to the list of players other than me, I need to user that in the fab.js/comet code that drives players. In the function that broadcasts to all listeners, I access the player being moved in the window's parent (this is comet rendered in an iframe):
function broadcast(obj) {
listeners.forEach(
function(listener) {
var body = '<script type="text/javascript">' + "\nif (console) console.debug('" + obj.body + "')\n</script>\n";
listener({body: body});

body = '<script type="text/javascript">' + "\n" +
"var attrs = " + obj.body + ";\n" +
"window.parent.player_list.add_player(attrs);\n" +
"var player = window.parent.player_list.get_player(attrs.id);" +
"if (typeof(player) != 'undefined') {\n" +
" player.walk_to(attrs.x, attrs.y);\n" +
"}" +
"</script>\n";
listener({body: body});
}
);
}
The add_player method is silently ignored if the player is already a member of the room (or is me):
PlayerList.prototype.add_player = function(obj) {
if (!this.other_players[obj.id] && obj.id != this.me.id) {
if (console) {console.debug("adding:" + obj.id);}
this.other_players[obj.id] = new Player(obj.id, obj);
}
};
The walk_to method is already a working method on Player so I should be good to go. Except I am not.

Sadly, I spend the bulk of my night tracking down a problem that boils down to this: in Javascript, do not give the same name to both a method and a property. By way of example, when I try to obtain the list of other players, this is bad:
PlayerList.prototype.others = function() {
var ret = [];
for (var id in this.others) {
ret.push(this.others[id]);
}
return ret;
};
After renaming the object property to other_players, I eventually get the code mostly working. Mostly, except the fab.js broadcast code is only broadcasting to one client. I will pick up with that next.

Day #99

Sunday, May 9, 2010

Baby Steps on Mother's Day

‹prev | My Chain | next›

It is doubtful that I will make much progress this Mother's day. Nevertheless, even on a special day like this, I want to make some progress and keep my chain unbroken. So here goes...

With my code now well-factored and well-behaved, I want to begin the process of seeing others in the <canvas> room as I move about it. Right now, all of the comet communication from the fab.js server is moving an explicitly referenced character around. If I am to move many named characters around, I need a list of all players with which I can interact. But first, players need to be able to identify themselves. For that, I add a form above the <canvas> element:
 <body>
<form id="login" method="get">
<label>Name
<input type="text" name="player">
</label>
<input type="submit" value="Play">
</form>

<canvas id="canvas" width="500" height="500"></canvas>
</body>
I am not doing anything fancy on the server side to prevent duplicate logins (and I do not even have accounts on the server side). For now, I simply want to identify myself via the form. If I have done so, show the room (and tell the server). If not, show the login form. This bit of jQuery does the trick:
$(function() {
var kv = location.search.substr(1).split(/=/);
if (kv[0] == 'player' && kv[1]) {
$('#login').hide();
new Room($("#canvas")[0], {me:kv[1]});
}
else {
$('#canvas').hide();
}
});
I am actually a bit surprised that jQuery does not make query parameter parsing easier than that (no doubt there is a plugin for that). For my purposes however, splitting the query paramter string (location.search) on the key-value separator (=) is enough. If the play parameter is present, then hide the login form and show the room. Otherwise hide the room and leave the form visible to prompt the user to login.

Now that players can identify themselves, I need a mechanism for fab.js to interact with a list of players on all connected browsers. My first attempt initializes with me (so that the server never tries to move me, only I can move me), but provides an interface for the server access players so that it can inform the client that Player objects have moved:
var PlayerList = function(me) {
this.me = me;
this.others = {};
};

PlayerList.prototype.add_player = function(obj) {
if (!this.others[obj.id] && obj.id != this.me.id) {
this.others[obj.id] = new Player(obj.id, obj);
}
};

PlayerList.prototype.get_player = function(id) {
return this.others[id];
};
With this, I can add others to my board (but I handle me as a special case) and I also provide a mechanism to access each player so that I can inform them that they need to move.

I stop there for tonight. Hopefully tomorrow, I will be able to get other players showing up in my room.

Day #98

Saturday, May 8, 2010

Keeping the Investors Happy with Firefox Support

‹prev | My Chain | next›

Tonight I need to to obtain buy-in from my investors... my kids. Unfortunately, they still use Firefox. I have developed so far on Chrome exclusively. When I tried to show my kids how things are working so far... well, I was a bit embarrassed.

After refactoring a bit, I get to the point that can fix things for Firefox. The view-only version works (the right window below):



The problem only shows up when I try to control the the game from Firefox. So the problem is not with the <canvas> rendering, rather with the handling of the mouse events. Happily, I still have console.debug output that Firebug picks up:
x_diff: NaN, y_diffNaN, angle: NaN        player.js (line 32)
Tracing that back, I find the source of the trouble is in the event handling of my Player:
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;
}
};
The trouble in there is the use of offsetX/offsetY, which varies between browser implementations. jQuery normalizes the location of events on the page in event.pageX and event.pageY. That is not quite what I need. Instead what I want is the coordinate of the event inside my <canvas> room.

To get that, I need the offset() of the <canvas> element relative to the page. If that is offset 8 pixels from the top and 8 pixels from the side of the page, then I can subtract 8 pixels from the event's pageX and pageY to get the <canvas> coordinate.

My worry here is that I do not want to couple the Player and the Room more than necessary. If possible, I want to notify the Player of an event such that the Player need only pull the x-y coordinate from the event in order to act. Given that reasoning, it sounds as if the best place to put this is in the Room:
Room.prototype.decorate_event = function(evt) {
return {
type: evt.type,
x: evt.pageX - $(this.canvas).offset().left,
y: evt.pageY - $(this.canvas).offset().top
};
};
I can then pass that "decorated" event to the Player, who is a subscriber to events on the <canvas> board:
Room.prototype.init_events = function() {
var self = this;
$(this.canvas).click(function(evt) {
var decorated_event = self.decorate_event(evt);
self.subscribers.forEach(
function(subscriber) { subscriber.notify(decorated_event); }
);
});
};
After updating Player to get the x-y coordinate from event.x and event.y, I have the code working in Firefox and Chrome. Hopefully my investors will be pleased.

Day #97