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

<channel>
	<title>Chandler Prall</title>
	<atom:link href="http://www.chandlerprall.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.chandlerprall.com</link>
	<description>Thoughts &#38; Experiments for the Web</description>
	<lastBuildDate>Mon, 17 Sep 2012 16:11:25 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Mindless &#8211; js13kGames</title>
		<link>http://www.chandlerprall.com/2012/09/mindless-js13kgames/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mindless-js13kgames</link>
		<comments>http://www.chandlerprall.com/2012/09/mindless-js13kgames/#comments</comments>
		<pubDate>Mon, 17 Sep 2012 16:02:58 +0000</pubDate>
		<dc:creator>chandler</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://chandler.prallfamily.com/?p=414</guid>
		<description><![CDATA[A little more than a month ago the js13kGames competition was announced, and September 13th was the deadline. Entries for the competiton must fit all of their code and assets in a ZIP file no larger than 13 kilobytes. 13Kb &#8230; <a href="http://www.chandlerprall.com/2012/09/mindless-js13kgames/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>A little more than a month ago the <a href="http://js13kgames.com/">js13kGames</a> competition was announced, and September 13th was the deadline. Entries for the competiton must fit all of their code and assets in a ZIP file no larger than 13 kilobytes. 13Kb isn&#8217;t much code but you can stuff around 50Kb of JavaScript into a ZIP that size. When I saw the competition I knew that I whatever game I put together had to be 3D. I began brainstorming for ideas, but for the first week of the competition I focused on writing the engine &#8211; thankfully I had a lot of help in the way of Three.js. 3D engines use a lot of math for everything, and I ripped those classes out of Three.js, renamed a few variables, and had a functioning math library. For the rendering I poured over CanvasRenderer to see how it works. I didn&#8217;t want to copy the renderer as it would have been a lot of work to remove all of the unnecessary components. Instead, I began to write my own rendering pipeline based on the one in Three.js. After a few long nights my hacked together engine was rendering simple models. Even better, the whole engine compressed down to just 2.5Kb. Now I needed a game to write.</p>
<p>Note: the following contains some spoilers &#8211; if you haven&#8217;t played <a href="http://js13kgames.com/entries/mindless/">Mindless</a> yet go check it out.</p>
<p>When I first learned about the js13KGames competition I asked <a href="http://www.godblessthechase.com/">Nick Anderson</a> if he would like to help come up with a compelling game and story. A few weeks before this we had been talking about video games and some different elements he has wanted to see. After some discussion we landed on a zombie apocalypse with a twist &#8211; you are one of the infected and are being instructed to kill healthy civilians and scientists.</p>
<p>Nick&#8217;s idea was to see how people react to a story where what the &#8220;tutorial&#8221; is telling you doesn&#8217;t match what the characters are saying. We were relying on people&#8217;s trust of the introduction messages we have all grown accustomed to at the beginning of games. In Mindless, you are introduced as one of the last healthy people in town and are tasked with killing the scientists who created the virus. After walking down the first hallway, the player has killed a guard, a scientist, and a couple &#8220;infecteds&#8221; who are actually healthy civilians. The game play is established and nothing has contradicted expectations that the prompt is telling the truth.</p>
<p>The first room has a few (truly) infected people and one scientist. When you walk up to the scientist he pleads for you to stop and spare his life. This is the first time one of the characters talks to the player, and if you don&#8217;t kill him or walk away he speaks again. Moving on the player encounters a good mix of guards, scientists, civilians, and infecteds. If the player does not immediatly kill the scientists or civilians (who we are told are actually infected) then some dialog is shown, expressing what is really happening. These characters explain that there is a room on the other side of the lab where scientists have the solution and are trying to heal everyone, introducing the second possible ending.</p>
<p>Response to the story line has been mixed. Some people got it and were really excited about what was going on. Others blasted through the dialog and walked around stabbing everyone. Generally, those who didn&#8217;t read much of the dialog were confused about what they were supposed to do, thinking it was a run-and-slash which would have clear direction. It didn&#8217;t help that we had to remove 70% of Nick&#8217;s dialog to squeeze everything into 13Kb. Overall we learned that people really trust what is said in the introduction and anything which contradicts it should be killed.</p>
<p>In case you missed it &#8211; <a href="http://js13kgames.com/entries/mindless/">Play Mindless</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.chandlerprall.com/2012/09/mindless-js13kgames/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>requestAnimationFrame is not your [logic&#039;s] friend</title>
		<link>http://www.chandlerprall.com/2012/06/requestanimationframe-is-not-your-logics-friend/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=requestanimationframe-is-not-your-logics-friend</link>
		<comments>http://www.chandlerprall.com/2012/06/requestanimationframe-is-not-your-logics-friend/#comments</comments>
		<pubDate>Mon, 11 Jun 2012 14:14:31 +0000</pubDate>
		<dc:creator>chandler</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Web Dev]]></category>

		<guid isPermaLink="false">http://chandler.prallfamily.com/?p=361</guid>
		<description><![CDATA[Intro If you have been anywhere but under a rock then you have heard about Javascript&#8217;s new requestAnimationFrame function. You have probably used the shim posted by Paul Irish, may have tinkered with the version created by Opera developer Erik &#8230; <a href="http://www.chandlerprall.com/2012/06/requestanimationframe-is-not-your-logics-friend/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<h3>Intro</h3>
<p>If you have been anywhere but under a rock then you have heard about Javascript&#8217;s new requestAnimationFrame function. You have probably used the <a href="http://paulirish.com/2011/requestanimationframe-for-smart-animating/" target="_blank" rel="nofollow">shim posted by Paul Irish</a>, may have tinkered with the <a href="http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating" target="_blank" rel="nofollow">version created by Opera developer Erik Möller</a>, or even read <a href="http://www.html5rocks.com/en/tutorials/speed/animations/" target="_blank" rel="nofollow">various</a> articles <a href="http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision" target="_blank" rel="nofollow">explaining</a> how to <a href="http://creativejs.com/resources/requestanimationframe/" target="_blank" rel="nofollow">best use it</a>.</p>
<p>I think requestAnimationFrame is a great addition to Javascript, but these two points need some emphasizing:</p>
<p>&nbsp;</p>
<ul>
<li>
<h4>Use requestAnimationFrame for animations / screen updates</h4>
</li>
<li>
<h4>Do not use it for anything else (especially game logic!)</h4>
</li>
</ul>
<p>&nbsp;</p>
<p>Seems kind obvious, right? requestAnimationFrame has the word &#8220;animation&#8221; right in its name. However, examples and articles have been circling the net which talk about completely replacing setTimeout with requestAnimationFrame. In some cases this is indeed the best thing to do, but I would argue that most of the time you will need to use setTimeout or setInterval as well.</p>
<p><span id="more-361"></span></p>
<h3>Quick example</h3>
<p>What exactly does this mean? Here&#8217;s a short demonstration; the top code block relies on requestAnimationFrame to handle everything while the second block has the game logic separated out from the graphics.</p>
<pre class="brush: jscript; title: ; notranslate">
function render() {
    [...] // Code to update the DOM, or Canvas,
          // or anything else graphics-related

    [...] // Update the player's location, health,
          // or anything else logic-related
    
    requestAnimationFrame( render );
}
</pre>
<pre class="brush: jscript; title: ; notranslate">
function render() {
    [...] // Code to update the DOM, or Canvas,
          // or anything else graphics-related
    
    requestAnimationFrame( render );
}

function gameStep() {
    [...] // Update the player's location, health,
          // or anything else logic-related
    
    setTimeout( gameStep, 1000 / 60 ); // process the game logic
                                    // at a target 60 FPS.
}
</pre>
<h3>The Growing Trend</h3>
<p>I&#8217;m just as guilty of abusing requestAnimationFrame as anyone else. In my <a href="http://chandlerprall.github.com/Physijs/" target="_blank">physics plugin</a> for Three.js I&#8217;m still using requestAnimationFrame to schedule both the physics updates as well as the rendering. The physics is handled in a web worker to avoid slowing the graphics framerate, but that simulation is still bound to the rendering because it is called from requestAnimationFrame. If the physics engine isn&#8217;t ready for another update until after the graphics render then it will sit around doing nothing for 10-15ms until requestAnimationFrame fires again. Changing the simulation loop to use setTimeout separates the logic from the graphics code and speeds up the whole demo by more than 30% in my tests &#8211; increasing the simulation&#8217;s effective FPS from 14 to over 20.</p>
<p>One common way to use requestAnimationFrame for game logic is to use a delta value to determine how much time has actually passed since the last update; in fact this is a smart thing to do whether your use the requestAnimationFrame or setTimeout method. However, relying on just this delta means your logic code is still bound to the graphics loop which can cause unexpected results &#8211; say in a multiplayer environment when the user will want their actions to be reflected immediately on the server instead of waiting for some graphics layer to first run.</p>
<p>You might think that this use of requestAnimationFrame is only an isolated issue but recently more people have been noticing its impact. Just a couple of days ago someone came into the #threejs IRC channel with this question:</p>
<blockquote><p>
Hi there, I&#8217;ve a short question&#8230;</p>
<p>I recently updated my code using requestAnimationFrame(), now my animation runs as fast as possible, where before it was running at fixed 30fps</p>
<p>i implemented a navigation through the space using the cursor-keys, but now the navigation-speed depends on the speed of the browser/computer
</p></blockquote>
<p>The solution was to move his game logic out of the requestAnimationFrame loop and put it in a separate loop driven by setTimeout. There are in fact a few things which will cause a requestAnimationFrame-based loop to run at different speeds.</p>
<ul>
<li>requestAnimationFrame is designed to speed up and slow down to match the monitor&#8217;s refresh rate. If you rely on it to drive logic then your game will play at different speeds depending on how quickly the monitor updates.</li>
<li>When a brower tab other than your page is selected the browser will slow down calls to your requestAnimationFrame loop &#8211; typically dropping to once per second. When your page is not being displayed there is no point in rendering anything on it.</li>
<li>A browser may throttle calls to your render function if the computer is in battery conservation mode. One of the biggest drains on a laptop battery is graphics and reducing how often draws occur has a big impact on battery life. If your code depends on requestAnimationFrame then it could slow down dramatically when the battery level is low.</li>
</ul>
<h3>Take away</h3>
<p>If you need to make recurring updates to something on the screen such as DOM changes or canvas drawing then you should definitely use requestAnimationFrame. But if you need to regularly make updates to data then setTimeout is still your friend. Using requestAnimationFrame and setTimeout together is not evil nor is it duplicating functionality. These functions are allies, not enemies, and when used together properly they can create robust user-friendly applications with the best of both worlds.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.chandlerprall.com/2012/06/requestanimationframe-is-not-your-logics-friend/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Physijs &#8211; a physics plugin for three.js</title>
		<link>http://www.chandlerprall.com/2012/04/physijs-a-physics-plugin-for-three-js/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=physijs-a-physics-plugin-for-three-js</link>
		<comments>http://www.chandlerprall.com/2012/04/physijs-a-physics-plugin-for-three-js/#comments</comments>
		<pubDate>Mon, 30 Apr 2012 14:28:50 +0000</pubDate>
		<dc:creator>chandler</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Web Dev]]></category>
		<category><![CDATA[WebGL]]></category>

		<guid isPermaLink="false">http://chandler.prallfamily.com/?p=347</guid>
		<description><![CDATA[After working on the Tower game I mentioned in the last post, I wanted to write a physics plugin for three.js to make it very easy to include physics in 3D scenes. While the plugin has been up on github &#8230; <a href="http://www.chandlerprall.com/2012/04/physijs-a-physics-plugin-for-three-js/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>After working on the Tower game I mentioned in the last post, I wanted to write a physics plugin for three.js to make it very easy to include physics in 3D scenes. While the plugin has been up on github for a while, I now feel it&#8217;s ready for an official release.</p>
<h3>What is it?</h3>
<p><a href="http://chandlerprall.github.com/Physijs/" target="_blank">Physijs</a> brings a very easy to use interface to the three.js framework. One of the reasons three.js is so popular is because it is so incredibly easy for graphics newbies to get into 3D programming. Physijs takes that philosophy to heart and makes physics simulations just as easy to run. In fact, there are just five easy steps that must be taken to make a 3D scene come alive.</p>
<h3>How does Physijs work?</h3>
<p>Physijs is built on top of ammo.js and runs the physics simulation in a separate thread (via web worker) to avoid impacting in your application&#8217;s performance and taking up your your 3D rendering time.</p>
<p>A lot of effort has been made to keep the style of code the same when using this plugin. Apart from updating an object&#8217;s position, all of the normal three.js conventions remain the same. If you are used to three.js, you already know how to use Physijs.</p>
<h3>Who is this for?</h3>
<p>You, hopefully. If you are familiar with three.js and want to add physics to your scene, this is the plugin for you. No mucking about with shape definitions, keeping objects in their correct positions, or identifying collisions &#8211; simply use a few Physijs objects in place of three.js&#8217;s and you&#8217;ll automatically have a dynamic environment.</p>
<p>If you need (or want) a feature not already included then add it to the issue tracker or implement it yourself and send over a pull request at the <a href="https://github.com/chandlerprall/Physijs" target="_blank">github repo</a>.</p>
<h3>Examples</h3>
<p><a href="http://chandlerprall.github.com/Physijs/examples/body.html" target="_blank"><img src="http://chandlerprall.github.com/Physijs/examples/body.jpg" alt="rigid bodies" style="margin-right: 10px"></a><a href="http://chandlerprall.github.com/Physijs/examples/collisions.html" target="_blank"><img src="http://chandlerprall.github.com/Physijs/examples/collisions.jpg" alt="collisions" style="margin-right: 10px"></a><a href="http://chandlerprall.github.com/Physijs/examples/compound.html" target="_blank"><img src="http://chandlerprall.github.com/Physijs/examples/compound.jpg" alt="compound shapes" style="margin-right: 10px"></a><a href="http://chandlerprall.github.com/Physijs/examples/shapes.html" target="_blank"><img src="http://chandlerprall.github.com/Physijs/examples/shapes.jpg" alt="all shapes" style="margin-right: 10px"></a><a href="http://chandlerprall.github.com/Physijs/examples/jenga.html" target="_blank"><img src="http://chandlerprall.github.com/Physijs/examples/jenga.jpg" alt="jenga" style="margin-right: 10px"></a></p>
<h3>Features</h3>
<ul>
<li>Support for <a href="https://github.com/chandlerprall/Physijs/wiki/Basic-Shapes">multiple object shapes</a>, including custom convex objects.</li>
<li>Material system provides simple control over friction and restitution (&#8220;bounciness&#8221;)</li>
<li>Integrated collision detection and events</li>
<li>Compound objects using the hierarchy system in three.js</li>
<li>Rotations using either euler or quaternion systems &#8211; your preference</li>
<li>Built seamlessly on top of three.js to keep the same convention and coding style</li>
</ul>
<h3>In the Future</h3>
<ul>
<li>More (and better) optimizations</li>
<li>Constraint systems such as point-to-point and hinge.</li>
<li>Vehicle systems</li>
<li>Heightfield/heightmap shape</li>
<li>It would be awesome to have concave shape decomposition</li>
</ul>
<h3 style="margin-top: 40px;"><a href="https://github.com/chandlerprall/Physijs">Go to GitHub repo &raquo;</a></h3>
]]></content:encoded>
			<wfw:commentRss>http://www.chandlerprall.com/2012/04/physijs-a-physics-plugin-for-three-js/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Physics with Ammo.js + Three.js</title>
		<link>http://www.chandlerprall.com/2012/03/physics-with-ammo-js-three-js/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=physics-with-ammo-js-three-js</link>
		<comments>http://www.chandlerprall.com/2012/03/physics-with-ammo-js-three-js/#comments</comments>
		<pubDate>Sat, 03 Mar 2012 05:36:55 +0000</pubDate>
		<dc:creator>chandler</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[WebGL]]></category>

		<guid isPermaLink="false">http://chandler.prallfamily.com/?p=308</guid>
		<description><![CDATA[Let&#8217;s explore the basics of using Ammo.js for physics in a Three.js environment. For my entry to the Pokki 1UP contest I rushed out a simple physics-based WebGL game. From start to finish I had 9 days left until the &#8230; <a href="http://www.chandlerprall.com/2012/03/physics-with-ammo-js-three-js/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>Let&#8217;s explore the basics of using Ammo.js for physics in a Three.js environment.</p>
<p>For my entry to the Pokki 1UP contest I rushed out a simple physics-based WebGL game. From start to finish I had 9 days left until the game needed to be submitted. I broke that down into one day for the initial setup, a couple days for physics, one day for sound, one day for interface, and the last day for minute touch ups. Turned out to be the perfect timeline. The setup consisted of creating a <a href="https://github.com/mrdoob/three.js" rel="nofollow" target="_blank">Three.js</a> environment within the <a href="http://developers.pokki.com/" rel="nofollow" target="_blank">Pokki framework</a>. I also spent that first day hashing out the basic ideas, inspired by a &#8220;reverse Tetris&#8221; plan.</p>
<p>The second day was my first real attempt at using any physics library. Right now the most popular Javascript physics library is probably <a href="http://box2d-js.sourceforge.net/" rel="nofollow" target="_blank">Box2D</a>, as long as you don&#8217;t need to simulate a full 3D world. My game didn&#8217;t need an entire 3D simulation &#8211; the player can only move blocks along the X axis and gravity only applies to the Y axis; no simulation was needed across the Z axis. However, the results I got from Box2D were poor. It seemed to detect collisions a bit late and I wasn&#8217;t able to coerce any of the boxes to interact in a believable way. I attribute that to my unfamiliarity with the library, but I was on a very tight time table and I had spent a full night failing to achieve decent results.</p>
<p>Next night I found my winner &#8211; <a href="https://github.com/kripken/ammo.js/" rel="nofollow" target="_blank">Ammo.js</a> &#8211; which is a direct port from the C++ library <em>Bullet physics</em>. An added benefit is Ammo.js does simulate a full 3D environment, not just 2 dimensions like Box2D; this gave my game more realism as the blocks aren&#8217;t constrained to just XY coordinates. I was able to get all of the necessary physics setup in just a few hours &#8211; from a static ground plane to placeable blocks and a tipping tower. In this post I am leaving out any of the scene management of creating and adding the 3D objects themselves; if you are not familiar with Three.js I highly suggest doing yourself a favor and <a href="http://learningthreejs.com/blog/2011/08/06/lets-do-a-cube/" rel="nofollow" target="_blank">learn how to setup a simple scene</a>, and then <a href="https://github.com/mrdoob/three.js/tree/master/examples" rel="nofollow" target="_blank">play with some of the included examples</a>.</p>
<p><span id="more-308"></span></p>
<h2>Setting up the scene</h2>
<p>In order to use Ammo.js in your 3D scene you must first create the simulation world. These six lines create a default environment and add it as a property to the THREE.Scene object, making it simple to interactive with later. The only customization you need to do here is adjust the gravity vector on the last line.</p>
<pre class="brush: jscript; title: ; notranslate">
var collisionConfiguration = new Ammo.btDefaultCollisionConfiguration();
var dispatcher = new Ammo.btCollisionDispatcher( collisionConfiguration );
var overlappingPairCache = new Ammo.btDbvtBroadphase();
var solver = new Ammo.btSequentialImpulseConstraintSolver();
scene.world = new Ammo.btDiscreteDynamicsWorld( dispatcher, overlappingPairCache, solver, collisionConfiguration );
scene.world.setGravity(new Ammo.btVector3(0, -12, 0));
</pre>
<h2>Creating the ground</h2>
<p>For the second part of creating a scene we need to initialize the ground object. This takes a few more lines of code than creating the world, but not by much. Again, most of the code is simply creating the default configuration. One important thing to remember here is that the shape measurements used on the first line is <strong>half</strong> of the full ground&#8217;s box. This is the case in both Ammo.js and Box2D when creating either a box or a sphere &#8211; the size you pass in is either the sphere&#8217;s radius or half the box&#8217;s measurements. Second, remember to set the ground&#8217;s <strong>mass to 0</strong> so that gravity cannot affect it. Basic principle of physics: an object without mass cannot move (or exist, usually&#8230; but hey, this is just a simulation!)</p>
<pre class="brush: jscript; title: ; notranslate">
var groundShape = new Ammo.btBoxShape(new Ammo.btVector3( 25, 1, 25 )); // Create block 50x2x50
var groundTransform = new Ammo.btTransform();
groundTransform.setIdentity();
groundTransform.setOrigin(new Ammo.btVector3( 0, -1, 0 )); // Set initial position

var groundMass = 0; // Mass of 0 means ground won't move from gravity or collisions
var localInertia = new Ammo.btVector3(0, 0, 0);
var motionState = new Ammo.btDefaultMotionState( groundTransform );
var rbInfo = new Ammo.btRigidBodyConstructionInfo( groundMass, motionState, groundShape, localInertia );
var groundAmmo = new Ammo.btRigidBody( rbInfo );
scene.world.addRigidBody( groundAmmo );
</pre>
<h2>Creating boxes</h2>
<p>So far we&#8217;ve created a 3D scene and a 3D world. They know nothing about each other, and there&#8217;s nothing going on physics-wise anyway. Now it&#8217;s time to create a box and add it to the world. There is one major point to pay attention to here: Ammo.js uses quaternions to represent an object&#8217;s rotation. Three.js models use Euler rotation by default, but you can change that by setting mesh.useQuaternion = true; You&#8217;ll see in the next section how to update a Three.js scene from the Ammo.js world.</p>
<pre class="brush: jscript; title: ; notranslate">
var mass = 3 * 3 * 3; // Matches box dimensions for simplicity
var startTransform = new Ammo.btTransform();
startTransform.setIdentity();
startTransform.setOrigin(new Ammo.btVector3( position_x, 20, position_z )); // Set initial position

var localInertia = new Ammo.btVector3(0, 0, 0);

var boxShape = new Ammo.btBoxShape(new Ammo.btVector3( 1.5, 1.5, 1.5 )); // Box is 3x3x3
boxShape.calculateLocalInertia( mass, localInertia );

var motionState = new Ammo.btDefaultMotionState( startTransform );
var rbInfo = new Ammo.btRigidBodyConstructionInfo( mass, motionState, boxShape, localInertia );
var boxAmmo = new Ammo.btRigidBody( rbInfo );
scene.world.addRigidBody( boxAmmo );

boxAmmo.mesh = box; // Assign the Three.js mesh in `box`, this is used to update the model position later
boxes.push( boxAmmo ); // Keep track of this box
</pre>
<h2>Lights, camera, action!</h2>
<p>&#8220;Wait just a minute,&#8221; I hear you exclaim, &#8220;that does nothing, the box just floats in the air not moving at all!&#8221; You are correct, and it is now time to run the physics and update the 3D scene. To do that I have a function which is called from the render loop.</p>
<pre class="brush: jscript; title: ; notranslate">
updateBoxes = function() {
	scene.world.stepSimulation( 1 / 60, 5 ); // Tells Ammo.js to apply physics for 1/60th of a second with a maximum of 5 steps
	var i, transform = new Ammo.btTransform(), origin, rotation;
	
	for ( i = 0; i &lt; boxes.length; i++ ) {
		boxes[i].getMotionState().getWorldTransform( transform ); // Retrieve box position &amp; rotation from Ammo
		
		// Update position
		origin = transform.getOrigin();
		boxes[i].mesh.position.x = origin.x();
		boxes[i].mesh.position.y = origin.y();
		boxes[i].mesh.position.z = origin.z();
		
		// Update rotation
		rotation = transform.getRotation();
		boxes[i].mesh.quaternion.x = rotation.x();
		boxes[i].mesh.quaternion.y = rotation.y();
		boxes[i].mesh.quaternion.z = rotation.z();
		boxes[i].mesh.quaternion.w = rotation.w();
	};
};
</pre>
<h2>Finishing touches</h2>
<p>Finally, add in some user interaction and you have a nice little demo. After the basics are in place you can begin expanding to your heart&#8217;s content. Maybe it&#8217;s as simple as dropping boxes from the air, or maybe you&#8217;d be more interested in creating a bowling ally. Perhaps a game of ping pong or air hockey? Whatever it is, using Ammo.js with Three.js is simple and there&#8217;s no reason not to try it.</p>
<p>If you&#8217;re anything like me, looking at an example&#8217;s source code is just as much help as a blog post introducing some concepts. An example using the code from this post can be viewed <a href="http://chandler.prallfamily.com/labs/three/ammo/introduction/" target="_blank">over on this page</a>.</p>
<p><a href="http://chandler.prallfamily.com/labs/three/ammo/introduction/" target="_blank"><img src="http://chandler.prallfamily.com/wp-content/uploads/2012/03/ammothree_example.png" alt="Ammo.js + Three.js Example" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.chandlerprall.com/2012/03/physics-with-ammo-js-three-js/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>New WebGL Game &#8211; Tower</title>
		<link>http://www.chandlerprall.com/2012/02/new-webgl-game-tower/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=new-webgl-game-tower</link>
		<comments>http://www.chandlerprall.com/2012/02/new-webgl-game-tower/#comments</comments>
		<pubDate>Mon, 20 Feb 2012 19:07:08 +0000</pubDate>
		<dc:creator>chandler</dc:creator>
				<category><![CDATA[Life]]></category>
		<category><![CDATA[WebGL]]></category>

		<guid isPermaLink="false">http://chandler.prallfamily.com/?p=283</guid>
		<description><![CDATA[My first idea for the 1UP contest Where in the world have I been the past two months? Late last December Pokki announced their 1UP HTML5 game contest, which ends today. I started working on a World War II themed &#8230; <a href="http://www.chandlerprall.com/2012/02/new-webgl-game-tower/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<figure class="right"><img src="http://chandler.prallfamily.com/wp-content/uploads/2012/02/trenches_screenshot.jpg" alt="My first idea for the 1UP contest" style="width: 300px;" /><br />
<figcaption>My first idea for the 1UP contest</figcaption>
</figure>
<p>Where in the world have I been the past two months?</p>
<p>Late last December Pokki announced their <a href="http://www.pokki.com/1up/" target="_blank" rel="nofollow">1UP HTML5 game contest</a>, which ends today. I started working on a World War II themed RTS. As it turns out, making a real time strategy game requires more than 2 months if you&#8217;re starting from scratch. So one week before the contest deadline I scrapped that idea and started work on a completely different game.</p>
<p>Fortunately I was able to complete the second concept in time. The game is called <strong>Tower</strong> and the aim is to build the tallest stack of wooden and stone blocks as you can while racing the clock. For now Tower is only available to Windows users through the Pokki store, but I will put it online for others when the contest is over.</p>
<p>I will put up another post in a week or so detailing how I put Tower together. It was the first time I worked with any of physics libraries (happily decided on <a href="https://github.com/kripken/ammo.js/" target="_blank" rel="nofollow">ammo.js</a>) but overall everything was straightforward.</p>
<p><script type='text/javascript' src='http://cdn.pokki.com/embed/pokki_helper.js'></script><br />
<a class='pokki-download' onclick='return pokki_helper.download(this, "Tower", "Pokki_Tower");' href='http://www.pokki.com/download/?name=Tower&#038;etag=Pokki_Tower' style='display:block;color:#fff;font:bold 11px Arial,sans-serif;background:#03b5fc;text-decoration:none;padding:5px 11px 5px 24px;'>Click here to download Tower for Pokki</a></p>
<p><img src="http://chandler.prallfamily.com/wp-content/uploads/2012/02/tower_screenshot.jpg" alt="Tower" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.chandlerprall.com/2012/02/new-webgl-game-tower/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Constructive solid geometry with Three.js</title>
		<link>http://www.chandlerprall.com/2011/12/constructive-solid-geometry-with-three-js/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=constructive-solid-geometry-with-three-js</link>
		<comments>http://www.chandlerprall.com/2011/12/constructive-solid-geometry-with-three-js/#comments</comments>
		<pubDate>Thu, 08 Dec 2011 07:50:23 +0000</pubDate>
		<dc:creator>chandler</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[WebGL]]></category>

		<guid isPermaLink="false">http://chandler.prallfamily.com/?p=230</guid>
		<description><![CDATA[A few days ago Evan Wallace released his Constructive solid geometry library for WebGL. This library uses Boolean operations (addition, subtraction, union, intersect) to be applied on 3D geometry such as cubes, spheres, or anything else you can throw at &#8230; <a href="http://www.chandlerprall.com/2011/12/constructive-solid-geometry-with-three-js/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>A few days ago <a href="http://madebyevan.com" rel="nofollow">Evan Wallace</a> released his <a href="http://evanw.github.com/csg.js/" rel="nofollow">Constructive solid geometry</a> library for WebGL. This library uses Boolean operations (addition, subtraction, union, intersect) to be applied on 3D geometry such as cubes, spheres, or anything else you can throw at it. I thought this would be a very nice capability to have in Three.js and wrote a wrapper for Evan&#8217;s CSG library.</p>
<p><strong><a href="http://chandler.prallfamily.com/labs/three/csg/ThreeCSG.js">Download ThreeCSG.js</a></strong></p>
<p>First, an example of what code using just the CSG library looks like:</p>
<p><img src="http://chandler.prallfamily.com/wp-content/uploads/2011/12/pure_csg.gif" style="float: right; height: 150px;" /></p>
<pre class="brush: jscript; title: ; notranslate">
var cube = new CSG.cube();
var sphere = CSG.sphere({radius: 1.3, stacks: 16});
var geometry = cube.subtract(sphere);
</pre>
<p>&nbsp;<br />&nbsp;<br />&nbsp;<br />&nbsp;<br />
Let&#8217;s add in Three.js and my CSG wrapper:</p>
<p><img src="http://chandler.prallfamily.com/wp-content/uploads/2011/12/easy_csg.gif" style="float: right; height: 150px;" /></p>
<pre class="brush: jscript; title: ; notranslate">
var cube = THREE.CSG.toCSG(new THREE.CubeGeometry( 2, 2, 2 ));
var sphere = THREE.CSG.toCSG(new THREE.SphereGeometry(1.4, 16, 16));
var geometry = THREE.CSG.fromCSG( sphere.subtract(cube) );
var mesh = new THREE.Mesh(geometry, new THREE.MeshNormalMaterial());
</pre>
<p>It&#8217;s that simple. The toCSG function accepts objects of both THREE.Geometry and THREE.Mesh types. Objects can be positioned either by the mesh&#8217;s position or by supplying a second parameter to the toCSG function. Both methods are shown below. (rotation can be set from the mesh&#8217;s rotation property or through a supplied third parameter)</p>
<p><img src="http://chandler.prallfamily.com/wp-content/uploads/2011/12/mesh_position.gif" style="float: right; height: 150px;" /></p>
<pre class="brush: jscript; title: ; notranslate">
var cube_mesh = new THREE.Mesh(
	new THREE.CubeGeometry( 2, 2, 2 )
);
cube_mesh.position.x = 1;

var cube = THREE.CSG.toCSG(cube_mesh);
var sphere = THREE.CSG.toCSG(new THREE.SphereGeometry(1.4, 16, 16));
var geometry = sphere.subtract(cube);
var mesh = new THREE.Mesh(geometry, new THREE.MeshNormalMaterial());
</pre>
<p><img src="http://chandler.prallfamily.com/wp-content/uploads/2011/12/vector_position.gif" style="float: right; height: 150px;" /></p>
<pre class="brush: jscript; title: ; notranslate">
var cube = THREE.CSG.toCSG(
	new THREE.CubeGeometry( 2, 2, 2 ),
	new THREE.Vector3(-1, 0, 0)
);
var sphere = THREE.CSG.toCSG(new THREE.SphereGeometry(1.4, 16, 16));
var geometry = THREE.CSG.fromCSG( sphere.subtract(cube) );
var mesh = new THREE.Mesh(geometry, new THREE.MeshNormalMaterial());
</pre>
<p>In these examples I only used the built in primitive objects but the same functionality should work for any Three.js compatible models. UV coordinates are not generated (all values are set to 0) but everything else related to THREE.Mesh works as you would expect.</p>
<p><strong>Links, resources</strong><br />
<a href="http://chandler.prallfamily.com/labs/three/csg/csg.html">Live demo of the last example</a><br />
<a href="http://chandler.prallfamily.com/labs/three/csg/ThreeCSG.js">CSG wrapper for Three.js</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.chandlerprall.com/2011/12/constructive-solid-geometry-with-three-js/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>RegEx for truncating &amp; trimming</title>
		<link>http://www.chandlerprall.com/2011/11/regex-for-truncating-trimming/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=regex-for-truncating-trimming</link>
		<comments>http://www.chandlerprall.com/2011/11/regex-for-truncating-trimming/#comments</comments>
		<pubDate>Fri, 04 Nov 2011 06:36:50 +0000</pubDate>
		<dc:creator>chandler</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://chandler.prallfamily.com/?p=223</guid>
		<description><![CDATA[I&#8217;m always a bit excited after writing a fairly succinct-yet-powerful regular expression, so I thought I&#8217;d take a short break from the WebGL topics for this tidbit: This magical regex will trim &#038; truncate text down to 20 characters without &#8230; <a href="http://www.chandlerprall.com/2011/11/regex-for-truncating-trimming/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p>I&#8217;m always a bit excited after writing a fairly succinct-yet-powerful regular expression, so I thought I&#8217;d take a short break from the WebGL topics for this tidbit:</p>
<pre class="brush: plain; light: true; title: ; notranslate">([^\s][\s\S]{0,20}(?!=[^\s]))([\s]|$)</pre>
<p>This magical regex will trim &#038; truncate text down to 20 characters without breaking apart the last word. Need a different number of characters? Just change the &#8220;20&#8243; to whatever you need. Here are some quick examples:</p>
<pre class="brush: plain; light: true; title: ; notranslate">
&quot;I'm sorry Dave, I cannot let you do that.&quot; -&gt; &quot;I'm sorry Dave, I&quot;
&quot;Top 'o the morning to ye!&quot; -&gt; &quot;Top 'o the morning to&quot;
&quot;             Testing the trimming out!       &quot; -&gt; &quot;Testing the trimming&quot;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.chandlerprall.com/2011/11/regex-for-truncating-trimming/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Steep Parallax Shader</title>
		<link>http://www.chandlerprall.com/2011/09/steep-parallax-shader/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=steep-parallax-shader</link>
		<comments>http://www.chandlerprall.com/2011/09/steep-parallax-shader/#comments</comments>
		<pubDate>Mon, 05 Sep 2011 04:55:21 +0000</pubDate>
		<dc:creator>chandler</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[WebGL]]></category>

		<guid isPermaLink="false">http://chandler.prallfamily.com/?p=208</guid>
		<description><![CDATA[View demo. After my last post about a basic parallax shader I have been working on implenting a steep parallax shader in WebGL. This shader is a lot more computationally intense than normal parallax because it uses ray tracing to &#8230; <a href="http://www.chandlerprall.com/2011/09/steep-parallax-shader/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><a href="http://chandler.prallfamily.com/webgl/bumpmaps/steep_parallax.html" target="_blank"><strong>View demo.</strong><br /><img src="http://chandler.prallfamily.com/webgl/bumpmaps/preview_steep.jpg" alt="Steep Parallax Shader" title="Steep Parallax Shader" style="border-width: 0;" /></a></p>
<p>After my last post about a basic parallax shader I have been working on implenting a <a href="http://graphics.cs.brown.edu/games/SteepParallax/index.html" target="_blank">steep parallax shader</a> in WebGL. This shader is a lot more computationally intense than normal parallax because it uses ray tracing to find the correct UV values and to cast shadows onto itself. There is only one big change between the original shader and my WebGL implementation and that is using <i>for</i> loops instead of <i>while</i>s. This change had to be made because WebGL&#8217;s specifications don&#8217;t support while loops. This is for security reasons, so that a website cannot create infinite loops in the GPU and hang the user&#8217;s system. Likewise, for loops must loop over constants. This change makes the shader less efficient but it isn&#8217;t too much of an impact and requires the number of ray trace steps to be hard-coded in the shader.</p>
<p>As this shader ray traces each individual pixel it is best used on objects which take up a smaller amount of the screen real estate. When viewing <a href="http://chandler.prallfamily.com/webgl/bumpmaps/steep_parallax.html" target="_blank">the example</a> I see 60fps at 800&#215;600 but it drops to around 30fps at 1920&#215;1200.</p>
<p><span id="more-208"></span></p>
<p><strong>Vertex Shader</strong></p>
<pre class="brush: jscript; title: ; notranslate">
	uniform vec3 LightSource;
	
	attribute vec4 tangent;

	varying vec2 vUv;
	varying vec3 vPosition;
	
	varying vec3 vNormal;
	varying vec3 vTangent;
	varying vec3 vBinormal;
	
	varying vec3 tsPosition;
	varying vec3 tsCameraPosition;
	varying vec3 tsLightSource;
	
	void main( void ) {
		
		vUv = uv;
		vPosition = position;
		
		gl_Position = projectionMatrix * modelViewMatrix * vec4(vPosition, 1.0);
		
		// Find &amp; normalize the plane's normal, tangent, and binormal vectors
		vNormal = normalize( normal );
		vTangent = normalize( tangent.xyz );
		vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );
		
		// Convert vertice, camera, and light vector positions into tangent space
		mat3 TBNMatrix = mat3(vTangent, vBinormal, vNormal);
		tsPosition = position * TBNMatrix;
		tsCameraPosition = cameraPosition * TBNMatrix;
		tsLightSource = LightSource * TBNMatrix;
		
	}
</pre>
<p><strong>Fragment Shader</strong></p>
<pre class="brush: jscript; title: ; notranslate">
	uniform sampler2D base;
	uniform sampler2D map;
	
	uniform vec3 ambientColor;
	uniform vec3 diffuseColor;
	uniform vec3 specularColor;
	uniform float shininess;
	uniform float scale;
	uniform float shadow;
	
	varying vec3 vNormal;
    varying vec3 vTangent;
    varying vec3 vBinormal;
	
	varying vec3 vPosition;
	varying vec2 vUv;
	
	varying vec3 tsPosition;
	varying vec3 tsCameraPosition;
	varying vec3 tsLightSource;
	
	void main()
	{
		float bumpScale = scale;
		
		// normalize the other tangent space vectors
		vec3 viewVector = normalize(tsCameraPosition - tsPosition);
		vec3 lightVector = normalize(tsLightSource - tsPosition);
		
		vec3 tsE = normalize(tsCameraPosition);

		const float numSteps = 30.0; // How many steps the UV ray tracing should take
		float height = 1.0;
		float step = 1.0 / numSteps;

		vec2 offset = vUv;
		vec4 NB = texture2D(map, offset);

		vec2 delta = vec2(-tsE.x, -tsE.y) * bumpScale / (tsE.z * numSteps);

		// find UV offset
		for (float i = 0.0; i &lt; numSteps; i++) {
			if (NB.a &lt; height) {
				height -= step;
				offset += delta;
				NB = texture2D(map, offset);
			} else {
				break;
			}
		}
		
		vec3 color = texture2D(base, offset).rgb;
        
        
        	vec3 normal = texture2D(map, offset).rgb * 2.0 - 1.0;

		// calculate this pixel's lighting
        	float nxDir = max(0.0, dot(normal, lightVector));
        	vec3 ambient = ambientColor * color;

        	float specularPower = 0.0;
        	if(nxDir != 0.0)
        	{
                	vec3 halfVector = normalize(lightVector + viewVector);
                	float nxHalf = max(0.0, dot(normal, halfVector));
                	specularPower = pow(nxHalf, shininess);
        	}
        	vec3 specular = specularColor * specularPower;
        
        
        	vec3 pixel_color = ambient + (diffuseColor * nxDir * color) + specular;
        
		// find shadowing if enabled
        	if (shadow == 1.0) {
	        	vec2 shadow_offset = offset;
			vec3 tsH = normalize(lightVector + tsE);
			float NdotL = max(0.0, dot(normal, lightVector));
			
			float selfShadow = 0.0;
			
			if (NdotL &gt; 0.0) {
				
				const float numShadowSteps = 10.0;
				step = 1.0 / numShadowSteps;
				delta = vec2(lightVector.x, lightVector.y) * bumpScale / (numShadowSteps * lightVector.z);
				
				height = NB.a + step * .1;
				
				for (float i = 0.0; i &lt; numShadowSteps; i++) {
					if (NB.a &lt; height &amp;&amp; height &lt; 1.0) {
						height += step;
						shadow_offset += delta;
						NB = texture2D(map, shadow_offset);
					} else {
						break;
					}
				}
				
				selfShadow = float(NB.a &lt; height);
				
			}
			
			if (selfShadow == 0.0) {
			pixel_color *= .5;
			}
		}
		
		gl_FragColor = vec4(pixel_color, 1.0);
		
		if (offset.x &lt; 0.0 || offset.x &gt; 1.0 || offset.y &lt; 0.0 || offset.y &gt; 1.0) {
			gl_FragColor.a = 0.0;
		}
	}
</pre>
<p>There are the same seven parameters passed in as the normal parallax shader plus an additional one, <i>shadow</i></p>
<ul>
<li>base &#8211; the texture</li>
<li>map &#8211; normal map in RGB space, height/bump map in the alpha channel</li>
<li>ambientColor &#8211; ambient color in a vec3</li>
<li>diffuseColor &#8211; diffuse color in a vec3</li>
<li>specularColor &#8211; specular color in a vec3</li>
<li>shininess &#8211; how shiny the surface should appear</li>
<li>scale &#8211; float indicating how deep the surface is</li>
<li>shadow &#8211; if equal to 1.0 the surface self-shadows</li>
</ul>
<p>As before, these uniform values can be played with in <a href="http://chandler.prallfamily.com/webgl/bumpmaps/steep_parallax.html" target="_blank">the example</a> to see how they affect the texture.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.chandlerprall.com/2011/09/steep-parallax-shader/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Parallax Shader for WebGL / ThreeJS</title>
		<link>http://www.chandlerprall.com/2011/08/parallax-shader-for-webgl-threejs/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=parallax-shader-for-webgl-threejs</link>
		<comments>http://www.chandlerprall.com/2011/08/parallax-shader-for-webgl-threejs/#comments</comments>
		<pubDate>Sat, 20 Aug 2011 07:18:39 +0000</pubDate>
		<dc:creator>chandler</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[WebGL]]></category>

		<guid isPermaLink="false">http://chandler.prallfamily.com/?p=188</guid>
		<description><![CDATA[View demo. Update 8/22/2011: I have updated the vertex/fragment shaders so they work with rotated/positioned objects. Previous version especially didn&#8217;t like rotations. Two additional demos have been added as well to show how the scale/bias can be used to change &#8230; <a href="http://www.chandlerprall.com/2011/08/parallax-shader-for-webgl-threejs/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><a href="http://chandler.prallfamily.com/webgl/bumpmaps/parallax.html" target="_blank"><strong>View demo.</strong><br /><img src="http://chandler.prallfamily.com/webgl/bumpmaps/preview.jpg" alt="Parallax Shader" title="Parallax Shader" style="border-width: 0;" /></a></p>
<p><strong><br />
Update 8/22/2011: I have updated the vertex/fragment shaders so they work with rotated/positioned objects. Previous version especially didn&#8217;t like rotations. Two additional demos have been added as well to show how the scale/bias can be used to change the texture depth.<br />
<a href="http://chandler.prallfamily.com/webgl/bumpmaps/parallax_flat.html" target="_blank">Horizontal Plane</a></strong> &#8211; showing a stone walkway<strong><br />
<a href="http://chandler.prallfamily.com/webgl/bumpmaps/parallax_cube.html" target="_blank">Cube Geometry</a></strong> &#8211; multi-face geometry<strong><br />
</strong></p>
<p>It&#8217;s been too long since my last post. I&#8217;ve been working on some proof-of-concepts for a couple WebGL projects I have going on. One of those concepts is <a href="http://en.wikipedia.org/wiki/Parallax_mapping" target="_blank" rel="nofollow">Parallax Mapping</a>, which transforms a flat plane surface into a 3D projection &#8211; kind of hologram style. This method passes memory and processing use from the RAM and CPU onto to the GPU. When dealing with Javascript based games, this is very helpful. You can define a plane with the 4 corner vertices and the graphics card will handle creating the 3D surface. Parallax mapping differs from bump maps by adjusting the texture itself based on the camera&#8217;s perspective. Bump mapping applies different lighting based on the perspective, parallax mapping actually shifts the texture&#8217;s perspective. The best way to understand what this means is to <a href="http://chandler.prallfamily.com/webgl/bumpmaps/parallax.html" target="_blank">see it for yourself</a>. In that example move your cursor around the window; the camera will move along with you and the texture will be adjusted based on the new perspective.</p>
<p>The parallax shader is actually quite simple.</p>
<p><span id="more-188"></span></p>
<p><strong>Vertex Shader</strong></p>
<pre class="brush: jscript; title: ; notranslate">
	uniform vec3 LightSource;
	
	attribute vec4 tangent;

	varying vec2 vUv;
	varying vec3 vPosition;
	
	varying vec3 vNormal;
	varying vec3 vTangent;
	varying vec3 vBinormal;
	
	varying vec3 tsPosition;
	varying vec3 tsCameraPosition;
	varying vec3 tsLightSource;
	
	void main( void ) {
		
		vUv = uv;
		vPosition = position;
		
		gl_Position = projectionMatrix * modelViewMatrix * vec4(vPosition, 1.0);
		
		// Find &amp; normalize the plane's normal, tangent, and binormal vectors
		vNormal = normalize( normal );
		vTangent = normalize( tangent.xyz );
		vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );
		
		// Convert vertice, camera, and light vector positions into tangent space
		mat3 TBNMatrix = mat3(vTangent, vBinormal, vNormal);
		tsPosition = position * TBNMatrix;
		tsCameraPosition = cameraPosition * TBNMatrix;
		tsLightSource = LightSource * TBNMatrix;
		
	}
</pre>
<p><strong>Fragment Shader</strong></p>
<pre class="brush: jscript; title: ; notranslate">
	uniform sampler2D base; // base texture
	uniform sampler2D map; // normal map in rgb space, heightmap in alpha channel
	
	uniform vec3 ambientColor; // color of ambient light
	uniform vec3 diffuseColor; // color of diffuse lighting
	uniform vec3 specularColor; // color of specular highlights
	uniform float shininess; // how shiny the surface is
	uniform vec2 scaleBias; // x = scale, y = bias
	
	varying vec3 vPosition;
	varying vec2 vUv;
	
	varying vec3 tsPosition;
	varying vec3 tsCameraPosition;
	varying vec3 tsLightSource;
	
	void main()
	{
		// calculate the UV offset
		float height = texture2D(map, vUv).a;
		float v = height * scaleBias.r - scaleBias.g;

		// normalize the camera's tangent space position
		vec3 eye = normalize(tsCameraPosition);

		vec2 newCoords = vUv + (eye.xy * v);
		
		vec3 color = texture2D(base, newCoords).rgb; // default color 
		vec3 normal = texture2D(map, newCoords).rgb * 2.0 - 1.0;
		
		// normalize the other tangent space vectors
		vec3 viewVector = normalize(tsCameraPosition - tsPosition);
		vec3 lightVector = normalize(tsLightSource - tsPosition);
        
		// calculate lighting values
        float nxDir = max(0.0, dot(normal, lightVector));
        vec3 ambient = ambientColor * color;

        float specularPower = 0.0;
        if(nxDir != 0.0)
        {
            vec3 halfVector = normalize(lightVector + viewVector);
			float nxHalf = max(0.0, dot(normal, halfVector));
			specularPower = pow(nxHalf, shininess);
        }
        vec3 specular = specularColor * specularPower;

        gl_FragColor = vec4(ambient + (diffuseColor * nxDir * color) + specular, 1.0);
        
		
	}
</pre>
<p>There are seven parameters passed in through the uniforms:</p>
<ul>
<li>base &#8211; the texture</li>
<li>map &#8211; normal map in RGB space, height/bump map in the alpha channel</li>
<li>ambientColor &#8211; ambient color in a vec3</li>
<li>diffuseColor &#8211; diffuse color in a vec3</li>
<li>specularColor &#8211; specular color in a vec3</li>
<li>shininess &#8211; how shiny the surface should appear</li>
<li>scaleBias &#8211; a vec2 where x = scale and y = bias
</ul>
<p>These uniform values can be played with in <a href="http://chandler.prallfamily.com/webgl/bumpmaps/parallax.html" target="_blank">the example</a> to see how they affect the texture. That&#8217;s how simple it is to incorporate parallax mapping into a WebGL application.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.chandlerprall.com/2011/08/parallax-shader-for-webgl-threejs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ThreeBuilds</title>
		<link>http://www.chandlerprall.com/2011/08/threebuilds/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=threebuilds</link>
		<comments>http://www.chandlerprall.com/2011/08/threebuilds/#comments</comments>
		<pubDate>Mon, 08 Aug 2011 02:48:26 +0000</pubDate>
		<dc:creator>chandler</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[WebGL]]></category>

		<guid isPermaLink="false">http://chandler.prallfamily.com/?p=182</guid>
		<description><![CDATA[Announcing ThreeBuilds I have seen quite a few people ask how to build there own versions of the three.js library from source. Some of them want to have the latest and greatest code, others want historical versions to compare their &#8230; <a href="http://www.chandlerprall.com/2011/08/threebuilds/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><strong>Announcing <a href="http://chandler.prallfamily.com/threebuilds/" target="_blank">ThreeBuilds</a></strong></p>
<p>I have seen quite a few people ask how to build there own versions of the <a href="https://github.com/mrdoob/three.js" target="_blank" rel="nofollow">three.js</a> library from source. Some of them want to have the latest and greatest code, others want historical versions to compare their code to. There are a number of reasons to have historical versions of a library easily available, and that is what <a href="http://chandler.prallfamily.com/threebuilds/" target="_blank">ThreeBuilds</a> aims to do. Builds are available from each three.js tag and the most recent code is rebuilt each night.</p>
<p>Each build tries to include as many of the build configurations as possible, but it wasn&#8217;t until recently that some of that functionality was added to the build script. Going forward all builds will include the uncompressed and minified files for each build configuration (All, WebGL, Canvas, etc).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.chandlerprall.com/2011/08/threebuilds/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
