Planet WebGL

January 20, 2012

Learning Three.js

Casting Shadows

This post is about shadow casting, a technique which approximates the effect you see in real life everyday. They may be tricky to tune but they looks so good, it worths it. Shadows are an efficient tool when you to make your scene more realistic. We will see how they can be used inside three.js and see more about lights while we are at it.

As usual, there is a demo. It is kept it real simple thus you can read the code more easily. The scene is a simple object in the middle, a spotlight moving around and a plane to receive the object shadow. The light frustum is left visible in orange.

<iframe allowfullscreen="allowfullscreen" frameborder="0" height="420" mozallowfullscreen="mozallowfullscreen" src="http://learningthreejs.com/data/casting-shadows" webkitallowfullscreen="webkitallowfullscreen" width="100%"> </iframe>

Let's Code Shadows

Casting shadows in three.js involves 3 parts: the renderer which does the computation, the lights which cast shadows, and objects which receives lights and shadows.

Set up the Renderer

The renderer is the one which will compute the shadows positions for your 3D scene. Shadow casting is quite expensive. It is only supported by WebGLRenderer. It uses Shadow mapping, a technique specific to WebGL, performed directly on the GPU.

```javascript

renderer.shadowMapEnabled = true;

```

You can smooth produced shadows with shadowMapSoft. It default to false. On the left, the shadow is crisp, on the right it is soft.

```javascript

// to antialias the shadow
renderer.shadowMapSoft = true;

```

Configure your objects

For Object3D, two parameters controls how they interact with lights and shadows. Set .castShadow to true if the object occludes light, so to cast a shadow. Set .receiveShadow to true if the object is supposed to receive shadows. Both default to false

```javascript

object3d.castShadow = true;
object3d.receiveShadow  = false;

```

This is the configuration for the central object in the demo. It will occlude lights but won't be able to receive shadow. So you wont see any self shadow.

Tune your Lights

THREE.DirectionalLight or THREE.SpotLight are able to cast shadows. Let's details them. A directional light is when light rays are parallel. A bit like when you look at the sun rays on the left. It mostly behaves like a light source very far from us. A spot light is when light rays seems to originate from a single point, and spreads outward in a coned direction, like in the dance club on the right (Images are from wikipedia). To enable the shadow casting on a light, just use this line.

```javascript

light.castShadow = true;

```

You can tune the shadowDarkness. It is the opacity of the shadow. 0 means no shadow, 1 means pure back shadow.

```javascript

light.shadowDarkness = 0.5;

```

In the same vibe, it possible to show the shadow camera on the screen with shadowCameraVisible. A very usefull feature during tuning or debugging.

```javascript

light.shadowCameraVisible = true;

```

More of Directional Lights

Additionally, when casting shadow with a THREE.DirectionalLight, you need to setup an orthographic camera. What is that ? it is a different form of 3D projection. Perspective is the way we see things in real life. So it seems more natural to us than orthographic projection. On the left, an illustration shows a perspective projection. You can see what is inside the orange shape. On the right, the same for a orthographic one.

Recent three.js r47 release includes a very didactic example from alteredq. Play with it, it may understand the difference between orthographic and perspective cameras. Here is a possible configuration of the frustum for the orthographic camera of our light.

```javascript

light.shadowCameraRight     =  5;
light.shadowCameraLeft      = -5;
light.shadowCameraTop       =  5;
light.shadowCameraBottom    = -5;

```

Conclusion

This is it, you can code shadow casting in three.js now :) Go ahead and play with them. They are hard to master but very efficient visually. Keep in mind that those shadows aren't real. They only uses 'some tricks' to make them appears as real. And they do so in real time !! To achieve this result, they take significant shortcuts which produce artifacts. To avoid those require tuning and experience.

That's all for today folks. Have fun.

January 20, 2012 01:44 PM

January 19, 2012

Learning Three.js

Boilerplate Builder for Three.js

We recently introduced a boilerplate for three.js in a previous post. It aims to ease your first contact with three.js. It contains a template for a simple project, a sample on which we already applied good practices. You download it and run it in a matter of minutes. Thus you can immediatly focus on your own things. In short, it aims for Fast bootstrap + Good Practices.

It seems nice, hey ? Well there is a glitch. The boilerplate for three.js needs more flexibily. In a way, it acts as a ground on top of which you start your own thing. We do our best to provide good defaults, but they are only defaults. What if you got specific requirements ? How to start your project then ? The boilerplate builder has been written for you :)

Try it out. Go ahead, play with the options, discover what they do and customize your own boilerplate. The screencast below is short introduction where i describe the boilerplate builder.

<iframe allowfullscreen="allowfullscreen" frameborder="0" height="349" src="http://www.youtube.com/embed/ANnPWZGRsGk?hl=en&amp;fs=1" width="425"></iframe>

Making-Of the Builder

The builder itself was interesting to build. It uses various nice features from the current web. It is a pure-browser webapp with a file download, a preview of a webgl project and a nice looking visual appearance.

Pure Browser Download

I like to write pure-browser application. They dont require a server to run, only static files. It makes it much easier to host your application. So boilerplate builder has been written as a pure-browser application :) It uses jszip , a library which create .zip files with Javascript. Its creates the boilerplater.zip that you download. Additionally, it uses downloadify , a small library to create and download files without server.

Together, jszip and downloadify makes it easy to pack several files together, and allow the user to download it. All that in pure-browser, neat no? I love what the web is becoming!

Boilerplate Preview

The preview is a bit different. We start to load the index.html template for the boilerplate. We apply all the options you configured and produce the final version. To actually preview this file, we encode it in base64 to build a data url with it. Only then, we create an iframe with this data uri and you can see the webgl preview :)

Data url is an old thing from 1998 which is back in spotlight due to HTML5. It allows to encode data directly in the URL. It may be used to include image directly in css for examples. Very usefull but not for human consumption. To give you an idea, here is index.html as a data url in base64. You could encode it as text if you escape it properly. It looks like long ugly random string.

```

data:text/html;base64,PCFkb2N0eXBlIGh0....

```

Visual Appearance

It includes twitter bootstrap for css. I am quite grateful for this framework. Without it, the builder page will be so ugly, that people run away without even trying the application itself. twitter bootstrap makes it so easy to write a webapp which looks good on the screen. I think all the css-impaired of the world should thanks twitter for this framework :)

Conclusion

It has been quite fun to write it. I learned some web skills, discovered new part of three.js, and on top of that, it looks good on screen. I could not ask for more. The goal of boilerplate builder for three.js is to add more flexibility to the fast bootstrap + good practices from the boilerplate. I hope it will help people starting lots of new three.js projects :)

That's all folks. Have fun.

January 19, 2012 09:59 AM

January 17, 2012

Learning Three.js

Dom Events in 3D Space

Ever dreamed of a object3d.on('click', function(){ ... });?

I have :) This post presents a little experiment. What about implementing the concept of dom events in 3D Space. In a web page, a click event is trigger when a user click on a element. This is common knowledge in web development. What about having that but in a three.js scene ? Maybe people will start do 3D user interface with that, who knows. How great would that be ?!? So let's do that.

Try it out. The demo contains 3 teapots. Each bind a different type of events. When the events are triggered, teapots are animated. Animations are made by tween.js, a nice js tweening engine seen in a previous post. Play with it to get a feel of it, maybe think about the type of UI you could do in 3D.

<iframe allowfullscreen="allowfullscreen" frameborder="0" height="349" src="http://www.youtube.com/embed/c2KLj8sie9Q?hl=en&amp;fs=1" width="425"></iframe>

Let's Get Started

First let's include the source. You download threex.domevent.js. and copy this line in your page.

```html

<script src='threex.domevent.js'></script>

```

Let's Use It

