WebGLRenderer.js 40 KB

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