RaytracingWorker.js 13 KB

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