<iframe allowfullscreen="allowfullscreen" frameborder="0" height="315" mozallowfullscreen="mozallowfullscreen" src="http://jeromeetienne.github.com/threex/examples/threex.domevent" style="float: right; margin-left: 1em;" webkitallowfullscreen="webkitallowfullscreen" width="420"> </iframe>

Let's say we want do to an action when the user is clicking on a object. We just do the following.

```javascript

mesh.on('click', function(){
    mesh.scale.x *= 2;
});

```

This short line means "if the user click on this mesh, make it twice wider". Eloquent meaning, short syntax ... pretty sweet in my book. If you wish to stop listening just do as usual.

```javascript

mesh.off('click', callback)

```

In fact, there is 2 naming for those functions: one is addEventListener / removeEventListener from HTMLElement The other is copied on jQuery api: on / off Pick the one you like. They are doing the same thing.

Always in a effort to stay close to usual pratices, the events name are the same as in DOM. The semantic is the same too. Currently, the available events are click, dblclick, mouseup, mousedown, mouseover and mouse out.

Some Internals

three.js already has the ability to interact with the mouse. You can see it in action here and here. Internally they use 2 three.js classes: THREE.Projector and THREE.Ray. threex.domevent.js is an higher level api on top of those functions, an interface which mimic dom events, something closer to the usual web developper.

It is a nice api. clean, short, object oriented and feels familiar to web developpers. A little hichup tho, it modifies THREE.Object3D class. It is a global class, so it may be legitimatly considered unclean by some people. If this bother you, simply do THREEx.DomEvent.noConflict() and use the standalone API. It is documented in the annoted source. In fact, the object oriented API is just a thin wrapper on top of the standalone API.

Conclusion

We all know the click event when the user click on a webpage. This experiment wishes to provide to web developpers the same experience in 3D. I hope people will do crazy innovations by using 3D in user interfaces. This is a first version. Maybe we will implement bubbling in the future, even events like 'change'.

As usual, threex.domevent.js source is available on github. There is an annoted source for implementation details. That's all folks. Have fun.

January 17, 2012 10:56 AM

January 11, 2012

Learning Three.js

Tunnel Effect for your Demo

This post presents a tunnel effect. This is a classic in 3D demo. They are visually efficient and easy to code. In fact, tunnels are so trendy that even doctor who and stargate have fun in them :)

Try the demo. It has been built using the boilerplate for three.js seen in a previous post. The code is simple and small. Less than 20lines has been added on top of the boilerplate. We will create a THREE.Geometry to get the shape of tunnel. Then we will use a texture trick to create the visual illusion of moving.

<iframe allowfullscreen="allowfullscreen" frameborder="0" height="420px" mozallowfullscreen="mozallowfullscreen" src="http://jeromeetienne.github.com/tunnelgl/" webkitallowfullscreen="webkitallowfullscreen" width="100%"> </iframe>

Let's build the walls

The first step is to build the walls of the tunnel. It is easier that one would expect. A tunnel may be seen as a cylinder with the camera inside. Once you realized that, most of the work is done. Luckily for us, three.js got an easy way to build cylinders, called CylinderGeometry. Nevertheless our tunnel / cylinder got 2 special points.

First, it is open-ended. So we must not build its top and bottom. We need this to see thru its extremities. This is handled by a parameter in CylinderGeometry. We just set openended parameter to true and the rest is done for us :)

Second, the camera is usually located outside of objects. But our tunnel/cylinder has the camera inside it. To make our object visible from the inside, we need to turn it inside out. For that, just use mesh.flipSided = true

Let's go forward

Now we need to go forward in this tunnel For that we will use an old trick. We won't move the tunnel walls themselves, only their appearance. It gives the visual illusion that we are moving. Remember what they say in matrix ? "there is no spoon". It is all the same, we are moving while staying still :)

<iframe allowfullscreen="allowfullscreen" frameborder="0" height="349" src="http://www.youtube.com/embed/dzm8kTIj_0M?hl=en&amp;fs=1" width="425"></iframe>

A Texture isn't a spoon

First we want to move the appearance of the cylinder, thus the player got the illusion to go forward. We will use THREE.Texture for that. We wont move the actual pixels of the textures, only its coordinates. Additionnaly we want the texture to repeat on the cylinder, thus it appears as continuous. WebGL texture is a powerfull and flexible tool. You can tweak so many features.

First let's make this texture move. Suppose we want the texture to loop once every 10 seconds. So the coordinate .offset.y needs to go from 0 to 1 in 10 seconds. This line is enougth to make the tunnel move forward. You can change your speed within the tunnel by changing this number.

```javascript

texture.offset.y    += 0.1 * seconds;

```

Now the texture repetition. For that we will use a texture parameter called wrap. It indicates how the gpu repeat the texture on a face. Here is a good tutorial on opengl wrap. By default, wrapS / wrapT are set to THREE.ClampToEdgeWrapping. So the texture is scaled to match exactly the size of the face. In our case, we want to repeat the texture and not scale it. So we use THREE.RepeatWrapping.

```javascript

texture.wrapT   = THREE.RepeatWrapping;

```

Conclusion

We have seen how to do a tunnel with three.js. This is very simple to code and awesome on the screen. It is less than 20 lines added to the boilerplate. The cylinder geometry was already provided. We used THREE.Texture offsets to provide the optical illusion of moving.

Later, we may add a blue phonebooth and play doctor who :) The code is available on github under MIT license. Feel free to fork and modify. That's all folks, have fun.

January 11, 2012 12:00 PM

December 28, 2011

Learning Three.js

Let’s Make a 3D Game: Supporting Mobile

This post is about supporting mobile. We will try to port marblesoccer on mobile. When doing a boilerplate for three.js, mobile had to be supported for compatibility. So it gave me the idea of this post. What about porting our game on mobile ? Porting a 3D web game to mobile ? crazy :)

The desktop version looks kindof ok. What would be the result of this experiment ? Is that even possible ? What about usable ? This is the purpose of this experiment to find out.

<iframe allowfullscreen="allowfullscreen" frameborder="0" height="349" src="http://www.youtube.com/embed/Ow_ceac1aEE?hl=en&amp;fs=1" width="425"></iframe>

Mobile isn't desktop

Indeed... desktop and mobile are quite different plateforms. Which differences are relevant to us ? First, mobile network is bad, especially latency. So avoid download of long files, such as texture or sound. Here is a good talk on Mobile Web Performance. Another thing, mobile got no keyboard, no mouse, but a touch screen We need to get a game controller for this environement. We use virtualjoystick.js. See details in our previous post.

One big thing is that currently, on mobile, WebGL hasnt reached mainstream to say the least. No major vendor is shipping phone with webgl, so nobody or close get webgl on phone. So for our little experiment, we will display in Canvas 2D with THREE.CanvasRenderer.

Porting to canvas 2D

So what need to be done ? First step is to use the proper renderer when suitable. Second is fixing material and geometry to fit canvas2D renderer capability. Last step is to look for room of optimisations. Ok now let's intanciate the renderer. If webgl is available, use THREE.WebGLRenderer else use THREE.CanvasRenderer. Not too hard hey ? We already did that in the boilerplate for three.js

<iframe allowfullscreen="allowfullscreen" frameborder="0" height="315" mozallowfullscreen="mozallowfullscreen" src="http://marblesoccer.com?render=canvas&amp;bypasslanding=1" style="float: right; margin-left: 1em;" webkitallowfullscreen="webkitallowfullscreen" width="420"> </iframe>

We simplify geometry to reduce the number of polygon. For marble geometry, the sphere got 512 faces on webgl, and only 9 on canvas2d. Drastic :) What about material ? For webgl, we used phong for fancy lightings, We used textures for realistic effects. But with canvas2D, those technics cant be used. They are way too slow.

