WebGLRenderer.js 38.5 KB
Newer Older
N
Nicolas Garcia Belmonte 已提交
1 2 3
/**
 * @author supereggbert / http://www.paulbrunt.co.uk/
 * @author mrdoob / http://mrdoob.com/
4
 * @author alteredq / http://alteredqualia.com/
N
Nicolas Garcia Belmonte 已提交
5 6
 */

7 8
THREE.WebGLRenderer = function ( scene ) {
	
M
Mr.doob 已提交
9 10
	// Currently you can use just up to 4 directional / point lights total.
	// Chrome barfs on shader linking when there are more than 4 lights :(
11 12 13 14 15 16 17
		
	// It seems problem comes from having too many varying vectors.
	
	// Weirdly, this is not GPU limitation as the same shader works ok in Firefox.
	// This difference could come from Chrome using ANGLE on Windows, 
	// thus going DirectX9 route (while FF uses OpenGL).
	
18 19
	var _canvas = document.createElement( 'canvas' ), _gl, _program,
	_modelViewMatrix = new THREE.Matrix4(), _normalMatrix,
20
	
M
Mr.doob 已提交
21
	BASIC = 0, LAMBERT = 1, PHONG = 2, DEPTH = 3, NORMAL = 4, CUBE = 5, // material constants used in shader
22
	
23
	maxLightCount = allocateLights( scene, 4 );
24
	
N
Nicolas Garcia Belmonte 已提交
25 26 27 28
	this.domElement = _canvas;
	this.autoClear = true;

	initGL();
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
	initProgram( maxLightCount.directional, maxLightCount.point );
	
	// Querying via gl.getParameter() reports different values for CH and FF for many max parameters.
	// On my GPU Chrome reports MAX_VARYING_VECTORS = 8, FF reports 0 yet compiles shaders with many
	// more varying vectors (up to 29 lights are ok, more start to throw warnings to FF error console
	// and then crash the browser).
	
	//alert( dumpObject( getGLParams() ) );
	
	
	function allocateLights( scene, maxLights ) {

		// heuristics to create shader parameters according to lights in the scene
		// (not to blow over maxLights budget)
		
		if ( scene ) {

			var l, ll, light, dirLights = pointLights = maxDirLights = maxPointLights = 0;
			
			for ( l = 0, ll = scene.lights.length; l < ll; l++ ) {
				
				light = scene.lights[ l ];
				
				if ( light instanceof THREE.DirectionalLight ) dirLights++;
				if ( light instanceof THREE.PointLight ) pointLights++;
				
			}
			
			if ( ( pointLights + dirLights ) <= maxLights ) {
				
				maxDirLights = dirLights;
				maxPointLights = pointLights;
			
			} else {
				
				maxDirLights = Math.ceil( maxLights * dirLights / ( pointLights + dirLights ) );
				maxPointLights = maxLights - maxDirLights;
				
			}
			
			return { 'directional' : maxDirLights, 'point' : maxPointLights };
			
		}
		
		return { 'directional' : 1, 'point' : maxLights - 1 };
		
	};
N
Nicolas Garcia Belmonte 已提交
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

	this.setSize = function ( width, height ) {

		_canvas.width = width;
		_canvas.height = height;
		_gl.viewport( 0, 0, _canvas.width, _canvas.height );

	};

	this.clear = function () {

		_gl.clear( _gl.COLOR_BUFFER_BIT | _gl.DEPTH_BUFFER_BIT );

	};

91 92
	this.setupLights = function ( scene ) {

93
		var l, ll, light, r, g, b,
A
alteredq 已提交
94
			ambientLights = [], pointLights = [], directionalLights = [],
95
			colors = [], positions = [];
96

97
		_gl.uniform1i( _program.enableLighting, scene.lights.length );
98 99 100 101 102 103 104

		for ( l = 0, ll = scene.lights.length; l < ll; l++ ) {

			light = scene.lights[ l ];

			if ( light instanceof THREE.AmbientLight ) {

105
				ambientLights.push( light );
106

107
			} else if ( light instanceof THREE.DirectionalLight ) {
108

109
				directionalLights.push( light );
110

111 112
			} else if( light instanceof THREE.PointLight ) {

113 114
				pointLights.push( light );
				
115 116 117
			}

		}
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
		
		// sum all ambient lights
		r = g = b = 0.0;
		
		for ( l = 0, ll = ambientLights.length; l < ll; l++ ) {
			
			r += ambientLights[ l ].color.r;
			g += ambientLights[ l ].color.g;
			b += ambientLights[ l ].color.b;
			
		}
		
		_gl.uniform3f( _program.ambientLightColor, r, g, b );

		// pass directional lights as float arrays
		
		colors = []; positions = [];
		
		for ( l = 0, ll = directionalLights.length; l < ll; l++ ) {
			
			light = directionalLights[ l ];
			
			colors.push( light.color.r * light.intensity );
			colors.push( light.color.g * light.intensity );
			colors.push( light.color.b * light.intensity );

			positions.push( light.position.x );
			positions.push( light.position.y );
			positions.push( light.position.z );
			
		}
		
		if ( directionalLights.length ) {

			_gl.uniform1i(  _program.directionalLightNumber, directionalLights.length );
			_gl.uniform3fv( _program.directionalLightDirection, positions );
			_gl.uniform3fv( _program.directionalLightColor, colors );
			
		}
157

158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
		// pass point lights as float arrays
		
		colors = []; positions = [];
		
		for ( l = 0, ll = pointLights.length; l < ll; l++ ) {
			
			light = pointLights[ l ];
			
			colors.push( light.color.r * light.intensity );
			colors.push( light.color.g * light.intensity );
			colors.push( light.color.b * light.intensity );

			positions.push( light.position.x );
			positions.push( light.position.y );
			positions.push( light.position.z );
			
		}
		
		if ( pointLights.length ) {

			_gl.uniform1i(  _program.pointLightNumber, pointLights.length );
			_gl.uniform3fv( _program.pointLightPosition, positions );
			_gl.uniform3fv( _program.pointLightColor, colors );
		
		}
		
184 185 186 187
	};

	this.createBuffers = function ( object, mf ) {

188
		var f, fl, fi, face, vertexNormals, normal, uv, v1, v2, v3, v4, m, ml, i, l,
189 190 191 192 193 194 195 196 197 198

		materialFaceGroup = object.materialFaceGroup[ mf ],

		faceArray = [],
		lineArray = [],

		vertexArray = [],
		normalArray = [],
		uvArray = [],

199
		vertexIndex = 0,
200

201
		useSmoothNormals = false;
202

203 204 205
		// need to find out if there is any material in the object
		// (among all mesh materials and also face materials)
		// which would need smooth normals
206

207
		function needsSmoothNormals( material ) {
208

209
			return material && material.shading != undefined && material.shading == THREE.SmoothShading;
210

211
		}
212

213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
		for ( m = 0, ml = object.material.length; m < ml; m++ ) {

			meshMaterial = object.material[ m ];

			if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {

				for ( i = 0, l = materialFaceGroup.material.length; i < l; i++ ) {
					
					if ( needsSmoothNormals( materialFaceGroup.material[ i ] ) ) {
						
						useSmoothNormals = true;
						break;
						
					}

				}

			} else {

				if ( needsSmoothNormals( meshMaterial ) ) {
					
					useSmoothNormals = true;
					break;
					
				}

			}
			
			if ( useSmoothNormals ) break;

		}
		
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
		for ( f = 0, fl = materialFaceGroup.faces.length; f < fl; f++ ) {

			fi = materialFaceGroup.faces[f];

			face = object.geometry.faces[ fi ];
			vertexNormals = face.vertexNormals;
			normal = face.normal;
			uv = object.geometry.uvs[ fi ];

			if ( face instanceof THREE.Face3 ) {

				v1 = object.geometry.vertices[ face.a ].position;
				v2 = object.geometry.vertices[ face.b ].position;
				v3 = object.geometry.vertices[ face.c ].position;

				vertexArray.push( v1.x, v1.y, v1.z );
				vertexArray.push( v2.x, v2.y, v2.z );
				vertexArray.push( v3.x, v3.y, v3.z );

264
				if ( vertexNormals.length == 3 && useSmoothNormals ) {
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307

					normalArray.push( vertexNormals[0].x, vertexNormals[0].y, vertexNormals[0].z );
					normalArray.push( vertexNormals[1].x, vertexNormals[1].y, vertexNormals[1].z );
					normalArray.push( vertexNormals[2].x, vertexNormals[2].y, vertexNormals[2].z );

				} else {

					normalArray.push( normal.x, normal.y, normal.z );
					normalArray.push( normal.x, normal.y, normal.z );
					normalArray.push( normal.x, normal.y, normal.z );

				}

				if ( uv ) {

					uvArray.push( uv[0].u, uv[0].v );
					uvArray.push( uv[1].u, uv[1].v );
					uvArray.push( uv[2].u, uv[2].v );

				}

				faceArray.push( vertexIndex, vertexIndex + 1, vertexIndex + 2 );

				// TODO: don't add lines that already exist (faces sharing edge)

				lineArray.push( vertexIndex, vertexIndex + 1 );
				lineArray.push( vertexIndex, vertexIndex + 2 );
				lineArray.push( vertexIndex + 1, vertexIndex + 2 );

				vertexIndex += 3;

			} else if ( face instanceof THREE.Face4 ) {

				v1 = object.geometry.vertices[ face.a ].position;
				v2 = object.geometry.vertices[ face.b ].position;
				v3 = object.geometry.vertices[ face.c ].position;
				v4 = object.geometry.vertices[ face.d ].position;

				vertexArray.push( v1.x, v1.y, v1.z );
				vertexArray.push( v2.x, v2.y, v2.z );
				vertexArray.push( v3.x, v3.y, v3.z );
				vertexArray.push( v4.x, v4.y, v4.z );

308
				if ( vertexNormals.length == 4 && useSmoothNormals ) {
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344

					normalArray.push( vertexNormals[0].x, vertexNormals[0].y, vertexNormals[0].z );
					normalArray.push( vertexNormals[1].x, vertexNormals[1].y, vertexNormals[1].z );
					normalArray.push( vertexNormals[2].x, vertexNormals[2].y, vertexNormals[2].z );
					normalArray.push( vertexNormals[3].x, vertexNormals[3].y, vertexNormals[3].z );

				} else {

					normalArray.push( normal.x, normal.y, normal.z );
					normalArray.push( normal.x, normal.y, normal.z );
					normalArray.push( normal.x, normal.y, normal.z );
					normalArray.push( normal.x, normal.y, normal.z );

				}

				if ( uv ) {

					uvArray.push( uv[0].u, uv[0].v );
					uvArray.push( uv[1].u, uv[1].v );
					uvArray.push( uv[2].u, uv[2].v );
					uvArray.push( uv[3].u, uv[3].v );

				}

				faceArray.push( vertexIndex, vertexIndex + 1, vertexIndex + 2 );
				faceArray.push( vertexIndex, vertexIndex + 2, vertexIndex + 3 );

				// TODO: don't add lines that already exist (faces sharing edge)

				lineArray.push( vertexIndex, vertexIndex + 1 );
				lineArray.push( vertexIndex, vertexIndex + 2 );
				lineArray.push( vertexIndex, vertexIndex + 3 );
				lineArray.push( vertexIndex + 1, vertexIndex + 2 );
				lineArray.push( vertexIndex + 2, vertexIndex + 3 );

				vertexIndex += 4;
345
				
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
			}
		}

		if ( !vertexArray.length ) {

			return;

		}

		materialFaceGroup.__webGLVertexBuffer = _gl.createBuffer();
		_gl.bindBuffer( _gl.ARRAY_BUFFER, materialFaceGroup.__webGLVertexBuffer );
		_gl.bufferData( _gl.ARRAY_BUFFER, new Float32Array( vertexArray ), _gl.STATIC_DRAW );

		materialFaceGroup.__webGLNormalBuffer = _gl.createBuffer();
		_gl.bindBuffer( _gl.ARRAY_BUFFER, materialFaceGroup.__webGLNormalBuffer );
		_gl.bufferData( _gl.ARRAY_BUFFER, new Float32Array( normalArray ), _gl.STATIC_DRAW );

		materialFaceGroup.__webGLUVBuffer = _gl.createBuffer();
		_gl.bindBuffer( _gl.ARRAY_BUFFER, materialFaceGroup.__webGLUVBuffer );
		_gl.bufferData( _gl.ARRAY_BUFFER, new Float32Array( uvArray ), _gl.STATIC_DRAW );

		materialFaceGroup.__webGLFaceBuffer = _gl.createBuffer();
		_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, materialFaceGroup.__webGLFaceBuffer );
		_gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( faceArray ), _gl.STATIC_DRAW );

		materialFaceGroup.__webGLLineBuffer = _gl.createBuffer();
		_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, materialFaceGroup.__webGLLineBuffer );
		_gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, new Uint16Array( lineArray ), _gl.STATIC_DRAW );

		materialFaceGroup.__webGLFaceCount = faceArray.length;
		materialFaceGroup.__webGLLineCount = lineArray.length;

	};

	this.renderBuffer = function ( material, materialFaceGroup ) {

382 383
		var mColor, mOpacity, mReflectivity,
			mWireframe, mLineWidth, mBlending,
A
alteredq 已提交
384
			mAmbient, mSpecular, mShininess,
385 386
			mMap, envMap, mixEnvMap,
			mRefractionRatio, useRefract;
A
alteredq 已提交
387 388 389 390 391 392 393 394 395 396 397 398 399 400
		
		if ( material instanceof THREE.MeshPhongMaterial ||
			 material instanceof THREE.MeshLambertMaterial ||
			 material instanceof THREE.MeshBasicMaterial ) {
		
			mColor = material.color;
			mOpacity = material.opacity;
			
			mWireframe = material.wireframe;
			mLineWidth = material.wireframe_linewidth;
			
			mBlending = material.blending;
		
			mMap = material.map;
401
			envMap = material.env_map;
402 403 404 405 406 407

			mixEnvMap = material.combine == THREE.Mix;
			mReflectivity = material.reflectivity;
			
			useRefract = material.env_map && material.env_map.mapping == THREE.RefractionMap;
			mRefractionRatio = material.refraction_ratio;
A
alteredq 已提交
408 409
			
			_gl.uniform4f( _program.mColor,  mColor.r * mOpacity, mColor.g * mOpacity, mColor.b * mOpacity, mOpacity );
410 411
			
			_gl.uniform1i( _program.mixEnvMap, mixEnvMap );
412
			_gl.uniform1f( _program.mReflectivity, mReflectivity );
413 414 415 416
			
			_gl.uniform1i( _program.useRefract, useRefract );
			_gl.uniform1f( _program.mRefractionRatio, mRefractionRatio );
			
A
alteredq 已提交
417 418
		}
		
419 420 421 422 423 424 425 426 427 428
		if ( material instanceof THREE.MeshNormalMaterial ) {
			
			mOpacity = material.opacity;
			mBlending = material.blending;
			
			_gl.uniform1f( _program.mOpacity, mOpacity );
			
			_gl.uniform1i( _program.material, NORMAL );
			
		} else if ( material instanceof THREE.MeshDepthMaterial ) {
429 430 431 432 433 434
			
			mOpacity = material.opacity;
			
			mWireframe = material.wireframe;
			mLineWidth = material.wireframe_linewidth;
			
435 436
			_gl.uniform1f( _program.mOpacity, mOpacity );
			
437 438 439 440 441 442 443
			_gl.uniform1f( _program.m2Near, material.__2near );
			_gl.uniform1f( _program.mFarPlusNear, material.__farPlusNear );
			_gl.uniform1f( _program.mFarMinusNear, material.__farMinusNear );
			
			_gl.uniform1i( _program.material, DEPTH );
			
		} else if ( material instanceof THREE.MeshPhongMaterial ) {
444 445 446

			mAmbient  = material.ambient;
			mSpecular = material.specular;
A
alteredq 已提交
447 448 449 450 451 452
			mShininess = material.shininess;
			
			_gl.uniform4f( _program.mAmbient,  mAmbient.r,  mAmbient.g,  mAmbient.b,  mOpacity );
			_gl.uniform4f( _program.mSpecular, mSpecular.r, mSpecular.g, mSpecular.b, mOpacity );
			_gl.uniform1f( _program.mShininess, mShininess );
			
453 454
			_gl.uniform1i( _program.material, PHONG );

A
alteredq 已提交
455 456 457
		} else if ( material instanceof THREE.MeshLambertMaterial ) {
			
			_gl.uniform1i( _program.material, LAMBERT );
458

A
alteredq 已提交
459
		} else if ( material instanceof THREE.MeshBasicMaterial ) {
460

A
alteredq 已提交
461
			_gl.uniform1i( _program.material, BASIC );
462

M
Mr.doob 已提交
463 464 465 466 467 468
		} else if ( material instanceof THREE.MeshCubeMaterial ) {

			_gl.uniform1i( _program.material, CUBE );
			
			envMap = material.env_map;

A
alteredq 已提交
469 470 471
		} 
		
		if ( mMap ) {
472

473
			if ( !material.__webGLTexture && material.map.image.loaded ) {
474 475 476

				material.__webGLTexture = _gl.createTexture();
				_gl.bindTexture( _gl.TEXTURE_2D, material.__webGLTexture );
A
alteredq 已提交
477
				_gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, _gl.RGBA, _gl.UNSIGNED_BYTE, material.map.image ) ;
478 479
				_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
				_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
480 481 482 483 484 485 486 487 488
				_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.LINEAR );
				_gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.LINEAR_MIPMAP_LINEAR );
				_gl.generateMipmap( _gl.TEXTURE_2D );
				_gl.bindTexture( _gl.TEXTURE_2D, null );

			}

			_gl.activeTexture( _gl.TEXTURE0 );
			_gl.bindTexture( _gl.TEXTURE_2D, material.__webGLTexture );
