RaytracingWorker.js 12 KB

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