This is enougth to get it working. It display something reasonable on the screen at least. We sacrifice a lot tho, no more texture not fancy lighting. And now the bad new, it results in 3fps on my ipad2 ios4... ouch.

More measures

How come performances are so bad ? So i did more measures. I disabled the display of map and marbles to see how they impact performance. If we display the map and the marbles, we got 3fps on my ipad2. If we display only marbles, no more maps, we got 23fps, much better. but still not great... Considere that we are only displaying marbles and they are real simple.

If we display no marble, and no map. we got only 30fps. So all the rest, all the non display part is already using a big part of time ? what are we doing ? not much... Still we run realistic 3D physics and ipad2 cpu isnt as fast as usual desktop ones.

Time to optimize

Ok it is slow but this is a first try. I admit the code isnt not too optimized. cpu / gpu performance are so good on desktop, i may have been sloppy here and there :) There are areas of optimisations. We need to draw less polygons.

First we need to reduce the geometry of the map. We can do that by clustering voxels: if 2 voxels got the same color and touch each other, display one large box, instead of 2 small boxes. We did it to optimize our physics. See details in microphysics post. Additionnaly we could use marblesoccer's map editor to redesign a map with a simpler geometry.

Another low-hanging fruit is to remove faces which are never seen, like in minecraft example from three.js. We could try to 2D sprites instead of 3D spheres for marble. We wont use THREE.Sprite. It isnt supported THREE.CanvasRenderer. But dont worry, it is possible with the particle system. See how THREE.Particle is used in canvas_particles_sprites.html example.

Conclusion

And after all that, what can you expect ? Will that run at 60fps ? 30fps ? Not likely or it will require a lot of effort. So animations arent smooth, what about the look? Watch what you got on the screen... On the right, a canvas version. live here. On the left you can see a webgl version. live here. Lets face it... canvas version is ugly.

After a significant work, you get poor performance and crappy look. Not many players would accept that... currently canvas performance doesnt seems suitable to display 3D on mobile. It is a good way to monitor performances and see how they evolve with time.

December 28, 2011 12:46 PM

December 26, 2011

Learning Three.js

Let’s Make a 3D Game: Virtual Joystick

Here is another article of the "Let's Make a 3D Game" series. We have already seen how to handle other inputs like keyboard and device orientation. This post is about virtualjoystick.js It virtual joystick, another input you can use for your games. A virtual joystick emulates a joystick behaviour on a touch screen. virtualjoystick.js has been coded in a effort to port marblesoccer to mobile device. Show, dont tell, Try it out.

This demo works with mouse events too thus, it is easier to test/debug. virtualjoystick.js has been widely inpired by this post by Seb Lee-Delisle. The screencast below is short introduction about virtualjoystick.js

<iframe allowfullscreen="allowfullscreen" frameborder="0" height="349" src="http://www.youtube.com/embed/viyr_W0z1U8?hl=en&amp;fs=1" width="425"></iframe>

Let's Get Started

First step, you download virtualjoystick.js from its github Then include it in your own code.

```html

<script src="virtualjoystick.js"></script>

```

The joystick is composed of 2 parts: the base and the stick. First the plare touch the screen, it gives the position of the base. Then it drags its fingers to gives the position of the stick

Let's Use it

<iframe allowfullscreen="allowfullscreen" frameborder="0" height="315" mozallowfullscreen="mozallowfullscreen" src="http://jeromeetienne.github.com/virtualjoystick.js/" style="float: right; margin-left: 1em;" webkitallowfullscreen="webkitallowfullscreen" width="420"> </iframe>

First step is to create the object from VirtualJoystick class.

```javascript

var joystick = new VirtualJoystick()

```

The constructor has some options. They have sensible default. You can change them to fit your specific needs. See github README for a full API description. You may look at the index.html. It is an example which uses the library.

It is possible to read analogic coordinates. joystick.deltaX() gives the delta x between the base and the stick in pixel. joystick.deltaY() gives the delta y. Those analogic coordinates may be interpreted as a joystick with 4 switches. Similar to arrow keys in a way. joystick.up() tells you if your joystick is up or not. You guessed the meaning of .down(), .right() and .left().

Conclusion

The source is available on github under MIT license. Later, a button may be implemented as well. It is alway usefull to able to fire in video games :) That's all folks, have fun.

December 26, 2011 11:21 AM

December 20, 2011

Learning Three.js

Boilerplate for Three.js

This post presents boilerplate for three.js. I looked at html5 boilerplate and found it awesome. html5 boilerplate is a fast way start a clean project. It avoids repetitive tasks, following DRY principles. It includes all those good practices, which are so easy to forget. It seems all good to me :) boilerplate for three.js tries to apply similar principles. I frequently write simple three.js demo for tutorials, and repeat the first steps way too often for my tastes :) It has been done in effort to make 3D on the web even easier.

Try it out. "Boilerplate for three.js is a web template for a fast, robust and future-proof site. Boilerplate is not a framework, nor does it prescribe any philosophy of development, it's just got some tricks to get your project off the ground quickly and right-footed." - freely adapted from html5 boilerplate site.

Walkthrough

This project is at an early stage. Dont hesitate to suggest improvements or bug fixes in github issues. It has been done to run everywhere, and to promote good practices. The screencast below will walk you through the source of the project. 22min... a long one :)

<iframe allowfullscreen="allowfullscreen" frameborder="0" height="349" src="http://www.youtube.com/embed/kOReCN5t2Eo?hl=en&amp;fs=1" width="425"></iframe>

Compatibility is key

It has to run everywhere. We believe that compatibility is crucial on the web. The boilerplate seamlessly works on desktop and mobile. It is working on webgl/canvas2d and supports mouse/touch events.

It renders on webgl if available, else it fallbacks on canvas2D. It is often forgotten, but three.js is able render on various backends, they are called renderers. It isnt always possible to fallback tho. Materials are especially sensible to the type of renderer you use. For examples, many materials are webgl specific as they contains shaders and canvas2D got no shaders. Up to you to find the balance that fit your needs.

The camera controls is rather basic. If you need a different controls for your camera, pick one in this list. This one is simple to use and understand, a nice feature for a boilerplate. It supports mouse events and touch events. So you can run with a touch screen with a glitch.

Good Practices

Some features have been added: fullscreen, screenshot and window resize. I consider them good pratices which are often forgotten. Some numbers based on three.js examples: 128 examples total, 26 of them handle touch events, 11 handle window resize, 2 handle screenshot, 0 handle fullscreen.

<iframe allowfullscreen="allowfullscreen" frameborder="0" height="315" mozallowfullscreen="mozallowfullscreen" src="http://jeromeetienne.github.com/threejsboilerplate" style="float: right; margin-left: 1em;" webkitallowfullscreen="webkitallowfullscreen" width="420"> </iframe>

Fullscreen is supported to enjoy your 3D on a large display without visual distraction. If you press f, your demo will go fullscreen. For technical details, see "Make It Fullscreen" post.

Screenshot makes it easy to share the image as what you see on the screen at a given moment. If you press p, a new tab will open with a screenshot of the rendered content. For technical details, see "screenhot in javascript" post. It it usefull to share nice images and to help debug on various plateforms.

Window resize is supported because it is required. Without it, your 3D scene will loose scaleing and center when you resize the window or go fullscreen. For technical details, see "window resize your demos" post.

How to use it ?

It is quite simple, first you download the code as a .zip file or with the git command line below.

```

git clone git://github.com/jeromeetienne/threejsboilerplate.git

```

then start updating index.html to fit your needs. Below is a screencast where i use the boilerplate to display a teapot in only 3min! Why a teapot ? Because it is the "hello world" of 3D :) Be warned, the video is a bit speedy, im just starting at doing screencast. Next ones will hopefully be slower.

