RaytracingWorker.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. var worker;
  2. var BLOCK = 128;
  3. var startX, startY, division, completed = 0;
  4. var scene, camera, renderer, loader, sceneId;
  5. importScripts( '../../../build/three.js' );
  6. self.onmessage = function( e ) {
  7. var data = e.data;
  8. if ( ! data ) return;
  9. if ( data.init ) {
  10. var
  11. width = data.init[ 0 ],
  12. height = data.init[ 1 ];
  13. worker = data.worker;
  14. BLOCK = data.blockSize;
  15. if ( ! renderer ) renderer = new THREE.RaytracingRendererWorker();
  16. if ( ! loader ) loader = new THREE.ObjectLoader();
  17. renderer.setSize( width, height );
  18. // TODO fix passing maxRecursionDepth as parameter.
  19. // if (data.maxRecursionDepth) maxRecursionDepth = data.maxRecursionDepth;
  20. completed = 0;
  21. }
  22. if ( data.scene ) {
  23. scene = loader.parse( data.scene );
  24. camera = loader.parse( data.camera );
  25. var meta = data.annex;
  26. scene.traverse( function( o ) {
  27. if ( o.isPointLight ) {
  28. o.physicalAttenuation = true;
  29. }
  30. var mat = o.material;
  31. if (!mat) return;
  32. var material = meta[ mat.uuid ];
  33. for (var m in material) {
  34. mat[ m ] = material[ m ];
  35. }
  36. } );
  37. sceneId = data.sceneId;
  38. }
  39. if ( data.render && scene && camera ) {
  40. startX = data.x;
  41. startY = data.y;
  42. renderer.render( scene, camera );
  43. }
  44. }
  45. /**
  46. * DOM-less version of Raytracing Renderer
  47. * @author mrdoob / http://mrdoob.com/
  48. * @author alteredq / http://alteredqualia.com/
  49. * @author zz95 / http://github.com/zz85
  50. */
  51. THREE.RaytracingRendererWorker = function () {
  52. console.log( 'THREE.RaytracingRendererWorker', THREE.REVISION );
  53. var scope = this;
  54. var maxRecursionDepth = 3;
  55. var canvasWidth, canvasHeight;
  56. var canvasWidthHalf, canvasHeightHalf;
  57. var origin = new THREE.Vector3();
  58. var direction = new THREE.Vector3();
  59. var cameraPosition = new THREE.Vector3();
  60. var raycaster = new THREE.Raycaster( origin, direction );
  61. var ray = raycaster.ray;
  62. var raycasterLight = new THREE.Raycaster();
  63. var rayLight = raycasterLight.ray;
  64. var perspective;
  65. var cameraNormalMatrix = new THREE.Matrix3();
  66. var objects;
  67. var lights = [];
  68. var cache = {};
  69. this.setSize = function ( width, height ) {
  70. canvasWidth = width;
  71. canvasHeight = height;
  72. canvasWidthHalf = Math.floor( canvasWidth / 2 );
  73. canvasHeightHalf = Math.floor( canvasHeight / 2 );
  74. };
  75. //
  76. var spawnRay = ( function () {
  77. var diffuseColor = new THREE.Color();
  78. var specularColor = new THREE.Color();
  79. var lightColor = new THREE.Color();
  80. var schlick = new THREE.Color();
  81. var lightContribution = new THREE.Color();
  82. var eyeVector = new THREE.Vector3();
  83. var lightVector = new THREE.Vector3();
  84. var normalVector = new THREE.Vector3();
  85. var halfVector = new THREE.Vector3();
  86. var localPoint = new THREE.Vector3();
  87. var reflectionVector = new THREE.Vector3();
  88. var tmpVec = new THREE.Vector3();
  89. var tmpColor = [];
  90. for ( var i = 0; i < maxRecursionDepth; i ++ ) {
  91. tmpColor[ i ] = new THREE.Color();
  92. }
  93. return function spawnRay( rayOrigin, rayDirection, outputColor, recursionDepth ) {
  94. outputColor.setRGB( 0, 0, 0 );
  95. //
  96. ray.origin = rayOrigin;
  97. ray.direction = rayDirection;
  98. var intersections = raycaster.intersectObjects( objects, true );
  99. // ray didn't find anything
  100. // (here should come setting of background color?)
  101. if ( intersections.length === 0 ) return;
  102. // ray hit
  103. var intersection = intersections[ 0 ];
  104. var point = intersection.point;
  105. var object = intersection.object;
  106. var material = object.material;
  107. var face = intersection.face;
  108. var vertices = object.geometry.vertices;
  109. //
  110. var _object = cache[ object.id ];
  111. eyeVector.subVectors( ray.origin, point ).normalize();
  112. // resolve pixel diffuse color
  113. if ( material.isMeshLambertMaterial ||
  114. material.isMeshPhongMaterial ||
  115. material.isMeshBasicMaterial ) {
  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.isMeshBasicMaterial ) {
  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.isMeshLambertMaterial || material.isMeshPhongMaterial ) {
  138. var normalComputed = false;
  139. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  140. var light = lights[ i ];
  141. lightVector.setFromMatrixPosition( light.matrixWorld );
  142. lightVector.sub( point );
  143. rayLight.direction.copy( lightVector ).normalize();
  144. var intersections = raycasterLight.intersectObjects( objects, true );
  145. // point in shadow
  146. if ( intersections.length > 0 ) continue;
  147. // point lit
  148. if ( normalComputed === false ) {
  149. // the same normal can be reused for all lights
  150. // (should be possible to cache even more)
  151. localPoint.copy( point ).applyMatrix4( _object.inverseMatrix );
  152. computePixelNormal( normalVector, localPoint, material.flatShading, face, vertices );
  153. normalVector.applyMatrix3( _object.normalMatrix ).normalize();
  154. normalComputed = true;
  155. }
  156. lightColor.copyGammaToLinear( light.color );
  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.isMeshPhongMaterial ) {
  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, flatShading, face, vertices ) {
  230. var faceNormal = face.normal;
  231. var vertexNormals = face.vertexNormals;
  232. if ( flatShading === true ) {
  233. outputVector.copy( faceNormal );
  234. } else {
  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 + 0 ] = 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. sceneId: sceneId,
  287. time: Date.now() - reallyThen, // time for this renderer
  288. }, [ data.buffer ] );
  289. data = new Uint8ClampedArray( blockSize * blockSize * 4 );
  290. // OK Done!
  291. completed ++;
  292. };
  293. }() );
  294. this.render = function ( scene, camera ) {
  295. reallyThen = Date.now()
  296. // update scene graph
  297. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  298. // update camera matrices
  299. if ( camera.parent === null ) camera.updateMatrixWorld();
  300. cameraPosition.setFromMatrixPosition( camera.matrixWorld );
  301. //
  302. cameraNormalMatrix.getNormalMatrix( camera.matrixWorld );
  303. perspective = 0.5 / Math.tan( THREE.Math.degToRad( camera.fov * 0.5 ) ) * canvasHeight;
  304. objects = scene.children;
  305. // collect lights and set up object matrices
  306. lights.length = 0;
  307. scene.traverse( function ( object ) {
  308. if ( object.isPointLight ) {
  309. lights.push( object );
  310. }
  311. if ( cache[ object.id ] === undefined ) {
  312. cache[ object.id ] = {
  313. normalMatrix: new THREE.Matrix3(),
  314. inverseMatrix: new THREE.Matrix4()
  315. };
  316. }
  317. var _object = cache[ object.id ];
  318. _object.normalMatrix.getNormalMatrix( object.matrixWorld );
  319. _object.inverseMatrix.getInverse( object.matrixWorld );
  320. } );
  321. renderBlock( startX, startY );
  322. };
  323. };
  324. Object.assign( THREE.RaytracingRendererWorker.prototype, THREE.EventDispatcher.prototype );