Tuesday, August 16, 2016

HTML5 Form Validation With the “pattern” Attribute_part1

In this tutorial we’ll explore HTML’s pattern attribute, using it to help us customize the way we validate our forms.

Validation

Form validation is of vital importance to a website’s security as well as its usability. The validation process evaluates whether the input value is in the correct format before submitting it. For example, if we have an input field for an email address, the value must certainly contain a valid email address; it should start with a letter or a number, followed by the @ symbol, then end with a domain name.

The HTML5 specification has made validation that bit easier with the introduction of new input types such as emailurl, and tel, and these also come packaged up with predefined validation. Whenever the value given is not met with the expected formatting, these input types will throw an error message thus preventing submission.
Invalid email address error message (Chrome)
Expecting every possible input scenario to be catered for is impractical, however. What if you have a username, zip code, or any special data types that are not specified as standard input types? How do we validate those inputs? This is where the attribute pattern comes into play.

Using the Pattern Attribute

The pattern attribute is only applicable on the input element. It allows us to define our own rule to validate the input value using Regular Expressions (RegEx). Again, if the value does not match the specified pattern, the input will throw an error.

For example, say we have a username input in our form. There isn’t a standard type for username, hence we use the regular text input type:
  1. <form action="somefile.php">
  2.     <input type="text" name="username" placeholder="Username">
  3. </form>
Let’s define a rule to add using the pattern attribute. In this case, we’ll specify that the username should only consist of lowercase letters; no capital letters, numbers or other special characters allowed. In addition, the username length shouldn’t be more than 15 characters. In RegEx, this rule can be expressed as [a-z]{1,15}.

Add [a-z]{1,15} as the value of the pattern attribute in our username input:
  1. <form action="somefile.php">
  2.     <input type="text" name="username" placeholder="Username" pattern="[a-z]{1,15}">
  3. </form>
Now, since it only accepts lowercase letters, submitting any other value will throw an error message:

The error message, stating the pattern is not matched
As you can see above, the error message says “Please match the requested format.” So our validation is working, but this message doesn’t help our users understand what the requested format actually is. UX fail.

Customizing the Validation Message

Fortunately, we can customize the message to be more helpful, and we have a couple of ways to do so. The easiest approach is to specify a title attribute within our input element:
  1. <form action="somefile.php">
  2.     <input
  3.         type="text"
  4.         name="username"
  5.         placeholder="Username"
  6.         pattern="[a-z]{1,15}"
  7.         title="Username should only contain lowercase letters. e.g. john">
  8. </form>
Now the title is included along with the default message:


Still, the popup message is inconsistent. If we compare it with the one thrown by the email input type shown earlier, the actual instructions could be more prominent.

The second approach will solve this for us.

Replacing the Default Validation Message

Let’s now replace the default “Please match the requested format” with a completely customized message. We’ll use a bit of JavaScript to do this.

Begin by adding an id to the input element, so as to be able to select it conveniently.
  1. <form action="somefile.php">
  2.     <input
  3.         type="text"
  4.         name="username"
  5.         placeholder="Username"
  6.         pattern="[a-z]{1,15}"
  7.         id="username">
  8. </form>
Now, we can select the input element using JavaScript and assign it to a variable (either between <script> tags on our page, in a separate JavaScript file, or in the JS pane on CodePen):
  1. var input = document.getElementById('username');
Lastly, we specify the message used when the input shows its invalid state.
  1. input.oninvalid = function(event) {
  2.     event.target.setCustomValidity('Username should only contain lowercase letters. e.g. john');
  3. }
The oninvalid event inherits an event object which contains a few properties, including the target property (the invalid element) and the validationMessage which contains the error text message. In the example above, we have overriden the text message using the setCustomValidity() method.

We should now find the custom message seamlessly replacing the default.


(continue)
If you found this post interesting, follow and support us.
Suggest for you:

Creating an MP3 Player with HTML5

Learn Web Development Using  HTML5 Advanced Programing

Ultimate HTML5,CSS3 & JAVASCRIPT To Create Your Own Interractive Websites