<iframe allowfullscreen="allowfullscreen" frameborder="0" height="349" src="http://www.youtube.com/embed/0XPOCi6FJX0?hl=en&amp;fs=1" width="425"></iframe>

Conclusion

Later, it may be cool to have a builder. I think it may be possible to make it client only. jszip library would create the zip containing all the files. shorttag.js library would compile templates according to user needs. A builder would produce a cleaner and smaller result for you to play with.

I gave a short talk at parisjs about it, here are the slides. I hope boilerplate for three.js. will help make three.js even easier to use. This project is quite new and will likely improve soon. That's all folks, have fun :)

December 20, 2011 06:09 PM

December 19, 2011

Learning Three.js

Particles: Online Editor for Sparks.js

This post is the second of our serie on particles. It presents sparkseditor , an online editor for sparks.js with three.js. In a few word, it is a webpage which provide an text editor with a sparks.js effect. You got the code in the editor and you see live the resulting particles effect. I like this live aspect a lot :) I think it makes your design more direct, lower latency, less overhead. More creative in a way. Try it out.

This editor has been made to lower the barrier of entry on sparks.js with three.js particles. The UI is rather simple and obvious. You can find a small presentation in the screencast below.

<iframe allowfullscreen="allowfullscreen" frameborder="0" height="349" src="http://www.youtube.com/embed/nu00FhIW5bc?hl=en&amp;fs=1" width="425"></iframe>

Live editor rocks

Sparkseditor is widely inpired by glsl editor from mrdoob and shadertoy from Inigo Quilez. On the same vibe, lea verou recently released dablet, an online editor for css. There is a clear trend here... What is it about those live editors ? A live editor produces a result immediatly. This helps design your effect faster. Be light on your foot kindof style. Very agile way to design.

Additionally, it is easy to share with others because we have bookmarkability. We do that by storing state in url. On the down side, it makes super long+ugly urls... url shortening helps us reduces this issue. In our case, we use bitly service.

This editor is purely static files. No specific server to run, no need to admin and no risk to go offline. Oh and by the way i dont not even have to pay for hosting this application. I think it shows html5 in all its power. The web is becoming something real nice :) html5 i love you!

conclusion

Under the hood, sparkseditor uses threex.sparks.js, a threex helper, to make sparks.js even easier to use. This helper will be the subject of a future post of our particles series.

The source is open-source under MIT. You can get it in its git repository. If you hit bugs, fill issues on github. Feel free to fork and modify it! That's all folks, have fun :)

December 19, 2011 11:11 AM

December 15, 2011

Learning WebGL

WebGL around the net, 15 December 2011

by giles at December 15, 2011 02:10 PM

December 14, 2011

Learning Three.js

Particles: Introduction to Sparks.js

This post is the first of a serie on particles. It specifically is about sparks.js. sparks.js is lightweight 3d Particle system in javascript, for use with three.js and tween.js. It is from zz85 who already did 3D text and Catmull Clark subdivision. a productive guy :)

The demo below is one of the many three.js examples. While im on it, the example directory is a gold mine. Go dig in it to understand how to code three.js :) Back to the point, this demo is rather cool no ? You want to do the same ? During this short post, let me walk you walk thru the code for particles in this example.

<iframe frameborder="0" height="420" src="http://mrdoob.github.com/three.js/examples/webgl_particles_shapes.html" width="100%"></iframe>

Lets Get Started

So lets see how to use it. First step, you download sparks.js from its github. Then include it in your own code.

```html

<script src="Sparks.js"></script>

```

First a few words on what is a particle system. It is usually composed of 2 big parts: the emitter and the particle itself. Emitter creates particles. Particles are usually smallish objects on the screen. As you got many particles at the same time, they appears a single mass.

Let's create an emitter

First we create the emitter like this. emitter is the main object we will play with.

```javascript

var counter = new SPARKS.SteadyCounter( 500 );
var emitter = new SPARKS.Emitter( counter );

```

counter controls how frequently particles are created. Here it will emit 500 particles per seconds. Now let's start emit particles.

```javascript

emitter.start();

```

Sparks.js has a very flexible core. It mainly uses two stacks of functions. Initializers is the stack run at the creation of a particle. Actions is another stack which is run at every step of a particle life. Those functions are run in order. Up to you to configure them to fit your needs. You can easily code your own initializer or action. Dont worry it got a bunch of predefined ones.

Let's initialize

Lets me walk you thru the ones used in our example. The whole stack is below. emitter.addInitializer() to push a new initializer, and emitter.removeInitializer() to remove it, not too hard :)

```javascript

emitterpos = new THREE.Vector3( 0, 0, 0 );
emitter.addInitializer( new SPARKS.Position( new SPARKS.PointZone( emitterpos ) ) );
emitter.addInitializer( new SPARKS.Lifetime( 1, 15 ));
var vector = new THREE.Vector3( 0, -5, 1 );
emitter.addInitializer( new SPARKS.Velocity( new SPARKS.PointZone( vector ) ) );

```

SPARKS.Position(zone) initializer set the original position of the particle. A zone provide a location in space. new SPARKS.PointZone( emitterpos ) means the particles will always start from this specific point in space. It is possible to have other zones. For example, SPARKS.LineZone( startVector3, endVector3 ) represents a line between 2 points, so your particle would start anywhere on this line.

SPARKS.Lifetime(mintime, maxtime) initializer set particle's lifetime. You can specify a range and a random value will be assigned. Don't forget to add SPARKS.Age action to handle its lifetime. And the last one. SPARKS.Velocity(zone) set particle's velocity based on a zone location. The initializer stack is setup the particle at the begining of its life. Let's see what happen during this life.

Let's do some actions

Actions are performed at every step of a particle life. Same as with initializers, emitter.addAction() to push a new action, emitter.removeAction() to remove it. For our examples the whole action stack is this.

```javascript

emitter.addAction( new SPARKS.Age() );
emitter.addAction( new SPARKS.Accelerate( 0, 0, -50 ) );
emitter.addAction( new SPARKS.Move() );
emitter.addAction( new SPARKS.RandomDrift( 90, 100, 2000 ) );

```

Now lets details it. We have already seen SPARKS.Age(). It is handle the lifetime of each particle. SPARKS.Accelerate(x,y,z) changes the velocity by adding a fixed amount at every step. This one produces a gravity effect with a negative y. SPARKS.Move() makes the particles move in our 3D space. SPARKS.RandomDrift(x,y,z) changes the velocity by adding a random amount at every step.

Conclusion

I hope this short introduction got you excited about sparks.js. Next posts on the particle series may be a UI editor, stay tuned! I find sparks.js clean and flexible. Flexibility is very important for particles. It helps provide a wide variety of effect in your games/demos. For more informations and authoritative answer, see the github repository. That's all for today folks, have fun.

December 14, 2011 11:08 AM

December 10, 2011

Learning Three.js

Constructive Solid Geometry With csg.js

