Informatique Graphique

WebGL et Three.js

Guillaume Gilet

OpenGL (1991 - Demain)

  • API bas-niveau
  • Multi-plateformes, multi-languages
  • Khronos Group
  • Communication avec le GPU
  • En constante évolution (4.4, Aout 2013)

WebGL (2011 - Demain)

  • Basé sur OpenGL E/S 2.0 et html5
  • Accéder au fonctionnalitées OpenGL depuis un navigateur Web
  • Utilise JavaScript
  • En constante évolution
  • Fonctionne avec la plupart des navigateurs (Attention a IE)

Three.js

  • github.com/mrdoob/three.js
  • Faciliter l'utilisation de WebGL
  • Fournit également Canvas et SVG
  • Définit :
    • Une Scène : Contient des objets
    • Une Caméra : Le point de vue
    • Un WebGLRenderer : Dessine la scène

Les bases

Créer la méthode de rendu (WebGLRenderer)


    var renderer = new THREE.WebGLRenderer({antialias: true});
    renderer.setSize(document.body.clientWidth, 
    document.body.clientHeight);
          

L'attacher au document html


    document.body.appendChild(renderer.domElement);
          

Définir la couleur de fond


    renderer.setClearColorHex(0xAAAAAA, 1.0);
    renderer.clear();
          

Exemple 1

Les bases

Une caméra et une scène

Ajoutons une caméra


    var camera = new THREE.PerspectiveCamera(45, width/height, 1, 10000);
camera.position.z = 300;
          

Une scène avec une sphère


    var scene = new THREE.Scene();
  var sphere = new THREE.Mesh(new THREE.SphereGeometry(50,50,50),
               new THREE.MeshBasicMaterial({color: 0xFF0000}));
scene.add(sphere);
          

Et Dessinons la scène depuis la caméra


    renderer.render(scene, camera);
          

Exemple 2 - Une première forme

Les bases

Sans lumière, c'est un peu plat

Ajoutons une lumière


     var light = new THREE.SpotLight();
      light.position.set( 80, 150, 250 );
      scene.add(light);
          

Un matériau qui interagit avec la lumière


  var sphere = new THREE.Mesh(new THREE.SphereGeometry(50,50,50),
      new THREE.MeshPhongMaterial( { ambient: 0x000000, 
                                     color: 0x0055ff, 
                                     specular: 0x555555, 
                                     shininess: 50 } ) );
          

Exemple 3 - Avec lumière

Les bases

3D Temps Réel - Un peu d'animation

Une fonction pour animer (un cube)


   function animate(t) {
        
          cube.rotation.set(
              1,t/800,1);
          renderer.clear();
          
          renderer.render(scene, camera);
        
        window.requestAnimationFrame(animate, renderer.domElement);
      };
      animate(new Date().getTime());
          

Exemple 4 - Avec animation