WebGLRenderer.js 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513
  1. /**
  2. * @author supereggbert / http://www.paulbrunt.co.uk/
  3. * @author mrdoob / http://mrdoob.com/
  4. * @author alteredq / http://alteredqualia.com/
  5. */
  6. THREE.WebGLRenderer = function ( scene ) {
  7. // Currently you can use just up to 4 directional / point lights total.
  8. // Chrome barfs on shader linking when there are more than 4 lights :(
  9. // The problem comes from shader using too many varying vectors.
  10. // This is not GPU limitation as the same shader works ok in Firefox
  11. // and Chrome with "--use-gl=desktop" flag.
  12. // Difference comes from Chrome on Windows using by default ANGLE,
  13. // thus going DirectX9 route (while FF uses OpenGL).
  14. // See http://code.google.com/p/chromium/issues/detail?id=63491
  15. var _canvas = document.createElement( 'canvas' ), _gl,
  16. _program, _oldProgram,
  17. _modelViewMatrix = new THREE.Matrix4(), _normalMatrix,
  18. _viewMatrixArray = new Float32Array(16),
  19. _modelViewMatrixArray = new Float32Array(16),
  20. _projectionMatrixArray = new Float32Array(16),
  21. _normalMatrixArray = new Float32Array(9),
  22. _objectMatrixArray = new Float32Array(16),
  23. // ubershader material constants
  24. BASIC = 0, LAMBERT = 1, PHONG = 2, DEPTH = 3, NORMAL = 4, CUBE = 5,
  25. // heuristics to create shader parameters according to lights in the scene
  26. // (not to blow over maxLights budget)
  27. maxLightCount = allocateLights( scene, 4 );
  28. this.domElement = _canvas;
  29. this.autoClear = true;
  30. initGL();
  31. initUbershader( maxLightCount.directional, maxLightCount.point );
  32. //alert( dumpObject( getGLParams() ) );
  33. this.setSize = function ( width, height ) {
  34. _canvas.width = width;
  35. _canvas.height = height;
  36. _gl.viewport( 0, 0, _canvas.width, _canvas.height );
  37. };
  38. this.clear = function () {
  39. _gl.clear( _gl.COLOR_BUFFER_BIT | _gl.DEPTH_BUFFER_BIT );
  40. };
  41. this.setupLights = function ( program, scene ) {
  42. var l, ll, light, r, g, b,
  43. ambientLights = [], pointLights = [], directionalLights = [],
  44. colors = [], positions = [];
  45. _gl.uniform1i( program.uniforms.enableLighting, scene.lights.length );
  46. for ( l = 0, ll = scene.lights.length; l < ll; l++ ) {
  47. light = scene.lights[ l ];
  48. if ( light instanceof THREE.AmbientLight ) {
  49. ambientLights.push( light );
  50. } else if ( light instanceof THREE.DirectionalLight ) {
  51. directionalLights.push( light );
  52. } else if( light instanceof THREE.PointLight ) {
  53. pointLights.push( light );
  54. }
  55. }
  56. // sum all ambient lights
  57. r = g = b = 0.0;
  58. for ( l = 0, ll = ambientLights.length; l < ll; l++ ) {
  59. r += ambientLights[ l ].color.r;
  60. g += ambientLights[ l ].color.g;
  61. b += ambientLights[ l ].color.b;
  62. }
  63. _gl.uniform3f( program.uniforms.ambientLightColor, r, g, b );
  64. // pass directional lights as float arrays
  65. colors = []; positions = [];
  66. for ( l = 0, ll = directionalLights.length; l < ll; l++ ) {
  67. light = directionalLights[ l ];
  68. colors.push( light.color.r * light.intensity );
  69. colors.push( light.color.g * light.intensity );
  70. colors.push( light.color.b * light.intensity );
  71. positions.push( light.position.x );
  72. positions.push( light.position.y );
  73. positions.push( light.position.z );
  74. }
  75. if ( directionalLights.length ) {
  76. _gl.uniform1i( program.uniforms.directionalLightNumber, directionalLights.length );
  77. _gl.uniform3fv( program.uniforms.directionalLightDirection, positions );
  78. _gl.uniform3fv( program.uniforms.directionalLightColor, colors );
  79. }
  80. // pass point lights as float arrays
  81. colors = []; positions = [];
  82. for ( l = 0, ll = pointLights.length; l < ll; l++ ) {
  83. light = pointLights[ l ];
  84. colors.push( light.color.r * light.intensity );
  85. colors.push( light.color.g * light.intensity );
  86. colors.push( light.color.b * light.intensity );
  87. positions.push( light.position.x );
  88. positions.push( light.position.y );
  89. positions.push( light.position.z );
  90. }
  91. if ( pointLights.length ) {
  92. _gl.uniform1i( program.uniforms.pointLightNumber, pointLights.length );
  93. _gl.uniform3fv( program.uniforms.pointLightPosition, positions );
  94. _gl.uniform3fv( program.uniforms.pointLightColor, colors );
  95. }
  96. };
  97. this.createBuffers = function ( object, mf ) {
  98. var f, fl, fi, face, vertexNormals, normal, uv, v1, v2, v3, v4, m, ml, i,
  99. faceArray = [],
  100. lineArray = [],
  101. vertexArray = [],
  102. normalArray = [],
  103. uvArray = [],
  104. vertexIndex = 0,
  105. materialFaceGroup = object.materialFaceGroup[ mf ],
  106. needsSmoothNormals = bufferNeedsSmoothNormals ( materialFaceGroup, object );
  107. for ( f = 0, fl = materialFaceGroup.faces.length; f < fl; f++ ) {
  108. fi = materialFaceGroup.faces[f];
  109. face = object.geometry.faces[ fi ];
  110. vertexNormals = face.vertexNormals;
  111. faceNormal = face.normal;
  112. uv = object.geometry.uvs[ fi ];
  113. if ( face instanceof THREE.Face3 ) {
  114. v1 = object.geometry.vertices[ face.a ].position;
  115. v2 = object.geometry.vertices[ face.b ].position;
  116. v3 = object.geometry.vertices[ face.c ].position;
  117. vertexArray.push( v1.x, v1.y, v1.z );
  118. vertexArray.push( v2.x, v2.y, v2.z );
  119. vertexArray.push( v3.x, v3.y, v3.z );
  120. if ( vertexNormals.length == 3 && needsSmoothNormals ) {
  121. for ( i = 0; i < 3; i ++ ) {
  122. normalArray.push( vertexNormals[ i ].x, vertexNormals[ i ].y, vertexNormals[ i ].z );
  123. }
  124. } else {
  125. for ( i = 0; i < 3; i ++ ) {
  126. normalArray.push( faceNormal.x, faceNormal.y, faceNormal.z );
  127. }
  128. }
  129. if ( uv ) {
  130. for ( i = 0; i < 3; i ++ ) {
  131. uvArray.push( uv[ i ].u, uv[ i ].v );
  132. }
  133. }
  134. faceArray.push( vertexIndex, vertexIndex + 1, vertexIndex + 2 );
  135. // TODO: don't add lines that already exist (faces sharing edge)
  136. lineArray.push( vertexIndex, vertexIndex + 1 );
  137. lineArray.push( vertexIndex, vertexIndex + 2 );
  138. lineArray.push( vertexIndex + 1, vertexIndex + 2 );
  139. vertexIndex += 3;
  140. } else if ( face instanceof THREE.Face4 ) {
  141. v1 = object.geometry.vertices[ face.a ].position;
  142. v2 = object.geometry.vertices[ face.b ].position;
  143. v3 = object.geometry.vertices[ face.c ].position;
  144. v4 = object.geometry.vertices[ face.d ].position;
  145. vertexArray.push( v1.x, v1.y, v1.z );
  146. vertexArray.push( v2.x, v2.y, v2.z );
  147. vertexArray.push( v3.x, v3.y, v3.z );
  148. vertexArray.push( v4.x, v4.y, v4.z );
  149. if ( vertexNormals.length == 4 && needsSmoothNormals ) {
  150. for ( i = 0; i < 4; i ++ ) {
  151. normalArray.push( vertexNormals[ i ].x, vertexNormals[ i ].y, vertexNormals[ i ].z );
  152. }
  153. } else {
  154. for ( i = 0; i < 4; i ++ ) {
  155. normalArray.push( faceNormal.x, faceNormal.y, faceNormal.z );
  156. }
  157. }
  158. if ( uv ) {
  159. for ( i = 0; i < 4; i ++ ) {
  160. uvArray.push( uv[ i ].u, uv[ i ].v );
  161. }
  162. }
  163. faceArray.push( vertexIndex, vertexIndex + 1, vertexIndex + 2 );
  164. faceArray.push( vertexIndex, vertexIndex + 2, vertexIndex + 3 );
  165. // TODO: don't add lines that already exist (faces sharing edge)
  166. lineArray.push( vertexIndex, vertexIndex + 1 );
  167. lineArray.push( vertexIndex, vertexIndex + 2 );
  168. lineArray.push( vertexIndex, vertexIndex + 3 );
  169. lineArray.push( vertexIndex + 1, vertexIndex + 2 );
  170. lineArray.push( vertexIndex + 2, vertexIndex + 3 );
  171. vertexIndex += 4;
  172. }
  173. }
  174. if ( !vertexArray.length ) {
  175. return;
  176. }
  177. materialFaceGroup.__webGLVertexBuffer = _gl.createBuffer();
  178. _gl.bindBuffer( _gl.ARRAY_BUFFER, materialFaceGroup.__webGLVertexBuffer );
  179. _gl.bufferData( _gl.ARRAY_BUFFER, new Float32Array( vertexArray ), _gl.STATIC_DRAW );
  180. materialFaceGroup.__webGLNormalBuffer = _gl.createBuffer();
  181. _gl.bindBuffer( _gl.ARRAY_BUFFER, materialFaceGroup.__webGLNormalBuffer );
  182. _gl.bufferData( _gl.ARRAY_BUFFER, new Float32Array( normalArray ), _gl.STATIC_DRAW );
  183. materialFaceGroup.__webGLUVBuffer = _gl.createBuffer();
  184. _gl.bindBuffer( _gl.ARRAY_BUFFER, materialFaceGroup.__webGLUVBuffer );
  185. _gl.bufferData( _gl.ARRAY_BUFFER, new Float32Array( uvArray ), _gl.STATIC_DRAW );
  186. materialFaceGroup.__webGLFaceBuffer = _gl.createBuffer();
  187. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, materialFaceGroup.__webGLFaceBuffer );
  188. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( faceArray ), _gl.STATIC_DRAW );
  189. materialFaceGroup.__webGLLineBuffer = _gl.createBuffer();
  190. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, materialFaceGroup.__webGLLineBuffer );
  191. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( lineArray ), _gl.STATIC_DRAW );
  192. materialFaceGroup.__webGLFaceCount = faceArray.length;
  193. materialFaceGroup.__webGLLineCount = lineArray.length;
  194. };
  195. this.renderBuffer = function ( camera, material, materialFaceGroup ) {
  196. var mColor, mOpacity, mReflectivity,
  197. mWireframe, mLineWidth, mBlending,
  198. mAmbient, mSpecular, mShininess,
  199. mMap, envMap, mixEnvMap,
  200. mRefractionRatio, useRefract,
  201. program, u, identifiers;
  202. if ( material instanceof THREE.MeshShaderMaterial ) {
  203. if ( !material.program ) {
  204. material.program = buildProgram( material.fragment_shader, material.vertex_shader );
  205. identifiers = [ 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'objectMatrix', 'cameraPosition' ];
  206. for( u in material.uniforms ) identifiers.push(u);
  207. cacheUniformLocations( material.program, identifiers );
  208. cacheAttributeLocations( material.program );
  209. }
  210. program = material.program;
  211. } else {
  212. program = _program;
  213. }
  214. if( program != _oldProgram ) {
  215. _gl.useProgram( program );
  216. _oldProgram = program;
  217. }
  218. if ( material instanceof THREE.MeshShaderMaterial ) {
  219. setUniforms( program, material.uniforms );
  220. this.loadCamera( program, camera );
  221. this.loadMatrices( program );
  222. } else if ( material instanceof THREE.MeshPhongMaterial ||
  223. material instanceof THREE.MeshLambertMaterial ||
  224. material instanceof THREE.MeshBasicMaterial ) {
  225. mColor = material.color;
  226. mOpacity = material.opacity;
  227. mWireframe = material.wireframe;
  228. mLineWidth = material.wireframe_linewidth;
  229. mBlending = material.blending;
  230. mMap = material.map;
  231. envMap = material.env_map;
  232. mixEnvMap = material.combine == THREE.Mix;
  233. mReflectivity = material.reflectivity;
  234. useRefract = material.env_map && material.env_map.mapping == THREE.RefractionMapping;
  235. mRefractionRatio = material.refraction_ratio;
  236. _gl.uniform4f( program.uniforms.mColor, mColor.r * mOpacity, mColor.g * mOpacity, mColor.b * mOpacity, mOpacity );
  237. _gl.uniform1i( program.uniforms.mixEnvMap, mixEnvMap );
  238. _gl.uniform1f( program.uniforms.mReflectivity, mReflectivity );
  239. _gl.uniform1i( program.uniforms.useRefract, useRefract );
  240. _gl.uniform1f( program.uniforms.mRefractionRatio, mRefractionRatio );
  241. }
  242. if ( material instanceof THREE.MeshNormalMaterial ) {
  243. mOpacity = material.opacity;
  244. mBlending = material.blending;
  245. _gl.uniform1f( program.uniforms.mOpacity, mOpacity );
  246. _gl.uniform1i( program.uniforms.material, NORMAL );
  247. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  248. mOpacity = material.opacity;
  249. mWireframe = material.wireframe;
  250. mLineWidth = material.wireframe_linewidth;
  251. _gl.uniform1f( program.uniforms.mOpacity, mOpacity );
  252. _gl.uniform1f( program.uniforms.m2Near, material.__2near );
  253. _gl.uniform1f( program.uniforms.mFarPlusNear, material.__farPlusNear );
  254. _gl.uniform1f( program.uniforms.mFarMinusNear, material.__farMinusNear );
  255. _gl.uniform1i( program.uniforms.material, DEPTH );
  256. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  257. mAmbient = material.ambient;
  258. mSpecular = material.specular;
  259. mShininess = material.shininess;
  260. _gl.uniform4f( program.uniforms.mAmbient, mAmbient.r, mAmbient.g, mAmbient.b, mOpacity );
  261. _gl.uniform4f( program.uniforms.mSpecular, mSpecular.r, mSpecular.g, mSpecular.b, mOpacity );
  262. _gl.uniform1f( program.uniforms.mShininess, mShininess );
  263. _gl.uniform1i( program.uniforms.material, PHONG );
  264. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  265. _gl.uniform1i( program.uniforms.material, LAMBERT );
  266. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  267. _gl.uniform1i( program.uniforms.material, BASIC );
  268. } else if ( material instanceof THREE.MeshCubeMaterial ) {
  269. _gl.uniform1i( program.uniforms.material, CUBE );
  270. envMap = material.env_map;
  271. }
  272. if ( mMap ) {
  273. setTexture( mMap, 0 );
  274. _gl.uniform1i( program.uniforms.tMap, 0 );
  275. _gl.uniform1i( program.uniforms.enableMap, 1 );
  276. } else {
  277. _gl.uniform1i( program.uniforms.enableMap, 0 );
  278. }
  279. if ( envMap ) {
  280. setCubeTexture( envMap, 1 );
  281. _gl.uniform1i( program.uniforms.tCube, 1 );
  282. _gl.uniform1i( program.uniforms.enableCubeMap, 1 );
  283. } else {
  284. _gl.uniform1i( program.uniforms.enableCubeMap, 0 );
  285. }
  286. // vertices
  287. _gl.bindBuffer( _gl.ARRAY_BUFFER, materialFaceGroup.__webGLVertexBuffer );
  288. _gl.vertexAttribPointer( program.position, 3, _gl.FLOAT, false, 0, 0 );
  289. // normals
  290. _gl.bindBuffer( _gl.ARRAY_BUFFER, materialFaceGroup.__webGLNormalBuffer );
  291. _gl.vertexAttribPointer( program.normal, 3, _gl.FLOAT, false, 0, 0 );
  292. // uvs
  293. if ( mMap ) {
  294. _gl.bindBuffer( _gl.ARRAY_BUFFER, materialFaceGroup.__webGLUVBuffer );
  295. _gl.enableVertexAttribArray( program.uv );
  296. _gl.vertexAttribPointer( program.uv, 2, _gl.FLOAT, false, 0, 0 );
  297. } else {
  298. _gl.disableVertexAttribArray( program.uv );
  299. }
  300. // render triangles
  301. if ( ! mWireframe ) {
  302. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, materialFaceGroup.__webGLFaceBuffer );
  303. _gl.drawElements( _gl.TRIANGLES, materialFaceGroup.__webGLFaceCount, _gl.UNSIGNED_SHORT, 0 );
  304. // render lines
  305. } else {
  306. _gl.lineWidth( mLineWidth );
  307. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, materialFaceGroup.__webGLLineBuffer );
  308. _gl.drawElements( _gl.LINES, materialFaceGroup.__webGLLineCount, _gl.UNSIGNED_SHORT, 0 );
  309. }
  310. };
  311. this.renderPass = function ( camera, object, materialFaceGroup, blending, transparent ) {
  312. var i, l, m, ml, material, meshMaterial;
  313. for ( m = 0, ml = object.material.length; m < ml; m++ ) {
  314. meshMaterial = object.material[ m ];
  315. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  316. for ( i = 0, l = materialFaceGroup.material.length; i < l; i++ ) {
  317. material = materialFaceGroup.material[ i ];
  318. if ( material && material.blending == blending && ( material.opacity < 1.0 == transparent ) ) {
  319. this.setBlending( material.blending );
  320. this.renderBuffer( camera, material, materialFaceGroup );
  321. }
  322. }
  323. } else {
  324. material = meshMaterial;
  325. if ( material && material.blending == blending && ( material.opacity < 1.0 == transparent ) ) {
  326. this.setBlending( material.blending );
  327. this.renderBuffer( camera, material, materialFaceGroup );
  328. }
  329. }
  330. }
  331. };
  332. this.render = function( scene, camera ) {
  333. var o, ol;
  334. this.initWebGLObjects( scene );
  335. if ( this.autoClear ) {
  336. this.clear();
  337. }
  338. camera.autoUpdateMatrix && camera.updateMatrix();
  339. this.loadCamera( _program, camera );
  340. this.setupLights( _program, scene );
  341. // opaque pass
  342. for ( o = 0, ol = scene.__webGLObjects.length; o < ol; o++ ) {
  343. webGLObject = scene.__webGLObjects[ o ];
  344. if ( webGLObject.__object.visible ) {
  345. this.setupMatrices( webGLObject.__object, camera );
  346. this.loadMatrices( _program );
  347. this.renderPass( camera, webGLObject.__object, webGLObject, THREE.NormalBlending, false );
  348. }
  349. }
  350. // transparent pass
  351. for ( o = 0, ol = scene.__webGLObjects.length; o < ol; o++ ) {
  352. webGLObject = scene.__webGLObjects[ o ];
  353. if ( webGLObject.__object.visible ) {
  354. this.setupMatrices( webGLObject.__object, camera );
  355. this.loadMatrices( _program );
  356. // opaque blended materials
  357. this.renderPass( camera, webGLObject.__object, webGLObject, THREE.AdditiveBlending, false );
  358. this.renderPass( camera, webGLObject.__object, webGLObject, THREE.SubtractiveBlending, false );
  359. // transparent blended materials
  360. this.renderPass( camera, webGLObject.__object, webGLObject, THREE.AdditiveBlending, true );
  361. this.renderPass( camera, webGLObject.__object, webGLObject, THREE.SubtractiveBlending, true );
  362. // transparent normal materials
  363. this.renderPass( camera, webGLObject.__object, webGLObject, THREE.NormalBlending, true );
  364. }
  365. }
  366. };
  367. this.initWebGLObjects = function( scene ) {
  368. var o, ol, object, mf, materialFaceGroup;
  369. if ( !scene.__webGLObjects ) {
  370. scene.__webGLObjects = [];
  371. }
  372. for ( o = 0, ol = scene.objects.length; o < ol; o++ ) {
  373. object = scene.objects[ o ];
  374. if ( object instanceof THREE.Mesh ) {
  375. // create separate VBOs per material
  376. for ( mf in object.materialFaceGroup ) {
  377. materialFaceGroup = object.materialFaceGroup[ mf ];
  378. // initialise buffers on the first access
  379. if( ! materialFaceGroup.__webGLVertexBuffer ) {
  380. this.createBuffers( object, mf );
  381. materialFaceGroup.__object = object;
  382. scene.__webGLObjects.push( materialFaceGroup );
  383. }
  384. }
  385. }/* else if ( object instanceof THREE.Line ) {
  386. } else if ( object instanceof THREE.Particle ) {
  387. }*/
  388. }
  389. };
  390. this.removeObject = function ( scene, object ) {
  391. var o, ol, zobject;
  392. for ( o = scene.__webGLObjects.length - 1; o >= 0; o-- ) {
  393. zobject = scene.__webGLObjects[ o ].__object;
  394. if ( object == zobject ) {
  395. scene.__webGLObjects.splice( o, 1 );
  396. }
  397. }
  398. };
  399. this.setupMatrices = function ( object, camera ) {
  400. object.autoUpdateMatrix && object.updateMatrix();
  401. _modelViewMatrix.multiply( camera.matrix, object.matrix );
  402. _viewMatrixArray.set( camera.matrix.flatten() );
  403. _modelViewMatrixArray.set( _modelViewMatrix.flatten() );
  404. _projectionMatrixArray.set( camera.projectionMatrix.flatten() );
  405. _normalMatrix = THREE.Matrix4.makeInvert3x3( _modelViewMatrix ).transpose();
  406. _normalMatrixArray.set( _normalMatrix.m );
  407. _objectMatrixArray.set( object.matrix.flatten() );
  408. };
  409. this.loadMatrices = function ( program ) {
  410. _gl.uniformMatrix4fv( program.uniforms.viewMatrix, false, _viewMatrixArray );
  411. _gl.uniformMatrix4fv( program.uniforms.modelViewMatrix, false, _modelViewMatrixArray );
  412. _gl.uniformMatrix4fv( program.uniforms.projectionMatrix, false, _projectionMatrixArray );
  413. _gl.uniformMatrix3fv( program.uniforms.normalMatrix, false, _normalMatrixArray );
  414. _gl.uniformMatrix4fv( program.uniforms.objectMatrix, false, _objectMatrixArray );
  415. };
  416. this.loadCamera = function( program, camera ) {
  417. _gl.uniform3f( program.uniforms.cameraPosition, camera.position.x, camera.position.y, camera.position.z );
  418. };
  419. this.setBlending = function( blending ) {
  420. switch ( blending ) {
  421. case THREE.AdditiveBlending:
  422. _gl.blendEquation( _gl.FUNC_ADD );
  423. _gl.blendFunc( _gl.ONE, _gl.ONE );
  424. break;
  425. case THREE.SubtractiveBlending:
  426. //_gl.blendEquation( _gl.FUNC_SUBTRACT );
  427. _gl.blendFunc( _gl.DST_COLOR, _gl.ZERO );
  428. break;
  429. default:
  430. _gl.blendEquation( _gl.FUNC_ADD );
  431. _gl.blendFunc( _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  432. break;
  433. }
  434. };
  435. this.setFaceCulling = function ( cullFace, frontFace ) {
  436. if ( cullFace ) {
  437. if ( !frontFace || frontFace == "ccw" ) {
  438. _gl.frontFace( _gl.CCW );
  439. } else {
  440. _gl.frontFace( _gl.CW );
  441. }
  442. if( cullFace == "back" ) {
  443. _gl.cullFace( _gl.BACK );
  444. } else if( cullFace == "front" ) {
  445. _gl.cullFace( _gl.FRONT );
  446. } else {
  447. _gl.cullFace( _gl.FRONT_AND_BACK );
  448. }
  449. _gl.enable( _gl.CULL_FACE );
  450. } else {
  451. _gl.disable( _gl.CULL_FACE );
  452. }
  453. };
  454. function initGL() {
  455. try {
  456. _gl = _canvas.getContext( 'experimental-webgl', { antialias: true} );
  457. } catch(e) { }
  458. if (!_gl) {
  459. alert("WebGL not supported");
  460. throw "cannot create webgl context";
  461. }
  462. _gl.clearColor( 0, 0, 0, 1 );
  463. _gl.clearDepth( 1 );
  464. _gl.enable( _gl.DEPTH_TEST );
  465. _gl.depthFunc( _gl.LEQUAL );
  466. _gl.frontFace( _gl.CCW );
  467. _gl.cullFace( _gl.BACK );
  468. _gl.enable( _gl.CULL_FACE );
  469. _gl.enable( _gl.BLEND );
  470. //_gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  471. //_gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE ); // cool!
  472. _gl.blendFunc( _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  473. _gl.clearColor( 0, 0, 0, 0 );
  474. };
  475. function generateFragmentShader( maxDirLights, maxPointLights ) {
  476. var chunks = [
  477. maxDirLights ? "#define MAX_DIR_LIGHTS " + maxDirLights : "",
  478. maxPointLights ? "#define MAX_POINT_LIGHTS " + maxPointLights : "",
  479. "uniform int material;", // 0 - Basic, 1 - Lambert, 2 - Phong, 3 - Depth, 4 - Normal, 5 - Cube
  480. "uniform bool enableMap;",
  481. "uniform bool enableCubeMap;",
  482. "uniform bool mixEnvMap;",
  483. "uniform samplerCube tCube;",
  484. "uniform float mReflectivity;",
  485. "uniform sampler2D tMap;",
  486. "uniform vec4 mColor;",
  487. "uniform float mOpacity;",
  488. "uniform vec4 mAmbient;",
  489. "uniform vec4 mSpecular;",
  490. "uniform float mShininess;",
  491. "uniform float m2Near;",
  492. "uniform float mFarPlusNear;",
  493. "uniform float mFarMinusNear;",
  494. "uniform int pointLightNumber;",
  495. "uniform int directionalLightNumber;",
  496. maxDirLights ? "uniform mat4 viewMatrix;" : "",
  497. maxDirLights ? "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];" : "",
  498. "varying vec3 vNormal;",
  499. "varying vec2 vUv;",
  500. "varying vec3 vLightWeighting;",
  501. maxPointLights ? "varying vec3 vPointLightVector[ MAX_POINT_LIGHTS ];" : "",
  502. "varying vec3 vViewPosition;",
  503. "varying vec3 vReflect;",
  504. "uniform vec3 cameraPosition;",
  505. "void main() {",
  506. "vec4 mapColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
  507. "vec4 cubeColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
  508. // diffuse map
  509. "if ( enableMap ) {",
  510. "mapColor = texture2D( tMap, vUv );",
  511. "}",
  512. // cube map
  513. "if ( enableCubeMap ) {",
  514. "cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  515. // "cubeColor.r = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) ).r;",
  516. // "cubeColor.g = textureCube( tCube, vec3( -vReflect.x + 0.005, vReflect.yz ) ).g;",
  517. // "cubeColor.b = textureCube( tCube, vec3( -vReflect.x + 0.01, vReflect.yz ) ).b;",
  518. "}",
  519. // Cube
  520. "if ( material == 5 ) { ",
  521. "vec3 wPos = cameraPosition - vViewPosition;",
  522. "gl_FragColor = textureCube( tCube, vec3( -wPos.x, wPos.yz ) );",
  523. // Normals
  524. "} else if ( material == 4 ) { ",
  525. "gl_FragColor = vec4( 0.5*normalize( vNormal ) + vec3(0.5, 0.5, 0.5), mOpacity );",
  526. // Depth
  527. "} else if ( material == 3 ) { ",
  528. // this breaks shader validation in Chrome 9.0.576.0 dev
  529. // and also latest continuous build Chromium 9.0.583.0 (66089)
  530. // (curiously it works in Chrome 9.0.576.0 canary build and Firefox 4b7)
  531. //"float w = 1.0 - ( m2Near / ( mFarPlusNear - gl_FragCoord.z * mFarMinusNear ) );",
  532. "float w = 0.5;",
  533. "gl_FragColor = vec4( w, w, w, mOpacity );",
  534. // Blinn-Phong
  535. // based on o3d example
  536. "} else if ( material == 2 ) { ",
  537. "vec3 normal = normalize( vNormal );",
  538. "vec3 viewPosition = normalize( vViewPosition );",
  539. // point lights
  540. maxPointLights ? "vec4 pointDiffuse = vec4( 0.0, 0.0, 0.0, 0.0 );" : "",
  541. maxPointLights ? "vec4 pointSpecular = vec4( 0.0, 0.0, 0.0, 0.0 );" : "",
  542. maxPointLights ? "for( int i = 0; i < MAX_POINT_LIGHTS; i++ ) {" : "",
  543. maxPointLights ? "vec3 pointVector = normalize( vPointLightVector[ i ] );" : "",
  544. maxPointLights ? "vec3 pointHalfVector = normalize( vPointLightVector[ i ] + vViewPosition );" : "",
  545. maxPointLights ? "float pointDotNormalHalf = dot( normal, pointHalfVector );" : "",
  546. maxPointLights ? "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );" : "",
  547. // Ternary conditional is from the original o3d shader. Here it produces abrupt dark cutoff artefacts.
  548. // Using just pow works ok in Chrome, but makes different artefact in Firefox 4.
  549. // Zeroing on negative pointDotNormalHalf seems to work in both.
  550. //"float specularCompPoint = dot( normal, pointVector ) < 0.0 || pointDotNormalHalf < 0.0 ? 0.0 : pow( pointDotNormalHalf, mShininess );",
  551. //"float specularCompPoint = pow( pointDotNormalHalf, mShininess );",
  552. //"float pointSpecularWeight = pointDotNormalHalf < 0.0 ? 0.0 : pow( pointDotNormalHalf, mShininess );",
  553. // Ternary conditional inside for loop breaks Chrome shader linking.
  554. // Must do it with if.
  555. maxPointLights ? "float pointSpecularWeight = 0.0;" : "",
  556. maxPointLights ? "if ( pointDotNormalHalf >= 0.0 )" : "",
  557. maxPointLights ? "pointSpecularWeight = pow( pointDotNormalHalf, mShininess );" : "",
  558. maxPointLights ? "pointDiffuse += mColor * pointDiffuseWeight;" : "",
  559. maxPointLights ? "pointSpecular += mSpecular * pointSpecularWeight;" : "",
  560. maxPointLights ? "}" : "",
  561. // directional lights
  562. maxDirLights ? "vec4 dirDiffuse = vec4( 0.0, 0.0, 0.0, 0.0 );" : "",
  563. maxDirLights ? "vec4 dirSpecular = vec4( 0.0, 0.0, 0.0, 0.0 );" : "",
  564. maxDirLights ? "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {" : "",
  565. maxDirLights ? "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );" : "",
  566. maxDirLights ? "vec3 dirVector = normalize( lDirection.xyz );" : "",
  567. maxDirLights ? "vec3 dirHalfVector = normalize( lDirection.xyz + vViewPosition );" : "",
  568. maxDirLights ? "float dirDotNormalHalf = dot( normal, dirHalfVector );" : "",
  569. maxDirLights ? "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );" : "",
  570. maxDirLights ? "float dirSpecularWeight = 0.0;" : "",
  571. maxDirLights ? "if ( dirDotNormalHalf >= 0.0 )" : "",
  572. maxDirLights ? "dirSpecularWeight = pow( dirDotNormalHalf, mShininess );" : "",
  573. maxDirLights ? "dirDiffuse += mColor * dirDiffuseWeight;" : "",
  574. maxDirLights ? "dirSpecular += mSpecular * dirSpecularWeight;" : "",
  575. maxDirLights ? "}" : "",
  576. // all lights contribution summation
  577. "vec4 totalLight = mAmbient;",
  578. maxDirLights ? "totalLight += dirDiffuse + dirSpecular;" : "",
  579. maxPointLights ? "totalLight += pointDiffuse + pointSpecular;" : "",
  580. // looks nicer with weighting
  581. "if ( mixEnvMap ) {",
  582. "gl_FragColor = vec4( mix( mapColor.rgb * totalLight.xyz * vLightWeighting, cubeColor.rgb, mReflectivity ), mapColor.a );",
  583. "} else {",
  584. "gl_FragColor = vec4( mapColor.rgb * cubeColor.rgb * totalLight.xyz * vLightWeighting, mapColor.a );",
  585. "}",
  586. // Lambert: diffuse lighting
  587. "} else if ( material == 1 ) {",
  588. "if ( mixEnvMap ) {",
  589. "gl_FragColor = vec4( mix( mColor.rgb * mapColor.rgb * vLightWeighting, cubeColor.rgb, mReflectivity ), mColor.a * mapColor.a );",
  590. "} else {",
  591. "gl_FragColor = vec4( mColor.rgb * mapColor.rgb * cubeColor.rgb * vLightWeighting, mColor.a * mapColor.a );",
  592. "}",
  593. // Basic: unlit color / texture
  594. "} else {",
  595. "if ( mixEnvMap ) {",
  596. "gl_FragColor = mix( mColor * mapColor, cubeColor, mReflectivity );",
  597. "} else {",
  598. "gl_FragColor = mColor * mapColor * cubeColor;",
  599. "}",
  600. "}",
  601. "}" ];
  602. return chunks.join("\n");
  603. };
  604. function generateVertexShader( maxDirLights, maxPointLights ) {
  605. var chunks = [
  606. maxDirLights ? "#define MAX_DIR_LIGHTS " + maxDirLights : "",
  607. maxPointLights ? "#define MAX_POINT_LIGHTS " + maxPointLights : "",
  608. "uniform bool enableLighting;",
  609. "uniform bool useRefract;",
  610. "uniform int pointLightNumber;",
  611. "uniform int directionalLightNumber;",
  612. "uniform vec3 ambientLightColor;",
  613. maxDirLights ? "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];" : "",
  614. maxDirLights ? "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];" : "",
  615. maxPointLights ? "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];" : "",
  616. maxPointLights ? "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];" : "",
  617. "uniform mat4 viewMatrix;",
  618. "uniform mat3 normalMatrix;",
  619. "varying vec3 vNormal;",
  620. "varying vec2 vUv;",
  621. "varying vec3 vLightWeighting;",
  622. maxPointLights ? "varying vec3 vPointLightVector[ MAX_POINT_LIGHTS ];" : "",
  623. "varying vec3 vViewPosition;",
  624. "varying vec3 vReflect;",
  625. "uniform float mRefractionRatio;",
  626. "void main(void) {",
  627. // world space
  628. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  629. "vViewPosition = cameraPosition - mPosition.xyz;",
  630. // this doesn't work on Mac
  631. //"vec3 nWorld = mat3(objectMatrix) * normal;",
  632. "vec3 nWorld = mat3( objectMatrix[0].xyz, objectMatrix[1].xyz, objectMatrix[2].xyz ) * normal;",
  633. // eye space
  634. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  635. "vec3 transformedNormal = normalize( normalMatrix * normal );",
  636. "if ( !enableLighting ) {",
  637. "vLightWeighting = vec3( 1.0, 1.0, 1.0 );",
  638. "} else {",
  639. "vLightWeighting = ambientLightColor;",
  640. // directional lights
  641. maxDirLights ? "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {" : "",
  642. maxDirLights ? "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );" : "",
  643. maxDirLights ? "float directionalLightWeighting = max( dot( transformedNormal, normalize(lDirection.xyz ) ), 0.0 );" : "",
  644. maxDirLights ? "vLightWeighting += directionalLightColor[ i ] * directionalLightWeighting;" : "",
  645. maxDirLights ? "}" : "",
  646. // point lights
  647. maxPointLights ? "for( int i = 0; i < MAX_POINT_LIGHTS; i++ ) {" : "",
  648. maxPointLights ? "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );" : "",
  649. maxPointLights ? "vPointLightVector[ i ] = normalize( lPosition.xyz - mvPosition.xyz );" : "",
  650. maxPointLights ? "float pointLightWeighting = max( dot( transformedNormal, vPointLightVector[ i ] ), 0.0 );" : "",
  651. maxPointLights ? "vLightWeighting += pointLightColor[ i ] * pointLightWeighting;" : "",
  652. maxPointLights ? "}" : "",
  653. "}",
  654. "vNormal = transformedNormal;",
  655. "vUv = uv;",
  656. "if ( useRefract ) {",
  657. "vReflect = refract( normalize(mPosition.xyz - cameraPosition), normalize(nWorld.xyz), mRefractionRatio );",
  658. "} else {",
  659. "vReflect = reflect( normalize(mPosition.xyz - cameraPosition), normalize(nWorld.xyz) );",
  660. "}",
  661. "gl_Position = projectionMatrix * mvPosition;",
  662. "}" ];
  663. return chunks.join("\n");
  664. };
  665. function buildProgram( fragment_shader, vertex_shader ) {
  666. var program = _gl.createProgram(),
  667. prefix_fragment = [
  668. "#ifdef GL_ES",
  669. "precision highp float;",
  670. "#endif",
  671. ""
  672. ].join("\n"),
  673. prefix_vertex = [
  674. "uniform mat4 objectMatrix;",
  675. "uniform mat4 modelViewMatrix;",
  676. "uniform mat4 projectionMatrix;",
  677. "uniform vec3 cameraPosition;",
  678. "attribute vec3 position;",
  679. "attribute vec3 normal;",
  680. "attribute vec2 uv;",
  681. ""
  682. ].join("\n");
  683. _gl.attachShader( program, getShader( "fragment", prefix_fragment + fragment_shader ) );
  684. _gl.attachShader( program, getShader( "vertex", prefix_vertex + vertex_shader ) );
  685. _gl.linkProgram( program );
  686. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  687. alert( "Could not initialise shaders\n"+
  688. "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  689. }
  690. program.uniforms = {};
  691. return program;
  692. };
  693. function setUniforms( program, uniforms ) {
  694. var u, value, type, location, texture;
  695. for( u in uniforms ) {
  696. type = uniforms[u].type;
  697. value = uniforms[u].value;
  698. location = program.uniforms[u];
  699. if( type == "i" ) {
  700. _gl.uniform1i( location, value );
  701. } else if( type == "f" ) {
  702. _gl.uniform1f( location, value );
  703. } else if( type == "t" ) {
  704. _gl.uniform1i( location, value );
  705. texture = uniforms[u].texture;
  706. if ( texture instanceof THREE.TextureCube ) {
  707. setCubeTexture( texture, value );
  708. } else if ( texture instanceof THREE.Texture ) {
  709. setTexture( texture, value );
  710. }
  711. }
  712. }
  713. };
  714. function setCubeTexture( texture, slot ) {
  715. if ( texture instanceof THREE.TextureCube &&
  716. texture.image.length == 6 ) {
  717. if ( !texture.image.__webGLTextureCube &&
  718. !texture.image.__cubeMapInitialized && texture.image.loadCount == 6 ) {
  719. texture.image.__webGLTextureCube = _gl.createTexture();
  720. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webGLTextureCube );
  721. _gl.texParameteri( _gl.TEXTURE_CUBE_MAP, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  722. _gl.texParameteri( _gl.TEXTURE_CUBE_MAP, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  723. _gl.texParameteri( _gl.TEXTURE_CUBE_MAP, _gl.TEXTURE_MAG_FILTER, _gl.LINEAR );
  724. _gl.texParameteri( _gl.TEXTURE_CUBE_MAP, _gl.TEXTURE_MIN_FILTER, _gl.LINEAR_MIPMAP_LINEAR );
  725. for ( var i = 0; i < 6; ++i ) {
  726. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, _gl.RGBA, _gl.RGBA, _gl.UNSIGNED_BYTE, texture.image[ i ] );
  727. }
  728. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  729. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  730. texture.image.__cubeMapInitialized = true;
  731. }
  732. _gl.activeTexture( _gl.TEXTURE0 + slot );
  733. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webGLTextureCube );
  734. }
  735. };
  736. function setTexture( texture, slot ) {
  737. if ( !texture.__webGLTexture && texture.image.loaded ) {
  738. texture.__webGLTexture = _gl.createTexture();
  739. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webGLTexture );
  740. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, _gl.RGBA, _gl.UNSIGNED_BYTE, texture.image );
  741. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrap_s ) );
  742. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrap_t ) );
  743. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.LINEAR );
  744. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.LINEAR_MIPMAP_LINEAR );
  745. _gl.generateMipmap( _gl.TEXTURE_2D );
  746. _gl.bindTexture( _gl.TEXTURE_2D, null );
  747. }
  748. _gl.activeTexture( _gl.TEXTURE0 + slot );
  749. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webGLTexture );
  750. };
  751. function cacheUniformLocations( program, identifiers ) {
  752. var i, l, id;
  753. for( i = 0, l = identifiers.length; i < l; i++ ) {
  754. id = identifiers[i];
  755. program.uniforms[id] = _gl.getUniformLocation( program, id );
  756. }
  757. };
  758. function cacheAttributeLocations( program ) {
  759. program.position = _gl.getAttribLocation( program, "position" );
  760. _gl.enableVertexAttribArray( program.position );
  761. program.normal = _gl.getAttribLocation( program, "normal" );
  762. _gl.enableVertexAttribArray( program.normal );
  763. program.uv = _gl.getAttribLocation( program, "uv" );
  764. _gl.enableVertexAttribArray( program.uv );
  765. };
  766. function initUbershader( maxDirLights, maxPointLights ) {
  767. var vertex_shader = generateVertexShader( maxDirLights, maxPointLights ),
  768. fragment_shader = generateFragmentShader( maxDirLights, maxPointLights );
  769. //log ( vertex_shader );
  770. //log ( fragment_shader );
  771. _program = buildProgram( fragment_shader, vertex_shader );
  772. _gl.useProgram( _program );
  773. // matrices
  774. // lights
  775. // material properties (Basic / Lambert / Blinn-Phong shader)
  776. // material properties (Depth)
  777. cacheUniformLocations( _program, [ 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'objectMatrix', 'cameraPosition',
  778. 'enableLighting', 'ambientLightColor',
  779. 'material', 'mColor', 'mAmbient', 'mSpecular', 'mShininess', 'mOpacity',
  780. 'enableMap', 'tMap',
  781. 'enableCubeMap', 'tCube', 'mixEnvMap', 'mReflectivity',
  782. 'mRefractionRatio', 'useRefract',
  783. 'm2Near', 'mFarPlusNear', 'mFarMinusNear'
  784. ] );
  785. if ( maxDirLights ) {
  786. cacheUniformLocations( _program, [ 'directionalLightNumber', 'directionalLightColor', 'directionalLightDirection' ] );
  787. }
  788. if ( maxPointLights ) {
  789. cacheUniformLocations( _program, [ 'pointLightNumber', 'pointLightColor', 'pointLightPosition' ] );
  790. }
  791. // texture (diffuse map)
  792. _gl.uniform1i( _program.uniforms.enableMap, 0 );
  793. _gl.uniform1i( _program.uniforms.tMap, 0 );
  794. // cube texture
  795. _gl.uniform1i( _program.uniforms.enableCubeMap, 0 );
  796. _gl.uniform1i( _program.uniforms.tCube, 1 ); // it's important to use non-zero texture unit, otherwise it doesn't work
  797. _gl.uniform1i( _program.uniforms.mixEnvMap, 0 );
  798. // refraction
  799. _gl.uniform1i( _program.uniforms.useRefract, 0 );
  800. // vertex arrays
  801. cacheAttributeLocations( _program );
  802. };
  803. function getShader( type, string ) {
  804. var shader;
  805. if ( type == "fragment" ) {
  806. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  807. } else if ( type == "vertex" ) {
  808. shader = _gl.createShader( _gl.VERTEX_SHADER );
  809. }
  810. _gl.shaderSource( shader, string );
  811. _gl.compileShader( shader );
  812. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  813. alert( _gl.getShaderInfoLog( shader ) );
  814. return null;
  815. }
  816. return shader;
  817. };
  818. function paramThreeToGL( p ) {
  819. switch ( p ) {
  820. case THREE.Repeat: return _gl.REPEAT; break;
  821. case THREE.ClampToEdge: return _gl.CLAMP_TO_EDGE; break;
  822. case THREE.MirroredRepeat: return _gl.MIRRORED_REPEAT; break;
  823. }
  824. return 0;
  825. };
  826. function materialNeedsSmoothNormals( material ) {
  827. return material && material.shading != undefined && material.shading == THREE.SmoothShading;
  828. };
  829. function bufferNeedsSmoothNormals( materialFaceGroup, object ) {
  830. var m, ml, i, l, needsSmoothNormals = false;
  831. for ( m = 0, ml = object.material.length; m < ml; m++ ) {
  832. meshMaterial = object.material[ m ];
  833. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  834. for ( i = 0, l = materialFaceGroup.material.length; i < l; i++ ) {
  835. if ( materialNeedsSmoothNormals( materialFaceGroup.material[ i ] ) ) {
  836. needsSmoothNormals = true;
  837. break;
  838. }
  839. }
  840. } else {
  841. if ( materialNeedsSmoothNormals( meshMaterial ) ) {
  842. needsSmoothNormals = true;
  843. break;
  844. }
  845. }
  846. if ( needsSmoothNormals ) break;
  847. }
  848. return needsSmoothNormals;
  849. };
  850. function allocateLights( scene, maxLights ) {
  851. if ( scene ) {
  852. var l, ll, light, dirLights = pointLights = maxDirLights = maxPointLights = 0;
  853. for ( l = 0, ll = scene.lights.length; l < ll; l++ ) {
  854. light = scene.lights[ l ];
  855. if ( light instanceof THREE.DirectionalLight ) dirLights++;
  856. if ( light instanceof THREE.PointLight ) pointLights++;
  857. }
  858. if ( ( pointLights + dirLights ) <= maxLights ) {
  859. maxDirLights = dirLights;
  860. maxPointLights = pointLights;
  861. } else {
  862. maxDirLights = Math.ceil( maxLights * dirLights / ( pointLights + dirLights ) );
  863. maxPointLights = maxLights - maxDirLights;
  864. }
  865. return { 'directional' : maxDirLights, 'point' : maxPointLights };
  866. }
  867. return { 'directional' : 1, 'point' : maxLights - 1 };
  868. };
  869. /* DEBUG
  870. function getGLParams() {
  871. var params = {
  872. 'MAX_VARYING_VECTORS': _gl.getParameter( _gl.MAX_VARYING_VECTORS ),
  873. 'MAX_VERTEX_ATTRIBS': _gl.getParameter( _gl.MAX_VERTEX_ATTRIBS ),
  874. 'MAX_TEXTURE_IMAGE_UNITS': _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS ),
  875. 'MAX_VERTEX_TEXTURE_IMAGE_UNITS': _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ),
  876. 'MAX_COMBINED_TEXTURE_IMAGE_UNITS' : _gl.getParameter( _gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS ),
  877. 'MAX_VERTEX_UNIFORM_VECTORS': _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS ),
  878. 'MAX_FRAGMENT_UNIFORM_VECTORS': _gl.getParameter( _gl.MAX_FRAGMENT_UNIFORM_VECTORS )
  879. }
  880. return params;
  881. };
  882. function dumpObject( obj ) {
  883. var p, str = "";
  884. for ( p in obj ) {
  885. str += p + ": " + obj[p] + "\n";
  886. }
  887. return str;
  888. }
  889. */
  890. };