├── .gitignore ├── README.md ├── glUtils.js ├── index.html ├── sylvester.src.js └── webgl-path-tracing.js /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WebGL Path Tracing 2 | 3 | ![](http://evanw.github.com/webgl-path-tracing/image.png) 4 | 5 | [Try it live](http://madebyevan.com/webgl-path-tracing/) (requires a browser with WebGL) 6 | 7 | Path tracing is a realistic lighting algorithm that simulates light bouncing around a scene. This path tracer uses WebGL for realtime performance and supports diffuse, mirrored, and glossy surfaces. The path tracer is continually rendering, so the scene will start off grainy and become smoother over time. 8 | 9 | The entire scene is dynamically compiled into a GLSL shader. Everything can be repositioned using the current shader, but any geometry or material change means a recompilation. To calculate a pixel color, a ray is shot into the scene and allowed to bounce around five times. At each bounce, the direct light incoming at that point (including shadows) is multiplied by all previous material colors and accumulated. Soft shadows are achieved by randomly jittering the light position per-pixel. 10 | -------------------------------------------------------------------------------- /glUtils.js: -------------------------------------------------------------------------------- 1 | // augment Sylvester some 2 | Matrix.Translation = function (v) 3 | { 4 | if (v.elements.length == 2) { 5 | var r = Matrix.I(3); 6 | r.elements[2][0] = v.elements[0]; 7 | r.elements[2][1] = v.elements[1]; 8 | return r; 9 | } 10 | 11 | if (v.elements.length == 3) { 12 | var r = Matrix.I(4); 13 | r.elements[0][3] = v.elements[0]; 14 | r.elements[1][3] = v.elements[1]; 15 | r.elements[2][3] = v.elements[2]; 16 | return r; 17 | } 18 | 19 | throw "Invalid length for Translation"; 20 | } 21 | 22 | Matrix.prototype.flatten = function () 23 | { 24 | var result = []; 25 | if (this.elements.length == 0) 26 | return []; 27 | 28 | 29 | for (var j = 0; j < this.elements[0].length; j++) 30 | for (var i = 0; i < this.elements.length; i++) 31 | result.push(this.elements[i][j]); 32 | return result; 33 | } 34 | 35 | Matrix.prototype.ensure4x4 = function() 36 | { 37 | if (this.elements.length == 4 && 38 | this.elements[0].length == 4) 39 | return this; 40 | 41 | if (this.elements.length > 4 || 42 | this.elements[0].length > 4) 43 | return null; 44 | 45 | for (var i = 0; i < this.elements.length; i++) { 46 | for (var j = this.elements[i].length; j < 4; j++) { 47 | if (i == j) 48 | this.elements[i].push(1); 49 | else 50 | this.elements[i].push(0); 51 | } 52 | } 53 | 54 | for (var i = this.elements.length; i < 4; i++) { 55 | if (i == 0) 56 | this.elements.push([1, 0, 0, 0]); 57 | else if (i == 1) 58 | this.elements.push([0, 1, 0, 0]); 59 | else if (i == 2) 60 | this.elements.push([0, 0, 1, 0]); 61 | else if (i == 3) 62 | this.elements.push([0, 0, 0, 1]); 63 | } 64 | 65 | return this; 66 | }; 67 | 68 | Matrix.prototype.make3x3 = function() 69 | { 70 | if (this.elements.length != 4 || 71 | this.elements[0].length != 4) 72 | return null; 73 | 74 | return Matrix.create([[this.elements[0][0], this.elements[0][1], this.elements[0][2]], 75 | [this.elements[1][0], this.elements[1][1], this.elements[1][2]], 76 | [this.elements[2][0], this.elements[2][1], this.elements[2][2]]]); 77 | }; 78 | 79 | Vector.prototype.flatten = function () 80 | { 81 | return this.elements; 82 | }; 83 | 84 | function mht(m) { 85 | var s = ""; 86 | if (m.length == 16) { 87 | for (var i = 0; i < 4; i++) { 88 | s += "[" + m[i*4+0].toFixed(4) + "," + m[i*4+1].toFixed(4) + "," + m[i*4+2].toFixed(4) + "," + m[i*4+3].toFixed(4) + "]
"; 89 | } 90 | } else if (m.length == 9) { 91 | for (var i = 0; i < 3; i++) { 92 | s += "[" + m[i*3+0].toFixed(4) + "," + m[i*3+1].toFixed(4) + "," + m[i*3+2].toFixed(4) + "]
"; 93 | } 94 | } else { 95 | return m.toString(); 96 | } 97 | return s; 98 | } 99 | 100 | // 101 | // gluLookAt 102 | // 103 | function makeLookAt(ex, ey, ez, 104 | cx, cy, cz, 105 | ux, uy, uz) 106 | { 107 | var eye = $V([ex, ey, ez]); 108 | var center = $V([cx, cy, cz]); 109 | var up = $V([ux, uy, uz]); 110 | 111 | var mag; 112 | 113 | var z = eye.subtract(center).toUnitVector(); 114 | var x = up.cross(z).toUnitVector(); 115 | var y = z.cross(x).toUnitVector(); 116 | 117 | var m = $M([[x.e(1), x.e(2), x.e(3), 0], 118 | [y.e(1), y.e(2), y.e(3), 0], 119 | [z.e(1), z.e(2), z.e(3), 0], 120 | [0, 0, 0, 1]]); 121 | 122 | var t = $M([[1, 0, 0, -ex], 123 | [0, 1, 0, -ey], 124 | [0, 0, 1, -ez], 125 | [0, 0, 0, 1]]); 126 | return m.x(t); 127 | } 128 | 129 | // 130 | // glOrtho 131 | // 132 | function makeOrtho(left, right, 133 | bottom, top, 134 | znear, zfar) 135 | { 136 | var tx = -(right+left)/(right-left); 137 | var ty = -(top+bottom)/(top-bottom); 138 | var tz = -(zfar+znear)/(zfar-znear); 139 | 140 | return $M([[2/(right-left), 0, 0, tx], 141 | [0, 2/(top-bottom), 0, ty], 142 | [0, 0, -2/(zfar-znear), tz], 143 | [0, 0, 0, 1]]); 144 | } 145 | 146 | // 147 | // gluPerspective 148 | // 149 | function makePerspective(fovy, aspect, znear, zfar) 150 | { 151 | var ymax = znear * Math.tan(fovy * Math.PI / 360.0); 152 | var ymin = -ymax; 153 | var xmin = ymin * aspect; 154 | var xmax = ymax * aspect; 155 | 156 | return makeFrustum(xmin, xmax, ymin, ymax, znear, zfar); 157 | } 158 | 159 | // 160 | // glFrustum 161 | // 162 | function makeFrustum(left, right, 163 | bottom, top, 164 | znear, zfar) 165 | { 166 | var X = 2*znear/(right-left); 167 | var Y = 2*znear/(top-bottom); 168 | var A = (right+left)/(right-left); 169 | var B = (top+bottom)/(top-bottom); 170 | var C = -(zfar+znear)/(zfar-znear); 171 | var D = -2*zfar*znear/(zfar-znear); 172 | 173 | return $M([[X, 0, A, 0], 174 | [0, Y, B, 0], 175 | [0, 0, C, D], 176 | [0, 0, -1, 0]]); 177 | } 178 | 179 | // 180 | // glOrtho 181 | // 182 | function makeOrtho(left, right, bottom, top, znear, zfar) 183 | { 184 | var tx = - (right + left) / (right - left); 185 | var ty = - (top + bottom) / (top - bottom); 186 | var tz = - (zfar + znear) / (zfar - znear); 187 | 188 | return $M([[2 / (right - left), 0, 0, tx], 189 | [0, 2 / (top - bottom), 0, ty], 190 | [0, 0, -2 / (zfar - znear), tz], 191 | [0, 0, 0, 1]]); 192 | } 193 | 194 | -------------------------------------------------------------------------------- /index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | WebGL Path Tracing 4 | 67 | 68 | 69 | 70 | 71 |

WebGL Path Tracing

72 | 73 |

Path tracing is a realistic lighting algorithm that simulates light bouncing around a scene.  This path tracer uses WebGL for realtime performance and supports diffuse, mirrored, and glossy surfaces.  The path tracer is continually rendering, so the scene will start off grainy and become smoother over time.  Here's how to interact with it:

74 | 75 | 82 | 83 |
84 | 85 |
86 | 87 |

88 | 89 | 90 | 91 |

92 | 93 |

94 | Material: 95 | 100 | 101 |
with glossiness factor: 0 < < 1 102 |
103 |
104 | 105 | Environment: 106 | 110 |

111 | 112 |

113 | Load preset scene: 114 |
115 |
116 |
117 |
118 |
119 |
120 |

121 |
122 | 123 |

The entire scene is dynamically compiled into a GLSL shader.  Everything can be repositioned using the current shader, but any geometry or material change means a recompilation.  To calculate a pixel color, a ray is shot into the scene and allowed to bounce around five times.  At each bounce, the direct light incoming at that point (including shadows) is multiplied by all previous material colors and accumulated.  Soft shadows are achieved by randomly jittering the light position per-pixel.  The path tracing solution will only completely converge if your browser supports the OES_texture_float extension.

124 | 125 | 126 | -------------------------------------------------------------------------------- /sylvester.src.js: -------------------------------------------------------------------------------- 1 | // === Sylvester === 2 | // Vector and Matrix mathematics modules for JavaScript 3 | // Copyright (c) 2007 James Coglan 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining 6 | // a copy of this software and associated documentation files (the "Software"), 7 | // to deal in the Software without restriction, including without limitation 8 | // the rights to use, copy, modify, merge, publish, distribute, sublicense, 9 | // and/or sell copies of the Software, and to permit persons to whom the 10 | // Software is furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included 13 | // in all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 16 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 18 | // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 20 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 21 | // DEALINGS IN THE SOFTWARE. 22 | 23 | var Sylvester = { 24 | version: '0.1.3', 25 | precision: 1e-6 26 | }; 27 | 28 | function Vector() {} 29 | Vector.prototype = { 30 | 31 | // Returns element i of the vector 32 | e: function(i) { 33 | return (i < 1 || i > this.elements.length) ? null : this.elements[i-1]; 34 | }, 35 | 36 | // Returns the number of elements the vector has 37 | dimensions: function() { 38 | return this.elements.length; 39 | }, 40 | 41 | // Returns the modulus ('length') of the vector 42 | modulus: function() { 43 | return Math.sqrt(this.dot(this)); 44 | }, 45 | 46 | // Returns true iff the vector is equal to the argument 47 | eql: function(vector) { 48 | var n = this.elements.length; 49 | var V = vector.elements || vector; 50 | if (n != V.length) { return false; } 51 | do { 52 | if (Math.abs(this.elements[n-1] - V[n-1]) > Sylvester.precision) { return false; } 53 | } while (--n); 54 | return true; 55 | }, 56 | 57 | // Returns a copy of the vector 58 | dup: function() { 59 | return Vector.create(this.elements); 60 | }, 61 | 62 | // Maps the vector to another vector according to the given function 63 | map: function(fn) { 64 | var elements = []; 65 | this.each(function(x, i) { 66 | elements.push(fn(x, i)); 67 | }); 68 | return Vector.create(elements); 69 | }, 70 | 71 | // Calls the iterator for each element of the vector in turn 72 | each: function(fn) { 73 | var n = this.elements.length, k = n, i; 74 | do { i = k - n; 75 | fn(this.elements[i], i+1); 76 | } while (--n); 77 | }, 78 | 79 | // Returns a new vector created by normalizing the receiver 80 | toUnitVector: function() { 81 | var r = this.modulus(); 82 | if (r === 0) { return this.dup(); } 83 | return this.map(function(x) { return x/r; }); 84 | }, 85 | 86 | // Returns the angle between the vector and the argument (also a vector) 87 | angleFrom: function(vector) { 88 | var V = vector.elements || vector; 89 | var n = this.elements.length, k = n, i; 90 | if (n != V.length) { return null; } 91 | var dot = 0, mod1 = 0, mod2 = 0; 92 | // Work things out in parallel to save time 93 | this.each(function(x, i) { 94 | dot += x * V[i-1]; 95 | mod1 += x * x; 96 | mod2 += V[i-1] * V[i-1]; 97 | }); 98 | mod1 = Math.sqrt(mod1); mod2 = Math.sqrt(mod2); 99 | if (mod1*mod2 === 0) { return null; } 100 | var theta = dot / (mod1*mod2); 101 | if (theta < -1) { theta = -1; } 102 | if (theta > 1) { theta = 1; } 103 | return Math.acos(theta); 104 | }, 105 | 106 | // Returns true iff the vector is parallel to the argument 107 | isParallelTo: function(vector) { 108 | var angle = this.angleFrom(vector); 109 | return (angle === null) ? null : (angle <= Sylvester.precision); 110 | }, 111 | 112 | // Returns true iff the vector is antiparallel to the argument 113 | isAntiparallelTo: function(vector) { 114 | var angle = this.angleFrom(vector); 115 | return (angle === null) ? null : (Math.abs(angle - Math.PI) <= Sylvester.precision); 116 | }, 117 | 118 | // Returns true iff the vector is perpendicular to the argument 119 | isPerpendicularTo: function(vector) { 120 | var dot = this.dot(vector); 121 | return (dot === null) ? null : (Math.abs(dot) <= Sylvester.precision); 122 | }, 123 | 124 | // Returns the result of adding the argument to the vector 125 | add: function(vector) { 126 | var V = vector.elements || vector; 127 | if (this.elements.length != V.length) { return null; } 128 | return this.map(function(x, i) { return x + V[i-1]; }); 129 | }, 130 | 131 | // Returns the result of subtracting the argument from the vector 132 | subtract: function(vector) { 133 | var V = vector.elements || vector; 134 | if (this.elements.length != V.length) { return null; } 135 | return this.map(function(x, i) { return x - V[i-1]; }); 136 | }, 137 | 138 | // Returns the result of multiplying the elements of the vector by the argument 139 | multiply: function(k) { 140 | return this.map(function(x) { return x*k; }); 141 | }, 142 | 143 | x: function(k) { return this.multiply(k); }, 144 | 145 | // Returns the scalar product of the vector with the argument 146 | // Both vectors must have equal dimensionality 147 | dot: function(vector) { 148 | var V = vector.elements || vector; 149 | var i, product = 0, n = this.elements.length; 150 | if (n != V.length) { return null; } 151 | do { product += this.elements[n-1] * V[n-1]; } while (--n); 152 | return product; 153 | }, 154 | 155 | // Returns the vector product of the vector with the argument 156 | // Both vectors must have dimensionality 3 157 | cross: function(vector) { 158 | var B = vector.elements || vector; 159 | if (this.elements.length != 3 || B.length != 3) { return null; } 160 | var A = this.elements; 161 | return Vector.create([ 162 | (A[1] * B[2]) - (A[2] * B[1]), 163 | (A[2] * B[0]) - (A[0] * B[2]), 164 | (A[0] * B[1]) - (A[1] * B[0]) 165 | ]); 166 | }, 167 | 168 | // Returns the (absolute) largest element of the vector 169 | max: function() { 170 | var m = 0, n = this.elements.length, k = n, i; 171 | do { i = k - n; 172 | if (Math.abs(this.elements[i]) > Math.abs(m)) { m = this.elements[i]; } 173 | } while (--n); 174 | return m; 175 | }, 176 | 177 | // Returns the index of the first match found 178 | indexOf: function(x) { 179 | var index = null, n = this.elements.length, k = n, i; 180 | do { i = k - n; 181 | if (index === null && this.elements[i] == x) { 182 | index = i + 1; 183 | } 184 | } while (--n); 185 | return index; 186 | }, 187 | 188 | // Returns a diagonal matrix with the vector's elements as its diagonal elements 189 | toDiagonalMatrix: function() { 190 | return Matrix.Diagonal(this.elements); 191 | }, 192 | 193 | // Returns the result of rounding the elements of the vector 194 | round: function() { 195 | return this.map(function(x) { return Math.round(x); }); 196 | }, 197 | 198 | // Returns a copy of the vector with elements set to the given value if they 199 | // differ from it by less than Sylvester.precision 200 | snapTo: function(x) { 201 | return this.map(function(y) { 202 | return (Math.abs(y - x) <= Sylvester.precision) ? x : y; 203 | }); 204 | }, 205 | 206 | // Returns the vector's distance from the argument, when considered as a point in space 207 | distanceFrom: function(obj) { 208 | if (obj.anchor) { return obj.distanceFrom(this); } 209 | var V = obj.elements || obj; 210 | if (V.length != this.elements.length) { return null; } 211 | var sum = 0, part; 212 | this.each(function(x, i) { 213 | part = x - V[i-1]; 214 | sum += part * part; 215 | }); 216 | return Math.sqrt(sum); 217 | }, 218 | 219 | // Returns true if the vector is point on the given line 220 | liesOn: function(line) { 221 | return line.contains(this); 222 | }, 223 | 224 | // Return true iff the vector is a point in the given plane 225 | liesIn: function(plane) { 226 | return plane.contains(this); 227 | }, 228 | 229 | // Rotates the vector about the given object. The object should be a 230 | // point if the vector is 2D, and a line if it is 3D. Be careful with line directions! 231 | rotate: function(t, obj) { 232 | var V, R, x, y, z; 233 | switch (this.elements.length) { 234 | case 2: 235 | V = obj.elements || obj; 236 | if (V.length != 2) { return null; } 237 | R = Matrix.Rotation(t).elements; 238 | x = this.elements[0] - V[0]; 239 | y = this.elements[1] - V[1]; 240 | return Vector.create([ 241 | V[0] + R[0][0] * x + R[0][1] * y, 242 | V[1] + R[1][0] * x + R[1][1] * y 243 | ]); 244 | break; 245 | case 3: 246 | if (!obj.direction) { return null; } 247 | var C = obj.pointClosestTo(this).elements; 248 | R = Matrix.Rotation(t, obj.direction).elements; 249 | x = this.elements[0] - C[0]; 250 | y = this.elements[1] - C[1]; 251 | z = this.elements[2] - C[2]; 252 | return Vector.create([ 253 | C[0] + R[0][0] * x + R[0][1] * y + R[0][2] * z, 254 | C[1] + R[1][0] * x + R[1][1] * y + R[1][2] * z, 255 | C[2] + R[2][0] * x + R[2][1] * y + R[2][2] * z 256 | ]); 257 | break; 258 | default: 259 | return null; 260 | } 261 | }, 262 | 263 | // Returns the result of reflecting the point in the given point, line or plane 264 | reflectionIn: function(obj) { 265 | if (obj.anchor) { 266 | // obj is a plane or line 267 | var P = this.elements.slice(); 268 | var C = obj.pointClosestTo(P).elements; 269 | return Vector.create([C[0] + (C[0] - P[0]), C[1] + (C[1] - P[1]), C[2] + (C[2] - (P[2] || 0))]); 270 | } else { 271 | // obj is a point 272 | var Q = obj.elements || obj; 273 | if (this.elements.length != Q.length) { return null; } 274 | return this.map(function(x, i) { return Q[i-1] + (Q[i-1] - x); }); 275 | } 276 | }, 277 | 278 | // Utility to make sure vectors are 3D. If they are 2D, a zero z-component is added 279 | to3D: function() { 280 | var V = this.dup(); 281 | switch (V.elements.length) { 282 | case 3: break; 283 | case 2: V.elements.push(0); break; 284 | default: return null; 285 | } 286 | return V; 287 | }, 288 | 289 | // Returns a string representation of the vector 290 | inspect: function() { 291 | return '[' + this.elements.join(', ') + ']'; 292 | }, 293 | 294 | // Set vector's elements from an array 295 | setElements: function(els) { 296 | this.elements = (els.elements || els).slice(); 297 | return this; 298 | } 299 | }; 300 | 301 | // Constructor function 302 | Vector.create = function(elements) { 303 | var V = new Vector(); 304 | return V.setElements(elements); 305 | }; 306 | 307 | // i, j, k unit vectors 308 | Vector.i = Vector.create([1,0,0]); 309 | Vector.j = Vector.create([0,1,0]); 310 | Vector.k = Vector.create([0,0,1]); 311 | 312 | // Random vector of size n 313 | Vector.Random = function(n) { 314 | var elements = []; 315 | do { elements.push(Math.random()); 316 | } while (--n); 317 | return Vector.create(elements); 318 | }; 319 | 320 | // Vector filled with zeros 321 | Vector.Zero = function(n) { 322 | var elements = []; 323 | do { elements.push(0); 324 | } while (--n); 325 | return Vector.create(elements); 326 | }; 327 | 328 | 329 | 330 | function Matrix() {} 331 | Matrix.prototype = { 332 | 333 | // Returns element (i,j) of the matrix 334 | e: function(i,j) { 335 | if (i < 1 || i > this.elements.length || j < 1 || j > this.elements[0].length) { return null; } 336 | return this.elements[i-1][j-1]; 337 | }, 338 | 339 | // Returns row k of the matrix as a vector 340 | row: function(i) { 341 | if (i > this.elements.length) { return null; } 342 | return Vector.create(this.elements[i-1]); 343 | }, 344 | 345 | // Returns column k of the matrix as a vector 346 | col: function(j) { 347 | if (j > this.elements[0].length) { return null; } 348 | var col = [], n = this.elements.length, k = n, i; 349 | do { i = k - n; 350 | col.push(this.elements[i][j-1]); 351 | } while (--n); 352 | return Vector.create(col); 353 | }, 354 | 355 | // Returns the number of rows/columns the matrix has 356 | dimensions: function() { 357 | return {rows: this.elements.length, cols: this.elements[0].length}; 358 | }, 359 | 360 | // Returns the number of rows in the matrix 361 | rows: function() { 362 | return this.elements.length; 363 | }, 364 | 365 | // Returns the number of columns in the matrix 366 | cols: function() { 367 | return this.elements[0].length; 368 | }, 369 | 370 | // Returns true iff the matrix is equal to the argument. You can supply 371 | // a vector as the argument, in which case the receiver must be a 372 | // one-column matrix equal to the vector. 373 | eql: function(matrix) { 374 | var M = matrix.elements || matrix; 375 | if (typeof(M[0][0]) == 'undefined') { M = Matrix.create(M).elements; } 376 | if (this.elements.length != M.length || 377 | this.elements[0].length != M[0].length) { return false; } 378 | var ni = this.elements.length, ki = ni, i, nj, kj = this.elements[0].length, j; 379 | do { i = ki - ni; 380 | nj = kj; 381 | do { j = kj - nj; 382 | if (Math.abs(this.elements[i][j] - M[i][j]) > Sylvester.precision) { return false; } 383 | } while (--nj); 384 | } while (--ni); 385 | return true; 386 | }, 387 | 388 | // Returns a copy of the matrix 389 | dup: function() { 390 | return Matrix.create(this.elements); 391 | }, 392 | 393 | // Maps the matrix to another matrix (of the same dimensions) according to the given function 394 | map: function(fn) { 395 | var els = [], ni = this.elements.length, ki = ni, i, nj, kj = this.elements[0].length, j; 396 | do { i = ki - ni; 397 | nj = kj; 398 | els[i] = []; 399 | do { j = kj - nj; 400 | els[i][j] = fn(this.elements[i][j], i + 1, j + 1); 401 | } while (--nj); 402 | } while (--ni); 403 | return Matrix.create(els); 404 | }, 405 | 406 | // Returns true iff the argument has the same dimensions as the matrix 407 | isSameSizeAs: function(matrix) { 408 | var M = matrix.elements || matrix; 409 | if (typeof(M[0][0]) == 'undefined') { M = Matrix.create(M).elements; } 410 | return (this.elements.length == M.length && 411 | this.elements[0].length == M[0].length); 412 | }, 413 | 414 | // Returns the result of adding the argument to the matrix 415 | add: function(matrix) { 416 | var M = matrix.elements || matrix; 417 | if (typeof(M[0][0]) == 'undefined') { M = Matrix.create(M).elements; } 418 | if (!this.isSameSizeAs(M)) { return null; } 419 | return this.map(function(x, i, j) { return x + M[i-1][j-1]; }); 420 | }, 421 | 422 | // Returns the result of subtracting the argument from the matrix 423 | subtract: function(matrix) { 424 | var M = matrix.elements || matrix; 425 | if (typeof(M[0][0]) == 'undefined') { M = Matrix.create(M).elements; } 426 | if (!this.isSameSizeAs(M)) { return null; } 427 | return this.map(function(x, i, j) { return x - M[i-1][j-1]; }); 428 | }, 429 | 430 | // Returns true iff the matrix can multiply the argument from the left 431 | canMultiplyFromLeft: function(matrix) { 432 | var M = matrix.elements || matrix; 433 | if (typeof(M[0][0]) == 'undefined') { M = Matrix.create(M).elements; } 434 | // this.columns should equal matrix.rows 435 | return (this.elements[0].length == M.length); 436 | }, 437 | 438 | // Returns the result of multiplying the matrix from the right by the argument. 439 | // If the argument is a scalar then just multiply all the elements. If the argument is 440 | // a vector, a vector is returned, which saves you having to remember calling 441 | // col(1) on the result. 442 | multiply: function(matrix) { 443 | if (!matrix.elements) { 444 | return this.map(function(x) { return x * matrix; }); 445 | } 446 | var returnVector = matrix.modulus ? true : false; 447 | var M = matrix.elements || matrix; 448 | if (typeof(M[0][0]) == 'undefined') { M = Matrix.create(M).elements; } 449 | if (!this.canMultiplyFromLeft(M)) { return null; } 450 | var ni = this.elements.length, ki = ni, i, nj, kj = M[0].length, j; 451 | var cols = this.elements[0].length, elements = [], sum, nc, c; 452 | do { i = ki - ni; 453 | elements[i] = []; 454 | nj = kj; 455 | do { j = kj - nj; 456 | sum = 0; 457 | nc = cols; 458 | do { c = cols - nc; 459 | sum += this.elements[i][c] * M[c][j]; 460 | } while (--nc); 461 | elements[i][j] = sum; 462 | } while (--nj); 463 | } while (--ni); 464 | var M = Matrix.create(elements); 465 | return returnVector ? M.col(1) : M; 466 | }, 467 | 468 | x: function(matrix) { return this.multiply(matrix); }, 469 | 470 | // Returns a submatrix taken from the matrix 471 | // Argument order is: start row, start col, nrows, ncols 472 | // Element selection wraps if the required index is outside the matrix's bounds, so you could 473 | // use this to perform row/column cycling or copy-augmenting. 474 | minor: function(a, b, c, d) { 475 | var elements = [], ni = c, i, nj, j; 476 | var rows = this.elements.length, cols = this.elements[0].length; 477 | do { i = c - ni; 478 | elements[i] = []; 479 | nj = d; 480 | do { j = d - nj; 481 | elements[i][j] = this.elements[(a+i-1)%rows][(b+j-1)%cols]; 482 | } while (--nj); 483 | } while (--ni); 484 | return Matrix.create(elements); 485 | }, 486 | 487 | // Returns the transpose of the matrix 488 | transpose: function() { 489 | var rows = this.elements.length, cols = this.elements[0].length; 490 | var elements = [], ni = cols, i, nj, j; 491 | do { i = cols - ni; 492 | elements[i] = []; 493 | nj = rows; 494 | do { j = rows - nj; 495 | elements[i][j] = this.elements[j][i]; 496 | } while (--nj); 497 | } while (--ni); 498 | return Matrix.create(elements); 499 | }, 500 | 501 | // Returns true iff the matrix is square 502 | isSquare: function() { 503 | return (this.elements.length == this.elements[0].length); 504 | }, 505 | 506 | // Returns the (absolute) largest element of the matrix 507 | max: function() { 508 | var m = 0, ni = this.elements.length, ki = ni, i, nj, kj = this.elements[0].length, j; 509 | do { i = ki - ni; 510 | nj = kj; 511 | do { j = kj - nj; 512 | if (Math.abs(this.elements[i][j]) > Math.abs(m)) { m = this.elements[i][j]; } 513 | } while (--nj); 514 | } while (--ni); 515 | return m; 516 | }, 517 | 518 | // Returns the indeces of the first match found by reading row-by-row from left to right 519 | indexOf: function(x) { 520 | var index = null, ni = this.elements.length, ki = ni, i, nj, kj = this.elements[0].length, j; 521 | do { i = ki - ni; 522 | nj = kj; 523 | do { j = kj - nj; 524 | if (this.elements[i][j] == x) { return {i: i+1, j: j+1}; } 525 | } while (--nj); 526 | } while (--ni); 527 | return null; 528 | }, 529 | 530 | // If the matrix is square, returns the diagonal elements as a vector. 531 | // Otherwise, returns null. 532 | diagonal: function() { 533 | if (!this.isSquare) { return null; } 534 | var els = [], n = this.elements.length, k = n, i; 535 | do { i = k - n; 536 | els.push(this.elements[i][i]); 537 | } while (--n); 538 | return Vector.create(els); 539 | }, 540 | 541 | // Make the matrix upper (right) triangular by Gaussian elimination. 542 | // This method only adds multiples of rows to other rows. No rows are 543 | // scaled up or switched, and the determinant is preserved. 544 | toRightTriangular: function() { 545 | var M = this.dup(), els; 546 | var n = this.elements.length, k = n, i, np, kp = this.elements[0].length, p; 547 | do { i = k - n; 548 | if (M.elements[i][i] == 0) { 549 | for (j = i + 1; j < k; j++) { 550 | if (M.elements[j][i] != 0) { 551 | els = []; np = kp; 552 | do { p = kp - np; 553 | els.push(M.elements[i][p] + M.elements[j][p]); 554 | } while (--np); 555 | M.elements[i] = els; 556 | break; 557 | } 558 | } 559 | } 560 | if (M.elements[i][i] != 0) { 561 | for (j = i + 1; j < k; j++) { 562 | var multiplier = M.elements[j][i] / M.elements[i][i]; 563 | els = []; np = kp; 564 | do { p = kp - np; 565 | // Elements with column numbers up to an including the number 566 | // of the row that we're subtracting can safely be set straight to 567 | // zero, since that's the point of this routine and it avoids having 568 | // to loop over and correct rounding errors later 569 | els.push(p <= i ? 0 : M.elements[j][p] - M.elements[i][p] * multiplier); 570 | } while (--np); 571 | M.elements[j] = els; 572 | } 573 | } 574 | } while (--n); 575 | return M; 576 | }, 577 | 578 | toUpperTriangular: function() { return this.toRightTriangular(); }, 579 | 580 | // Returns the determinant for square matrices 581 | determinant: function() { 582 | if (!this.isSquare()) { return null; } 583 | var M = this.toRightTriangular(); 584 | var det = M.elements[0][0], n = M.elements.length - 1, k = n, i; 585 | do { i = k - n + 1; 586 | det = det * M.elements[i][i]; 587 | } while (--n); 588 | return det; 589 | }, 590 | 591 | det: function() { return this.determinant(); }, 592 | 593 | // Returns true iff the matrix is singular 594 | isSingular: function() { 595 | return (this.isSquare() && this.determinant() === 0); 596 | }, 597 | 598 | // Returns the trace for square matrices 599 | trace: function() { 600 | if (!this.isSquare()) { return null; } 601 | var tr = this.elements[0][0], n = this.elements.length - 1, k = n, i; 602 | do { i = k - n + 1; 603 | tr += this.elements[i][i]; 604 | } while (--n); 605 | return tr; 606 | }, 607 | 608 | tr: function() { return this.trace(); }, 609 | 610 | // Returns the rank of the matrix 611 | rank: function() { 612 | var M = this.toRightTriangular(), rank = 0; 613 | var ni = this.elements.length, ki = ni, i, nj, kj = this.elements[0].length, j; 614 | do { i = ki - ni; 615 | nj = kj; 616 | do { j = kj - nj; 617 | if (Math.abs(M.elements[i][j]) > Sylvester.precision) { rank++; break; } 618 | } while (--nj); 619 | } while (--ni); 620 | return rank; 621 | }, 622 | 623 | rk: function() { return this.rank(); }, 624 | 625 | // Returns the result of attaching the given argument to the right-hand side of the matrix 626 | augment: function(matrix) { 627 | var M = matrix.elements || matrix; 628 | if (typeof(M[0][0]) == 'undefined') { M = Matrix.create(M).elements; } 629 | var T = this.dup(), cols = T.elements[0].length; 630 | var ni = T.elements.length, ki = ni, i, nj, kj = M[0].length, j; 631 | if (ni != M.length) { return null; } 632 | do { i = ki - ni; 633 | nj = kj; 634 | do { j = kj - nj; 635 | T.elements[i][cols + j] = M[i][j]; 636 | } while (--nj); 637 | } while (--ni); 638 | return T; 639 | }, 640 | 641 | // Returns the inverse (if one exists) using Gauss-Jordan 642 | inverse: function() { 643 | if (!this.isSquare() || this.isSingular()) { return null; } 644 | var ni = this.elements.length, ki = ni, i, j; 645 | var M = this.augment(Matrix.I(ni)).toRightTriangular(); 646 | var np, kp = M.elements[0].length, p, els, divisor; 647 | var inverse_elements = [], new_element; 648 | // Matrix is non-singular so there will be no zeros on the diagonal 649 | // Cycle through rows from last to first 650 | do { i = ni - 1; 651 | // First, normalise diagonal elements to 1 652 | els = []; np = kp; 653 | inverse_elements[i] = []; 654 | divisor = M.elements[i][i]; 655 | do { p = kp - np; 656 | new_element = M.elements[i][p] / divisor; 657 | els.push(new_element); 658 | // Shuffle of the current row of the right hand side into the results 659 | // array as it will not be modified by later runs through this loop 660 | if (p >= ki) { inverse_elements[i].push(new_element); } 661 | } while (--np); 662 | M.elements[i] = els; 663 | // Then, subtract this row from those above it to 664 | // give the identity matrix on the left hand side 665 | for (j = 0; j < i; j++) { 666 | els = []; np = kp; 667 | do { p = kp - np; 668 | els.push(M.elements[j][p] - M.elements[i][p] * M.elements[j][i]); 669 | } while (--np); 670 | M.elements[j] = els; 671 | } 672 | } while (--ni); 673 | return Matrix.create(inverse_elements); 674 | }, 675 | 676 | inv: function() { return this.inverse(); }, 677 | 678 | // Returns the result of rounding all the elements 679 | round: function() { 680 | return this.map(function(x) { return Math.round(x); }); 681 | }, 682 | 683 | // Returns a copy of the matrix with elements set to the given value if they 684 | // differ from it by less than Sylvester.precision 685 | snapTo: function(x) { 686 | return this.map(function(p) { 687 | return (Math.abs(p - x) <= Sylvester.precision) ? x : p; 688 | }); 689 | }, 690 | 691 | // Returns a string representation of the matrix 692 | inspect: function() { 693 | var matrix_rows = []; 694 | var n = this.elements.length, k = n, i; 695 | do { i = k - n; 696 | matrix_rows.push(Vector.create(this.elements[i]).inspect()); 697 | } while (--n); 698 | return matrix_rows.join('\n'); 699 | }, 700 | 701 | // Set the matrix's elements from an array. If the argument passed 702 | // is a vector, the resulting matrix will be a single column. 703 | setElements: function(els) { 704 | var i, elements = els.elements || els; 705 | if (typeof(elements[0][0]) != 'undefined') { 706 | var ni = elements.length, ki = ni, nj, kj, j; 707 | this.elements = []; 708 | do { i = ki - ni; 709 | nj = elements[i].length; kj = nj; 710 | this.elements[i] = []; 711 | do { j = kj - nj; 712 | this.elements[i][j] = elements[i][j]; 713 | } while (--nj); 714 | } while(--ni); 715 | return this; 716 | } 717 | var n = elements.length, k = n; 718 | this.elements = []; 719 | do { i = k - n; 720 | this.elements.push([elements[i]]); 721 | } while (--n); 722 | return this; 723 | } 724 | }; 725 | 726 | // Constructor function 727 | Matrix.create = function(elements) { 728 | var M = new Matrix(); 729 | return M.setElements(elements); 730 | }; 731 | 732 | // Identity matrix of size n 733 | Matrix.I = function(n) { 734 | var els = [], k = n, i, nj, j; 735 | do { i = k - n; 736 | els[i] = []; nj = k; 737 | do { j = k - nj; 738 | els[i][j] = (i == j) ? 1 : 0; 739 | } while (--nj); 740 | } while (--n); 741 | return Matrix.create(els); 742 | }; 743 | 744 | // Diagonal matrix - all off-diagonal elements are zero 745 | Matrix.Diagonal = function(elements) { 746 | var n = elements.length, k = n, i; 747 | var M = Matrix.I(n); 748 | do { i = k - n; 749 | M.elements[i][i] = elements[i]; 750 | } while (--n); 751 | return M; 752 | }; 753 | 754 | // Rotation matrix about some axis. If no axis is 755 | // supplied, assume we're after a 2D transform 756 | Matrix.Rotation = function(theta, a) { 757 | if (!a) { 758 | return Matrix.create([ 759 | [Math.cos(theta), -Math.sin(theta)], 760 | [Math.sin(theta), Math.cos(theta)] 761 | ]); 762 | } 763 | var axis = a.dup(); 764 | if (axis.elements.length != 3) { return null; } 765 | var mod = axis.modulus(); 766 | var x = axis.elements[0]/mod, y = axis.elements[1]/mod, z = axis.elements[2]/mod; 767 | var s = Math.sin(theta), c = Math.cos(theta), t = 1 - c; 768 | // Formula derived here: http://www.gamedev.net/reference/articles/article1199.asp 769 | // That proof rotates the co-ordinate system so theta 770 | // becomes -theta and sin becomes -sin here. 771 | return Matrix.create([ 772 | [ t*x*x + c, t*x*y - s*z, t*x*z + s*y ], 773 | [ t*x*y + s*z, t*y*y + c, t*y*z - s*x ], 774 | [ t*x*z - s*y, t*y*z + s*x, t*z*z + c ] 775 | ]); 776 | }; 777 | 778 | // Special case rotations 779 | Matrix.RotationX = function(t) { 780 | var c = Math.cos(t), s = Math.sin(t); 781 | return Matrix.create([ 782 | [ 1, 0, 0 ], 783 | [ 0, c, -s ], 784 | [ 0, s, c ] 785 | ]); 786 | }; 787 | Matrix.RotationY = function(t) { 788 | var c = Math.cos(t), s = Math.sin(t); 789 | return Matrix.create([ 790 | [ c, 0, s ], 791 | [ 0, 1, 0 ], 792 | [ -s, 0, c ] 793 | ]); 794 | }; 795 | Matrix.RotationZ = function(t) { 796 | var c = Math.cos(t), s = Math.sin(t); 797 | return Matrix.create([ 798 | [ c, -s, 0 ], 799 | [ s, c, 0 ], 800 | [ 0, 0, 1 ] 801 | ]); 802 | }; 803 | 804 | // Random matrix of n rows, m columns 805 | Matrix.Random = function(n, m) { 806 | return Matrix.Zero(n, m).map( 807 | function() { return Math.random(); } 808 | ); 809 | }; 810 | 811 | // Matrix filled with zeros 812 | Matrix.Zero = function(n, m) { 813 | var els = [], ni = n, i, nj, j; 814 | do { i = n - ni; 815 | els[i] = []; 816 | nj = m; 817 | do { j = m - nj; 818 | els[i][j] = 0; 819 | } while (--nj); 820 | } while (--ni); 821 | return Matrix.create(els); 822 | }; 823 | 824 | 825 | 826 | function Line() {} 827 | Line.prototype = { 828 | 829 | // Returns true if the argument occupies the same space as the line 830 | eql: function(line) { 831 | return (this.isParallelTo(line) && this.contains(line.anchor)); 832 | }, 833 | 834 | // Returns a copy of the line 835 | dup: function() { 836 | return Line.create(this.anchor, this.direction); 837 | }, 838 | 839 | // Returns the result of translating the line by the given vector/array 840 | translate: function(vector) { 841 | var V = vector.elements || vector; 842 | return Line.create([ 843 | this.anchor.elements[0] + V[0], 844 | this.anchor.elements[1] + V[1], 845 | this.anchor.elements[2] + (V[2] || 0) 846 | ], this.direction); 847 | }, 848 | 849 | // Returns true if the line is parallel to the argument. Here, 'parallel to' 850 | // means that the argument's direction is either parallel or antiparallel to 851 | // the line's own direction. A line is parallel to a plane if the two do not 852 | // have a unique intersection. 853 | isParallelTo: function(obj) { 854 | if (obj.normal) { return obj.isParallelTo(this); } 855 | var theta = this.direction.angleFrom(obj.direction); 856 | return (Math.abs(theta) <= Sylvester.precision || Math.abs(theta - Math.PI) <= Sylvester.precision); 857 | }, 858 | 859 | // Returns the line's perpendicular distance from the argument, 860 | // which can be a point, a line or a plane 861 | distanceFrom: function(obj) { 862 | if (obj.normal) { return obj.distanceFrom(this); } 863 | if (obj.direction) { 864 | // obj is a line 865 | if (this.isParallelTo(obj)) { return this.distanceFrom(obj.anchor); } 866 | var N = this.direction.cross(obj.direction).toUnitVector().elements; 867 | var A = this.anchor.elements, B = obj.anchor.elements; 868 | return Math.abs((A[0] - B[0]) * N[0] + (A[1] - B[1]) * N[1] + (A[2] - B[2]) * N[2]); 869 | } else { 870 | // obj is a point 871 | var P = obj.elements || obj; 872 | var A = this.anchor.elements, D = this.direction.elements; 873 | var PA1 = P[0] - A[0], PA2 = P[1] - A[1], PA3 = (P[2] || 0) - A[2]; 874 | var modPA = Math.sqrt(PA1*PA1 + PA2*PA2 + PA3*PA3); 875 | if (modPA === 0) return 0; 876 | // Assumes direction vector is normalized 877 | var cosTheta = (PA1 * D[0] + PA2 * D[1] + PA3 * D[2]) / modPA; 878 | var sin2 = 1 - cosTheta*cosTheta; 879 | return Math.abs(modPA * Math.sqrt(sin2 < 0 ? 0 : sin2)); 880 | } 881 | }, 882 | 883 | // Returns true iff the argument is a point on the line 884 | contains: function(point) { 885 | var dist = this.distanceFrom(point); 886 | return (dist !== null && dist <= Sylvester.precision); 887 | }, 888 | 889 | // Returns true iff the line lies in the given plane 890 | liesIn: function(plane) { 891 | return plane.contains(this); 892 | }, 893 | 894 | // Returns true iff the line has a unique point of intersection with the argument 895 | intersects: function(obj) { 896 | if (obj.normal) { return obj.intersects(this); } 897 | return (!this.isParallelTo(obj) && this.distanceFrom(obj) <= Sylvester.precision); 898 | }, 899 | 900 | // Returns the unique intersection point with the argument, if one exists 901 | intersectionWith: function(obj) { 902 | if (obj.normal) { return obj.intersectionWith(this); } 903 | if (!this.intersects(obj)) { return null; } 904 | var P = this.anchor.elements, X = this.direction.elements, 905 | Q = obj.anchor.elements, Y = obj.direction.elements; 906 | var X1 = X[0], X2 = X[1], X3 = X[2], Y1 = Y[0], Y2 = Y[1], Y3 = Y[2]; 907 | var PsubQ1 = P[0] - Q[0], PsubQ2 = P[1] - Q[1], PsubQ3 = P[2] - Q[2]; 908 | var XdotQsubP = - X1*PsubQ1 - X2*PsubQ2 - X3*PsubQ3; 909 | var YdotPsubQ = Y1*PsubQ1 + Y2*PsubQ2 + Y3*PsubQ3; 910 | var XdotX = X1*X1 + X2*X2 + X3*X3; 911 | var YdotY = Y1*Y1 + Y2*Y2 + Y3*Y3; 912 | var XdotY = X1*Y1 + X2*Y2 + X3*Y3; 913 | var k = (XdotQsubP * YdotY / XdotX + XdotY * YdotPsubQ) / (YdotY - XdotY * XdotY); 914 | return Vector.create([P[0] + k*X1, P[1] + k*X2, P[2] + k*X3]); 915 | }, 916 | 917 | // Returns the point on the line that is closest to the given point or line 918 | pointClosestTo: function(obj) { 919 | if (obj.direction) { 920 | // obj is a line 921 | if (this.intersects(obj)) { return this.intersectionWith(obj); } 922 | if (this.isParallelTo(obj)) { return null; } 923 | var D = this.direction.elements, E = obj.direction.elements; 924 | var D1 = D[0], D2 = D[1], D3 = D[2], E1 = E[0], E2 = E[1], E3 = E[2]; 925 | // Create plane containing obj and the shared normal and intersect this with it 926 | // Thank you: http://www.cgafaq.info/wiki/Line-line_distance 927 | var x = (D3 * E1 - D1 * E3), y = (D1 * E2 - D2 * E1), z = (D2 * E3 - D3 * E2); 928 | var N = Vector.create([x * E3 - y * E2, y * E1 - z * E3, z * E2 - x * E1]); 929 | var P = Plane.create(obj.anchor, N); 930 | return P.intersectionWith(this); 931 | } else { 932 | // obj is a point 933 | var P = obj.elements || obj; 934 | if (this.contains(P)) { return Vector.create(P); } 935 | var A = this.anchor.elements, D = this.direction.elements; 936 | var D1 = D[0], D2 = D[1], D3 = D[2], A1 = A[0], A2 = A[1], A3 = A[2]; 937 | var x = D1 * (P[1]-A2) - D2 * (P[0]-A1), y = D2 * ((P[2] || 0) - A3) - D3 * (P[1]-A2), 938 | z = D3 * (P[0]-A1) - D1 * ((P[2] || 0) - A3); 939 | var V = Vector.create([D2 * x - D3 * z, D3 * y - D1 * x, D1 * z - D2 * y]); 940 | var k = this.distanceFrom(P) / V.modulus(); 941 | return Vector.create([ 942 | P[0] + V.elements[0] * k, 943 | P[1] + V.elements[1] * k, 944 | (P[2] || 0) + V.elements[2] * k 945 | ]); 946 | } 947 | }, 948 | 949 | // Returns a copy of the line rotated by t radians about the given line. Works by 950 | // finding the argument's closest point to this line's anchor point (call this C) and 951 | // rotating the anchor about C. Also rotates the line's direction about the argument's. 952 | // Be careful with this - the rotation axis' direction affects the outcome! 953 | rotate: function(t, line) { 954 | // If we're working in 2D 955 | if (typeof(line.direction) == 'undefined') { line = Line.create(line.to3D(), Vector.k); } 956 | var R = Matrix.Rotation(t, line.direction).elements; 957 | var C = line.pointClosestTo(this.anchor).elements; 958 | var A = this.anchor.elements, D = this.direction.elements; 959 | var C1 = C[0], C2 = C[1], C3 = C[2], A1 = A[0], A2 = A[1], A3 = A[2]; 960 | var x = A1 - C1, y = A2 - C2, z = A3 - C3; 961 | return Line.create([ 962 | C1 + R[0][0] * x + R[0][1] * y + R[0][2] * z, 963 | C2 + R[1][0] * x + R[1][1] * y + R[1][2] * z, 964 | C3 + R[2][0] * x + R[2][1] * y + R[2][2] * z 965 | ], [ 966 | R[0][0] * D[0] + R[0][1] * D[1] + R[0][2] * D[2], 967 | R[1][0] * D[0] + R[1][1] * D[1] + R[1][2] * D[2], 968 | R[2][0] * D[0] + R[2][1] * D[1] + R[2][2] * D[2] 969 | ]); 970 | }, 971 | 972 | // Returns the line's reflection in the given point or line 973 | reflectionIn: function(obj) { 974 | if (obj.normal) { 975 | // obj is a plane 976 | var A = this.anchor.elements, D = this.direction.elements; 977 | var A1 = A[0], A2 = A[1], A3 = A[2], D1 = D[0], D2 = D[1], D3 = D[2]; 978 | var newA = this.anchor.reflectionIn(obj).elements; 979 | // Add the line's direction vector to its anchor, then mirror that in the plane 980 | var AD1 = A1 + D1, AD2 = A2 + D2, AD3 = A3 + D3; 981 | var Q = obj.pointClosestTo([AD1, AD2, AD3]).elements; 982 | var newD = [Q[0] + (Q[0] - AD1) - newA[0], Q[1] + (Q[1] - AD2) - newA[1], Q[2] + (Q[2] - AD3) - newA[2]]; 983 | return Line.create(newA, newD); 984 | } else if (obj.direction) { 985 | // obj is a line - reflection obtained by rotating PI radians about obj 986 | return this.rotate(Math.PI, obj); 987 | } else { 988 | // obj is a point - just reflect the line's anchor in it 989 | var P = obj.elements || obj; 990 | return Line.create(this.anchor.reflectionIn([P[0], P[1], (P[2] || 0)]), this.direction); 991 | } 992 | }, 993 | 994 | // Set the line's anchor point and direction. 995 | setVectors: function(anchor, direction) { 996 | // Need to do this so that line's properties are not 997 | // references to the arguments passed in 998 | anchor = Vector.create(anchor); 999 | direction = Vector.create(direction); 1000 | if (anchor.elements.length == 2) {anchor.elements.push(0); } 1001 | if (direction.elements.length == 2) { direction.elements.push(0); } 1002 | if (anchor.elements.length > 3 || direction.elements.length > 3) { return null; } 1003 | var mod = direction.modulus(); 1004 | if (mod === 0) { return null; } 1005 | this.anchor = anchor; 1006 | this.direction = Vector.create([ 1007 | direction.elements[0] / mod, 1008 | direction.elements[1] / mod, 1009 | direction.elements[2] / mod 1010 | ]); 1011 | return this; 1012 | } 1013 | }; 1014 | 1015 | 1016 | // Constructor function 1017 | Line.create = function(anchor, direction) { 1018 | var L = new Line(); 1019 | return L.setVectors(anchor, direction); 1020 | }; 1021 | 1022 | // Axes 1023 | Line.X = Line.create(Vector.Zero(3), Vector.i); 1024 | Line.Y = Line.create(Vector.Zero(3), Vector.j); 1025 | Line.Z = Line.create(Vector.Zero(3), Vector.k); 1026 | 1027 | 1028 | 1029 | function Plane() {} 1030 | Plane.prototype = { 1031 | 1032 | // Returns true iff the plane occupies the same space as the argument 1033 | eql: function(plane) { 1034 | return (this.contains(plane.anchor) && this.isParallelTo(plane)); 1035 | }, 1036 | 1037 | // Returns a copy of the plane 1038 | dup: function() { 1039 | return Plane.create(this.anchor, this.normal); 1040 | }, 1041 | 1042 | // Returns the result of translating the plane by the given vector 1043 | translate: function(vector) { 1044 | var V = vector.elements || vector; 1045 | return Plane.create([ 1046 | this.anchor.elements[0] + V[0], 1047 | this.anchor.elements[1] + V[1], 1048 | this.anchor.elements[2] + (V[2] || 0) 1049 | ], this.normal); 1050 | }, 1051 | 1052 | // Returns true iff the plane is parallel to the argument. Will return true 1053 | // if the planes are equal, or if you give a line and it lies in the plane. 1054 | isParallelTo: function(obj) { 1055 | var theta; 1056 | if (obj.normal) { 1057 | // obj is a plane 1058 | theta = this.normal.angleFrom(obj.normal); 1059 | return (Math.abs(theta) <= Sylvester.precision || Math.abs(Math.PI - theta) <= Sylvester.precision); 1060 | } else if (obj.direction) { 1061 | // obj is a line 1062 | return this.normal.isPerpendicularTo(obj.direction); 1063 | } 1064 | return null; 1065 | }, 1066 | 1067 | // Returns true iff the receiver is perpendicular to the argument 1068 | isPerpendicularTo: function(plane) { 1069 | var theta = this.normal.angleFrom(plane.normal); 1070 | return (Math.abs(Math.PI/2 - theta) <= Sylvester.precision); 1071 | }, 1072 | 1073 | // Returns the plane's distance from the given object (point, line or plane) 1074 | distanceFrom: function(obj) { 1075 | if (this.intersects(obj) || this.contains(obj)) { return 0; } 1076 | if (obj.anchor) { 1077 | // obj is a plane or line 1078 | var A = this.anchor.elements, B = obj.anchor.elements, N = this.normal.elements; 1079 | return Math.abs((A[0] - B[0]) * N[0] + (A[1] - B[1]) * N[1] + (A[2] - B[2]) * N[2]); 1080 | } else { 1081 | // obj is a point 1082 | var P = obj.elements || obj; 1083 | var A = this.anchor.elements, N = this.normal.elements; 1084 | return Math.abs((A[0] - P[0]) * N[0] + (A[1] - P[1]) * N[1] + (A[2] - (P[2] || 0)) * N[2]); 1085 | } 1086 | }, 1087 | 1088 | // Returns true iff the plane contains the given point or line 1089 | contains: function(obj) { 1090 | if (obj.normal) { return null; } 1091 | if (obj.direction) { 1092 | return (this.contains(obj.anchor) && this.contains(obj.anchor.add(obj.direction))); 1093 | } else { 1094 | var P = obj.elements || obj; 1095 | var A = this.anchor.elements, N = this.normal.elements; 1096 | var diff = Math.abs(N[0]*(A[0] - P[0]) + N[1]*(A[1] - P[1]) + N[2]*(A[2] - (P[2] || 0))); 1097 | return (diff <= Sylvester.precision); 1098 | } 1099 | }, 1100 | 1101 | // Returns true iff the plane has a unique point/line of intersection with the argument 1102 | intersects: function(obj) { 1103 | if (typeof(obj.direction) == 'undefined' && typeof(obj.normal) == 'undefined') { return null; } 1104 | return !this.isParallelTo(obj); 1105 | }, 1106 | 1107 | // Returns the unique intersection with the argument, if one exists. The result 1108 | // will be a vector if a line is supplied, and a line if a plane is supplied. 1109 | intersectionWith: function(obj) { 1110 | if (!this.intersects(obj)) { return null; } 1111 | if (obj.direction) { 1112 | // obj is a line 1113 | var A = obj.anchor.elements, D = obj.direction.elements, 1114 | P = this.anchor.elements, N = this.normal.elements; 1115 | var multiplier = (N[0]*(P[0]-A[0]) + N[1]*(P[1]-A[1]) + N[2]*(P[2]-A[2])) / (N[0]*D[0] + N[1]*D[1] + N[2]*D[2]); 1116 | return Vector.create([A[0] + D[0]*multiplier, A[1] + D[1]*multiplier, A[2] + D[2]*multiplier]); 1117 | } else if (obj.normal) { 1118 | // obj is a plane 1119 | var direction = this.normal.cross(obj.normal).toUnitVector(); 1120 | // To find an anchor point, we find one co-ordinate that has a value 1121 | // of zero somewhere on the intersection, and remember which one we picked 1122 | var N = this.normal.elements, A = this.anchor.elements, 1123 | O = obj.normal.elements, B = obj.anchor.elements; 1124 | var solver = Matrix.Zero(2,2), i = 0; 1125 | while (solver.isSingular()) { 1126 | i++; 1127 | solver = Matrix.create([ 1128 | [ N[i%3], N[(i+1)%3] ], 1129 | [ O[i%3], O[(i+1)%3] ] 1130 | ]); 1131 | } 1132 | // Then we solve the simultaneous equations in the remaining dimensions 1133 | var inverse = solver.inverse().elements; 1134 | var x = N[0]*A[0] + N[1]*A[1] + N[2]*A[2]; 1135 | var y = O[0]*B[0] + O[1]*B[1] + O[2]*B[2]; 1136 | var intersection = [ 1137 | inverse[0][0] * x + inverse[0][1] * y, 1138 | inverse[1][0] * x + inverse[1][1] * y 1139 | ]; 1140 | var anchor = []; 1141 | for (var j = 1; j <= 3; j++) { 1142 | // This formula picks the right element from intersection by 1143 | // cycling depending on which element we set to zero above 1144 | anchor.push((i == j) ? 0 : intersection[(j + (5 - i)%3)%3]); 1145 | } 1146 | return Line.create(anchor, direction); 1147 | } 1148 | }, 1149 | 1150 | // Returns the point in the plane closest to the given point 1151 | pointClosestTo: function(point) { 1152 | var P = point.elements || point; 1153 | var A = this.anchor.elements, N = this.normal.elements; 1154 | var dot = (A[0] - P[0]) * N[0] + (A[1] - P[1]) * N[1] + (A[2] - (P[2] || 0)) * N[2]; 1155 | return Vector.create([P[0] + N[0] * dot, P[1] + N[1] * dot, (P[2] || 0) + N[2] * dot]); 1156 | }, 1157 | 1158 | // Returns a copy of the plane, rotated by t radians about the given line 1159 | // See notes on Line#rotate. 1160 | rotate: function(t, line) { 1161 | var R = Matrix.Rotation(t, line.direction).elements; 1162 | var C = line.pointClosestTo(this.anchor).elements; 1163 | var A = this.anchor.elements, N = this.normal.elements; 1164 | var C1 = C[0], C2 = C[1], C3 = C[2], A1 = A[0], A2 = A[1], A3 = A[2]; 1165 | var x = A1 - C1, y = A2 - C2, z = A3 - C3; 1166 | return Plane.create([ 1167 | C1 + R[0][0] * x + R[0][1] * y + R[0][2] * z, 1168 | C2 + R[1][0] * x + R[1][1] * y + R[1][2] * z, 1169 | C3 + R[2][0] * x + R[2][1] * y + R[2][2] * z 1170 | ], [ 1171 | R[0][0] * N[0] + R[0][1] * N[1] + R[0][2] * N[2], 1172 | R[1][0] * N[0] + R[1][1] * N[1] + R[1][2] * N[2], 1173 | R[2][0] * N[0] + R[2][1] * N[1] + R[2][2] * N[2] 1174 | ]); 1175 | }, 1176 | 1177 | // Returns the reflection of the plane in the given point, line or plane. 1178 | reflectionIn: function(obj) { 1179 | if (obj.normal) { 1180 | // obj is a plane 1181 | var A = this.anchor.elements, N = this.normal.elements; 1182 | var A1 = A[0], A2 = A[1], A3 = A[2], N1 = N[0], N2 = N[1], N3 = N[2]; 1183 | var newA = this.anchor.reflectionIn(obj).elements; 1184 | // Add the plane's normal to its anchor, then mirror that in the other plane 1185 | var AN1 = A1 + N1, AN2 = A2 + N2, AN3 = A3 + N3; 1186 | var Q = obj.pointClosestTo([AN1, AN2, AN3]).elements; 1187 | var newN = [Q[0] + (Q[0] - AN1) - newA[0], Q[1] + (Q[1] - AN2) - newA[1], Q[2] + (Q[2] - AN3) - newA[2]]; 1188 | return Plane.create(newA, newN); 1189 | } else if (obj.direction) { 1190 | // obj is a line 1191 | return this.rotate(Math.PI, obj); 1192 | } else { 1193 | // obj is a point 1194 | var P = obj.elements || obj; 1195 | return Plane.create(this.anchor.reflectionIn([P[0], P[1], (P[2] || 0)]), this.normal); 1196 | } 1197 | }, 1198 | 1199 | // Sets the anchor point and normal to the plane. If three arguments are specified, 1200 | // the normal is calculated by assuming the three points should lie in the same plane. 1201 | // If only two are sepcified, the second is taken to be the normal. Normal vector is 1202 | // normalised before storage. 1203 | setVectors: function(anchor, v1, v2) { 1204 | anchor = Vector.create(anchor); 1205 | anchor = anchor.to3D(); if (anchor === null) { return null; } 1206 | v1 = Vector.create(v1); 1207 | v1 = v1.to3D(); if (v1 === null) { return null; } 1208 | if (typeof(v2) == 'undefined') { 1209 | v2 = null; 1210 | } else { 1211 | v2 = Vector.create(v2); 1212 | v2 = v2.to3D(); if (v2 === null) { return null; } 1213 | } 1214 | var A1 = anchor.elements[0], A2 = anchor.elements[1], A3 = anchor.elements[2]; 1215 | var v11 = v1.elements[0], v12 = v1.elements[1], v13 = v1.elements[2]; 1216 | var normal, mod; 1217 | if (v2 !== null) { 1218 | var v21 = v2.elements[0], v22 = v2.elements[1], v23 = v2.elements[2]; 1219 | normal = Vector.create([ 1220 | (v12 - A2) * (v23 - A3) - (v13 - A3) * (v22 - A2), 1221 | (v13 - A3) * (v21 - A1) - (v11 - A1) * (v23 - A3), 1222 | (v11 - A1) * (v22 - A2) - (v12 - A2) * (v21 - A1) 1223 | ]); 1224 | mod = normal.modulus(); 1225 | if (mod === 0) { return null; } 1226 | normal = Vector.create([normal.elements[0] / mod, normal.elements[1] / mod, normal.elements[2] / mod]); 1227 | } else { 1228 | mod = Math.sqrt(v11*v11 + v12*v12 + v13*v13); 1229 | if (mod === 0) { return null; } 1230 | normal = Vector.create([v1.elements[0] / mod, v1.elements[1] / mod, v1.elements[2] / mod]); 1231 | } 1232 | this.anchor = anchor; 1233 | this.normal = normal; 1234 | return this; 1235 | } 1236 | }; 1237 | 1238 | // Constructor function 1239 | Plane.create = function(anchor, v1, v2) { 1240 | var P = new Plane(); 1241 | return P.setVectors(anchor, v1, v2); 1242 | }; 1243 | 1244 | // X-Y-Z planes 1245 | Plane.XY = Plane.create(Vector.Zero(3), Vector.k); 1246 | Plane.YZ = Plane.create(Vector.Zero(3), Vector.i); 1247 | Plane.ZX = Plane.create(Vector.Zero(3), Vector.j); 1248 | Plane.YX = Plane.XY; Plane.ZY = Plane.YZ; Plane.XZ = Plane.ZX; 1249 | 1250 | // Utility functions 1251 | var $V = Vector.create; 1252 | var $M = Matrix.create; 1253 | var $L = Line.create; 1254 | var $P = Plane.create; 1255 | -------------------------------------------------------------------------------- /webgl-path-tracing.js: -------------------------------------------------------------------------------- 1 | /* 2 | WebGL Path Tracing (http://madebyevan.com/webgl-path-tracing/) 3 | License: MIT License (see below) 4 | 5 | Copyright (c) 2010 Evan Wallace 6 | 7 | Permission is hereby granted, free of charge, to any person 8 | obtaining a copy of this software and associated documentation 9 | files (the "Software"), to deal in the Software without 10 | restriction, including without limitation the rights to use, 11 | copy, modify, merge, publish, distribute, sublicense, and/or sell 12 | copies of the Software, and to permit persons to whom the 13 | Software is furnished to do so, subject to the following 14 | conditions: 15 | 16 | The above copyright notice and this permission notice shall be 17 | included in all copies or substantial portions of the Software. 18 | 19 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 20 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 21 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 22 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 23 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 24 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 25 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 26 | OTHER DEALINGS IN THE SOFTWARE. 27 | */ 28 | 29 | //////////////////////////////////////////////////////////////////////////////// 30 | // shader strings 31 | //////////////////////////////////////////////////////////////////////////////// 32 | 33 | // vertex shader for drawing a textured quad 34 | var renderVertexSource = 35 | ' attribute vec3 vertex;' + 36 | ' varying vec2 texCoord;' + 37 | ' void main() {' + 38 | ' texCoord = vertex.xy * 0.5 + 0.5;' + 39 | ' gl_Position = vec4(vertex, 1.0);' + 40 | ' }'; 41 | 42 | // fragment shader for drawing a textured quad 43 | var renderFragmentSource = 44 | ' precision highp float;' + 45 | ' varying vec2 texCoord;' + 46 | ' uniform sampler2D texture;' + 47 | ' void main() {' + 48 | ' gl_FragColor = texture2D(texture, texCoord);' + 49 | ' }'; 50 | 51 | // vertex shader for drawing a line 52 | var lineVertexSource = 53 | ' attribute vec3 vertex;' + 54 | ' uniform vec3 cubeMin;' + 55 | ' uniform vec3 cubeMax;' + 56 | ' uniform mat4 modelviewProjection;' + 57 | ' void main() {' + 58 | ' gl_Position = modelviewProjection * vec4(mix(cubeMin, cubeMax, vertex), 1.0);' + 59 | ' }'; 60 | 61 | // fragment shader for drawing a line 62 | var lineFragmentSource = 63 | ' precision highp float;' + 64 | ' void main() {' + 65 | ' gl_FragColor = vec4(1.0);' + 66 | ' }'; 67 | 68 | // constants for the shaders 69 | var bounces = '5'; 70 | var epsilon = '0.0001'; 71 | var infinity = '10000.0'; 72 | var lightSize = 0.1; 73 | var lightVal = 0.5; 74 | 75 | // vertex shader, interpolate ray per-pixel 76 | var tracerVertexSource = 77 | ' attribute vec3 vertex;' + 78 | ' uniform vec3 eye, ray00, ray01, ray10, ray11;' + 79 | ' varying vec3 initialRay;' + 80 | ' void main() {' + 81 | ' vec2 percent = vertex.xy * 0.5 + 0.5;' + 82 | ' initialRay = mix(mix(ray00, ray01, percent.y), mix(ray10, ray11, percent.y), percent.x);' + 83 | ' gl_Position = vec4(vertex, 1.0);' + 84 | ' }'; 85 | 86 | // start of fragment shader 87 | var tracerFragmentSourceHeader = 88 | ' precision highp float;' + 89 | ' uniform vec3 eye;' + 90 | ' varying vec3 initialRay;' + 91 | ' uniform float textureWeight;' + 92 | ' uniform float timeSinceStart;' + 93 | ' uniform sampler2D texture;' + 94 | ' uniform float glossiness;' + 95 | ' vec3 roomCubeMin = vec3(-1.0, -1.0, -1.0);' + 96 | ' vec3 roomCubeMax = vec3(1.0, 1.0, 1.0);'; 97 | 98 | // compute the near and far intersections of the cube (stored in the x and y components) using the slab method 99 | // no intersection means vec.x > vec.y (really tNear > tFar) 100 | var intersectCubeSource = 101 | ' vec2 intersectCube(vec3 origin, vec3 ray, vec3 cubeMin, vec3 cubeMax) {' + 102 | ' vec3 tMin = (cubeMin - origin) / ray;' + 103 | ' vec3 tMax = (cubeMax - origin) / ray;' + 104 | ' vec3 t1 = min(tMin, tMax);' + 105 | ' vec3 t2 = max(tMin, tMax);' + 106 | ' float tNear = max(max(t1.x, t1.y), t1.z);' + 107 | ' float tFar = min(min(t2.x, t2.y), t2.z);' + 108 | ' return vec2(tNear, tFar);' + 109 | ' }'; 110 | 111 | // given that hit is a point on the cube, what is the surface normal? 112 | // TODO: do this with fewer branches 113 | var normalForCubeSource = 114 | ' vec3 normalForCube(vec3 hit, vec3 cubeMin, vec3 cubeMax)' + 115 | ' {' + 116 | ' if(hit.x < cubeMin.x + ' + epsilon + ') return vec3(-1.0, 0.0, 0.0);' + 117 | ' else if(hit.x > cubeMax.x - ' + epsilon + ') return vec3(1.0, 0.0, 0.0);' + 118 | ' else if(hit.y < cubeMin.y + ' + epsilon + ') return vec3(0.0, -1.0, 0.0);' + 119 | ' else if(hit.y > cubeMax.y - ' + epsilon + ') return vec3(0.0, 1.0, 0.0);' + 120 | ' else if(hit.z < cubeMin.z + ' + epsilon + ') return vec3(0.0, 0.0, -1.0);' + 121 | ' else return vec3(0.0, 0.0, 1.0);' + 122 | ' }'; 123 | 124 | // compute the near intersection of a sphere 125 | // no intersection returns a value of +infinity 126 | var intersectSphereSource = 127 | ' float intersectSphere(vec3 origin, vec3 ray, vec3 sphereCenter, float sphereRadius) {' + 128 | ' vec3 toSphere = origin - sphereCenter;' + 129 | ' float a = dot(ray, ray);' + 130 | ' float b = 2.0 * dot(toSphere, ray);' + 131 | ' float c = dot(toSphere, toSphere) - sphereRadius*sphereRadius;' + 132 | ' float discriminant = b*b - 4.0*a*c;' + 133 | ' if(discriminant > 0.0) {' + 134 | ' float t = (-b - sqrt(discriminant)) / (2.0 * a);' + 135 | ' if(t > 0.0) return t;' + 136 | ' }' + 137 | ' return ' + infinity + ';' + 138 | ' }'; 139 | 140 | // given that hit is a point on the sphere, what is the surface normal? 141 | var normalForSphereSource = 142 | ' vec3 normalForSphere(vec3 hit, vec3 sphereCenter, float sphereRadius) {' + 143 | ' return (hit - sphereCenter) / sphereRadius;' + 144 | ' }'; 145 | 146 | // use the fragment position for randomness 147 | var randomSource = 148 | ' float random(vec3 scale, float seed) {' + 149 | ' return fract(sin(dot(gl_FragCoord.xyz + seed, scale)) * 43758.5453 + seed);' + 150 | ' }'; 151 | 152 | // random cosine-weighted distributed vector 153 | // from http://www.rorydriscoll.com/2009/01/07/better-sampling/ 154 | var cosineWeightedDirectionSource = 155 | ' vec3 cosineWeightedDirection(float seed, vec3 normal) {' + 156 | ' float u = random(vec3(12.9898, 78.233, 151.7182), seed);' + 157 | ' float v = random(vec3(63.7264, 10.873, 623.6736), seed);' + 158 | ' float r = sqrt(u);' + 159 | ' float angle = 6.283185307179586 * v;' + 160 | // compute basis from normal 161 | ' vec3 sdir, tdir;' + 162 | ' if (abs(normal.x)<.5) {' + 163 | ' sdir = cross(normal, vec3(1,0,0));' + 164 | ' } else {' + 165 | ' sdir = cross(normal, vec3(0,1,0));' + 166 | ' }' + 167 | ' tdir = cross(normal, sdir);' + 168 | ' return r*cos(angle)*sdir + r*sin(angle)*tdir + sqrt(1.-u)*normal;' + 169 | ' }'; 170 | 171 | // random normalized vector 172 | var uniformlyRandomDirectionSource = 173 | ' vec3 uniformlyRandomDirection(float seed) {' + 174 | ' float u = random(vec3(12.9898, 78.233, 151.7182), seed);' + 175 | ' float v = random(vec3(63.7264, 10.873, 623.6736), seed);' + 176 | ' float z = 1.0 - 2.0 * u;' + 177 | ' float r = sqrt(1.0 - z * z);' + 178 | ' float angle = 6.283185307179586 * v;' + 179 | ' return vec3(r * cos(angle), r * sin(angle), z);' + 180 | ' }'; 181 | 182 | // random vector in the unit sphere 183 | // note: this is probably not statistically uniform, saw raising to 1/3 power somewhere but that looks wrong? 184 | var uniformlyRandomVectorSource = 185 | ' vec3 uniformlyRandomVector(float seed) {' + 186 | ' return uniformlyRandomDirection(seed) * sqrt(random(vec3(36.7539, 50.3658, 306.2759), seed));' + 187 | ' }'; 188 | 189 | // compute specular lighting contribution 190 | var specularReflection = 191 | ' vec3 reflectedLight = normalize(reflect(light - hit, normal));' + 192 | ' specularHighlight = max(0.0, dot(reflectedLight, normalize(hit - origin)));'; 193 | 194 | // update ray using normal and bounce according to a diffuse reflection 195 | var newDiffuseRay = 196 | ' ray = cosineWeightedDirection(timeSinceStart + float(bounce), normal);'; 197 | 198 | // update ray using normal according to a specular reflection 199 | var newReflectiveRay = 200 | ' ray = reflect(ray, normal);' + 201 | specularReflection + 202 | ' specularHighlight = 2.0 * pow(specularHighlight, 20.0);'; 203 | 204 | // update ray using normal and bounce according to a glossy reflection 205 | var newGlossyRay = 206 | ' ray = normalize(reflect(ray, normal)) + uniformlyRandomVector(timeSinceStart + float(bounce)) * glossiness;' + 207 | specularReflection + 208 | ' specularHighlight = pow(specularHighlight, 3.0);'; 209 | 210 | var yellowBlueCornellBox = 211 | ' if(hit.x < -0.9999) surfaceColor = vec3(0.1, 0.5, 1.0);' + // blue 212 | ' else if(hit.x > 0.9999) surfaceColor = vec3(1.0, 0.9, 0.1);'; // yellow 213 | 214 | var redGreenCornellBox = 215 | ' if(hit.x < -0.9999) surfaceColor = vec3(1.0, 0.3, 0.1);' + // red 216 | ' else if(hit.x > 0.9999) surfaceColor = vec3(0.3, 1.0, 0.1);'; // green 217 | 218 | function makeShadow(objects) { 219 | return '' + 220 | ' float shadow(vec3 origin, vec3 ray) {' + 221 | concat(objects, function(o){ return o.getShadowTestCode(); }) + 222 | ' return 1.0;' + 223 | ' }'; 224 | } 225 | 226 | function makeCalculateColor(objects) { 227 | return '' + 228 | ' vec3 calculateColor(vec3 origin, vec3 ray, vec3 light) {' + 229 | ' vec3 colorMask = vec3(1.0);' + 230 | ' vec3 accumulatedColor = vec3(0.0);' + 231 | 232 | // main raytracing loop 233 | ' for(int bounce = 0; bounce < ' + bounces + '; bounce++) {' + 234 | // compute the intersection with everything 235 | ' vec2 tRoom = intersectCube(origin, ray, roomCubeMin, roomCubeMax);' + 236 | concat(objects, function(o){ return o.getIntersectCode(); }) + 237 | 238 | // find the closest intersection 239 | ' float t = ' + infinity + ';' + 240 | ' if(tRoom.x < tRoom.y) t = tRoom.y;' + 241 | concat(objects, function(o){ return o.getMinimumIntersectCode(); }) + 242 | 243 | // info about hit 244 | ' vec3 hit = origin + ray * t;' + 245 | ' vec3 surfaceColor = vec3(0.75);' + 246 | ' float specularHighlight = 0.0;' + 247 | ' vec3 normal;' + 248 | 249 | // calculate the normal (and change wall color) 250 | ' if(t == tRoom.y) {' + 251 | ' normal = -normalForCube(hit, roomCubeMin, roomCubeMax);' + 252 | [yellowBlueCornellBox, redGreenCornellBox][environment] + 253 | newDiffuseRay + 254 | ' } else if(t == ' + infinity + ') {' + 255 | ' break;' + 256 | ' } else {' + 257 | ' if(false) ;' + // hack to discard the first 'else' in 'else if' 258 | concat(objects, function(o){ return o.getNormalCalculationCode(); }) + 259 | [newDiffuseRay, newReflectiveRay, newGlossyRay][material] + 260 | ' }' + 261 | 262 | // compute diffuse lighting contribution 263 | ' vec3 toLight = light - hit;' + 264 | ' float diffuse = max(0.0, dot(normalize(toLight), normal));' + 265 | 266 | // trace a shadow ray to the light 267 | ' float shadowIntensity = shadow(hit + normal * ' + epsilon + ', toLight);' + 268 | 269 | // do light bounce 270 | ' colorMask *= surfaceColor;' + 271 | ' accumulatedColor += colorMask * (' + lightVal + ' * diffuse * shadowIntensity);' + 272 | ' accumulatedColor += colorMask * specularHighlight * shadowIntensity;' + 273 | 274 | // calculate next origin 275 | ' origin = hit;' + 276 | ' }' + 277 | 278 | ' return accumulatedColor;' + 279 | ' }'; 280 | } 281 | 282 | function makeMain() { 283 | return '' + 284 | ' void main() {' + 285 | ' vec3 newLight = light + uniformlyRandomVector(timeSinceStart - 53.0) * ' + lightSize + ';' + 286 | ' vec3 texture = texture2D(texture, gl_FragCoord.xy / 512.0).rgb;' + 287 | ' gl_FragColor = vec4(mix(calculateColor(eye, initialRay, newLight), texture, textureWeight), 1.0);' + 288 | ' }'; 289 | } 290 | 291 | function makeTracerFragmentSource(objects) { 292 | return tracerFragmentSourceHeader + 293 | concat(objects, function(o){ return o.getGlobalCode(); }) + 294 | intersectCubeSource + 295 | normalForCubeSource + 296 | intersectSphereSource + 297 | normalForSphereSource + 298 | randomSource + 299 | cosineWeightedDirectionSource + 300 | uniformlyRandomDirectionSource + 301 | uniformlyRandomVectorSource + 302 | makeShadow(objects) + 303 | makeCalculateColor(objects) + 304 | makeMain(); 305 | } 306 | 307 | //////////////////////////////////////////////////////////////////////////////// 308 | // utility functions 309 | //////////////////////////////////////////////////////////////////////////////// 310 | 311 | function getEyeRay(matrix, x, y) { 312 | return matrix.multiply(Vector.create([x, y, 0, 1])).divideByW().ensure3().subtract(eye); 313 | } 314 | 315 | function setUniforms(program, uniforms) { 316 | for(var name in uniforms) { 317 | var value = uniforms[name]; 318 | var location = gl.getUniformLocation(program, name); 319 | if(location == null) continue; 320 | if(value instanceof Vector) { 321 | gl.uniform3fv(location, new Float32Array([value.elements[0], value.elements[1], value.elements[2]])); 322 | } else if(value instanceof Matrix) { 323 | gl.uniformMatrix4fv(location, false, new Float32Array(value.flatten())); 324 | } else { 325 | gl.uniform1f(location, value); 326 | } 327 | } 328 | } 329 | 330 | function concat(objects, func) { 331 | var text = ''; 332 | for(var i = 0; i < objects.length; i++) { 333 | text += func(objects[i]); 334 | } 335 | return text; 336 | } 337 | 338 | Vector.prototype.ensure3 = function() { 339 | return Vector.create([this.elements[0], this.elements[1], this.elements[2]]); 340 | }; 341 | 342 | Vector.prototype.ensure4 = function(w) { 343 | return Vector.create([this.elements[0], this.elements[1], this.elements[2], w]); 344 | }; 345 | 346 | Vector.prototype.divideByW = function() { 347 | var w = this.elements[this.elements.length - 1]; 348 | var newElements = []; 349 | for(var i = 0; i < this.elements.length; i++) { 350 | newElements.push(this.elements[i] / w); 351 | } 352 | return Vector.create(newElements); 353 | }; 354 | 355 | Vector.prototype.componentDivide = function(vector) { 356 | if(this.elements.length != vector.elements.length) { 357 | return null; 358 | } 359 | var newElements = []; 360 | for(var i = 0; i < this.elements.length; i++) { 361 | newElements.push(this.elements[i] / vector.elements[i]); 362 | } 363 | return Vector.create(newElements); 364 | }; 365 | 366 | Vector.min = function(a, b) { 367 | if(a.length != b.length) { 368 | return null; 369 | } 370 | var newElements = []; 371 | for(var i = 0; i < a.elements.length; i++) { 372 | newElements.push(Math.min(a.elements[i], b.elements[i])); 373 | } 374 | return Vector.create(newElements); 375 | }; 376 | 377 | Vector.max = function(a, b) { 378 | if(a.length != b.length) { 379 | return null; 380 | } 381 | var newElements = []; 382 | for(var i = 0; i < a.elements.length; i++) { 383 | newElements.push(Math.max(a.elements[i], b.elements[i])); 384 | } 385 | return Vector.create(newElements); 386 | }; 387 | 388 | Vector.prototype.minComponent = function() { 389 | var value = Number.MAX_VALUE; 390 | for(var i = 0; i < this.elements.length; i++) { 391 | value = Math.min(value, this.elements[i]); 392 | } 393 | return value; 394 | }; 395 | 396 | Vector.prototype.maxComponent = function() { 397 | var value = -Number.MAX_VALUE; 398 | for(var i = 0; i < this.elements.length; i++) { 399 | value = Math.max(value, this.elements[i]); 400 | } 401 | return value; 402 | }; 403 | 404 | function compileSource(source, type) { 405 | var shader = gl.createShader(type); 406 | gl.shaderSource(shader, source); 407 | gl.compileShader(shader); 408 | if(!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { 409 | throw 'compile error: ' + gl.getShaderInfoLog(shader); 410 | } 411 | return shader; 412 | } 413 | 414 | function compileShader(vertexSource, fragmentSource) { 415 | var shaderProgram = gl.createProgram(); 416 | gl.attachShader(shaderProgram, compileSource(vertexSource, gl.VERTEX_SHADER)); 417 | gl.attachShader(shaderProgram, compileSource(fragmentSource, gl.FRAGMENT_SHADER)); 418 | gl.linkProgram(shaderProgram); 419 | if(!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) { 420 | throw 'link error: ' + gl.getProgramInfoLog(shaderProgram); 421 | } 422 | return shaderProgram; 423 | } 424 | 425 | //////////////////////////////////////////////////////////////////////////////// 426 | // class Sphere 427 | //////////////////////////////////////////////////////////////////////////////// 428 | 429 | function Sphere(center, radius, id) { 430 | this.center = center; 431 | this.radius = radius; 432 | this.centerStr = 'sphereCenter' + id; 433 | this.radiusStr = 'sphereRadius' + id; 434 | this.intersectStr = 'tSphere' + id; 435 | this.temporaryTranslation = Vector.create([0, 0, 0]); 436 | } 437 | 438 | Sphere.prototype.getGlobalCode = function() { 439 | return '' + 440 | ' uniform vec3 ' + this.centerStr + ';' + 441 | ' uniform float ' + this.radiusStr + ';'; 442 | }; 443 | 444 | Sphere.prototype.getIntersectCode = function() { 445 | return '' + 446 | ' float ' + this.intersectStr + ' = intersectSphere(origin, ray, ' + this.centerStr + ', ' + this.radiusStr + ');'; 447 | }; 448 | 449 | Sphere.prototype.getShadowTestCode = function() { 450 | return '' + 451 | this.getIntersectCode() + 452 | ' if(' + this.intersectStr + ' < 1.0) return 0.0;'; 453 | }; 454 | 455 | Sphere.prototype.getMinimumIntersectCode = function() { 456 | return '' + 457 | ' if(' + this.intersectStr + ' < t) t = ' + this.intersectStr + ';'; 458 | }; 459 | 460 | Sphere.prototype.getNormalCalculationCode = function() { 461 | return '' + 462 | ' else if(t == ' + this.intersectStr + ') normal = normalForSphere(hit, ' + this.centerStr + ', ' + this.radiusStr + ');'; 463 | }; 464 | 465 | Sphere.prototype.setUniforms = function(renderer) { 466 | renderer.uniforms[this.centerStr] = this.center.add(this.temporaryTranslation); 467 | renderer.uniforms[this.radiusStr] = this.radius; 468 | }; 469 | 470 | Sphere.prototype.temporaryTranslate = function(translation) { 471 | this.temporaryTranslation = translation; 472 | }; 473 | 474 | Sphere.prototype.translate = function(translation) { 475 | this.center = this.center.add(translation); 476 | }; 477 | 478 | Sphere.prototype.getMinCorner = function() { 479 | return this.center.add(this.temporaryTranslation).subtract(Vector.create([this.radius, this.radius, this.radius])); 480 | }; 481 | 482 | Sphere.prototype.getMaxCorner = function() { 483 | return this.center.add(this.temporaryTranslation).add(Vector.create([this.radius, this.radius, this.radius])); 484 | }; 485 | 486 | Sphere.prototype.intersect = function(origin, ray) { 487 | return Sphere.intersect(origin, ray, this.center.add(this.temporaryTranslation), this.radius); 488 | }; 489 | 490 | Sphere.intersect = function(origin, ray, center, radius) { 491 | var toSphere = origin.subtract(center); 492 | var a = ray.dot(ray); 493 | var b = 2*toSphere.dot(ray); 494 | var c = toSphere.dot(toSphere) - radius*radius; 495 | var discriminant = b*b - 4*a*c; 496 | if(discriminant > 0) { 497 | var t = (-b - Math.sqrt(discriminant)) / (2*a); 498 | if(t > 0) { 499 | return t; 500 | } 501 | } 502 | return Number.MAX_VALUE; 503 | }; 504 | 505 | //////////////////////////////////////////////////////////////////////////////// 506 | // class Cube 507 | //////////////////////////////////////////////////////////////////////////////// 508 | 509 | function Cube(minCorner, maxCorner, id) { 510 | this.minCorner = minCorner; 511 | this.maxCorner = maxCorner; 512 | this.minStr = 'cubeMin' + id; 513 | this.maxStr = 'cubeMax' + id; 514 | this.intersectStr = 'tCube' + id; 515 | this.temporaryTranslation = Vector.create([0, 0, 0]); 516 | } 517 | 518 | Cube.prototype.getGlobalCode = function() { 519 | return '' + 520 | ' uniform vec3 ' + this.minStr + ';' + 521 | ' uniform vec3 ' + this.maxStr + ';'; 522 | }; 523 | 524 | Cube.prototype.getIntersectCode = function() { 525 | return '' + 526 | ' vec2 ' + this.intersectStr + ' = intersectCube(origin, ray, ' + this.minStr + ', ' + this.maxStr + ');'; 527 | }; 528 | 529 | Cube.prototype.getShadowTestCode = function() { 530 | return '' + 531 | this.getIntersectCode() + 532 | ' if(' + this.intersectStr + '.x > 0.0 && ' + this.intersectStr + '.x < 1.0 && ' + this.intersectStr + '.x < ' + this.intersectStr + '.y) return 0.0;'; 533 | }; 534 | 535 | Cube.prototype.getMinimumIntersectCode = function() { 536 | return '' + 537 | ' if(' + this.intersectStr + '.x > 0.0 && ' + this.intersectStr + '.x < ' + this.intersectStr + '.y && ' + this.intersectStr + '.x < t) t = ' + this.intersectStr + '.x;'; 538 | }; 539 | 540 | Cube.prototype.getNormalCalculationCode = function() { 541 | return '' + 542 | // have to compare intersectStr.x < intersectStr.y otherwise two coplanar 543 | // cubes will look wrong (one cube will "steal" the hit from the other) 544 | ' else if(t == ' + this.intersectStr + '.x && ' + this.intersectStr + '.x < ' + this.intersectStr + '.y) normal = normalForCube(hit, ' + this.minStr + ', ' + this.maxStr + ');'; 545 | }; 546 | 547 | Cube.prototype.setUniforms = function(renderer) { 548 | renderer.uniforms[this.minStr] = this.getMinCorner(); 549 | renderer.uniforms[this.maxStr] = this.getMaxCorner(); 550 | }; 551 | 552 | Cube.prototype.temporaryTranslate = function(translation) { 553 | this.temporaryTranslation = translation; 554 | }; 555 | 556 | Cube.prototype.translate = function(translation) { 557 | this.minCorner = this.minCorner.add(translation); 558 | this.maxCorner = this.maxCorner.add(translation); 559 | }; 560 | 561 | Cube.prototype.getMinCorner = function() { 562 | return this.minCorner.add(this.temporaryTranslation); 563 | }; 564 | 565 | Cube.prototype.getMaxCorner = function() { 566 | return this.maxCorner.add(this.temporaryTranslation); 567 | }; 568 | 569 | Cube.prototype.intersect = function(origin, ray) { 570 | return Cube.intersect(origin, ray, this.getMinCorner(), this.getMaxCorner()); 571 | }; 572 | 573 | Cube.intersect = function(origin, ray, cubeMin, cubeMax) { 574 | var tMin = cubeMin.subtract(origin).componentDivide(ray); 575 | var tMax = cubeMax.subtract(origin).componentDivide(ray); 576 | var t1 = Vector.min(tMin, tMax); 577 | var t2 = Vector.max(tMin, tMax); 578 | var tNear = t1.maxComponent(); 579 | var tFar = t2.minComponent(); 580 | if(tNear > 0 && tNear < tFar) { 581 | return tNear; 582 | } 583 | return Number.MAX_VALUE; 584 | }; 585 | 586 | //////////////////////////////////////////////////////////////////////////////// 587 | // class Light 588 | //////////////////////////////////////////////////////////////////////////////// 589 | 590 | function Light() { 591 | this.temporaryTranslation = Vector.create([0, 0, 0]); 592 | } 593 | 594 | Light.prototype.getGlobalCode = function() { 595 | return 'uniform vec3 light;'; 596 | }; 597 | 598 | Light.prototype.getIntersectCode = function() { 599 | return ''; 600 | }; 601 | 602 | Light.prototype.getShadowTestCode = function() { 603 | return ''; 604 | }; 605 | 606 | Light.prototype.getMinimumIntersectCode = function() { 607 | return ''; 608 | }; 609 | 610 | Light.prototype.getNormalCalculationCode = function() { 611 | return ''; 612 | }; 613 | 614 | Light.prototype.setUniforms = function(renderer) { 615 | renderer.uniforms.light = light.add(this.temporaryTranslation); 616 | }; 617 | 618 | Light.clampPosition = function(position) { 619 | for(var i = 0; i < position.elements.length; i++) { 620 | position.elements[i] = Math.max(lightSize - 1, Math.min(1 - lightSize, position.elements[i])); 621 | } 622 | }; 623 | 624 | Light.prototype.temporaryTranslate = function(translation) { 625 | var tempLight = light.add(translation); 626 | Light.clampPosition(tempLight); 627 | this.temporaryTranslation = tempLight.subtract(light); 628 | }; 629 | 630 | Light.prototype.translate = function(translation) { 631 | light = light.add(translation); 632 | Light.clampPosition(light); 633 | }; 634 | 635 | Light.prototype.getMinCorner = function() { 636 | return light.add(this.temporaryTranslation).subtract(Vector.create([lightSize, lightSize, lightSize])); 637 | }; 638 | 639 | Light.prototype.getMaxCorner = function() { 640 | return light.add(this.temporaryTranslation).add(Vector.create([lightSize, lightSize, lightSize])); 641 | }; 642 | 643 | Light.prototype.intersect = function(origin, ray) { 644 | return Number.MAX_VALUE; 645 | }; 646 | 647 | //////////////////////////////////////////////////////////////////////////////// 648 | // class PathTracer 649 | //////////////////////////////////////////////////////////////////////////////// 650 | 651 | function PathTracer() { 652 | var vertices = [ 653 | -1, -1, 654 | -1, +1, 655 | +1, -1, 656 | +1, +1 657 | ]; 658 | 659 | // create vertex buffer 660 | this.vertexBuffer = gl.createBuffer(); 661 | gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); 662 | gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); 663 | 664 | // create framebuffer 665 | this.framebuffer = gl.createFramebuffer(); 666 | 667 | // create textures 668 | var type = gl.getExtension('OES_texture_float') ? gl.FLOAT : gl.UNSIGNED_BYTE; 669 | this.textures = []; 670 | for(var i = 0; i < 2; i++) { 671 | this.textures.push(gl.createTexture()); 672 | gl.bindTexture(gl.TEXTURE_2D, this.textures[i]); 673 | gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); 674 | gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); 675 | gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, 512, 512, 0, gl.RGB, type, null); 676 | } 677 | gl.bindTexture(gl.TEXTURE_2D, null); 678 | 679 | // create render shader 680 | this.renderProgram = compileShader(renderVertexSource, renderFragmentSource); 681 | this.renderVertexAttribute = gl.getAttribLocation(this.renderProgram, 'vertex'); 682 | gl.enableVertexAttribArray(this.renderVertexAttribute); 683 | 684 | // objects and shader will be filled in when setObjects() is called 685 | this.objects = []; 686 | this.sampleCount = 0; 687 | this.tracerProgram = null; 688 | } 689 | 690 | PathTracer.prototype.setObjects = function(objects) { 691 | this.uniforms = {}; 692 | this.sampleCount = 0; 693 | this.objects = objects; 694 | 695 | // create tracer shader 696 | if(this.tracerProgram != null) { 697 | gl.deleteProgram(this.shaderProgram); 698 | } 699 | this.tracerProgram = compileShader(tracerVertexSource, makeTracerFragmentSource(objects)); 700 | this.tracerVertexAttribute = gl.getAttribLocation(this.tracerProgram, 'vertex'); 701 | gl.enableVertexAttribArray(this.tracerVertexAttribute); 702 | }; 703 | 704 | PathTracer.prototype.update = function(matrix, timeSinceStart) { 705 | // calculate uniforms 706 | for(var i = 0; i < this.objects.length; i++) { 707 | this.objects[i].setUniforms(this); 708 | } 709 | this.uniforms.eye = eye; 710 | this.uniforms.glossiness = glossiness; 711 | this.uniforms.ray00 = getEyeRay(matrix, -1, -1); 712 | this.uniforms.ray01 = getEyeRay(matrix, -1, +1); 713 | this.uniforms.ray10 = getEyeRay(matrix, +1, -1); 714 | this.uniforms.ray11 = getEyeRay(matrix, +1, +1); 715 | this.uniforms.timeSinceStart = timeSinceStart; 716 | this.uniforms.textureWeight = this.sampleCount / (this.sampleCount + 1); 717 | 718 | // set uniforms 719 | gl.useProgram(this.tracerProgram); 720 | setUniforms(this.tracerProgram, this.uniforms); 721 | 722 | // render to texture 723 | gl.useProgram(this.tracerProgram); 724 | gl.bindTexture(gl.TEXTURE_2D, this.textures[0]); 725 | gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); 726 | gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer); 727 | gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.textures[1], 0); 728 | gl.vertexAttribPointer(this.tracerVertexAttribute, 2, gl.FLOAT, false, 0, 0); 729 | gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); 730 | gl.bindFramebuffer(gl.FRAMEBUFFER, null); 731 | 732 | // ping pong textures 733 | this.textures.reverse(); 734 | this.sampleCount++; 735 | }; 736 | 737 | PathTracer.prototype.render = function() { 738 | gl.useProgram(this.renderProgram); 739 | gl.bindTexture(gl.TEXTURE_2D, this.textures[0]); 740 | gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); 741 | gl.vertexAttribPointer(this.renderVertexAttribute, 2, gl.FLOAT, false, 0, 0); 742 | gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); 743 | }; 744 | 745 | //////////////////////////////////////////////////////////////////////////////// 746 | // class Renderer 747 | //////////////////////////////////////////////////////////////////////////////// 748 | 749 | function Renderer() { 750 | var vertices = [ 751 | 0, 0, 0, 752 | 1, 0, 0, 753 | 0, 1, 0, 754 | 1, 1, 0, 755 | 0, 0, 1, 756 | 1, 0, 1, 757 | 0, 1, 1, 758 | 1, 1, 1 759 | ]; 760 | var indices = [ 761 | 0, 1, 1, 3, 3, 2, 2, 0, 762 | 4, 5, 5, 7, 7, 6, 6, 4, 763 | 0, 4, 1, 5, 2, 6, 3, 7 764 | ]; 765 | 766 | // create vertex buffer 767 | this.vertexBuffer = gl.createBuffer(); 768 | gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); 769 | gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); 770 | 771 | // create index buffer 772 | this.indexBuffer = gl.createBuffer(); 773 | gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); 774 | gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW); 775 | 776 | // create line shader 777 | this.lineProgram = compileShader(lineVertexSource, lineFragmentSource); 778 | this.vertexAttribute = gl.getAttribLocation(this.lineProgram, 'vertex'); 779 | gl.enableVertexAttribArray(this.vertexAttribute); 780 | 781 | this.objects = []; 782 | this.selectedObject = null; 783 | this.pathTracer = new PathTracer(); 784 | } 785 | 786 | Renderer.prototype.setObjects = function(objects) { 787 | this.objects = objects; 788 | this.selectedObject = null; 789 | this.pathTracer.setObjects(objects); 790 | }; 791 | 792 | Renderer.prototype.update = function(modelviewProjection, timeSinceStart) { 793 | var jitter = Matrix.Translation(Vector.create([Math.random() * 2 - 1, Math.random() * 2 - 1, 0]).multiply(1 / 512)); 794 | var inverse = jitter.multiply(modelviewProjection).inverse(); 795 | this.modelviewProjection = modelviewProjection; 796 | this.pathTracer.update(inverse, timeSinceStart); 797 | }; 798 | 799 | Renderer.prototype.render = function() { 800 | this.pathTracer.render(); 801 | 802 | if(this.selectedObject != null) { 803 | gl.useProgram(this.lineProgram); 804 | gl.bindTexture(gl.TEXTURE_2D, null); 805 | gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer); 806 | gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer); 807 | gl.vertexAttribPointer(this.vertexAttribute, 3, gl.FLOAT, false, 0, 0); 808 | setUniforms(this.lineProgram, { 809 | cubeMin: this.selectedObject.getMinCorner(), 810 | cubeMax: this.selectedObject.getMaxCorner(), 811 | modelviewProjection: this.modelviewProjection 812 | }); 813 | gl.drawElements(gl.LINES, 24, gl.UNSIGNED_SHORT, 0); 814 | } 815 | }; 816 | 817 | //////////////////////////////////////////////////////////////////////////////// 818 | // class UI 819 | //////////////////////////////////////////////////////////////////////////////// 820 | 821 | function UI() { 822 | this.renderer = new Renderer(); 823 | this.moving = false; 824 | } 825 | 826 | UI.prototype.setObjects = function(objects) { 827 | this.objects = objects; 828 | this.objects.splice(0, 0, new Light()); 829 | this.renderer.setObjects(this.objects); 830 | }; 831 | 832 | UI.prototype.update = function(timeSinceStart) { 833 | this.modelview = makeLookAt(eye.elements[0], eye.elements[1], eye.elements[2], 0, 0, 0, 0, 1, 0); 834 | this.projection = makePerspective(55, 1, 0.1, 100); 835 | this.modelviewProjection = this.projection.multiply(this.modelview); 836 | this.renderer.update(this.modelviewProjection, timeSinceStart); 837 | }; 838 | 839 | UI.prototype.mouseDown = function(x, y) { 840 | var t; 841 | var origin = eye; 842 | var ray = getEyeRay(this.modelviewProjection.inverse(), (x / 512) * 2 - 1, 1 - (y / 512) * 2); 843 | 844 | // test the selection box first 845 | if(this.renderer.selectedObject != null) { 846 | var minBounds = this.renderer.selectedObject.getMinCorner(); 847 | var maxBounds = this.renderer.selectedObject.getMaxCorner(); 848 | t = Cube.intersect(origin, ray, minBounds, maxBounds); 849 | 850 | if(t < Number.MAX_VALUE) { 851 | var hit = origin.add(ray.multiply(t)); 852 | 853 | if(Math.abs(hit.elements[0] - minBounds.elements[0]) < 0.001) this.movementNormal = Vector.create([-1, 0, 0]); 854 | else if(Math.abs(hit.elements[0] - maxBounds.elements[0]) < 0.001) this.movementNormal = Vector.create([+1, 0, 0]); 855 | else if(Math.abs(hit.elements[1] - minBounds.elements[1]) < 0.001) this.movementNormal = Vector.create([0, -1, 0]); 856 | else if(Math.abs(hit.elements[1] - maxBounds.elements[1]) < 0.001) this.movementNormal = Vector.create([0, +1, 0]); 857 | else if(Math.abs(hit.elements[2] - minBounds.elements[2]) < 0.001) this.movementNormal = Vector.create([0, 0, -1]); 858 | else this.movementNormal = Vector.create([0, 0, +1]); 859 | 860 | this.movementDistance = this.movementNormal.dot(hit); 861 | this.originalHit = hit; 862 | this.moving = true; 863 | 864 | return true; 865 | } 866 | } 867 | 868 | t = Number.MAX_VALUE; 869 | this.renderer.selectedObject = null; 870 | 871 | for(var i = 0; i < this.objects.length; i++) { 872 | var objectT = this.objects[i].intersect(origin, ray); 873 | if(objectT < t) { 874 | t = objectT; 875 | this.renderer.selectedObject = this.objects[i]; 876 | } 877 | } 878 | 879 | return (t < Number.MAX_VALUE); 880 | }; 881 | 882 | UI.prototype.mouseMove = function(x, y) { 883 | if(this.moving) { 884 | var origin = eye; 885 | var ray = getEyeRay(this.modelviewProjection.inverse(), (x / 512) * 2 - 1, 1 - (y / 512) * 2); 886 | 887 | var t = (this.movementDistance - this.movementNormal.dot(origin)) / this.movementNormal.dot(ray); 888 | var hit = origin.add(ray.multiply(t)); 889 | this.renderer.selectedObject.temporaryTranslate(hit.subtract(this.originalHit)); 890 | 891 | // clear the sample buffer 892 | this.renderer.pathTracer.sampleCount = 0; 893 | } 894 | }; 895 | 896 | UI.prototype.mouseUp = function(x, y) { 897 | if(this.moving) { 898 | var origin = eye; 899 | var ray = getEyeRay(this.modelviewProjection.inverse(), (x / 512) * 2 - 1, 1 - (y / 512) * 2); 900 | 901 | var t = (this.movementDistance - this.movementNormal.dot(origin)) / this.movementNormal.dot(ray); 902 | var hit = origin.add(ray.multiply(t)); 903 | this.renderer.selectedObject.temporaryTranslate(Vector.create([0, 0, 0])); 904 | this.renderer.selectedObject.translate(hit.subtract(this.originalHit)); 905 | this.moving = false; 906 | } 907 | }; 908 | 909 | UI.prototype.render = function() { 910 | this.renderer.render(); 911 | }; 912 | 913 | UI.prototype.selectLight = function() { 914 | this.renderer.selectedObject = this.objects[0]; 915 | }; 916 | 917 | UI.prototype.addSphere = function() { 918 | this.objects.push(new Sphere(Vector.create([0, 0, 0]), 0.25, nextObjectId++)); 919 | this.renderer.setObjects(this.objects); 920 | }; 921 | 922 | UI.prototype.addCube = function() { 923 | this.objects.push(new Cube(Vector.create([-0.25, -0.25, -0.25]), Vector.create([0.25, 0.25, 0.25]), nextObjectId++)); 924 | this.renderer.setObjects(this.objects); 925 | }; 926 | 927 | UI.prototype.deleteSelection = function() { 928 | for(var i = 0; i < this.objects.length; i++) { 929 | if(this.renderer.selectedObject == this.objects[i]) { 930 | this.objects.splice(i, 1); 931 | this.renderer.selectedObject = null; 932 | this.renderer.setObjects(this.objects); 933 | break; 934 | } 935 | } 936 | }; 937 | 938 | UI.prototype.updateMaterial = function() { 939 | var newMaterial = parseInt(document.getElementById('material').value, 10); 940 | if(material != newMaterial) { 941 | material = newMaterial; 942 | this.renderer.setObjects(this.objects); 943 | } 944 | }; 945 | 946 | UI.prototype.updateEnvironment = function() { 947 | var newEnvironment = parseInt(document.getElementById('environment').value, 10); 948 | if(environment != newEnvironment) { 949 | environment = newEnvironment; 950 | this.renderer.setObjects(this.objects); 951 | } 952 | }; 953 | 954 | UI.prototype.updateGlossiness = function() { 955 | var newGlossiness = parseFloat(document.getElementById('glossiness').value); 956 | if(isNaN(newGlossiness)) newGlossiness = 0; 957 | newGlossiness = Math.max(0, Math.min(1, newGlossiness)); 958 | if(material == MATERIAL_GLOSSY && glossiness != newGlossiness) { 959 | this.renderer.pathTracer.sampleCount = 0; 960 | } 961 | glossiness = newGlossiness; 962 | }; 963 | 964 | //////////////////////////////////////////////////////////////////////////////// 965 | // main program 966 | //////////////////////////////////////////////////////////////////////////////// 967 | 968 | var gl; 969 | var ui; 970 | var error; 971 | var canvas; 972 | var inputFocusCount = 0; 973 | 974 | var angleX = 0; 975 | var angleY = 0; 976 | var zoomZ = 2.5; 977 | var eye = Vector.create([0, 0, 0]); 978 | var light = Vector.create([0.4, 0.5, -0.6]); 979 | 980 | var nextObjectId = 0; 981 | 982 | var MATERIAL_DIFFUSE = 0; 983 | var MATERIAL_MIRROR = 1; 984 | var MATERIAL_GLOSSY = 2; 985 | var material = MATERIAL_DIFFUSE; 986 | var glossiness = 0.6; 987 | 988 | var YELLOW_BLUE_CORNELL_BOX = 0; 989 | var RED_GREEN_CORNELL_BOX = 1; 990 | var environment = YELLOW_BLUE_CORNELL_BOX; 991 | 992 | function tick(timeSinceStart) { 993 | eye.elements[0] = zoomZ * Math.sin(angleY) * Math.cos(angleX); 994 | eye.elements[1] = zoomZ * Math.sin(angleX); 995 | eye.elements[2] = zoomZ * Math.cos(angleY) * Math.cos(angleX); 996 | 997 | document.getElementById('glossiness-factor').style.display = (material == MATERIAL_GLOSSY) ? 'inline' : 'none'; 998 | 999 | ui.updateMaterial(); 1000 | ui.updateGlossiness(); 1001 | ui.updateEnvironment(); 1002 | ui.update(timeSinceStart); 1003 | ui.render(); 1004 | } 1005 | 1006 | function makeStacks() { 1007 | var objects = []; 1008 | 1009 | // lower level 1010 | objects.push(new Cube(Vector.create([-0.5, -0.75, -0.5]), Vector.create([0.5, -0.7, 0.5]), nextObjectId++)); 1011 | 1012 | // further poles 1013 | objects.push(new Cube(Vector.create([-0.45, -1, -0.45]), Vector.create([-0.4, -0.45, -0.4]), nextObjectId++)); 1014 | objects.push(new Cube(Vector.create([0.4, -1, -0.45]), Vector.create([0.45, -0.45, -0.4]), nextObjectId++)); 1015 | objects.push(new Cube(Vector.create([-0.45, -1, 0.4]), Vector.create([-0.4, -0.45, 0.45]), nextObjectId++)); 1016 | objects.push(new Cube(Vector.create([0.4, -1, 0.4]), Vector.create([0.45, -0.45, 0.45]), nextObjectId++)); 1017 | 1018 | // upper level 1019 | objects.push(new Cube(Vector.create([-0.3, -0.5, -0.3]), Vector.create([0.3, -0.45, 0.3]), nextObjectId++)); 1020 | 1021 | // closer poles 1022 | objects.push(new Cube(Vector.create([-0.25, -0.7, -0.25]), Vector.create([-0.2, -0.25, -0.2]), nextObjectId++)); 1023 | objects.push(new Cube(Vector.create([0.2, -0.7, -0.25]), Vector.create([0.25, -0.25, -0.2]), nextObjectId++)); 1024 | objects.push(new Cube(Vector.create([-0.25, -0.7, 0.2]), Vector.create([-0.2, -0.25, 0.25]), nextObjectId++)); 1025 | objects.push(new Cube(Vector.create([0.2, -0.7, 0.2]), Vector.create([0.25, -0.25, 0.25]), nextObjectId++)); 1026 | 1027 | // upper level 1028 | objects.push(new Cube(Vector.create([-0.25, -0.25, -0.25]), Vector.create([0.25, -0.2, 0.25]), nextObjectId++)); 1029 | 1030 | return objects; 1031 | } 1032 | 1033 | function makeTableAndChair() { 1034 | var objects = []; 1035 | 1036 | // table top 1037 | objects.push(new Cube(Vector.create([-0.5, -0.35, -0.5]), Vector.create([0.3, -0.3, 0.5]), nextObjectId++)); 1038 | 1039 | // table legs 1040 | objects.push(new Cube(Vector.create([-0.45, -1, -0.45]), Vector.create([-0.4, -0.35, -0.4]), nextObjectId++)); 1041 | objects.push(new Cube(Vector.create([0.2, -1, -0.45]), Vector.create([0.25, -0.35, -0.4]), nextObjectId++)); 1042 | objects.push(new Cube(Vector.create([-0.45, -1, 0.4]), Vector.create([-0.4, -0.35, 0.45]), nextObjectId++)); 1043 | objects.push(new Cube(Vector.create([0.2, -1, 0.4]), Vector.create([0.25, -0.35, 0.45]), nextObjectId++)); 1044 | 1045 | // chair seat 1046 | objects.push(new Cube(Vector.create([0.3, -0.6, -0.2]), Vector.create([0.7, -0.55, 0.2]), nextObjectId++)); 1047 | 1048 | // chair legs 1049 | objects.push(new Cube(Vector.create([0.3, -1, -0.2]), Vector.create([0.35, -0.6, -0.15]), nextObjectId++)); 1050 | objects.push(new Cube(Vector.create([0.3, -1, 0.15]), Vector.create([0.35, -0.6, 0.2]), nextObjectId++)); 1051 | objects.push(new Cube(Vector.create([0.65, -1, -0.2]), Vector.create([0.7, 0.1, -0.15]), nextObjectId++)); 1052 | objects.push(new Cube(Vector.create([0.65, -1, 0.15]), Vector.create([0.7, 0.1, 0.2]), nextObjectId++)); 1053 | 1054 | // chair back 1055 | objects.push(new Cube(Vector.create([0.65, 0.05, -0.15]), Vector.create([0.7, 0.1, 0.15]), nextObjectId++)); 1056 | objects.push(new Cube(Vector.create([0.65, -0.55, -0.09]), Vector.create([0.7, 0.1, -0.03]), nextObjectId++)); 1057 | objects.push(new Cube(Vector.create([0.65, -0.55, 0.03]), Vector.create([0.7, 0.1, 0.09]), nextObjectId++)); 1058 | 1059 | // sphere on table 1060 | objects.push(new Sphere(Vector.create([-0.1, -0.05, 0]), 0.25, nextObjectId++)); 1061 | 1062 | return objects; 1063 | } 1064 | 1065 | function makeSphereAndCube() { 1066 | var objects = []; 1067 | objects.push(new Cube(Vector.create([-0.25, -1, -0.25]), Vector.create([0.25, -0.75, 0.25]), nextObjectId++)); 1068 | objects.push(new Sphere(Vector.create([0, -0.75, 0]), 0.25, nextObjectId++)); 1069 | return objects; 1070 | } 1071 | 1072 | function makeSphereColumn() { 1073 | var objects = []; 1074 | objects.push(new Sphere(Vector.create([0, 0.75, 0]), 0.25, nextObjectId++)); 1075 | objects.push(new Sphere(Vector.create([0, 0.25, 0]), 0.25, nextObjectId++)); 1076 | objects.push(new Sphere(Vector.create([0, -0.25, 0]), 0.25, nextObjectId++)); 1077 | objects.push(new Sphere(Vector.create([0, -0.75, 0]), 0.25, nextObjectId++)); 1078 | return objects; 1079 | } 1080 | 1081 | function makeCubeAndSpheres() { 1082 | var objects = []; 1083 | objects.push(new Cube(Vector.create([-0.25, -0.25, -0.25]), Vector.create([0.25, 0.25, 0.25]), nextObjectId++)); 1084 | objects.push(new Sphere(Vector.create([-0.25, 0, 0]), 0.25, nextObjectId++)); 1085 | objects.push(new Sphere(Vector.create([+0.25, 0, 0]), 0.25, nextObjectId++)); 1086 | objects.push(new Sphere(Vector.create([0, -0.25, 0]), 0.25, nextObjectId++)); 1087 | objects.push(new Sphere(Vector.create([0, +0.25, 0]), 0.25, nextObjectId++)); 1088 | objects.push(new Sphere(Vector.create([0, 0, -0.25]), 0.25, nextObjectId++)); 1089 | objects.push(new Sphere(Vector.create([0, 0, +0.25]), 0.25, nextObjectId++)); 1090 | return objects; 1091 | } 1092 | 1093 | function makeSpherePyramid() { 1094 | var root3_over4 = 0.433012701892219; 1095 | var root3_over6 = 0.288675134594813; 1096 | var root6_over6 = 0.408248290463863; 1097 | var objects = []; 1098 | 1099 | // first level 1100 | objects.push(new Sphere(Vector.create([-0.5, -0.75, -root3_over6]), 0.25, nextObjectId++)); 1101 | objects.push(new Sphere(Vector.create([0.0, -0.75, -root3_over6]), 0.25, nextObjectId++)); 1102 | objects.push(new Sphere(Vector.create([0.5, -0.75, -root3_over6]), 0.25, nextObjectId++)); 1103 | objects.push(new Sphere(Vector.create([-0.25, -0.75, root3_over4 - root3_over6]), 0.25, nextObjectId++)); 1104 | objects.push(new Sphere(Vector.create([0.25, -0.75, root3_over4 - root3_over6]), 0.25, nextObjectId++)); 1105 | objects.push(new Sphere(Vector.create([0.0, -0.75, 2.0 * root3_over4 - root3_over6]), 0.25, nextObjectId++)); 1106 | 1107 | // second level 1108 | objects.push(new Sphere(Vector.create([0.0, -0.75 + root6_over6, root3_over6]), 0.25, nextObjectId++)); 1109 | objects.push(new Sphere(Vector.create([-0.25, -0.75 + root6_over6, -0.5 * root3_over6]), 0.25, nextObjectId++)); 1110 | objects.push(new Sphere(Vector.create([0.25, -0.75 + root6_over6, -0.5 * root3_over6]), 0.25, nextObjectId++)); 1111 | 1112 | // third level 1113 | objects.push(new Sphere(Vector.create([0.0, -0.75 + 2.0 * root6_over6, 0.0]), 0.25, nextObjectId++)); 1114 | 1115 | return objects; 1116 | } 1117 | 1118 | var XNEG = 0, XPOS = 1, YNEG = 2, YPOS = 3, ZNEG = 4, ZPOS = 5; 1119 | 1120 | function addRecursiveSpheresBranch(objects, center, radius, depth, dir) { 1121 | objects.push(new Sphere(center, radius, nextObjectId++)); 1122 | if(depth--) { 1123 | if(dir != XNEG) addRecursiveSpheresBranch(objects, center.subtract(Vector.create([radius * 1.5, 0, 0])), radius / 2, depth, XPOS); 1124 | if(dir != XPOS) addRecursiveSpheresBranch(objects, center.add(Vector.create([radius * 1.5, 0, 0])), radius / 2, depth, XNEG); 1125 | 1126 | if(dir != YNEG) addRecursiveSpheresBranch(objects, center.subtract(Vector.create([0, radius * 1.5, 0])), radius / 2, depth, YPOS); 1127 | if(dir != YPOS) addRecursiveSpheresBranch(objects, center.add(Vector.create([0, radius * 1.5, 0])), radius / 2, depth, YNEG); 1128 | 1129 | if(dir != ZNEG) addRecursiveSpheresBranch(objects, center.subtract(Vector.create([0, 0, radius * 1.5])), radius / 2, depth, ZPOS); 1130 | if(dir != ZPOS) addRecursiveSpheresBranch(objects, center.add(Vector.create([0, 0, radius * 1.5])), radius / 2, depth, ZNEG); 1131 | } 1132 | } 1133 | 1134 | function makeRecursiveSpheres() { 1135 | var objects = []; 1136 | addRecursiveSpheresBranch(objects, Vector.create([0, 0, 0]), 0.3, 2, -1); 1137 | return objects; 1138 | } 1139 | 1140 | window.onload = function() { 1141 | gl = null; 1142 | error = document.getElementById('error'); 1143 | canvas = document.getElementById('canvas'); 1144 | try { gl = canvas.getContext('experimental-webgl'); } catch(e) {} 1145 | 1146 | if(gl) { 1147 | error.innerHTML = 'Loading...'; 1148 | 1149 | // keep track of whether an is focused or not (will be no only if inputFocusCount == 0) 1150 | var inputs = document.getElementsByTagName('input'); 1151 | for(var i= 0; i < inputs.length; i++) { 1152 | inputs[i].onfocus = function(){ inputFocusCount++; }; 1153 | inputs[i].onblur = function(){ inputFocusCount--; }; 1154 | } 1155 | 1156 | material = parseInt(document.getElementById('material').value, 10); 1157 | environment = parseInt(document.getElementById('environment').value, 10); 1158 | ui = new UI(); 1159 | ui.setObjects(makeSphereColumn()); 1160 | var start = new Date(); 1161 | error.style.zIndex = -1; 1162 | setInterval(function(){ tick((new Date() - start) * 0.001); }, 1000 / 60); 1163 | } else { 1164 | error.innerHTML = 'Your browser does not support WebGL.
Please see Getting a WebGL Implementation.'; 1165 | } 1166 | }; 1167 | 1168 | function elementPos(element) { 1169 | var x = 0, y = 0; 1170 | while(element.offsetParent) { 1171 | x += element.offsetLeft; 1172 | y += element.offsetTop; 1173 | element = element.offsetParent; 1174 | } 1175 | return { x: x, y: y }; 1176 | } 1177 | 1178 | function eventPos(event) { 1179 | return { 1180 | x: event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft, 1181 | y: event.clientY + document.body.scrollTop + document.documentElement.scrollTop 1182 | }; 1183 | } 1184 | 1185 | function canvasMousePos(event) { 1186 | var mousePos = eventPos(event); 1187 | var canvasPos = elementPos(canvas); 1188 | return { 1189 | x: mousePos.x - canvasPos.x, 1190 | y: mousePos.y - canvasPos.y 1191 | }; 1192 | } 1193 | 1194 | var mouseDown = false, oldX, oldY; 1195 | 1196 | document.onmousedown = function(event) { 1197 | var mouse = canvasMousePos(event); 1198 | oldX = mouse.x; 1199 | oldY = mouse.y; 1200 | 1201 | if(mouse.x >= 0 && mouse.x < 512 && mouse.y >= 0 && mouse.y < 512) { 1202 | mouseDown = !ui.mouseDown(mouse.x, mouse.y); 1203 | 1204 | // disable selection because dragging is used for rotating the camera and moving objects 1205 | return false; 1206 | } 1207 | 1208 | return true; 1209 | }; 1210 | 1211 | document.onmousemove = function(event) { 1212 | var mouse = canvasMousePos(event); 1213 | 1214 | if(mouseDown) { 1215 | // update the angles based on how far we moved since last time 1216 | angleY -= (mouse.x - oldX) * 0.01; 1217 | angleX += (mouse.y - oldY) * 0.01; 1218 | 1219 | // don't go upside down 1220 | angleX = Math.max(angleX, -Math.PI / 2 + 0.01); 1221 | angleX = Math.min(angleX, Math.PI / 2 - 0.01); 1222 | 1223 | // clear the sample buffer 1224 | ui.renderer.pathTracer.sampleCount = 0; 1225 | 1226 | // remember this coordinate 1227 | oldX = mouse.x; 1228 | oldY = mouse.y; 1229 | } else { 1230 | var canvasPos = elementPos(canvas); 1231 | ui.mouseMove(mouse.x, mouse.y); 1232 | } 1233 | }; 1234 | 1235 | document.onmouseup = function(event) { 1236 | mouseDown = false; 1237 | 1238 | var mouse = canvasMousePos(event); 1239 | ui.mouseUp(mouse.x, mouse.y); 1240 | }; 1241 | 1242 | document.onkeydown = function(event) { 1243 | // if there are no elements focused 1244 | if(inputFocusCount == 0) { 1245 | // if backspace or delete was pressed 1246 | if(event.keyCode == 8 || event.keyCode == 46) { 1247 | ui.deleteSelection(); 1248 | 1249 | // don't let the backspace key go back a page 1250 | return false; 1251 | } 1252 | } 1253 | }; 1254 | --------------------------------------------------------------------------------