├── index.html
├── js
├── blankWebVR.js
├── vr
│ ├── PhoneVR.js
│ ├── VRControls.js
│ └── VREffect.js
└── demoWebVR.js
├── README.md
└── LICENSE
/index.html:
--------------------------------------------------------------------------------
1 |
22 |
23 |
24 |
25 |
26 |
27 | webVR boilerplate
28 |
29 |
30 |
39 |
40 |
41 |
42 |
43 |
46 |
47 |
48 |
52 |
53 |
54 |
55 |
58 |
59 |
60 |
64 |
65 |
66 |
--------------------------------------------------------------------------------
/js/blankWebVR.js:
--------------------------------------------------------------------------------
1 | // Setup three.js WebGL renderer
2 | var renderer = new THREE.WebGLRenderer( { antialias: true } );
3 |
4 | // Append the canvas element created by the renderer to document body element.
5 | document.body.appendChild( renderer.domElement );
6 |
7 | //Create a three.js scene
8 | var scene = new THREE.Scene();
9 |
10 | //Create a three.js camera
11 | var camera = new THREE.PerspectiveCamera( 110, window.innerWidth / window.innerHeight, 2, 10000 );
12 | scene.add(camera);
13 |
14 | //Apply VR headset positional data to camera.
15 | var controls = new THREE.VRControls( camera );
16 |
17 | //Apply VR stereo rendering to renderer
18 | var effect = new THREE.VREffect( renderer );
19 | effect.setSize( window.innerWidth, window.innerHeight );
20 |
21 |
22 | /************* TODO: Generate Your VR Scene Below *********************/
23 |
24 |
25 | /*
26 | TODO: Create, position, and add 3d objects here
27 | */
28 |
29 |
30 | /*
31 | Request animation frame loop function
32 | */
33 | function animate() {
34 | // TODO: Apply any desired changes for the next frame here.
35 |
36 |
37 | //Update VR headset position and apply to camera.
38 | controls.update();
39 |
40 | // Render the scene through the VREffect.
41 | effect.render( scene, camera );
42 | requestAnimationFrame( animate );
43 | }
44 |
45 | animate(); // Kick off animation loop
46 |
47 |
48 |
49 | /***************** TODO: Generate Your VR Scene Above *****************/
50 |
51 |
52 |
53 | /*
54 | Listen for click event to enter full-screen mode.
55 | We listen for single click because that works best for mobile for now
56 | */
57 | document.body.addEventListener( 'click', function(){
58 | effect.setFullScreen( true );
59 | })
60 |
61 | /*
62 | Listen for keyboard events
63 | */
64 | function onkey(event) {
65 | event.preventDefault();
66 |
67 | if (event.keyCode == 90) { // z
68 | controls.resetSensor(); //zero rotation
69 | } else if (event.keyCode == 70 || event.keyCode == 13) { //f or enter
70 | effect.setFullScreen(true) //fullscreen
71 | }
72 | };
73 | window.addEventListener("keydown", onkey, true);
74 |
75 | /*
76 | Handle window resizes
77 | */
78 | function onWindowResize() {
79 | camera.aspect = window.innerWidth / window.innerHeight;
80 | camera.updateProjectionMatrix();
81 | effect.setSize( window.innerWidth, window.innerHeight );
82 | }
83 | window.addEventListener( 'resize', onWindowResize, false );
84 |
--------------------------------------------------------------------------------
/js/vr/PhoneVR.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | // It seems to be impossible to synchronously detect whether we have an orientation sensor.
4 | // Even Chromium on the desktop has a 'deviceorientation' event, and it will fire once with
5 | // all nulls.
6 |
7 | function PhoneVR() {
8 | this.deviceAlpha = null;
9 | this.deviceGamma = null;
10 | this.deviceBeta = null;
11 |
12 | window.addEventListener('deviceorientation', function(orientation) {
13 | this.deviceAlpha = orientation.alpha;
14 | this.deviceGamma = orientation.gamma;
15 | this.deviceBeta = orientation.beta;
16 | }.bind(this));
17 | }
18 |
19 | PhoneVR.prototype.orientationIsAvailable = function() {
20 | return this.deviceAlpha !== null;
21 | }
22 |
23 | PhoneVR.prototype.rotationQuat = function() {
24 | if (!this.orientationIsAvailable())
25 | return null;
26 |
27 | var degtorad = Math.PI / 180; // Degree-to-Radian conversion
28 | var z = this.deviceAlpha * degtorad / 2;
29 | var x = this.deviceBeta * degtorad / 2;
30 | var y = this.deviceGamma * degtorad / 2;
31 | var cX = Math.cos(x);
32 | var cY = Math.cos(y);
33 | var cZ = Math.cos(z);
34 | var sX = Math.sin(x);
35 | var sY = Math.sin(y);
36 | var sZ = Math.sin(z);
37 |
38 | // ZXY quaternion construction.
39 | var w = cX * cY * cZ - sX * sY * sZ;
40 | var x = sX * cY * cZ - cX * sY * sZ;
41 | var y = cX * sY * cZ + sX * cY * sZ;
42 | var z = cX * cY * sZ + sX * sY * cZ;
43 |
44 | var deviceQuaternion = new THREE.Quaternion(x, y, z, w);
45 |
46 | // Correct for the screen orientation.
47 | var screenOrientation = (this.getScreenOrientation() * degtorad)/2;
48 | var screenTransform = new THREE.Quaternion(0, 0, -Math.sin(screenOrientation), Math.cos(screenOrientation));
49 |
50 | var deviceRotation = new THREE.Quaternion();
51 | deviceRotation.multiplyQuaternions(deviceQuaternion, screenTransform);
52 |
53 | // deviceRotation is the quaternion encoding of the transformation
54 | // from camera coordinates to world coordinates. The problem is that
55 | // our shader uses conventional OpenGL coordinates
56 | // (+x = right, +y = up, +z = backward), but the DeviceOrientation
57 | // spec uses different coordinates (+x = East, +y = North, +z = up).
58 | // To fix the mismatch, we need to fix this. We'll arbitrarily choose
59 | // North to correspond to -z (the default camera direction).
60 | var r22 = Math.sqrt(0.5);
61 | deviceRotation.multiplyQuaternions(new THREE.Quaternion(-r22, 0, 0, r22), deviceRotation);
62 |
63 | return deviceRotation;
64 | }
65 |
66 | PhoneVR.prototype.getScreenOrientation = function() {
67 | switch (window.screen.orientation || window.screen.mozOrientation) {
68 | case 'landscape-primary':
69 | return 90;
70 | case 'landscape-secondary':
71 | return -90;
72 | case 'portrait-secondary':
73 | return 180;
74 | case 'portrait-primary':
75 | return 0;
76 | }
77 | if (window.orientation !== undefined)
78 | return window.orientation;
79 | }
80 |
--------------------------------------------------------------------------------
/js/demoWebVR.js:
--------------------------------------------------------------------------------
1 | // Setup three.js WebGL renderer
2 | var renderer = new THREE.WebGLRenderer( { antialias: true } );
3 |
4 | // Append the canvas element created by the renderer to document body element.
5 | document.body.appendChild( renderer.domElement );
6 |
7 | //Create a three.js scene
8 | var scene = new THREE.Scene();
9 |
10 | //Create a three.js camera
11 | var camera = new THREE.PerspectiveCamera( 110, window.innerWidth / window.innerHeight, 2, 10000 );
12 | scene.add(camera);
13 |
14 | //Apply VR headset positional data to camera.
15 | var controls = new THREE.VRControls( camera );
16 |
17 | //Apply VR stereo rendering to renderer
18 | var effect = new THREE.VREffect( renderer );
19 | effect.setSize( window.innerWidth, window.innerHeight );
20 |
21 | /*
22 | Create, position, and add 3d objects
23 | */
24 | var pi = 3.141592653589793238;
25 |
26 | var geometry = new THREE.DodecahedronGeometry(10);
27 | var material = new THREE.MeshNormalMaterial();
28 | material.side = THREE.DoubleSide;
29 | var dodecahedron = new THREE.Mesh( geometry, material );
30 | dodecahedron.position.z = -20;
31 | scene.add(dodecahedron);
32 |
33 | var tetrahedron = new THREE.Mesh(new THREE.TetrahedronGeometry(10), new THREE.MeshBasicMaterial({color: 0xEE0443, wireframe: true}));
34 | var tetrahedronIncrement = 0;
35 | var z = Math.sin(-3/2*pi/1000*tetrahedronIncrement)*40;
36 | var x = Math.cos(-3/2*pi/1000*tetrahedronIncrement)*40;
37 | tetrahedron.position.set(x, 0, z);
38 | scene.add(tetrahedron);
39 |
40 | var cubes = [];
41 | for (var i = 0; i < 10; i++) {
42 | cubes[i] = new THREE.Mesh(new THREE.BoxGeometry(10, 10, 10), new THREE.MeshBasicMaterial({color: 0x0443EE}));
43 | cubes[i].position.z = i*(-20) + 100;
44 | cubes[i].position.x = i*(-20);
45 | scene.add(cubes[i]);
46 | }
47 |
48 | var floor = new THREE.Mesh( new THREE.PlaneBufferGeometry( 1000, 1000, 1, 1 ), new THREE.MeshBasicMaterial( { color: 0x404040, side: THREE.DoubleSide } ) );
49 | floor.rotation.x = pi/2;
50 | floor.position.y = -50;
51 | scene.add( floor );
52 |
53 | /*
54 | Request animation frame loop function
55 | */
56 | function animate() {
57 | // Apply any desired changes for the next frame. In this case, we rotate our object.
58 | dodecahedron.rotation.x += 0.01;
59 | dodecahedron.rotation.y += 0.005;
60 |
61 | tetrahedron.rotation.x += 0.01;
62 | tetrahedronIncrement++;
63 | if (tetrahedronIncrement >= 1000) {
64 | tetrahedronIncrement = 0;
65 | }
66 | var z = Math.sin(-2*pi/1000*tetrahedronIncrement)*40;
67 | var x = Math.cos(-2*pi/1000*tetrahedronIncrement)*40;
68 | tetrahedron.position.set(x, 0, z);
69 |
70 | //Update VR headset position and apply to camera.
71 | controls.update();
72 |
73 | // Render the scene through the VREffect.
74 | effect.render( scene, camera );
75 | requestAnimationFrame( animate );
76 | }
77 |
78 | animate(); // Kick off animation loop
79 |
80 | /*
81 | Listen for click event to enter full-screen mode.
82 | We listen for single click because that works best for mobile for now
83 | */
84 | document.body.addEventListener( 'click', function(){
85 | effect.setFullScreen( true );
86 | })
87 |
88 | /*
89 | Listen for keyboard events
90 | */
91 | function onkey(event) {
92 | event.preventDefault();
93 |
94 | if (event.keyCode == 90) { // z
95 | controls.resetSensor(); //zero rotation
96 | } else if (event.keyCode == 70 || event.keyCode == 13) { //f or enter
97 | effect.setFullScreen(true) //fullscreen
98 | }
99 | };
100 | window.addEventListener("keydown", onkey, true);
101 |
102 | /*
103 | Handle window resizes
104 | */
105 | function onWindowResize() {
106 | camera.aspect = window.innerWidth / window.innerHeight;
107 | camera.updateProjectionMatrix();
108 | effect.setSize( window.innerWidth, window.innerHeight );
109 | }
110 | window.addEventListener( 'resize', onWindowResize, false );
111 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # The eleVR webVR Boilerplate
2 | This is the standard ThreeJS-based boilerplate for webVR currently being used by [the eleVR team](http://elevr.com). It is a starting point for web-based VR experiences that work with the Oculus Rift as well as with smartphones + a google cardboard or similar phoneVR headset. There is also a non-VR fallback for experiencing the content without a VR device.
3 |
4 | The boilerplate also has gamepad and keyboard controls that are on by default.
5 |
6 | If you would like to use this boilerplate as a starting point for your own VR projects, check out brief tutorial for doing so at the bottom of this page.
7 |
8 | # Controls:
9 | Click (or tap) to enter full-screen VR mode.
10 |
11 | Navigation Controls:
12 | - WASD + E/Q navigation support for rotation.
13 | - Arrow key navigation support for moving the location of the camera.
14 | - Gamepad joystick navigation controls.
15 | - Orientation control with a VR headset OR mobile phone.
16 |
17 | # Explanation of Files:
18 | index.html
19 | - A simple html file.
20 | - By default, it points at demoWebVR.js, which contains a demo webVR experience
21 | - You can change it to point at blankWebVR.js, which is clearly annotated for creating your own experience
22 |
23 | demoWebVR.js
24 | - A basic demo THREE.js experience is written into this file, you can use it as a guideline.
25 |
26 | blankWebVR.js
27 | - A clearly annotated boilerplate file that you can add code to to create your own webVR project from scratch
28 |
29 | [THREE.js (three.min.js)](https://github.com/mrdoob/three.js/)
30 | - WebGL helper library that lets you create webGL experiences using JS.
31 |
32 | PhoneVR.js (special thanks to [Andrew Lutomirski](https://github.com/amluto) for helping with this)
33 | - Detects whether a device with orientation is being used and turns phone orientation data into a quaternion.
34 |
35 | VRControls.js [(forked from MozVR version)](https://github.com/MozVR/vr-web-examples/tree/master/threejs-vr-boilerplate)
36 | - THREE.js controls which take advantage of the WebVR API.
37 | - Keyboard controls
38 | - Gamepad controls
39 | - Pulls in phoneVR information for phoneVR controls
40 |
41 | VREffect.js [(forked from MozVR version)](https://github.com/MozVR/vr-web-examples/tree/master/threejs-vr-boilerplate)
42 | - THREE.js effect which renders a scene with two cameras in it side by side when in webVR or on a phone for VR viewing, but just a single camera full-screen as a fallback for non-VR viewing.
43 |
44 | # WebVR Basic Tutorial
45 | 1. Obtain a webVR browser (we recommend Firefox Nightly) for your OS
46 | 1a. Also get the appropriate Oculus runtime if you are going to use with an Oculus
47 | 2. If you are using Firefox Nightly, enable webVR in your browser
48 | - enter "about:config" into your address bar
49 | - use the search tool to find "vr"
50 | - then set "dom.vr.enabled" to "true"
51 | 3. Edit demoWebVR.js in the webVR-boilerplate/js folder to create your scene.
52 | - It has some sample code already to get you started
53 | - We assume that you will use three.js, a wrapper around webGL to create your VR project.
54 | You can find some great docs for three.js here: http://threejs.org/docs/
55 | - Always Remember: Google is your friend!
56 | 3a. OR change index.html to point at blankWebVR.js in the webVR-boilerplate/js folder and create your scene from scratch
57 | - blankWebVR.js contains no sample code, but you can always cross reference demoWebVR.js if you would like some
58 |
59 | Bonus: Set up your computer to serve up your website to localhost, this allows you to do things like experiment with image and video textures and test-run your stuff on your mobile device. The fastest and simplest is probably python simple server (default port is 8000):
60 |
61 | % python -m SimpleHTTPServer [port]
62 |
63 | # Acknowledgements
64 | This boilerplate is based on [Mozilla's boilerplate](https://github.com/MozVR/vr-web-examples/tree/master/threejs-vr-boilerplate)
65 |
66 | It has been developed with the advice, help, and contributions of a great many people including (but not limited to) the other members of the eleVR team (Emily Eifler and Vi Hart), [Andrew Lutomirski](https://github.com/amluto), and Henry Segerman.
67 |
68 |
--------------------------------------------------------------------------------
/js/vr/VRControls.js:
--------------------------------------------------------------------------------
1 | /**
2 | /**
3 | * @author dmarcos / https://github.com/dmarcos
4 | * @author hawksley / https://github.com/hawksley (added support for many more forms of control)
5 | */
6 |
7 | THREE.VRControls = function ( camera, speed, done ) {
8 | this.phoneVR = new PhoneVR();
9 |
10 | this.speed = speed || 3; // 3 is just a good default speed multiplier
11 |
12 | //---game controller stuff---
13 | this.haveEvents = 'ongamepadconnected' in window;
14 | this.controllers = {};
15 |
16 | this._camera = camera;
17 |
18 | this._init = function () {
19 | var self = this;
20 |
21 | //hold down keys to do rotations and stuff
22 | function key(event, sign) {
23 | var control = self.manualControls[event.keyCode];
24 |
25 | if (typeof control === 'undefined' || sign === 1 && control.active || sign === -1 && !control.active) {
26 | return;
27 | }
28 |
29 | control.active = (sign === 1);
30 | if (self.isWASD && control.index <= 2){
31 | self.manualRotateRate[control.index] += sign * control.sign;
32 | } else if (self.isArrows && control.index <= 5) {
33 | self.manualMoveRate[control.index - 3] += sign * control.sign;
34 | }
35 | }
36 |
37 | document.addEventListener('keydown', function(event) { key(event, 1); }, false);
38 | document.addEventListener('keyup', function(event) { key(event, -1); }, false);
39 |
40 |
41 | function connecthandler(e) {
42 | addgamepad(e.gamepad);
43 | }
44 |
45 | function addgamepad(gamepad) {
46 | self.controllers[gamepad.index] = gamepad;
47 | }
48 |
49 | function disconnecthandler(e) {
50 | removegamepad(e.gamepad);
51 | }
52 |
53 | function removegamepad(gamepad) {
54 | delete self.controllers[gamepad.index];
55 | }
56 |
57 | function scangamepads() {
58 | var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
59 | for (var i = 0; i < gamepads.length; i++) {
60 | if (gamepads[i]) {
61 | if (gamepads[i].index in self.controllers) {
62 | self.controllers[gamepads[i].index] = gamepads[i];
63 | } else {
64 | addgamepad(gamepads[i]);
65 | }
66 | }
67 | }
68 | }
69 |
70 | window.addEventListener("gamepadconnected", connecthandler);
71 | window.addEventListener("gamepaddisconnected", disconnecthandler);
72 | if (!self.haveEvents) {
73 | setInterval(scangamepads, 500);
74 | }
75 |
76 | if ( !navigator.mozGetVRDevices && !navigator.getVRDevices ) {
77 | if ( done ) {
78 | done("Your browser is not VR Ready");
79 | }
80 | return;
81 | }
82 |
83 | if ( navigator.getVRDevices ) {
84 | navigator.getVRDevices().then( gotVRDevices );
85 | } else {
86 | navigator.mozGetVRDevices( gotVRDevices );
87 | }
88 |
89 | function gotVRDevices( devices ) {
90 | var vrInput;
91 | var error;
92 | for ( var i = 0; i < devices.length; ++i ) {
93 | if ( devices[i] instanceof PositionSensorVRDevice ) {
94 | vrInput = devices[i]
95 | self._vrInput = vrInput;
96 | break; // We keep the first we encounter
97 | }
98 | }
99 | if ( done ) {
100 | if ( !vrInput ) {
101 | error = 'HMD not available';
102 | }
103 | done( error );
104 | }
105 | }
106 | };
107 |
108 | this._init();
109 |
110 | this.manualRotation = new THREE.Quaternion();
111 |
112 | this.manualControls = {
113 | 65 : {index: 1, sign: 1, active: 0}, // a
114 | 68 : {index: 1, sign: -1, active: 0}, // d
115 | 87 : {index: 0, sign: 1, active: 0}, // w
116 | 83 : {index: 0, sign: -1, active: 0}, // s
117 | 81 : {index: 2, sign: -1, active: 0}, // q
118 | 69 : {index: 2, sign: 1, active: 0}, // e
119 |
120 | 38 : {index: 3, sign: -1, active: 0}, // up
121 | 40 : {index: 3, sign: 1, active: 0}, // down
122 | 37 : {index: 4, sign: 1, active: 0}, // left
123 | 39 : {index: 4, sign: -1, active: 0}, // right
124 | 191 : {index: 5, sign: 1, active: 0}, // fwd slash
125 | 222 : {index: 5, sign: -1, active: 0} // single quote
126 | };
127 |
128 | this.manualRotateRate = new Float32Array([0, 0, 0]);
129 | this.manualMoveRate = new Float32Array([0, 0, 0]);
130 | this.updateTime = 0;
131 |
132 | this.isGamepad = true;
133 | this.isArrows = true;
134 | this.isWASD = true;
135 |
136 | this.enableGamepad = function(isGamepad) {
137 | this.isGamepad = isGamepad;
138 | }
139 |
140 | this.enableArrows = function(isArrows) {
141 | this.isArrows = isArrows;
142 | }
143 |
144 | this.enableWASD = function(isWASD) {
145 | this.isWASD = isWASD;
146 | }
147 |
148 | this.update = function() {
149 | var camera = this._camera;
150 | var vrState = this.getVRState();
151 | var manualRotation = this.manualRotation;
152 | var oldTime = this.updateTime;
153 | var newTime = Date.now();
154 | this.updateTime = newTime;
155 |
156 | /*
157 | Get controller button info
158 | */
159 | // if (this.isGamepad) {
160 | var j;
161 |
162 | for (j in this.controllers) {
163 | var controller = this.controllers[j];
164 |
165 | this.manualMoveRate[1] = -1 * Math.round(controller.axes[0]);
166 | this.manualMoveRate[0] = Math.round(controller.axes[1]);
167 | this.manualRotateRate[1] = -1 * Math.round(controller.axes[3]);
168 | this.manualRotateRate[0] = -1 * Math.round(controller.axes[4]);
169 | }
170 | // }
171 |
172 | // if (this.isGamepad || this.isWASD) {
173 | var interval = (newTime - oldTime) * 0.001;
174 | var update = new THREE.Quaternion(this.manualRotateRate[0] * interval,
175 | this.manualRotateRate[1] * interval,
176 | this.manualRotateRate[2] * interval, 1.0);
177 | update.normalize();
178 | manualRotation.multiplyQuaternions(manualRotation, update);
179 | // }
180 |
181 | // if (this.isGamepad || this.isArrows) {
182 | var offset = new THREE.Vector3();
183 | if (this.manualMoveRate[0] != 0 || this.manualMoveRate[1] != 0 || this.manualMoveRate[2] != 0){
184 | offset = getFwdVector().multiplyScalar( interval * this.speed * this.manualMoveRate[0])
185 | .add(getRightVector().multiplyScalar( interval * this.speed * this.manualMoveRate[1]))
186 | .add(getUpVector().multiplyScalar( interval * this.speed * this.manualMoveRate[2]));
187 | }
188 |
189 | camera.position = camera.position.add(offset);
190 | // }
191 |
192 | if ( camera ) {
193 | if ( !vrState ) {
194 | camera.quaternion.copy(manualRotation);
195 | return;
196 | }
197 |
198 | // Applies head rotation from sensors data.
199 | var totalRotation = new THREE.Quaternion();
200 | var state = vrState.hmd.rotation;
201 | if (vrState.hmd.rotation[0] !== 0 ||
202 | vrState.hmd.rotation[1] !== 0 ||
203 | vrState.hmd.rotation[2] !== 0 ||
204 | vrState.hmd.rotation[3] !== 0) {
205 | var vrStateRotation = new THREE.Quaternion(state[0], state[1], state[2], state[3]);
206 | totalRotation.multiplyQuaternions(manualRotation, vrStateRotation);
207 | } else {
208 | totalRotation = manualRotation;
209 | }
210 |
211 | camera.quaternion.copy(totalRotation);
212 | }
213 | };
214 |
215 | this.resetSensor = function() {
216 | var vrInput = this._vrInput;
217 | if (!vrInput) {
218 | return null;
219 | }
220 | vrInput.resetSensor();
221 | };
222 |
223 | this.getRotation = function() {
224 | if ( typeof vrState == "undefined" || !vrState ) {
225 | return this.manualRotation;
226 | }
227 |
228 | var totalRotation = new THREE.Quaternion();
229 | var state = vrState.hmd.rotation;
230 | if (vrState.hmd.rotation[0] !== 0 ||
231 | vrState.hmd.rotation[1] !== 0 ||
232 | vrState.hmd.rotation[2] !== 0 ||
233 | vrState.hmd.rotation[3] !== 0) {
234 | var vrStateRotation = new THREE.Quaternion(state[0], state[1], state[2], state[3]);
235 | totalRotation.multiplyQuaternions(manualRotation, vrStateRotation);
236 | } else {
237 | totalRotation = manualRotation;
238 | }
239 |
240 | return totalRotation;
241 | };
242 |
243 | this.getVRState = function() {
244 | var vrInput = this._vrInput;
245 | var orientation;
246 | var vrState;
247 |
248 | if ( vrInput ) {
249 | orientation = vrInput.getState().orientation;
250 | } else if (this.phoneVR.rotationQuat()) {
251 | orientation = this.phoneVR.rotationQuat();
252 | } else {
253 | return null;
254 | }
255 |
256 | if (orientation == null) {
257 | return null;
258 | }
259 | vrState = {
260 | hmd : {
261 | rotation : [
262 | orientation.x,
263 | orientation.y,
264 | orientation.z,
265 | orientation.w
266 | ]
267 | }
268 | };
269 | return vrState;
270 | };
271 |
272 | function getFwdVector() {
273 | return new THREE.Vector3(0,0,1).applyQuaternion(camera.quaternion);
274 | }
275 |
276 | function getRightVector() {
277 | return new THREE.Vector3(-1,0,0).applyQuaternion(camera.quaternion);
278 | }
279 |
280 | function getUpVector() {
281 | return new THREE.Vector3(0,-1,0).applyQuaternion(camera.quaternion);
282 | }
283 | };
284 |
--------------------------------------------------------------------------------
/js/vr/VREffect.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @author dmarcos / https://github.com/dmarcos
3 | * @author hawksley / https://github.com/hawksley (added phone VR support, and fixed full screen for all devices)
4 | *
5 | * It handles stereo rendering
6 | * If mozGetVRDevices and getVRDevices APIs are not available it gracefuly falls back to a
7 | * regular renderer
8 | *
9 | * The HMD supported is the Oculus DK1 and The Web API doesn't currently allow
10 | * to query for the display resolution (only the chrome API allows it).
11 | * The dimensions of the screen are temporarly hardcoded (1280 x 800).
12 | *
13 | * For VR mode to work it has to be used with the Oculus enabled builds of Firefox or Chrome:
14 | *
15 | * Firefox:
16 | *
17 | * OSX: http://people.mozilla.com/~vladimir/vr/firefox-33.0a1.en-US.mac.dmg
18 | * WIN: http://people.mozilla.com/~vladimir/vr/firefox-33.0a1.en-US.win64-x86_64.zip
19 | *
20 | * Chrome builds:
21 | *
22 | * https://drive.google.com/folderview?id=0BzudLt22BqGRbW9WTHMtOWMzNjQ&usp=sharing#list
23 | *
24 | */
25 | THREE.VREffect = function ( renderer, done ) {
26 |
27 | var cameraLeft = new THREE.PerspectiveCamera();
28 | var cameraRight = new THREE.PerspectiveCamera();
29 |
30 | this._renderer = renderer;
31 |
32 | this._init = function() {
33 | var self = this;
34 |
35 | // default some stuff for mobile VR
36 | self.phoneVR = new PhoneVR();
37 | self.leftEyeTranslation = { x: -0.03200000151991844, y: -0, z: -0, w: 0 };
38 | self.rightEyeTranslation = { x: 0.03200000151991844, y: -0, z: -0, w: 0 };
39 | self.leftEyeFOV = { upDegrees: 53.04646464878503, rightDegrees: 47.52769258067174, downDegrees: 53.04646464878503, leftDegrees: 46.63209579904155 };
40 | self.rightEyeFOV = { upDegrees: 53.04646464878503, rightDegrees: 46.63209579904155, downDegrees: 53.04646464878503, leftDegrees: 47.52769258067174 };
41 |
42 |
43 | if ( !navigator.mozGetVRDevices && !navigator.getVRDevices ) {
44 | if ( done ) {
45 | done("Your browser is not VR Ready");
46 | }
47 | return;
48 | }
49 | if ( navigator.getVRDevices ) {
50 | navigator.getVRDevices().then( gotVRDevices );
51 | } else {
52 | navigator.mozGetVRDevices( gotVRDevices );
53 | }
54 | function gotVRDevices( devices ) {
55 | var vrHMD;
56 | var error;
57 | for ( var i = 0; i < devices.length; ++i ) {
58 | if ( devices[i] instanceof HMDVRDevice ) {
59 | vrHMD = devices[i];
60 | self._vrHMD = vrHMD;
61 | var parametersLeft = vrHMD.getEyeParameters( "left" );
62 | var parametersRight = vrHMD.getEyeParameters( "right" );
63 | self.leftEyeTranslation = parametersLeft.eyeTranslation;
64 | self.rightEyeTranslation = parametersRight.eyeTranslation;
65 | self.leftEyeFOV = parametersLeft.recommendedFieldOfView;
66 | self.rightEyeFOV = parametersRight.recommendedFieldOfView;
67 | break; // We keep the first we encounter
68 | }
69 | }
70 |
71 | if ( done ) {
72 | if ( !vrHMD ) {
73 | error = 'HMD not available';
74 | }
75 | done( error );
76 | }
77 | }
78 | };
79 |
80 | this._init();
81 |
82 | this.render = function ( scene, camera ) {
83 | var renderer = this._renderer;
84 | var vrHMD = this._vrHMD;
85 | renderer.enableScissorTest( false );
86 | // VR render mode if HMD is available
87 | if ( vrHMD ) {
88 | this.renderStereo.apply( this, arguments );
89 | return;
90 | }
91 |
92 | if (this.phoneVR.deviceAlpha !== null) { //default to stereo render for devices with orientation sensor, like mobile
93 | this.renderStereo.apply( this, arguments );
94 | return;
95 | }
96 |
97 | // Regular render mode if not HMD
98 | renderer.render.apply( this._renderer, arguments );
99 | };
100 |
101 | this.renderStereo = function( scene, camera, renderTarget, forceClear ) {
102 |
103 | var leftEyeTranslation = this.leftEyeTranslation;
104 | var rightEyeTranslation = this.rightEyeTranslation;
105 | var renderer = this._renderer;
106 | var rendererWidth = renderer.domElement.width / renderer.devicePixelRatio;
107 | var rendererHeight = renderer.domElement.height / renderer.devicePixelRatio;
108 | var eyeDivisionLine = rendererWidth / 2;
109 |
110 | renderer.enableScissorTest( true );
111 | renderer.clear();
112 |
113 | if ( camera.parent === undefined ) {
114 | camera.updateMatrixWorld();
115 | }
116 |
117 | cameraLeft.projectionMatrix = this.FovToProjection( this.leftEyeFOV, true, camera.near, camera.far );
118 | cameraRight.projectionMatrix = this.FovToProjection( this.rightEyeFOV, true, camera.near, camera.far );
119 |
120 | camera.matrixWorld.decompose( cameraLeft.position, cameraLeft.quaternion, cameraLeft.scale );
121 | camera.matrixWorld.decompose( cameraRight.position, cameraRight.quaternion, cameraRight.scale );
122 |
123 | cameraLeft.translateX( leftEyeTranslation.x );
124 | cameraRight.translateX( rightEyeTranslation.x );
125 |
126 | // render left eye
127 | renderer.setViewport( 0, 0, eyeDivisionLine, rendererHeight );
128 | renderer.setScissor( 0, 0, eyeDivisionLine, rendererHeight );
129 | renderer.render( scene, cameraLeft );
130 |
131 | // render right eye
132 | renderer.setViewport( eyeDivisionLine, 0, eyeDivisionLine, rendererHeight );
133 | renderer.setScissor( eyeDivisionLine, 0, eyeDivisionLine, rendererHeight );
134 | renderer.render( scene, cameraRight );
135 |
136 | };
137 |
138 | this.setSize = function( width, height ) {
139 | renderer.setSize( width, height );
140 | };
141 |
142 | this.setFullScreen = function( enable ) {
143 | var renderer = this._renderer;
144 | var vrHMD = this._vrHMD;
145 | var canvasOriginalSize = this._canvasOriginalSize;
146 |
147 | // If state doesn't change we do nothing
148 | if ( enable === this._fullScreen ) {
149 | return;
150 | }
151 | this._fullScreen = !!enable;
152 |
153 | if (!vrHMD) {
154 | var canvas = renderer.domElement;
155 | if (canvas.mozRequestFullScreen) {
156 | canvas.mozRequestFullScreen(); // Firefox
157 | } else if (canvas.webkitRequestFullscreen) {
158 | canvas.webkitRequestFullscreen(); // Chrome and Safari
159 | } else if (canvas.requestFullScreen){
160 | canvas.requestFullscreen();
161 | }
162 | return;
163 | }
164 |
165 | // VR Mode disabled
166 | if ( !enable ) {
167 | // Restores canvas original size
168 | renderer.setSize( canvasOriginalSize.width, canvasOriginalSize.height );
169 | return;
170 | }
171 | // VR Mode enabled
172 | this._canvasOriginalSize = {
173 | width: renderer.domElement.width,
174 | height: renderer.domElement.height
175 | };
176 | // Hardcoded Rift display size
177 | renderer.setSize( 1280, 800, false );
178 | this.startFullscreen();
179 | };
180 |
181 | this.startFullscreen = function() {
182 | var self = this;
183 | var renderer = this._renderer;
184 | var vrHMD = this._vrHMD;
185 | var canvas = renderer.domElement;
186 | var fullScreenChange =
187 | canvas.mozRequestFullScreen? 'mozfullscreenchange' : 'webkitfullscreenchange';
188 |
189 | document.addEventListener( fullScreenChange, onFullScreenChanged, false );
190 | function onFullScreenChanged() {
191 | if ( !document.mozFullScreenElement && !document.webkitFullScreenElement ) {
192 | self.setFullScreen( false );
193 | }
194 | }
195 | if ( canvas.mozRequestFullScreen ) {
196 | canvas.mozRequestFullScreen( { vrDisplay: vrHMD } );
197 | } else {
198 | canvas.webkitRequestFullscreen( { vrDisplay: vrHMD } );
199 | }
200 | };
201 |
202 | this.FovToNDCScaleOffset = function( fov ) {
203 | var pxscale = 2.0 / (fov.leftTan + fov.rightTan);
204 | var pxoffset = (fov.leftTan - fov.rightTan) * pxscale * 0.5;
205 | var pyscale = 2.0 / (fov.upTan + fov.downTan);
206 | var pyoffset = (fov.upTan - fov.downTan) * pyscale * 0.5;
207 | return { scale: [pxscale, pyscale], offset: [pxoffset, pyoffset] };
208 | };
209 |
210 | this.FovPortToProjection = function( fov, rightHanded /* = true */, zNear /* = 0.01 */, zFar /* = 10000.0 */ )
211 | {
212 | rightHanded = rightHanded === undefined ? true : rightHanded;
213 | zNear = zNear === undefined ? 0.01 : zNear;
214 | zFar = zFar === undefined ? 10000.0 : zFar;
215 |
216 | var handednessScale = rightHanded ? -1.0 : 1.0;
217 |
218 | // start with an identity matrix
219 | var mobj = new THREE.Matrix4();
220 | var m = mobj.elements;
221 |
222 | // and with scale/offset info for normalized device coords
223 | var scaleAndOffset = this.FovToNDCScaleOffset(fov);
224 |
225 | // X result, map clip edges to [-w,+w]
226 | m[0*4+0] = scaleAndOffset.scale[0];
227 | m[0*4+1] = 0.0;
228 | m[0*4+2] = scaleAndOffset.offset[0] * handednessScale;
229 | m[0*4+3] = 0.0;
230 |
231 | // Y result, map clip edges to [-w,+w]
232 | // Y offset is negated because this proj matrix transforms from world coords with Y=up,
233 | // but the NDC scaling has Y=down (thanks D3D?)
234 | m[1*4+0] = 0.0;
235 | m[1*4+1] = scaleAndOffset.scale[1];
236 | m[1*4+2] = -scaleAndOffset.offset[1] * handednessScale;
237 | m[1*4+3] = 0.0;
238 |
239 | // Z result (up to the app)
240 | m[2*4+0] = 0.0;
241 | m[2*4+1] = 0.0;
242 | m[2*4+2] = zFar / (zNear - zFar) * -handednessScale;
243 | m[2*4+3] = (zFar * zNear) / (zNear - zFar);
244 |
245 | // W result (= Z in)
246 | m[3*4+0] = 0.0;
247 | m[3*4+1] = 0.0;
248 | m[3*4+2] = handednessScale;
249 | m[3*4+3] = 0.0;
250 |
251 | mobj.transpose();
252 |
253 | return mobj;
254 | };
255 |
256 | this.FovToProjection = function( fov, rightHanded /* = true */, zNear /* = 0.01 */, zFar /* = 10000.0 */ )
257 | {
258 | var fovPort = {
259 | upTan: Math.tan(fov.upDegrees * Math.PI / 180.0),
260 | downTan: Math.tan(fov.downDegrees * Math.PI / 180.0),
261 | leftTan: Math.tan(fov.leftDegrees * Math.PI / 180.0),
262 | rightTan: Math.tan(fov.rightDegrees * Math.PI / 180.0)
263 | };
264 | return this.FovPortToProjection(fovPort, rightHanded, zNear, zFar);
265 | };
266 |
267 | };
268 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------