WebGLRenderer.js 50 KB

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