Easily Learn HTML 5 From Scratch

Ionic by Example: Create Mobile Apps in HTML5

Monday, August 15, 2016

HTML5 Mastery: Fragments


There are several types of DOM nodes. There are DocumentElementText and many more, which also implement the generalized Node. One of the more interesting, yet until now not so often used ones, is the DocumentFragment node. It is basically a special container for nodes.

A DocumentFragment node is treated specially in many DOM algorithms. In this article we will see some of the API methods that are designed for use in conjunction with the DocumentFragment. We will also see that the concept of node containers is important for other modern web technologies, such as the <template> element or the whole shadow DOM API. But before we start we should have a quick look at fragment parsing, which is not directly related to the DocumentFragment.

Fragment Parsing

An HTML5 parser can be used for more than just parsing a complete document. It can also be used for parsing a part of a document, called a fragment. Setting properties such as innerHTML or outerHTML will trigger fragment parsing. Fragment parsing works similar to regular parsing with a few exceptions. The biggest difference is the need for a contextual root.

The fragment that is being parsed is likely placed as the child of some element, which may or may not have additional ancestors. This information is crucial to determine the current parsing mode, which depends on the current tree’s hierarchy. Additionally, fragment parsing will not trigger script execution due to security reasons.

We may therefore use code like the following, but we won’t see the additional output. The script execution won’t be triggered.
  1. var foo = document.querySelector('#foo');
  2. foo.innerHTML = '<b>Hallo World!</b><script>alert("Hi.");</script>';
Using fragment parsing is a simple way to reduce DOM operations. Instead of creating, changing and appending nodes, which all involve context switches and therefore DOM operations, we work exclusively in constructing a string, which is then evaluated and handled from the parser. Hence we only have a single, or just a few, DOM operations. The disadvantage of this method is that we require the parser and more work in JavaScript. The key question is: What is more time-consuming? Are the various DOM operations more expensive than all the required JavaScript string manipulations, or is it the other way round?

Clearly this depends on the case. For a particular scenario, Grgur Grisogono did the work to compare the performance using several methods. It also depends highly on the browser, especially how fast the JavaScript engine is. A higher value means more operations and is therefore desired.


Even though browsers are faster these days, the relative behavior is still valid. This should motivate us to search for better solutions and learn more about the DocumentFragment.

Aggregate DOM Operations

The idea behind the DocumentFragment node is simple: a container for Node objects. When a DocumentFragment is appended, it is expanded to append only the contents of the container, not the container itself. When a deep copy of a DocumentFragment is requested, its content is cloned as well. The container itself will never be attached to another node, even though it has to have an owner, which is the document that created the fragment.

Creating a DocumentFragment works as follows:
  1. var fragment = document.createDocumentFragment();
From this point on, fragment behaves exactly like any other DOM parent node. We can attach nodes, remove nodes or access existing nodes. The option for running CSS queries using querySelector and querySelectorAll is available. Most importantly, as already mentioned, we can clone the node using cloneNode().

Templating in HTML

If document fragments are so great, why not use them for templating? Well, a DocumentFragment cannot be constructed in plain HTML, as the concept is only exposed via the DOM API. It is therefore only possible to create containers in JavaScript. This reduces the usage benefits a lot. Right now the most popular approach is still text-oriented. We start by placing our template in a pseudo <script> element. The element is pseudo, because the type attribute will be set to an invalid mime-type. This way nothing will be executed, but the text content of the element will use different parsing rules.

The image above shows the tokenization states. The parsing rules for script tags are special, since parsing will take place with a special tokenization state. HTML knows five tokenization states, but the fifth one, Plaintext, is not of great interest for us. The Rawtext state is very similar to Script, which leaves us with three states to explain.

