<commit_before>var Physics = function() {
    PIXELS_PER_METER = 16;
    return function(context, gameWidth, gameHeight) {
        function newDebugDraw() {
            var debugDraw = new b2DebugDraw();
            debugDraw.SetSprite(document.getElementById("sup").getContext("2d"));
            debugDraw.SetDrawScale(PIXELS_PER_METER);
            debugDraw.SetFillAlpha(0.5);
            debugDraw.SetLineThickness(1.0);
            debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
            return debugDraw;
        }

        var b2Vec2 = Box2D.Common.Math.b2Vec2;
        var b2BodyDef = Box2D.Dynamics.b2BodyDef;
        var b2Body = Box2D.Dynamics.b2Body;
        var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
        var b2Fixture = Box2D.Dynamics.b2Fixture;
        var b2World = Box2D.Dynamics.b2World;
        var b2MassData = Box2D.Collision.Shapes.b2MassData;
        var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
        var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
        var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
        var b2Settings = Box2D.Common.b2Settings;
        this.toRemove = [];
        this.boxesRemoved = 0;

        b2Settings.b2_maxTranslation = 10000.0;
        b2Settings.b2_maxTranslationSquared = 10000.0*10000.0;

        var that = this;
        var turnRate = 0;
        var targetRotation = 0;
        var rotation = 0;
        var gravity = 0.00001;

        Constants.get("world_rotation_rate", function(value) {
            turnRate = value;
        });

        var debugDraw = newDebugDraw();

        this.world = new b2World(newGravity(), false);
        this.world.UserData = this;
        this.world.SetDebugDraw(debugDraw);
        Constants.get("world_gravity", function(value) {
            gravity = value;
            that.world.SetGravity(newGravity());
        });

        var setPhysicalProperties = function(cls, fix, massless) {
            if (massless === undefined) {
                massless = false;
            }
            Constants.get([cls + '_friction',
                           cls + '_restitution'],
                           function(fric, rest) {
                fix.SetFriction(fric);
                fix.SetRestitution(rest);
            });
            if (!massless) {
                Constants.get(cls + '_density',
                              function(density) {
                    fix.SetDensity(density);
                });
            }
        };

        newWorld();

        this.newBlock = function(cls, stage, controllable) {
            if (controllable === undefined) {
                controllable = false;
            }
            var fd                 = new b2FixtureDef;
            fd.shape               = new b2PolygonShape();
            fd.density = 1.0;
            fd.friction = 0.3;
            fd.restitution = 0.1;

            fd.shape.SetAsBox(1,1);

            var bodyDef                  = new b2BodyDef();
            bodyDef.type                 = b2Body.b2_dynamicBody;
            bodyDef.position.x           = 300/PIXELS_PER_METER;
            bodyDef.position.y           = 300/PIXELS_PER_METER;
            bodyDef.allowSleep           = false;
            var body = that.world.CreateBody(bodyDef);
            var fix = body.CreateFixture(fd);
            setPhysicalProperties(cls, fix);

            var e = new Entity();
            body.SetUserData({tag: "BLOCK", entity:e});
            Constants.get([cls + "_image", cls + "_scale"], function(value, scale) {
                var beeTexture = PIXI.Texture.fromImage(value, true);
                var beeSprite = new PIXI.Sprite(beeTexture);

                beeSprite.anchor.x = 0.5;
                beeSprite.anchor.y = 0.5;

                beeSprite.scale.x = scale;
                beeSprite.scale.y = scale;

                e.addComponent(SpriteComponent(stage, beeSprite));
                e.addComponent(PhysicsComponent(body));
                if (controllable) {
                    body.SetUserData({tag: "PLAYER", entity:e});
                    e.addComponent(MovableComponent());
                    Constants.get("movement_speed", function(x) {
                        e({id: "setMovementSpeed", speed: x});
                    });
                    Constants.get("movement_vertical", function(x) {
                        e({id: "setVerticalSpeed", speed: x});
                    });
                    e.addComponent(GrabberComponent());
                }
                World.add(e);
            });
        };

        this.draw = function() {
            that.world.DrawDebugData();
        };

        var velocityIterations = 12, positionIterations = 12;

        Constants.get(["physics_velocityIterations",
                "physics_positionIterations"],
                function(x, y) {
                    velocityIterations = x;
                    positionIterations = y;
                });

        this.update = function() {
            if (Math.abs(targetRotation - rotation) > turnRate) {
                function sign(x) { return x ? x < 0 ? -1 : 1 : 0; }
                direction = sign(targetRotation - rotation);
                rotation += direction * turnRate;
                that.world.SetGravity(newGravity());
            }

            that.toRemove = [];
            that.world.Step(1/60, velocityIterations, positionIterations);
            for (var i = 0; i < that.toRemove.length; i++) {
                var body = that.toRemove[i];
                that.world.DestroyBody(body);
                World.del(body.GetUserData().entity);
                that.boxesRemoved += 1;
            }
            that.world.ClearForces();
        };

        this.getRotation = function() {
            return rotation;
        };

        this.setTargetRotation = function(rotation) {
            targetRotation = rotation;
        };

        function newGravity() {
            var vector = rotate([0, gravity*PIXELS_PER_METER]);
            return new b2Vec2(vector[0], vector[1]);
        }

        function rotate(vec) {
            var sine   = Math.sin(rotation * (Math.PI/180));
            var cosine = Math.cos(rotation * (Math.PI/180));
            return [vec[0] * cosine + vec[1] * sine,
                   vec[0] * -sine + vec[1] * cosine];
        }

        function addWall(x, y, width, height, rotation, offset1, offset2) {
            //floor
            var floorDef                 = new b2FixtureDef;
            floorDef.shape               = new b2PolygonShape();
            floorDef.friction            = 0.2;
            floorDef.restitution         = 0.7;
            floorDef.shape.SetAsOrientedBox(width/2, height/2, new b2Vec2(offset1, offset2), rotation * Math.PI/180);

            var floorBodyDef                  = new b2BodyDef();
            floorBodyDef.type                 = b2Body.b2_staticBody;
            floorBodyDef.position.x           = x/PIXELS_PER_METER;
            floorBodyDef.position.y           = y/PIXELS_PER_METER;
            var body = that.world.CreateBody(floorBodyDef)
            var fix = body.CreateFixture(floorDef);
            setPhysicalProperties('wall', fix, true);
        }

        function newWorld() {
            addWall(gameWidth/2, 0, 10000, 3, 0, 0, 0);
            addWall(gameWidth/2, gameHeight, 10000, 3, 0, 0, 0);
            addWall(0, gameHeight/2, 3, 100000, 0, 0, 0);
            addWall(gameWidth, gameHeight/2, 3, 100000, 0, 0, 0);
            //addWall(gameWidth, gameHeight/2, 100000, 3, 45, 3, 3);
            addWall(gameWidth+100, gameHeight/2, 100000, 3, 45, 0, 0);
            addWall(-100, gameHeight/2, 100000, 3, 45, 0, 0);
            addWall(gameWidth/2, -100, 10000, 3, -45, 0, 0);
            addWall(gameWidth/2, gameHeight+100, 10000, 3, -45, 0, 0);
            var myContactListener = {
                "BeginContact" : function(contact) {
                    var data1 = contact.GetFixtureA().GetBody().GetUserData()
                        var data2 = contact.GetFixtureB().GetBody().GetUserData()
                        if (data1 && data2) {
                            if (data1.tag == "GOAL" && data2.tag == "BLOCK") {
                                that.toRemove.push(contact.GetFixtureB().GetBody());
                            }
                            if (data2.tag == "GOAL" && data1.tag == "BLOCK") {
                                that.toRemove.push(contact.GetFixtureA().GetBody());
                            }
                        }
                },
                "EndContact" : function() {
                },
                "PreSolve" : function() {
                },
                "PostSolve" : function() {
                }
            };
            that.world.SetContactListener(myContactListener);
        }

        this.newGoal = function(gameSize) {
            Constants.get(["goal_width", "goal_height"], function(width, height) {
                //floor
                var floorDef                 = new b2FixtureDef;
                floorDef.shape               = new b2PolygonShape();
                floorDef.IsSensor            = true;
                floorDef.friction            = 0.2;
                floorDef.restitution         = 0.7;
                floorDef.shape.SetAsBox(width/2, height/2);

                var floorBodyDef                  = new b2BodyDef();
                floorBodyDef.type                 = b2Body.b2_staticBody;
                floorBodyDef.position.x           = gameSize*0.5/PIXELS_PER_METER;
                floorBodyDef.position.y           = gameSize*0.5/PIXELS_PER_METER;
                var body = that.world.CreateBody(floorBodyDef);

                body.SetUserData({tag: "GOAL"});
                body.CreateFixture(floorDef);
            });
        }

        this.rotate = rotate;
    };
}();
<commit_msg>Add a constant for the physics debug overlay<commit_after>var Physics = function() {
    PIXELS_PER_METER = 16;
    return function(context, gameWidth, gameHeight) {
        function newDebugDraw() {
            var debugDraw = new b2DebugDraw();
            debugDraw.SetSprite(document.getElementById("sup").getContext("2d"));
            debugDraw.SetDrawScale(PIXELS_PER_METER);
            debugDraw.SetFillAlpha(0.5);
            debugDraw.SetLineThickness(1.0);
            debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
            return debugDraw;
        }

        var b2Vec2 = Box2D.Common.Math.b2Vec2;
        var b2BodyDef = Box2D.Dynamics.b2BodyDef;
        var b2Body = Box2D.Dynamics.b2Body;
        var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
        var b2Fixture = Box2D.Dynamics.b2Fixture;
        var b2World = Box2D.Dynamics.b2World;
        var b2MassData = Box2D.Collision.Shapes.b2MassData;
        var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
        var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
        var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
        var b2Settings = Box2D.Common.b2Settings;
        this.toRemove = [];
        this.boxesRemoved = 0;

        b2Settings.b2_maxTranslation = 10000.0;
        b2Settings.b2_maxTranslationSquared = 10000.0*10000.0;

        var that = this;
        var turnRate = 0;
        var targetRotation = 0;
        var rotation = 0;
        var gravity = 0.00001;

        Constants.get("world_rotation_rate", function(value) {
            turnRate = value;
        });

        this.world = new b2World(newGravity(), false);
        this.world.UserData = this;

        var debugDraw = newDebugDraw();

        Constants.get("debug_physics", function(value) {
            if (value) {
                that.world.SetDebugDraw(debugDraw);
            } else {
                that.world.SetDebugDraw(null);
                debugDraw.m_sprite.graphics.clear();
            }
        });

        Constants.get("world_gravity", function(value) {
            gravity = value;
            that.world.SetGravity(newGravity());
        });

        var setPhysicalProperties = function(cls, fix, massless) {
            if (massless === undefined) {
                massless = false;
            }
            Constants.get([cls + '_friction',
                           cls + '_restitution'],
                           function(fric, rest) {
                fix.SetFriction(fric);
                fix.SetRestitution(rest);
            });
            if (!massless) {
                Constants.get(cls + '_density',
                              function(density) {
                    fix.SetDensity(density);
                });
            }
        };

        newWorld();

        this.newBlock = function(cls, stage, controllable) {
            if (controllable === undefined) {
                controllable = false;
            }
            var fd                 = new b2FixtureDef;
            fd.shape               = new b2PolygonShape();
            fd.density = 1.0;
            fd.friction = 0.3;
            fd.restitution = 0.1;

            fd.shape.SetAsBox(1,1);

            var bodyDef                  = new b2BodyDef();
            bodyDef.type                 = b2Body.b2_dynamicBody;
            bodyDef.position.x           = 300/PIXELS_PER_METER;
            bodyDef.position.y           = 300/PIXELS_PER_METER;
            bodyDef.allowSleep           = false;
            var body = that.world.CreateBody(bodyDef);
            var fix = body.CreateFixture(fd);
            setPhysicalProperties(cls, fix);

            var e = new Entity();
            body.SetUserData({tag: "BLOCK", entity:e});
            Constants.get([cls + "_image", cls + "_scale"], function(value, scale) {
                var beeTexture = PIXI.Texture.fromImage(value, true);
                var beeSprite = new PIXI.Sprite(beeTexture);

                beeSprite.anchor.x = 0.5;
                beeSprite.anchor.y = 0.5;

                beeSprite.scale.x = scale;
                beeSprite.scale.y = scale;

                e.addComponent(SpriteComponent(stage, beeSprite));
                e.addComponent(PhysicsComponent(body));
                if (controllable) {
                    body.SetUserData({tag: "PLAYER", entity:e});
                    e.addComponent(MovableComponent());
                    Constants.get("movement_speed", function(x) {
                        e({id: "setMovementSpeed", speed: x});
                    });
                    Constants.get("movement_vertical", function(x) {
                        e({id: "setVerticalSpeed", speed: x});
                    });
                    e.addComponent(GrabberComponent());
                }
                World.add(e);
            });
        };

        this.draw = function() {
            that.world.DrawDebugData();
        };

        var velocityIterations = 12, positionIterations = 12;

        Constants.get(["physics_velocityIterations",
                "physics_positionIterations"],
                function(x, y) {
                    velocityIterations = x;
                    positionIterations = y;
                });

        this.update = function() {
            if (Math.abs(targetRotation - rotation) > turnRate) {
                function sign(x) { return x ? x < 0 ? -1 : 1 : 0; }
                direction = sign(targetRotation - rotation);
                rotation += direction * turnRate;
                that.world.SetGravity(newGravity());
            }

            that.toRemove = [];
            that.world.Step(1/60, velocityIterations, positionIterations);
            for (var i = 0; i < that.toRemove.length; i++) {
                var body = that.toRemove[i];
                that.world.DestroyBody(body);
                World.del(body.GetUserData().entity);
                that.boxesRemoved += 1;
            }
            that.world.ClearForces();
        };

        this.getRotation = function() {
            return rotation;
        };

        this.setTargetRotation = function(rotation) {
            targetRotation = rotation;
        };

        function newGravity() {
            var vector = rotate([0, gravity*PIXELS_PER_METER]);
            return new b2Vec2(vector[0], vector[1]);
        }

        function rotate(vec) {
            var sine   = Math.sin(rotation * (Math.PI/180));
            var cosine = Math.cos(rotation * (Math.PI/180));
            return [vec[0] * cosine + vec[1] * sine,
                   vec[0] * -sine + vec[1] * cosine];
        }

        function addWall(x, y, width, height, rotation, offset1, offset2) {
            //floor
            var floorDef                 = new b2FixtureDef;
            floorDef.shape               = new b2PolygonShape();
            floorDef.friction            = 0.2;
            floorDef.restitution         = 0.7;
            floorDef.shape.SetAsOrientedBox(width/2, height/2, new b2Vec2(offset1, offset2), rotation * Math.PI/180);

            var floorBodyDef                  = new b2BodyDef();
            floorBodyDef.type                 = b2Body.b2_staticBody;
            floorBodyDef.position.x           = x/PIXELS_PER_METER;
            floorBodyDef.position.y           = y/PIXELS_PER_METER;
            var body = that.world.CreateBody(floorBodyDef)
            var fix = body.CreateFixture(floorDef);
            setPhysicalProperties('wall', fix, true);
        }

        function newWorld() {
            addWall(gameWidth/2, 0, 10000, 3, 0, 0, 0);
            addWall(gameWidth/2, gameHeight, 10000, 3, 0, 0, 0);
            addWall(0, gameHeight/2, 3, 100000, 0, 0, 0);
            addWall(gameWidth, gameHeight/2, 3, 100000, 0, 0, 0);
            //addWall(gameWidth, gameHeight/2, 100000, 3, 45, 3, 3);
            addWall(gameWidth+100, gameHeight/2, 100000, 3, 45, 0, 0);
            addWall(-100, gameHeight/2, 100000, 3, 45, 0, 0);
            addWall(gameWidth/2, -100, 10000, 3, -45, 0, 0);
            addWall(gameWidth/2, gameHeight+100, 10000, 3, -45, 0, 0);
            var myContactListener = {
                "BeginContact" : function(contact) {
                    var data1 = contact.GetFixtureA().GetBody().GetUserData()
                        var data2 = contact.GetFixtureB().GetBody().GetUserData()
                        if (data1 && data2) {
                            if (data1.tag == "GOAL" && data2.tag == "BLOCK") {
                                that.toRemove.push(contact.GetFixtureB().GetBody());
                            }
                            if (data2.tag == "GOAL" && data1.tag == "BLOCK") {
                                that.toRemove.push(contact.GetFixtureA().GetBody());
                            }
                        }
                },
                "EndContact" : function() {
                },
                "PreSolve" : function() {
                },
                "PostSolve" : function() {
                }
            };
            that.world.SetContactListener(myContactListener);
        }

        this.newGoal = function(gameSize) {
            Constants.get(["goal_width", "goal_height"], function(width, height) {
                //floor
                var floorDef                 = new b2FixtureDef;
                floorDef.shape               = new b2PolygonShape();
                floorDef.IsSensor            = true;
                floorDef.friction            = 0.2;
                floorDef.restitution         = 0.7;
                floorDef.shape.SetAsBox(width/2, height/2);

                var floorBodyDef                  = new b2BodyDef();
                floorBodyDef.type                 = b2Body.b2_staticBody;
                floorBodyDef.position.x           = gameSize*0.5/PIXELS_PER_METER;
                floorBodyDef.position.y           = gameSize*0.5/PIXELS_PER_METER;
                var body = that.world.CreateBody(floorBodyDef);

                body.SetUserData({tag: "GOAL"});
                body.CreateFixture(floorDef);
            });
        }

        this.rotate = rotate;
    };
}();
<|endoftext|>


