WebGL With Three.js – Lesson 7

WebGL With Three.js – Lesson 7

0 60005
WebGL With Three.js - Lesson 7
WebGL With Three.js - Lesson 7

WebGL With Three.js – Lesson 7

Our lessons on webgl are continuing. Today we extend the practice of loading ready three-dimensional models. In constant conditions of lack of time, it is always more convenient to simply download and implement a ready-made model than to implement it programmatically. At the moment, many loaders for three.js are already developed. In this article we will review the following loaders: AWDLoader, BabylonLoader, PDBLoader, PLYLoader, STLLoader, VRMLLoader and VTKLoader. Yes, it’s a lot more at once, but we have to finish with the loaders to start on the next topic in the next lesson.

Live Demo

Preparation

Before all, we need to prepare a skeleton (main scene) for all our uploaders. In this step, we need to create a new text file, and, let’s name it as ‘index.html’. Here is the source of it:

<!DOCTYPE html>
<html lang="en" >
    <head>
        <meta charset="utf-8" />
        <meta name="author" content="Script Tutorials" />
        <title>WebGL With Three.js - Lesson 7 - loading three-dimensional models | Script Tutorials</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
        <link href="css/main.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
        <script src="js/three.min.js"></script>
        <script src="js/AWDLoader.js"></script>
        <script src="js/BabylonLoader.js"></script>
        <script src="js/PDBLoader.js"></script>
        <script src="js/PLYLoader.js"></script>
        <script src="js/STLLoader.js"></script>
        <script src="js/VRMLLoader.js"></script>
        <script src="js/VTKLoader.js"></script>
        <script src="js/THREEx.WindowResize.js"></script>
        <script src="js/OrbitControls.js"></script>
        <script src="js/stats.min.js"></script>
        <script src="js/script.js"></script>
    </body>
</html>

As you noticed, we attached all the standard libraries (three.js, WindowResize, OrbitControls and stats) and all the loaders at once. In today’s example we will load all 9 different types of models at once.

Preparation of the main webgl scene

script.js

var lesson7 = {
  scene: null,
  camera: null,
  renderer: null,
  container: null,
  controls: null,
  clock: null,
  stats: null,
  init: function() { // Initialization
    // create main scene
    this.scene = new THREE.Scene();
    this.scene.fog = new THREE.FogExp2(0xcce0ff, 0.0003);
    var SCREEN_WIDTH = window.innerWidth,
        SCREEN_HEIGHT = window.innerHeight;
    // prepare camera
    var VIEW_ANGLE = 60, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 0.1, FAR = 20000;
    this.camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR);
    this.scene.add(this.camera);
    this.camera.position.set(-27, 15, -25);
    this.camera.lookAt(new THREE.Vector3(0,0,0));
    // prepare renderer
    this.renderer = new THREE.WebGLRenderer({ antialias:true });
    this.renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
    this.renderer.setClearColor(this.scene.fog.color);
    this.renderer.shadowMapEnabled = true;
    this.renderer.shadowMapSoft = true;
    // prepare container
    this.container = document.createElement('div');
    document.body.appendChild(this.container);
    this.container.appendChild(this.renderer.domElement);
    // events
    THREEx.WindowResize(this.renderer, this.camera);
    // prepare controls (OrbitControls)
    this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);
    this.controls.target = new THREE.Vector3(0, 0, 0);
    this.controls.maxDistance = 3000;
    // prepare clock
    this.clock = new THREE.Clock();
    // prepare stats
    this.stats = new Stats();
    this.stats.domElement.style.position = 'absolute';
    this.stats.domElement.style.left = '50px';
    this.stats.domElement.style.bottom = '50px';
    this.stats.domElement.style.zIndex = 1;
    this.container.appendChild( this.stats.domElement );
    this.scene.add( new THREE.AmbientLight(0x606060) );
    // light
    var dirLight = new THREE.DirectionalLight(0xffffff);
    dirLight.position.set(200, 200, 1000).normalize();
    this.camera.add(dirLight);
    this.camera.add(dirLight.target);
    // load models
    this.loadModels();
  },
  loadModels: function() {
    // here we will load all the models ...
  }
};
// Animate the scene
function animate() {
  requestAnimationFrame(animate);
  render();
  update();
}
// Update controls and stats
function update() {
  lesson7.controls.update(lesson7.clock.getDelta());
  lesson7.stats.update();
}
// Render the scene
function render() {
  if (lesson7.renderer) {
    lesson7.renderer.render(lesson7.scene, lesson7.camera);
  }
}
// Initialize lesson on page load
function initializeLesson() {
  lesson7.init();
  animate();
}
if (window.addEventListener)
  window.addEventListener('load', initializeLesson, false);