Let’s consider an example. We use three elements that are good representatives for each of the three remaining states. The <div> element is, as many others, in the parsed characters (PCData) regime. The <textarea>, uses RCData like, e.g., the <title> element. Even more like raw characters is the Rawtext state, which could be represented by using a <style> element. There are subtle differences regarding escaping between the Rawtext and Script state. However, we will treat them as equivalent in the following discussion.
  1. var example = '<br>me & you > them';
  2. var types = ["div", "textarea", "script"];
  3.  
  4. types.forEach(function (type) {
  5.   var foo = document.createElement(type);
  6.   foo.innerHTML = example;
  7.   console.log(foo.innerHTML);
  8. })
Maybe we would expect that the output is the same, but even knowing that there are differences: Who knows what they look like?
  1. <br>me &amp; you &gt; them
  2. &lt;br&gt;me &amp; you &gt; them
  3. <br>me & you > them
Only the last one matches the input string perfectly. Hence we have a clear winner. So this explains why <script> elements are so popular for transporting the templating fragments. But here is where the funny part starts. Most templating engines will create a function from the string, which takes a model and spits out a list of generated DOM nodes for the view. Some may already bind the values depending on the model. The important part is the node generation, which is mostly string-oriented, at least during the first iteration.

The W3C recognized the situation and reacted by introducing the <template> element. The element can be understood as a DocumentFragment carrier. Since the DocumentFragment does not participate directly in the DOM tree, it is attached to a node via a property. Using the element is as easy as the following example:
  1. <template>
  2.   <img src="{src}" alt="{alt}">
  3.   <div class="comment">{comment}</div>
  4. </template>
In the DOM we won’t see any children of this element. All children have been attached to the contained DocumentFragment instance, which can be accessed via the content property.

Let’s get these children:
  1. var fragment = document.querySelector('template').content;
  2. var img = fragment.querySelector('img');
  3. var comments = fragment.querySelectorAll('.comment');
The text has been inserted in curly braces to indicate our intention of treating them as placeholders. There is no system of filling them out automatically.

Let’s create a function to return the instantiated nodes for us. We tailor the code for the previous example.
  1. function createNodes (model) {
  2.     var fragment = document.querySelector('template').content;
  3.     var instance = fragment.clone(true);//deep cloning!
  4.     var img = instance.querySelector('img');
  5.     img.setAttribute('src', model.src);
  6.     img.setAttribute('alt', model.alt);
  7.     var div = instance.querySelector('div');
  8.     div.textContent = model.comment;
  9.     return instance;
  10. }
Generalization is possible by iterating over all attributes of elements and child nodes, replacing text that matches a predefined structure in attributes and text nodes. Finally the instantiated nodes can be appended somewhere:
  1. var nodes = createNodes({ 
  2.     src: 'image.png',
  3.     alt: 'Image',
  4.     comment: 'Great!'
  5. });
document.querySelector('#comments').appendChild(nodes);
There are three important aspects of the <template> element:
  1. It triggers a different parsing mode. It is therefore more than just some element.
  2. Its children won’t be attached to the DOM, but to a DocumentFragment accessible via content.
  3. We have to make a deep copy of the fragment before we can use it.
Finally, a document fragment is so useful that it can be even utilized to make small parts of websites re-usable and more flexible.

The Shadow DOM

In recent years the demand for web components has exploded. Many of the front-end frameworks try to mimic a kind of web component structure. It is required, however, to have real DOM support, even though polyfills are certainly possible. The Polymer project is a good example of great polyfills, showcasing what could be done with web components.

What the shadow DOM allows us to do is to append a DocumentFragment to any Element. There are three constraints:
  1. The DocumentFragment has to be special—it has to be a ShadowRoot.
  2. Every Element can only have one ShadowRoot, or none of course.
  3. The contents of the ShadowRoot are separated from the original DOM.
These constraints have consequences.

One consequence of attaching a ShadowRoot to an element is that the element is not rendered any more—instead the content within the shadow DOM is rendered. The content is scoped, however, which means that it may follow its own styling rules. Also the whole event handling process is a little bit different.

As a result, another new concept has been introduced: slots. We can define slots in our shadow DOM, which are filled with nodes from the element, which hosts the ShadowRoot. It seems obvious that creating custom elements, which carry the shadow DOM, is a good idea. The whole custom elements specification is a reaction to that.

