WebGLRenderer.js 37 KB

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