Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div id="container"></div>
              
            
!

CSS

              
                body, div, canvas {
  margin: 0;
  padding: 0;
  overflow: hidden;
}
              
            
!

JS

              
                $(document).ready(function() {

    var app = _initApp();
    app.sphere = _addTextureMesh(app);
    _attachControls(app);
    app.controls.autoRotate = true;
    app.animate();
});

function _initApp() {
  var outputDiv = document.getElementById("container");

  var app = {
		// create a scene, that will hold all our elements such as objects, cameras and lights.
		scene: new THREE.Scene(),
    renderer: new THREE.WebGLRenderer(),
    spotLight: new THREE.SpotLight(0xffffff),
    camera: new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000),
    clock: new THREE.Clock(),
    render: function() {
      app.renderer.render(app.scene, app.camera);
    },
    animate: function(dt) {
      requestAnimationFrame(app.animate);
      if(app.controls) {
        app.controls.update();
      }
        app.render();
      }
  };
  
  app.renderer.setClearColor(new THREE.Color(0xEEEEEE));
  app.renderer.setSize(window.innerWidth, window.innerHeight);

  app.spotLight.position.set(0, 0, 0);
  app.spotLight.castShadow = true;
  app.scene.add(app.spotLight);

  outputDiv.appendChild(app.renderer.domElement);

  return(app);
}

function _addTextureMesh(app) {
 var texLoader = new THREE.TextureLoader();
  
  //allow cross origin loading (http://stackoverflow.com/questions/24087757/three-js-and-loading-a-cross-domain-image#24103129)
  texLoader.crossOrigin = '';

  texLoader.load('https://dev.ngit.hr/vr/textures/sphere-uv.png', // R0010792_20160925153154_vr.jpg
    function (texture) {
      app.mesh = _createSphereMesh(texture);
      app.scene.add(app.mesh);
      app.mesh.scale.x = -1; // this will make the texture be drawn on the inner side of the sphere
    });
}

function _createSphereMesh(texture) {
  var material = new THREE.MeshBasicMaterial({
    map: texture,
    shading: THREE.FlatShading,
    side: THREE.FrontSide
  });

  var geometry = new THREE.SphereGeometry(10, 12, 6);

  // this is where the magic begins
  // ... overriding the default UV with the one built manually
  _assignUVs(geometry);
  
  var mesh = new THREE.Mesh(geometry, material);
  return(mesh);
}

function _attachControls(app) {
  app.controls = new THREE.OrbitControls(app.camera, app.renderer.domElement);
  // The [target] is positioned in the sphere center, while
  // camera is positioned a tiny bit off center.
  // This creates a small sphere, on who's surface the camera will
  // be moved/rotated by the OrbitControls. That will make
  // camera pivot in the dead center of the spkere.
  // 
  // The camera offset defines the direction in which the camera
  // will initially be facing.
  app.camera.position.set(-.1,.2,.1);
  app.controls.target.set(0,0,0);
}

function _assignUVs(geometry) {

  // This function is based on the code found at (the original source doesn't work well)
  // http://stackoverflow.com/questions/20774648/three-js-generate-uv-coordinate
  // 
  // She following page explains how UV map should be calculated
  // https://solutiondesign.com/blog/-/blogs/webgl-and-three-js-texture-mappi-1/
  // 
  // The following documentation shows what a apherical UV map should look like
  // https://threejs.org/examples/#misc_uv_tests

  // converting all vertices into polar coordinates
  var polarVertices = geometry.vertices.map(cartesian2polar);
  
  geometry.faceVertexUvs[0] = []; // This clears out any UV mapping that may have already existed on the object

  // walking through all the faces defined by the object
  // ... we need to define a UV map for each of them
  geometry.faces.forEach(function(face) {

    var uvs = [];

    // Each face is a triangle defined by three points or vertices (point a, b and c).
    // Instead of storing the three points (vertices) by itself,
    // a face uses points from the [vertices] array.
    // The 'a', 'b' and 'c' properties of the [face] object in fact represent
    // index at which each of the three points is stored in the [vertices] array
    var ids = [ 'a', 'b', 'c'];

    for( var i = 0; i < ids.length; i++ ) {

      // using the point to access the vertice
      var vertexIndex = face[ ids[ i ] ];
      var vertex = polarVertices[ vertexIndex ];

      // If the vertice is located at the top or the bottom
      // of the sphere, the x coordinates will always be 0
      // This isn't good, since it will make all the faces
      // which meet at this point use the same starting point
      // for their texture ...
      // this is a bit difficult to explainm, so try to comment out
      // the following block and take look at the top of the
      // spehere to see how it is mapped. Also have a look
      // at the following image: https://dev.ngit.hr/vr/textures/sphere-uv.png
      if(vertex.theta === 0 && (vertex.phi === 0 || vertex.phi === Math.PI)) {

        // at the sphere bottom and at the top different
        // points are alligned differently - have a look at the
        // following image https://dev.ngit.hr/vr/textures/sphere-uv.png
        var alignedVertice = vertex.phi === 0 ? face.b : face.a;

        vertex = {
          phi: vertex.phi,
          theta: polarVertices[ alignedVertice ].theta
        };
      }

      // Fixing vertices, which close the gap in the circle
      // These are the last vertices in a row, and are at identical position as
      // vertices which are at the first position in the row.
      // This causes the [theta] angle to be miscalculated
      if(vertex.theta === Math.PI && cartesian2polar(face.normal).theta < Math.PI/2) {
        vertex.theta = -Math.PI;
      }

      var canvasPoint = polar2canvas(vertex);

      uvs.push( new THREE.Vector2( 1-canvasPoint.x, 1-canvasPoint.y ) );
    }

    geometry.faceVertexUvs[ 0 ].push( uvs );
  });
  geometry.uvsNeedUpdate = true;
} // function _assignUVs(geometry) {...}

function cartesian2polar(position){
    var r=Math.sqrt(position.x*position.x + position.z*position.z + position.y*position.y);
  
    return({
      r: r,  
      phi:Math.acos(position.y / r),
      theta:Math.atan2(position.z, position.x)
    });
}

function polar2cartesian(polar){
    return({
        x: polar.distance * Math.cos(polar.radians),
        z: polar.distance * Math.sin(polar.radians)
    });
}

function polar2canvas(polarPoint) {
  return({
    y: polarPoint.phi/Math.PI,
    x: (polarPoint.theta+Math.PI) / (2*Math.PI)
  })
}
              
            
!
999px

Console