<commit_before>var Physics = function() {
    PIXELS_PER_METER = 16;
    return function(context, gameWidth, gameHeight) {
        function newDebugDraw() {
            var debugDraw = new b2DebugDraw();
            debugDraw.SetSprite(document.getElementById("sup").getContext("2d"));
            debugDraw.SetDrawScale(PIXELS_PER_METER);
            debugDraw.SetFillAlpha(0.5);
            debugDraw.SetLineThickness(1.0);
            debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
            return debugDraw;
        }

        var b2Vec2 = Box2D.Common.Math.b2Vec2;
        var b2BodyDef = Box2D.Dynamics.b2BodyDef;
        var b2Body = Box2D.Dynamics.b2Body;
        var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
        var b2Fixture = Box2D.Dynamics.b2Fixture;
        var b2World = Box2D.Dynamics.b2World;
        var b2MassData = Box2D.Collision.Shapes.b2MassData;
        var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
        var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
        var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
        var b2Settings = Box2D.Common.b2Settings;

        b2Settings.b2_maxTranslation = 10000.0;
        b2Settings.b2_maxTranslationSquared = 10000.0*10000.0;

        var that = this;
        var turnRate = 0;
        var targetRotation = 0;
        var rotation = 0;
        var gravity = 0.00001;

        Constants.get("world_rotation_rate", function(value) {
            turnRate = value;
        });

        var debugDraw = newDebugDraw();

        this.world = new b2World(newGravity(), false);
        this.world.UserData = this;
        this.world.SetDebugDraw(debugDraw);
        Constants.get("world_gravity", function(value) {
            gravity = value;
            that.world.SetGravity(newGravity());
        });

        newWorld();

        this.newBlock = function(cls, stage, controllable) {
            if (controllable === undefined) {
                controllable = false;
            }
            var fd                 = new b2FixtureDef;
            fd.shape               = new b2PolygonShape();
            fd.density = 1.0;
            fd.friction = 0.3;
            fd.restitution = 0.1;

            fd.shape.SetAsBox(1,1);

            var bodyDef                  = new b2BodyDef();
            bodyDef.type                 = b2Body.b2_dynamicBody;
            bodyDef.position.x           = 300/PIXELS_PER_METER;
            bodyDef.position.y           = 300/PIXELS_PER_METER;
            bodyDef.allowSleep           = false;
            var body = that.world.CreateBody(bodyDef);
            body.CreateFixture(fd);

            var e = new Entity();
            Constants.get([cls + "_image", cls + "_scale"], function(value, scale) {
                console.log("value");
                console.log(value);
                var beeTexture = PIXI.Texture.fromImage(value, true);
                var beeSprite = new PIXI.Sprite(beeTexture);

                beeSprite.anchor.x = 0.5;
                beeSprite.anchor.y = 0.5;

                beeSprite.scale.x = scale;
                beeSprite.scale.y = scale;

                e.addComponent(SpriteComponent(stage, beeSprite));
                e.addComponent(PhysicsComponent(body));
                if (controllable) {
                    e.addComponent(MovableComponent());
                    Constants.get("movement_speed", function(x) {
                        e({id: "setMovementSpeed", speed: x});
                    });
                    Constants.get("movement_vertical", function(x) {
                        e({id: "setVerticalSpeed", speed: x});
                    });
                }
                console.log("here");
                World.add(e);
            });
        };

        this.draw = function() {
            that.world.DrawDebugData();
        };

        var velocityIterations = 12, positionIterations = 12;

        Constants.get(["physics_velocityIterations",
                       "physics_positionIterations"],
                       function(x, y) {
                           velocityIterations = x;
                           positionIterations = y;
                       });

        this.update = function() {
            if (Math.abs(targetRotation - rotation) > turnRate) {
                function sign(x) { return x ? x < 0 ? -1 : 1 : 0; }
                direction = sign(targetRotation - rotation);
                rotation += direction * turnRate;
                that.world.SetGravity(newGravity());
            }

            that.world.Step(1/60, velocityIterations, positionIterations);
            that.world.ClearForces();
        };

        this.getRotation = function() {
            return rotation;
        };

        this.setTargetRotation = function(rotation) {
            targetRotation = rotation;
        };

        function newGravity() {
            var vector = rotate([0, gravity*PIXELS_PER_METER]);
            return new b2Vec2(vector[0], vector[1]);
        }

        function rotate(vec) {
            var sine   = Math.sin(rotation * (Math.PI/180));
            var cosine = Math.cos(rotation * (Math.PI/180));
            return [vec[0] * cosine + vec[1] * sine,
                    vec[0] * -sine + vec[1] * cosine];
        }

        function addWall(x, y, width, height, rotation, offset1, offset2) {
            //floor
            var floorDef                 = new b2FixtureDef;
            floorDef.shape               = new b2PolygonShape();
            floorDef.friction            = 0.2;
            floorDef.restitution         = 0.7;
            floorDef.shape.SetAsOrientedBox(width/2, height/2, new b2Vec2(offset1, offset2), rotation * Math.PI/180);

            var floorBodyDef                  = new b2BodyDef();
            floorBodyDef.type                 = b2Body.b2_staticBody;
            floorBodyDef.position.x           = x/PIXELS_PER_METER;
            floorBodyDef.position.y           = y/PIXELS_PER_METER;
            that.world.CreateBody(floorBodyDef).CreateFixture(floorDef);
        }

        function newWorld() {
            addWall(gameWidth/2, 0, 10000, 3, 0, 0, 0);
            addWall(gameWidth/2, gameHeight, 10000, 3, 0, 0, 0);
            addWall(0, gameHeight/2, 3, 100000, 0, 0, 0);
            addWall(gameWidth, gameHeight/2, 3, 100000, 0, 0, 0);
            //addWall(gameWidth, gameHeight/2, 100000, 3, 45, 3, 3);
            addWall(gameWidth+100, gameHeight/2, 100000, 3, 45, 0, 0);
            addWall(-100, gameHeight/2, 100000, 3, 45, 0, 0);
            addWall(gameWidth/2, -100, 10000, 3, -45, 0, 0);
            addWall(gameWidth/2, gameHeight+100, 10000, 3, -45, 0, 0);
            var myContactListener = function() {
                return {
                    "BeginContact" : function() {
                        console.log("lol");
                    },
                    "EndContact" : function() {
                    },
                    "PreSolve" : function() {
                    },
                    "PostSolve" : function() {
                    }
                }
            };
            that.world.SetContactListener(myContactListener());
        }

        this.newGoal = function(gameSize) {
            Constants.get(["goal_width", "goal_height"], function(width, height) {
                //floor
                var floorDef                 = new b2FixtureDef;
                floorDef.shape               = new b2PolygonShape();
                floorDef.IsSensor            = true;
                floorDef.friction            = 0.2;
                floorDef.restitution         = 0.7;
                floorDef.shape.SetAsOrientedBox(width/2, height/2);

                var floorBodyDef                  = new b2BodyDef();
                floorBodyDef.type                 = b2Body.b2_staticBody;
                floorBodyDef.position.x           = gameSize*0.5/PIXELS_PER_METER;
                floorBodyDef.position.y           = gameSize*0.5/PIXELS_PER_METER;
                that.world.CreateBody(floorBodyDef).CreateFixture(floorDef);
            });
        }

        this.rotate = rotate;
    };
}();
<commit_msg>Move restitution, friction and density out<commit_after>var Physics = function() {
    PIXELS_PER_METER = 16;
    return function(context, gameWidth, gameHeight) {
        function newDebugDraw() {
            var debugDraw = new b2DebugDraw();
            debugDraw.SetSprite(document.getElementById("sup").getContext("2d"));
            debugDraw.SetDrawScale(PIXELS_PER_METER);
            debugDraw.SetFillAlpha(0.5);
            debugDraw.SetLineThickness(1.0);
            debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
            return debugDraw;
        }

        var b2Vec2 = Box2D.Common.Math.b2Vec2;
        var b2BodyDef = Box2D.Dynamics.b2BodyDef;
        var b2Body = Box2D.Dynamics.b2Body;
        var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
        var b2Fixture = Box2D.Dynamics.b2Fixture;
        var b2World = Box2D.Dynamics.b2World;
        var b2MassData = Box2D.Collision.Shapes.b2MassData;
        var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
        var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
        var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
        var b2Settings = Box2D.Common.b2Settings;

        b2Settings.b2_maxTranslation = 10000.0;
        b2Settings.b2_maxTranslationSquared = 10000.0*10000.0;

        var that = this;
        var turnRate = 0;
        var targetRotation = 0;
        var rotation = 0;
        var gravity = 0.00001;

        Constants.get("world_rotation_rate", function(value) {
            turnRate = value;
        });

        var debugDraw = newDebugDraw();

        this.world = new b2World(newGravity(), false);
        this.world.UserData = this;
        this.world.SetDebugDraw(debugDraw);
        Constants.get("world_gravity", function(value) {
            gravity = value;
            that.world.SetGravity(newGravity());
        });

        var setPhysicalProperties = function(cls, fix, massless) {
            if (massless === undefined) {
                massless = false;
            }
            Constants.get([cls + '_friction',
                           cls + '_restitution'],
                           function(fric, rest) {
                fix.SetFriction(fric);
                fix.SetRestitution(rest);
                console.log("New PP", cls, fric, rest);
            });
            if (!massless) {
                Constants.get(cls + '_density',
                              function(density) {
                    fix.SetDensity(density);
                });
            }
        };

        newWorld();

        this.newBlock = function(cls, stage, controllable) {
            if (controllable === undefined) {
                controllable = false;
            }
            var fd                 = new b2FixtureDef;
            fd.shape               = new b2PolygonShape();
            fd.density = 1.0;
            fd.friction = 0.3;
            fd.restitution = 0.1;

            fd.shape.SetAsBox(1,1);

            var bodyDef                  = new b2BodyDef();
            bodyDef.type                 = b2Body.b2_dynamicBody;
            bodyDef.position.x           = 300/PIXELS_PER_METER;
            bodyDef.position.y           = 300/PIXELS_PER_METER;
            bodyDef.allowSleep           = false;
            var body = that.world.CreateBody(bodyDef);
            var fix = body.CreateFixture(fd);
            setPhysicalProperties(cls, fix);

            var e = new Entity();
            Constants.get([cls + "_image", cls + "_scale"], function(value, scale) {
                console.log("value");
                console.log(value);
                var beeTexture = PIXI.Texture.fromImage(value, true);
                var beeSprite = new PIXI.Sprite(beeTexture);

                beeSprite.anchor.x = 0.5;
                beeSprite.anchor.y = 0.5;

                beeSprite.scale.x = scale;
                beeSprite.scale.y = scale;

                e.addComponent(SpriteComponent(stage, beeSprite));
                e.addComponent(PhysicsComponent(body));
                if (controllable) {
                    e.addComponent(MovableComponent());
                    Constants.get("movement_speed", function(x) {
                        e({id: "setMovementSpeed", speed: x});
                    });
                    Constants.get("movement_vertical", function(x) {
                        e({id: "setVerticalSpeed", speed: x});
                    });
                }
                console.log("here");
                World.add(e);
            });
        };

        this.draw = function() {
            that.world.DrawDebugData();
        };

        var velocityIterations = 12, positionIterations = 12;

        Constants.get(["physics_velocityIterations",
                       "physics_positionIterations"],
                       function(x, y) {
                           velocityIterations = x;
                           positionIterations = y;
                       });

        this.update = function() {
            if (Math.abs(targetRotation - rotation) > turnRate) {
                function sign(x) { return x ? x < 0 ? -1 : 1 : 0; }
                direction = sign(targetRotation - rotation);
                rotation += direction * turnRate;
                that.world.SetGravity(newGravity());
            }

            that.world.Step(1/60, velocityIterations, positionIterations);
            that.world.ClearForces();
        };

        this.getRotation = function() {
            return rotation;
        };

        this.setTargetRotation = function(rotation) {
            targetRotation = rotation;
        };

        function newGravity() {
            var vector = rotate([0, gravity*PIXELS_PER_METER]);
            return new b2Vec2(vector[0], vector[1]);
        }

        function rotate(vec) {
            var sine   = Math.sin(rotation * (Math.PI/180));
            var cosine = Math.cos(rotation * (Math.PI/180));
            return [vec[0] * cosine + vec[1] * sine,
                    vec[0] * -sine + vec[1] * cosine];
        }

        function addWall(x, y, width, height, rotation, offset1, offset2) {
            //floor
            var floorDef                 = new b2FixtureDef;
            floorDef.shape               = new b2PolygonShape();
            floorDef.friction            = 0.2;
            floorDef.restitution         = 0.7;
            floorDef.shape.SetAsOrientedBox(width/2, height/2, new b2Vec2(offset1, offset2), rotation * Math.PI/180);

            var floorBodyDef                  = new b2BodyDef();
            floorBodyDef.type                 = b2Body.b2_staticBody;
            floorBodyDef.position.x           = x/PIXELS_PER_METER;
            floorBodyDef.position.y           = y/PIXELS_PER_METER;
            var body = that.world.CreateBody(floorBodyDef)
            var fix = body.CreateFixture(floorDef);
            setPhysicalProperties('wall', fix, true);
        }

        function newWorld() {
            addWall(gameWidth/2, 0, 10000, 3, 0, 0, 0);
            addWall(gameWidth/2, gameHeight, 10000, 3, 0, 0, 0);
            addWall(0, gameHeight/2, 3, 100000, 0, 0, 0);
            addWall(gameWidth, gameHeight/2, 3, 100000, 0, 0, 0);
            //addWall(gameWidth, gameHeight/2, 100000, 3, 45, 3, 3);
            addWall(gameWidth+100, gameHeight/2, 100000, 3, 45, 0, 0);
            addWall(-100, gameHeight/2, 100000, 3, 45, 0, 0);
            addWall(gameWidth/2, -100, 10000, 3, -45, 0, 0);
            addWall(gameWidth/2, gameHeight+100, 10000, 3, -45, 0, 0);
            var myContactListener = function() {
                return {
                    "BeginContact" : function() {
                        console.log("lol");
                    },
                    "EndContact" : function() {
                    },
                    "PreSolve" : function() {
                    },
                    "PostSolve" : function() {
                    }
                }
            };
            that.world.SetContactListener(myContactListener());
        }

        this.newGoal = function(gameSize) {
            Constants.get(["goal_width", "goal_height"], function(width, height) {
                //floor
                var floorDef                 = new b2FixtureDef;
                floorDef.shape               = new b2PolygonShape();
                floorDef.IsSensor            = true;
                floorDef.friction            = 0.2;
                floorDef.restitution         = 0.7;
                floorDef.shape.SetAsOrientedBox(width/2, height/2);

                var floorBodyDef                  = new b2BodyDef();
                floorBodyDef.type                 = b2Body.b2_staticBody;
                floorBodyDef.position.x           = gameSize*0.5/PIXELS_PER_METER;
                floorBodyDef.position.y           = gameSize*0.5/PIXELS_PER_METER;
                that.world.CreateBody(floorBodyDef).CreateFixture(floorDef);
            });
        }

        this.rotate = rotate;
    };
}();
<|endoftext|>


