29a.ch

Entries tagged “html5”

Loading twitter widgets asynchronously using yepnope

Twitter widgets block the loading of your page by default. So if twitter goes down it will take half of the internet with it. That of course is fail! So let's use yepnope.js to decouple them from your page.

Starting position

<body>
<a href="http://twitter.com/share" class="twitter-share-button" data-count="vertical" data-via="29a_ch">Tweet</a>
<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script>
<script src="http://widgets.twimg.com/j/2/widget.js"></script>
<script>
new TWTR.Widget({
  version: 2,
  type: 'search',
  search: 'rainbow'
  // ...
}).render().start();
</script>
</body>

Twitter button

The twitter button is actually implemented nicely using data attributes and progressive enhancement. This makes life easy for us.

<a href="http://twitter.com/share" class="twitter-share-button" data-count="horizontal" data-via="29a_ch">Tweet</a>
<script src="yepnope.js"></script>
<script>yepnope('http://platform.twitter.com/widgets.js');</script>

As you can see loading the twitter button with yepnope is trivial but you get some flickering. Let's improve that with a stylesheet

a.twitter-share-button { display: block; width: 110px; height: 20px; visibility: hidden; }

This will preallocate the space needed for the twitter button. You might need to tweak it depending on the button you have chosen. Making the button fade in with css3 transitions would be another option.

Twitter Search Widget

The twitter search widget is a bit more problematic as it is using document.write(). I really wonder why they got the button so right and the other widgets so wrong. BOOOOH! If you look at the source you will find something interesting though:

if(!o.id){document.write(

It looks like somebody at twitter was aware of the fact that using document.write isn't a good idea and provided a way around it. He just didn't clearly document it. So let's use the id option to fix our problem.

<div id="twat"></div>
<script src="yepnope.js"></script>
<script>
function twatr(){
    new TWTR.Widget({
      id: 'twat',
      version: 2,
      type: 'search',
      search: 'rainbow'
      // ...
    }).render().start();
}
yepnope({load: 'http://widgets.twimg.com/j/2/widget.js', callback: twatr});
</script>

I hope you can now sleep well at night - without nightmares of fail whales (just ignore the fact that you are using an undocumented feature).

Chaotic Particles HTML5 Canvas Demo

I created this demo more or less by accident when prototyping some particle mechanics for a game. It is based on a particle system, and an acceleration map but more on that later. It reminds me quite a bit of simulations of galaxy formation or a lava lamp, it's really nice to watch.

Demo

screenshot

Click the image to open the demo. In the demo, set the particles in motion by dragging with your mouse.

Mobile devices

This demo also works on Android including fullscreen (tested on a nexus one with 2.2), iPhone and iPad! Give it a try ;)

How it works

Each particle has a position and a velocity stored in a typed Float32Array (yes, they work on iOS). In addition to that there is an acceleration 'map' in the background. When you drag over the particle system, you initialize the acceleration map which sets the whole system in motion.

accelerationMap[particle.position] += particle.velocity*someFactor
particle.velocity += accelerationMap[particle.position];
particle.position += particle.velocity;
...
The magic sauce to it is the feedback from the particle velocity to the acceleration map. Together with some damping this results in the system you are seeing. For more details, feel free to have a look at the source.

HTML5 Water Ripples Demo

Finally after a long time I can present you a new demo. It is inspired by the wave propagation formula mr.doob demoed a while ago. I was quite amazed by how simple it was and so I decided to build myself a little pond.

Demo

screenshot

Click the screenshot to start the demo. Move your mouse over the pool to disturb the water.

How it works

I think the really interesting part here is the wave propagation formula:

waveHeight = (buffer0[i-1] + buffer0[i+1] + buffer0[i+width] + buffer0[i-width])/2-buffer1[i];
buffer1[i] = waveHeight;
aux = buffer0;
buffer0 = buffer1;
buffer1 = aux;
Given are two height maps (buffer0 and buffer1). The buffers get rotated every frame so buffer0 points to heights of the wave in the last frame and buffer1 to the one before it. The height of the wave in the current frame at a certain point is calculated by simply averaging the height of the neighboring points in buffer0 and subtracting the height in buffer1. You can think of it like this, every point wants to be at the same height it's neighbors are and it wants to go towards zero. That is basically all there is to the wave propagation (I also added some simple filtering to make it a bit smoother).

The rest is pretty simple, and made up on the spot. The refraction is done by offsetting the texture coordinates by the height difference between the current point and it's neighbors. The lightning and caustics are faked similarly based on the height differences and the height of the current point.

In short it's all fake.

Performance

Chrome is fast, firefox is slow, at least thats the way it usually is. To my pleasant surprise the jaeger monkey builds of firefox seem to finally catch up. Another interesting thing is that safari seems to be the fastest (for this demo).

Credits

The photo was shot by Travholt licensed CC-BY-SA. As mentioned in the intro, I got the wave propagation function from mr.doob.

Other Experiments

Be sure to check out my other experiments. If you like what you saw you should subscribe to my blog or follow me on twitter.

Chrome and Safari don't cache html5 audio

Chrome and Safari seem to ignore the http cache headers for html5 audio files. When you are programming a game that can be fatal. First it delays the playback, second you get at least one http request per play(). So what can you do? Write a html5 Cache Manifest!

Also at least chrome seems to have a limit on the number of <audio> elements that can be created. You notice the problem when you call play() on an audio file and nothing happens anymore. My solution to this was to create a pool for audio elements for reuse.

With those two techniques I'm now able recreate the sound of a gatling gun by playing individual bullet shots, yay!

Javascript Galaxy Simulation

This is an older demo I did a while ago but haven't published yet. It's pretty slow unoptimized and hackish and the projection is wrong and I don't feel like fixing it. But it still looks cool! So thought I should publish it anyway.

What does it do? It simulates a spiral galaxy with 5000 stars.

Demo

screenshot

Click the screenshot to start the demo. It's pretty slow in firefox, works well in chrome.

How it works

Doing calculating the gravitational forces for 5000 particles in realtime using javascript is hard, and it would probably be quite hard to get stable spirals. So I cheated a little (a lot actually). To simulate the slowdown of the motion of stars in more dense areas I'm simply using a texture:

skymap

That's pretty much it: Generate a bunch of stars spinning around a center and modulate their speed according to the density map. Feel free to take a look at the source, but remember, I told you that it's a mess and all wrong.

Other Experiments

Be sure to check out my other experiments too.

Demonstrating evolution in 999b

When I saw the JS1K demo contest I knew I had to enter. I first tried to do some GFX demo, but I was lacking an impressive idea. So when I tried to sleep last night at 2 in the morning I had an idea which I needed to implement: Demonstrating evolution by natural selection in 999b/666b gzipped:

x = ('var_a=Math,b=a.random,c=document.g'+
'etElementById("c"),e=c.getContext("2d")'+
',f=[],g=b()*		 16777216<<0,h,i'+
',j,k,l=(g		  &16711680)>>16'+
',m=(g&65		    280)>>8,n=g&'+
'255,o,p		    ;c.width=320'+
';c.height=320;		    e.shadowBlur'+
'=10;for /* */	      (p=   0;p<64;p++)f'+
'.push(b(		    )*16777216<<'+
'0);func		    tion_q(d){fo'+
'r(d=d.t oStr		  ing(16);d.leng'+
'th<6;)			d = " 0"+d;retur'+
'n"#"+		      d } d ocument.body'+
'.sty		     l e .b a c kground='+
'q(g);		    setInterval(function'+
'(){e.		 c l e a r R e c t ( 0 ,'+
'0,320,		3 2 0 ) ; f o r ( p = 0 '+
';p<64;	    p + + ) { h = f [ p ] ; i = '+
'l-((h&	  1 6 7 1 1 6 8 0 ) > > 1 6 ) ;j'+
"=m-((h&65 2 8 0 ) > > 8 ) ; k = n - ( h"+
'&255);o=a.sqrt(i*i+j*j+k*k)/443;if(b()<'+
"o)h=f[p]=(f[b()*64<<0]&16773120|f[b()*6"+
'4<<0]&4095)^1<<(b()*24<<0);e.fillStyle='+
"q(h);e.fillRect(1+p%8<<5,1+p/8<<5,32,32"+
')}},100);e.shadowColor="#000";').replace(
/\s/g,"").replace(/_/g,' ');eval(x);
/*evolution in 999b by 29a.ch**/

+1 if you recognize that guy.

Demo

It's basically a few cells colored cells. The selection criteria is the color difference between the cell and the background. So cells that stand out have a higher chance of getting eaten.

Click me

How it works

You can see the full unminimized sourcecode here evolution.js I'll only explain the meaty stuff.

env = random()*(1<<24)<<0,
...
population.push(random()*(1<<24)<<0)

A random environment and population is initialized. The shift by 0 is a short way to round a number. Both the environment and the genes of the population are random 24 bit integers, that can be viewed as rgb colors.

subject=population[i];
r = r_-((subject&0xff0000)>>16);
g = g_-((subject&0xff00)>>8);
b = b_-(subject&0xff);
distance=M.sqrt(r*r+g*g+b*b)/443;
if(random()<distance){

The fitness for survival is determined by measuring the distance between the color of the individual and the environment. The lower the distance, the higher the chance for survival.

subject = population[i] = (
                // breed
                ((population[random()*popsize<<0]&0xfff000)|
                (population[random()*popsize<<0]&0xfff))
                // Mutate
                ^(1<<(random()*24<<0))
            );

When an individual dies, a new one is bred by sexual reproduction (parthenogenesis and necrophilia are possible as well). The new individual then gets one random mutation. That's pretty much all there is to it.

Realtime Raytracing in Javascript!

Yes we can! Thanks to the performance of modern javascript engines like V8 it is now possible to do realtime raytracing in javascript.

Demo

This demo requires a quick modern browser with support for the canvas tag and a fast computer. Google chrome seems to work best. Firefox is too slow. If it doesn't work make sure that your browser is not zooming in (hit ctrl+0 in chrome and firefox).

How it works

cubemap The frames are renderer using a technique called raytracing. The environment is mapped using cube mapping. I store all the values of the cubemap as floats. I increase the definition range by multiplying all values bigger than 0.95 with 2. This makes sure that the bright parts of the image are also very bright in the reflections. You can think of this as faking hdr. I do not calculate any lighting, it is all coming from the environment map. To make the animation look a bit more fluid and hide the aliasing I apply some fake motion blur by blending the current frame with the previous one. Feel free to ask questions if you want to know more.

Source

You can view the sourcecode here: rtrt.js. Feel free to copy from it, but please let me know if you use it for something cool. :) Also beware that the code is pretty hacky and unpolished.

Other Experiments

Be sure to check out my other experiments too. If you like what you saw you should subscribe to my newsfeed or follow me on twitter.

Credits

The environment map was created by Paul Debevec of the ICT Graphics lab. You can find his collection of light probes here. Thanks for letting me use it.

Path tracing a cornell box in Javascript

Last Saturday I have released my little javascript pathtracer that rendered a very simple scene. This time I want to show off some of the more advanced effects that can be simulated nicely using path tracing. I decided to set up a scene similar to the well known Cornell Box to demonstrate effects such as soft shadows, color bleeding, reflection, refraction and caustics. I did not include Depth of Field in this experiment because it didn't fit the scene well in my opinion.

The experiment

cornell box

Click the image to start the rendering. Warning, this experiment is slow. Run it using a fast web browser (google chrome) and be a little bit patient. Opera won't work because it doesn't support web workers.

You might also want to check out my previous path tracing experiment.

Path tracing

Path tracing is a way of solving the rendering equation using monte carlo integration. It is a form of ray tracing. According to wikipedia 'Path tracing is the simplest, most physically-accurate and slowest rendering method'. Sounds like the perfect target for a javascript experiment!

Implementation

The implementation is basically an extended version of the path tracer in my last post. It is using html5 web workers to render the image on up to 4 cores without locking up the page. One of the cool things I came up with is jittering the points on the view plane for each pixel to get rid of aliasing. I also changed the color of the light to that of warm sunlight (~5400k). I probably got the fresnel equations wrong and generally things are quite rough. I'm not an expert in the field of raytracing and I probably did a lot of things in a suboptimal way. But feel free to have a look at the source code (~300 LOC) and ask questions. I think the code should be quite easy to understand.

Please write a comment if you've got anything to say. If you think my experiments are interesting, follow me on twitter or subscribe to my atom feed.

Path tracing in Javascript using web workers

Improved version

An improved version of this path tracer is available here.

The experiment

screenshot

Click to start. If it doesn't work in your browser and it's not IE or Opera, please write a comment. The output of the javascript error console would be very helpful too.

Path tracing

Path tracing is a way of solving the rendering equation using monte carlo integration. It is a form of ray tracing. According to wikipedia 'Path tracing is the simplest, most physically-accurate and slowest rendering method'. Sounds like the perfect target for a javascript experiment!

Implementation

My implementation is currently only calculating the diffuse term of the rendering equation. The only light source is the sky. The big sky speeds up the rendering and convergence quite a lot.

The sourcecode is split up into two files. main.js is the glue for initializing the workers and aggregating the results. worker.js is where you'll find the real meat. I'm spawning four workers right now to take advantage of modern multicore cpus. Feel free to ask questions if something is unclear.

Performance

As you can tell from the sourcecode it is clearly not optimized for performance. What is still interesting though is how various webbrowsers perform. On my Intel Core i7 machine google chrome (4.1) is roughly 26 times faster than firefox (3.6)! Chrome does 13 iterations/s, Firefox does 0.5. Also firefox seems to support only 3 workers, this leaves one core almost idle. The dev version of chrome is even faster at 18.75 iterations/s. My congratulations to the chrome and v8 developers. I hope firefox will catch up soon.

Twitter

On a side note, I created a twitter account for those who prefer it over the rss/atom feeds.
Follow 29a_ch on Twitter

Update

I found a little bug in the code that affected the performance. I'm now getting more than 20.5 iterations/s in chrome dev. I think a faster random function would make it even faster.

Box2Dflash Version 2.0 ported Javascript

Please note that this is experimental code! If you use this please let me know and give Erin Catto and me some credit.

Some weeks ago I wrote a script to convert version 2.0.2 of Box2DFlash to Javascript. I hesitated to release it because it is basically one big nasty hack that just happens to work. But as I got a few requests for it so I decided to release it. Please let me know if you do something with it. :)

