WebGLRenderer.js 32.1 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 9 10 11 12 13 14 15 16 17
THREE.WebGLRenderer = function ( scene ) {
	
	// Currently you can use just up to 5 directional / point lights total.
	// Chrome barfs on shader linking when there are more than 5 lights :(
		
	// 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
	
21
	BASIC = 0, LAMBERT = 1, PHONG = 2, DEPTH = 3, NORMAL = 4, // material constants used in shader
22 23 24
	
	maxLightCount = allocateLights( scene, 5 );
	
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 210

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

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 ) {

A
alteredq 已提交
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
		var mColor, mOpacity, mWireframe, mLineWidth, mBlending,
			mAmbient, mSpecular, mShininess,
			mMap;
		
		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;
			
			_gl.uniform4f( _program.mColor,  mColor.r * mOpacity, mColor.g * mOpacity, mColor.b * mOpacity, mOpacity );
		
		}
		
404 405 406 407 408 409 410 411 412 413
		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 ) {
414 415 416 417 418 419
			
			mOpacity = material.opacity;
			
			mWireframe = material.wireframe;
			mLineWidth = material.wireframe_linewidth;
			
420 421
			_gl.uniform1f( _program.mOpacity, mOpacity );
			
422 423 424 425 426 427 428
			_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 ) {
429 430 431

			mAmbient  = material.ambient;
			mSpecular = material.specular;
A
alteredq 已提交
432 433 434 435 436 437
			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 );
			
438 439
			_gl.uniform1i( _program.material, PHONG );

A
alteredq 已提交
440 441 442
		} else if ( material instanceof THREE.MeshLambertMaterial ) {
			
			_gl.uniform1i( _program.material, LAMBERT );
443

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

A
alteredq 已提交
446
			_gl.uniform1i( _program.material, BASIC );
447

A
alteredq 已提交
448 449 450
		} 
		
		if ( mMap ) {
451

A
alteredq 已提交
452
			if ( !material.__webGLTexture && material.map.loaded ) {
453 454 455

				material.__webGLTexture = _gl.createTexture();
				_gl.bindTexture( _gl.TEXTURE_2D, material.__webGLTexture );
A
alteredq 已提交
456
				_gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, _gl.RGBA, _gl.UNSIGNED_BYTE, material.map.image ) ;
457 458 459 460 461 462 463 464 465
				_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 已提交
466
			_gl.uniform1i( _program.tMap,  0 );
467

A
alteredq 已提交
468
			_gl.uniform1i( _program.enableMap, 1 );
469

A
alteredq 已提交
470 471 472 473
		} else {
			
			_gl.uniform1i( _program.enableMap, 0 );
			
474
		}
A
alteredq 已提交
475
		
476 477

		// vertices
478
		
479 480 481 482
		_gl.bindBuffer( _gl.ARRAY_BUFFER, materialFaceGroup.__webGLVertexBuffer );
		_gl.vertexAttribPointer( _program.position, 3, _gl.FLOAT, false, 0, 0 );

		// normals
483
		
484 485 486 487
		_gl.bindBuffer( _gl.ARRAY_BUFFER, materialFaceGroup.__webGLNormalBuffer );
		_gl.vertexAttribPointer( _program.normal, 3, _gl.FLOAT, false, 0, 0 );

		// uvs
488
		
A
alteredq 已提交
489
		if ( mMap ) {
490 491 492 493 494 495 496 497 498 499 500 501 502

			_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
503
		
A
alteredq 已提交
504
		if ( ! mWireframe ) {
505 506 507 508 509

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

		// render lines
510
		
A
alteredq 已提交
511
		} else {
512

A
alteredq 已提交
513
			_gl.lineWidth( mLineWidth );
514 515 516 517 518 519 520 521 522 523 524 525
			_gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, materialFaceGroup.__webGLLineBuffer );
			_gl.drawElements( _gl.LINES, materialFaceGroup.__webGLLineCount, _gl.UNSIGNED_SHORT, 0 );

		}

	};

	this.renderMesh = function ( object, camera ) {

		var i, l, m, ml, mf, material, meshMaterial, materialFaceGroup;

		// create separate VBOs per material
526
		
527 528 529 530
		for ( mf in object.materialFaceGroup ) {

			materialFaceGroup = object.materialFaceGroup[ mf ];

531
			// initialise buffers on the first access
532
			
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
			if( ! materialFaceGroup.__webGLVertexBuffer ) {

				this.createBuffers( object, mf );

			}

			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++ ) {

						material = materialFaceGroup.material[ i ];
						this.renderBuffer( material, materialFaceGroup );

					}

				} else {

					material = meshMaterial;
					this.renderBuffer( material, materialFaceGroup );

				}

			}