<commit_before>var Physics = function() {
    PIXELS_PER_METER = 16;
    return function(context, gameWidth, gameHeight, endGameCallback) {
        var that = this;
        function newDebugDraw() {
            var debugDraw = new b2DebugDraw();
            debugDraw.SetSprite(document.getElementById("sup").getContext("2d"));
            debugDraw.SetDrawScale(PIXELS_PER_METER*that.debugScale);
            debugDraw.SetFillAlpha(0.5);
            debugDraw.SetLineThickness(1.0);
            debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
            return debugDraw;
        }

        var b2Vec2 = Box2D.Common.Math.b2Vec2;
        var b2BodyDef = Box2D.Dynamics.b2BodyDef;
        var b2Body = Box2D.Dynamics.b2Body;
        var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
        var b2Fixture = Box2D.Dynamics.b2Fixture;
        var b2World = Box2D.Dynamics.b2World;
        var b2MassData = Box2D.Collision.Shapes.b2MassData;
        var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
        var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
        var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
        var b2Settings = Box2D.Common.b2Settings;
        this.toRemove = [];
        this.boxesRemoved = 0;

        b2Settings.b2_maxTranslation = 10000.0;
        b2Settings.b2_maxTranslationSquared = 10000.0*10000.0;
        b2Settings.b2MixRestitution = function(r1, r2) {
            if (r1 === undefined)
                r1 = 0;
            if (r2 === undefined)
                r2 = 0;
            return Math.min(r1, r2);
        };

        var turnRate = Constants.k('world_rotation_rate');
        var targetRotation = 0;
        var rotation = 0;
        var gravity = 0.00001;

        this.world = new b2World(newGravity(), false);
        this.world.UserData = this;

        var debugDraw = newDebugDraw();

        if (Constants.k('debug_physics')) {
            that.world.SetDebugDraw(debugDraw);
        } else {
            that.world.SetDebugDraw(null);
            debugDraw.m_sprite.graphics.clear();
        }

        gravity = Constants.k('world_gravity');
        that.world.SetGravity(newGravity());

        var setPhysicalProperties = function(cls, fix, massless) {
            if (massless === undefined) {
                massless = false;
            }
            fix.SetFriction(Constants.k(cls + '_friction'));
            fix.SetRestitution(Constants.k(cls + '_restitution'));
            if (!massless) {
                fix.SetDensity(Constants.k(cls + '_density'));
            }
        };

        newWorld(endGameCallback);

        this.newBlock = function(cls, stage) {
            var fd                 = new b2FixtureDef;
            fd.shape               = new b2PolygonShape();
            fd.density = 1.0;
            fd.friction = 0.3;
            fd.restitution = 0.1;

            badBlockChance = Constants.k('block_bad_prob');
            var killsYou = Math.random() < badBlockChance;
            if (cls == "block" && killsYou) {
                cls = "block_bad";
            }

            value = Constants.k(cls + '_image');
            scale = Constants.k(cls + '_scale');
            flags = Constants.k(cls + '_flags');
            size = Constants.k('game_size');
            dist = Constants.k('mousehole_spawn_distance');
            randomness = Constants.k('spawn_randomness');
            var bodyDef                  = new b2BodyDef();
            bodyDef.type                 = b2Body.b2_dynamicBody;
            if (/c/.exec(flags)) {
                fd.shape.SetAsBox(1, 2.5);
            } else {
                fd.shape.SetAsBox(1, 1);
            }
            var radius = dist;
            var gravVec = newGravity()
            gravVec.NegativeSelf();
            gravVec.Normalize();
            gravVec.Multiply(radius);

            var x = size/2+gravVec.x+Math.random()*randomness-randomness/2;
            var y = size/2+gravVec.y+Math.random()*randomness-randomness/2;

            bodyDef.position.x           = x/PIXELS_PER_METER;
            bodyDef.position.y           = y/PIXELS_PER_METER;
            bodyDef.allowSleep           = false;
            if (/f/.exec(flags)) {
                bodyDef.fixedRotation = true;
            }
            var body = that.world.CreateBody(bodyDef);
            var fix = body.CreateFixture(fd);
            setPhysicalProperties(cls, fix);

            var e = new BaseEntity();

            // pick a source
            value = value.split(' ');
            value = value[Math.floor(Math.random() * value.length)];
            var beeTexture = PIXI.Texture.fromImage(value, true);
            var beeSprite = new PIXI.Sprite(beeTexture);

            if (/c/.exec(flags)) {
                beeSprite.anchor.x = 0.42;
            } else {
                beeSprite.anchor.x = 0.5;
            }
            beeSprite.anchor.y = 0.5;

            beeSprite.scale.x = scale;
            beeSprite.scale.y = scale;

            e = new PhysicsEntityAdapter(body, e)
            e = new SpriteAdapter(stage, beeSprite, e);
            if (/f/.exec(flags)) {
                e = new RotateWithWorldAdapter(e);
            }
            if (/d/.exec(flags)) {
                e = new PoisonAdapter(endGameCallback, 'player', e);
            }
            if (/g/.exec(flags)) {
                e = new TagAdapter(['worthPoints', 'grabbable'], e);
                e = new ScoreAdapter(e);
            }
            if (/t/.exec(flags)) {
                e = new TagAdapter(['block'], e);
                e = new LimitedLifespanAdapter(10, function() {
                    var total = 0;
                    World.all(function(x) {
                        if (e.hasTag('block')) {
                            total += 1;
                        }
                    });
                    return total > 20;
                }, e);
            }
            if (/c/.exec(flags)) {
                e = new TagAdapter(['player'], e);
                e = new LateralMovementAdapter(e);
                e = new GrabAdapter(e);
                e = new JumpAdapter(e);
                e = new DebugLateralMovementAdapter(e);
                e = new JumpSpacingAdapter(e);
                e = new ControlAdapter(e);
                body.SetUserData({tag: "PLAYER", entity:e});
            } else {
                body.SetUserData({tag: "BLOCK", entity:e, "spawnTime":unixTime()});
            }
            World.add(e);
        };

        this.draw = function(scaleFactor) {
            that.debugScale = scaleFactor;
            that.world.SetDebugDraw(newDebugDraw());
            that.world.DrawDebugData();
        };

        var doneRotating = true
        this.update = function(callback) {
            if (Math.abs(targetRotation - rotation) > turnRate) {
                doneRotating = false;
                function sign(x) { return x ? x < 0 ? -1 : 1 : 0; }
                direction = sign(targetRotation - rotation);
                rotation += direction * turnRate;
                that.world.SetGravity(newGravity());
            } else {
                if (!doneRotating) {
                    rotation = targetRotation;
                    callback();
                    doneRotating = true;
                }
            }

            that.toRemove = [];
            that.world.Step(1/60, Constants.k('physics_velocityIterations'), Constants.k('physics_positionIterations'));
            for (var i = 0; i < that.toRemove.length; i++) {
                var body = that.toRemove[i];
                that.world.DestroyBody(body);
                World.del(body.GetUserData().entity);
                that.boxesRemoved += 1;
            }
            that.world.ClearForces();
        };

        this.getRotation = function() {
            return rotation;
        };

        this.setTargetRotation = function(rotation) {
            targetRotation = rotation;
        };

        function newGravity() {
            var vector = rotate([0, gravity*PIXELS_PER_METER]);
            return new b2Vec2(vector[0], vector[1]);
        }

        function rotate(vec) {
            var sine   = Math.sin(rotation * (Math.PI/180));
            var cosine = Math.cos(rotation * (Math.PI/180));
            return [vec[0] * cosine + vec[1] * sine,
                   vec[0] * -sine + vec[1] * cosine];
        }

        function newPlatform(x, y, width, height, orientation) {
            var orientationRadians  = orientation * (Math.PI/180);
            var platformDef         = new b2FixtureDef;
            platformDef.shape       = new b2PolygonShape();
            platformDef.friction    = 0.2;
            platformDef.restitution = 0.7;
            platformDef.shape.SetAsOrientedBox(width/2, height/2, new b2Vec2(0, 0), orientationRadians);

            var platformBodyDef    = new b2BodyDef();
            platformBodyDef.type   = b2Body.b2_staticBody;
            platformBodyDef.position.x = x/PIXELS_PER_METER;
            platformBodyDef.position.y = y/PIXELS_PER_METER;
            var body = that.world.CreateBody(platformBodyDef);
            body.SetAngle(orientationRadians);

            body.SetUserData({'tag': 'WALL'});

            var fix = body.CreateFixture(platformDef);
            setPhysicalProperties('platform', fix, true);

        }

        function addWall(x, y, width, height, rotation, offset1, offset2) {
            //floor
            var floorDef                 = new b2FixtureDef;
            floorDef.shape               = new b2PolygonShape();
            floorDef.friction            = 0.2;
            floorDef.restitution         = 0.7;
            floorDef.shape.SetAsOrientedBox(width/2, height/2, new b2Vec2(offset1, offset2), rotation * Math.PI/180);

            var floorBodyDef                  = new b2BodyDef();
            floorBodyDef.type                 = b2Body.b2_staticBody;
            floorBodyDef.position.x           = x/PIXELS_PER_METER;
            floorBodyDef.position.y           = y/PIXELS_PER_METER;
            var body = that.world.CreateBody(floorBodyDef)
            body.SetUserData({'tag': 'WALL'});
            var fix = body.CreateFixture(floorDef);
            setPhysicalProperties('wall', fix, true);
        }

        function newWorld(endGameCallback) {
            addWall(gameWidth/2, 0, 10000, 3, 0, 0, 0);
            addWall(gameWidth/2, gameHeight, 10000, 3, 0, 0, 0);
            addWall(0, gameHeight/2, 3, 100000, 0, 0, 0);
            addWall(gameWidth, gameHeight/2, 3, 100000, 0, 0, 0);
            //addWall(gameWidth, gameHeight/2, 100000, 3, 45, 3, 3);
            addWall(gameWidth+gameWidth*0.25, gameHeight/2, 100000, 3, 45, 0, 0);
            addWall(-gameWidth*0.25, gameHeight/2, 100000, 3, 45, 0, 0);
            addWall(gameWidth/2, -gameHeight*0.25, 10000, 3, -45, 0, 0);
            addWall(gameWidth/2, gameHeight+gameHeight*0.25, 10000, 3, -45, 0, 0);
            var platThickness = 0.7;
            var platLength = 5;
            newPlatform((1/2)*gameWidth, (2/7)*gameHeight, platLength, platThickness, 90);
            newPlatform((1/2)*gameWidth, (5/7)*gameHeight, platLength, platThickness, 270);
            newPlatform((2/7)*gameWidth, (1/2)*gameHeight, platThickness, platLength, 0);
            newPlatform((5/7)*gameWidth, (1/2)*gameHeight, platThickness, platLength, 180);
            var myContactListener = {
                "BeginContact" : function(contact) {
                    var data1 = contact.GetFixtureA().GetBody().GetUserData();
                    var data2 = contact.GetFixtureB().GetBody().GetUserData();
                    if (data1 && data2) {
                        if (data1.entity !== undefined && data2.entity !== undefined) {
                            data1.entity.collideInto(data2.entity);
                            data2.entity.collideInto(data1.entity);
                        }
                        if (data1.tag == "WALL" && data2.entity != null) {
                            data2.entity.doHitWall();
                        }
                        if (data2.tag == "WALL" && data1.entity != null) {
                            data1.entity.doHitWall();
                        }
                    }
                },
                "EndContact" : function() {
                },
                "PreSolve" : function() {
                },
                "PostSolve" : function() {
                }
            };
            that.world.SetContactListener(myContactListener);
        }

        this.newGoal = function(gameSize, stage) {
            width = Constants.k('goal_width');
            height = Constants.k('goal_height');
            image = Constants.k('goal_image');
            scale = Constants.k('goal_scale');
            //floor
            var floorDef                 = new b2FixtureDef;
            floorDef.shape               = new b2PolygonShape();
            floorDef.isSensor            = true;
            //floorDef.friction            = 0.2;
            //floorDef.restitution         = 0.7;
            floorDef.shape.SetAsBox(width/2, height/2);

            var floorBodyDef                  = new b2BodyDef();
            floorBodyDef.type                 = b2Body.b2_staticBody;
            floorBodyDef.position.x           = gameSize*0.5/PIXELS_PER_METER;
            floorBodyDef.position.y           = gameSize*0.5/PIXELS_PER_METER;
            var body = that.world.CreateBody(floorBodyDef);

            body.SetUserData({tag: "GOAL"});
            var fix = body.CreateFixture(floorDef);

            var e = new BaseEntity();

            var beeTexture = PIXI.Texture.fromImage(image, true);
            var beeSprite = new PIXI.Sprite(beeTexture);

            beeSprite.anchor.x = 0.5;
            beeSprite.anchor.y = 0.5;

            beeSprite.scale.x = scale;
            beeSprite.scale.y = scale;
            e = new PhysicsEntityAdapter(body, e);
            e = new SpriteAdapter(stage, beeSprite, e);
            e = new PoisonAdapter(function(x) {
                x.doHitGoal();
            }, 'worthPoints', e);
            World.add(e);
        }

        this.rotate = rotate;
    };
}();
<commit_msg>Make entities just have the tag ENTITY<commit_after>var Physics = function() {
    PIXELS_PER_METER = 16;
    return function(context, gameWidth, gameHeight, endGameCallback) {
        var that = this;
        function newDebugDraw() {
            var debugDraw = new b2DebugDraw();
            debugDraw.SetSprite(document.getElementById("sup").getContext("2d"));
            debugDraw.SetDrawScale(PIXELS_PER_METER*that.debugScale);
            debugDraw.SetFillAlpha(0.5);
            debugDraw.SetLineThickness(1.0);
            debugDraw.SetFlags(b2DebugDraw.e_shapeBit | b2DebugDraw.e_jointBit);
            return debugDraw;
        }

        var b2Vec2 = Box2D.Common.Math.b2Vec2;
        var b2BodyDef = Box2D.Dynamics.b2BodyDef;
        var b2Body = Box2D.Dynamics.b2Body;
        var b2FixtureDef = Box2D.Dynamics.b2FixtureDef;
        var b2Fixture = Box2D.Dynamics.b2Fixture;
        var b2World = Box2D.Dynamics.b2World;
        var b2MassData = Box2D.Collision.Shapes.b2MassData;
        var b2PolygonShape = Box2D.Collision.Shapes.b2PolygonShape;
        var b2CircleShape = Box2D.Collision.Shapes.b2CircleShape;
        var b2DebugDraw = Box2D.Dynamics.b2DebugDraw;
        var b2Settings = Box2D.Common.b2Settings;
        this.toRemove = [];
        this.boxesRemoved = 0;

        b2Settings.b2_maxTranslation = 10000.0;
        b2Settings.b2_maxTranslationSquared = 10000.0*10000.0;
        b2Settings.b2MixRestitution = function(r1, r2) {
            if (r1 === undefined)
                r1 = 0;
            if (r2 === undefined)
                r2 = 0;
            return Math.min(r1, r2);
        };

        var turnRate = Constants.k('world_rotation_rate');
        var targetRotation = 0;
        var rotation = 0;
        var gravity = 0.00001;

        this.world = new b2World(newGravity(), false);
        this.world.UserData = this;

        var debugDraw = newDebugDraw();

        if (Constants.k('debug_physics')) {
            that.world.SetDebugDraw(debugDraw);
        } else {
            that.world.SetDebugDraw(null);
            debugDraw.m_sprite.graphics.clear();
        }

        gravity = Constants.k('world_gravity');
        that.world.SetGravity(newGravity());

        var setPhysicalProperties = function(cls, fix, massless) {
            if (massless === undefined) {
                massless = false;
            }
            fix.SetFriction(Constants.k(cls + '_friction'));
            fix.SetRestitution(Constants.k(cls + '_restitution'));
            if (!massless) {
                fix.SetDensity(Constants.k(cls + '_density'));
            }
        };

        newWorld(endGameCallback);

        this.newBlock = function(cls, stage) {
            var fd                 = new b2FixtureDef;
            fd.shape               = new b2PolygonShape();
            fd.density = 1.0;
            fd.friction = 0.3;
            fd.restitution = 0.1;

            badBlockChance = Constants.k('block_bad_prob');
            var killsYou = Math.random() < badBlockChance;
            if (cls == "block" && killsYou) {
                cls = "block_bad";
            }

            value = Constants.k(cls + '_image');
            scale = Constants.k(cls + '_scale');
            flags = Constants.k(cls + '_flags');
            size = Constants.k('game_size');
            dist = Constants.k('mousehole_spawn_distance');
            randomness = Constants.k('spawn_randomness');
            var bodyDef                  = new b2BodyDef();
            bodyDef.type                 = b2Body.b2_dynamicBody;
            if (/c/.exec(flags)) {
                fd.shape.SetAsBox(1, 2.5);
            } else {
                fd.shape.SetAsBox(1, 1);
            }
            var radius = dist;
            var gravVec = newGravity()
            gravVec.NegativeSelf();
            gravVec.Normalize();
            gravVec.Multiply(radius);

            var x = size/2+gravVec.x+Math.random()*randomness-randomness/2;
            var y = size/2+gravVec.y+Math.random()*randomness-randomness/2;

            bodyDef.position.x           = x/PIXELS_PER_METER;
            bodyDef.position.y           = y/PIXELS_PER_METER;
            bodyDef.allowSleep           = false;
            if (/f/.exec(flags)) {
                bodyDef.fixedRotation = true;
            }
            var body = that.world.CreateBody(bodyDef);
            var fix = body.CreateFixture(fd);
            setPhysicalProperties(cls, fix);

            var e = new BaseEntity();

            // pick a source
            value = value.split(' ');
            value = value[Math.floor(Math.random() * value.length)];
            var beeTexture = PIXI.Texture.fromImage(value, true);
            var beeSprite = new PIXI.Sprite(beeTexture);

            if (/c/.exec(flags)) {
                beeSprite.anchor.x = 0.42;
            } else {
                beeSprite.anchor.x = 0.5;
            }
            beeSprite.anchor.y = 0.5;

            beeSprite.scale.x = scale;
            beeSprite.scale.y = scale;

            e = new PhysicsEntityAdapter(body, e)
            e = new SpriteAdapter(stage, beeSprite, e);
            if (/f/.exec(flags)) {
                e = new RotateWithWorldAdapter(e);
            }
            if (/d/.exec(flags)) {
                e = new PoisonAdapter(endGameCallback, 'player', e);
            }
            if (/g/.exec(flags)) {
                e = new TagAdapter(['worthPoints', 'grabbable'], e);
                e = new ScoreAdapter(e);
            }
            if (/t/.exec(flags)) {
                e = new TagAdapter(['block'], e);
                e = new LimitedLifespanAdapter(10, function() {
                    var total = 0;
                    World.all(function(x) {
                        if (e.hasTag('block')) {
                            total += 1;
                        }
                    });
                    return total > 20;
                }, e);
            }
            if (/c/.exec(flags)) {
                e = new TagAdapter(['player'], e);
                e = new LateralMovementAdapter(e);
                e = new GrabAdapter(e);
                e = new JumpAdapter(e);
                e = new DebugLateralMovementAdapter(e);
                e = new JumpSpacingAdapter(e);
                e = new ControlAdapter(e);
            }
            body.SetUserData({tag: "ENTITY", entity:e});
            World.add(e);
        };

        this.draw = function(scaleFactor) {
            that.debugScale = scaleFactor;
            that.world.SetDebugDraw(newDebugDraw());
            that.world.DrawDebugData();
        };

        var doneRotating = true
        this.update = function(callback) {
            if (Math.abs(targetRotation - rotation) > turnRate) {
                doneRotating = false;
                function sign(x) { return x ? x < 0 ? -1 : 1 : 0; }
                direction = sign(targetRotation - rotation);
                rotation += direction * turnRate;
                that.world.SetGravity(newGravity());
            } else {
                if (!doneRotating) {
                    rotation = targetRotation;
                    callback();
                    doneRotating = true;
                }
            }

            that.toRemove = [];
            that.world.Step(1/60, Constants.k('physics_velocityIterations'), Constants.k('physics_positionIterations'));
            for (var i = 0; i < that.toRemove.length; i++) {
                var body = that.toRemove[i];
                that.world.DestroyBody(body);
                World.del(body.GetUserData().entity);
                that.boxesRemoved += 1;
            }
            that.world.ClearForces();
        };

        this.getRotation = function() {
            return rotation;
        };

        this.setTargetRotation = function(rotation) {
            targetRotation = rotation;
        };

        function newGravity() {
            var vector = rotate([0, gravity*PIXELS_PER_METER]);
            return new b2Vec2(vector[0], vector[1]);
        }

        function rotate(vec) {
            var sine   = Math.sin(rotation * (Math.PI/180));
            var cosine = Math.cos(rotation * (Math.PI/180));
            return [vec[0] * cosine + vec[1] * sine,
                   vec[0] * -sine + vec[1] * cosine];
        }

        function newPlatform(x, y, width, height, orientation) {
            var orientationRadians  = orientation * (Math.PI/180);
            var platformDef         = new b2FixtureDef;
            platformDef.shape       = new b2PolygonShape();
            platformDef.friction    = 0.2;
            platformDef.restitution = 0.7;
            platformDef.shape.SetAsOrientedBox(width/2, height/2, new b2Vec2(0, 0), orientationRadians);

            var platformBodyDef    = new b2BodyDef();
            platformBodyDef.type   = b2Body.b2_staticBody;
            platformBodyDef.position.x = x/PIXELS_PER_METER;
            platformBodyDef.position.y = y/PIXELS_PER_METER;
            var body = that.world.CreateBody(platformBodyDef);
            body.SetAngle(orientationRadians);

            body.SetUserData({'tag': 'WALL'});

            var fix = body.CreateFixture(platformDef);
            setPhysicalProperties('platform', fix, true);

        }

        function addWall(x, y, width, height, rotation, offset1, offset2) {
            //floor
            var floorDef                 = new b2FixtureDef;
            floorDef.shape               = new b2PolygonShape();
            floorDef.friction            = 0.2;
            floorDef.restitution         = 0.7;
            floorDef.shape.SetAsOrientedBox(width/2, height/2, new b2Vec2(offset1, offset2), rotation * Math.PI/180);

            var floorBodyDef                  = new b2BodyDef();
            floorBodyDef.type                 = b2Body.b2_staticBody;
            floorBodyDef.position.x           = x/PIXELS_PER_METER;
            floorBodyDef.position.y           = y/PIXELS_PER_METER;
            var body = that.world.CreateBody(floorBodyDef)
            body.SetUserData({'tag': 'WALL'});
            var fix = body.CreateFixture(floorDef);
            setPhysicalProperties('wall', fix, true);
        }

        function newWorld(endGameCallback) {
            addWall(gameWidth/2, 0, 10000, 3, 0, 0, 0);
            addWall(gameWidth/2, gameHeight, 10000, 3, 0, 0, 0);
            addWall(0, gameHeight/2, 3, 100000, 0, 0, 0);
            addWall(gameWidth, gameHeight/2, 3, 100000, 0, 0, 0);
            //addWall(gameWidth, gameHeight/2, 100000, 3, 45, 3, 3);
            addWall(gameWidth+gameWidth*0.25, gameHeight/2, 100000, 3, 45, 0, 0);
            addWall(-gameWidth*0.25, gameHeight/2, 100000, 3, 45, 0, 0);
            addWall(gameWidth/2, -gameHeight*0.25, 10000, 3, -45, 0, 0);
            addWall(gameWidth/2, gameHeight+gameHeight*0.25, 10000, 3, -45, 0, 0);
            var platThickness = 0.7;
            var platLength = 5;
            newPlatform((1/2)*gameWidth, (2/7)*gameHeight, platLength, platThickness, 90);
            newPlatform((1/2)*gameWidth, (5/7)*gameHeight, platLength, platThickness, 270);
            newPlatform((2/7)*gameWidth, (1/2)*gameHeight, platThickness, platLength, 0);
            newPlatform((5/7)*gameWidth, (1/2)*gameHeight, platThickness, platLength, 180);
            var myContactListener = {
                "BeginContact" : function(contact) {
                    var data1 = contact.GetFixtureA().GetBody().GetUserData();
                    var data2 = contact.GetFixtureB().GetBody().GetUserData();
                    if (data1 && data2) {
                        if (data1.entity !== undefined && data2.entity !== undefined) {
                            data1.entity.collideInto(data2.entity);
                            data2.entity.collideInto(data1.entity);
                        }
                        if (data1.tag == "WALL" && data2.entity != null) {
                            data2.entity.doHitWall();
                        }
                        if (data2.tag == "WALL" && data1.entity != null) {
                            data1.entity.doHitWall();
                        }
                    }
                },
                "EndContact" : function() {
                },
                "PreSolve" : function() {
                },
                "PostSolve" : function() {
                }
            };
            that.world.SetContactListener(myContactListener);
        }

        this.newGoal = function(gameSize, stage) {
            width = Constants.k('goal_width');
            height = Constants.k('goal_height');
            image = Constants.k('goal_image');
            scale = Constants.k('goal_scale');
            //floor
            var floorDef                 = new b2FixtureDef;
            floorDef.shape               = new b2PolygonShape();
            floorDef.isSensor            = true;
            //floorDef.friction            = 0.2;
            //floorDef.restitution         = 0.7;
            floorDef.shape.SetAsBox(width/2, height/2);

            var floorBodyDef                  = new b2BodyDef();
            floorBodyDef.type                 = b2Body.b2_staticBody;
            floorBodyDef.position.x           = gameSize*0.5/PIXELS_PER_METER;
            floorBodyDef.position.y           = gameSize*0.5/PIXELS_PER_METER;
            var body = that.world.CreateBody(floorBodyDef);

            body.SetUserData({tag: "ENTITY"});
            var fix = body.CreateFixture(floorDef);

            var e = new BaseEntity();

            var beeTexture = PIXI.Texture.fromImage(image, true);
            var beeSprite = new PIXI.Sprite(beeTexture);

            beeSprite.anchor.x = 0.5;
            beeSprite.anchor.y = 0.5;

            beeSprite.scale.x = scale;
            beeSprite.scale.y = scale;
            e = new PhysicsEntityAdapter(body, e);
            e = new SpriteAdapter(stage, beeSprite, e);
            e = new PoisonAdapter(function(x) {
                x.doHitGoal();
            }, 'worthPoints', e);
            World.add(e);
        }

        this.rotate = rotate;
    };
}();
<|endoftext|>