A
alteredq 已提交
489
			_gl.uniform1i( _program.tMap,  0 );
490

A
alteredq 已提交
491
			_gl.uniform1i( _program.enableMap, 1 );
492

A
alteredq 已提交
493 494 495 496
		} else {
			
			_gl.uniform1i( _program.enableMap, 0 );
			
497
		}
A
alteredq 已提交
498
		
499 500 501 502 503 504
		if ( envMap ) {
			
			if ( material.env_map && 
				 material.env_map instanceof THREE.TextureCube && 
				 material.env_map.image.length == 6 ) {
				
M
Mr.doob 已提交
505
				if ( !material.env_map.image.__webGLTextureCube && !material.env_map.image.__cubeMapInitialized && material.env_map.image.loadCount == 6 ) {
506
					
M
Mr.doob 已提交
507
					material.env_map.image.__webGLTextureCube = _gl.createTexture();
508
					
M
Mr.doob 已提交
509
					_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, material.env_map.image.__webGLTextureCube );
510 511 512 513 514 515 516
					
					_gl.texParameteri( _gl.TEXTURE_CUBE_MAP, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
					_gl.texParameteri( _gl.TEXTURE_CUBE_MAP, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
			
					_gl.texParameteri( _gl.TEXTURE_CUBE_MAP, _gl.TEXTURE_MAG_FILTER, _gl.LINEAR );
					_gl.texParameteri( _gl.TEXTURE_CUBE_MAP, _gl.TEXTURE_MIN_FILTER, _gl.LINEAR_MIPMAP_LINEAR );
					
M
Mr.doob 已提交
517 518
					//_gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, true );
					
519 520 521 522 523 524 525
					_gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X, 0, _gl.RGBA, _gl.RGBA, _gl.UNSIGNED_BYTE, material.env_map.image[0] );
					_gl.texImage2D( _gl.TEXTURE_CUBE_MAP_NEGATIVE_X, 0, _gl.RGBA, _gl.RGBA, _gl.UNSIGNED_BYTE, material.env_map.image[1] );
					_gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_Y, 0, _gl.RGBA, _gl.RGBA, _gl.UNSIGNED_BYTE, material.env_map.image[2] );
					_gl.texImage2D( _gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, _gl.RGBA, _gl.RGBA, _gl.UNSIGNED_BYTE, material.env_map.image[3] );
					_gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_Z, 0, _gl.RGBA, _gl.RGBA, _gl.UNSIGNED_BYTE, material.env_map.image[4] );
					_gl.texImage2D( _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, _gl.RGBA, _gl.RGBA, _gl.UNSIGNED_BYTE, material.env_map.image[5] );
					
M
Mr.doob 已提交
526 527
					//_gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, false );
					
528 529 530 531
					_gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
					
					_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
					
M
Mr.doob 已提交
532 533 534
					material.env_map.image.__cubeMapInitialized = true;
					
					//log( "texture cube initialised " + material );
535 536 537 538
					
				}
				
				_gl.activeTexture( _gl.TEXTURE1 );
