WebGLRenderer.js 42 KB

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