RaytracingWorker.js 12 KB

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