else if (window.attachEvent)
  window.attachEvent('onload', initializeLesson);
else window.onload = initializeLesson;

With this code we created an empty scene (with light fog), camera, renderer, controler, stats, light and ground. We also prepared another function ‘loadModels’, where we will put all our loaders.

AWDLoader

About AWD – AWD is a binary file format for 3D scenes, objects and related data. It’s main use is with the Away3D engine, but any encoder/decoder that conforms with the open specification can work with AWD files. The file format specification and a set of tools for working with AWD files are maintained by the Away3D development team. AWD is designed to be light-weight, fast and easy to parse, and to be extensible both by user applications and future versions of the file format, while remaining both forwards and backwards compatible.

To load AWD files into three.js you can use the following code:

  // prepare AWD loader and load the model
  var oAwdLoader = new THREE.AWDLoader();
  oAwdLoader.load('models/sample.awd', function(object) {
    object.position.set(-10, 1, -15);
    object.scale.set(0.1, 0.1, 0.1);
    lesson7.scene.add(object);
  });

BabylonLoader

About – Babylon.js uses a JSON file format for describing scenes.

To load babylon files into three.js you can use the following code:

  // prepare Babylon loader and load the model
  var oBabylonLoader = new THREE.BabylonLoader();
  oBabylonLoader.load('models/rabbit.babylon', function(object) {
    // apply custom material
    object.traverse( function(child) {
      if (child instanceof THREE.Mesh) {
        // apply custom material (texture)
        var textureD = THREE.ImageUtils.loadTexture('models/0.jpg', undefined, function() {
          child.material = new THREE.MeshLambertMaterial({  map: textureD });
          child.position.set(-10, 0, -5);
          child.scale.set(0.1, 0.1, 0.1);
          lesson7.scene.add(child);
        });
        textureD.needsUpdate = true;
        textureD.magFilter = THREE.NearestFilter;
        textureD.repeat.set(1, 1);
        textureD.wrapS = textureD.wrapT = THREE.RepeatWrapping;
        textureD.anisotropy = 16;
      }
    });
  });

PDBLoader

About – he Protein Data Bank (PDB) is a repository for the three-dimensional structural data of large biological molecules, such as proteins and nucleic acids.

To load PDB files into three.js you can use the following code:

  // prepare PDB loader and load the model
  var oPdbLoader = new THREE.PDBLoader();
  oPdbLoader.load('models/caf2.pdb', function(geometry, geometryBonds) {
    var group = new THREE.Object3D();
    var i = 0;
    geometry.vertices.forEach(function (position) {
      var sphere = new THREE.SphereGeometry(0.3);
      var material = new THREE.MeshPhongMaterial({color: geometry.colors[i++]});
      var mesh = new THREE.Mesh(sphere, material);
      mesh.position.copy(position);
      group.add(mesh);
    });
    for (var j = 0; j < geometryBonds.vertices.length; j += 2) {
      var path = new THREE.SplineCurve3([geometryBonds.vertices[j], geometryBonds.vertices[j + 1]]);
      var tube = new THREE.TubeGeometry(path, 1, 0.05)
      var material = new THREE.MeshPhongMaterial({color: 0xcccccc});
      var mesh = new THREE.Mesh(tube, material);
      group.add(mesh);
    }
    group.position.set(20, 5, -20);
    group.scale.set(2, 2, 2);
    lesson7.scene.add(group);
  });

PLYLoader

About – PLY is a computer file format known as the Polygon File Format or the Stanford Triangle Format. The format was principally designed to store three-dimensional data from 3D scanners. It supports a relatively simple description of a single object as a list of nominally flat polygons. A variety of properties can be stored including: color and transparency, surface normals, texture coordinates and data confidence values. The format permits one to have different properties for the front and back of a polygon.