560 561

		}
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585

	};

	this.setupMatrices = function ( object, camera ) {

		object.autoUpdateMatrix && object.updateMatrix();

		_modelViewMatrix.multiply( camera.matrix, object.matrix );

		_program.viewMatrixArray = new Float32Array( camera.matrix.flatten() );
		_program.modelViewMatrixArray = new Float32Array( _modelViewMatrix.flatten() );
		_program.projectionMatrixArray = new Float32Array( camera.projectionMatrix.flatten() );

		_normalMatrix = THREE.Matrix4.makeInvert3x3( _modelViewMatrix ).transpose();
		_program.normalMatrixArray = new Float32Array( _normalMatrix.m );

		_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() ) );

	};

586
	this.render = function ( scene, camera ) {
587 588

		var o, ol, object;
589 590 591 592 593 594 595

		if ( this.autoClear ) {

			this.clear();

		}

596 597 598 599
		camera.autoUpdateMatrix && camera.updateMatrix();
		_gl.uniform3f( _program.cameraPosition, camera.position.x, camera.position.y, camera.position.z );

		this.setupLights( scene );
600 601 602 603 604

		for ( o = 0, ol = scene.objects.length; o < ol; o++ ) {

			object = scene.objects[ o ];

605
			this.setupMatrices( object, camera );
606 607 608

			if ( object instanceof THREE.Mesh ) {

609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
				this.renderMesh( object, camera );

			} else if ( object instanceof THREE.Line ) {

				// TODO

				// It would be very inefficient to do lines one-by-one.

				// This will need a complete redesign from how CanvasRenderer does it.

				// Though it could be brute forced, if only used for lightweight
				// stuff (as CanvasRenderer can only handle small number of elements 
				// anyways). 

				// Heavy-duty wireframe lines are handled efficiently in mesh renderer.

			} else if ( object instanceof THREE.Particle ) {

				// TODO

				// The same as with lines, particles shouldn't be handled one-by-one.

				// Again, heavy duty particle system would require different approach,
				// like one VBO per particle system and then update attribute arrays, 
				// though the best would be to move also behavior computation
				// into the shader (ala http://spidergl.org/example.php?id=11)

			}

N
Nicolas Garcia Belmonte 已提交
638 639 640
		}

	};
641 642 643 644 645 646 647 648 649 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
	
	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 已提交
676 677 678 679 680

	function initGL() {

		try {

U
unknown 已提交
681
			_gl = _canvas.getContext( 'experimental-webgl', { antialias: true} );
N
Nicolas Garcia Belmonte 已提交
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697

		} 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 );

698 699
		_gl.frontFace( _gl.CCW );
		_gl.cullFace( _gl.BACK );
700
		_gl.enable( _gl.CULL_FACE );
701
		
N
Nicolas Garcia Belmonte 已提交
702
		_gl.enable( _gl.BLEND );
U
unknown 已提交
703
		//_gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
N
Nicolas Garcia Belmonte 已提交
704
		// _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE ); // cool!
705
		_gl.blendFunc( _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
N
Nicolas Garcia Belmonte 已提交
706 707
		_gl.clearColor( 0, 0, 0, 0 );

708
	};
N
Nicolas Garcia Belmonte 已提交
709