<commit_before>const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const fs = require('fs');
const path = require('path');
const config = require('./config');
const moment = require('moment');
const spawn = require('child_process').spawn;
const Promise = require('bluebird');

function Picture(){

  this.filepath;
  this.keyname;
  this.url;

  this.getUrl = function(expires){
    expires = expires ? expires : 60;
    var params = {Bucket: config.aws_s3_bucket, Key: this.keyname, Expires: expires};
    this.url = s3.getSignedUrl('getObject', params);
  	return this.url;
  }
}

var captureProc = null;
function takePicture() {
  return new Promise(function(resolve){

    if(captureProc != null) {
      captureProc.kill();
      captureProc = null;
	  }

    var date = moment.utc();
    var datestr = date.format('YYYYMMDDHHmmss');
    var filename = datestr+".jpg";
    var filepath = path.join(config.capture_dir, filename);
    var keyname = date.format("YYYY/MM/DD/") + filename;
    var args = ["-awb", "auto", "-ex", "auto", "-w", config.capture_width, "-h", config.capture_height, "-vf", "-o", filepath];

    console.info(keyname + "\tcapture started")
    captureProc = spawn('raspistill', args);
    console.info(keyname + "\tcapture complete")

    var picture = new Picture();
    picture.filepath = filepath;
    picture.keyname = keyname;

    captureProc.on('close', function(code){
      resolve(picture);
	  });
  });
}

