Check out my
new book!
HTML5 Games book
3D chess developments A long time ago I started working on a 3D chess game using canvas but never got around to finishing it. Well, Stefano Gioffré took it upon himself to add some very cool features and not least, integrate a chess engine allowing you to play against the computer. Awesome work, Stefano.


Check it out here: http://htmlchess.sourceforge.net/demo/example.html

Read more...
Worlds of WebGL Here's another thing I did while I was first playing around with WebGL, working on the musical solar system thing. Due to changes in the WebGL spec and the various implementations it got broken before I had a chance to put it online and it's just been sitting collecting dust ever since. I just tried fixing some of the issues and it seems to run ok now (let me know if it doesn't). It's a small experiment with a whole bunch of particles/planets forming larger shapes. Enjoy!

Link: Worlds of WebGL

Make sure you have a WebGL capable browser. Check out this page over at Learning WebGL if you need help getting one.

Read more...
WebGL Musical Solar System
A solar system of dancing planets, made with JavaScript, WebGL and HTML5 audio.

In my quest to get to know WebGL better, I've gradually been building my way up from the standard "paint one triangle" tests to more and more advanced things. Never having touched OpenGL before, this is all a nice learning experience for me and I can now render not only one but two triangles at once as well as cubes, spheres and what have you. There's been some nice progress around the web as well, most recently with Yohei Shimomae's Cube Defense, a tower defense like game built with JavaScript and WebGL - probably the first WebGL game ever but hopefully many will follow!

Without further ado, here's my own first, small pet project: A solar system of dancing planets.

You will need either a Firefox nightly build or a Chromium continuous build to run this (in my experience, it runs best in Chrome). I don't know if WebKit on Mac will work and I've only tested FF and Chrome on Windows. If you have any success running it on Mac, please leave a comment saying so. So far it doesn't look good, though.

In Firefox you need to enable WebGL by going to "about:config", searching for "webgl" and enabling it "for all sites".

Chrome needs to be launched with the command line arguments "--enable-webgl --no-sandbox", so make a shortcut to chrome.exe and add those arguments.

If for some reason you're unable to do that or you're just lazy, there's also a YouTube video. The real thing looks better, though.

For those interested, this time the audio comes from an HTML5 <audio> element and not from SoundManager2 (which is great but also Flash). However, HTML5 doesn't give you the same detailed audio data (FFT and such) that Flash does, so I'm actually reading the data from a separate text file. I would of course rather have had actual access to the data, but this will do - and it keeps it totally Flash-less.
Read more...
WebGL Cheat Sheet WebGL has been getting a fair amount of buzz lately - and rightfully so, because it is cool. For those that don't know, WebGL is the 3D extension of the Canvas element, based on OpenGL ES 2.0. Having a standardized low-level graphics API like that available in the browser is pretty exciting stuff if you ask me. 3D canvas graphics has been long underway and not until just recently did it get to an interesting state when the first signs of WebGL showed up in both the (Mac) WebKit and Firefox nightly builds.

Note: This cheat sheet has become a bit out of date as the specs have been released and changes have been made that are not reflected in the cheat sheet. I will update it as soon as possible. Cheers. It's still very much a work in progress and the official specs haven't been made public yet, I'm not even sure how far they (Khronos, the working group responsible) are in settling on the specs. So that means there aren't much in terms of references out there for people like me who are anxious to play around with this new toy. There are a few example demos from both the WebKit and the Mozilla camps and cool sites like Learning WebGL are starting to pop up. There's of course the OES 2.0 reference and the source code for both WebKit and Mozilla implementations is also readily available. So, I decided to just make my own reference sheet by combining those sources and the result is a condensed WebGL cheat sheet which fits on 4 pages - or 2 if you have good eyes and print two on each page.

As an added bonus, this exercise forced me to dig through the entire OES2.0 spec, which was great since I'm an OpenGL newbie and learning stuff is cool!

Of course, given the current state of WebGL, any of the information in this document is subject to change from day to day. I might most certainly have missed a bunch of things as well due to lack of insight and good references. In addition to that there also seem to be a few differences in the two implementations, so those will be corrected when I know what actually needs correcting.

I also don't have access to a Mac and since the WebKit implementation is Mac-only for now, I haven't actually seen it action. There might be more differences between the two than I've found just by glancing over the source.

Anyway, here it is in both PDF and HTML:

WebGL Cheat Sheet PDF

WebGL Cheat Sheet HTML

The HTML version has the extra bonus feature of tooltip information when you hover the mouse over (most of the) function parameters and enum values.

And corrections and suggestions are of course most welcome!
Read more...
Creating pseudo-3D games... part 2 Part 2 of my series of articles about how to use JavaScript, DHTML and Canvas to create raycasting games like Wolfenstein 3D is up at Dev.Opera - read the article here.

In this article I've taken the result of the first article and improved upon it by, among other things, optimizing performance and adding sprites and scary (not really) enemies that run after you.

Note that the titles of the articles are a bit misleading since Canvas is only really used for drawing the minimap, everything else is plain DHTML.
Read more...
Creating pseudo 3D games with HTML 5 canvas Just a quick post to let you know that I've got an article up at Dev.Opera where I talk about creating a simple raycasting engine like the one I used in my WolfenFlickr project. Read the whole article here. Feel free to ask questions and leave comments both here and at dev.opera.com. Read more...
WolfenFlickr 3D - An unlikely mashup Long after B.J. Blazkowicz left Castle Wolfenstein guns blazing, the castle still holds a few secrets. On a super secret floor stolen art in the form of Flickr images has been found and for the first time, this strange gallery is now open to the public.

If you're interested in building an engine such as this yourself, take a look at the Dev.Opera article I've written on this topic.

This is a (silly) mashup of Wolfenstein 3D and Flickr. More specifically, it's a Javascript raycaster using Wolfenstein graphics that allows you to import Flickr images by username/search query and then walk around this odd gallery.

If you don't care about the details and just want WolfenFlickr gallery action, go straight to the WolfenFlickr 3D demo page.

This little experiment killed two birds with one stone. First, I wanted to get to know Flickr's API (and Flickr itself, actually, me not being a big photo nerd). Second, I wanted to do a Javascript raycasting engine. In a moment of unusual clarity, it came to me that these goals were not mutually exclusive and while the end result borders the useless (hey, most things here do), the project served its purpose well.

WolfenFlickr 3D - Flickr / Wolfenstein 3D JavaScript MashupThe Flickr API part turned out to be pretty simple. The Flickr guys are good people and provide very easy to use methods, JSON data and the option to specify callback JS functions making it a breeze to implement Flickr integration, at least on the level that I'm using here. So, we simply retrieve all photos from a specified user (or matching a search query) to create a list of images for our gallery. For performance reasons, only the first 20 Flickr images are used.

The Wolfenstein part wasn't all too hard either, although lots of tinkering was needed to make it run semi-smoothly. Unlike the previous JavaScript Wolfenstein 3D experiments here, this one uses a raycasting engine and not the JavaScript 3D engine. If you want to read more about raycasting, check this link or Wikipedia.

Basically, The screen is divided into X amount of vertical strips (div elements). Each of these strips contains an image element with all the wall textures making the strips serve as containers and masks for the actual lines. "Rays" are then cast out on the map for each strip and when the ray hits a wall, we simply move and scale the wall texture image in the strip according to which wall type, where on the wall the ray hit and how far away it is. Each strip also holds a copy of all the Flickr images positioned on top of the wall textures. Each wall block (with picture frame) is assigned a Flickr image and then it's just a matter of showing the appropriate part of the image on top of the texture. The pictures are stretched (and slightly cropped) to fit the frames, so it looks best with pictures that are not too tall/wide. There are a few things I need to fix and then maybe I'll do a more detailed post on the raycasting part if there's any interest?

I also tried using canvas just to see what kind of performance that would give. It appeared to be roughly equal to the straight DOM approach but would get complicated (and probably slower) when sprites were added since the current approach utilizes the browser's own fast depth sorting via the z-index on the strips and sprites.

Tested with FF2, FF3, Opera 9.51, IE7 (IE8b1 doesn't work), Safari 3.3.2. For some reason the recent WebKit nightlies are not working for me at all (crashes on any page, anyone else get that?), but Safari 4 dev preview works fine.
Safari is awesome and runs very smoothly for me. Opera 9.51 runs ok, IE7 and FF2 a little slower and for some reason FF3 is just horrible slow. Where FF2 takes a hit at the raycasting (ie. pure Javascript) and is quite fast at changing/rendering the DOM elements, it seems FF3 is just the opposite. Maybe I'll give the canvas approach another go and see how FF3 likes that.
Edit: For better performance in Opera, turn off [Multimedia]->"Interpolate images" in "opera:config" and it should run a lot faster.
The player position is for some reason not drawn on the minimap in IE (and the map might not render at all). Other than that, there shouldn't be any major problems (aside from speed).

Take the WolfenFlickr 3D tour!

Edit: I also found a Youtube video of WolfenFlickr in action. Check it out if you're having trouble with the real thing!

And do leave a comment if you feel like it.
Read more...
3D JavaScript Chess - mouse support Just a quick post to say that my 3D JavaScript chess game has gotten some better mouse support. You can now use the mouse to select and move the pieces (it's a bit sluggish, I know). Also, when a piece is selected, the valid target squares will be shown in green.



Check it out here
Read more...
Javascript Wolfenstein 3D

Ok, so here's another fun little experiment. Wolfenstein 3D using Javascript, Canvas and a touch of Ajax. Wolfenstein 3D is definitely one of the games that stand out when I think back to my younger game playing days. The mother of all FPS games, the baddest piece of nazi-ass-kicking software ever produced.

Hey! While you're here, why don't you check out the new Games section, a section completely dedicated to online JavaScript web games! And subscribe to the feeds to get the latest updates and games! Now back to Wolfenstein...

For the tl;dr crowd: Click here to play

All of the first floor is mapped out, albeit with a few modifications. For instance, secret doors are not implemented, so a hole in the wall was needed, as well as a few other minor changes. There are other limitations as well, look further down for a list before complaining.


The original Wolfenstein 3D game by id Software was made using a neat technique called ray casting which allows nice performance on modest hardware. That technique is quite possible to implement using Javascript and Canvas and other people have already done so with great success. There have even been other tiny Wolfenstein-like games made in as little as 5kB and as few as 20 lines of Javascript. Making it small wasn't the aim of this exercise, however, and aside from not caring about file size, it uses a different approach in order to test the 3D renderer I've posted about earlier. The level geometry is set up almost as any other geometry, and exploiting the locked camera angle in Wolf 3D, we simply precalculate all the angles a wall can be viewed at and save those textures. From there it's just a matter of figuring out which texture to paint.

There are both benefits and drawbacks to this approach, the main drawback being my lack of 3D programming experience causing a few ugly things to happen. On the plus side, it should allow for easily mixing in real 3D geometry, like crates and barrels or whatever they fill FPS games with these days. I'll experiment with this in the near future.

For AI, there is nothing yet. No AI for the guards whatsoever. They just stand around and wait to be shot.

For sound, it uses Scott Schiller's awesome SoundManager 2 library in order to play mp3 files converted from the game files.

All the assets (sprites, textures, sounds) were ripped from the shareware edition using FloEdit, with the exception of the music by the great Bobby Prince which was found here.

Now for the game: Click here and Get Psyched!

Tested in Firefox 2 and 3, Safari 3.1.2, Opera (9.27 and 9.50b, beta being the best).

As you will see on the page, there are a few options:
The size of the game area matters the most and the medium version is quite playable on my computer while the large is very sluggish.
The low/high res texture option only has a small effect on performance as well as visual appearance. Playing with unshaded walls may give a small increase in performance.

Controls:
Use WASD for movement. Click and drag the mouse to rotate, or use the left/right arrows.
Press "x" to open doors and "c" to fire your gun.

Now, a whole bunch of issues, missing features and disclaimers:
  • Only browsers with real canvas support are supported. That means Firefox, Opera, WebKit. Sorry, no Internet Explorer!
  • Since the guards don't shoot, you can't die. You cannot finish the level either. The elevator does nothing. Actually, it is not even there.
  • There is only one weapon, the pistol. No knife.
  • There are no dogs. Just guards.
  • There is no AI. Guards just stand still, waiting to die.
  • The collision detection is rather crappy. As is the shooting code. You can shoot through walls, but only in the same room. You can't shoot through (open) doors.
  • It is possible to get stuck in a closing door. If it happens, try to open it again.
  • Weird things happen when you get near the walls and view them at an angle, like huge distortion of the texture, or the wall simply fails to render. Also, at the moment the precalculated wall textures don't account correctly for perspective distortion.
I do plan to finish it at some point and maybe do all the shareware levels, but for the immediate future I'm probably going to leave it at this and move on, except for maybe some optimizing and code tidying.


If this caught your interest, be sure to check out the related WolfenFlickr 3D project which uses real raycasting. Also see these other posts related to games!

Read more...
3D Javascript Chess bug fix Oh, haha.
Seems I left in a couple of calls to the Firebug console.log function in the 3D Javascript Chess demo, causing it to throw errors when moving pieces (unless you have Firebug installed and enabled, of course).
So if you tried earlier and it wouldn't move the pieces, it should work now.
Read more...
3D Javascript Chess (WIP)

Here is a work-in-progress 3D Javascript chess game, utilizing the 3D Canvas/Javascript renderer I've posted about before.

Since there are just too many polygons to render everything from scratch every time something changes, each piece is rendered unto its own canvas element. This means that we can move and manipulate any piece without having to redraw the entire scene. Unfortunately this has broken excanvas support for Internet Explorer, so until I get that fixed it's only for browsers with real canvas support (FF, Opera, Webkit)

In the future, I want to add some texturing to the pieces and maybe the board as well to make it look nicer. Also animated movement and perhaps even make use of some particle effects or something for when pieces are captured.

Click and drag the mouse to rotate the board. Note that when rotating the board all the pieces are hidden to allow smooth rotation. Mouse support for selecting/moving pieces will also be added in the near future, but for now you have to use the keyboard: Use 2,4,6,8 on the numeric keypad to move the selector square and 5 to select a piece and move it (press 5 again on the selected piece to deselect it).

There is no CPU opponent (yet). I'll probably see if I can find another suitable chess engine and borrow from that. Until then, the player controls both black and white.

It also needs a bit of GUI work. Key things like showing which side is up and a moves list are missing.

On the chess part, it also needs some work. Movement and capturing of enemy pieces should work alright, but none of the special moves (castling, en passant, promotion) are implemented and the game doesn't know about check/checkmate (to "end" the game, just capture a king).

Check it out here
Read more...
3D Javascript Particle Generator Particles are awesome and so are particle generators. If you didn't know, a particle emitter is an object which spawns a large group of small objects (particles). It can be used to create a whole bunch of different effects like fire, rain, snow and magic!



Building on to the canvas 3D renderer, I hacked together a small particle emitter as a learning experience.

The demo has a number of controls for adjusting particle generation (size, shape, speed, direction, etc.) Several of the controls also have an additional "noise" control, which allows adding a random amount to that parameter.
There are a bunch of presets as well, that show effects such as a cone of smoke, a flame and even a fruity spiral!

Will be expanded with more controls and particle goodness in the future.

Performance seems best in Opera (specially the beta). Firefox and Safari are ok, but a little sluggish with high particle counts. IE sits this one out, for now at least.

Check it out here

Read more...
Canvas 3D - better textures The previous attempt at texturing was very crude and wasn't very useful as it rendered the whole texture onto every face of the model.
So now I've refined the texturing and I'm now using UV coordinates to determine which part of the texture belongs to which part of the model. This allows for nicer texturing as seen below.
It still uses affine mapping, which means that each pixel in a triangle is rendered as if it was at the same distance from the viewer as all the other pixels in that triangle.
It's still not correct, but a reasonable compromise, considering we still need something resembling a framerate.

The backside is that for now, this only works in Firefox, Opera beta and the latest WebKit nightlies, since we're now using the *ImageData methods.

Check the demo here



Read more...
Javascript/Canvas 3D Renderer - now with textures!
UPDATE: An updated version with better texturing has been posted here

Dabbling a bit further into the 3D Canvas experiments, I tried to get some basic texturing going on. To do any real, correct texturing, you'd have to read and render the texture image data on a pixel-by-pixel basis, since each pixel would have different distance from the viewer. While I suppose that would be possible (using the *ImageData methods), I don't want to think about how slow it would probably be.


What we're doing here instead is just rendering each face as if all the pixels were at the same distance. That means we can just draw a triangular image (rotated, skewed and scaled) to fit the triangular faces. This approach may cause visible distortion (or lack of distortion) in some cases, but with the models used here, I think the result is acceptable.

Performance is of course lower when using textures, but the models with low polygon-count can easily still be rotated in something resembling real time. Safari is still the fastest for me, followed by Opera and Firefox. No textures for IE for now, I'm afraid.

Check it out here: http://www.nihilogic.dk/labs/canvas3dtexture/





Read more...
Canvas 3D Renderer written in Javascript "UPDATE: An updated version with texturing has been posted here


For another project, I wanted to see how feasible it was to render simple 3D models using the canvas element. The result is this little app, which loads a given mesh (stored in a custom json format) and renders it with lighting and some simple controls like rotation and zooming.


Performance isn't amazing as the triangle count rises above a few hundred (at least on my modest box), but it should work on both FF, Opera, Safari and IE (using excanvas). Safari yields the most pleasant experience while IE is quite horrible.

I'm not sure how usable this is yet, but it seems possible to render static images of simple models.

http://www.nihilogic.dk/labs/canvas3d/





Read more...