710 711 712
	function generateFragmentShader( maxDirLights, maxPointLights ) {
	
		var chunks = [
713

714 715 716
			"#ifdef GL_ES",
			"precision highp float;",
			"#endif",
717 718 719 720
		
			maxDirLights   ? "#define MAX_DIR_LIGHTS " + maxDirLights     : "",
			maxPointLights ? "#define MAX_POINT_LIGHTS " + maxPointLights : "",
		
721
			"uniform int material;", // 0 - Basic, 1 - Lambert, 2 - Phong, 3 - Depth, 4 - Normal
722

A
alteredq 已提交
723 724 725
			"uniform bool enableMap;",
		
			"uniform sampler2D tMap;",
726
			"uniform vec4 mColor;",
727
			"uniform float mOpacity;",
728

729
			"uniform vec4 mAmbient;",
730
			"uniform vec4 mSpecular;",
731
			"uniform float mShininess;",
732

733 734 735 736
			"uniform float m2Near;",
			"uniform float mFarPlusNear;",
			"uniform float mFarMinusNear;",
			
737 738 739 740 741 742
			"uniform int pointLightNumber;",
			"uniform int directionalLightNumber;",
			
			maxDirLights ? "uniform mat4 viewMatrix;" : "",
			maxDirLights ? "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];" : "",
			
743
			"varying vec3 vNormal;",
744 745
			"varying vec2 vUv;",
			
746 747
			"varying vec3 vLightWeighting;",

748 749
			maxPointLights ? "varying vec3 vPointLightVector[ MAX_POINT_LIGHTS ];"     : "",
			
750
			"varying vec3 vViewPosition;",
751
			
752
			"void main() {",
753

A
alteredq 已提交
754
				"vec4 mapColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
755

A
alteredq 已提交
756 757 758 759 760
				"if ( enableMap ) {",
				
					"mapColor = texture2D( tMap, vUv );",
					
				"}",
761

762 763 764 765 766 767 768 769 770
				// Normals
				
				"if ( material == 4 ) { ",
				
					"gl_FragColor = vec4( 0.5*normalize( vNormal ) + vec3(0.5, 0.5, 0.5), mOpacity );",
				
				// Depth
				
				"} else if ( material == 3 ) { ",
771 772 773 774 775 776 777
					
					// 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;",
					
778 779 780 781
					"gl_FragColor = vec4( w, w, w, mOpacity );",
				
				// Blinn-Phong
				// based on o3d example
A
alteredq 已提交
782
				
783
				"} else if ( material == 2 ) { ", 
784 785 786 787

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

788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
					// 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 );" : "",

					maxPointLights ? "for( int i = 0; i < pointLightNumber; i++ ) {" : "",
					
					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.
					
805 806
					//"float specularCompPoint = dot( normal, pointVector ) < 0.0 || pointDotNormalHalf < 0.0 ? 0.0 : pow( pointDotNormalHalf, mShininess );",
					//"float specularCompPoint = pow( pointDotNormalHalf, mShininess );",
807
					//"float pointSpecularWeight = pointDotNormalHalf < 0.0 ? 0.0 : pow( pointDotNormalHalf, mShininess );",
808

809 810
					// Ternary conditional inside for loop breaks Chrome shader linking.
					// Must do it with if.
811

812 813 814 815
					maxPointLights ? 	"float pointSpecularWeight = 0.0;" : "",
					maxPointLights ? 	"if ( pointDotNormalHalf >= 0.0 )" : "",
					maxPointLights ? 		"pointSpecularWeight = pow( pointDotNormalHalf, mShininess );" : "",
						
A
alteredq 已提交
816
					maxPointLights ? 	"pointDiffuse  += mColor * pointDiffuseWeight;" : "",
817 818 819
					maxPointLights ? 	"pointSpecular += mSpecular * pointSpecularWeight;" : "",
						
					maxPointLights ? "}" : "",
820

821 822 823 824 825 826
					// 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 );" : "",
					
					maxDirLights ? "for( int i = 0; i < directionalLightNumber; i++ ) {" : "",
827

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

830 831 832 833
					maxDirLights ? 		"vec3 dirVector = normalize( lDirection.xyz );" : "",
					maxDirLights ? 		"vec3 dirHalfVector = normalize( lDirection.xyz + vViewPosition );" : "",
						
					maxDirLights ? 		"float dirDotNormalHalf = dot( normal, dirHalfVector );" : "",
834

835 836 837 838 839
					maxDirLights ? 		"float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );" : "",  
						
					maxDirLights ? 		"float dirSpecularWeight = 0.0;" : "",
					maxDirLights ? 		"if ( dirDotNormalHalf >= 0.0 )" : "",
					maxDirLights ? 			"dirSpecularWeight = pow( dirDotNormalHalf, mShininess );" : "",
840

A
alteredq 已提交
841
					maxDirLights ? 		"dirDiffuse  += mColor * dirDiffuseWeight;" : "",
842 843 844 845 846 847 848 849 850 851 852 853
					maxDirLights ? 		"dirSpecular += mSpecular * dirSpecularWeight;" : "",

					maxDirLights ? "}" : "",

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

					// looks nicer with weighting
					
A
alteredq 已提交
854
					"gl_FragColor = vec4( mapColor.rgb * totalLight.xyz * vLightWeighting, mapColor.a );",
855

A
alteredq 已提交
856
				// Lambert: diffuse lighting
857
				
858
				"} else if ( material == 1 ) {", 
859

A
alteredq 已提交
860
					"gl_FragColor = vec4( mColor.rgb * mapColor.rgb * vLightWeighting, mColor.a * mapColor.a );",
861

A
alteredq 已提交
862
				// Basic: unlit color / texture
863
				
864 865
				"} else {", 

A
alteredq 已提交
866
					"gl_FragColor = mColor * mapColor;",
867
					
868 869
				"}",

870 871 872 873 874 875 876 877 878 879 880 881 882
			"}" ];
			
		return chunks.join("\n");
		
	};
	
	function generateVertexShader( maxDirLights, maxPointLights ) {
		
		var chunks = [
			
			maxDirLights   ? "#define MAX_DIR_LIGHTS " + maxDirLights     : "",
			maxPointLights ? "#define MAX_POINT_LIGHTS " + maxPointLights : "",
			
883 884
			"attribute vec3 position;",
			"attribute vec3 normal;",
885
			"attribute vec2 uv;",
886

887 888
			"uniform vec3 cameraPosition;",

889
			"uniform bool enableLighting;",
890 891 892 893
			
			"uniform int pointLightNumber;",
			"uniform int directionalLightNumber;",
			
894
			"uniform vec3 ambientLightColor;",
895 896 897
			
			maxDirLights ? "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];"     : "",
			maxDirLights ? "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];" : "",
898

899 900
			maxPointLights ? "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];"    : "",
			maxPointLights ? "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];" : "",
901

902
			"uniform mat4 objMatrix;",
903
			"uniform mat4 viewMatrix;",
904
			"uniform mat4 modelViewMatrix;",
905
			"uniform mat4 projectionMatrix;",
906
			"uniform mat3 normalMatrix;",
907 908

			"varying vec3 vNormal;",
909
			"varying vec2 vUv;",
910
			
911
			"varying vec3 vLightWeighting;",
912

913 914
			maxPointLights ? "varying vec3 vPointLightVector[ MAX_POINT_LIGHTS ];"     : "",
			
915
			"varying vec3 vViewPosition;",
916 917
			
			"varying vec3 vFragPosition;",
918

919
			"void main(void) {",
920

921 922 923 924
				// world space
				
				"vec4 mPosition = objMatrix * vec4( position, 1.0 );",
				"vViewPosition = cameraPosition - mPosition.xyz;",
925
				
926 927
				// eye space
				
928
				"vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
929
				"vec3 transformedNormal = normalize( normalMatrix * normal );",
930

931
				"if ( !enableLighting ) {",
932

933
					"vLightWeighting = vec3( 1.0, 1.0, 1.0 );",
934 935 936

				"} else {",

937 938 939 940 941 942
					"vLightWeighting = ambientLightColor;",
					
					// directional lights
					
					maxDirLights ? "for( int i = 0; i < directionalLightNumber; i++ ) {" : "",
					maxDirLights ?		"vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );" : "",
943
					maxDirLights ?		"float directionalLightWeighting = max( dot( transformedNormal, normalize(lDirection.xyz ) ), 0.0 );" : "",
944 945 946 947 948 949 950 951 952 953 954
					maxDirLights ?		"vLightWeighting += directionalLightColor[ i ] * directionalLightWeighting;" : "",
					maxDirLights ? "}" : "",
					
					// point lights
					
					maxPointLights ? "for( int i = 0; i < pointLightNumber; i++ ) {" : "",
					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 ? "}" : "",
955
					
956
				"}",
957

958
				"vNormal = transformedNormal;",
959
				"vUv = uv;",
960

961
				"gl_Position = projectionMatrix * mvPosition;",
962

963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
			"}" ];
			
		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 已提交
978 979 980 981 982 983 984

		_gl.linkProgram( _program );

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

			alert( "Could not initialise shaders" );

985 986
			//alert( "VALIDATE_STATUS: " + _gl.getProgramParameter( _program, _gl.VALIDATE_STATUS ) );
			//alert( _gl.getError() );
N
Nicolas Garcia Belmonte 已提交
987
		}