So how can we use the shadow DOM? Let’s do some JavaScript to reveal the API. We start with the following HTML fragment:
  1. <div id="#shadow-dialog">
  2.     <span slot="header">
  3.         My header title
  4.     </span>
  5.     <div slot="content">
  6.         <strong>Some very important content</strong>
  7.     </div>
  8. </div>
At this point everything behaves as usual. Here is where our JavaScript skills are demanded:
  1. var context = document.querySelector('#shadow-dialog');
  2. var root = context.attachShadow({ mode: 'open' });
  3. var headerSlot = document.createElement('slot');
  4. headerSlot.name = 'header';
  5. root.appendChild(headerSlot);
  6. var contentSlot = document.createElement('slot');
  7. contentSlot.name = 'content';
  8. root.appendChild(contentSlot);
Up to here we have not gained much. We started with some elements, and we are back with them. Effectively the composed DOM tree would look as follows:
  1. <div id="#shadow-dialog">
  2.     <slot name="header">
  3.         <span slot="header">
  4.             My header title
  5.         </span>
  6.     </slot>
  7.     <slot name="content">
  8.         <div slot="content">
  9.             <strong>Some very important content</strong>
  10.         </div>
  11.     </slot>
  12. </div>
By default, all nodes of our shadow root are assigned to a default slot, if there is one. A default slot does not have a name. So what have we gained? We integrated some transparent elements—congratulations! But even more importantly, our original markup does not have to change in order to change the structure, attributes or layout of our composed DOM tree. We only need to change which elements are appended to the shadow root, and that’s it. We have essentially modularized the front-end.

Now some people may think that we had similar techniques already on the server-side. And of course some client-side frameworks also try to aggregate code like this. There are some key differences, however. First, we have the browser’s full support (if implemented). Second, the sandboxing makes rendering with specific rules for that module easy—no clash with existing CSS rules. It is essentially guaranteed that the module works on every page. No more debugging to see where the CSS rules interfere with each other. Finally, we produce much nicer code. It’s easy to generate and cheap to transport, and we can expect even better performance.

Conclusion

The DocumentFragment is a useful helper that has the ability to reduce the number of DOM operations drastically. It is also an important cornerstone of modern technologies, especially in the web components area. It has already generated two really outstanding technologies: the <template> element and ShadowRoot. While the former simplifies templating a lot, giving us a nice performance speedup and an elegant way to transport pre-generated nodes, the latter is the foundation for web components.

Is it really worth knowing about the DocumentFragment? Probably not yet. If we’re writing a framework or library then it is definitely a must, but most users will be happy that is very likely already used in their favorite front-end library, such as jQuery, Angular, and others. They all use the DocumentFragment in one or more places to overcome potential performance hits. Is a virtual DOM faster than the real one? Yes, of course, but it may not be as fast without using a DocumentFragment to aggregate multiple operations.
Written by Florian Rappl

If you found this post interesting, follow and support us.
Suggest for you:

Build Responsive Real World Websites with HTML5 and CSS3

Build Professional Websites with HTML5 and CSS3 from Scratch

Advanced HTML5 Tutorial for Web Developers

Coding Made Easy: HTML & CSS For Beginners

Easily Learn HTML 5 From Scratch

Thursday, August 11, 2016

WebGL Physics and Collision Detection Using Babylon.js and Oimo.js_part 2 (end)

4. Creating Spheres & Boxes With Physics States

We’re now going to add some spheres (with an Amiga texture) and some boxes (with a wood texture) to the scene.

These meshes will have physics state set. For instance, this means that they will bounce on the floor if you launch them in the air, bounce between them after a collision has been detected, and so on. The physics engine needs to know which kind of impostor you’d like to use for the mesh (plane, sphere, or box today), as well as the mass and friction properties.

If you’ve chosen Option 1, you can download the two textures here.