function uploadPicture(picture) {
  return new Promise(function(resolve, reject){
    fs.readFile(picture.filepath, function(err, data) {
      if(err) throw err;

      var s3bucket = new AWS.S3({params: {Bucket: config.aws_s3_bucket }});
      var params = {
        Key: picture.keyname,
        Body: data
      };

      console.info(picture.keyname + "\tupload started");
      s3bucket.upload(params, function (err, data) {
        if (err) {
        	reject(err);
        } else {
          console.info(picture.keyname + "\tupload complete");
          resolve(picture);
        }
      });
	  });
  });
}

function deleteFile(picture) {
  return new Promise(function(resolve, reject){
    fs.unlink(picture.filepath, function(err){
      if (err) throw err;
      console.info(picture.keyname + "\tdeleted local file\t" + picture.filepath);
      resolve(picture);
    });
  });
}

function capture(){
  takePicture()
    .then(uploadPicture)
    .then(deleteFile)
    .then(function(picture){
      console.info(picture.keyname + "\turl created\t" + picture.getUrl(60));
    });
}

var interval;
var pid_path = path.join(__dirname,'pilapse.pid');

function start(){

  fs.access(pid_path, function (err) {
    if (!err) throw new Error('PID file exists at ' + pid_path);
  });

  var pid = String(process.pid);
  fs.writeFile(pid_path, pid, function(err) {
    if (err) throw err;
  });

  console.info("process\tstarting timelapse\t" + config.capture_frequency + " seconds");

  capture(); // take picture on start
  interval = setInterval(function(){
    capture();
  }, config.capture_frequency * 1000)
}

