RaytracingRenderer.js 12 KB

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