Add this code to your project:
  1. function CreateMaterials() {
  2.     materialAmiga = new BABYLON.StandardMaterial("amiga", scene);
  3.     materialAmiga.diffuseTexture = new BABYLON.Texture("assets/amiga.jpg", scene);
  4.     materialAmiga.emissiveColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  5.     materialAmiga.diffuseTexture.uScale = 5;
  6.     materialAmiga.diffuseTexture.vScale = 5;
  7.     materialWood = new BABYLON.StandardMaterial("wood", scene);
  8.     materialWood.diffuseTexture = new BABYLON.Texture("assets/wood.jpg", scene);
  9.     materialWood.emissiveColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  10. }
  11. function addListeners() {
  12.     window.addEventListener("keydown", function (evt) {
  13.         // s for sphere
  14.         if (evt.keyCode == 83) {
  15.             for (var index = 0; index < 25; index++) {
  16.                 var sphere = BABYLON.Mesh.CreateSphere("Sphere0", 10, 0.5, scene);
  17.                 sphere.material = materialAmiga;
  18.                 sphere.position = new BABYLON.Vector3(0 + index / 10, 3, 5 + index / 10);
  19.                 sphere.setPhysicsState(BABYLON.PhysicsEngine.SphereImpostor, { mass: 1 });
  20.             }
  21.         }
  22.         // b for box
  23.         if (evt.keyCode == 66) {
  24.             for (var index = 0; index < 10; index++) {
  25.                 var box0 = BABYLON.Mesh.CreateBox("Box0", 0.5, scene);
  26.                 box0.position = new BABYLON.Vector3(0 + index / 5, 3, 5 + index / 5);
  27.                 box0.material = materialWood;
  28.                 box0.setPhysicsState(BABYLON.PhysicsEngine.BoxImpostor, { mass: 4 });
  29.             }
  30.         }
  31.     });
  32. }
You can see that boxes are heavier than the spheres by a factor of 4.

Note: If you need to understand how material works in Babylon.js, watch the module Introduction to WebGL 3D with HTML5 and Babylon.js: Understanding Materials and Inputs, or play with our dedicated Playground sample, Babylon.js Playground: Materials sample.

Add these two lines of code after the scene.enablePhysics line:
  1. CreateMaterials();
  2. addListeners();
And launch the web project. Navigate to the center of the museum and press the s or b keys. You’ll obtain this fun result:


5. Adding Picking Support to Click on Meshes

Let’s add another cool feature: the ability to click on one of the objects to throw it away. For that, you need to send a ray from the 2D coordinates of the mouse inside the 3D scene, check whether this ray touches one of the interesting meshes, and if so, apply an impulse force on it to try to move it.

Note: to understand how picking works, please view the MVA module Introduction to WebGL 3D with HTML5 and Babylon.js: Advanced Features. Or play with our online sample, Babylon.js Playground: Picking sample.

Add this code into the addListeners() function:
  1. canvas.addEventListener("mousedown", function (evt) {
  2.     var pickResult = scene.pick(evt.clientX, evt.clientY, function (mesh) {
  3.         if (mesh.name.indexOf("Sphere0") !== -1 || mesh.name.indexOf("Box0") !== -1) {
  4.             return true;
  5.         }
  6.         return false;
  7.     });
  8.     if (pickResult.hit) {
  9.         var dir = pickResult.pickedPoint.subtract(scene.activeCamera.position);
  10.         dir.normalize();
  11.         pickResult.pickedMesh.applyImpulse(dir.scale(1), pickResult.pickedPoint);
  12.     }
  13. });
Launch your code in your favorite browser. You can now click on your physic meshes to play with them.

6. Displaying the Bounding Boxes to Better Understand the Whole Story

Finally, we’re going to create a debug scene to let you display/hide the colliders and activate/deactivate the physics properties on them.

We’re going to inject the UI into this div:
  1. <div id=“lcContainer”>
  2.     <ul id=“listColliders”>
  3.     </ul>
  4. </div>