function stop(){

  fs.unlink(pid_path, function(err){
    if (err) throw err;
  });

  if(interval) clearInterval(interval);
  console.info("process\thalting timelapse");
}

// MAIN :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

start();
process.on('SIGTERM', stop);
process.on('SIGINT', stop);
<commit_msg>Switching to readFile for compatibility<commit_after>const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const fs = require('fs');
const path = require('path');
const config = require('./config');
const moment = require('moment');
const spawn = require('child_process').spawn;
const Promise = require('bluebird');

function Picture(){

  this.filepath;
  this.keyname;
  this.url;

  this.getUrl = function(expires){
    expires = expires ? expires : 60;
    var params = {Bucket: config.aws_s3_bucket, Key: this.keyname, Expires: expires};
    this.url = s3.getSignedUrl('getObject', params);
  	return this.url;
  }
}

var captureProc = null;
function takePicture() {
  return new Promise(function(resolve){

    if(captureProc != null) {
      captureProc.kill();
      captureProc = null;
	  }

    var date = moment.utc();
    var datestr = date.format('YYYYMMDDHHmmss');
    var filename = datestr+".jpg";
    var filepath = path.join(config.capture_dir, filename);
    var keyname = date.format("YYYY/MM/DD/") + filename;
    var args = ["-awb", "auto", "-ex", "auto", "-w", config.capture_width, "-h", config.capture_height, "-vf", "-o", filepath];

    console.info(keyname + "\tcapture started")
    captureProc = spawn('raspistill', args);
    console.info(keyname + "\tcapture complete")

    var picture = new Picture();
    picture.filepath = filepath;
    picture.keyname = keyname;

    captureProc.on('close', function(code){
      resolve(picture);
	  });
  });
}

function uploadPicture(picture) {
  return new Promise(function(resolve, reject){
    fs.readFile(picture.filepath, function(err, data) {
      if(err) throw err;

      var s3bucket = new AWS.S3({params: {Bucket: config.aws_s3_bucket }});
      var params = {
        Key: picture.keyname,
        Body: data
      };

      console.info(picture.keyname + "\tupload started");
      s3bucket.upload(params, function (err, data) {
        if (err) {
        	reject(err);
        } else {
          console.info(picture.keyname + "\tupload complete");
          resolve(picture);
        }
      });
	  });
  });
}

function deleteFile(picture) {
  return new Promise(function(resolve, reject){
    fs.unlink(picture.filepath, function(err){
      if (err) throw err;
      console.info(picture.keyname + "\tdeleted local file\t" + picture.filepath);
      resolve(picture);
    });
  });
}

function capture(){
  takePicture()
    .then(uploadPicture)
    .then(deleteFile)
    .then(function(picture){
      console.info(picture.keyname + "\turl created\t" + picture.getUrl(60));
    });
}

var interval;
var pid_path = path.join(__dirname,'pilapse.pid');

function start(){

  fs.readFile(pid_path, function(err, data){
    if(!err) throw new Error('Process '+ data +' already running from '+pid_path);
  });

  fs.access(pid_path, function (err) {
    if (!err) throw new Error('PID file exists at ' + pid_path);
  });

  var pid = String(process.pid);
  fs.writeFile(pid_path, pid, function(err) {
    if (err) throw err;
  });

  console.info("process\tstarting timelapse\t" + config.capture_frequency + " seconds");

  capture(); // take picture on start
  interval = setInterval(function(){
    capture();
  }, config.capture_frequency * 1000)
}

function stop(){

  fs.unlink(pid_path, function(err){
    if (err) throw err;
  });

  if(interval) clearInterval(interval);
  console.info("process\thalting timelapse");
}

// MAIN :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

start();
process.on('SIGTERM', stop);
process.on('SIGINT', stop);
<|endoftext|>


<commit_before>import { combineReducers } from 'redux';
import { createKeyedReducer, createPaginationReducer } from 'app/utils/reducers';

const reducer = combineReducers({
  conversations: createPaginationReducer([
    'REQUEST_CONVERSATIONS',
    'RECEIVE_CONVERSATIONS_SUCCESS',
    'RECEIVE_CONVERSATIONS_FAILURE',
  ]),
  messagesByConversation: createKeyedReducer(
    action => action.payload && action.payload.conversationId,
    createPaginationReducer([
      'REQUEST_MESSAGES',
      'RECEIVE_MESSAGES_SUCCESS',
      'RECEIVE_MESSAGES_FAILURE',
    ])
  ),
});

export default reducer;
<commit_msg>client: quickfix messagesByConversation reducer<commit_after>import { combineReducers } from 'redux';
import contains from 'lodash/collection/includes';
import { createKeyedReducer, createPaginationReducer } from 'app/utils/reducers';

