RaytracingRenderer.js 12 KB

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