And we’ll use this function to handle the UI:
  1. function CreateCollidersHTMLList() {
  2.     var listColliders = document.getElementById(“listColliders”);
  3.     for (var j = 0; j < meshesColliderList.length; j++) {
  4.         var newLi = document.createElement(“li”);
  5.         var chkVisibility = document.createElement(‘input’);
  6.         chkVisibility.type = “checkbox”;
  7.         chkVisibility.name = meshesColliderList[j].name;
  8.         chkVisibility.id = “colvis” + j;
  9.         var chkPhysics = document.createElement(‘input’);
  10.         chkPhysics.type = “checkbox”;
  11.         chkPhysics.name = meshesColliderList[j].name;
  12.         chkPhysics.id = “colphysx” + j;
  13.         (function (j) {
  14.             chkVisibility.addEventListener(
  15.              “click”,
  16.              function (event) {
  17.                  onChangeVisibility(j, event);
  18.              },
  19.              false
  20.            );
  21.             chkPhysics.addEventListener(
  22.             “click”,
  23.             function (event) {
  24.                 onChangePhysics(j, event);
  25.             },
  26.             false
  27.             );
  28.         })(j)
  29.         newLi.textContent = meshesColliderList[j].name + “ visibility/physx “;
  30.         newLi.appendChild(chkVisibility);
  31.         newLi.appendChild(chkPhysics);
  32.         listColliders.appendChild(newLi);
  33.     }
  34.     function onChangeVisibility(id, event) {
  35.         if (!meshesColliderList[id].isVisible) {
  36.             meshesColliderList[id].isVisible = true;
  37.             meshesColliderList[id].material.alpha = 0.75;
  38.             meshesColliderList[id].material.ambientColor.r = 1;
  39.         }
  40.         else {
  41.             meshesColliderList[id].isVisible = false;
  42.         }
  43.     }
  44.     function onChangePhysics(id, event) {
  45.         if (!meshesColliderList[id].checkCollisions) {
  46.             meshesColliderList[id].checkCollisions = true;
  47.             meshesColliderList[id].setPhysicsState(BABYLON.PhysicsEngine.BoxImpostor, { mass: 0, 
  48.                                                    friction: 0.5, restitution: 0.7 });
  49.         }
  50.         else {
  51.             meshesColliderList[id].checkCollisions = false;
  52.             meshesColliderList[id].setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  53.         }
  54.     }
  55. }
I know, it generates a very ugly UI, but I was too lazy to spend more time on it. Feel free to improve it!

Call this new function and launch the web project. Now, for instance, display the colliders 12 and 17:


You can also, with the second checkbox, enable/disable the physics properties. For instance, if you disable the physics properties on collider 12 and launch the spheres, they will now go through this wall! This is shown in the following screenshot as the sphere surrounded by the red square:


You can play with this debugging sample directly in your browser here: Babylon.js Espilit Physicsdebug demo.

Please also have a look at this awesome demo built by Samuel Girardin that also uses Oimo.js on some funny characters:
This article is part of the web dev tech series from Microsoft.
Written by David Rousset

If you found this post interesting, follow and support us.
Suggest for you:

Build Responsive Real World Websites with HTML5 and CSS3

Build Professional Websites with HTML5 and CSS3 from Scratch

Advanced HTML5 Tutorial for Web Developers

Coding Made Easy: HTML & CSS For Beginners

Easily Learn HTML 5 From Scratch

WebGL Physics and Collision Detection Using Babylon.js and Oimo.js_part 1

Today, I’d like to share with you the basics of collisions, physics and bounding boxes by playing with the WebGL Babylon.js engine and a physics engine companion named Oimo.js.

Here’s the demo we’re going to build together: Babylon.js Espilit Physics demo with Oimo.js.


You can launch it in a WebGL-compatible browser—like IE11, Firefox, Chrome, Opera, Safari 8, or Microsoft Edge in Windows 10 Technical Preview—and then move inside the scene like in an FPS game. Press the s key to launch some spheres/balls and the b key to launch some boxes. Using your mouse, you can also click on one of the spheres or boxes to apply some impulse force on it.

1. Understanding Collisions