988
		
N
Nicolas Garcia Belmonte 已提交
989 990 991

		_gl.useProgram( _program );

992 993
		// matrices
		
N
Nicolas Garcia Belmonte 已提交
994
		_program.viewMatrix = _gl.getUniformLocation( _program, "viewMatrix" );
995
		_program.modelViewMatrix = _gl.getUniformLocation( _program, "modelViewMatrix" );
N
Nicolas Garcia Belmonte 已提交
996
		_program.projectionMatrix = _gl.getUniformLocation( _program, "projectionMatrix" );
997
		_program.normalMatrix = _gl.getUniformLocation( _program, "normalMatrix" );
998
		_program.objMatrix = _gl.getUniformLocation( _program, "objMatrix" );
N
Nicolas Garcia Belmonte 已提交
999

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

1002 1003
		// lights
		
A
alteredq 已提交
1004
		_program.enableLighting = _gl.getUniformLocation( _program, 'enableLighting' );
1005
		
A
alteredq 已提交
1006
		_program.ambientLightColor = _gl.getUniformLocation( _program, 'ambientLightColor' );
1007 1008 1009
		
		if ( maxDirLights ) {
			
A
alteredq 已提交
1010 1011 1012
			_program.directionalLightNumber = _gl.getUniformLocation( _program, 'directionalLightNumber' );
			_program.directionalLightColor = _gl.getUniformLocation( _program, 'directionalLightColor' );
			_program.directionalLightDirection = _gl.getUniformLocation( _program, 'directionalLightDirection' );
1013 1014
			
		}