This post is about constructive solid geometry , an impressive word :) In fact, it is just a way to build complex objects from simpler ones. Those simple objects are assembled using operations such as union, difference and intersection. Recently Evan Wallas released csg.js, a clean self-contained library to do constructive solid geometry. So Chandler Prall wrote a bridge to make it easy to use with three.js. With all this nice code, i wrote the little demo of a dice you can see on the right. Thus you can click to change the operations, play with it and have a feel of the various operations. Let's start So lets see how to use it. First step, you download csg.js from here , ThreeCSG.js bridge from here . Then include those line in your own code. ```html <script src="csg.js"></script> <script src="ThreeCSG.js"></script> ``` Let's convert Ok now that we got the source, let's use it. ThreeCSG.js is a bridge between three.js and csg.js. Both libraries use a different format for geometry. ThreeCSG.js does the conversion back and forth. To convert your three.js geometry to a csg geometry, use this line. ```javascript var geometryCsg = THREE.CSG.toCSG(geometryThree); ``` Then you likely apply boolean operations on csg.js geometry. To convert it back to three.js, just do ```javascript var geometryThree = THREE.CSG.fromCSG(geometryCsg); ``` You end up with a normal three.js geometry than you can use everywhere, like GeometryUtils or Mesh. Let's assemble Now the fun part, lets assemble objects with those misterious boolean operations on ours csg.js geometries. There are 3 of them: difference, union and intersect. To build our dice, first we build a cube then we subtract a bunch of spheres to makes the holes. Once you converted your objects, you apply operations on them. For the dice, we use .subtract(). ```javascript cube.substract(spheres) ``` But it is possible to use .union() to add them. ```javascript cube.union(spheres) ``` Or to keep only the common part of both objects with .intersect(). You can chain those operations to your own taste. Up to you to be creative :) ```javascript cube.intersect(spheres) ``` Conclusion Constructive solid Geometry is simple and quite powerfull. csg.js , ThreeCSG.js and three.js makes it real easy to play with. You may look at the source of our dice demo to see a working version of this code. That's all for today, have fun :)

December 10, 2011 03:30 PM

December 08, 2011

Learning WebGL

WebGL around the net, 8 December 2011

A relatively quiet week!

by giles at December 08, 2011 02:50 PM

December 01, 2011

Learning WebGL

Retrospective changes to the lessons, part 94

WebGL is increasingly being supported on mobile devices. Firefox on my Android phone (a Samsung Galaxy S II) quite happily displays all of my tutorials, and many other WebGL sites as well. But not all mobile devices are equal; some quite popular ones apparently don’t support highp precision in fragment shaders.

The WebGL spec says that all implementations must support at least mediump, so it looks like that’s the most sensible precision to use as a default for most WebGL sites. I’ve changed the lessons here so that they use it. I also took the opportunity to get rid of some compatibility cruft that dated from the early days of WebGL: the #ifdef GL_ES that surrounded the precision qualifiers.

If you’ve got some WebGL demos out there, I strongly recommend you do likewise!

Many thanks to Ken Russell and Cedric Vivier for the heads-up about this.

[UPDATE: Cedric tweets that the precision operators have no effect on desktop machines right now anyway, so it sounds like there really is no downside to making this change.]

by giles at December 01, 2011 08:45 PM

WebGL around the net, 1 December 2011

by giles at December 01, 2011 02:08 PM

November 24, 2011

Learning WebGL

WebGL around the net, 24 November 2011

by giles at November 24, 2011 02:48 PM

November 21, 2011

Learning Three.js

Lets Make a 3D Game: Make It Embedded

This post is part of the "Let's make a 3D game" series. The previous post was on fullscreen API. Here is another one on resizing the display area. This post is about embedding your game in another page. It is usefull to include it in a blog, in facebook, iGoogle or other game plateforms. MarbleSoccer now contains all the tricks explained in this post. Show dont tell, you can see it embedded on the left. Embedding your game implies various things. As your game is hosted in another page, it likely got a smaller display area. HTML5 CSS media query makes it easy to fit various sizes. Another part are the DOM events from the iframe. They will be propagated to the host page and may produce undesirable effects. We see how to shield them. But first let's see about iframe Let's go play in an iframe iframe is an easy and secure way to embed a page in another. Let's declare it. ```html <iframe src="http://marblesoccer.com" allowfullscreen webkitallowfullscreen mozallowfullscreen width="480" height="320" frameborder="0"> </iframe> ``` The attributes are pretty classics: frameborder to remove an ugly default border, width and height for size and src for your game page. The ones ending with allowfullscreen tell the browser that this iframe is allowed to go fullscreen. More about fullscreen in this previous post or in the spec. You may need to determined if your game is embedded or not. Use this line will tell if it is in a iframe or not. ```javascript var isInIframe = (window != window.top); ``` Fit in a smaller display area When your game is embedded, it is likely to have a smaller display area. How to deal with this ? First, we have 2 types of rendering in our game: a 3D display where three.js displays the WebGL, and a DOM display for OSD such as score, timers and other popups. For 3D rendering, we have already seen window resizing in this post. Just download THREEx.WindowResize and add this line and you are done. Not too hard, hey. ```javascript THREEx.WindowResize(renderer, camera); ``` Now the DOM display. It may simply be done via CSS and media queries. Typically, you may reduce the size of your font or icons. I won't try to teach css, other do that much better than me. Just a pick of what i did, not sure at all it is the best way. I reduce the OSD display if your game page is 640px or less. ```css @media all and (max-width: 640px) { /* here put your style specific for embedded case */ body { font-size : 60%; } img { width : 48px; } } ``` Shield Events Strange section title, hey. It means prevents DOM events from the iframe to interfere with the host page. Not much clearer... Maybe with an example ? Let's see the arrows+scroll case. Show dont tell. Below are 2 iframes: on the left, no shielding happens, on the right shielding happens. Try to click on them and use arrows up/down. On the left, the host page scrolls, but not on the right. Why does this happen ? good question :) If our game iframe got the focus and users press up or down, the iframe will received keydown/keyup events. Up to now, all is ok... Troubles appear when those events are bubbling to the host page, they may trigger a scrolling. Imagine the page going up and down while you play, the game becomes unplayable very fast :) So here is the code which prevents this behavior. It listens to arrows keydown events. and prevent their default. ```javascript document.addEventListener('keydown', function(event){ // if it is keydown on a arrow, prevent default if( event.keyCode >= 37 && event.keyCode <= 40 ){ event.preventDefault(); } }, true); ``` Conclusion I gathered the code in threex.embedded, see its annoted source. Iframe is a easy and secure way to make your game embeddable. We have seen how to handle smaller display area with THREEx.WindowResize and media queries. Additionnaly we even shield DOM events, so we can use arrow keys for player control. You are all set! Go embed your game now :)

November 21, 2011 03:32 PM

November 20, 2011

Learning WebGL

Server upgrade

I’ve just upgraded the Learning WebGL server from Debian Lenny to Squeeze. It looks like everything went smoothly, but please do let me know if anything’s broken…

by giles at November 20, 2011 05:33 PM

November 17, 2011

Learning WebGL

WebGL around the net, 17 November 2011

  • An awesome demo from Florian Bösch — WebGL GPU Landscaping and Erosion. You’ll need a decent graphics card to be able to run the live version, though.
  • The Light is a new game by Stefan Wagner showing off WebGL, HTML5 Audio and the Fullscreen API
  • “The plants in the ECOSPHERE grow from your tweets tagged with #COP17.”
  • A nice demoscene production, using Three.js: Anaemia by Litewerx (via Photon Storm)
  • Not quite so pretty to look at, but technically incredibly impressive! Frank is a WebGL demo in 4kb, including visuals and music.
  • Shapesmith’s “aim is to make designing 3D printable models accessible to anyone with a modern browser”
  • A nice basic shader tutorial in .NET magazine by Bartek Drozdz.
  • Good news for SceneJS fans — the long-awaited version 2.0 has now been released. If focuses on “high rendering speed for complex scenes containing many individually articulated and pickable objects, which is characteristic of model viewing applications for engineering, architecture and medical visualisation.”
  • ThreeNodes.js is a graphical programming environment for building real-time interactive media, drawing inspiration from vvvv.
  • Illyriad’s first WebGL experiment was published last week; here’s an interesting follow-up post about their experiments with compressed textures.
  • WebCL looks like it’ll bring some amazing parallelisation features to JavaScript, but — like WebGL’s GLSL — coding it might be harder than you might like. River Trail, an Intel Labs project that pre-dates WebCL (but has a fork using WebCL as a back-end) adds much simpler-to-program parallelisation support, compiling JavaScript to OpenCL kernels. It has some way to go, but it’s very clever stuff.
  • If you want something a bit ahead of the current Firefox beta, but don’t want to have to go quite as far as a nightly build, you might want to try out Aurora — a new pre-beta channel. It’s currently at version 10 (as you’d expect, two versions ahead of the release version) and has some nice enhancements, including WebGL antialiasing.
  • Here’s the beginnings of a translation of my tutorials into Russian — just the first half of lesson 1 for now.