Looking at the Wikipedia collision detection definition, we can read that:
Collision detection typically refers to the computational problem of detecting the intersection of two or more objects. While the topic is most often associated with its use in video games and other physical simulations, it also has applications in robotics. In addition to determining whether two objects have collided, collision detection systems may also calculate time of impact (TOI), and report a contact manifold (the set of intersecting points). Collision response deals with simulating what happens when a collision is detected (see physics engine, ragdoll physics). Solving collision detection problems requires extensive use of concepts from linear algebra and computational geometry.
Let’s now unpack that definition into a cool 3D scene that will act as our starting base for this tutorial.

You can move in this great museum as you would in the real world. You won’t fall through the floor, walk through walls, or fly. We’re simulating gravity. All of that seems pretty obvious, but it requires a bunch of computation to simulate that in a 3D virtual world.

The first question we need to resolve when we think about collision detection is how complex it should be. Indeed, testing whether two complex meshes are colliding could cost a lot of CPU, even more with a JavaScript engine where it’s complex to offload that on something other than the UI thread.

To better understand how we’re managing this complexity, navigate into the Espilit museum near this desk:

You’re blocked by the table even if there seems to be some space available on the right. Is it a bug in our collision algorithm? No, it’s not (Babylon.js is free of bugs!). It’s because Michel Rousseau, the 3D artist who built this scene, has done this by choice. To simplify the collision detection, he has used a specific collider.

What’s a Collider?

Rather than testing the collisions against the complete detailed meshes, you can put them into simple invisible geometries. Those colliders will act as the mesh representation and will be used by the collision engine instead. Most of the time, you won’t see the differences but it will allow us to use much less CPU, as the math behind that is much simpler to compute.

Every engine supports at least two types of colliders: the bounding box and the bounding sphere. You’ll better understand by looking at this picture:

Extracted from: Computer Visualization, Ray Tracing, Video Games, Replacement of Bounding Boxes
This beautiful yellow duck is the mesh to be displayed. Rather than testing the collisions against each of its faces, we can try to insert it into the best bounding geometry. In this case, a box seems a better choice than a sphere to act as the mesh impostor. But the choice really depends on the mesh itself.

Let’s go back to the Espilit scene and display the invisible bounding element in a semitransparent red color:

You can now understand why you can’t move by the right side of the desk. It’s because you’re colliding (well, the Babylon.js camera is colliding) with this box. If you’d like to do so, simply change its size by lowering the width to perfectly fit the width of the desk.

Note: if you’d like to start learning Babylon.js, you can follow the free training course at Microsoft Virtual Academy (MVA). For instance, you can jump directly to Introduction to WebGL 3D with HTML5 and Babylon.js: Using Babylon.js for Beginners where we cover this collision part of Babylon.js. You can also have a look at the code inside our interactive playground tool, Babylon.js playground: Collisions sample.

Based on the complexity of the collision or physics engine, there are other types of colliders available: the capsule and the mesh, for instance.
Extracted from: Getting Started with Unity - Colliders & UnityScript
Capsule is useful for humans or humanoids as it better fits our body than a box or a sphere. Mesh is almost never the complete mesh itself—rather, it’s a simplified version of the original mesh you’re targeting—but it is still much more precise than a box, a sphere, or a capsule.

2. Loading the Starting Scene

To load our Espilit scene, you have various options:

Option 1: Download it from our GitHub repository, and then follow the Introduction to WebGL 3D with HTML5 and Babylon.js: Loading Assets module of our MVA course to learn how to load a .babylon scene. Basically, you need to host the assets and the Babylon.js engine into a web server and set the proper MIME types for the .babylon extension.

Option 2: Download this premade Visual Studio solution (.zip file).

Note: If you are unfamiliar with Visual Studio, take a look at this article: Web developers, Visual Studio could be a great free tool to develop with… Please note also that the Pro version is now free for a lot of different scenarios. It’s named Visual Studio 2013 Community Edition.