To load PLY files into three.js you can use the following code:

  // prepare PLY loader and load the model
  var oPlyLoader = new THREE.PLYLoader();
  oPlyLoader.load('models/F117.ply', function(geometry) {
    var material = new THREE.MeshBasicMaterial({color: 0xff4444});
    var mesh = new THREE.Mesh(geometry, material);
    mesh.rotation.set( - Math.PI / 2 - 0.2, 0, - Math.PI / 2 + 0.2);
    mesh.position.set(-20, 15, 10);
    mesh.scale.set(2, 2, 2);
    lesson7.scene.add(mesh);
  });

STLLoader

About – STL (STereoLithography) is a file format native to the stereolithography CAD software created by 3D Systems. STL is also known as Standard Tessellation Language. This file format is supported by many other software packages; it is widely used for rapid prototyping and computer-aided manufacturing. STL files describe only the surface geometry of a three-dimensional object without any representation of color, texture or other common CAD model attributes. The STL format specifies both ASCII and binary representations. Binary files are more common, since they are more compact.

To load STL files into three.js you can use the following code:

  // prepare STL loader and load the model
  var oStlLoader = new THREE.STLLoader();
  oStlLoader.load('models/piano.stl', function(geometry) {
    var material = new THREE.MeshNormalMaterial();
    var mesh = new THREE.Mesh(geometry, material);
    mesh.rotation.set( - Math.PI / 2, 0, Math.PI / 2);
    mesh.position.set(-10, 0, 10);
    mesh.scale.set(2, 2, 2);
    lesson7.scene.add(mesh);
  });

VRMLLoader

About – VRML is a text file format where, e.g., vertices and edges for a 3D polygon can be specified along with the surface color, UV mapped textures, shininess, transparency, and so on. URLs can be associated with graphical components so that a web browser might fetch a webpage or a new VRML file from the Internet when the user clicks on the specific graphical component. Animations, sounds, lighting, and other aspects of the virtual world can interact with the user or may be triggered by external events such as timers. A special Script Node allows the addition of program code (e.g., written in Java or ECMAScript) to a VRML file.

To load WRL files into three.js you can use the following code:

  // prepare WRL loader and load the model
  var oWrlLoader = new THREE.VRMLLoader();
  oWrlLoader.load('models/house.wrl', function(geometry) {
    lesson7.scene.add(geometry);
  });

VTKLoader

About – The Visualization Toolkit (VTK) is an open-source, freely available software system for 3D computer graphics, image processing and visualization. VTK consists of a C++ class library and several interpreted interface layers including Tcl/Tk, Java, and Python. Kitware, whose team created and continues to extend the toolkit, offers professional support and consulting services for VTK. VTK supports a wide variety of visualization algorithms including: scalar, vector, tensor, texture, and volumetric methods; and advanced modeling techniques such as: implicit modeling, polygon reduction, mesh smoothing, cutting, contouring, and Delaunay triangulation. VTK has an extensive information visualization framework, has a suite of 3D interaction widgets, supports parallel processing, and integrates with various databases on GUI toolkits such as Qt and Tk. VTK is cross-platform and runs on Linux, Windows, Mac and Unix platforms. VTK also includes ancillary support for 3D interaction widgets, two and three-dimensional annotation, and parallel computing. At its core VTK is implemented as a C++ toolkit, requiring users to build applications by combining various objects into an application. The system also supports automated wrapping of the C++ core into Python, Java and Tcl, so that VTK applications may also be written using these interpreted programming languages.

To load VTK files into three.js you can use the following code:

  // prepare VTK loader and load the model
  var oVtkLoader = new THREE.VTKLoader();
  oVtkLoader.load('models/bunny.vtk', function(geometry) {
    geometry.computeVertexNormals();
    var material = new THREE.MeshLambertMaterial( { color:0xff4444, side: THREE.DoubleSide } );
    var mesh = new THREE.Mesh(geometry, material);
    mesh.position.set(0, 0, -15);
    mesh.scale.set(20, 20, 20);
    lesson7.scene.add(mesh);
  });

Live Demo

[sociallocker]

download in package

[/sociallocker]

SIMILAR ARTICLES

Understanding Closures

0 24610

NO COMMENTS

Leave a Reply