1015

1016 1017
		if ( maxPointLights ) {
			
A
alteredq 已提交
1018 1019 1020
			_program.pointLightNumber = _gl.getUniformLocation( _program, 'pointLightNumber' );
			_program.pointLightColor = _gl.getUniformLocation( _program, 'pointLightColor' );
			_program.pointLightPosition = _gl.getUniformLocation( _program, 'pointLightPosition' );
1021 1022
			
		}
U
unknown 已提交
1023

1024 1025
		// material
		
A
alteredq 已提交
1026
		_program.material = _gl.getUniformLocation( _program, 'material' );
1027
		
A
alteredq 已提交
1028
		// material properties (Basic / Lambert / Blinn-Phong shader)
1029
		
A
alteredq 已提交
1030
		_program.mColor = _gl.getUniformLocation( _program, 'mColor' );
1031
		_program.mOpacity = _gl.getUniformLocation( _program, 'mOpacity' );
1032

1033 1034
		// material properties (Blinn-Phong shader)
		
A
alteredq 已提交
1035 1036 1037
		_program.mAmbient = _gl.getUniformLocation( _program, 'mAmbient' );
		_program.mSpecular = _gl.getUniformLocation( _program, 'mSpecular' );
		_program.mShininess = _gl.getUniformLocation( _program, 'mShininess' );
1038

A
alteredq 已提交
1039 1040 1041 1042
		// texture (diffuse map)
		
		_program.enableMap = _gl.getUniformLocation( _program, "enableMap" );
		_gl.uniform1i( _program.enableMap,  0 );
1043
		
A
alteredq 已提交
1044 1045
		_program.tMap = _gl.getUniformLocation( _program, "tMap" );
		_gl.uniform1i( _program.tMap,  0 );
1046

1047 1048 1049 1050 1051 1052
		// material properties (Depth)
		
		_program.m2Near = _gl.getUniformLocation( _program, 'm2Near' );
		_program.mFarPlusNear = _gl.getUniformLocation( _program, 'mFarPlusNear' );
		_program.mFarMinusNear = _gl.getUniformLocation( _program, 'mFarMinusNear' );
		
1053 1054
		// vertex arrays
		
N
Nicolas Garcia Belmonte 已提交
1055 1056 1057
		_program.position = _gl.getAttribLocation( _program, "position" );
		_gl.enableVertexAttribArray( _program.position );

1058 1059
		_program.normal = _gl.getAttribLocation( _program, "normal" );
		_gl.enableVertexAttribArray( _program.normal );
1060

U
unknown 已提交
1061 1062 1063 1064
		_program.uv = _gl.getAttribLocation( _program, "uv" );
		_gl.enableVertexAttribArray( _program.uv );


N
Nicolas Garcia Belmonte 已提交
1065
		_program.viewMatrixArray = new Float32Array(16);
1066
		_program.modelViewMatrixArray = new Float32Array(16);
N
Nicolas Garcia Belmonte 已提交
1067
		_program.projectionMatrixArray = new Float32Array(16);
N
Nicolas Garcia Belmonte 已提交
1068

1069
	};
N
Nicolas Garcia Belmonte 已提交
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095

	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;
1096 1097
		
	};
N
Nicolas Garcia Belmonte 已提交
1098

A
alteredq 已提交
1099
	/* DEBUG
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
	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 已提交
1129 1130
	*/

N
Nicolas Garcia Belmonte 已提交
1131
};