M
Mr.doob 已提交
539
				_gl.bindTexture( _gl.TEXTURE_CUBE_MAP, material.env_map.image.__webGLTextureCube );
540 541 542 543 544 545 546 547 548 549 550 551
				_gl.uniform1i( _program.tCube,  1 );
				
			}
			
			_gl.uniform1i( _program.enableCubeMap, 1 );
			
		} else {
			
			_gl.uniform1i( _program.enableCubeMap, 0 );
			
		}
		
552
		// vertices
553
		
554 555 556 557
		_gl.bindBuffer( _gl.ARRAY_BUFFER, materialFaceGroup.__webGLVertexBuffer );
		_gl.vertexAttribPointer( _program.position, 3, _gl.FLOAT, false, 0, 0 );

		// normals
558
		
559 560 561 562
		_gl.bindBuffer( _gl.ARRAY_BUFFER, materialFaceGroup.__webGLNormalBuffer );
		_gl.vertexAttribPointer( _program.normal, 3, _gl.FLOAT, false, 0, 0 );

		// uvs
563
		
A
alteredq 已提交
564
		if ( mMap ) {
565 566 567 568 569 570 571 572 573 574 575 576 577

			_gl.bindBuffer( _gl.ARRAY_BUFFER, materialFaceGroup.__webGLUVBuffer );

			_gl.enableVertexAttribArray( _program.uv );
			_gl.vertexAttribPointer( _program.uv, 2, _gl.FLOAT, false, 0, 0 );

		} else {

			_gl.disableVertexAttribArray( _program.uv );

		}

		// render triangles