Demo

Screenshot

You can see a demo of it in action here. You can click to trigger an explosion. On my notebook the demo runs fluidly in chrome. In firefox 3.5 it is pretty slow. In the current nightly it runs smooth as well. So I guess firefox is slowly catching up. Oh and just forget about IE.

Approach

At first thought this conversion would be trivial as both actionscript and javascript are dialects of ECMAScript. Well, I was wrong. Nevertheless I continued to follow my regex based approach, basically trying to ram my head through a wall. After a few attempts I succeeded to convert Box2DAS3 to javascript. It had a nasty bug tough. Two solid cubes were able to penetrate each other when the fell on their edges. The reason? ActionScript supports 'properties'. I didn't know about this and the conversion script does not support it. In the end I fixed the few properties in the translated code by hand because I was to lazy to add support for getters and setters to the conversion script. Now it seems to work pretty well. Please keep in mind, this is not a generic actionscript to javascript compiler, it's just a script that happens to work for box2dflash.

The explosions in the demo are simulated by shooting out a few tracer particles with a high density and velocity. The benefit over just applying an impulse to each object is that the strength of the impulse is proportional to the surface area. Also the force of the explosion will to some extend be redirected to the side by the floor. When using this in production code you would probably want to destroy this tracer particles after their first collision or a few seconds.

Please keep in mind, I'm not an expert on the subject. There are probably better and faster ways to approximate this than my crude way of using tracer particles (Navier-Stokes in javascript anybody? ;) ). Maybe I'll try to do some fluid dynamics on the gpu using webgl some day. It would be cool for sure.

Compiled Script

I compiled a single file version of the script using googles closure compiler. box2d.js.

Complete Zip

The zip file contains the actionscript source, the conversion script and a patch to fix some of the things the conversion script misses. box2d2.zip

Github

github.com/jwagner/box2d2-js

Documentation

I didn't write any. But you can use the documentation of box2dflash.

Author

Jonas Wagner Jonas Wagner
Software Engineer
Zürich, Switzerland

More about me

Follow 29a_ch on Twitter

Experiments

screenshot screenshot screenshot screenshot

More Experiments

Latest Posts Tags Archive Links

guitarmasterclass.net (guitar lessons)