RaytracingWorker.js 12 KB

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