const reducer = combineReducers({
  conversations: createPaginationReducer([
    'REQUEST_CONVERSATIONS',
    'RECEIVE_CONVERSATIONS_SUCCESS',
    'RECEIVE_CONVERSATIONS_FAILURE',
  ]),
  messagesByConversation: createKeyedReducer(
    action => contains(['REQUEST_MESSAGES', 'RECEIVE_MESSAGES_SUCCESS', 'RECEIVE_MESSAGES_FAILURE'], action.type)
              && action.payload.conversationId, // TODO: refactor
    createPaginationReducer([
      'REQUEST_MESSAGES',
      'RECEIVE_MESSAGES_SUCCESS',
      'RECEIVE_MESSAGES_FAILURE',
    ])
  ),
});

export default reducer;
<|endoftext|>


<commit_before>(function() {
	'use strict';

	/**
	 * (en)Agent의 Chart 정보를 로드하고 chart library에 사용할 수 있도록 데이터를 가공함.
	 * @ko Agent의 Chart 정보를 로드하고 chart library에 사용할 수 있도록 데이터를 가공함.
	 * @group Service
	 * @name AgentDaoService
	 * @class
	 */
	pinpointApp.constant( "agentDaoServiceConfig", {
	    agentStatUrl: "/getAgentStat.pinpoint",
		dateFormat: "YYYY-MM-DD HH:mm:ss"
	});

	pinpointApp.service( "AgentDaoService", [ "agentDaoServiceConfig",
	    function AgentDaoService( cfg ) {

			/**
			 * (en)선택한 Agent의 Chart 정보를 로드함.
			 * @ko 선택한 Agent의 Chart 정보를 로드함.
			 * @method AgentDaoService#getAgentStat
			 * @param {String} query
			 * @param {Function} cb
			 */
	        this.getAgentStat = function (query, cb) {
	            jQuery.ajax({
	                type: 'GET',
	                url: cfg.agentStatUrl,
	                cache: false,
	                dataType: 'json',
	                data: query,
	                success: function (result) {
	                    if (angular.isFunction(cb)) {
	                        cb(null, result);
	                    }
	                },
	                error: function (xhr, status, error) {
	                    if (angular.isFunction(cb)) {
	                        cb(error, {});
	                    }
	                }
	            });
	        };

	        /**
	         * calculate a sampling rate based on the given period
	         * @param period in minutes
	         */
	        this.getSampleRate = function (period) {
	            var MAX_POINTS = 100;
	            var points = period / 5;
	            var rate = Math.floor(points / MAX_POINTS);
	            return points <= MAX_POINTS ? 1 : rate;
	        };

	        /**
	         * parse memory chart data for amcharts
	         * @param info
	         * @param agentStat
	         * @returns {Array}
	         */
	        this.parseMemoryChartDataForAmcharts = function (info, agentStat) {
	            var newData = [],
	                pointsTime = agentStat.charts['JVM_GC_OLD_TIME'].points,
	                pointsCount = agentStat.charts['JVM_GC_OLD_COUNT'].points;

	            if (pointsTime.length !== pointsCount.length) {
	                throw new Error('assertion error', 'time.length != count.length');
	            }

	            var currTime, currCount, prevTime, prevCount; // for gc

	            for (var i = 0; i < pointsCount.length; ++i) {
	                var thisData = {
	                    time: moment(pointsTime[i].xVal).format( cfg.dateFormat )
	                };
	                for (var k in info.line) {
	                    if (info.line[k].isFgc) {
	                        var gcCount = 0;
	                        var gcTime = 0;
	                        currTime = pointsTime[i].maxYVal;
	                        currCount = pointsCount[i].maxYVal;
	                        if (!prevTime || !prevCount) {
	                            prevTime = currTime;
	                            prevCount = currCount;
	                        } else {
	                            var countDelta = currCount - prevCount;
	                            var timeDelta = currTime - prevTime;
	                            var fgcOccurred = (Math.abs(countDelta) > 0) && (Math.abs(timeDelta) > 0);
	                            var jvmRestarted = countDelta < 0 && timeDelta < 0;

	                            if (fgcOccurred) {
	                                if (jvmRestarted) {
	                                    gcCount = currCount;
	                                    gcTime = currTime;
	                                } else {
	                                    gcCount = currCount - prevCount;
	                                    gcTime = currTime - prevTime;
	                                }
	                                prevCount = currCount;
	                                prevTime = currTime;
	                            }
	                        }
	                        if (gcCount > 0 && gcTime > 0) {
	                            thisData[info.line[k].key+"Count"] = gcCount;
	                        	thisData[info.line[k].key+"Time"] = gcTime;
	                        }
	                    } else {
	                    	var value = agentStat.charts[info.line[k].id].points[i].maxYVal;
	                    	if ( value >= 0 ) {
	                    		thisData[info.line[k].key] = value;
	                    	}
	                    }

	                }

	                newData.push(thisData);
	            }
	            return newData;
	        };

	        /**
	         * parse cpuLoad chart data for amcharts
	         * @param cpuLoad
	         * @param agentStat
	         * @returns {Array}
	         */
	        this.parseCpuLoadChartDataForAmcharts = function (cpuLoad, agentStat) {
	            // Cpu Load data availability check
	            var jvmCpuLoadData = agentStat.charts['CPU_LOAD_JVM'];
	            var systemCpuLoadData = agentStat.charts['CPU_LOAD_SYSTEM'];
	            if (jvmCpuLoadData || systemCpuLoadData) {
	            	cpuLoad.isAvailable = true;
	            } else {
	            	return;
	            }
	            var newData = [],
	            pointsJvmCpuLoad = jvmCpuLoadData.points,
	            pointsSystemCpuLoad = systemCpuLoadData.points;

	            if (pointsJvmCpuLoad.length !== pointsSystemCpuLoad.length) {
	                throw new Error('assertion error', 'jvmCpuLoad.length != systemCpuLoad.length');
	            }

	            for (var i = 0; i < pointsJvmCpuLoad.length; ++i) {
	                if (pointsJvmCpuLoad[i].xVal !== pointsSystemCpuLoad[i].xVal) {
	                	throw new Error('assertion error', 'timestamp mismatch between jvmCpuLoad and systemCpuLoad');
	                }
	                var thisData = {
						time: moment(pointsJvmCpuLoad[i].xVal).format( cfg.dateFormat ),
	                    maxCpuLoad: 100
	                };
	                var jvmCpuLoad = typeof agentStat.charts['CPU_LOAD_JVM'].points[i].maxYVal == "number" ? agentStat.charts['CPU_LOAD_JVM'].points[i].maxYVal.toFixed(2) : 0.00;
	                var systemCpuLoad = typeof agentStat.charts['CPU_LOAD_SYSTEM'].points[i].maxYVal == "number" ? agentStat.charts['CPU_LOAD_SYSTEM'].points[i].maxYVal.toFixed(2) : 0.00;
	                if ( jvmCpuLoad >= 0 ) {
	                    thisData.jvmCpuLoad = jvmCpuLoad;
	                }
	                if ( systemCpuLoad >= 0 ) {
	                    thisData.systemCpuLoad = systemCpuLoad;
	                }
	                newData.push(thisData);
	            }
	            return newData;
	        };

            /**
             * parse tps chart data for amcharts
             * @param tps
             * @param agentStat
             * @returns {Array}
             */
	        this.parseTpsChartDataForAmcharts = function (tps, agentStat) {
	            // TPS data availability check
	        	var aSampledContinuationData = agentStat.charts['TPS_SAMPLED_CONTINUATION'].points;
	        	var aSampledNewData = agentStat.charts['TPS_SAMPLED_NEW'].points;
	        	var aUnsampledContinuationData = agentStat.charts['TPS_UNSAMPLED_CONTINUATION'].points;
	        	var aUnsampledNewData = agentStat.charts['TPS_UNSAMPLED_NEW'].points;
	        	var aTotalData = agentStat.charts['TPS_TOTAL'].points;
				var newData = [];
				var DATA_UNAVAILABLE = -1;

	        	var tpsLength = aTotalData.length;
	        	if ( tpsLength > 0 ) {
	        		tps.isAvailable = true;
	        	} else {
	        		return newData;
	        	}

	            for ( var i = 0 ; i < tpsLength ; i++ ) {
	            	var obj = {
						"time" : moment(aSampledContinuationData[i].xVal).format( cfg.dateFormat )
					};
					var sampledContinuationTps = getFloatValue( aSampledContinuationData[i].avgYVal );
					var sampledNewTps = getFloatValue( aSampledNewData[i].avgYVal );
					var unsampledContinuationTps = getFloatValue( aUnsampledContinuationData[i].avgYVal );
					var unsampledNewTps = getFloatValue( aUnsampledNewData[i].avgYVal );
					var totalTps = getFloatValue( aTotalData[i].avgYVal );

					if ( sampledContinuationTps != DATA_UNAVAILABLE ) {
						obj.sampledContinuationTps = sampledContinuationTps;
					}
					if ( sampledNewTps != DATA_UNAVAILABLE ) {
						obj.sampledNewTps = sampledNewTps;
					}
					if ( unsampledContinuationTps != DATA_UNAVAILABLE ) {
						obj.unsampledContinuationTps = unsampledContinuationTps;
					}
					if ( unsampledNewTps != DATA_UNAVAILABLE ) {
						obj.unsampledNewTps = unsampledNewTps;
					}
					if ( totalTps != DATA_UNAVAILABLE ) {
						obj.totalTps = totalTps;
					}
					newData.push( obj );
	            }

	            return newData;
	        };
			this.parseActiveTraceChartDataForAmcharts = function (activeTrace, agentStat) {
				var aActiveTraceFastData = agentStat.charts[ "ACTIVE_TRACE_FAST" ].points;
				var aActiveTraceNormal = agentStat.charts[ "ACTIVE_TRACE_NORMAL" ].points;
				var aActiveTraceSlow = agentStat.charts[ "ACTIVE_TRACE_SLOW" ].points;
				var aActiveTraceVerySlow = agentStat.charts[ "ACTIVE_TRACE_VERY_SLOW" ].points;
				var newData = [];
				var DATA_UNAVAILABLE = -1;

				if ( aActiveTraceFastData || aActiveTraceNormal || aActiveTraceSlow || aActiveTraceVerySlow ) {
					activeTrace.isAvailable = true;
				} else {
					return newData;
				}

				for ( var i = 0 ; i < aActiveTraceFastData.length ; i++ ) {
					var obj = {
						"time": moment(aActiveTraceFastData[i].xVal).format(cfg.dateFormat)
					};

					var fast = getFloatValue( aActiveTraceFastData[i].avgYVal );
					var normal = getFloatValue( aActiveTraceNormal[i].avgYVal );
					var slow = getFloatValue( aActiveTraceSlow[i].avgYVal );
					var verySlow = getFloatValue( aActiveTraceVerySlow[i].avgYVal );

					if ( fast != DATA_UNAVAILABLE ) {
						obj.fast = fast;
						obj.fastTitle = aActiveTraceFastData[i].title;
					}
					if ( normal != DATA_UNAVAILABLE ) {
						obj.normal = normal;
						obj.normalTitle = aActiveTraceNormal[i].title;
					}
					if ( slow != DATA_UNAVAILABLE ) {
						obj.slow = slow;
						obj.slowTitle = aActiveTraceSlow[i].title;
					}
					if ( verySlow != DATA_UNAVAILABLE ) {
						obj.verySlow = verySlow;
						obj.verySlowTitle = aActiveTraceVerySlow[i].title
					}
					newData.push( obj );
				}
				return newData;
			};
			function getFloatValue( val ) {
				return angular.isNumber( val ) ? val.toFixed(2) : 0.00;
			}
	    }
	]);
})();
<commit_msg>Fix jshint error<commit_after>(function() {
	'use strict';

	/**
	 * (en)Agent의 Chart 정보를 로드하고 chart library에 사용할 수 있도록 데이터를 가공함.
	 * @ko Agent의 Chart 정보를 로드하고 chart library에 사용할 수 있도록 데이터를 가공함.
	 * @group Service
	 * @name AgentDaoService
	 * @class
	 */
	pinpointApp.constant( "agentDaoServiceConfig", {
	    agentStatUrl: "/getAgentStat.pinpoint",
		dateFormat: "YYYY-MM-DD HH:mm:ss"
	});

	pinpointApp.service( "AgentDaoService", [ "agentDaoServiceConfig",
	    function AgentDaoService( cfg ) {

			/**
			 * (en)선택한 Agent의 Chart 정보를 로드함.
			 * @ko 선택한 Agent의 Chart 정보를 로드함.
			 * @method AgentDaoService#getAgentStat
			 * @param {String} query
			 * @param {Function} cb
			 */
	        this.getAgentStat = function (query, cb) {
	            jQuery.ajax({
	                type: 'GET',
	                url: cfg.agentStatUrl,
	                cache: false,
	                dataType: 'json',
	                data: query,
	                success: function (result) {
	                    if (angular.isFunction(cb)) {
	                        cb(null, result);
	                    }
	                },
	                error: function (xhr, status, error) {
	                    if (angular.isFunction(cb)) {
	                        cb(error, {});
	                    }
	                }
	            });
	        };

	        /**
	         * calculate a sampling rate based on the given period
	         * @param period in minutes
	         */
	        this.getSampleRate = function (period) {
	            var MAX_POINTS = 100;
	            var points = period / 5;
	            var rate = Math.floor(points / MAX_POINTS);
	            return points <= MAX_POINTS ? 1 : rate;
	        };

	        /**
	         * parse memory chart data for amcharts
	         * @param info
	         * @param agentStat
	         * @returns {Array}
	         */
	        this.parseMemoryChartDataForAmcharts = function (info, agentStat) {
	            var newData = [],
	                pointsTime = agentStat.charts['JVM_GC_OLD_TIME'].points,
	                pointsCount = agentStat.charts['JVM_GC_OLD_COUNT'].points;

	            if (pointsTime.length !== pointsCount.length) {
	                throw new Error('assertion error', 'time.length != count.length');
	            }

	            var currTime, currCount, prevTime, prevCount; // for gc

	            for (var i = 0; i < pointsCount.length; ++i) {
	                var thisData = {
	                    time: moment(pointsTime[i].xVal).format( cfg.dateFormat )
	                };
	                for (var k in info.line) {
	                    if (info.line[k].isFgc) {
	                        var gcCount = 0;
	                        var gcTime = 0;
	                        currTime = pointsTime[i].maxYVal;
	                        currCount = pointsCount[i].maxYVal;
	                        if (!prevTime || !prevCount) {
	                            prevTime = currTime;
	                            prevCount = currCount;
	                        } else {
	                            var countDelta = currCount - prevCount;
	                            var timeDelta = currTime - prevTime;
	                            var fgcOccurred = (Math.abs(countDelta) > 0) && (Math.abs(timeDelta) > 0);
	                            var jvmRestarted = countDelta < 0 && timeDelta < 0;

	                            if (fgcOccurred) {
	                                if (jvmRestarted) {
	                                    gcCount = currCount;
	                                    gcTime = currTime;
	                                } else {
	                                    gcCount = currCount - prevCount;
	                                    gcTime = currTime - prevTime;
	                                }
	                                prevCount = currCount;
	                                prevTime = currTime;
	                            }
	                        }
	                        if (gcCount > 0 && gcTime > 0) {
	                            thisData[info.line[k].key+"Count"] = gcCount;
	                        	thisData[info.line[k].key+"Time"] = gcTime;
	                        }
	                    } else {
	                    	var value = agentStat.charts[info.line[k].id].points[i].maxYVal;
	                    	if ( value >= 0 ) {
	                    		thisData[info.line[k].key] = value;
	                    	}
	                    }

	                }

	                newData.push(thisData);
	            }
	            return newData;
	        };

	        /**
	         * parse cpuLoad chart data for amcharts
	         * @param cpuLoad
	         * @param agentStat
	         * @returns {Array}
	         */
	        this.parseCpuLoadChartDataForAmcharts = function (cpuLoad, agentStat) {
	            // Cpu Load data availability check
	            var jvmCpuLoadData = agentStat.charts['CPU_LOAD_JVM'];
	            var systemCpuLoadData = agentStat.charts['CPU_LOAD_SYSTEM'];
	            if (jvmCpuLoadData || systemCpuLoadData) {
	            	cpuLoad.isAvailable = true;
	            } else {
	            	return;
	            }
	            var newData = [],
	            pointsJvmCpuLoad = jvmCpuLoadData.points,
	            pointsSystemCpuLoad = systemCpuLoadData.points;

	            if (pointsJvmCpuLoad.length !== pointsSystemCpuLoad.length) {
	                throw new Error('assertion error', 'jvmCpuLoad.length != systemCpuLoad.length');
	            }

	            for (var i = 0; i < pointsJvmCpuLoad.length; ++i) {
	                if (pointsJvmCpuLoad[i].xVal !== pointsSystemCpuLoad[i].xVal) {
	                	throw new Error('assertion error', 'timestamp mismatch between jvmCpuLoad and systemCpuLoad');
	                }
	                var thisData = {
						time: moment(pointsJvmCpuLoad[i].xVal).format( cfg.dateFormat ),
	                    maxCpuLoad: 100
	                };
	                var jvmCpuLoad = typeof agentStat.charts['CPU_LOAD_JVM'].points[i].maxYVal == "number" ? agentStat.charts['CPU_LOAD_JVM'].points[i].maxYVal.toFixed(2) : 0.00;
	                var systemCpuLoad = typeof agentStat.charts['CPU_LOAD_SYSTEM'].points[i].maxYVal == "number" ? agentStat.charts['CPU_LOAD_SYSTEM'].points[i].maxYVal.toFixed(2) : 0.00;
	                if ( jvmCpuLoad >= 0 ) {
	                    thisData.jvmCpuLoad = jvmCpuLoad;
	                }
	                if ( systemCpuLoad >= 0 ) {
	                    thisData.systemCpuLoad = systemCpuLoad;
	                }
	                newData.push(thisData);
	            }
	            return newData;
	        };

            /**
             * parse tps chart data for amcharts
             * @param tps
             * @param agentStat
             * @returns {Array}
             */
	        this.parseTpsChartDataForAmcharts = function (tps, agentStat) {
	            // TPS data availability check
	        	var aSampledContinuationData = agentStat.charts['TPS_SAMPLED_CONTINUATION'].points;
	        	var aSampledNewData = agentStat.charts['TPS_SAMPLED_NEW'].points;
	        	var aUnsampledContinuationData = agentStat.charts['TPS_UNSAMPLED_CONTINUATION'].points;
	        	var aUnsampledNewData = agentStat.charts['TPS_UNSAMPLED_NEW'].points;
	        	var aTotalData = agentStat.charts['TPS_TOTAL'].points;
				var newData = [];
				var DATA_UNAVAILABLE = -1;

	        	var tpsLength = aTotalData.length;
	        	if ( tpsLength > 0 ) {
	        		tps.isAvailable = true;
	        	} else {
	        		return newData;
	        	}

	            for ( var i = 0 ; i < tpsLength ; i++ ) {
	            	var obj = {
						"time" : moment(aSampledContinuationData[i].xVal).format( cfg.dateFormat )
					};
					var sampledContinuationTps = getFloatValue( aSampledContinuationData[i].avgYVal );
					var sampledNewTps = getFloatValue( aSampledNewData[i].avgYVal );
					var unsampledContinuationTps = getFloatValue( aUnsampledContinuationData[i].avgYVal );
					var unsampledNewTps = getFloatValue( aUnsampledNewData[i].avgYVal );
					var totalTps = getFloatValue( aTotalData[i].avgYVal );

					if ( sampledContinuationTps != DATA_UNAVAILABLE ) {
						obj.sampledContinuationTps = sampledContinuationTps;
					}
					if ( sampledNewTps != DATA_UNAVAILABLE ) {
						obj.sampledNewTps = sampledNewTps;
					}
					if ( unsampledContinuationTps != DATA_UNAVAILABLE ) {
						obj.unsampledContinuationTps = unsampledContinuationTps;
					}
					if ( unsampledNewTps != DATA_UNAVAILABLE ) {
						obj.unsampledNewTps = unsampledNewTps;
					}
					if ( totalTps != DATA_UNAVAILABLE ) {
						obj.totalTps = totalTps;
					}
					newData.push( obj );
	            }

	            return newData;
	        };
			this.parseActiveTraceChartDataForAmcharts = function (activeTrace, agentStat) {
				var aActiveTraceFastData = agentStat.charts[ "ACTIVE_TRACE_FAST" ].points;
				var aActiveTraceNormal = agentStat.charts[ "ACTIVE_TRACE_NORMAL" ].points;
				var aActiveTraceSlow = agentStat.charts[ "ACTIVE_TRACE_SLOW" ].points;
				var aActiveTraceVerySlow = agentStat.charts[ "ACTIVE_TRACE_VERY_SLOW" ].points;
				var newData = [];
				var DATA_UNAVAILABLE = -1;

				if ( aActiveTraceFastData || aActiveTraceNormal || aActiveTraceSlow || aActiveTraceVerySlow ) {
					activeTrace.isAvailable = true;
				} else {
					return newData;
				}

				for ( var i = 0 ; i < aActiveTraceFastData.length ; i++ ) {
					var obj = {
						"time": moment(aActiveTraceFastData[i].xVal).format(cfg.dateFormat)
					};

					var fast = getFloatValue( aActiveTraceFastData[i].avgYVal );
					var normal = getFloatValue( aActiveTraceNormal[i].avgYVal );
					var slow = getFloatValue( aActiveTraceSlow[i].avgYVal );
					var verySlow = getFloatValue( aActiveTraceVerySlow[i].avgYVal );

					if ( fast != DATA_UNAVAILABLE ) {
						obj.fast = fast;
						obj.fastTitle = aActiveTraceFastData[i].title;
					}
					if ( normal != DATA_UNAVAILABLE ) {
						obj.normal = normal;
						obj.normalTitle = aActiveTraceNormal[i].title;
					}
					if ( slow != DATA_UNAVAILABLE ) {
						obj.slow = slow;
						obj.slowTitle = aActiveTraceSlow[i].title;
					}
					if ( verySlow != DATA_UNAVAILABLE ) {
						obj.verySlow = verySlow;
						obj.verySlowTitle = aActiveTraceVerySlow[i].title;
					}
					newData.push( obj );
				}
				return newData;
			};
			function getFloatValue( val ) {
				return angular.isNumber( val ) ? val.toFixed(2) : 0.00;
			}
	    }
	]);
})();
<|endoftext|>