by giles at November 17, 2011 02:28 PM

Learning Three.js

Lets Make a 3D Game: Make It Fullscreen

This post is part of the "Lets make a 3D game" series. It is about the fullscreen API. This API allows to make DOM elements fullscreen. Fullscreen is quite important for games. It provides a larger display so a more immersive experience for your players. All that from javascript, so no more needed to ask "please f11" to your players, isnt that sweet ? :) The fullscreen API is still in discussion, but the basics are settled. At the time of this writing, it is available in firefox nightly, webkit nightlyand chrome stable. It has been already added in marbleSoccer. The icon is from The Noun Project, a source of nice and clean icons. Try it out! Click on it to toggle fullscreen state. If you dont see the icon, your browser doesn't yet have the fullscreen API. Ok now is time for code :) Let's get started As usual, i provide a little helper to make it easier for you to include it in your games. It is called THREEx.FullScreen.js. It hides the prefix of each vendor and the little discrepencies between their API implementation. You download this file from here and include it in your page like this ```html <script src='THREEx.FullScreen.js'></script> ``` How to use it ? The API is simple, only 4 calls. Lets see them one by one. To test if it is possible to have fullscreen on your system, do ```javascript THREEx.FullScreen.available(); ``` To test if fullscreen is currently activated on your page ```javascript THREEx.FullScreen.activated(); ``` To Request fullscreen on a given element, just do ```javascript THREEx.FullScreen.request(element); ``` If element isnt provided, it defaults to document.body. To cancel fullscreen on your page, use this line. ```javascript THREEx.FullScreen.cancel(); ``` Quite straight forward, no ? :) As an example, let's make a toggle, the same used in marbleSoccer. ```javascript if( THREEx.FullScreen.activated() ){ THREEx.FullScreen.cancel(); }else{ THREEx.FullScreen.request(); } ``` What about the standard ? There is a w3c proposal in dicussion. John dyer has written an in-depth summary. Mozilla provides details on their API. At the time of this writing It is available in firefox nightly, webkit nightly and chrome stable. Conclusion For more details on THREEx.FullScreen, see its annoted source. It is a simple to add in your game. It provides a more immersive experience to your players. On a related subject, we will soon likely do a post about embedding your game in another page. It is usefull when you want to include it in a blog, in facebook or other game plateforms.

November 17, 2011 06:59 AM

November 11, 2011

hacks.mozilla.org

Announcing Firefox Aurora 10

We’re happy to announce the availability of Aurora 10.
(Download and Test Aurora 10)

In additional to the normal improvements that you’ve come to expect like performance, security and bug fixes, Aurora 10 focuses in HTML5 enhancements.

New additions

Developer Tools

Aurora 10 also implements incremental enhancements like IndexedDB setVersion API changes. Ongoing detailed attention to evolving specifications help to keep Firefox at the front of the Web revolution. (Read more about IndexedDB on MDN.)

DOM

  • We now fire a “load” event on stylesheet linking when the sheet load finishes or “error” if the load fails.
  • We turn the POSTDATA prompt into an information page (when navigating in session history).
  • We only forward event attributes on body/frameset to the window if we also forward the corresponding on* property.
  • We no longer allow more than one call to window.open() when we allow popups.
  • We fixed a bug where a success callback never fired when a position update is triggered after getCurrentPosition().
  • We removed replaceWholeText().
  • We fixed an error with createPattern(zero-size canvas).
  • We now handle putImageData(nonfinite) correctly.
  • We now throw INVALID_STATE_ERR when dispatching uninitialized events.
  • We’ve made Document.documentURI readonly.
  • We fixed document.importNode to comply with optional argument omitted.

Web workers

  • We now allow data URLs.
  • We implemented event.stopImmediatePropagation in workers.
  • We made XHR2 response/responseType work in Web Workers.

Graphics

  • We implement the WebGL OES_standard_derivatives extension.
  • We implement minimal-capabilities WebGL mode.

JavaScript

  • The function caller property no longer skips over eval frames.
  • We fixed E4X syntax so that it is not accepted in ES5 strict mode.
  • weakmap.set no longer returns itself instead of undefined.
  • We implemented the battery API.

Offline: IndexedDB enhancements

  • IndexedDB setVersion API changes
  • Added support for IDBObjectStore/IDBIndex.count
  • Various methods accept both keys and KeyRanges.
  • Added support for IDBCursor.advance.
  • Implemented deleteDatabase.
  • objectStoreNames are no longer updated on closed databases when another connection adds or removes object stores
  • IDBObjectStore.delete and IDBCursor.delete now return undefined.
  • No longer throws an error if there are unknown properties in the options objects to createObjectStore/createIndex.
  • We now the errorCode to “ABORT_ERR” for all pending requests when IDBTransaction.abort() is called.
  • Fixed the sort order for indexes.

Layout

  • We have updated the current rule for handling malformed media queries.
  • We now support the HTML5 <bdi> element and CSS property unicode-bidi: isolate.
  • The CSS3 implementation now supports unicode-bidi: plaintext.

Media

  • Implemented Document.mozFullScreenEnabled.
  • Enabled the DOM full-screen API on desktop Firefox by default.

by jstagner at November 11, 2011 10:34 PM

November 10, 2011

Learning WebGL

WebGL around the net, 10 November 2011

by giles at November 10, 2011 02:35 PM

November 08, 2011

hacks.mozilla.org

Using CORS to load WebGL textures from cross-domain images

In Firefox, as well as in Chrome, it is now possible to load cross-domain images into WebGL textures, if they have been approved by CORS.

Most prominently, this feature allows for impressive 3D mapping applications such as Google MapsGL and Nokia Maps 3D.

What happened

Earlier this year, the Editor’s Draft WebGL specification got updated in response to a security concern. The additions were:

  1. A mandatory clause disallowing usage of cross-domain elements as WebGL textures in the general case.
  2. A non-normative clause specifically allowing cross-domain elements that have CORS approval. For that occasion, the HTML specification on the <img> element got updated to add a new crossorigin attribute.

The first got implemented in Firefox 5, the second is now in Firefox 8.

How to use this feature

There are two CORS modes: “anonymous” and “use-credentials”. We’ll focus on “anonymous” as it’s the common case. A great example of images served with anonymous CORS is Google Maps imagery, such as:

http://khm0.googleapis.com/kh?v=95&x=0&y=0&z=0

In order to load it with CORS as a WebGL texture, we set the crossOrigin attribute on it:

var earthImage = new Image();
earthImage.crossOrigin = "anonymous";

Now we load it as usual:

    earthImage.onload = function() {
      // whatever you usually to do load WebGL textures
    };
    earthImage.src = "http://khm0.googleapis.com/kh?v=95&x=0&y=0&z=0";

That’s it! Aside from setting the crossOrigin attribute, we didn’t have to do anything. Here is the full self-contained example.

The HTTP headers

If we study the HTTP headers for this image (using, for example, Firefox’s Web Console), we find that the Request Headers contain

Origin: null

which is the effect of having set this crossOrigin attribute on the img element. And the Response Headers contain

Access-Control-Allow-Origin: null

which is the effect of the server supporting CORS for this file.

Doing this in HTML

Of course, one could also set this attribute in HTML, in which case it’s case-insensitive:

<img src="http://khm0.googleapis.com/kh?v=95&x=0&y=0&z=0" crossorigin="anonymous">

And since “anonymous” is both the missing-value-default and the invalid-value-default for the crossorigin attribute, we can pass any invalid value for it, or even just omit its value:

<img src="http://khm0.googleapis.com/kh?v=95&x=0&y=0&z=0" crossorigin>

Coming soon: CORS approval for Canvas 2D drawImage

What if you first draw a CORS-approved cross-domain image onto a 2D
canvas, and then use that canvas as the source of a WebGL texture? The
good news is that this will work in Firefox 9, which is hitting the Beta
channel soon. This fix means that demos like this will work really
nicely in Firefox 9.

by Benoit Jacob at November 08, 2011 03:43 PM

November 03, 2011

Learning WebGL

WebGL around the net, 3 November 2011

Lots of good stuff today!

by giles at November 03, 2011 03:06 PM

November 02, 2011

Learning Three.js

Lets Make a 3D Game: microphysics.js, even easier

This post is part of the "Lets make a 3D game" series. It is a follow up from the previous article on microphysics.js. It will describe how to easily include microphysics.js in your three.js games. THREEx.microphysics.js is a THREEx wrapper for microphysics.js. It helps binding three.js objects to microphysics.js. The API is chained for convenience.

Let's get started

So lets see how to use it. First step, you download it here. Then include it in your own code with this line.

```html

<script src="THREEx.microphysics.js"></script>

```

Initialisation

You instanciate the physics engine, like that.

```javascript

var microphysics = new THREEx.Microphysics(opts);

```

opts is optional. opts.timeStep controls the frequency of the world update. The smaller it is the more accurate is the physics but the longer it is to compute. It defaults to 1/60. Once instanciated, you start it.

```javascript

microphysics.start();

```

Binding THREE.Mesh

Of course we need to add some mesh in the world. After this line, the mesh is bound to microphysics.js, so its position is driven by the physics.

```javascript

microphysics.bindMesh(mesh, opts);

```

mesh.position is honored. If you need to unbind a mesh, just do

```javascript

microphysics.unbindMesh(mesh);

```

At the time of this writing, microphysics.js support only moving sphere and static boxes, so geometry may only be THREE.SphereGeometry or THREE.CubeGeometry. If your mesh got another geometry, use opts.geometry to say how you wish the mesh to be handled.

```javascript

microphysics.bindMesh(mesh, {
     geometry   : new THREE.CubeGeometry(200,200,200);
});

```

It is also possible to overwrite Mesh.position with opts.position, or to send options directly to microphysics.js with opts.physics.

```javascript

microphysics.bindMesh(mesh, {
    // to overwrite the Mesh.position
    position    : { x : 1, y : 1, z : 2 },
    // to pass options directly to microphysics.js
    physics     : { restitution : 0.98 }
});

```

Updating the physics

In your render loop, just add this line. It will first update the physics world and then move accordingly any THREE.Mesh you bound.

```javascript

microphysics.update();  

```

Needs a Direct Access ?

If you need to have direct access to microphysics.js, uses microphysics.body(mesh) to get the vphy.Body bound to mesh. To access vphy.World, just use microphysics.word().

Conclusion

In the previous article on microphysics.js, we learned how to use microphysics.js directly. This article makes it really easy to include in your three.js demo/game. It is so nice that it is what is used in the playground. That's all for today folks. Have fun :)

November 02, 2011 05:16 PM

October 28, 2011

hacks.mozilla.org

Beam me up, Scotty – bringing HTML5 to the enterprise

The last few days I was busy talking to in-house developers at two large enterprise companies, Sabre in Poland and SAP in Germany. Both these companies approached us asking for a talk about HTML5 as the topic gets a lot of interest in the upper echelons and there is a lot of confusion about it.

As we were in Poland anyways to attend Frontrow it was easy to visit Sabre and give a one hour presentation on the ins and outs of HTML5 and where the web might go. The day after the same talk was repeated over Skype for the German office of SAP.

In the one hour presentation we covered:

  • the basics of HTML5
  • what it meant as an evolution of markup
  • what HTML5 is not
  • common HTML5 myths
  • “Friends of HTML5″ – related technologies and
  • what the future of web technologies could look like

The slides are available online or embedded below (cursor keys to navigate, press N to show and hide notes and cursor down to proceed on slides with bullet points):

<iframe src="http://icant.co.uk/talks/what-is-html5/#1" style="border:none;width:100%;height:400px;"></iframe>

The audio recording of the talk is available on archive.org.

<audio controls="controls" preload="metadata" style="display:block;margin:1em;"><source src="http://www.archive.org/download/Html5101-WhatItIsWhatItIsntAndWhereItMightGo/WhatIsHtml5.mp3" type="audio/mp3"></source><source src="http://www.archive.org/download/Html5101-WhatItIsWhatItIsntAndWhereItMightGo/WhatIsHtml5.ogg" type="audio/ogg"></source></audio>

The slides and the audio is licensed with Creative Commons, so feel free to re-use and distribute them.

by Chris Heilmann at October 28, 2011 01:08 PM

October 27, 2011

Learning WebGL

WebGL around the net, 27 October 2011

by giles at October 27, 2011 03:11 PM

October 26, 2011

hacks.mozilla.org

Debugging and editing webpages in 3D

Tilt is a Firefox addon that lets you visualize any web page in 3D. A new update is available, coming with more developer-oriented features. Try the addon.

<object height="375" width="500"><param name="movie" value="http://www.youtube.com/v/_7eG_PONHRw?version=3&amp;feature=oembed"><param name="allowFullScreen" value="true"><param name="allowscriptaccess" value="always"><embed allowfullscreen="true" allowscriptaccess="always" height="375" src="http://www.youtube.com/v/_7eG_PONHRw?version=3&amp;feature=oembed" type="application/x-shockwave-flash" width="500"></embed></object>

Since the first alpha version of Tilt was announced (a Firefox extension focused on creating a 3D visualization of a webpage), a lot of work has been done to add a great number of developer-oriented features. These focus on debugging the structure of a webpage, inspecting styling and attributes for each node and seamlessly refreshing the visualization when the DOM structure changes or after contents of document are repainted.

Solve nesting problems

Tilt is useful when searching problems in the HTML structure (like finding unclosed DIV elements for example) by providing the extra third dimension, layering each node based on nesting in the DOM tree. Stacks of elements visually represent branches in the DOM, and each node can be inspected for the inner HTML contents, its computed CSS style and the attributes.

Clicking anywhere on the visualization highlights a color-coded rectangle surrounding the corresponding node. Double click shows up the source preview for that node. Tilt also tries to show the most relevant information when needed (one is most likely to inspect the attributes of an input, button or image element, for example, but can easily switch between HTML, CSS and attributes view at any time).

Minidom map

The “minidom” is a tree view representation showing a minimalistic snapshot of the document object model. Each node is assigned a color associated by tag name (blue for div, green for span etc.) and represented as a strip, along with visual markers for the id and/or class if available. Each one of these strips also has a width relative to the type, id and class name length for the respective element, and the corresponding 3D stack in the visualization has color-coded margins. The coloring for individual elements is easily changeable using the color picker near to the minidom legend.

Clicking a strip in the tree view (or directly a stack on the 3D document visualization mesh) also highlights the node with a colored quad. This behavior is a good way to relate with the Style Inspector, and a more unified interaction between Tilt and other Developer Tools is planned in the future. All of these additions make it easier to analyze the bounds of each node, along with the HTML, computed CSS and attributes.

Realtime editing

Because Tilt is able to detect when a webpage’s DOM structure changes or when a repaint is necessary, integration is seamless with existing Developer Tools. Using Tilt and Firebug or Style Editor at the same time is easy. One can enable or disable CSS properties, changing the style of a node, and the visualization changes accordingly.