578
		
A
alteredq 已提交
579
		if ( ! mWireframe ) {
580 581 582 583 584

			_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, materialFaceGroup.__webGLFaceBuffer );
			_gl.drawElements( _gl.TRIANGLES, materialFaceGroup.__webGLFaceCount, _gl.UNSIGNED_SHORT, 0 );

		// render lines
585
		
A
alteredq 已提交
586
		} else {
587

A
alteredq 已提交
588
			_gl.lineWidth( mLineWidth );
589 590 591 592 593 594 595
			_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, materialFaceGroup.__webGLLineBuffer );
			_gl.drawElements( _gl.LINES, materialFaceGroup.__webGLLineCount, _gl.UNSIGNED_SHORT, 0 );

		}

	};

M
Mr.doob 已提交
596
	this.renderPass = function ( object, materialFaceGroup, blending ) {
597
		
M
Mr.doob 已提交
598 599 600
		var i, l, m, ml, material, meshMaterial;
		
		for ( m = 0, ml = object.material.length; m < ml; m++ ) {
601

M
Mr.doob 已提交
602
			meshMaterial = object.material[ m ];
603

M
Mr.doob 已提交
604
			if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
605

M
Mr.doob 已提交
606
				for ( i = 0, l = materialFaceGroup.material.length; i < l; i++ ) {
607

M
Mr.doob 已提交
608
					material = materialFaceGroup.material[ i ];
609
					if ( material && material.blending == blending ) {
M
Mr.doob 已提交
610 611
						
						this.setBlending( material.blending );
612
						this.renderBuffer( material, materialFaceGroup );
M
Mr.doob 已提交
613
						
614 615
					}

M
Mr.doob 已提交
616
				}
617

M
Mr.doob 已提交
618
			} else {
619

M
Mr.doob 已提交
620
				material = meshMaterial;
621
				if ( material && material.blending == blending ) {
M
Mr.doob 已提交
622 623 624
					
					this.setBlending( material.blending );
					this.renderBuffer( material, materialFaceGroup );
625 626 627
				}

			}
628 629

		}
M
Mr.doob 已提交
630
		
631 632
	};

M
Mr.doob 已提交
633 634 635 636 637 638
	this.render = function( scene, camera ) {
		
		var o, ol;
		
		this.initWebGLObjects( scene );
		
639 640 641 642 643 644
		if ( this.autoClear ) {

			this.clear();

		}

645 646 647 648
		camera.autoUpdateMatrix && camera.updateMatrix();
		_gl.uniform3f( _program.cameraPosition, camera.position.x, camera.position.y, camera.position.z );

		this.setupLights( scene );
649

M
Mr.doob 已提交
650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
		// opaque pass
		
		for ( o = 0, ol = scene.__webGLObjects.length; o < ol; o++ ) {
			
			webGLObject = scene.__webGLObjects[ o ];
			
			this.setupMatrices( webGLObject.__object, camera );
			this.renderPass( webGLObject.__object, webGLObject, THREE.NormalBlending );
			
		}
		
		// transparent pass
		
		for ( o = 0, ol = scene.__webGLObjects.length; o < ol; o++ ) {
			
			webGLObject = scene.__webGLObjects[ o ];
			
			this.setupMatrices( webGLObject.__object, camera );
			this.renderPass( webGLObject.__object, webGLObject, THREE.AdditiveBlending );
			this.renderPass( webGLObject.__object, webGLObject, THREE.SubtractiveBlending );
			
		}
		
	};
	
	this.initWebGLObjects = function( scene ) {
		
		var o, ol, object, mf, materialFaceGroup;
		
		if ( !scene.__webGLObjects ) {
				
			scene.__webGLObjects = [];
			
		}
		
685 686 687 688 689 690
		for ( o = 0, ol = scene.objects.length; o < ol; o++ ) {

			object = scene.objects[ o ];

			if ( object instanceof THREE.Mesh ) {

M
Mr.doob 已提交
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
				// create separate VBOs per material
				
				for ( mf in object.materialFaceGroup ) {

					materialFaceGroup = object.materialFaceGroup[ mf ];

					// initialise buffers on the first access
					
					if( ! materialFaceGroup.__webGLVertexBuffer ) {

						this.createBuffers( object, mf );
						materialFaceGroup.__object = object;
						scene.__webGLObjects.push( materialFaceGroup );

					}
					
				}
708 709

			} else if ( object instanceof THREE.Line ) {
M
Mr.doob 已提交
710 711 712 713 714 715 716 717 718 719 720
				
			} else if ( object instanceof THREE.Particle ) {
			
			}
			
		}
		
	};
	
	
	this.setupMatrices = function ( object, camera ) {
721

M
Mr.doob 已提交
722
		object.autoUpdateMatrix && object.updateMatrix();
723

M
Mr.doob 已提交
724
		_modelViewMatrix.multiply( camera.matrix, object.matrix );
725

M
Mr.doob 已提交
726 727 728
		_program.viewMatrixArray = new Float32Array( camera.matrix.flatten() );
		_program.modelViewMatrixArray = new Float32Array( _modelViewMatrix.flatten() );
		_program.projectionMatrixArray = new Float32Array( camera.projectionMatrix.flatten() );
729

M
Mr.doob 已提交
730 731
		_normalMatrix = THREE.Matrix4.makeInvert3x3( _modelViewMatrix ).transpose();
		_program.normalMatrixArray = new Float32Array( _normalMatrix.m );
732

M
Mr.doob 已提交
733 734 735 736 737
		_gl.uniformMatrix4fv( _program.viewMatrix, false, _program.viewMatrixArray );
		_gl.uniformMatrix4fv( _program.modelViewMatrix, false, _program.modelViewMatrixArray );
		_gl.uniformMatrix4fv( _program.projectionMatrix, false, _program.projectionMatrixArray );
		_gl.uniformMatrix3fv( _program.normalMatrix, false, _program.normalMatrixArray );
		_gl.uniformMatrix4fv( _program.objMatrix, false, new Float32Array( object.matrix.flatten() ) );
738

M
Mr.doob 已提交
739
	};