Of course, you can still follow this tutorial if you don’t want to use Visual Studio. Here is the code to load our scene. Remember that most browsers support WebGL now—remember to test for Internet Explorer even on your Mac.
  1. /// <reference path="/scripts/babylon.js" />
  2. var engine;
  3. var canvas;
  4. var scene;
  5. document.addEventListener("DOMContentLoaded", startGame, false);
  6. function startGame() {
  7.     if (BABYLON.Engine.isSupported()) {
  8.         canvas = document.getElementById("renderCanvas");
  9.         engine = new BABYLON.Engine(canvas, true);
  10.         BABYLON.SceneLoader.Load("Espilit/", "Espilit.babylon", engine, function (loadedScene) {
  11.             scene = loadedScene;
  12.     
  13.             // Wait for textures and shaders to be ready
  14.             scene.executeWhenReady(function () {
  15.                 // Attach camera to canvas inputs
  16.                 scene.activeCamera.attachControl(canvas);
  17.                  
  18.                 // Once the scene is loaded, just register a render loop to render it
  19.                 engine.runRenderLoop(function () {
  20.                     scene.render();
  21.                 });
  22.             });
  23.         }, function (progress) {
  24.             // To do: give progress feedback to user
  25.         });
  26.     }
  27. }
Using this material, you will only benefit from the embedded collision engine of Babylon.js. Indeed, we’re making a difference between our collision engine and a physics engine.

The collision engine is mostly dedicated to the camera interacting with the scene. You can enable gravity or not on the camera, and you can enable the checkCollision option on the camera and on the various meshes.

The collision engine can also help you to know if two meshes are colliding. But that’s all (this is already a lot, in fact!). The collision engine won’t generate actions, force or impulse after two Babylon.js objects are colliding. You need a physics engine for that to bring life to the objects.

The way we’ve been integrating physics in Babylon.js is via a plugin mechanism. You can read more about that here: Adding your own physics engine plugin to Babylon.js. We’re supporting two open-source physics engines: Cannon.js and Oimo.js. Oimo is now the preferred default physics engine.

If you’ve chosen Option 1 to load the scene, you then need to download Oimo.js from our GitHub. It’s a slightly updated version we’ve made to better support Babylon.js. If you’ve chosen Option 2, it’s already referenced and available in the VS solution under the scripts folder.

3. Enabling Physics Support in the Scene and Transforming Colliders Into Physics Impostors

The first thing to do is to enable physics on the scene. For that, please add these lines of code:
  1. scene.enablePhysics(new BABYLON.Vector3(0, -10, 0), new BABYLON.OimoJSPlugin());
  2. //scene.enablePhysics(new BABYLON.Vector3(0, -10, 0), new BABYLON.CannonJSPlugin());
You’re setting up the gravity level (-10 on the Y axis in this sample code, which is more or less like what we have on Earth) and the physics engine you’d like to use. We’ll use Oimo.js, but the commented line shows how to use Cannon.js.

Now, we need to iterate through all non-visible colliders used by the collision engine and activate physics properties on it. For that, you simply need to find all meshes where checkCollisions is set to true but not visible in the scene:
  1. for (var i = 1; i < scene.meshes.length; i++) {
  2.     if (scene.meshes[i].checkCollisions && scene.meshes[i].isVisible === false) {
  3.         scene.meshes[i].setPhysicsState(BABYLON.PhysicsEngine.BoxImpostor, { mass: 0, 
  4.                                         friction: 0.5, restitution: 0.7 });
  5.         meshesColliderList.push(scene.meshes[i]);
  6.     }
  7. }
Please declare the meshesColliderList also:
  1. var meshesColliderList = [];
And we’re done! We’re ready to throw some objects in our scene and put a lot of mess in this beautiful but way-too-calm museum.
Written by David Rousset

If you found this post interesting, follow and support us.
Suggest for you:

Advanced HTML5 Tutorial for Web Developers

Build Professional Websites with HTML5 and CSS3 from Scratch

Build Responsive Real World Websites with HTML5 and CSS3

Build Real World Websites from Scratch using HTML5 and CSS3

Learn Web Development Using  HTML5 Advanced Programing