-
Notifications
You must be signed in to change notification settings - Fork 0
/
rootworld.js
134 lines (134 loc) · 69.3 KB
/
rootworld.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
var Env={world:null,hud:null,gl:null,client:null,setEnvironment:function(a,b,c,d){Env.world=a;Env.hud=b;Env.gl=c;Env.client=d||null}};var FullWindowResizer=function(a,b,c,d){this.gl=a;this.glCanvas=b;this.hud=c;this.hudCanvas=d};FullWindowResizer.prototype.resize=function(){this.glCanvas.width=window.innerWidth;this.glCanvas.height=window.innerHeight;this.gl.viewportWidth=window.innerWidth;this.gl.viewportHeight=window.innerHeight;this.hudCanvas.width=window.innerWidth;this.hudCanvas.height=window.innerHeight;this.hud.resize();this.hud.render()};
FullWindowResizer.prototype.attachEventListener=function(){window.addEventListener("resize",util.bind(this.resize,this))};var Types={constructors_:{},registerType:function(a,b){a.type=b;a.getType=function(){return b};Types.constructors_[b]=a},getConstructor:function(a){return Types.constructors_[a]}};var World=function(){this.lights=[];this.camera=null;this.collisionManager=new CollisionManager(this);this.age=0;this.drawables=new ControlledList;this.transluscent=[];this.opaque=[];this.things=new ControlledList;this.projectiles=new ControlledList;this.effects=new ControlledList;this.disposables=[];this.backgroundColor=[1,1,1,1];this.sortBeforeDrawing=!0;this.paused=!1;this.thingsById={};this.stateSet=!1;this.thingsByType={}};World.prototype.populate=function(){};
World.prototype.onPauseChanged=function(a){};World.prototype.setSortBeforeDrawing=function(a){this.sortBeforeDrawing=a};World.prototype.setCollisionManager=function(a){this.collisionManager=a};World.prototype.getCamera=function(){return this.camera};World.prototype.setCamera=function(a){this.camera=a};World.prototype.addThing=function(a){this.addDrawable(a);this.things.add(a);this.thingsById[a.id]=a;var b=a.getType();this.thingsByType[b]||(this.thingsByType[b]=new ControlledList);this.thingsByType[b].add(a)};
World.prototype.removeObject=function(a){this.removeDrawable(a);var b=a.getType();this.getThingsByType(b).remove(a)};World.prototype.removeThing=function(a){this.things.remove(a);this.removeObject(a)};World.prototype.removeProjectile=function(a){this.projectiles.remove(a);this.removeObject(a)};World.prototype.addProjectile=function(a){this.addDrawable(a);this.projectiles.add(a)};World.prototype.addEffect=function(a){this.addDrawable(a);this.effects.add(a)};World.prototype.addDrawable=function(a){this.drawables.add(a)};
World.prototype.removeDrawable=function(a){this.drawables.remove(a)};World.prototype.getThingsByType=function(a){return this.thingsByType[a]||ControlledList.EMTPY_LIST};World.prototype.getThingsByClass=function(a){return this.getThingsByType(a.getType())};
World.prototype.draw=function(){Env.gl.reset(this.backgroundColor);Env.gl.pushViewMatrix();this.applyLights();this.camera.transform();Env.gl.setViewMatrixUniforms();if(this.sortBeforeDrawing){var a=this.camera.getPosition();this.transluscent.length=0;this.opaque.length=0;this.drawables.forEach(function(b){b.isDisposed||(b.computeDistanceSquaredToCamera(a),b.transluscent?this.transluscent.push(b):this.opaque.push(b))},this);this.opaque.sort(function(a,b){return a.distanceSquaredToCamera-b.distanceSquaredToCamera});
this.transluscent.sort(function(a,b){return b.distanceSquaredToCamera-a.distanceSquaredToCamera});for(var b=0;this.opaque[b];b++)this.opaque[b].draw();for(b=0;this.transluscent[b];b++)this.transluscent[b].draw()}else for(b=0;this.drawables.get(b);b++)this.drawables.get(b).draw();Env.gl.popViewMatrix()};World.prototype.advance=function(a){this.advanceBasics(a)};
World.prototype.advanceBasics=function(a){this.age+=a;this.updateLists();if(!this.paused){for(var b=0;this.things.get(b);b++)this.things.get(b).isDisposed||this.things.get(b).advance(a);for(b=0;this.projectiles.get(b);b++)this.projectiles.get(b).isDisposed||this.projectiles.get(b).advance(a);for(b=0;this.effects.get(b);b++)this.effects.get(b).isDisposed||this.effects.get(b).advance(a);this.collisionManager&&this.collisionManager.checkCollisions()}};World.prototype.addLight=function(a){this.lights.push(a)};
World.prototype.applyLights=function(){for(var a=0,b;b=this.lights[a];a++)b.apply()};World.prototype.reset=function(){this.things=[];this.effects=[];this.projectiles=[];this.populate()};World.prototype.updateLists=function(){this.things.update();this.effects.update();this.projectiles.update();this.drawables.update();for(util.object.forEach(this.thingsByType,function(a){a.update()});100<this.disposables.length;)this.disposables.shift().dispose()};
World.prototype.setBackgroundColor=function(a){this.backgroundColor=a};World.prototype.setState=function(a){a.performAddRemove();for(var b=a.readInt(),c=0;c<b;c++){var d=a.readInt(),e=a.readByte(),d=Types.getConstructor(e).newFromReader(a).setId(d);d.alive&&this.addThing(d)}a.checkSync();this.stateSet=!0;this.updateLists()};World.prototype.updateWorld=function(a){a.performAddRemove();for(var b=a.readInt(),c=0;c<b;c++){var d=a.readInt(),d=this.getThing(d),e=a.readByte();d?d.updateFromReader(a):Types.getConstructor(e).newFromReader(a)}a.checkSync()};
World.prototype.getThing=function(a){return this.thingsById[a]};World.prototype.hasThing=function(a){return Boolean(this.thingsById[a])};World.prototype.registerCollisionCondition=function(a,b,c,d){this.collisionManager.registerCollisionCondition(a,b,c,d)};var Camera=function(){};Camera.prototype.getPosition=function(){};Camera.prototype.transform=function(){};var MessageCode={GET_STATE:1,SET_STATE:2,GET_BOARD:3,SET_BOARD:4,UPDATE_WORLD:5,JOIN:6,YOU_ARE:7,KEY_EVENT:8,MOUSE_MOVE_EVENT:9,SCORE:11,NAME_MAP:12,MY_NAME_IS:13,RESTART:14,MODE:15,SAY:16,BROADCAST:17,SYNC:98,EOM:99,MY_SCORE_IS:51,LEFT_CLICK_EVENT:101,RIGHT_CLICK_EVENT:102};var Messages={readNameMapMessage:function(a){for(var b={},c=a.readInt(),d=0;d<c;d++){var e=a.readInt(),g=a.readString(),f=a.readInt();b[e]={name:g,unitId:f}}return b},readScoreMessage:function(a){for(var b=[],c=a.readInt(),d=0;d<c;d++){var e=a.readInt(),g=a.readInt();b.push([e,g])}return b}};var Reader=function(a){this.position=0;this.buffer=a;this.view=new DataView(this.buffer)};Reader.prototype.readFloat=function(){var a=this.view.getFloat32(this.position);this.position+=4;return a};Reader.prototype.readInt=function(){var a=this.view.getInt32(this.position);this.position+=4;return a};Reader.prototype.readShort=function(){var a=this.view.getInt16(this.position);this.position+=2;return a};Reader.prototype.readByte=function(){var a=this.view.getInt8(this.position);this.position++;return a};
Reader.prototype.readString=function(){var a=this.readInt(),b=String.fromCharCode.apply(null,new Uint8Array(this.buffer,this.position,a));this.position+=a;return b};Reader.prototype.checkSync=function(){this.checkCode(MessageCode.SYNC,"Sync")};Reader.prototype.checkEOM=function(){this.checkCode(MessageCode.EOM,"EOM")};Reader.prototype.checkCode=function(a,b){var c=this.readByte();if(c!=a)throw Error("checkCode failled on "+(b||a)+". Got "+c);};
Reader.prototype.checkIntCode=function(a,b){var c=this.readInt();if(c!=a)throw Error("checkCode failled on "+(b||a)+". Got "+c);};Reader.prototype.readThingMessage=function(){var a=this.readByte(),b=Types.getConstructor(a);if(b)return b.readMessage(this);throw Error("Don't recognize "+a);};Reader.prototype.readThing=function(){var a=this.readThingMessage();return new a.klass(a)};
Reader.prototype.readVec3=function(a){a=a||vec3.create();a[0]=this.readFloat();a[1]=this.readFloat();a[2]=this.readFloat();return a};Reader.prototype.readVec4=function(a){a=a||vec4.create();a[0]=this.readFloat();a[1]=this.readFloat();a[2]=this.readFloat();a[3]=this.readFloat();return a};
Reader.prototype.performAddRemove=function(){for(var a=this.readInt(),b=0;b<a;b++){var c=this.readInt(),d=this.readByte(),d=Types.getConstructor(d).newFromReader(this).setId(c);!Env.world.hasThing(c)&&d.alive&&Env.world.addThing(d)}this.checkSync();a=this.readInt();for(b=0;b<a;b++)c=this.readInt(),d=Env.world.thingsById[c],Env.world.thingsById[c]&&Env.world.removeThing(d);this.checkSync()};var WritableType={};var Writer=function(a){this.offset=0;this.buffer=new ArrayBuffer(a);this.byteView=new DataView(this.buffer)};Writer.prototype.writeInt8=function(a){this.byteView.setInt8(this.offset,a);this.offset++};Writer.prototype.writeInt16=function(a){this.byteView.setInt16(this.offset,a);this.offset+=2};Writer.prototype.writeString=function(a){for(var b=0,c=a.length;b<c;b++)this.writeInt8(a.charCodeAt(b))};Writer.prototype.getBytes=function(){return new Int8Array(this.buffer)};var GL=WebGLRenderingContext;GL.createGL=function(a){var b;try{b=a.getContext("experimental-webgl")}catch(c){throw Error("Didn't init GL");}b.viewportWidth=a.width;b.viewportHeight=a.height;b.modelMatrix=mat4.create();b.invertedModelMatrix=mat4.create();b.viewMatrix=mat4.create();b.perspectiveMatrix=mat4.create();b.normalMatrix=mat3.create();b.modelMatrixStack=new MatrixStack;b.viewMatrixStack=new MatrixStack;b.canvas=a;b.activeShaderProgram=null;return b};
GL.createGLWithDefaultShaders=function(a){a=GL.createGL(a);var b=ShaderProgram.createProgramWithDefaultShaders(a);a.setActiveProgram(b);return a};GL.prototype.setActiveProgram=function(a){this.activeShaderProgram=a;this.useProgram(a)};GL.prototype.getActiveProgram=function(){return this.activeShaderProgram};
GL.prototype.reset=function(a){util.assert(0==this.modelMatrixStack.nextIndex,"Model matrix stack not fully unloaded");util.assert(0==this.viewMatrixStack.nextIndex,"View matrix stack not fully unloaded");this.viewport(0,0,this.viewportWidth,this.viewportHeight);this.clearColor(a[0],a[1],a[2],a[3]);this.clear(GL.COLOR_BUFFER_BIT|GL.DEPTH_BUFFER_BIT);mat4.perspective(this.perspectiveMatrix,Math.PI/4,this.viewportWidth/this.viewportHeight,.1,1E4);this.enable(GL.DEPTH_TEST);this.enable(GL.BLEND);this.enable(GL.CULL_FACE);
this.blendFunc(GL.SRC_ALPHA,GL.ONE_MINUS_SRC_ALPHA);mat4.identity(this.modelMatrix);this.getActiveProgram().reset()};GL.prototype.pushModelMatrix=function(){this.modelMatrixStack.push(this.modelMatrix)};GL.prototype.popModelMatrix=function(){mat4.copy(this.modelMatrix,this.modelMatrixStack.pop())};GL.prototype.pushViewMatrix=function(){this.viewMatrixStack.push(this.viewMatrix)};GL.prototype.popViewMatrix=function(){mat4.copy(this.viewMatrix,this.viewMatrixStack.pop())};
GL.prototype.setModelMatrixUniforms=function(){var a=this.getActiveProgram();this.computeNormalMatrix();this.uniformMatrix4fv(a.modelMatrixUniform,!1,this.modelMatrix);this.uniformMatrix3fv(a.normalMatrixUniform,!1,this.normalMatrix)};GL.prototype.setViewMatrixUniforms=function(){var a=this.getActiveProgram();this.uniformMatrix4fv(a.perspectiveMatrixUniform,!1,this.perspectiveMatrix);this.uniformMatrix4fv(a.viewMatrixUniform,!1,this.viewMatrix)};
GL.prototype.computeNormalMatrix=function(){mat3.fromMat4(this.normalMatrix,mat4.invert(this.invertedModelMatrix,this.modelMatrix));mat3.transpose(this.normalMatrix,this.normalMatrix)};GL.prototype.rotate=function(){var a=mat4.create();return function(b){mat4.multiply(this.modelMatrix,this.modelMatrix,mat4.fromQuat(a,b))}}();GL.prototype.translate=function(a){mat4.translate(this.modelMatrix,this.modelMatrix,a)};GL.prototype.transform=function(a){mat4.multiply(this.modelMatrix,this.modelMatrix,a)};
GL.prototype.rotateView=function(){var a=mat4.create();return function(b){mat4.multiply(this.viewMatrix,this.viewMatrix,mat4.fromQuat(a,b))}}();GL.prototype.translateView=function(a){mat4.translate(this.viewMatrix,this.viewMatrix,a)};GL.prototype.updateBuffer=function(a,b){this.bindBuffer(GL.ARRAY_BUFFER,a);this.bufferSubData(GL.ARRAY_BUFFER,0,new Float32Array(b))};
GL.prototype.generateBuffer=function(a,b,c,d){d=d||GL.STATIC_DRAW;c=c||GL.ARRAY_BUFFER;var e=this.createBuffer();this.bindBuffer(c,e);this.bufferData(c,new Float32Array(a),d);e.itemSize=b;e.numItems=a.length/b;return e};GL.prototype.generateIndexBuffer=function(a){var b=this.createBuffer();this.bindBuffer(GL.ELEMENT_ARRAY_BUFFER,b);this.bufferData(GL.ELEMENT_ARRAY_BUFFER,new Uint16Array(a),GL.STATIC_DRAW);b.itemSize=1;b.numItems=a.length;return b};var MatrixStack=function(){this.stack=[];this.nextIndex=0};MatrixStack.prototype.push=function(a){this.stack[this.nextIndex]?mat4.copy(this.stack[this.nextIndex],a):this.stack.push(mat4.clone(a));this.nextIndex++};MatrixStack.prototype.pop=function(){this.nextIndex--;if(-1==this.nextIndex)throw Error("Invalid matrix pop!");return this.stack[this.nextIndex]};var ShaderProgram=function(){};ShaderProgram.USE_TEXTURE_DEFAULT=!1;ShaderProgram.USE_LIGHTING_DEFAULT=!0;ShaderProgram.UNIFORM_COLOR_DEFAULT=[1,1,1,1];ShaderProgram.UNIFORM_SCALE_DEFAULT=[1,1,1];ShaderProgram.defaultDomain="http://www.biologicalspeculation.com";ShaderProgram.loadExternalShader=function(a,b,c){var d=new XMLHttpRequest;d.open("GET",b,!1);d.send();return ShaderProgram.createShader(a,d.responseText,c)};
ShaderProgram.createShader=function(a,b,c){c=a.createShader(c);a.shaderSource(c,b);a.compileShader(c);return a.getShaderParameter(c,a.COMPILE_STATUS)?c:(alert(a.getShaderInfoLog(c)),null)};
ShaderProgram.createProgramWithDefaultShaders=function(a){var b=ShaderProgram.loadExternalShader(a,ShaderProgram.defaultDomain+"/worldJS/shaders/fragment.shader",a.FRAGMENT_SHADER),c=ShaderProgram.loadExternalShader(a,ShaderProgram.defaultDomain+"/worldJS/shaders/vertex.shader",a.VERTEX_SHADER);return ShaderProgram.createShaderProgram(a,c,b)};
ShaderProgram.createShaderProgram=function(a,b,c){var d=a.createProgram();d.gl=a;a.attachShader(d,b);a.attachShader(d,c);a.linkProgram(d);a.getProgramParameter(d,a.LINK_STATUS)||alert("Could not initialise shaders");a.useProgram(d);d.vertexPositionAttribute=a.getAttribLocation(d,"aVertexPosition");d.vertexPositionAttribute=a.getAttribLocation(d,"aVertexPosition");d.vertexNormalAttribute=a.getAttribLocation(d,"aVertexNormal");d.textureCoordAttribute=a.getAttribLocation(d,"aTextureCoord");a.enableVertexAttribArray(d.vertexPositionAttribute);
a.enableVertexAttribArray(d.vertexPositionAttribute);a.enableVertexAttribArray(d.vertexNormalAttribute);a.enableVertexAttribArray(d.textureCoordAttribute);d.perspectiveMatrixUniform=a.getUniformLocation(d,"uPerspectiveMatrix");d.modelMatrixUniform=a.getUniformLocation(d,"uModelMatrix");d.viewMatrixUniform=a.getUniformLocation(d,"uViewMatrix");d.normalMatrixUniform=a.getUniformLocation(d,"uNormalMatrix");d.samplerUniform=a.getUniformLocation(d,"uSampler");d.ambientColorUniform=a.getUniformLocation(d,
"uAmbientColor");d.pointLightingLocationUniform=a.getUniformLocation(d,"uPointLightingLocation");d.eyeLocationUniform=a.getUniformLocation(d,"uEyeLocation");d.pointLightingColorUniform=a.getUniformLocation(d,"uPointLightingColor");d.useLightingUniform=a.getUniformLocation(d,"uUseLighting");d.useTextureUniform=a.getUniformLocation(d,"uUseTexture");d.uniformColor=a.getUniformLocation(d,"uColor");d.uniformScale=a.getUniformLocation(d,"uScale");for(var e in ShaderProgram.prototype)d[e]=ShaderProgram.prototype[e];
d.loadedTexture=-1;d.loadedColor=[];d.loadedScale=[];d.loadedNormalBuffer=null;d.loadedIndexBuffer=null;d.loadedPositionBuffer=null;d.loadedTextureBuffer=null;d.isUsingTexture=!1;return d};ShaderProgram.prototype.reset=function(){this.setUseLighting(ShaderProgram.USE_LIGHTING_DEFAULT);this.setUseTexture(ShaderProgram.USE_TEXTURE_DEFAULT);this.setUniformColor(ShaderProgram.UNIFORM_COLOR_DEFAULT);this.setUniformScale(ShaderProgram.UNIFORM_SCALE_DEFAULT)};
ShaderProgram.prototype.setUseLighting=function(a){this.gl.uniform1i(this.useLightingUniform,a)};ShaderProgram.prototype.setUseTexture=function(a){a!=this.isUsingTexture&&(this.gl.uniform1i(this.useTextureUniform,a),this.isUsingTexture=a)};ShaderProgram.prototype.setUniformColor=function(a){vec4.equals(a,this.loadedColor)||(this.loadedColor=a,this.gl.uniform4fv(this.uniformColor,a))};
ShaderProgram.prototype.setUniformScale=function(a){vec4.equals(a,this.loadedScale)||(this.loadedScale=a,this.gl.uniform3fv(this.uniformScale,a))};ShaderProgram.prototype.bindVertexPositionBuffer=function(a){this.loadedPositionBuffer!=a&&(this.loadedPositionBuffer=a,this.bindAttributeBuffer_(a,this.vertexPositionAttribute))};ShaderProgram.prototype.bindVertexNormalBuffer=function(a){this.loadedNormalBuffer!=a&&(this.loadedNormalBuffer=a,this.bindAttributeBuffer_(a,this.vertexNormalAttribute))};
ShaderProgram.prototype.bindVertexTextureBuffer=function(a){this.loadedTextureBuffer!=a&&(this.loadedTextureBuffer=a,this.bindAttributeBuffer_(a,this.textureCoordAttribute))};ShaderProgram.prototype.bindVertexIndexBuffer=function(a){this.loadedIndexBuffer!=a&&(this.loadedIndexBuffer=a,this.gl.bindBuffer(GL.ELEMENT_ARRAY_BUFFER,a))};ShaderProgram.prototype.bindAttributeBuffer_=function(a,b){this.gl.bindBuffer(GL.ARRAY_BUFFER,a);this.gl.vertexAttribPointer(b,a.itemSize,GL.FLOAT,!1,0,0)};
ShaderProgram.prototype.bindTexture=function(a){this.loadedTexture!=a&&(this.loadedTexture=a,this.gl.activeTexture(GL.TEXTURE0),this.gl.bindTexture(GL.TEXTURE_2D,a))};var ContainerManager=function(a,b){this.fullscreenContainer=a;this.container=b;this.keyMap={};this.mouseMap={};this.resolvePrefixes();this.container.addEventListener("keydown",util.bind(this.onKey,this));this.container.addEventListener("keyup",util.bind(this.onKey,this));this.container.addEventListener("mousedown",util.bind(this.onMouseButton,this));this.container.addEventListener("mouseup",util.bind(this.onMouseButton,this));this.fullscreen=!1;this.container.focus()};ContainerManager.instance_=null;
ContainerManager.initSingleton=function(a,b){util.assertNull(ContainerManager.instance_,"Cannot init ContainerManager: already init'd");ContainerManager.instance_=new ContainerManager(a,b);return ContainerManager.instance_};ContainerManager.getInstance=function(){return ContainerManager.instance_};ContainerManager.prototype.onKey=function(a){this.keyMap[a.keyCode]="keydown"==a.type};ContainerManager.prototype.onMouseButton=function(a){this.keyMap[a.button]="mousedown"==a.type};
ContainerManager.prototype.isKeyDown=function(a){return this.keyMap[a]};ContainerManager.prototype.isMouseButtonDown=function(a){return this.mouseMap[a]};ContainerManager.prototype.setFullScreen=function(a){a?this.fullscreenContainer.requestFullScreen(Element.ALLOW_KEYBOARD_INPUT):this.fullscreenContainer.exitFullScreen()};ContainerManager.prototype.isFullScreen=function(){return this.fullscreen};ContainerManager.prototype.setPointerLock=function(a){a?this.container.requestPointerLock():document.exitPointerLock()};
ContainerManager.prototype.isPointerLocked=function(){return Boolean(document.pointerLockElement||document.mozPointerLockElement||document.webkitPointerLockElement)};
ContainerManager.prototype.resolvePrefixes=function(){this.fullscreenContainer.requestFullScreen=this.fullscreenContainer.requestFullscreen||this.fullscreenContainer.mozRequestFullScreen||this.fullscreenContainer.webkitRequestFullscreen;this.fullscreenContainer.exitFullScreen=this.fullscreenContainer.exitFullscreen||this.fullscreenContainer.mozCancelFullScreen||this.fullscreenContainer.webkitExitFullscreen;this.container.requestPointerLock=this.container.requestPointerLock||this.container.mozRequestPointerLock||
this.container.webkitRequestPointerLock;document.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock||document.webkitExitPointerLock;document.fullScreenElement=document.fullscreenElement||document.mozFullScreenElement||document.webkitFullscreenElement};var Light=function(a){this.ambientColor=vec3.nullableClone(a.ambientColor);this.directionalColor=vec3.nullableClone(a.directionalColor);this.anchor=a.anchor;this.position=a.position};Light.prototype.setAnchor=function(a){this.anchor=a};Light.prototype.setPosition=function(a){this.position=a};Light.prototype.setAmbientColor=function(a){vec3.copy(this.ambientColor,a)};Light.prototype.setDirectionalColor=function(a){vec3.copy(this.directionalColor,a)};
Light.prototype.getPosition=function(){if(this.position)return this.position;if(this.anchor)return this.anchor.position;throw Error("Error: one of (anchor, position) should be set.");};Light.prototype.apply=function(){var a=Env.gl.getActiveProgram();Env.gl.uniform3fv(a.ambientColorUniform,this.ambientColor);Env.gl.uniform3fv(a.pointLightingLocationUniform,this.getPosition());Env.gl.uniform3fv(a.pointLightingColorUniform,this.directionalColor)};Audio.prototype.maybePlay=function(){this.currentTime=0;Sounds.on&&this.play()};var Sounds={on:!0,get:function(a,b){var c=new Audio(a);c.addEventListener("ended",function(){b&&b()},!1);return c},getAndPlay:function(a,b){var c=Sounds.get(a,b);c.addEventListener("canplaythrough",function(){c.maybePlay()},!1)}};var Textures={byPath_:{},get:function(a){return Textures.byPath_[a]},initTextures:function(a,b){var c=[],d;for(d in a)c.push(Textures.initTexture(a[d]));return Promise.all(c)},initTexture:function(a){var b=Env.gl.createTexture();Textures.byPath_[a]=b;b.image=new Image;b.loaded=!1;return new Promise(function(c,d){b.image.onload=function(){Textures.packageTexture_(b);c(null)};b.image.src=a})},packageTexture_:function(a){var b=Env.gl;b.bindTexture(GL.TEXTURE_2D,a);b.pixelStorei(GL.UNPACK_FLIP_Y_WEBGL,
!0);b.texImage2D(GL.TEXTURE_2D,0,GL.RGBA,GL.RGBA,GL.UNSIGNED_BYTE,a.image);b.texParameteri(GL.TEXTURE_2D,GL.TEXTURE_MAG_FILTER,GL.LINEAR);b.texParameteri(GL.TEXTURE_2D,GL.TEXTURE_MIN_FILTER,GL.LINEAR_MIPMAP_NEAREST);b.generateMipmap(GL.TEXTURE_2D);a.loaded=!0},getTextTexture:function(a){if(a.key){var b=Textures[a.key];if(b)return b}b=document.createElement("canvas");b.id="hiddenCanvas";b.style.display="none";b.width=64;b.height=64;document.getElementsByTagName("body")[0].appendChild(b);b=document.getElementById("hiddenCanvas");
b.width=a.width;b.height=a.height;var c=b.getContext("2d");c.beginPath();c.rect(0,0,c.canvas.width,c.canvas.height);c.fillStyle=a.backgroundColor||"rgba(255, 255, 255, 1)";c.fill();c.fillStyle=a.textColor||"rgba(0, 0, 0, 1)";c.font=a.font||"bold 60px Monaco";c.textAlign="center";c.fillText(a.text,c.canvas.width/2,c.canvas.height-10);c.restore();var c=Env.gl,d=c.createTexture();c.bindTexture(c.TEXTURE_2D,d);c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MAG_FILTER,c.LINEAR);c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MIN_FILTER,
c.LINEAR_MIPMAP_NEAREST);c.pixelStorei(c.UNPACK_FLIP_Y_WEBGL,!0);c.texImage2D(c.TEXTURE_2D,0,c.RGBA,c.RGBA,c.UNSIGNED_BYTE,b);c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MAG_FILTER,c.LINEAR);c.texParameteri(c.TEXTURE_2D,c.TEXTURE_MIN_FILTER,c.LINEAR_MIPMAP_NEAREST);c.generateMipmap(c.TEXTURE_2D);d.loaded=!0;a.key&&(Textures[a.key]=d);return d}};var ControlledList=function(){this.elements=[];this.elementsToAdd=[];this.elementsToRemove=[]};ControlledList.EMTPY_LIST=new ControlledList;ControlledList.prototype.get=function(a){return this.elements[a]};ControlledList.prototype.getAll=function(a){return this.elements};ControlledList.prototype.add=function(a){this.elementsToAdd.push(a)};ControlledList.prototype.remove=function(a){this.elementsToRemove.push(a)};ControlledList.prototype.sort=function(a){this.elements.sort(a)};
ControlledList.prototype.size=function(){return this.elements.length};ControlledList.prototype.update=function(){util.array.pushAll(this.elements,this.elementsToAdd);this.elementsToAdd.length=0;util.array.removeAll(this.elements,this.elementsToRemove);this.elementsToRemove.length=0};ControlledList.prototype.forEachCross=function(a,b,c){for(var d=0,e=this.size();d<e;d++)for(var g=this.get(d),f=0,h=a.size();f<h;f++){var k=a.get(f);b.call(c,g,k)}};
ControlledList.prototype.forEach=function(a,b){util.array.forEach(this.elements,a,b)};var Framerate=function(){this.lastTime=0;this.numFramerates=30;this.renderTime=-1;this.framerates=[];this.rollingAverage=0};Framerate.prototype.calcRollingAverage=function(){for(var a=0,b=0;this.framerates[b];b++)a+=this.framerates[b];this.rollingAverage=Math.round(a/this.framerates.length)};
Framerate.prototype.snapshot=function(){if(0>this.renderTime)this.renderTime=(new Date).getTime();else{var a=(new Date).getTime(),b=a-this.renderTime;if(0!=b){for(this.framerates.push(1E3/b);this.framerates.length>this.numFramerates;)this.framerates.shift();this.renderTime=a;this.calcRollingAverage()}}};var Animator=function(a,b,c){this.world=a;this.hud=b;this.gl=c;this.framerate=new Framerate;this.paused=!1;this.drawOnTick=!0;this.boundTick=util.bind(this.tick,this)};Animator.instance_=null;Animator.initSingleton=function(a,b,c){util.assertNull(Animator.instance_,"Cannot init Animator: already init'd");Animator.instance_=new Animator(a,b,c);return Animator.instance_};Animator.getInstance=function(){return Animator.instance_};Animator.prototype.setDrawOnTick=function(a){this.drawOnTick=a};
Animator.prototype.start=function(){this.drawScene();this.tick()};Animator.prototype.setPaused=function(a){this.paused=a;this.world.onPauseChanged(this.paused)};Animator.prototype.togglePause=function(){this.paused=!this.paused;this.world.onPauseChanged(this.paused)};Animator.prototype.isPaused=function(){return this.paused};Animator.prototype.tick=function(){window.requestAnimationFrame(this.boundTick);this.paused||(this.advanceWorld(),this.drawOnTick&&this.drawScene());this.hud.render()};
Animator.prototype.drawScene=function(){this.world.draw()};Animator.prototype.advanceWorld=function(){var a=(new Date).getTime();if(0!=this.framerate.lastTime){var b=a-this.framerate.lastTime;100>b&&(this.world.advance(b/1E3),this.framerate.snapshot())}this.framerate.lastTime=a};Animator.prototype.getRollingAverageFramerate=function(){return this.framerate.rollingAverage};
Animator.prototype.profile=function(a){this.paused=!1;console.profile();setTimeout(function(){console.profileEnd();this.paused=!0},1E3*a)};Animator.profile=function(a){Animator.getInstance().profile(a||10)};var WorldInputAdapter=function(a){this.scope=a||null;this.onPointerLockChange=this.onMouseButton=this.onKey=this.onMouseMove=util.fn.noOp;this.attachEvents()};WorldInputAdapter.prototype.isKeyDown=function(a){return ContainerManager.getInstance().isKeyDown(a)};WorldInputAdapter.prototype.isMouseButtonDown=function(a){return ContainerManager.getInstance().isMouseButtonDown(a)};WorldInputAdapter.prototype.isPointerLocked=function(){return ContainerManager.getInstance().isPointerLocked()};
WorldInputAdapter.prototype.setKeyHandler=function(a,b){this.onKey=util.bind(a,b||this.scope);return this};WorldInputAdapter.prototype.setMouseButtonHandler=function(a,b){this.onMouseButton=util.bind(a,b||this.scope);return this};WorldInputAdapter.prototype.setMouseMoveHandler=function(a,b){this.onMouseMove=util.bind(a,b||this.scope);return this};WorldInputAdapter.prototype.setPointerLockChangeHandler=function(a,b){this.onPointerLockChange=util.bind(a,b||this.scope);return this};
WorldInputAdapter.prototype.onKeyInternal_=function(a){this.onKey(a)};WorldInputAdapter.prototype.onMouseButtonInternal_=function(a){this.onMouseButton(a)};WorldInputAdapter.prototype.onMouseMoveInternal_=function(a){this.onMouseMove(a)};WorldInputAdapter.prototype.onPointerLockChangeInternal_=function(a){this.onPointerLockChange(a)};WorldInputAdapter.prototype.getMovementX=function(a){return a.movementX||a.mozMovementX||a.webkitMovementX||0};
WorldInputAdapter.prototype.getMovementY=function(a){return a.movementY||a.mozMovementY||a.webkitMovementY||0};
WorldInputAdapter.prototype.attachEvents=function(){var a=ContainerManager.getInstance().container;a.addEventListener("keydown",util.bind(this.onKeyInternal_,this),!0);a.addEventListener("keyup",util.bind(this.onKeyInternal_,this),!0);a.addEventListener("mousedown",util.bind(this.onMouseButtonInternal_,this),!0);a.addEventListener("mouseup",util.bind(this.onMouseButtonInternal_,this),!0);document.addEventListener("mousemove",util.bind(this.onMouseMoveInternal_,this),!1);document.addEventListener("pointerlockchange",
util.bind(this.onPointerLockChangeInternal_,this));document.addEventListener("mozpointerlockchange",util.bind(this.onPointerLockChangeInternal_,this));document.addEventListener("webkitpointerlockchange",util.bind(this.onPointerLockChangeInternal_,this))};vec3.ZERO=vec3.fromValues(0,0,0);vec3.I=vec3.fromValues(1,0,0);vec3.J=vec3.fromValues(0,1,0);vec3.K=vec3.fromValues(0,0,1);vec3.NEG_K=vec3.fromValues(0,0,-1);vec4.WHITE=vec4.fromValues(1,1,1,1);vec4.CYAN=vec4.fromValues(.5,1,1,1);vec3.temp=vec3.create();mat4.temp=mat4.create();quat.temp=quat.create();vec3.nullableClone=function(a){return a?vec3.clone(a):vec3.create()};vec3.equals=function(a,b){return a[0]==b[0]&&a[1]==b[1]&&a[2]==b[2]};
Float32Array.prototype.toString=function(){return"["+Array.prototype.join.call(this,", ")+"]"};vec4.equals=function(a,b){return a[0]==b[0]&&a[1]==b[1]&&a[2]==b[2]&&a[3]==b[3]};quat.equals=vec4.equals;vec4.nullableClone=function(a){return a?vec4.clone(a):vec4.create()};vec4.randomColor=function(a){a[0]=Math.random();a[1]=Math.random();a[2]=Math.random();a[3]=1;return a};quat.nullableClone=function(a){return a?quat.clone(a):quat.create()};
vec3.project=function(a,b,c){b=vec3.dot(b,c);var d=vec3.dot(c,c);return vec3.scale(a,c,b/d)};vec3.pitch=function(a){var b=a[1];a=Math.sqrt(util.math.sqr(a[0])+util.math.sqr(a[2]));return Math.atan2(b,a)};vec3.pitchTo=function(){var a=vec3.create();return function(b,c){var d=vec3.subtract(a,b,c),e=Math.sqrt(util.math.sqr(d[0])+util.math.sqr(d[2]));return Math.atan2(d[1],e)}}();
vec3.pointToLine=function(){var a=vec3.create();return function(b,c,d,e){c=vec3.subtract(a,d,c);return vec3.normalize(b,vec3.subtract(b,c,vec3.scale(b,e,vec3.dot(c,e))))}}();var Quadratic=function(a,b,c){this.a=a;this.b=b;this.c=c;this.discriminant=b*b-4*a*c};Quadratic.prototype.valueAt=function(a){return this.a*a*a+this.b*a+this.c};Quadratic.prototype.rootCount=function(){return 0<this.discriminant?2:0==this.discriminant?1:0};Quadratic.prototype.firstRoot=function(){return(-this.b-Math.sqrt(this.discriminant))/(2*this.a)};Quadratic.prototype.minT=function(){return-this.b/(2*this.a)};Quadratic.prototype.minValue=function(){return this.valueAt(this.minT())};
Quadratic.newLineToOriginQuadratic=function(a,b,c){for(var d=0,e=0,g=0,f=0;3>f;f++)d+=util.math.sqr(b[f]),e+=2*b[f]*a[f],g+=util.math.sqr(a[f]);g-=util.math.sqr(c||0);return new Quadratic(d,e,g)};Quadratic.newLineToPointQuadratic=function(a,b,c,d){for(var e=0,g=0,f=0,h=0;3>h;h++)e+=util.math.sqr(b[h]-c[h]),g+=2*(b[h]-c[h])*a[h],f+=util.math.sqr(a[h]);f-=util.math.sqr(d||0);return new Quadratic(e,g,f)};Quadratic.inFrame=function(a){return 0<=a&&1>=a};var UniqueId={nextValue_:0,generate:function(){return UniqueId.nextValue_++}};var goog={provide:function(){},require:function(){},inherits:function(a,b){function c(){}c.prototype=b.prototype;a.superClass_=b.prototype;a.prototype=new c;a.prototype.constructor=a},base:function(a,b,c){var d=arguments.callee.caller;if(d.superClass_)return d.superClass_.constructor.apply(a,Array.prototype.slice.call(arguments,1));for(var e=2<arguments.length?Array.prototype.slice.call(arguments,2):util.emptyArray_,g=!1,f=a.constructor;f;f=f.superClass_&&f.superClass_.constructor)if(f.prototype[b]===
d)g=!0;else if(g)return f.prototype[b].apply(a,e);if(a[b]===d)return a.constructor.prototype[b].apply(a,e);throw Error("goog.base called from a method of one name to a method of a different name");},global:this,scope:function(a){a.call(goog.global)}},util={getCgiParams:function(){var a={};window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(b,c,d){a[c]=d});return a},getCgiParam:function(a){return util.getCgiParams()[a]},degToRad:function(a){return a*Math.PI/180},unimplemented:function(){throw Error("Unsupported Operation");
},emptyImplementation:function(){},partial:function(a,b){var c=Array.prototype.slice.call(arguments,1);return function(){var b=Array.prototype.slice.call(arguments);b.unshift.apply(b,c);return a.apply(this,b)}},bind:function(a,b,c){var d=Array.prototype.slice.call(arguments,2);return function(){var c=Array.prototype.slice.call(arguments);c.unshift.apply(c,d);return a.apply(b,c)}},emptyArray_:[],requiredPaths_:[],require:function(a){-1==util.requiredPaths_.indexOf(a)&&(util.requiredPaths_.push(a),
document.write('<script src="/'+a+'">\x3c/script>'))},useCss:function(a){-1==util.requiredPaths_.indexOf(a)&&(util.requiredPaths_.push(a),document.write('<link rel="stylesheet" type="text/css" href="/'+a+'">'))},renderSoy:function(a,b,c){a.innerHTML=b(c)},assert:function(a,b){if(!a)throw Error(b);},assertNotNull:function(a,b){if(null===a||void 0===a)throw Error(b);},assertNull:function(a,b){if(null!==a)throw Error(b);},assertEquals:function(a,b,c){if(a!=b)throw Error(c);},style:{}};
util.style.getRgbValues=function(a){a=a.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);return{red:parseInt(a[1],10),green:parseInt(a[2],10),blue:parseInt(a[3],10)}};util.style.toRgbString=function(a){return"rgb("+a.red+", "+a.green+", "+a.blue+")"};util.dom={};util.dom.getClosest=function(a,b){for(;!util.dom.matches(a,b)&&a.parentElement;)a=a.parentElement;return util.dom.matches(a,b)?a:null};util.dom.isChild=function(a,b){for(;a!=b&&a.parentElement;)a=a.parentElement;return a==b};
util.dom.find=function(a,b){return util.array.getOnlyElement(util.dom.findAll(a,b))};util.dom.findAll=function(a,b){return Array.prototype.slice.apply((b||document).querySelectorAll(a))};util.dom.hasClass=function(a,b){return a.classList.contains(b)};util.dom.addClass=function(a,b){a.classList.add(b)};util.dom.removeClass=function(a,b){a.classList.remove(b)};
util.dom.matches=function(a,b){if(!a.parentElement)throw Error("Cannot invoke util.dom.matches on a node with no parent.");return-1!=util.dom.findAll(b,a.parentElement).indexOf(a)};util.dom.getData=function(a,b){return a.dataset[b]};util.dom.getIntData=function(a,b){return parseInt(util.dom.getData(a,b),10)};util.dom.hide=function(a){a.style.display="none"};util.fn={};util.fn.addClass=function(a){return function(b){b.classList.add(a)}};util.fn.removeClass=function(a){return function(b){b.classList.remove(a)}};
util.fn.pluck=function(a){return function(b){return b[a]}};util.fn.equals=function(a){return function(b){return b===a}};util.fn.outputEquals=function(a,b){return function(c){return a(c)===b}};util.fn.pluckEquals=function(a,b){return function(c){return c[a]===b}};util.fn.not=function(a){return function(){return!a.apply(this,arguments)}};util.fn.greaterThan=function(a){return function(b){return b>a}};util.fn.constant=function(a){return function(){return a}};
util.fn.goTo=function(a){return function(){window.location.href=a}};util.fn.noOp=function(){};util.array={};util.array.pushAll=function(a,b){Array.prototype.push.apply(a,b)};util.array.removeAll=function(a,b){for(var c=0;c<b.length;c++)util.array.remove(a,b[c])};util.array.apply=function(a,b,c,d,e){for(var g=0,f;f=a[g];g++)f[b](c,d,e)};util.array.remove=function(a,b){for(var c;-1!=(c=a.indexOf(b));)a.splice(c,1);return a};
util.array.flatten=function(a){for(var b=[],c=0;a[c];c++)a[c].flatten?a.pushAll(a[c].flatten()):b.push(a[c])};util.array.average=function(a){for(var b=0,c=a.length,d=0;d<c;d++)b+=a[d];return b/c};util.array.pluck=function(a,b){var c=[];a.forEach(function(a){c.push(a[b])});return c};util.array.forEach=function(a,b,c){for(var d=a.length,e=0;e<d;e++)b.call(c,a[e],e,a)};util.array.map=function(a,b,c){for(var d=a.length,e=[],g=0;g<d;g++)e.push(b.call(c,a[g],g,a));return e};
util.array.getOnlyElement=function(a){util.assertEquals(1,a.length,"Array must have only one element. Length: "+a.length);return a[0]};util.object={};util.object.forEach=function(a,b,c){for(var d in a)b.call(c,a[d],d,a)};util.object.toArray=function(a,b,c){var d=[];util.object.forEach(a,function(a,g,f){d.push(b.call(c,a,g,f))},c);return d};util.object.shallowClone=function(a){var b={},c;for(c in a)b[c]=a[c];return b};util.math={ROOT_2:Math.sqrt(2)};util.math.sqr=function(a){return a*a};
util.math.random=function(a,b){return Math.random()*(b-a)+a};util.math.clamp=function(a,b,c){return Math.min(Math.max(a,b),c)};var CollisionManager=function(a){this.world=a;this.collisionConditions={};this.filtered=[]};CollisionManager.prototype.registerCollisionCondition=function(a,b,c,d){a=a.type;var e=b.type;b=CollisionManager.getKey(a,e);a=CollisionManager.getKey(e,a);c=new CollisionCondition(c,d);this.collisionConditions[b]=c;this.collisionConditions[a]=c.getInverted()};CollisionManager.prototype.isRegisteredCollision=function(a,b){return Boolean(this.collisionConditions[CollisionManager.getKey(a.getType(),b.getType())])};
CollisionManager.prototype.checkCollisions=function(){this.thingOnThing();this.thingOnProjectile()};CollisionManager.prototype.thingOnProjectile=function(){for(var a=0,b;b=this.world.things.get(a);a++)for(var c=0,d;d=this.world.projectiles.get(c);c++)b.isDisposed||d.isDisposed||d.alive&&(util.math.sqr(b.getOuterRadius()+d.getOuterRadius())<b.distanceSquaredTo(d)||this.test(b,d))};
CollisionManager.prototype.thingOnThing=function(){for(var a=0,b;b=this.world.things.get(a);a++)for(var c=a+1,d;d=this.world.things.get(c);c++)this.doPerPair(b,d)};CollisionManager.prototype.doPerPair=function(a,b){if(!a.isDisposed&&!b.isDisposed&&a.ground!=b&&b.ground!=a){var c=a.distanceSquaredTo(b);util.math.sqr(a.getOuterRadius()+b.getOuterRadius())<c||this.test(a,b)}};
CollisionManager.prototype.test=function(a,b){var c=a.getType(),d=b.getType(),c=CollisionManager.getKey(c,d);(c=this.collisionConditions[c])&&c.collisionFunction(a,b)};CollisionManager.getKey=function(a,b){return 1E3*a+b};var CollisionCondition=function(a,b){this.thresholdFunction=a;this.collisionFunction=b};CollisionCondition.prototype.getInverted=function(){return new CollisionCondition(function(a,b){return this.thresholdFunction(b,a)},function(a,b,c){return this.collisionFunction(b,a,c)})};var FpsAnchor=function(){};FpsAnchor.prototype.getViewOrientation=util.unimplemented;FpsAnchor.prototype.getEyePosition=util.unimplemented;var FpsCamera=function(a){this.anchor=null;this.objectCache={conjugateViewOrientation:quat.create(),anchorPosition:vec3.create(),negatedAnchorPosition:vec3.create()}};FpsCamera.prototype.transform=function(){var a=this.objectCache,b=this.anchor.getViewOrientation(),b=quat.conjugate(a.conjugateViewOrientation,b);Env.gl.rotateView(b);b=this.getPosition();Env.gl.translateView(vec3.negate(a.negatedAnchorPosition,b));Env.gl.uniform3fv(Env.gl.getActiveProgram().eyeLocationUniform,b)};
FpsCamera.prototype.getPosition=function(){return this.anchor.getEyePosition(this.objectCache.anchorPosition)};FpsCamera.prototype.setAnchor=function(a){this.anchor=a;this.anchor.setVisible(!1)};FpsCamera.prototype.getAnchor=function(){return this.anchor};var Field=function(){this.valueSet=!1;this.value=this.getInitial()};Field.prototype.isSet=function(){return this.valueSet};Field.prototype.markUnset=function(){this.valueSet=!1};Field.prototype.markAsSet=function(){this.valueSet=!0};Field.prototype.get=function(){return this.value};Field.prototype.getInitial=util.unimplemented;var ByteField=function(){Field.call(this)};goog.inherits(ByteField,Field);ByteField.prototype.read=function(a){this.value=a.readByte();this.markAsSet()};ByteField.prototype.getInitial=function(){return 0};var FloatField=function(){Field.call(this)};goog.inherits(FloatField,Field);FloatField.prototype.read=function(a){this.markAsSet();this.value=a.readFloat()};FloatField.prototype.getInitial=function(){return 0};var IntField=function(){Field.call(this)};goog.inherits(IntField,Field);IntField.prototype.read=function(a){this.value=a.readInt();this.markAsSet()};IntField.prototype.getInitial=function(){return 0};var Proto=function(){this.fields={}};Proto.EOM=127;Proto.prototype.read=function(a){for(this.markFieldsUnset();;){var b=a.readByte();if(b==Proto.EOM)break;this.fields[b].read(a)}};Proto.prototype.addField=function(a,b){return this.fields[a]=b};Proto.prototype.markFieldsUnset=function(){util.object.forEach(this.fields,function(a){a.markUnset()});return this};var QuatField=function(){Field.call(this)};goog.inherits(QuatField,Field);QuatField.prototype.read=function(a){this.markAsSet();this.value=a.readVec4()};QuatField.prototype.getInitial=function(){return quat.create()};QuatField.prototype.copyIfSet=function(a){this.isSet()&&quat.copy(a,this.get())};var Vec3Field=function(){Field.call(this)};goog.inherits(Vec3Field,Field);Vec3Field.prototype.read=function(a){this.markAsSet();this.value=a.readVec3()};Vec3Field.prototype.getInitial=function(){return vec3.create()};Vec3Field.prototype.copyIfSet=function(a){this.isSet()&&vec3.copy(a,this.get())};var Thing=function(a){this.id=null;this.upOrientation=quat.nullableClone(a.upOrientation);quat.rotateY(this.upOrientation,this.upOrientation,a.yaw||0);quat.rotateX(this.upOrientation,this.upOrientation,a.pitch||0);quat.rotateZ(this.upOrientation,this.upOrientation,a.roll||0);this.rPitch=a.rPitch||0;this.rYaw=a.rYaw||0;this.rRoll=a.rRoll||0;this.velocityType=a.velocityType||Thing.defaultVelocityType;this.position=vec3.nullableClone(a.position);this.velocity=vec3.nullableClone(a.velocity);this.acceleration=
vec3.nullableClone(a.acceleration);this.lastPosition=vec3.clone(this.position);this.color=a.color||vec4.fromValues(1,1,1,1);this.glomOverride=null;this.scale=a.uScale?vec3.fromValues(a.uScale,a.uScale,a.uScale):a.scale||vec3.fromValues(1,1,1);a.parentScale&&(vec3.multiply(this.scale,this.scale,a.parentScale),vec3.multiply(this.position,this.position,a.parentScale));this.alive=!(!1===a.alive||0===a.alive);this.age=0;this.damageMultiplier=a.damageMultiplier||1;this.visible=!(!1===a.visible||0===a.visible);
this.parts=[];this.effects=[];this.parent=null;this.isRoot=a.isRoot||!1;this.isStatic=a.isStatic||!1;this.glommable=!1!==a.glommable;this.transluscent=!1;this.name=a.name||null;this.isDisposed=!1;this.distanceSquaredToCamera=0;this.objectCache={findEncounter:{p_0:vec3.create(),p_1:vec3.create()},normal:vec3.create(),upNose:vec3.create()}};Thing.VelocityType={ABSOLUTE:1,RELATIVE:2};Thing.defaultVelocityType=Thing.VelocityType.ABSOLUTE;Thing.prototype.setId=function(a){this.id=a;return this};
Thing.prototype.advance=function(a){this.advanceBasics(a)};
Thing.prototype.advanceBasics=function(a){if(!this.isDisposed){this.age+=a;if(this.effects.length)for(var b=0;this.effects[b];b++)this.effects[b].advance(a);this.rYaw&&quat.rotateY(this.upOrientation,this.upOrientation,this.rYaw*a);this.rPitch&&quat.rotateX(this.upOrientation,this.upOrientation,this.rPitch*a);this.rRoll&&quat.rotateZ(this.upOrientation,this.upOrientation,this.rRoll*a);if(this.velocity[0]||this.velocity[1]||this.velocity[2])this.saveLastPosition(),this.velocityType==Thing.VelocityType.RELATIVE?
vec3.scaleAndAdd(this.position,this.position,vec3.transformQuat(vec3.temp,this.velocity,this.getMovementUp()),a):(vec3.scaleAndAdd(this.position,this.position,this.velocity,a),vec3.scaleAndAdd(this.velocity,this.velocity,this.acceleration,a));if(!this.isStatic&&this.parts.length)for(b=0;this.parts[b];b++)this.parts[b].advance(a)}};Thing.prototype.getMovementUp=function(){var a=quat.create();return function(b){return quat.copy(a,this.upOrientation)}}();
Thing.prototype.getConjugateUp=function(){var a=quat.create();return function(){return quat.conjugate(a,this.upOrientation)}}();Thing.prototype.localToParentCoords=function(a,b){vec3.transformQuat(a,b,this.upOrientation);vec3.add(a,a,this.position);return a};Thing.prototype.localToParentVector=function(a,b){vec3.transformQuat(a,b,this.upOrientation);return a};
Thing.prototype.parentToLocalCoords=function(){var a=quat.create();return function(b,c){quat.conjugate(a,this.upOrientation);vec3.subtract(b,c,this.position);vec3.transformQuat(b,b,a);return b}}();Thing.prototype.parentToLocalVector=function(){var a=quat.create();return function(b,c){quat.conjugate(a,this.upOrientation);vec3.transformQuat(b,c,a);return b}}();Thing.prototype.localToWorldCoords=function(a,b){this.localToParentCoords(a,b);this.parent&&this.parent.localToWorldCoords(a,a);return a};
Thing.prototype.localToWorldVector=function(a,b){this.localToParentVector(a,b);this.parent&&this.parent.localToWorldVector(a,a);return a};Thing.prototype.worldToLocalCoords=function(a,b){this.parent?(this.parent.worldToLocalCoords(a,b),this.parentToLocalCoords(a,a)):this.parentToLocalCoords(a,b);return a};Thing.prototype.worldToLocalVector=function(a,b){this.parent?(this.parent.worldToLocalVector(a,b),this.parentToLocalVector(a,a)):this.parentToLocalVector(a,b);return a};
Thing.prototype.findThingEncounter=function(a,b,c){return this.findEncounter(a.lastPosition,a.position,b,c)};Thing.prototype.findEncounter=function(a,b,c,d){var e=this.objectCache.findEncounter;a=this.parentToLocalCoords(e.p_0,a);b=this.parentToLocalCoords(e.p_1,b);e=null;this.parts.length||console.log(this);for(var g=0;this.parts[g];g++)if(!d||this.parts[g]!=d.exclude){var f=this.parts[g].findEncounter(a,b,c,d);f&&(!e||f.t<e.t)&&(e=f)}return e};
Thing.prototype.fromUpOrientation=function(){var a=vec3.create();return function(b){return vec3.transformQuat(a,b,this.upOrientation)}}();Thing.prototype.toUpOrientation=function(){var a=vec3.create();return function(b){return vec3.transformQuat(a,b,this.getConjugateUp())}}();Thing.prototype.draw=function(){!this.isDisposed&&this.visible&&(Env.gl.pushModelMatrix(),this.transform(),this.render(),Env.gl.popModelMatrix())};
Thing.prototype.transform=function(){Env.gl.translate(this.position);Env.gl.rotate(this.upOrientation);Env.gl.getActiveProgram().setUniformScale(this.scale)};Thing.prototype.render=function(){for(var a=0;this.parts[a];a++)this.parts[a].draw();for(a=0;this.effects[a];a++)this.effects[a].draw()};Thing.prototype.getType=function(){return this.constructor.type};
Thing.prototype.dispose=function(){this.position=this.velocity=null;this.isDisposed=!0;this.parent&&this.parent.removePart(this);Env.world.things.remove(this);Env.world.projectiles.remove(this);util.array.forEach(this.parts,function(a){a.dispose()})};Thing.prototype.setParent=function(a){this.parent=a};Thing.prototype.addPart=function(a){this.parts.push(a);a.setParent(this)};Thing.prototype.addEffect=function(a){this.effects.push(a);a.setParent(this)};
Thing.prototype.removePart=function(a){util.array.remove(this.parts,a);a.setParent(null)};Thing.prototype.addParts=function(a){util.array.forEach(a,function(a){this.addPart(a)},this)};Thing.prototype.saveLastPosition=function(){vec3.copy(this.lastPosition,this.position)};Thing.prototype.distanceSquaredTo=function(a){return vec3.squaredDistance(this.position,a.position)};Thing.prototype.computeDistanceSquaredToCamera=function(a){this.distanceSquaredToCamera=vec3.squaredDistance(this.position,a)};
Thing.prototype.getDeltaP=function(a){vec3.subtract(a,this.position,this.lastPosition)};Thing.prototype.setPitchOnly=function(a){quat.setAxisAngle(this.upOrientation,vec3.I,a)};Thing.prototype.getNormal=function(){return this.localToWorldVector(this.objectCache.normal,vec3.J)};Thing.prototype.getUpNose=function(){return this.localToWorldVector(this.objectCache.upNose,vec3.NEG_K)};
Thing.prototype.getGlommable=function(){if(this.glommable)return this;util.assertNotNull(this.parent,"No glommable target found.");return this.parent.getGlommable()};Thing.prototype.getRoot=function(){if(this.isRoot)return this;util.assertNotNull(this.parent,"No root found.");return this.parent.getRoot()};Thing.prototype.eachPart=function(a){util.array.forEach(this.parts,a,this)};
Thing.prototype.eachPartRecursive=function(a){util.array.forEach(this.parts,function(b){a.call(this,b);b.eachPartRecursive(a)},this)};Thing.prototype.eachEffect=function(a){util.array.forEach(this.effects,a,this)};Thing.prototype.setColor=function(a){this.color=a;this.transluscent=1>this.color[3];this.eachPartRecursive(function(b){b.color=a})};Thing.prototype.getParts=function(){return this.parts};Thing.prototype.setVisible=function(a){this.visible=a};
Thing.prototype.glom=function(a,b){debugger;this.glommable?(this.addEffect(a),Env.world.removeProjectile(a),vec3.copy(a.velocity,vec3.ZERO),vec3.copy(a.position,b)):(this.localToParentCoords(b,b),this.parent.glom(a,b))};Thing.prototype.updateFromProto=function(a){a.alive.isSet()&&(this.alive=a.alive.get());a.position.copyIfSet(this.position);a.velocity.copyIfSet(this.velocity);a.upOrientation.copyIfSet(this.upOrientation)};
Thing.Proto=function(){Proto.call(this);this.alive=this.addField(0,new ByteField);this.position=this.addField(1,new Vec3Field);this.velocity=this.addField(2,new Vec3Field);this.upOrientation=this.addField(3,new QuatField)};goog.inherits(Thing.Proto,Proto);var FreeCamera=function(a){Thing.call(this,a);this.negatedPosition=vec3.create()};goog.inherits(FreeCamera,Thing);FreeCamera.prototype.transform=function(){Env.gl.rotateView(this.upOrientation);Env.gl.translateView(vec3.negate(this.negatedPosition,this.position));Env.gl.uniform3fv(Env.gl.getActiveProgram().eyeLocationUniform,this.position)};FreeCamera.prototype.getPosition=function(){return this.position};var Client=function(a,b){this.world=a;this.host=window.location.host;this.socket=new WebSocket(["ws://",this.host,":",b,"/websock"].join(""));this.socket.onmessage=util.bind(this.onMessage,this);this.socket.binaryType="arraybuffer";this.socket.onopen=util.bind(this.onOpen,this);window.onbeforeunload=util.bind(function(){this.socket.close()},this)},raw,t0=0;
Client.prototype.onMessage=function(a){a=new Reader(a.data);var b=!0,c=a.readByte();switch(c){case MessageCode.SET_STATE:a.readInt();Env.world.setState(a);break;case MessageCode.UPDATE_WORLD:c=(new Date).getTime();a.readInt();t0=c;Env.world.stateSet?Env.world.updateWorld(a):b=!1;Env.world.draw();break;case MessageCode.SCORE:Env.world.scoreMap=Messages.readScoreMessage(a);break;case MessageCode.NAME_MAP:Env.world.nameMap=Messages.readNameMapMessage(a);break;case MessageCode.YOU_ARE:c=a.readInt();Env.world.hero=
Env.world.getThing(c);Env.world.camera=new FpsCamera({});Env.world.camera.setAnchor(Env.world.hero);break;case MessageCode.BROADCAST:var c=a.readInt(),d=a.readString();Env.hud.logger.log(Env.world.nameMap[c].name+": "+d);break;default:console.log("Unrecognized code: "+c),b=!1}b&&a.checkEOM()};Client.prototype.send=function(a){try{this.socket.send(a)}catch(b){}};Client.prototype.sendCode=function(a){this.send(new Uint8Array([a]))};Client.prototype.sendEOM=function(){this.sendCode(MessageCode.EOM)};
Client.prototype.sendMode=function(a){var b=new ArrayBuffer(8),c=new DataView(b);c.setInt8(0,MessageCode.MODE);c.setInt32(1,a);this.send(new Int8Array(b))};Client.prototype.sendKeyEvent=function(a,b){this.send(new Uint8Array([MessageCode.KEY_EVENT,a?1:0,b]))};Client.prototype.sendMyScoreIs=function(a){var b=new ArrayBuffer(5),c=new DataView(b);c.setInt8(0,MessageCode.MY_SCORE_IS);c.setInt32(1,a);this.send(new Int8Array(b))};
Client.prototype.sendMouseMoveEvent=function(a,b){var c=new ArrayBuffer(3),d=new DataView(c);d.setInt8(0,MessageCode.MOUSE_MOVE_EVENT);d.setInt8(1,a);d.setInt8(2,b);this.send(new Int8Array(c))};Client.prototype.myNameIs=function(a){var b=new Writer(1+a.length);b.writeInt8(MessageCode.MY_NAME_IS);b.writeString(a);this.send(b.getBytes())};Client.prototype.say=function(a){var b=new Writer(1+a.length);b.writeInt8(MessageCode.SAY);b.writeString(a);this.send(b.getBytes())};Client.prototype.onOpen=function(){this.sendCode(MessageCode.JOIN)};var LeafThing=function(a){Thing.call(this,a);this.drawable=!1!==a.drawable;this.elementType=a.elementType||GL.TRIANGLES;this.drawType=a.drawType||LeafThing.DrawType.ARRAYS;this.texture=a.texture||null;this.dynamic=a.dynamic||!1;this.normalBuffer=this.indexBuffer=this.textureBuffer=this.vertexBuffer=null};goog.inherits(LeafThing,Thing);LeafThing.DrawType={ARRAYS:0,ELEMENTS:1};LeafThing.prototype.render=function(){this.drawable&&this.renderSelf();this.effects.length&&this.eachEffect(function(a){a.draw()})};
LeafThing.prototype.renderSelf=function(){util.assert(this.drawable,"Cannot render- not drawable.");Env.gl.setModelMatrixUniforms();var a=Env.gl.getActiveProgram();a.setUniformColor(this.color);a.setUseTexture(Boolean(this.texture&&this.texture.loaded));this.texture&&a.bindTexture(this.texture);a.bindVertexPositionBuffer(this.vertexBuffer);a.bindVertexNormalBuffer(this.normalBuffer);this.textureBuffer&&a.bindVertexTextureBuffer(this.textureBuffer);a.bindVertexIndexBuffer(this.indexBuffer);this.drawType==
LeafThing.DrawType.ELEMENTS?Env.gl.drawElements(this.elementType,this.indexBuffer.numItems,GL.UNSIGNED_SHORT,0):Env.gl.drawArrays(this.elementType,0,this.vertexBuffer.numItems)};LeafThing.prototype.dispose=function(){LeafThing.superClass_.dispose.call(this);this.color=this.texture=this.normalBuffer=this.indexBuffer=this.textureBuffer=this.vertexBuffer=null};
LeafThing.prototype.finalize=function(){this.drawable&&(this.vertexBuffer=this.getPositionBuffer(),this.textureBuffer=this.getTextureBuffer(),this.normalBuffer=this.getNormalBuffer(),this.drawType==LeafThing.DrawType.ELEMENTS&&(this.indexBuffer=this.getIndexBuffer()))};LeafThing.prototype.getPositionBuffer=util.unimplemented;LeafThing.prototype.getIndexBuffer=util.unimplemented;
LeafThing.prototype.getTextureBuffer=function(){for(var a=[],b=0;b<this.vertexBuffer.numItems;b++)a.push(0),a.push(0);return Env.gl.generateBuffer(a,2)};LeafThing.prototype.getNormalBuffer=function(){for(var a=[],b=0;b<this.vertexBuffer.numItems;b++)a.push(0),a.push(0),a.push(1);return Env.gl.generateBuffer(a)};var PaneOutline=function(a){a.elementType=GL.LINES;a.drawType=LeafThing.DrawType.ELEMENTS;LeafThing.call(this,a);this.pane=a.pane;this.color=a.color;PaneOutline.inited||PaneOutline.init();this.position=this.pane.position;this.vertexBuffer=Env.gl.generateBuffer(this.pane.verticies,3);this.indexBuffer=PaneOutline.indexBuffer;this.normalBuffer=this.pane.normalBuffer};goog.inherits(PaneOutline,LeafThing);PaneOutline.inited=!1;PaneOutline.indexBuffer=null;
PaneOutline.init=function(){PaneOutline.inited=!0;PaneOutline.normalBuffer=Env.gl.generateBuffer([0,0,1,0,0,1,0,0,1,0,0,1],3);PaneOutline.indexBuffer=Env.gl.generateIndexBuffer([0,1,1,2,2,3,3,0])};var Box=function(a){a.drawType=LeafThing.DrawType.ELEMENTS;this.normalMultiplier=a.normalMultiplier||1;LeafThing.call(this,a);this.size=a.size;this.textureCountsByFace=a.textureCountsByFace||{};this.invert=a.invert;a.textureCounts&&util.array.forEach(Box.Faces,function(b){this.textureCountsByFace[b]||(this.textureCountsByFace[b]=a.textureCounts)},this);this.bottomFace=this.topFace=this.leftFace=this.rightFace=this.backFace=this.frontFace=null;this.buildPanes();this.finalize()};goog.inherits(Box,LeafThing);
Box.Faces="top bottom right left front back".split(" ");Box.prototype.getOuterRadius=function(){return Math.max(this.size[0],this.size[1],this.size[2])};Box.eachFace=function(a,b){util.array.forEach(Box.Faces,a,b)};Box.positionBufferCache={};
Box.prototype.getPositionBuffer=function(){var a=this.size;Box.positionBufferCache[a[0]]||(Box.positionBufferCache[a[0]]={});Box.positionBufferCache[a[0]][a[1]]||(Box.positionBufferCache[a[0]][a[1]]={});if(!Box.positionBufferCache[a[0]][a[1]][a[2]]){for(var b=this.invert?Box.invertedNormalizedVertexPositions:Box.normalizedVertexPositions,c=vec3.scale([],a,.5),d=[],e=0;e<b.length;e++)d.push(b[e]*c[e%3]);Box.positionBufferCache[a[0]][a[1]][a[2]]=Env.gl.generateBuffer(d,3)}return Box.positionBufferCache[a[0]][a[1]][a[2]]};
Box.textureBufferCache={};Box.prototype.getTextureBuffer=function(){var a=[];Box.eachFace(function(b){b=this.textureCountsByFace[b]||[1,1];util.array.pushAll(a,[0,0,b[0],0,b[0],b[1],0,b[1]])},this);return Env.gl.generateBuffer(a,2)};Box.indexBuffer=null;Box.prototype.getIndexBuffer=function(){if(!Box.indexBuffer){var a=[];Box.eachFace(function(b,c){util.array.pushAll(a,[4*c+0,4*c+1,4*c+2,4*c+0,4*c+2,4*c+3])});Box.indexBuffer=Env.gl.generateIndexBuffer(a)}return Box.indexBuffer};
Box.normalBufferCache={};Box.prototype.getNormalBuffer=function(){if(!Box.normalBufferCache[this.normalMultiplier]){var a=[];Box.eachFace(function(b,c){for(var d=0;4>d;d++)for(var e=0;e<Box.FACE_NORMALS[b].length;e++)a.push(this.normalMultiplier*Box.FACE_NORMALS[b][e])},this);Box.normalBufferCache[this.normalMultiplier]=Env.gl.generateBuffer(a,3)}return Box.normalBufferCache[this.normalMultiplier]};
Box.prototype.buildPanes=function(){var a=this.invert?-1:1;this.frontFace=new Pane({size:[this.size[0],this.size[1],0],position:[0,0,this.size[2]/2*a],drawable:!1,glommable:!1});this.backFace=new Pane({size:[this.size[0],this.size[1],0],position:[0,0,-this.size[2]/2*a],drawable:!1,glommable:!1,yaw:Math.PI});this.rightFace=new Pane({size:[this.size[2],this.size[1],0],position:[this.size[0]/2*a,0,0],drawable:!1,glommable:!1,yaw:Math.PI/2});this.leftFace=new Pane({size:[this.size[2],this.size[1],0],
position:[-this.size[0]/2*a,0,0],drawable:!1,glommable:!1,yaw:3*Math.PI/2});this.topFace=new Pane({size:[this.size[0],this.size[2],0],position:[0,this.size[1]/2*a,0],drawable:!1,glommable:!1,pitch:3*Math.PI/2});this.bottomFace=new Pane({size:[this.size[0],this.size[2],0],position:[0,-this.size[1]/2*a,0],drawable:!1,glommable:!1,pitch:Math.PI/2});this.addParts([this.frontFace,this.backFace,this.rightFace,this.leftFace,this.topFace,this.bottomFace])};
Box.FACE_NORMALS={top:[0,1,0],bottom:[0,-1,0],right:[1,0,0],left:[-1,0,0],front:[0,0,1],back:[0,0,-1]};Box.normalizedVertexPositions=[-1,1,1,1,1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,-1,1,-1,-1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,1,-1,1,1,1,1,-1,1,1,-1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1];
Box.invertedNormalizedVertexPositions=[-1,-1,1,1,-1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1,1,1,1,-1,1,1,-1,-1,-1,-1,1,-1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,1,-1,1,-1,-1,-1,-1,-1,1,-1,-1,1,1,-1,-1,1,-1,-1,1,1,1,1,1,1,-1,1,-1,-1,1];var DataThing=function(a){LeafThing.call(this,a);this.data=a.data;this.positionMultiplier=a.positionMultiplier||[1,1,1];a.glommable=!1;a.visible=!1;this.addPart(a.refObject);this.finalize()};goog.inherits(DataThing,LeafThing);DataThing.positionBufferCache={};DataThing.prototype.getPositionBuffer=function(){DataThing.positionBufferCache[this.data.type]||(DataThing.positionBufferCache[this.data.type]=Env.gl.generateBuffer(this.data.vertexCoordinates,3));return DataThing.positionBufferCache[this.data.type]};
DataThing.normalBufferCache={};DataThing.prototype.getNormalBuffer=function(){DataThing.normalBufferCache[this.data.type]||(DataThing.normalBufferCache[this.data.type]=Env.gl.generateBuffer(this.data.normalCoordinates,3));return DataThing.normalBufferCache[this.data.type]};DataThing.textureBufferCache={};
DataThing.prototype.getTextureBuffer=function(){DataThing.textureBufferCache[this.data.type]||(DataThing.textureBufferCache[this.data.type]=Env.gl.generateBuffer(this.data.textureCoordinates,2));return DataThing.textureBufferCache[this.data.type]};var OffsetContainer=function(a){Thing.call(this,a);this.thing=a.thing;this.addPart(this.thing)};goog.inherits(OffsetContainer,Thing);var OffsetBox=function(a){Thing.call(this,{position:vec3.nullableClone(a.position),name:a.name,parentScale:a.parentScale});a.position=a.offset;a.offset=null;a.parentScale=this.scale;this.thing=new Box(a);this.addPart(this.thing)};goog.inherits(OffsetBox,Thing);var Pane=function(a){a.drawType=LeafThing.DrawType.ELEMENTS;LeafThing.call(this,a);this.size=a.size;util.assert(!this.size[2],"z-size must be 0 or undefined for a pane.");this.textureCounts=a.textureCounts||[1,1];this.verticies=this.createVerticies();this.objectCache.findEncounter={encounter:{},p_0_lc:vec3.create(),p_1_lc:vec3.create(),delta:vec3.create(),encounterPoint:vec3.create()};this.finalize()};goog.inherits(Pane,LeafThing);
Pane.prototype.createVerticies=function(){var a=vec2.scale([],this.size,.5);return[-a[0],-a[1],0,a[0],-a[1],0,a[0],a[1],0,-a[0],a[1],0]};Pane.prototype.snapIn=function(a){for(var b=this.worldToLocalCoords(a.position,a.position),c=0;2>c;c++){var d=this.size[c]/2;b[c]<-d&&(b[c]=-d);b[c]>d&&(b[c]=d)}this.localToWorldCoords(a.position,b)};Pane.prototype.contains_lc=function(a,b){for(var c=b||0,d=0;2>d;d++){var e=this.size[d]/2+c;if(a[d]<-e||a[d]>e)return!1}return!0};
Pane.prototype.findEncounter=function(a,b,c,d){d=d?d.tolerance:0;var e=this.objectCache.findEncounter;a=this.parentToLocalCoords(e.p_0_lc,a);b=this.parentToLocalCoords(e.p_1_lc,b);var g=vec3.subtract(e.delta,b,a),f=-a[2]/g[2],h=e.encounter;h.expired=!0;if(Quadratic.inFrame(f)){var k=vec3.scaleAndAdd(e.encounterPoint,a,g,f);if(this.contains_lc(k,d)&&(this.maybeSetEncounter_(c,f,0,k),0==c))return h}this.contains_lc(a,d)&&this.maybeSetEncounter_(c,0,a[2],a);this.contains_lc(b,d)&&this.maybeSetEncounter_(c,
1,b[2],b);for(f=0;2>f;f++)for(var k=this.size[f]/2,n=Math.max(a[f],b[f]),l=Math.min(a[f],b[f]),p=-1;1>=p;p+=2){var m=p*k;if(n>m&&l<m){var m=(m-a[f])/g[f],q=vec3.scaleAndAdd(e.encounterPoint,a,g,m);this.contains_lc(q,d)&&this.maybeSetEncounter_(c,m,q[2],q)}}return h.expired?null:h};
Pane.prototype.maybeSetEncounter_=function(a,b,c,d){var e=this.objectCache.findEncounter.encounter;if(!(Math.abs(c)>a||!e.expired&&b>e.t))return e.part=this,e.t=b,e.distance=c,e.distanceSquared=util.math.sqr(c),e.point=d,e.expired=!1,e};Pane.prototype.getNormal=function(){return this.localToWorldVector(this.objectCache.normal,vec3.K)};Pane.positionBufferCache={};
Pane.prototype.getPositionBuffer=function(){if(this.dynamic)return Env.gl.generateBuffer(this.verticies,3);var a=Pane.positionBufferCache;a[this.size[0]]||(a[this.size[0]]={});a[this.size[0]][this.size[1]]||(a[this.size[0]][this.size[1]]=Env.gl.generateBuffer(this.verticies,3));return a[this.size[0]][this.size[1]]};Pane.indexBuffer=null;Pane.prototype.getIndexBuffer=function(){Pane.indexBuffer||(Pane.indexBuffer=Env.gl.generateIndexBuffer([0,1,2,0,2,3]));return Pane.indexBuffer};
Pane.textureBufferCache={};Pane.prototype.getTextureBuffer=function(){var a=this.textureCounts,b=Pane.textureBufferCache;b[a[0]]||(b[a[0]]={});b[a[0]][a[1]]||(b[a[0]][a[1]]=Env.gl.generateBuffer([0,0,a[0],0,a[0],a[1],0,a[1]],2));return b[a[0]][a[1]]};Pane.normalBuffer=null;Pane.prototype.getNormalBuffer=function(){Pane.normalBuffer||(Pane.normalBuffer=Env.gl.generateBuffer([0,0,1,0,0,1,0,0,1,0,0,1],3));return Pane.normalBuffer};var Sphere=function(a){a.leaf=!0;a.drawType=LeafThing.DrawType.ELEMENTS;LeafThing.call(this,a);this.radius=a.radius||1;this.longitudeCount=a.longitudeCount||15;this.latitudeCount=a.latitudeCount||15;this.objectCache.findEncounter={p_0:vec3.create(),delta:vec3.create()};this.finalize()};goog.inherits(Sphere,LeafThing);Sphere.inited=!1;Sphere.normalBuffer=null;Sphere.indexBuffer=null;Sphere.textureBuffer=null;
Sphere.prototype.findEncounter=function(a,b,c){var d=this.objectCache.findEncounter,e=util.math.sqr(c);a=this.parentToLocalCoords(d.p_0,a);b=this.parentToLocalCoords(d.delta,b);vec3.subtract(b,b,a);d=Quadratic.newLineToOriginQuadratic(a,b,this.radius);if(0<d.rootCount()){var g=d.firstRoot();if(Quadratic.inFrame(g))return this.makeEncounter(g,0,vec3.scaleAndAdd([],a,b,g))}if(0==c)return null;c=d.minT();if(Quadratic.inFrame(c)&&(g=d.valueAt(c),g<e))return this.makeEncounter(c,g,vec3.scaleAndAdd([],
a,b,c));c=d.valueAt(0);d=d.valueAt(1);return c<d&&c<e?this.makeEncounter(0,c,a):d<c&&d<e?this.makeEncounter(1,d,vec3.add([],a,b)):null};
Sphere.prototype.finalize=function(){if(this.drawable){for(var a=[],b=[],c=[],d=[],e=0;e<=this.latitudeCount;e++)for(var g=e*Math.PI/this.latitudeCount,f=Math.sin(g),g=Math.cos(g),h=0;h<=this.longitudeCount;h++){var k=2*h*Math.PI/this.longitudeCount+3*Math.PI/2,n=Math.sin(k),k=Math.cos(k)*f,l=g,n=n*f,p=1-h/this.longitudeCount,m=1-e/this.latitudeCount;b.push(k);b.push(l);b.push(n);a.push(this.radius*k);a.push(this.radius*l);a.push(this.radius*n);d.push(p);d.push(m);h!=this.longitudeCount&&e!=this.latitudeCount&&
(k=e*(this.longitudeCount+1)+h,l=k+this.longitudeCount+1,c.push(k),c.push(k+1),c.push(l),c.push(l),c.push(k+1),c.push(l+1))}Sphere.inited||(Sphere.normalBuffer=Env.gl.generateBuffer(b,3),Sphere.textureBuffer=Env.gl.generateBuffer(d,2),Sphere.indexBuffer=Env.gl.generateIndexBuffer(c));this.vertexBuffer=Env.gl.generateBuffer(a,3);this.normalBuffer=Sphere.normalBuffer;this.textureBuffer=Sphere.textureBuffer;this.indexBuffer=Sphere.indexBuffer}};
Sphere.prototype.makeEncounter=function(a,b,c){return{part:this,t:a,distanceSquared:b,point:c}};Sphere.prototype.getOuterRadius=function(){return this.radius};var KeyCode={MAC_ENTER:3,BACKSPACE:8,TAB:9,NUM_CENTER:12,ENTER:13,SHIFT:16,CTRL:17,ALT:18,PAUSE:19,CAPS_LOCK:20,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,PRINT_SCREEN:44,INSERT:45,DELETE:46,ZERO:48,ONE:49,TWO:50,THREE:51,FOUR:52,FIVE:53,SIX:54,SEVEN:55,EIGHT:56,NINE:57,FF_SEMICOLON:59,FF_EQUALS:61,FF_DASH:173,QUESTION_MARK:63,A:65,B:66,C:67,D:68,E:69,F:70,G:71,H:72,I:73,J:74,K:75,L:76,M:77,N:78,O:79,P:80,Q:81,R:82,S:83,T:84,U:85,V:86,W:87,X:88,Y:89,Z:90,
META:91,WIN_KEY_RIGHT:92,CONTEXT_MENU:93,NUM_ZERO:96,NUM_ONE:97,NUM_TWO:98,NUM_THREE:99,NUM_FOUR:100,NUM_FIVE:101,NUM_SIX:102,NUM_SEVEN:103,NUM_EIGHT:104,NUM_NINE:105,NUM_MULTIPLY:106,NUM_PLUS:107,NUM_MINUS:109,NUM_PERIOD:110,NUM_DIVISION:111,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,NUMLOCK:144,SCROLL_LOCK:145,FIRST_MEDIA_KEY:166,LAST_MEDIA_KEY:183,SEMICOLON:186,DASH:189,EQUALS:187,COMMA:188,PERIOD:190,SLASH:191,APOSTROPHE:192,TILDE:192,SINGLE_QUOTE:222,
OPEN_SQUARE_BRACKET:219,BACKSLASH:220,CLOSE_SQUARE_BRACKET:221,WIN_KEY:224,MAC_FF_META:224,MAC_WK_CMD_LEFT:91,MAC_WK_CMD_RIGHT:93,WIN_IME:229,PHANTOM:255};var Twiddler=function(a,b,c){this.obj=a;this.attr=b;this.interval=c;this.inputAdapter=(new WorldInputAdapter).setKeyHandler(this.onKey,this)};Twiddler.prototype.onKey=function(a){"keydown"==a.type&&(a.keyCode==KeyCode.OPEN_SQUARE_BRACKET&&(this.obj[this.attr]-=this.interval),a.keyCode==KeyCode.CLOSE_SQUARE_BRACKET&&(this.obj[this.attr]+=this.interval))};var HUD=function(a){this.widgets=[];this.canvas=a;this.context=a.getContext("2d");this.isRendering=!0;this.logger=new Logger(10,300);this.addWidget(this.logger)};HUD.prototype.render=function(){this.isRendering&&(this.clear(),util.array.forEach(this.widgets,function(a){a.render()}))};HUD.prototype.addWidget=function(a){this.widgets.push(a);a.context=this.context;a.resize();return this};HUD.prototype.resize=function(){util.array.forEach(this.widgets,function(a){a.resize()})};
HUD.prototype.clear=function(){this.context.clearRect(0,0,this.canvas.width,this.canvas.height)};var Widget=function(a,b){this.context=null;this.x=a;this.y=b;this.fillStyle=this.font=this.position=null};Widget.prototype.resize=function(){this.position=[0<this.x?this.x:this.context.canvas.width+this.x,0<this.y?this.y:this.context.canvas.height+this.y]};Widget.prototype.setFont=function(a){this.context.font=a};Widget.prototype.setFillStyle=function(a){this.context.fillStyle=a};
var Fraps=function(a,b){Widget.call(this,a,b)};goog.inherits(Fraps,Widget);Fraps.prototype.render=function(){Animator.getInstance();var a=Animator.getInstance().getRollingAverageFramerate();this.setFillStyle(45>a?"#F00":"#0F0");this.setFont("bold 16px courier");this.context.fillText("FPS: "+a,this.position[0],this.position[1])};var Crosshair=function(){Widget.call(this,0,0)};goog.inherits(Crosshair,Widget);
Crosshair.prototype.resize=function(){this.position=[this.context.canvas.width/2,this.context.canvas.height/2]};
Crosshair.prototype.render=function(){Animator.getInstance().isPaused()||(this.context.strokeStyle="#ff0000",this.context.translate(this.position[0],this.position[1]),this.context.beginPath(),this.context.moveTo(-10,0),this.context.lineTo(10,0),this.context.stroke(),this.context.beginPath(),this.context.moveTo(0,-10),this.context.lineTo(0,10),this.context.stroke(),this.context.translate(-this.position[0],-this.position[1]))};
var Logger=function(a,b){Widget.call(this,a,b);this.activeLines=0;this.maxLinesToShow=6;this.index=0;this.lines=[];this.timeout=null};goog.inherits(Logger,Widget);Logger.prototype.log=function(a){this.lines.push(a);this.activeLines=Math.min(this.maxLinesToShow,this.activeLines+1);clearTimeout(this.timeout);this.timeout=setTimeout(util.bind(this.fade,this),5E3)};
Logger.prototype.fade=function(){this.activeLines=Math.max(0,this.activeLines-1);0<this.activeLines&&setTimeout(util.bind(this.fade,this),5E3)};Logger.prototype.render=function(){if(this.activeLines){var a=this.lines.length;this.setFillStyle("#CCC");this.setFont("14px courier");for(var b=0;b<this.activeLines&&b<this.maxLinesToShow;b++){var c=this.lines[a-b-1];if(!c)break;this.context.fillText(c,this.position[0],this.position[1]-25*b)}}};var StartButton=function(){Widget.call(this,0,0)};
goog.inherits(StartButton,Widget);StartButton.prototype.render=function(){Animator.getInstance().isPaused()&&(this.setFont("56px wolfenstein"),this.setFillStyle("#FFF"),this.context.fillText("Click to Start",this.context.canvas.width/2-200,this.context.canvas.height/2-25))};var UpdatingWriter=function(a,b,c){Widget.call(this,a,b);this.textFunction=c;this.font="bold 28px courier";this.fillStyle="#00F"};goog.inherits(UpdatingWriter,Widget);
UpdatingWriter.prototype.render=function(){this.setFont(this.font);this.setFillStyle(this.fillStyle);this.context.fillText(this.textFunction(),this.position[0],this.position[1])};var PromptBox=function(){this.div=document.createElement("div");this.div.id="prompt-box";this.promptMessageDiv=document.createElement("span");this.promptMessageDiv.style.paddingRight="6px";this.div.appendChild(this.promptMessageDiv);this.inputDiv=document.createElement("input");this.inputDiv.style.width="149px";this.inputDiv.type="text";this.div.appendChild(this.inputDiv);this.callback=null;this.open=!1;this.inputDiv.addEventListener("keydown",util.bind(function(a){this.open&&a.keyCode==KeyCode.ENTER&&
this.close()},this))};PromptBox.instance=new PromptBox;PromptBox.ask=function(a,b){PromptBox.instance.ask(a,b)};PromptBox.prototype.ask=function(a,b){this.callback=b;this.div.style.left=Math.floor(Env.hud.canvas.offsetWidth/2)-150+"px";this.div.style.top=Math.floor(3*Env.hud.canvas.offsetHeight/4)-20+"px";this.promptMessageDiv.innerHTML=a;this.inputDiv.value="";document.getElementById("fullscreen-tab").appendChild(this.div);var c=this.inputDiv;setTimeout(function(){c.focus()},0);this.open=!0};
PromptBox.prototype.close=function(){document.getElementById("fullscreen-tab").removeChild(this.div);this.callback(this.inputDiv.value);this.open=!1;document.getElementById("game-div").focus()};var ScoreCard=function(a,b){Widget.call(this,a,b)};goog.inherits(ScoreCard,Widget);
ScoreCard.prototype.render=function(){this.setFont("bold 14px courier");Env.world.scoreMap.sort(function(a,b){return a[2]<b[2]});for(var a=0;a<Env.world.scoreMap.length;a++){var b=Env.world.scoreMap[a][0],c=Env.world.scoreMap[a][1],d=Env.world.nameMap[b],b=Env.world.nameMap[b].name;if(!Env.world.getThing(d.unitId))break;d=-1==d.unitId?vec4.CYAN:Env.world.getThing(d.unitId).color;this.setFillStyle("rgb("+Math.floor(256*d[0])+","+Math.floor(256*d[1])+","+Math.floor(256*d[2])+")");this.context.fillText(b+
" : "+c,this.position[0],this.position[1]+12*a)}};
//@ sourceMappingURL=rootworld.js.map