740

M
Mr.doob 已提交
741 742 743 744
	
	this.setBlending = function( blending ) {
		
		switch ( blending ) {
745

M
Mr.doob 已提交
746
			case THREE.AdditiveBlending:
747

M
Mr.doob 已提交
748 749 750 751
				_gl.blendEquation( _gl.FUNC_ADD );
				_gl.blendFunc( _gl.ONE, _gl.ONE );
			
				break;
752

M
Mr.doob 已提交
753
			case THREE.SubtractiveBlending:
754

M
Mr.doob 已提交
755 756 757 758 759 760 761 762 763 764 765
				//_gl.blendEquation( _gl.FUNC_SUBTRACT );
				_gl.blendFunc( _gl.DST_COLOR, _gl.ZERO );
			
				break;
				
			default:
			
				_gl.blendEquation( _gl.FUNC_ADD );
				_gl.blendFunc( _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
				
				break;
N
Nicolas Garcia Belmonte 已提交
766
		}
M
Mr.doob 已提交
767
		
N
Nicolas Garcia Belmonte 已提交
768
	};
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
	
	this.setFaceCulling = function( cullFace, frontFace ) {
		
		if ( cullFace ) {
			
			if ( !frontFace || frontFace == "ccw" ) {
			
				_gl.frontFace( _gl.CCW );
				
			} else {
				
				_gl.frontFace( _gl.CW );
			}
			
			if( cullFace == "back" ) {
					
				_gl.cullFace( _gl.BACK );
				
			} else if( cullFace == "front" ) {
				
				_gl.cullFace( _gl.FRONT );
			
			} else {
				
				_gl.cullFace( _gl.FRONT_AND_BACK );
			}
			
			_gl.enable( _gl.CULL_FACE );
			
		} else {
			
			_gl.disable( _gl.CULL_FACE );
		}

	};
N
Nicolas Garcia Belmonte 已提交
804 805 806 807 808

	function initGL() {

		try {

U
unknown 已提交
809
			_gl = _canvas.getContext( 'experimental-webgl', { antialias: true} );
N
Nicolas Garcia Belmonte 已提交
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825

		} catch(e) { }

		if (!_gl) {

			alert("WebGL not supported");
			throw "cannot create webgl context";

		}

		_gl.clearColor( 0, 0, 0, 1 );
		_gl.clearDepth( 1 );

		_gl.enable( _gl.DEPTH_TEST );
		_gl.depthFunc( _gl.LEQUAL );

826 827
		_gl.frontFace( _gl.CCW );
		_gl.cullFace( _gl.BACK );
828
		_gl.enable( _gl.CULL_FACE );
829
		
N
Nicolas Garcia Belmonte 已提交
830
		_gl.enable( _gl.BLEND );
U
unknown 已提交
831
		//_gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
M
Mr.doob 已提交
832
		//_gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE ); // cool!
833
		_gl.blendFunc( _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
N
Nicolas Garcia Belmonte 已提交
834 835
		_gl.clearColor( 0, 0, 0, 0 );

836
	};
N
Nicolas Garcia Belmonte 已提交
837

838 839 840
	function generateFragmentShader( maxDirLights, maxPointLights ) {
	
		var chunks = [
841

842 843 844
			"#ifdef GL_ES",
			"precision highp float;",
			"#endif",
845 846 847 848
		
			maxDirLights   ? "#define MAX_DIR_LIGHTS " + maxDirLights     : "",
			maxPointLights ? "#define MAX_POINT_LIGHTS " + maxPointLights : "",
		
M
Mr.doob 已提交
849
			"uniform int material;", // 0 - Basic, 1 - Lambert, 2 - Phong, 3 - Depth, 4 - Normal, 5 - Cube
850

A
alteredq 已提交
851
			"uniform bool enableMap;",
852
			"uniform bool enableCubeMap;",
853
			"uniform bool mixEnvMap;",
A
alteredq 已提交
854
		
855 856 857
			"uniform samplerCube tCube;",
			"uniform float mReflectivity;",

A
alteredq 已提交
858
			"uniform sampler2D tMap;",
859
			"uniform vec4 mColor;",
860
			"uniform float mOpacity;",
861

862
			"uniform vec4 mAmbient;",
863
			"uniform vec4 mSpecular;",
864
			"uniform float mShininess;",
865

866 867 868 869
			"uniform float m2Near;",
			"uniform float mFarPlusNear;",
			"uniform float mFarMinusNear;",
			
870 871 872 873 874 875
			"uniform int pointLightNumber;",
			"uniform int directionalLightNumber;",
			
			maxDirLights ? "uniform mat4 viewMatrix;" : "",
			maxDirLights ? "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];" : "",
			
876
			"varying vec3 vNormal;",
877 878
			"varying vec2 vUv;",
			
879 880
			"varying vec3 vLightWeighting;",

881 882
			maxPointLights ? "varying vec3 vPointLightVector[ MAX_POINT_LIGHTS ];"     : "",
			
883
			"varying vec3 vViewPosition;",
884
			
885
			"varying vec3 vReflect;",
M
Mr.doob 已提交
886 887 888
		
			"uniform vec3 cameraPosition;",
		
889
			"void main() {",
890

A
alteredq 已提交
891
				"vec4 mapColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
892
				"vec4 cubeColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
893

894 895
				// diffuse map
				
A
alteredq 已提交
896 897 898 899 900
				"if ( enableMap ) {",
				
					"mapColor = texture2D( tMap, vUv );",
					
				"}",
901

902 903 904 905
				// cube map
				
				"if ( enableCubeMap ) {",
					
906
					"cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
907 908 909
					
				"}",

M
Mr.doob 已提交
910 911 912 913 914 915 916
				// Cube
				
				"if ( material == 5 ) { ",

					"vec3 wPos = cameraPosition - vViewPosition;",
					"gl_FragColor = textureCube( tCube, vec3( -wPos.x, wPos.yz ) );",

917 918
				// Normals
				
M
Mr.doob 已提交
919
				"} else if ( material == 4 ) { ",
920 921 922 923 924 925
				
					"gl_FragColor = vec4( 0.5*normalize( vNormal ) + vec3(0.5, 0.5, 0.5), mOpacity );",
				
				// Depth
				
				"} else if ( material == 3 ) { ",
926 927 928 929 930 931 932
					
					// this breaks shader validation in Chrome 9.0.576.0 dev 
					// and also latest continuous build Chromium 9.0.583.0 (66089)
					// (curiously it works in Chrome 9.0.576.0 canary build and Firefox 4b7)
					//"float w = 1.0 - ( m2Near / ( mFarPlusNear - gl_FragCoord.z * mFarMinusNear ) );",
					"float w = 0.5;",
					
933 934 935 936
					"gl_FragColor = vec4( w, w, w, mOpacity );",
				
				// Blinn-Phong
				// based on o3d example
A
alteredq 已提交
937
				
938
				"} else if ( material == 2 ) { ", 
939 940 941 942

					"vec3 normal = normalize( vNormal );",
					"vec3 viewPosition = normalize( vViewPosition );",

943 944 945 946 947
					// point lights
					
					maxPointLights ? "vec4 pointDiffuse  = vec4( 0.0, 0.0, 0.0, 0.0 );" : "",
					maxPointLights ? "vec4 pointSpecular = vec4( 0.0, 0.0, 0.0, 0.0 );" : "",

948
					maxPointLights ? "for( int i = 0; i < MAX_POINT_LIGHTS; i++ ) {" : "",
949 950 951 952 953 954 955 956 957 958 959
					
					maxPointLights ? 	"vec3 pointVector = normalize( vPointLightVector[ i ] );" : "",
					maxPointLights ? 	"vec3 pointHalfVector = normalize( vPointLightVector[ i ] + vViewPosition );" : "",
						
					maxPointLights ? 	"float pointDotNormalHalf = dot( normal, pointHalfVector );" : "",
					maxPointLights ? 	"float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );" : "",

					// Ternary conditional is from the original o3d shader. Here it produces abrupt dark cutoff artefacts.
					// Using just pow works ok in Chrome, but makes different artefact in Firefox 4.
					// Zeroing on negative pointDotNormalHalf seems to work in both.
					
960 961
					//"float specularCompPoint = dot( normal, pointVector ) < 0.0 || pointDotNormalHalf < 0.0 ? 0.0 : pow( pointDotNormalHalf, mShininess );",
					//"float specularCompPoint = pow( pointDotNormalHalf, mShininess );",
962
					//"float pointSpecularWeight = pointDotNormalHalf < 0.0 ? 0.0 : pow( pointDotNormalHalf, mShininess );",
963

964 965
					// Ternary conditional inside for loop breaks Chrome shader linking.
					// Must do it with if.
966

967 968 969 970
					maxPointLights ? 	"float pointSpecularWeight = 0.0;" : "",
					maxPointLights ? 	"if ( pointDotNormalHalf >= 0.0 )" : "",
					maxPointLights ? 		"pointSpecularWeight = pow( pointDotNormalHalf, mShininess );" : "",
						
A
alteredq 已提交
971
					maxPointLights ? 	"pointDiffuse  += mColor * pointDiffuseWeight;" : "",
972 973 974
					maxPointLights ? 	"pointSpecular += mSpecular * pointSpecularWeight;" : "",
						
					maxPointLights ? "}" : "",
975

976 977 978 979 980
					// directional lights

					maxDirLights ? "vec4 dirDiffuse  = vec4( 0.0, 0.0, 0.0, 0.0 );" : "",
					maxDirLights ? "vec4 dirSpecular = vec4( 0.0, 0.0, 0.0, 0.0 );" : "",
					
981
					maxDirLights ? "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {" : "",
982

983
					maxDirLights ?		"vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );" : "",
984

985 986 987 988
					maxDirLights ? 		"vec3 dirVector = normalize( lDirection.xyz );" : "",
					maxDirLights ? 		"vec3 dirHalfVector = normalize( lDirection.xyz + vViewPosition );" : "",
						
					maxDirLights ? 		"float dirDotNormalHalf = dot( normal, dirHalfVector );" : "",
989

990 991 992 993 994
					maxDirLights ? 		"float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );" : "",  
						
					maxDirLights ? 		"float dirSpecularWeight = 0.0;" : "",
					maxDirLights ? 		"if ( dirDotNormalHalf >= 0.0 )" : "",
					maxDirLights ? 			"dirSpecularWeight = pow( dirDotNormalHalf, mShininess );" : "",
995

A
alteredq 已提交
996
					maxDirLights ? 		"dirDiffuse  += mColor * dirDiffuseWeight;" : "",
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
					maxDirLights ? 		"dirSpecular += mSpecular * dirSpecularWeight;" : "",

					maxDirLights ? "}" : "",

					// all lights contribution summation
					
					"vec4 totalLight = mAmbient;",
					maxDirLights   ? "totalLight += dirDiffuse + dirSpecular;" : "",
					maxPointLights ? "totalLight += pointDiffuse + pointSpecular;" : "",

					// looks nicer with weighting
					
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
					"if ( mixEnvMap ) {",
						
						"gl_FragColor = vec4( mix( mapColor.rgb * totalLight.xyz * vLightWeighting, cubeColor.rgb, mReflectivity ), mapColor.a );",
					
					"} else {",
				
						"gl_FragColor = vec4( mapColor.rgb * cubeColor.rgb * totalLight.xyz * vLightWeighting, mapColor.a );",
						
					"}",
					
A
alteredq 已提交
1019
				// Lambert: diffuse lighting
1020
				
1021
				"} else if ( material == 1 ) {", 
1022

1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
				"if ( mixEnvMap ) {",
					
						"gl_FragColor = vec4( mix( mColor.rgb * mapColor.rgb * vLightWeighting, cubeColor.rgb, mReflectivity ), mColor.a * mapColor.a );",
					
					"} else {",
					
						"gl_FragColor = vec4( mColor.rgb * mapColor.rgb * cubeColor.rgb * vLightWeighting, mColor.a * mapColor.a );",
					
					"}",
	
A
alteredq 已提交
1033
				// Basic: unlit color / texture
1034
				
1035 1036
				"} else {", 

1037 1038 1039 1040 1041 1042 1043 1044 1045
					"if ( mixEnvMap ) {",

						"gl_FragColor = mix( mColor * mapColor, cubeColor, mReflectivity );",
						
					"} else {",

						"gl_FragColor = mColor * mapColor * cubeColor;",
						
					"}",
1046
					
1047 1048
				"}",

1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
			"}" ];
			
		return chunks.join("\n");
		
	};
	
	function generateVertexShader( maxDirLights, maxPointLights ) {
		
		var chunks = [
			
			maxDirLights   ? "#define MAX_DIR_LIGHTS " + maxDirLights     : "",
			maxPointLights ? "#define MAX_POINT_LIGHTS " + maxPointLights : "",
			
1062 1063
			"attribute vec3 position;",
			"attribute vec3 normal;",
1064
			"attribute vec2 uv;",
1065

1066 1067
			"uniform vec3 cameraPosition;",

1068
			"uniform bool enableLighting;",
1069
			"uniform bool useRefract;",
1070 1071 1072 1073
			
			"uniform int pointLightNumber;",
			"uniform int directionalLightNumber;",
			
1074
			"uniform vec3 ambientLightColor;",
1075 1076 1077
			
			maxDirLights ? "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];"     : "",
			maxDirLights ? "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];" : "",
1078

1079 1080
			maxPointLights ? "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];"    : "",
			maxPointLights ? "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];" : "",
1081

1082
			"uniform mat4 objMatrix;",
1083
			"uniform mat4 viewMatrix;",
1084
			"uniform mat4 modelViewMatrix;",
1085
			"uniform mat4 projectionMatrix;",
1086
			"uniform mat3 normalMatrix;",
1087 1088

			"varying vec3 vNormal;",
1089
			"varying vec2 vUv;",
1090
			
1091
			"varying vec3 vLightWeighting;",
1092

1093 1094
			maxPointLights ? "varying vec3 vPointLightVector[ MAX_POINT_LIGHTS ];"     : "",
			
1095
			"varying vec3 vViewPosition;",
1096
			
1097
			"varying vec3 vReflect;",
1098
			"uniform float mRefractionRatio;",
1099

1100
			"void main(void) {",
1101

1102 1103 1104 1105
				// world space
				
				"vec4 mPosition = objMatrix * vec4( position, 1.0 );",
				"vViewPosition = cameraPosition - mPosition.xyz;",
1106
				
A
alteredq 已提交
1107 1108 1109
				// this doesn't work on Mac
				//"vec3 nWorld = mat3(objMatrix) * normal;",
				"vec3 nWorld = mat3( objMatrix[0].xyz, objMatrix[1].xyz, objMatrix[2].xyz ) * normal;",
1110
				
1111 1112
				// eye space
				
1113
				"vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
1114
				"vec3 transformedNormal = normalize( normalMatrix * normal );",
1115

1116
				"if ( !enableLighting ) {",
1117

1118
					"vLightWeighting = vec3( 1.0, 1.0, 1.0 );",
1119 1120 1121

				"} else {",

1122 1123 1124 1125
					"vLightWeighting = ambientLightColor;",
					
					// directional lights
					
1126
					maxDirLights ? "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {" : "",
1127
					maxDirLights ?		"vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );" : "",
1128
					maxDirLights ?		"float directionalLightWeighting = max( dot( transformedNormal, normalize(lDirection.xyz ) ), 0.0 );" : "",
1129 1130 1131 1132 1133
					maxDirLights ?		"vLightWeighting += directionalLightColor[ i ] * directionalLightWeighting;" : "",
					maxDirLights ? "}" : "",
					
					// point lights
					
1134
					maxPointLights ? "for( int i = 0; i < MAX_POINT_LIGHTS; i++ ) {" : "",
1135 1136 1137 1138 1139
					maxPointLights ? 	"vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );" : "",
					maxPointLights ? 	"vPointLightVector[ i ] = normalize( lPosition.xyz - mvPosition.xyz );" : "",
					maxPointLights ? 	"float pointLightWeighting = max( dot( transformedNormal, vPointLightVector[ i ] ), 0.0 );" : "",
					maxPointLights ? 	"vLightWeighting += pointLightColor[ i ] * pointLightWeighting;" : "",
					maxPointLights ? "}" : "",
1140
					
1141
				"}",
1142

1143
				"vNormal = transformedNormal;",
1144
				"vUv = uv;",
1145

1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
				"if ( useRefract ) {",
				
					"vReflect = refract( normalize(mPosition.xyz - cameraPosition), normalize(nWorld.xyz), mRefractionRatio );",
				
				"} else {",
				
					"vReflect = reflect( normalize(mPosition.xyz - cameraPosition), normalize(nWorld.xyz) );",
					
				"}",
				
1156
				"gl_Position = projectionMatrix * mvPosition;",
1157

1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
			"}" ];
			
		return chunks.join("\n");
		
	};
		
	function initProgram( maxDirLights, maxPointLights ) {

		_program = _gl.createProgram();
		
		//log ( generateVertexShader( maxDirLights, maxPointLights ) );
		//log ( generateFragmentShader( maxDirLights, maxPointLights ) );
		
		_gl.attachShader( _program, getShader( "fragment", generateFragmentShader( maxDirLights, maxPointLights ) ) );
		_gl.attachShader( _program, getShader( "vertex",   generateVertexShader( maxDirLights, maxPointLights ) ) );
N
Nicolas Garcia Belmonte 已提交
1173 1174 1175 1176 1177 1178 1179

		_gl.linkProgram( _program );

		if ( !_gl.getProgramParameter( _program, _gl.LINK_STATUS ) ) {

			alert( "Could not initialise shaders" );

1180 1181
			alert( "VALIDATE_STATUS: " + _gl.getProgramParameter( _program, _gl.VALIDATE_STATUS ) );
			alert( _gl.getError() );
N
Nicolas Garcia Belmonte 已提交
1182
		}
1183
		
N
Nicolas Garcia Belmonte 已提交
1184 1185 1186

		_gl.useProgram( _program );

1187 1188
		// matrices
		
N
Nicolas Garcia Belmonte 已提交
1189
		_program.viewMatrix = _gl.getUniformLocation( _program, "viewMatrix" );
1190
		_program.modelViewMatrix = _gl.getUniformLocation( _program, "modelViewMatrix" );
N
Nicolas Garcia Belmonte 已提交
1191
		_program.projectionMatrix = _gl.getUniformLocation( _program, "projectionMatrix" );
1192
		_program.normalMatrix = _gl.getUniformLocation( _program, "normalMatrix" );
1193
		_program.objMatrix = _gl.getUniformLocation( _program, "objMatrix" );
N
Nicolas Garcia Belmonte 已提交
1194

A
alteredq 已提交
1195
		_program.cameraPosition = _gl.getUniformLocation( _program, 'cameraPosition' );
1196

1197 1198
		// lights
		
A
alteredq 已提交
1199
		_program.enableLighting = _gl.getUniformLocation( _program, 'enableLighting' );
1200
		
A
alteredq 已提交
1201
		_program.ambientLightColor = _gl.getUniformLocation( _program, 'ambientLightColor' );
1202 1203 1204
		
		if ( maxDirLights ) {
			
A
alteredq 已提交
1205 1206 1207
			_program.directionalLightNumber = _gl.getUniformLocation( _program, 'directionalLightNumber' );
			_program.directionalLightColor = _gl.getUniformLocation( _program, 'directionalLightColor' );
			_program.directionalLightDirection = _gl.getUniformLocation( _program, 'directionalLightDirection' );
1208 1209
			
		}
1210

1211 1212
		if ( maxPointLights ) {
			
A
alteredq 已提交
1213 1214 1215
			_program.pointLightNumber = _gl.getUniformLocation( _program, 'pointLightNumber' );
			_program.pointLightColor = _gl.getUniformLocation( _program, 'pointLightColor' );
			_program.pointLightPosition = _gl.getUniformLocation( _program, 'pointLightPosition' );
1216 1217
			
		}
U
unknown 已提交
1218

1219 1220
		// material
		
A
alteredq 已提交
1221
		_program.material = _gl.getUniformLocation( _program, 'material' );
1222
		
A
alteredq 已提交
1223
		// material properties (Basic / Lambert / Blinn-Phong shader)
1224
		
A
alteredq 已提交
1225
		_program.mColor = _gl.getUniformLocation( _program, 'mColor' );
1226
		_program.mOpacity = _gl.getUniformLocation( _program, 'mOpacity' );
1227
		_program.mReflectivity = _gl.getUniformLocation( _program, 'mReflectivity' );
1228

1229 1230
		// material properties (Blinn-Phong shader)
		
A
alteredq 已提交
1231 1232 1233
		_program.mAmbient = _gl.getUniformLocation( _program, 'mAmbient' );
		_program.mSpecular = _gl.getUniformLocation( _program, 'mSpecular' );
		_program.mShininess = _gl.getUniformLocation( _program, 'mShininess' );
1234

A
alteredq 已提交
1235 1236 1237
		// texture (diffuse map)
		
		_program.enableMap = _gl.getUniformLocation( _program, "enableMap" );
1238
		_gl.uniform1i( _program.enableMap, 0 );
1239
		
A
alteredq 已提交
1240
		_program.tMap = _gl.getUniformLocation( _program, "tMap" );
1241
		_gl.uniform1i( _program.tMap, 0 );
1242

1243 1244 1245
		// cube texture
		
		_program.enableCubeMap = _gl.getUniformLocation( _program, "enableCubeMap" );
1246
		_gl.uniform1i( _program.enableCubeMap, 0 );
1247 1248
		
		_program.tCube = _gl.getUniformLocation( _program, "tCube" );
1249
		_gl.uniform1i( _program.tCube, 1 ); // it's important to use non-zero texture unit, otherwise it doesn't work
1250

1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
		_program.mixEnvMap = _gl.getUniformLocation( _program, "mixEnvMap" );
		_gl.uniform1i( _program.mixEnvMap, 0 );
		
		// refraction
		
		_program.mRefractionRatio = _gl.getUniformLocation( _program, 'mRefractionRatio' );
		
		_program.useRefract = _gl.getUniformLocation( _program, "useRefract" );
		_gl.uniform1i( _program.useRefract, 0 );
		
1261 1262 1263 1264 1265 1266
		// material properties (Depth)
		
		_program.m2Near = _gl.getUniformLocation( _program, 'm2Near' );
		_program.mFarPlusNear = _gl.getUniformLocation( _program, 'mFarPlusNear' );
		_program.mFarMinusNear = _gl.getUniformLocation( _program, 'mFarMinusNear' );
		
1267 1268
		// vertex arrays
		
N
Nicolas Garcia Belmonte 已提交
1269 1270 1271
		_program.position = _gl.getAttribLocation( _program, "position" );
		_gl.enableVertexAttribArray( _program.position );

1272 1273
		_program.normal = _gl.getAttribLocation( _program, "normal" );
		_gl.enableVertexAttribArray( _program.normal );
1274

U
unknown 已提交
1275 1276 1277 1278
		_program.uv = _gl.getAttribLocation( _program, "uv" );
		_gl.enableVertexAttribArray( _program.uv );


N
Nicolas Garcia Belmonte 已提交
1279
		_program.viewMatrixArray = new Float32Array(16);
1280
		_program.modelViewMatrixArray = new Float32Array(16);
N
Nicolas Garcia Belmonte 已提交
1281
		_program.projectionMatrixArray = new Float32Array(16);
N
Nicolas Garcia Belmonte 已提交
1282

1283
	};
N
Nicolas Garcia Belmonte 已提交
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309

	function getShader( type, string ) {

		var shader;

		if ( type == "fragment" ) {

			shader = _gl.createShader( _gl.FRAGMENT_SHADER );

		} else if ( type == "vertex" ) {

			shader = _gl.createShader( _gl.VERTEX_SHADER );

		}

		_gl.shaderSource( shader, string );
		_gl.compileShader( shader );

		if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {

			alert( _gl.getShaderInfoLog( shader ) );
			return null;

		}

		return shader;
1310 1311
		
	};
N
Nicolas Garcia Belmonte 已提交
1312

A
alteredq 已提交
1313
	/* DEBUG
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
	function getGLParams() {
		
		var params  = {
			
			'MAX_VARYING_VECTORS': _gl.getParameter( _gl.MAX_VARYING_VECTORS ),
			'MAX_VERTEX_ATTRIBS': _gl.getParameter( _gl.MAX_VERTEX_ATTRIBS ),
			
			'MAX_TEXTURE_IMAGE_UNITS': _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS ),
			'MAX_VERTEX_TEXTURE_IMAGE_UNITS': _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ),
			'MAX_COMBINED_TEXTURE_IMAGE_UNITS' : _gl.getParameter( _gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS ),
			
			'MAX_VERTEX_UNIFORM_VECTORS': _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS ),
			'MAX_FRAGMENT_UNIFORM_VECTORS': _gl.getParameter( _gl.MAX_FRAGMENT_UNIFORM_VECTORS )
		}
			
		return params;
	};
	
	function dumpObject( obj ) {
		
		var p, str = "";
		for ( p in obj ) {
			
			str += p + ": " + obj[p] + "\n";
			
		}
		
		return str;
	}
A
alteredq 已提交
1343 1344
	*/

N
Nicolas Garcia Belmonte 已提交
1345
};