RaytracingWorker.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. var workers, worker;
  2. var BLOCK = 128;
  3. var startX, startY, division, completed = 0;
  4. var scene, camera, renderer, loader;
  5. importScripts('../../../build/three.min.js');
  6. self.onmessage = function(e) {
  7. var data = e.data;
  8. if (!data) return;
  9. if (data.init) {
  10. console.log('init')
  11. var
  12. width = data.init[0],
  13. height = data.init[1];
  14. worker = data.worker;
  15. workers = data.workers;
  16. BLOCK = data.blockSize;
  17. // eval(data.initScene);
  18. // initScene(width, height);
  19. renderer = new THREE.RaytracingRendererWorker();
  20. loader = new THREE.ObjectLoader();
  21. renderer.setSize( width, height );
  22. // TODO fix passing maxRecursionDepth as parameter.
  23. // if (data.maxRecursionDepth) maxRecursionDepth = data.maxRecursionDepth;
  24. completed = 0;
  25. }
  26. if (data.scene) {
  27. scene = loader.parse(data.scene);
  28. camera = loader.parse(data.camera);
  29. var positions = data.positions;
  30. copyPositions(camera, positions);
  31. scene.traverse( function(o) {
  32. copyPositions( o, positions );
  33. } );
  34. }
  35. if (data.render && scene && camera) {
  36. startX = data.x;
  37. startY = data.y;
  38. renderer.render(scene, camera);
  39. }
  40. }
  41. function copyPositions(object, positions) {
  42. var info = positions[object.uuid];
  43. object.position.fromArray(info.position);
  44. object.scale.fromArray(info.scale);
  45. object.rotation.fromArray(info.rotation);
  46. }
  47. /**
  48. * DOM-less version of Raytracing Renderer
  49. * @author mrdoob / http://mrdoob.com/
  50. * @author alteredq / http://alteredqualia.com/
  51. * @author zz95 / http://github.com/zz85
  52. */
  53. THREE.RaytracingRendererWorker = function ( parameters ) {
  54. console.log( 'THREE.RaytracingRenderer', THREE.REVISION );
  55. parameters = parameters || {};
  56. var scope = this;
  57. var maxRecursionDepth = 3;
  58. var canvasWidth, canvasHeight;
  59. var canvasWidthHalf, canvasHeightHalf;
  60. var origin = new THREE.Vector3();
  61. var direction = new THREE.Vector3();
  62. var cameraPosition = new THREE.Vector3();
  63. var raycaster = new THREE.Raycaster( origin, direction );
  64. var raycasterLight = new THREE.Raycaster();
  65. var perspective;
  66. var modelViewMatrix = new THREE.Matrix4();
  67. var cameraNormalMatrix = new THREE.Matrix3();
  68. var objects;
  69. var lights = [];
  70. var cache = {};
  71. var animationFrameId = null;
  72. this.setSize = function ( width, height ) {
  73. canvasWidth = width;
  74. canvasHeight = height;
  75. canvasWidthHalf = Math.floor( canvasWidth / 2 );
  76. canvasHeightHalf = Math.floor( canvasHeight / 2 );
  77. };
  78. //
  79. var spawnRay = ( function () {
  80. var diffuseColor = new THREE.Color();
  81. var specularColor = new THREE.Color();
  82. var lightColor = new THREE.Color();
  83. var schlick = new THREE.Color();
  84. var lightContribution = new THREE.Color();
  85. var eyeVector = new THREE.Vector3();
  86. var lightVector = new THREE.Vector3();
  87. var normalVector = new THREE.Vector3();
  88. var halfVector = new THREE.Vector3();
  89. var localPoint = new THREE.Vector3();
  90. var reflectionVector = new THREE.Vector3();
  91. var tmpVec = new THREE.Vector3();
  92. var tmpColor = [];
  93. for ( var i = 0; i < maxRecursionDepth; i ++ ) {
  94. tmpColor[ i ] = new THREE.Color();
  95. }
  96. return function spawnRay( rayOrigin, rayDirection, outputColor, recursionDepth ) {
  97. var ray = raycaster.ray;
  98. ray.origin = rayOrigin;
  99. ray.direction = rayDirection;
  100. //
  101. var rayLight = raycasterLight.ray;
  102. //
  103. outputColor.setRGB( 0, 0, 0 );
  104. //
  105. var intersections = raycaster.intersectObjects( objects, true );
  106. // ray didn't find anything
  107. // (here should come setting of background color?)
  108. if ( intersections.length === 0 ) {
  109. return;
  110. }
  111. // ray hit
  112. var intersection = intersections[ 0 ];
  113. var point = intersection.point;
  114. var object = intersection.object;
  115. var material = object.material;
  116. var face = intersection.face;
  117. var vertices = object.geometry.vertices;
  118. //
  119. var _object = cache[ object.id ];
  120. localPoint.copy( point ).applyMatrix4( _object.inverseMatrix );
  121. eyeVector.subVectors( raycaster.ray.origin, point ).normalize();
  122. // resolve pixel diffuse color
  123. if ( material instanceof THREE.MeshLambertMaterial ||
  124. material instanceof THREE.MeshPhongMaterial ||
  125. material instanceof THREE.MeshBasicMaterial ) {
  126. diffuseColor.copyGammaToLinear( material.color );
  127. } else {
  128. diffuseColor.setRGB( 1, 1, 1 );
  129. }
  130. if ( material.vertexColors === THREE.FaceColors ) {
  131. diffuseColor.multiply( face.color );
  132. }
  133. // compute light shading
  134. rayLight.origin.copy( point );
  135. if ( material instanceof THREE.MeshBasicMaterial ) {
  136. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  137. var light = lights[ i ];
  138. lightVector.setFromMatrixPosition( light.matrixWorld );
  139. lightVector.sub( point );
  140. rayLight.direction.copy( lightVector ).normalize();
  141. var intersections = raycasterLight.intersectObjects( objects, true );
  142. // point in shadow
  143. if ( intersections.length > 0 ) continue;
  144. // point visible
  145. outputColor.add( diffuseColor );
  146. }
  147. } else if ( material instanceof THREE.MeshLambertMaterial ||
  148. material instanceof THREE.MeshPhongMaterial ) {
  149. var normalComputed = false;
  150. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  151. var light = lights[ i ];
  152. lightColor.copyGammaToLinear( light.color );
  153. lightVector.setFromMatrixPosition( light.matrixWorld );
  154. lightVector.sub( point );
  155. rayLight.direction.copy( lightVector ).normalize();
  156. var intersections = raycasterLight.intersectObjects( objects, true );
  157. // point in shadow
  158. if ( intersections.length > 0 ) continue;
  159. // point lit
  160. if ( normalComputed === false ) {
  161. // the same normal can be reused for all lights
  162. // (should be possible to cache even more)
  163. computePixelNormal( normalVector, localPoint, material.shading, face, vertices );
  164. normalVector.applyMatrix3( _object.normalMatrix ).normalize();
  165. normalComputed = true;
  166. }
  167. // compute attenuation
  168. var attenuation = 1.0;
  169. if ( light.physicalAttenuation === true ) {
  170. attenuation = lightVector.length();
  171. attenuation = 1.0 / ( attenuation * attenuation );
  172. }
  173. lightVector.normalize();
  174. // compute diffuse
  175. var dot = Math.max( normalVector.dot( lightVector ), 0 );
  176. var diffuseIntensity = dot * light.intensity;
  177. lightContribution.copy( diffuseColor );
  178. lightContribution.multiply( lightColor );
  179. lightContribution.multiplyScalar( diffuseIntensity * attenuation );
  180. outputColor.add( lightContribution );
  181. // compute specular
  182. if ( material instanceof THREE.MeshPhongMaterial ) {
  183. halfVector.addVectors( lightVector, eyeVector ).normalize();
  184. var dotNormalHalf = Math.max( normalVector.dot( halfVector ), 0.0 );
  185. var specularIntensity = Math.max( Math.pow( dotNormalHalf, material.shininess ), 0.0 ) * diffuseIntensity;
  186. var specularNormalization = ( material.shininess + 2.0 ) / 8.0;
  187. specularColor.copyGammaToLinear( material.specular );
  188. var alpha = Math.pow( Math.max( 1.0 - lightVector.dot( halfVector ), 0.0 ), 5.0 );
  189. schlick.r = specularColor.r + ( 1.0 - specularColor.r ) * alpha;
  190. schlick.g = specularColor.g + ( 1.0 - specularColor.g ) * alpha;
  191. schlick.b = specularColor.b + ( 1.0 - specularColor.b ) * alpha;
  192. lightContribution.copy( schlick );
  193. lightContribution.multiply( lightColor );
  194. lightContribution.multiplyScalar( specularNormalization * specularIntensity * attenuation );
  195. outputColor.add( lightContribution );
  196. }
  197. }
  198. }
  199. // reflection / refraction
  200. var reflectivity = material.reflectivity;
  201. if ( ( material.mirror || material.glass ) && reflectivity > 0 && recursionDepth < maxRecursionDepth ) {
  202. if ( material.mirror ) {
  203. reflectionVector.copy( rayDirection );
  204. reflectionVector.reflect( normalVector );
  205. } else if ( material.glass ) {
  206. var eta = material.refractionRatio;
  207. var dotNI = rayDirection.dot( normalVector );
  208. var k = 1.0 - eta * eta * ( 1.0 - dotNI * dotNI );
  209. if ( k < 0.0 ) {
  210. reflectionVector.set( 0, 0, 0 );
  211. } else {
  212. reflectionVector.copy( rayDirection );
  213. reflectionVector.multiplyScalar( eta );
  214. var alpha = eta * dotNI + Math.sqrt( k );
  215. tmpVec.copy( normalVector );
  216. tmpVec.multiplyScalar( alpha );
  217. reflectionVector.sub( tmpVec );
  218. }
  219. }
  220. var theta = Math.max( eyeVector.dot( normalVector ), 0.0 );
  221. var rf0 = reflectivity;
  222. var fresnel = rf0 + ( 1.0 - rf0 ) * Math.pow( ( 1.0 - theta ), 5.0 );
  223. var weight = fresnel;
  224. var zColor = tmpColor[ recursionDepth ];
  225. spawnRay( point, reflectionVector, zColor, recursionDepth + 1 );
  226. if ( material.specular !== undefined ) {
  227. zColor.multiply( material.specular );
  228. }
  229. zColor.multiplyScalar( weight );
  230. outputColor.multiplyScalar( 1 - weight );
  231. outputColor.add( zColor );
  232. }
  233. };
  234. }() );
  235. var computePixelNormal = ( function () {
  236. var tmpVec1 = new THREE.Vector3();
  237. var tmpVec2 = new THREE.Vector3();
  238. var tmpVec3 = new THREE.Vector3();
  239. return function computePixelNormal( outputVector, point, shading, face, vertices ) {
  240. var faceNormal = face.normal;
  241. var vertexNormals = face.vertexNormals;
  242. if ( shading === THREE.FlatShading ) {
  243. outputVector.copy( faceNormal );
  244. } else if ( shading === THREE.SmoothShading ) {
  245. // compute barycentric coordinates
  246. var vA = vertices[ face.a ];
  247. var vB = vertices[ face.b ];
  248. var vC = vertices[ face.c ];
  249. tmpVec3.crossVectors( tmpVec1.subVectors( vB, vA ), tmpVec2.subVectors( vC, vA ) );
  250. var areaABC = faceNormal.dot( tmpVec3 );
  251. tmpVec3.crossVectors( tmpVec1.subVectors( vB, point ), tmpVec2.subVectors( vC, point ) );
  252. var areaPBC = faceNormal.dot( tmpVec3 );
  253. var a = areaPBC / areaABC;
  254. tmpVec3.crossVectors( tmpVec1.subVectors( vC, point ), tmpVec2.subVectors( vA, point ) );
  255. var areaPCA = faceNormal.dot( tmpVec3 );
  256. var b = areaPCA / areaABC;
  257. var c = 1.0 - a - b;
  258. // compute interpolated vertex normal
  259. tmpVec1.copy( vertexNormals[ 0 ] );
  260. tmpVec1.multiplyScalar( a );
  261. tmpVec2.copy( vertexNormals[ 1 ] );
  262. tmpVec2.multiplyScalar( b );
  263. tmpVec3.copy( vertexNormals[ 2 ] );
  264. tmpVec3.multiplyScalar( c );
  265. outputVector.addVectors( tmpVec1, tmpVec2 );
  266. outputVector.add( tmpVec3 );
  267. }
  268. };
  269. }() );
  270. var renderBlock = ( function () {
  271. var blockSize = BLOCK;
  272. var data = new Uint8ClampedArray(blockSize * blockSize * 4);
  273. var pixelColor = new THREE.Color();
  274. return function renderBlock( blockX, blockY ) {
  275. var index = 0;
  276. for ( var y = 0; y < blockSize; y ++ ) {
  277. for ( var x = 0; x < blockSize; x ++, index += 4 ) {
  278. // spawn primary ray at pixel position
  279. origin.copy( cameraPosition );
  280. direction.set( x + blockX - canvasWidthHalf, - ( y + blockY - canvasHeightHalf ), - perspective );
  281. direction.applyMatrix3( cameraNormalMatrix ).normalize();
  282. spawnRay( origin, direction, pixelColor, 0 );
  283. // convert from linear to gamma
  284. data[ index ] = Math.sqrt( pixelColor.r ) * 255;
  285. data[ index + 1 ] = Math.sqrt( pixelColor.g ) * 255;
  286. data[ index + 2 ] = Math.sqrt( pixelColor.b ) * 255;
  287. data[ index + 3 ] = 255;
  288. }
  289. }
  290. // Use transferable objects! :)
  291. self.postMessage({
  292. data: data.buffer,
  293. blockX: blockX,
  294. blockY: blockY,
  295. blockSize: blockSize,
  296. }, [data.buffer]);
  297. data = new Uint8ClampedArray(blockSize * blockSize * 4);
  298. // OK Done!
  299. completed++;
  300. self.postMessage({
  301. type: 'complete',
  302. worker: worker,
  303. time: Date.now() - reallyThen
  304. });
  305. };
  306. }() );
  307. this.render = function ( scene, camera ) {
  308. reallyThen = Date.now()
  309. cancelAnimationFrame( animationFrameId );
  310. // update scene graph
  311. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  312. // update camera matrices
  313. if ( camera.parent === null ) camera.updateMatrixWorld();
  314. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  315. cameraPosition.setFromMatrixPosition( camera.matrixWorld );
  316. //
  317. cameraNormalMatrix.getNormalMatrix( camera.matrixWorld );
  318. origin.copy( cameraPosition );
  319. perspective = 0.5 / Math.tan( THREE.Math.degToRad( camera.fov * 0.5 ) ) * canvasHeight;
  320. objects = scene.children;
  321. // collect lights and set up object matrices
  322. lights.length = 0;
  323. scene.traverse( function ( object ) {
  324. if ( object instanceof THREE.Light ) {
  325. lights.push( object );
  326. }
  327. if ( cache[ object.id ] === undefined ) {
  328. cache[ object.id ] = {
  329. normalMatrix: new THREE.Matrix3(),
  330. inverseMatrix: new THREE.Matrix4()
  331. };
  332. }
  333. modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  334. var _object = cache[ object.id ];
  335. _object.normalMatrix.getNormalMatrix( modelViewMatrix );
  336. _object.inverseMatrix.getInverse( object.matrixWorld );
  337. } );
  338. renderBlock( startX, startY );
  339. };
  340. };
  341. THREE.EventDispatcher.prototype.apply( THREE.RaytracingRendererWorker.prototype );