<object height="375" width="500"><param name="movie" value="http://www.youtube.com/v/ae1p5W20Ug8?version=3&amp;feature=oembed"><param name="allowFullScreen" value="true"><param name="allowscriptaccess" value="always"><embed allowfullscreen="true" allowscriptaccess="always" height="375" src="http://www.youtube.com/v/ae1p5W20Ug8?version=3&amp;feature=oembed" type="application/x-shockwave-flash" width="500"></embed></object>

To enable realtime updates for the 3D webpage, go to the Options menu and check “Refresh visualization”.

Useful for learning

Developer tools such as “view source” have always been used to help people learn about web development. The 3D view highlights the structure of a page better than a flat view, thus anyone can immediately understand the parent-child relationship between nodes in a webpage, their positioning and how the layout is influenced.

One use case for this is the Hackasaurus mashup. The X-Ray Goggles is a nice and fun tool designed to make it easier to learn about the different document node types, the “building blocks” which create a webpage.

Export

A requested feature was the ability to export the visualization as a 3D mesh, to be used in games or other 3D editors. Tilt adds the ability to export to .obj, along with a material .mtl file and a .png texture (a screenshot of the entire webpage). The open .obj format ensures the fact that the mesh can be opened with almost any editor. Here’s a ray-traced rendering of hacks.mozilla.org in Blender:

Fun with experiments

As soon as it was released, many people found clever and interesting alternative ways to interact with Tilt. One experiment was creating a 3D visualization of an image, by exporting chunks of pixels to a HTML representation. The result was a voxel-like representation, with node blocks and stacks instead of pixels. A simple Image2Tilt converter was written in JavaScript, and you can try it directly in the browser.

<object height="375" width="500"><param name="movie" value="http://www.youtube.com/v/7YXq4gylERE?version=3&amp;feature=oembed"><param name="allowFullScreen" value="true"><param name="allowscriptaccess" value="always"><embed allowfullscreen="true" allowscriptaccess="always" height="375" src="http://www.youtube.com/v/7YXq4gylERE?version=3&amp;feature=oembed" type="application/x-shockwave-flash" width="500"></embed></object>

Accelerometer support was another addition based on community request. This shows how easy it is to add functionality that wasn’t originally planned.

<object height="281" width="500"><param name="movie" value="http://www.youtube.com/v/rbTLwVEfPn0?version=3&amp;feature=oembed"><param name="allowFullScreen" value="true"><param name="allowscriptaccess" value="always"><embed allowfullscreen="true" allowscriptaccess="always" height="281" src="http://www.youtube.com/v/rbTLwVEfPn0?version=3&amp;feature=oembed" type="application/x-shockwave-flash" width="500"></embed></object>

You can view the source code, fork it and also contribute to the addon with ideas or feature requests on Github, at github.com/victorporof/Tilt.

Available as an addon

The latest version of Tilt can be found on Github, but you can also download Tilt as an addon from addons.mozilla.org.

For compatibility, Tilt requires WebGL capabilities. Go to get.webgl.org to check availability and troubleshoot any issues. The current version works with Firefox 6.0 to latest 10.0 Nightly releases (latest Nightly builds now also support WebGL anti-aliasing, working great with Tilt).

To start Tilt, hit Control+Shift+M (or Command+Shift+M if you’re on Mac OS), or go to Web Developer -> Tilt, available in the Firefox application menu (or the Tools menu on Mac OS). You can modify this hotkey (and other properties) from the Options menu after starting Tilt.

More information about Tilt, the development process and milestone updates can be found on blog.mozilla.com/tilt.

Future

Tilt has become an active Developer Tools project, and an ongoing effort is made to integrate it with other existing tools like Style Inspector and Style Editor (source code and latest builds). As the 3D view of a webpage has proven to be useful for debugging, this main functionality will gradually become part of Firefox in future releases.

by victor at October 26, 2011 02:47 PM

October 20, 2011

Learning WebGL

WebGL around the net, 20 October 2011

by giles at October 20, 2011 01:36 PM

October 17, 2011

Learning Three.js

Lets Make a 3D Game: microphysics.js

This post is part of the "Lets make a 3D game" series. 3D and physics simulation always go well together even more so with marble games. One is required for marblesoccer but i wasnt convinced by current 3d physics engines. I explain why at the end. Fortunatly, @pyalot from codeflow.org has been kind enough to write one taylor-made for us: microphysics.js!! It is bite-sized, elegant and efficient. Less than 500 lines at the moment!! It is small engouh to be understood, important feature for a tutorial blog. It is a work in progress tho. We aren't aware of any bugs. New features will be added and the API is expected to move. Currently it implements moving spheres and static boxes (or AABB as we like to say). This is all we need for marblesoccer, the good thing about tailor-made. We are in business!!! Below is a screencast of me doing a short introduction of the playground. This just a page for you to experiment with microphysics.js. Let's get started So lets see how to use it. First step, you download it here. Then include it in your own code with this line. ```html <script src="physics.js"></script> ``` Let's Create a World Quite a title hey ? Dont you feel like galactus when you say it ? First you instanciate the physics world like this. ```javascript var world = new vphy.World() ``` Now you start it. Dont forget to give it the date as you see it. ```javascript world.start(Date.now()/1000); ``` The world is now fully initialized. You just have to periodically update it in your game/render loop. ```javascript var timeStep = 1/180; world.step(timeStep, Date.now()/1000); ``` The timeStep parameter is the precision of the physics engine, expressed in seconds. Quite a subtle tradeoff. The smaller it is, the more accurate is the physics, but the slower it is to compute. Up to you to find the balance that fit your needs. Let's Add Bodies Don't worry, this is not about killing people and dispose of their dead bodies :) In physics, A body is a solid object that you put in your world. microphysics bodies can be spheres or static boxes. Lets start right away by creating a sphere. ```javascript var sphere = new vphy.Sphere({ x : 10, y : 10, z : 10, restitution : 0.6, radius : 5, }); ``` This will position it at (10,10,10) in the world. restitution will determine how bouncy is this during a collision. A bouncing ball restitutes a lot. A falling eggs restitutes less :) This declaration seems quite verbose at first. Don't worry those parameters got sensible defaults, no need to specify them all. Now lets add it to our world ```javascript world.add(sphere); ``` If you need to remove it, just do world.remove(sphere). Not too hard hey ? Now lets create a static box. Boxes are called AABB. It stands for Axis-aligned bounding box. It is graphic jarguon for the smallest box containing your object. vphy.Sphereand vphy.AABB both derived from vphy.Body. x, y, z, resitution are vphy.Body parameters, common to both. So we wont review them again. ```javascript var body = new vphy.AABB({ width : 1, height: 1, depth : 1 }); ``` width, height and depth gives the dimensions of the box. After world.step(), you can read the new position of each body. Quite usefull to push back the resulting physics in your 3D scene :) ```javascript var pos = body.getPosition(); // x = pos[0], y = pos[1], z = pos[2] ``` Ok, so we got a world with solid objects in it, all bound to physical law. Now what about moving them ? Let's move our Bodies Lets make our sphere moves. The bodies you added to the world will move according to the forces applied on them. All that according to laws of motion from Newton. He discovered that by receiving an apple on the head, creativity can take strange paths sometime :) Ok let's add gravity, the force which moved this falling apple. This force is applied along a given direction to all our objects. The library already contains an helper just for that. Simply do ```javascript world.add(new vphy.LinearAccelerator({ x : 0, y : -9.8, z :

October 17, 2011 10:36 AM

October 13, 2011

Learning WebGL

WebGL around the net, 13 October 2011

by giles at October 13, 2011 01:45 PM