<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>O! Mr Speaker!</title>
	<atom:link href="http://www.mrspeaker.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.mrspeaker.net</link>
	<description>Javascript flâneur, internet flibbertygibbert</description>
	<lastBuildDate>Thu, 12 Apr 2012 11:04:45 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Caine&#8217;s Arcade Fun Pass Generator</title>
		<link>http://www.mrspeaker.net/2012/04/12/fun-pass-generator/</link>
		<comments>http://www.mrspeaker.net/2012/04/12/fun-pass-generator/#comments</comments>
		<pubDate>Thu, 12 Apr 2012 10:56:27 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[Wide world]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=3348</guid>
		<description><![CDATA[Caine's Arcade is the coolest arcade ever (even better than Flynn's Arcade and Bailey's Arcade. The "pros" of Caine's Arcade are that all the games are hand-built by a 9 year old, out of cardboard. But the "cons" are the prices: $1 gets you 4 plays, and $2 gets you a "Fun Pass" (tm) valid [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://cainesarcade.com/">Caine's Arcade</a> is the coolest arcade ever (even better than <a href="http://tron.wikia.com/wiki/Flynn%27s_Arcade">Flynn's Arcade</a> <em>and</em> <a href="http://en.wikipedia.org/wiki/Joysticks_(film)">Bailey's Arcade</a>. The "pros" of Caine's Arcade are that all the games are hand-built by a 9 year old, out of cardboard. But the "cons" are the prices: $1 gets you 4 plays, and $2 gets you a "Fun Pass" (tm) valid for 500 plays.</p>
<p>2 bucks! Phew... You might be thinking you could get around that by making a fake pass of your own - but Caine is way ahead of you. He's added a security check to each Fun Pass, to validate that it's the real deal:<br />
<span id="more-3348"></span><br />
<image src="/images/security-check.jpg" alt="Fun pass secure hash" class="frame-left" style="margin-bottom:15px" /></p>
<p>However, a after careful reverse-engineering effort, I've cracked the security code and made this <strong>"Caine's Arcade Fun Pass Generator"</strong>:</p>
<div id="funpass">
<div id="cut-here">&#9985;</div>
<div class="side" id="front">
        <span>$2.00</span><br />
        <span class="center-it">Fun Pass</span><br />
        <span class="right-it">500 Plays</span>
    </div>
<div class="side center-it" id="back">
        <span><br />
<input id="fp_id" placeholder="Fun Pass ID"/></span><br />
        <span>&nbsp;</span><br />
        <span><br />
<input id="security_number" placeholder="Security #" /></span>
    </div>
</div>
<p><img src="/images/security-analysis.jpg" alt="security recon." class="frame-right"/>Just put in a pass ID, print it out, and you're good to go! I have verified the accuracy of the passes by carefully studying frame-by-frame evidence from the video above - so I'm confident the passes will get around the security checks: But if you get busted using a fake pass, don't come crying to me.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2012/04/12/fun-pass-generator/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Syntax highlighting for writers</title>
		<link>http://www.mrspeaker.net/2012/03/24/syntax-highlighting-for-writers/</link>
		<comments>http://www.mrspeaker.net/2012/03/24/syntax-highlighting-for-writers/#comments</comments>
		<pubDate>Fri, 23 Mar 2012 16:27:56 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[Wide world]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=3334</guid>
		<description><![CDATA[Ok, This was a "here's an old project I've abandoned" type post, but after some interest in the matter I'm re-opening this for questions... Syntax highlighting for writers: what do you think? Yay, or nay? When you have a brilliant idea for a start-up, you mock up a prototype and show your intended audience. They'll [...]]]></description>
			<content:encoded><![CDATA[<p class="note">Ok, This was a "here's an old project I've abandoned" type post, but after some interest in the matter I'm re-opening this for questions... <a href="http://www.mrspeaker.net/2012/03/24/syntax-highlighting-for-writers/">Syntax highlighting for writers</a>: what do you think? <strong>Yay, or nay?</strong></p>
<p><img src="/images/syntx-austin.png" class="frame-right" alt="example of english-language syntax highlighting" />When you have a brilliant idea for a start-up, you mock up a prototype and show your intended audience. They'll be over the moon with excitement, and start paying for your service <em>immediately</em>. Word of mouth will grow, and before you know it you'll have a million users and you'll have so much money that you might become a tiny bit happier.</p>
<p>That's how it's supposed to go. Here's a project I started that fell down in the "prototype user-testing phase", documented here for prosperity. It's an english language syntax highlighter for writers of prose (and the sort). Here's the demo (select a colour-theme from the dropdown menu and imagine it's you typing, instead of robo-Jane Austin):</p>
<p><a href="http://www.mrspeaker.net/dev/syntx/">Syntax highlighting for writers</a></p>
<p><span id="more-3334"></span>"What are those colours?" You might be wondering (especially if you didn't pay much attention to english class when you were a kid, as I didn't). Why, apparently those - those are "nouns", and "adjectives", and "verbs", and "pronouns" and such. Yes, finally the tedium of plain text is broken! Such joy it will bring to bored novellists everywhere. Had Jane Austin access to syntax highlighting, she would have written like, 10 books. No doubt!</p>
<p>The system works by performing a natural-language analysis on sentences as they are typed by the user. Words are marked up with their type and colourised accordingly.</p>
<p>At least, that was the idea. But I asked a handful of writers what they thought of it, and they all said it was bloody stupid. I unleashed a string of colourful adjectives at them, but they failed to change their opinion. Ah well.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2012/03/24/syntax-highlighting-for-writers/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Typesafe Console: behind the scenes</title>
		<link>http://www.mrspeaker.net/2012/03/15/typesafe-console/</link>
		<comments>http://www.mrspeaker.net/2012/03/15/typesafe-console/#comments</comments>
		<pubDate>Thu, 15 Mar 2012 11:57:21 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[Nerd]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=3220</guid>
		<description><![CDATA[Scala, Play 2.0, CoffeeScript, real-time streams, server-sent events, (lots of) HTML5 canvas, local storage, push state, easter egg, ... If you've worked in IT for long enough, you make sure you get yourself in a position where you no longer have to work on dull projects. It's hard (dull projects are often very lucrative - [...]]]></description>
			<content:encoded><![CDATA[<p>Scala, Play 2.0, CoffeeScript, real-time streams, <span style="font-size:0.9em">server-sent events,</span> <span style="font-size:0.8em">(lots of) HTML5 canvas,</span> <span style="font-size:0.7em">local storage,</span> <span style="font-size:0.6em">push state,</span> <span style="font-size:3pt">easter egg,</span> <span style="font-size:0.4em">...</span></p>
<p><a href="http://console-demo.typesafe.com"><img src="/images/console.png" alt="the Typesafe Console" /></a></p>
<p>If you've worked in IT for long enough, you make sure you get yourself in a position where you no longer have to work on dull projects. It's hard (dull projects are often very lucrative - either for you or your boss) - but once you've ditched the boring projects there's no turning back.</p>
<p>With dull projects out of the picture you get to spend your days tinkering on good projects, or if you're lucky - interesting projects. However. Every once in a long while you have the rare opportunity to be involved in the developer's holy grail: Super-Good Interesting projects. And the <a href="http://console-demo.typesafe.com">recently-released Typesafe Console</a> was one of those Super-Good Interesting projects. Here's the story...<br />
<span id="more-3220"></span></p>
<p class="note" style="line-height:10px">
<a href="#story">The Story</a><br/><br />
<a href="#coffee">CoffeeScript: right or wrong?</a><br/><br />
<a href="#sse">Server-Sent Events and Comet</a><br/><br />
<a href="#canvas">Canvas vs SVG vs DOM</a><br/><br />
<a href="#html5">All things HTML5</a><br/><br />
<a href="#live">Pushin' it live</a><br/><br />
<a href="#third">(friends don't let friends use) Third-party libraries</a>.
</p>
<h3><a name="story"></a>The Story</h3>
<p>The <a href="http://typesafe.com/">chaps at Typesafe</a> were looking to create a front end to their impressively powerful <a href="http://akka.io/">Akka actors</a> monitoring system (via their exposed API). The idea was to create a visual tool for learning about Akka, for monitoring systems, and for looking really really cool. The release of the <a href="http://www.playframework.org/">Play 2.0 framework</a> - with all it's Scala-ry goodness - was imminent, and thanks to it's <a href="http://www.playframework.org/documentation/2.0/Iteratees">Iteratee-based IO architecture</a> was a perfect tool for the job.</p>
<p><a href="http://twitter.com/iamwarry">Maxime</a>, Zenexity's <em>Senior Head of Inventing Futuristic Stuff</em> developed the underlying concepts of the system (which I think I managed to not destroy completely) and <a href="http://twitter.com/Noxdzine">Anthony</a>, Zenexity's <em>Chief Officer of Making Stuff Look Funky</em> took the concepts and ran with them all the way to the <a href="http://www.youtube.com/watch?v=dp7dBbaZUIk">gaming grid</a>.</p>
<p><a href="http://www.zenexity.com" title="Zenexity"><img src="/images/zenexity-hack.jpg" alt="Some of the Zenexity fellows, en train de hackday" class="frame-left" /></a></p>
<div style="text-align:right;font-size:9pt;padding-right:15px">Some of the Zenexity crew, hard at work.</div>
<p>Next, we had to make things actually work. Which meant making the tough decisions: CoffeeScript, or JavaScript?</p>
<h3><a name="coffee"></a>CoffeeScript: right or wrong?</h3>
<p>I chose to go with <a href="http://coffeescript.org">CoffeeScript</a> for everything. I like CoffeeScript, but I love JavaScript - so I spent much time weighing up the pros and cons.</p>
<p>The Pros: there is built-in support for CoffeeScript in Play 2.0, and writing CoffeeScript is damn fun. The syntax is nice (heck, it had me at "short function syntax with implicit returns"), and there are a bunch of useful destructuring features. It has a super-simple classical inheritance component, and you can write <code>data?.node?.maxThreadCount</code> to soak up nulls - plus a whole bunch more.</p>
<p>The Cons: it's picky about whitespace, without being strict (many-a-times you need to check the compiled source to see if you need to add or remove a tab - especially when chaining methods, doing anonymous functions with callbacks, or reduce functions), it's a transpiled language so you either trust that the compiled source is efficient enough for updating a zillion graphs 60 times a second or you fully understand what it's doing so don't really need it anyway, and many of its cool features are being rolled into <a href="http://wiki.ecmascript.org/doku.php?id=harmony:proposals">JS.Next</a> (<a href="http://wiki.ecmascript.org/doku.php?id=strawman:strawman">hopefully many</a>) - so 5 years down the track developers will be depressed when they have to maintain a weird old language: and good luck hunting down the correct version of the compiler (note to self: package correct version of the compiler in the repo).</p>
<p>Buuut, in the end I gave the thumbs up to CoffeeScript. Did I mention it's fun?</p>
<h3><a name="sse"></a>Server-Sent Events and Comet</h3>
<p>With the core front-end language decided on it was time to look at how to talk to the back end. The initial "lets just get something up and running" version used long polling to call the server, which proxied the request through to the Akka service. This was obviously not going to cut it: it's so, old school... so it was time to get serious.</p>
<p><a href="http://www.twitter.com/erwan">Erwan</a> had recently made a <a href="https://github.com/playframework/Play20/blob/master/samples/workinprogress/twitterstream/app/controllers/Application.scala">cool sample Play app</a> that consumed Twitter's real-time stream and composed it with a <a href="http://en.wikipedia.org/wiki/Comet_(programming)">comet stream</a> output (using the <code>><></code> "poisson" (fish) operator!) and displayed them at a crazy rate - like, 1000 tweets a second for very common search terms.</p>
<p><a href="http://www.twitter.com/sebcreme">Sébastien</a> had ported our Play 1.2 app over to Play 2.0 - so Bridging the Akka API with composable streams via iteratees and enumeratees made perfect sense for the application. It meant we could specify, say, a stream of nodes and compose them with a stream of system information. When the user clicks on a navigation item, we just change streams. If we want to display more panels, we can just compose more streams: it can be as modular as we need.</p>
<p>The only potential issue was that when there were a number of users all looking at the same thing (such as the default view) then separate streams would be generated, which means separate calls to the Akka API, which would be extremely wasteful. Thankfully <a href="http://www.twitter.com/sadache">Sadek Drobi</a>, co-genius behind the core architecture of Play, came up with a cool solution of "hubbed iteratees" which allowed receivers to be plugged into existing streams. This greatly reduced the number of API calls needed and had the added bonus giving us synchronized views when looking at the same streams (minus network latency).</p>
<p>The comet streaming was working like a charm - but we were a bit uneasy about basing everything off comet. It's really a hack - and so it was time to convert things over to the non-hack equivalent: <a href="http://dev.w3.org/html5/eventsource/">Server-Sent Events</a>. It's <em>really</em> just paving the comet cowpath - we added 5 lines of code, an additional conditional check in the JavaScript, et voila: Server-Sent Events with comet fallback.</p>
<h3><a name="canvas"></a>Canvas vs SVG vs DOM</h3>
<p><img src="/images/console-graph.png" alt="a fancy graph" class="frame-right" style="border:0" />From the outset we wanted some wacky graphs (like the <em>node</em> and the <em>dispatcher</em> visualisations) so you could quickly grok how your system was doing. Using a pre-existing library wasn't really an option - especially when we weren't certain about how we wanted to render: canvas, SVG, or plain-ol' DOM elements with CSS transitions.</p>
<p>All were trialled (SVG was using <a href="http://raphaeljs.com/">Raphaël</a>, naturally). Canvas came out the winner thanks to it's flexibility to paint whatever we wanted easily (over the course of the project the graphs changed entirely, many times!) and performance in modern browsers was acceptable.</p>
<p>Aside from some mouseover information and a couple of clickable areas, there is not a lot of user interaction with the graph elements - if this was required then SVG (or DOM) probably would have won out.</p>
<p>Once we'd figured out and mocked up a bunch of graphs, <a href="http://www.twitter.com/greweb">@greweb</a> carved everything up into a flexible, reusable charting component library - using multiple canvas layers per graph, and a cool contraints system for putting everything together. All graphs were then assembled out of the components.</p>
<h3><a name="html5"></a>All things HTML5</h3>
<p>Along the way a whole host of incidental "HTML5 et al." technologies got dragged into the mix: the <a href="https://developer.mozilla.org/en/DOM/window.requestAnimationFrame">requestAnimationFrame</a> for animating (note: don't ignore the second parameter to the call - it's the element that you want to animate, and specifying it speeds things up a lot), <a href="https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history">push state</a> for managing history, <a href="https://developer.mozilla.org/en/DOM/Storage">local storage</a> for temporary caching of graph data (so things reload quickly if you're navigating around), the <a href="http://dev.w3.org/html5/eventsource/">Event Source object</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/Reduce">map/reduce and friends</a> other goodies from JavaScript 1.8... I tell you, it's good times to be a developer.</p>
<h3><a name="live"></a>Pushin' it live</h3>
<p>Although everything was ticking along nicely on our local versions - we also needed to provide a demo app that would be publicly accessible. By the public. All of them. Which is a very different use-case than the console's primary purpose - which is to monitor a system by, maybe, a handful of sys-admins/developers at a time.</p>
<p><img src="/images/console-play.jpg" class="frame-left" />Sadek's hubbed iteratee solution scaled beautifully (*cough* in theory, and simulated load tests *cough*) - but there was one potential bottleneck (that kept me awake at night for a few days before the release)... bandwidth. The console is all about pushing <em>tonnes</em> of real-time data into your browser. And tonnes of data, multiplied by every second, multiplied by thousands of simultaneous users, equals a. lot. of. bandwidth.</p>
<p>Thankfully, I was not in charge of making sure thing worked in the real world. Our resident Head of Making Things Stay Online - Jean-François - was. He set up a small cluster of cloudy machines, with the ability to bring new machines online in 5 minutes, if necessary.</p>
<p>When things went live, I sat there cautiously checking if things were still running. Jean-François didn't bat an eyelid. I was nervous that the untested-under-heavy-load-in-the-field streams would fall over as the hundreds of connections became thousands - and we'd need to bring a whole bunch of (expensive) machines up. After a few hours the bandwidth really started exploding and each reload of the page would give me mild heart-attacks... I asked Jean-François if he thought we'd be okay. He calmed me down by replying:</p>
<blockquote><p>It looks like we deployed a network of military satellites to make a sub-orbital nuke against a pigeon.</p></blockquote>
<p>He's a professional.</p>
<h3><a name="third"></a><span style="font-size:7pt">(friends don't let friends use)</span> Third-party libraries</h3>
<p>After things settled down, we could step back and do a bit of a post-mortem. Looking at the package we realised that we were including just two third-party libraries: <a href="http://jquery.com/">jQuery</a> for DOM manipulation (yeah, it's becoming less essential over time, but it's still so convenient), and <a href="http://fgnass.github.com/spin.js/">Spin.js</a> to add a lil' spinner when things are loading... and that's all. We didn't need an MVC-esque library (streams are dispatched via a simple message dispatcher - anything more would have been overkill), and CoffeeScript gave us a basic class implementation, which was all we needed.</p>
<p>We had the rare benefit of only having to target modern browsers - and when this is the case then piling on libraries isn't necessary: the core (CSS/JS), HTML5, and related technologies underneath them are already awesome, easy to use, and really, really, really fun to develop with. With the emergence of highly scalable, reactive server-side technologies like Akka and Play 2.0 - combined with the cool features that are filtering into browsers all over the globe - I personally am pretty excited to see what revolutionary stuff people come up with in the next few years.</p>
<p>And I'm going to do my best to make sure I'm working on them, too.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2012/03/15/typesafe-console/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Weird EventSource problems? Watch your content-length!</title>
		<link>http://www.mrspeaker.net/2012/03/09/eventsource-problems/</link>
		<comments>http://www.mrspeaker.net/2012/03/09/eventsource-problems/#comments</comments>
		<pubDate>Thu, 08 Mar 2012 14:13:35 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[HTML5]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=3216</guid>
		<description><![CDATA[Super short version: If you're using Server Sent Events, and it doesn't work in Firefox because "Firefox can't establish a connection to the server at..." and it's not a CORS problem... make sure you're not setting a content-length header. The end. Longer version: A (very cool) project I'm working on at the moment uses Server [...]]]></description>
			<content:encoded><![CDATA[<p>Super short version: If you're using <a href="http://dev.w3.org/html5/eventsource/">Server Sent Events</a>, and it doesn't work in Firefox because "Firefox can't establish a connection to the server at..." <em>and</em> it's not a CORS problem... make sure you're not setting a content-length header. The end.</p>
<p><span id="more-3216"></span>Longer version: A (very cool) project I'm working on at the moment uses Server Sent Events to push real-time monitoring data. If the EventSource object is not found in the browser, or there's a problem connecting, then it will fall back to comet.</p>
<p>Firefox was falling back to comet - even though it happily supports Server Sent Events. The only information I could find about this was "it's a cross domain issue". Which lead me on a long journey of blaming my reverse proxy, and other obviously incorrect theories.</p>
<p>After implementing a "hello, world" version which worked - and doing some header inspections showed that the server was adding a "CONTENT-LENGTH: -1" header - which Firefox certainly doesn't like. Removing or setting a positive value for the length, and all was happy. Though removing it is of course the correct answer: if you set a value for it then the connection is closed after the content length value is reached, and the browser re-connects.</p>
<p>The end.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2012/03/09/eventsource-problems/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>You can skip this ad in 0:02</title>
		<link>http://www.mrspeaker.net/2012/03/03/you-can-skip-this-ad-in-002/</link>
		<comments>http://www.mrspeaker.net/2012/03/03/you-can-skip-this-ad-in-002/#comments</comments>
		<pubDate>Sat, 03 Mar 2012 00:28:44 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[Wide world]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/2012/03/03/you-can-skip-this-ad-in-002/</guid>
		<description><![CDATA[Yeah, I can skip it MUCH faster than that.]]></description>
			<content:encoded><![CDATA[<p>Yeah, I can skip it MUCH faster than that.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2012/03/03/you-can-skip-this-ad-in-002/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Colourising sprites in Canvas – part 2</title>
		<link>http://www.mrspeaker.net/2012/02/02/colorising-sprites-2/</link>
		<comments>http://www.mrspeaker.net/2012/02/02/colorising-sprites-2/#comments</comments>
		<pubDate>Thu, 02 Feb 2012 10:21:16 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[HTML5]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=3162</guid>
		<description><![CDATA[And we're back! In part one we looked at setting up a tinted palette for drawing our 8-bit masterpieces to canvas. Here's what we're going for today: rendering colourised sprites and tiles. We'll be loading in our (ok, Notch's) 4-color sprite sheet and rendering tiles from it with our chosen colours. We need the InitPalette [...]]]></description>
			<content:encoded><![CDATA[<p><img src="/images/minicraft-sprites.png" class="frame-right" alt="colourised sprites" />And we're back! In <a href="http://www.mrspeaker.net/2011/12/30/colorising-sprites-1/">part one</a> we looked at setting up a tinted palette for drawing our 8-bit masterpieces to canvas. Here's what we're going for today: <a href="/dev/spritecol/p5-go.html">rendering colourised sprites and tiles</a>. We'll be loading in our (ok, Notch's) 4-color sprite sheet and rendering tiles from it with our chosen colours.</p>
<p><span id="more-3162"></span>We need the <code>InitPalette</code> and <code>GetColour</code> functions from last time, though the <code>InitPalette</code> function will now store the 216 colours as JavaScript objects (with r, g, and b components) rather than Notch's encoded version:</p>
<p><code>
<pre>
// Before:
colours.push(r1 << 16 | g1 << 8 | b1);

// After:
colours.push({
  r: r1,
  g: g1,
  b: b1
});
</pre>
<p></code></p>
<p>This saves us from having to decode the value before we use it - which is much more practical in JavaScript, because the canvas image data is stored as separate rgba values by default.</p>
<p>On with the new stuff. First up is to make sure we can draw pixels to our canvas element. The process goes like this...</p>
<ol>
<li>Get the canvas's image data with the <code>createImageData</code> function.</li>
<li>Manipulate the bits of the data as we desire</li>
<li>Replace the canvas data using the <code>putImageData</code> function</li>
<li>Repeat from step 2</li>
</ol>
<p class="note">All the JavaScript you see is "inline" for simplicity. All functions are global (and for some reason I uppercased the function names - I sometimes go a bit weird when writing tutorials). A lot of arrays are passed by reference... It's for demonstration purposes only! Namespace things, mix'em in, plaster some classical OOP on them, make them into endo-functing monads... REMEMBER: This isn't production code, it was just me dissecting and porting Notch's Minicraft effort!</p>
<h3>Drawing pixels with canvas</h3>
<p>Right, first we grab the canvas context and keep a reference to the image data. We'll also populate our palette, ready for using.</p>
<p><code>
<pre>&lt;canvas id="board" width="160" height="120"&gt;&lt;/canvas&gt;
...
var ctx = document.getElementById("board").getContext("2d"),
    output = ctx.createImageData(ctx.canvas.width, ctx.canvas.height),
    colours = [];

// Set up our palette
InitPalette(colours);
</pre>
<p></code></p>
<p>Then we run a loop where we pick a random colour index (from the 216 we generated) and put it in each pixel. The canvas data is stored 4 bytes per pixel (rgba) and we put 256 for alpha (opaque).</p>
<p><code>
<pre>
(function run() {
  for (var y = 0; y < ctx.canvas.height; y++) {
    for (var x = 0; x < ctx.canvas.width; x++) {

      // Pick a random palette colour
      var cc = ~~(Math.random() * 216),
          xo = x * 4,
          yo = y * ctx.canvas.width * 4,
          col = colours[cc];

      // Replace the canvas image pixel
      output.data[xo + yo] = col.r;
      output.data[xo + yo + 1] = col.g;
      output.data[xo + yo + 2] = col.b;
      output.data[xo + yo + 3] = 256;
    }
  }

  // Draw it
  ctx.putImageData(output, 0, 0);
  setTimeout(run, 50);
})();</pre>
<p></code>Alright! We have <a href="/dev/spritecol/p1-static.html">some palatte-ized noise</a> on the screen.</p>
<p><img src="/images/pal-static.png" alt="some noise" style="padding-left: 55px"/></p>
<h3>Loading an image</h3>
<p>Next, we need to load in the <a href="/dev/spritecol/sheet.png">grey-scale graphic file</a> (which is the spritesheet from Minicraft). To load an image as canvas data, we'll create a regular ol' JavaScript image then "paint" it onto a canvas element. Then extract the data from the canvas element and discard the JavaScript image and the canvas element. We just want the datas.</p>
<p><code>
<pre>
function LoadSpriteSheet(filename, callback) {
  var img = new Image(),
      pixels = [];
  img.onload = function() {
    var can = document.createElement("canvas"),
        ctx = can.getContext("2d");
    can.setAttribute("width", img.width);
    can.setAttribute("height", img.height);
    ctx.drawImage(img, 0, 0);

    var data = ctx.getImageData(0, 0, img.width, img.height).data;

    // The important bit!
    for(var i = 0; i < data.length; i += 4) {
      pixels.push(~~(data[i] / 64));
    };

    // Send it back
    callback &#038;& callback({
      width: img.width,
      height: img.height,
      pixels: pixels
    });
  }
  img.src = filename;
}
</pre>
<p></code>
<p class="note">If you're playing along at home, remember you need to have a web server running to load the image (you can't run this sample from a <code>file:///</code> url) otherwise you'll get a cross-domain error when trying to manipulate the canvas data.</p>
<p>There's one weird bit in there that is specifically for our colourising code: first, because we only care about greyscale for now - we only look at every 4th byte in the data (because if it's greyscale then r=g=b). And second, every byte that we keep we first <em>divide by 64</em>.</p>
<p>WTF?! Ok, it's a Notch-ism... When he was creating the graphics in his graphics editor, he carefully chose 4 rgb colour values that when divided by 64 (and floored) would return either 0, 1, 2, or 3! That's a handy index for us to work with in code, but at the same time - a decent scale to work in in photoshop.</p>
<p>What we end up with then, is an array sized <code>width * height</code> of integers from 0 to 3. To actually load an image with this function we pass the path and a callback function (because the image load is asynchronous).</p>
<p><code>
<pre>
var spritesheet = null;
LoadSpriteSheet("sheet.png", function(sheet) {
  spritesheet = sheet;
  run();
});
</pre>
<p></code></p>
<p>We then call our <code>run</code> function. For this demo we will blit the spritesheet directly to the output canvas image - this code is almost identical to the "random static" code - except instead of a random colour index, we read the integers from the spritesheet. Because this will only give us a colour from 0 to 3 (which would be from black to very very dark someother colour) we multiply it by, say, 10 - and get the colour from the palette.</p>
<p><code>
<pre>function run() {
  for (var y = 0; y < ctx.canvas.height; y++) {
    for (var x = 0; x < ctx.canvas.width; x++) {
      var cc = spritesheet.pixels[x + (y * spritesheet.width)],
          xo = x * 4,
          yo = y * ctx.canvas.width * 4,
          col = colours[cc * 10]; // make it brighter!

      output.data[xo + yo] = col.r;
      output.data[xo + yo + 1] = col.g;
      output.data[xo + yo + 2] = col.b;
      output.data[xo + yo + 3] = 256;
    }
  }
  ctx.putImageData(output, 0, 0);
  setTimeout(run, 50);
};
</pre>
<p></code><br />
What you see now is <a href="/dev/spritecol/p2-loadsheet.html">a strangely colourised version</a> of part of the spritesheet. We're getting closer!</p>
<h3>A kind of double-buffer</h3>
<p>Right, in the next step we'll create an extra array, the same size as the screen, that will represent... the screen. It will hold screen size, the spritesheet, and the pixels to eventually render. All the sprite rendering we will do to this array, and then at the end copy it to the output canvas element.</p>
<p><code>
<pre>buffer = {
  width: ctx.canvas.width,
  height: ctx.canvas.height,
  sheet: null,
  pixels: []
},</pre>
<p></code></p>
<p>When the spritesheet is loaded, it is stored in the buffer too (instead of the global variable we made last time). To render the buffer to the output canvas we do exactly the same as before - but pass in the arrays to copy from and too.</p>
<p><code>
<pre>function render(buffer, pixels) {
  for (var y = 0; y < buffer.height; y++) {
    for (var x = 0; x < buffer.width; x++) {
      var cc = buffer.pixels[x + (y * buffer.width)],
          xo = x * 4,
          yo = y * buffer.width * 4,
          col = colours[cc];

      if(!col) continue; // Make sure it's defined
      pixels.data[xo + yo] = col.r;
      pixels.data[xo + yo + 1] = col.g;
      pixels.data[xo + yo + 2] = col.b;
      pixels.data[xo + yo + 3] = 256;
    }
  }
}</pre>
<p></code>Now we can re-create our original static - but utilising the buffer:</p>
<p><code>
<pre>for (var y = 0; y < buffer.height; y++) {
  for (var x = 0; x < buffer.width; x++) {
    buffer.pixels[x + y * buffer.width] = ~~(Math.random() * 216);
  }
}

// Transfer screen to output buffer
render(buffer, output);
ctx.putImageData(output, 0, 0);
</pre>
<p></code></p>
<p>A small step backwards - but now we're <a href="http://www.mrspeaker.net/dev/spritecol/p3-buffer.html">rendering noise</a> with our back buffer.</p>
<h3>Plotting some sprites</h3>
<p><img src="/images/minitools.png" alt="minicraft tools" class="frame-left" />With our buffer in hand, we can now do some real work! Anything we put into the buffer will end up on the screen - so now we can copy pieces of the spritesheet data straight into the buffer array. We'll make a <code>renderTile</code> function that copies an 8 by 8 pixel rectangle from spritesheet to a given x and y location. This code is ported pretty much directly from Notch's <code>screen.render</code> function.</p>
<p><code>
<pre>
function renderTile(buffer, xp, yp, tile, colors) {
  var xTile = tile % 32,
      yTile = ~~(tile / 32),
      toffs = xTile * 8 + yTile * 8 * buffer.sheet.width;

  for(var y = 0; y < 8; y++) {
    if (y + yp < 0 || y + yp >= buffer.height) continue; // make sure the pixel is on screen.
    for(var x = 0; x < 8; x++) {
      if (x + xp < 0 || x + xp >= buffer.width) continue; // make sure the pixel is on screen.
      var col = (colors >> (buffer.sheet.pixels[x + y * buffer.sheet.width + toffs] * 8)) &#038; 255;
      if (col < 255) buffer.pixels[(x + xp) + (y + yp) * buffer.width] = col;
    }
  }
}</pre>
<p></code><br />
To render a tile, we pass in the buffer, the position to render, the tile index, and the colour we want to tint the tile with. Most of the code just figures out the correct offset from the spritesheet (notice the magic number "32"? that's because the sheet is 32 x 32 tiles. The magic number 8? Our tiles are 8 x 8 pixels).</p>
<p><strong>But the important line is this whole procedure</strong> is this: <code>var col = (colors >> (buffer.sheet.pixels[x + y * buffer.sheet.width + toffs] * 8)) &#038; 255;</code></p>
<p>This is where the colourising magic happens. The pixel value from 0 to 3 is found from the spritesheet. This is then multiplied by 8 to give either the value: 0, 8, 16, or 24. The colour number is then <em>right shifted</em> by that amount and <em>anded</em> by 255.</p>
<p>Does this sound kind of familiar? It's the inverse of what the ol' <code>GetColour</code> function did - which encoded 4 colour values into 1 integer. This is just doing the opposite: extracting one colour out of the integer and applying it to the correct pixel. The next line then checks that the value is not 255 - which will be our "invisible" colour for transparent areas. </p>
<p>We can call this function for each 8x8 sprite/tile we want to render. The tile number is the integer index into the spritesheet: 0 is the first tile in the first row, 1 is the second tile in the first row, 32 (1 * 32 + 0) is the first tile in the second row, 33 (1 * 32 + 1) is the second tile in the second row... </p>
<p><code>
<pre>renderTile(buffer, 20, 20, (5 * 32) + 0, GetColour(-1, 100, 320, 222));
renderTile(buffer, 30, 20, (5 * 32) + 2, GetColour(-1, 100, 320, 222));
renderTile(buffer, 40, 20, (5 * 32) + 3, GetColour(-1, 100, 320, 222));
</pre>
<p></code></p>
<p>Ah, that's more like it - <a href="/dev/spritecol/p4-render.html">Three colourised Minicraft tools</a>!</p>
<h3>Messing around with it</h3>
<p>With the ability to plot tiles and sprites at a given location - we have all we need to make some games! In each of your entity's render functionality you can call the renderTile as many times as you need. For example, to render a background over the whole screen:</p>
<pre><code>for(var y = 0; y < buffer.height / 8; y++) {
    for(var x = 0; x < buffer.width / 8; x++) {
        renderTile(buffer, x * 8, y * 8, 1, GetColour(0, 130, 120, 0));
    }
}
</code></pre>
<p>You can plot individual tiles to make a font plotter, or stitch a few tiles together for bigger sprites... whatever you want. Here's the code for the weird demo from the beginning of the article. Notice that the Minicraft players are actually 4 tiles in a square:</p>
<p><code>
<pre>var rnd = function(min, max){ if(!max){ max=min; min=0; }; return ~~(Math.random()*(max-min))+min;},
    rndCol = function(){ return parseInt(rnd(5) + "" + rnd(5) + "" + rnd(5), 10); };

// Render peoples
var midX = ~~(Math.sin(new Date().getTime() / 400) * 20) + 70,
    midY = ~~(buffer.height / 2) - 8,
    col1 = GetColour(-1, 1, rndCol(), rndCol()),
    col2 = GetColour(-1, 1, 23, 555);

// Man 1
renderTile(buffer, midX + 16, midY, (14 * 32) + 0, col1);
renderTile(buffer, midX + 24, midY, (14 * 32) + 1, col1);
renderTile(buffer, midX + 16, midY + 8, (15 * 32) + 0, col1);
renderTile(buffer, midX + 24, midY + 8, (15 * 32) + 1, col1);

// Man 2
renderTile(buffer, midX, midY, (16 * 32) + 0, col2);
renderTile(buffer, midX + 8, midY, (16 * 32) + 1, col2);
renderTile(buffer, midX, midY + 8, (17 * 32) + 0, col2);
renderTile(buffer, midX + 8, midY + 8, (17 * 32) + 1, col2);
</code></pre>
<p>Check out the <a href="http://www.ludumdare.com/compo/ludum-dare-22/?action=preview&#038;uid=398">Minicraft source</a> (or <a href="https://github.com/Miserlou/Minicraft">here on GitHub</a>) - especially the <code>render</code> functions of each entity (eg player.java) to see how Notch implements animation and rendering based on the player's direction, if they are attacking, etc.</p>
<p>Anyhow... <a href="/dev/spritecol/p5-go.html">that's it</a>. I'd highly recommend not using any of the code above, but re-implement it yourself from your brain... this code is already ported from Java which was written in a 48 hour game competition, by a mad man - so do yourself a favour and make your own (more idiomatic) version!</p>
<p>It's worth it I think... dynamically colourising sprites like this is a great way to prototype the look and feel of your game, add in old-school colour-cycling effects, and easily add variety to your entities.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2012/02/02/colorising-sprites-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Translating marketing garbage</title>
		<link>http://www.mrspeaker.net/2012/01/07/translating-marketing-garbage/</link>
		<comments>http://www.mrspeaker.net/2012/01/07/translating-marketing-garbage/#comments</comments>
		<pubDate>Fri, 06 Jan 2012 14:11:14 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[Wide world]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=3137</guid>
		<description><![CDATA[French is a beautiful language, so of course it makes sense that some right-wing crazies would fight like heck to keep English from ruining it. That's exactly the intent behind Toubon Law - which mandates that any commercial publications written (or containing text) in another language also come with a visible French translation. This usually [...]]]></description>
			<content:encoded><![CDATA[<p>French is a beautiful language, so of course it makes sense that some right-wing crazies would fight like heck to keep English from ruining it. That's exactly the intent behind <a href="http://en.wikipedia.org/wiki/Toubon_Law">Toubon Law</a> - which mandates that any commercial publications written (or containing text) in another language <em>also</em> come with a visible French translation.</p>
<p>This usually just means you have to properly internationalise software and that Open Source licenses are completely null and void as they are only written in English... but it becomes much more fun when you realise that advertising - despite containing no literal meaning whatsoever - also counts as "text". Meaningless catch phrases, and shallow one-liners are not exempt!<span id="more-3137"></span></p>
<p>How do you translate drivel into drivel? Here's one example:</p>
<p><img src="/images/EnglishGibberish.png" /><br />
Some smart people (jeez, I hope it was people) thought the Windows Phone needed a sincere and poignant statement to emphasise the beauty and meaning inherent in their life-changing product: <strong>Put people first.</strong>. Ermmmm, okay. Will do.</p>
<p>Now, nobody needs to be told that advertisement is dangerous and will actively make you stupider if you accidentally read it - but here's the nice part: this particular piece of nonsense is written in <em>English</em>. Which is completely unacceptable in France thanks to <em>loi toubon</em>.</p>
<p>So somebody else gets paid to take this meaningless phrase and turn it into <em>French</em> nonsense.</p>
<p><img src="/images/FrenchGibberish.png" /></p>
<p>And the result? "Soyez au cœur des contacts"... <strong>Be at the heart of (your) contacts</strong>. Ah, it's beauuutiful! I'd like to see this in some kind of translation loop... would it reach an equilibrium? Or would it create a sentence <em>so</em> banal as to instantly hebetate any who read it?</p>
<p>Toubon Law is great fun - though somehow the movie biz are kind of exempt from it... Rather than translating the movie titles from English to French, they can translate them from English to weirder English as long as they awkwardly work in the words <a href="http://www.senscritique.com/fry3000/liste/13157/le-mot--sex--est-rajoute-dans-le-titre-francais-pour-attirer-les-spectateurs-libidineux/">sex or sexy</a>. Peculiar loophole, that.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2012/01/07/translating-marketing-garbage/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Navigate the web with your gamepad</title>
		<link>http://www.mrspeaker.net/2012/01/03/gamepad-navigator/</link>
		<comments>http://www.mrspeaker.net/2012/01/03/gamepad-navigator/#comments</comments>
		<pubDate>Mon, 02 Jan 2012 15:30:02 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[HTML5]]></category>
		<category><![CDATA[Wide world]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=3121</guid>
		<description><![CDATA[How crap is the mouse, right? Yeah, I know! So I made a greasemonkey script to do my websurfin' using my NES-style USB gamepad. For those of you too excited to read on, take your gamepad-enabled build of Firefox and install Gamepad Navigator now! Up and down to scroll the page up and down. The [...]]]></description>
			<content:encoded><![CDATA[<p><img src="/images/nes-controller.png" class="frame-right" />How crap is the mouse, right? Yeah, I know! So I made a greasemonkey script to do my websurfin' using my <a href="http://www.thinkgeek.com/electronics/retro-gaming/ba5a/">NES-style USB gamepad</a>. For those of you too excited to read on, take your <a href="http://people.mozilla.com/~tmielczarek/mouselock+gamepad/">gamepad-enabled build of Firefox</a> and install <a href="https://github.com/mrspeaker/Gamepad-Navigator">Gamepad Navigator</a> now!</p>
<p><strong>Up and down</strong> to scroll the page up and down. The top-most visible link on the page will be highlighted for your navigating pleasure. <strong>Left and right</strong> to move between links, <strong>FIRE</strong> to visit. It's just that simple! </p>
<p><span id="more-3121"></span>
<p class="note">The <a href="http://dvcs.w3.org/hg/webevents/raw-file/default/gamepad.html">gamepad API</a> is verrry experimental at the moment - it's only available in special builds of Firefox and Chrome (Chrome Canary)... but it's comin' to a browser near you soon!</p>
<p>I also map the "select" button to back, and "start" button to forward, just for fun. It's only for Firefox at the moment (thanks to some weirdness in the Chrome implementation) and it's hardcoded to the Retrolink controller - you need to tweak the IDs in the script to match yours... but hey, works on my machine!</p>
<p><iframe width="450" height="335" src="http://www.youtube.com/embed/em8lmarM01g" frameborder="0" allowfullscreen></iframe></p>
<p>Konami code not included.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2012/01/03/gamepad-navigator/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Colourising sprites in Canvas &#8211; part 1</title>
		<link>http://www.mrspeaker.net/2011/12/30/colorising-sprites-1/</link>
		<comments>http://www.mrspeaker.net/2011/12/30/colorising-sprites-1/#comments</comments>
		<pubDate>Fri, 30 Dec 2011 10:09:57 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=3095</guid>
		<description><![CDATA[First things first: I promise to try to limit the Notch related posts in the future and I apologize to the legions of l337 coders for the continued coverage. Right, now, on to todays topic: "Colour like you're Notch" (Awright, punning on my own blog post titles!). While watching the livestream of Notch coding Minicraft, [...]]]></description>
			<content:encoded><![CDATA[<p><img src="/images/minicon.png" class="frame-right" />First things first: I promise to try to limit the Notch related posts in the future and I apologize to the legions of l337 coders for the continued coverage.</p>
<p>Right, now, on to todays topic: "Colour like you're Notch" (Awright, punning on <a href="http://www.mrspeaker.net/2011/09/15/code-like-youre-notch/">my own blog post titles</a>!). While watching the livestream of Notch coding <a href="http://www.ludumdare.com/compo/ludum-dare-22/?action=preview&#038;uid=398">Minicraft</a>,  I was intrigued by his dynamic sprite colorising. After a little reverse engineering and experimentation I realised it was dang simple, and we could apply something similar to HTML5 games.</p>
<p><span id="more-3095"></span>The idea is that you create your sprite sheet using only 4 colours. At runtime, you replace the 4 colours with any colours you like - so you can quickly modify the look and feel of the game, or have varied characters that differ only by colour - just like the ol' NES games.</p>
<p>While 95% of Notch's code is extremely straightforward and obvious, the colour system got a bit hairy due to the fact he faffed around with the implementation a few times to get the result he wanted. The end result seems more complex than it really is. The overview of the system goes like so:</p>
<p>1. Set up a limited (256 colour) indexed palette to be used in the game. The colour channels will be divided into 5 "shades".<br />
2. Draw the sprites in 4 colours. When loading the image into the game, reduce the pixels to values from 0 to 3 to represent the colour.<br />
3. When drawing a sprite to the screen, dynamically pass in the 4 colours to use.<br />
4. For each pixel, find the index in the palette and replace the pixel with that colour.<br />
5. Profit!</p>
<p>The trickiest part is realising that Notch just made up a custom colour selecting system. Throughout the Minicraft code you'll see lots of instances of a line like: <code>Color.get(100, 232, -1, 555)</code> - although it kind of looks like some kind of RGBA format, it's really defining 4 separate colours, each made up of 3 channels. The number 100 represents r = 1, g = 0, b = 0 and would be a very dark red. 555 represents r = 5, g = 5, b = 5 and would be white (full red, full green, and full blue). So let's see it in action...</p>
<p>In <code>Game.java</code>, the colour palette is set up. It uses 6 bits per channel to get our 256 colours in 5 shades. Here's the directly ported JavaScript version (well, except that I'm passing in the number of bits to use, so you can play with it):<br />
<code>
<pre>function InitPalette(colours, bits) {
  // Set colours
  for (var r = 0; r < bits; r++) {
    for (var g = 0; g < bits; g++) {
      for (var b = 0; b < bits; b++) {
        var rr = r * 255 / (bits - 1),
            gg = g * 255 / (bits - 1),
	    bb = b * 255 / (bits - 1);

        // Set the mid tone
        var mid = (rr * 30 + gg * 59 + bb * 11) / 100;

        // Tint the palette
        var r1 = ~~(((rr + mid * 1) / 2) * 230 / 255 + 10),
            g1 = ~~(((gg + mid * 1) / 2) * 230 / 255 + 10),
            b1 = ~~(((bb + mid * 1) / 2) * 230 / 255 + 10);

        // Push RGB values into a single integer
        colours.push(r1 << 16 | g1 << 8 | b1);
      }
    }
  }
}</pre>
<p></code></p>
<p>You can have a look at the palette that's generated by this function with <a href="http://jsfiddle.net/Rjcyj/2/">this jsFiddle</a>. One cool thing to notice is the tinting process. Try changing the final line to push the non-tinted values (rr instead of r1, gg instead of g1 etc). Without the tinting the game colours would <a href="http://jsfiddle.net/Rjcyj/1/">look like this</a>. Quite a nice way to give the game a "feel". Here they are side-by-side - the top one is tinted to be more "pastel-ly".</p>
<p><img src="/images/mini-palette.png" alt="comparing tinted and non-tinted palettes" /></p>
<p>The final line <code>colours.push(r1 << 16 | g1 << 8 | b1)</code> converts the RGB values into a single integer (the shift-left operator moves the red bits up the top, the green bits in the middle, and leaves the blue bits at the end). If you want to use this in your HTML5 games, then it'd be better to skip this encoding and store each colour as a simple object - because we just need to decode it later (perhaps the shift version is faster in JavaScript too? Might need a bit of testing!).</p>
<p>Anyway - now we have an indexed palette of colours. To get the colours back at our will we need to use the accessor methods Notch created in <code>Color.java</code>. Here's a JS version:<br />
<code>
<pre>function GetColour(a, b, c, d) {
  function getIndex(d) {
    if (d < 0) return 255;
    var r = ~~(d / 100) % 10; // First digit
    var g = ~~(d / 10) % 10; // Second digit
    var b = d % 10; // Third digit
    return r * 36 + g * 6 + b;
  }

  return (getIndex(d) << 24) + (getIndex(c) << 16) + (getIndex(b) << 8) + (getIndex(a));
}
</pre>
<p></code><br />
Notch's version is the same code, but he uses an overloaded <code>get</code> method for fetching the indexes. The final line returns a single integer like in the palette generation - it pushes the first colour 24 bits up the integer, the second colour 16 bits up etc. The value that it pushes is the index in the palette. This is calculated by the getIndex function by turning the decimal number into 3 channels. The function will accept a number between 0 and 555 (5 x reds, 5 x greens, and 5 x blues). If you put a number higher than 555 into it, it'll die. So don't do that.</p>
<p>Now we can get a single number to represent our 4 colours. <code>GetColour(500, 50, 5, 505) == -1190846796</code> (Be careful, it's tempting to put 500, 050, 005, 505 so it looks nice, but remember - a leading 0 mean the number is octal in JavaScript, so 050 will actually be 40 in decimal).</p>
<h3>Colouring in</h3>
<p>Now that we have a way to encode the colours, we need to be able to decode them. Which is just a matter of reversing the getColour method, really: pop out the values and find the palette index! To show it in action I'll just draw 4 rectangles in the four colours specified by GetColour:<br />
<code>
<pre>function DrawColours(ctx, colourInt, palette) {
    for(var i = 0; i < 4; i++) {
        var colIndx = (colourInt >> i * 8) &#038; 255,
            col = palette[colIndx],
            b1 = col &#038; 255,
            g1 = (col >> 8) &#038; 255,
            r1 = (col >> 16) &#038; 255;
        ctx.fillStyle = "rgb(" + r1 + "," + g1 + "," + b1 + ")";
        ctx.fillRect(i * 10, 0, 10, 10);
    }
}

DrawColours(ctx, GetColour(510, 0, 555, 55), colours);
</pre>
<p></code><br />
<a href="http://jsfiddle.net/Rjcyj/3/">The result</a> is a red-ish rectangle, a black, a "white", and an aqua blue rectangle. The decoding part can be found in the Minicraft source in <code>Screen.java</code> in the render function. The original code looked like this:<br />
<code>int col = (colors >> (sheet.pixels[xs + ys * sheet.width + toffs] * 8)) &#038; 255;</code>. First the pixel colour (for 0 to 3) is found in the sprite sheet that corresponds with the current tile. This is the "i" from our <code>DrawColours</code> function. The number is then multiplied by 8 to get the correct distance to shift by (0, 8, 16, or 24 bits). The result is the number we pushed in with the <code>GetColour</code> call - which was the index of the palette to use. The actual colour components can then be extracted and drawn.</p>
<p>Ok, that's it for this post - it's getting too long. As you can see, the system is very simple - it's just encoding and decoding palette indexes. <a href="http://www.mrspeaker.net/2012/02/02/colorising-sprites-2/">In the next post</a> I'll show you how to load in the sprite sheet, covert it to the correct 0 - 4 format we need, and plot the colourised tiles. Sounds exciting, hey?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2011/12/30/colorising-sprites-1/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>What I learned from watching people watching Notch</title>
		<link>http://www.mrspeaker.net/2011/12/20/troll-at-notch/</link>
		<comments>http://www.mrspeaker.net/2011/12/20/troll-at-notch/#comments</comments>
		<pubDate>Tue, 20 Dec 2011 10:08:59 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[Nerd]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=3066</guid>
		<description><![CDATA[Last weekend was the 22nd Ludum Dare 48 hour game comp. Again Notch livestreamed it, again I watched pretty much all of it, and again I learned a lot. But having seen Notch in action before, this time I could afford to take my eyes off the code from time to time, and spend a [...]]]></description>
			<content:encoded><![CDATA[<p>Last weekend was <a href="http://www.ludumdare.com/compo/ludum-dare-22/">the 22nd Ludum Dare</a> 48 hour game comp. Again Notch livestreamed it, again I watched pretty much all of it, and <a href="http://www.mrspeaker.net/2011/09/15/code-like-youre-notch/">again I learned a lot</a>. But having seen Notch in action before, this time I could afford to take my eyes off the code from time to time, and spend a bit more time to perusing the informative "chat" that accompanied the videos.</p>
<p><span id="more-3066"></span>With an average of around 5000 anonymous viewers, that's always going fun. Over the weekend the topics ebbed and flowed over 3 core themes: <strong>"What radio station is this?"</strong> (devolving into music flamewars), <strong>"When is the next Minecraft release?"</strong> (devolving into Minecraft flamewars), and <strong>"What program is he using?"</strong> (Devolving into programming language flamewars). Here were some of my favourite quotes from the informed and poignant programming language discussions:</p>
<ul style="line-height:17pt;padding-left:10px">
<li>java wasnt really made for games</li>
<li>C isn't a very good language, it doesnt have xml or objects</li>
<li>tell me, why the *** would you write a game in an imperative language if you knew c++ just as well?</li>
<li style="list-style-type:none;">
<blockquote>You should start with c++ if you want to learn programming. All other languages are ***, except for the D language.</p></blockquote>
</li>
<li>how do i OOP?</li>
<li>object oriented programming is a sad failed paradigm of the 80s</li>
<li>Object C isn't very flexible ;-;</li>
<li>i hear you need to learn html to get into C#, is this true?</li>
<li>you're a good c++ coder if you don't use any pointers</li>
<li>the part i hated most about notchs code was the bitwise shifting i hate that</li>
<li style="list-style-type:none;">
<blockquote>i learnt c++ from a book, its boring</p></blockquote>
</li>
<li>C++ isnt boring, just as fun as Java, but faster and more flexible</li>
<li>c++ is a mess now</li>
<li>java looks a lot like c++</li>
<li>i just now realized how similar c++ and java really are</li>
<li>C++ can be writtnel like C cause C++ has bacwardcompapility</li>
<li>the C lineage has it's tendrils everywhere in modern programming, maybe not in c++ but certainly in later iterations</li>
<li>c++ is like updated c#</li>
<li>whats easier to learn c++ or java and what is better overall( like quality of programm)</li>
<li style="list-style-type:none;">
<blockquote>java is easiest. c++ is more useful and makes a better program</p></blockquote>
</li>
<li>C# is an improved Java. Java is an improved C++. C++ is far harder, more difficult and complex than java or c#. C# is also a better language than both.</li>
<li style="list-style-type:none;">
<blockquote>C++ is the most efficient programming language to date</p></blockquote>
</li>
<li>java takes too much ressoursses</li>
<li>java is demanding in terms of RAM</li>
<li>Java is similar to C++ with Objects and stuff and antway wasnt java writen in C++</li>
<li>Visual is the standard programming language....doesn't mean its awful << haters</li>
<li>C++ is a giant, ugy, monstrosity of a language. somewhere inside it, there is a much simpler and more elegant language. that language is called java.</li>
<li>Chrome sucks because it has seperate processes for EVERY tab! And they say it's lightweight.. lol</li>
<li>why are you people talking about c++? seriously, learn c# or sth. like that, but not c++... *** c++. so outdated nowadays and just terrible</li>
<li style="list-style-type:none;">
<blockquote>as long as someone is using a old programming language it's worth learning... look @ bank systems they're coded in old langs</p></blockquote>
</li>
</ul>
<p>No one was delving on the irony of spending an hour or so arguing about which language is better for games, without noticing that <a href="https://s3.amazonaws.com/ld48/ld22/index.html">an actual game was unfolding before their eyes</a>. If only games were flamewar powered!</p>
<p>It was obvious that most people liked the idea of making a game, but balked when confronted with the part where you <em>actually had to put in a bit of effort</em>. This attitude was entrenched firmly in what was perhaps my favourite quote for the weekend - directed towards Notch's wife (who at one point was moderating the madness):</p>
<blockquote><p>EZ, any advice for women who want to marry men who are in game development?</p></blockquote>
<p>Now that's just plain lazy.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2011/12/20/troll-at-notch/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>

