--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/PhysicsObject.cc Thu Dec 04 19:53:59 2008 +0000
@@ -0,0 +1,368 @@
+#include "Player.hh"
+#include "PhysicsObject.hh"
+#include "Engine.hh"
+
+#include <cmath>
+
+PhysicsObject::PhysicsObject (PhysicsWorld &world, float mass,
+ Vector position, Vector velocity)
+ : world(world), position(position), velocity(velocity),
+ mass(mass), inAir(true), aim(0), facingRight(true), reloadTimer(0) {
+ // TODO: Is thir the right way to do this?
+ //world.addPlayerObject(this);
+}
+
+/**
+ * Player walks on floor.
+ */
+Vector PhysicsObject::walk_one_step (float partial, bool right) {
+ // which way we are walking
+ float deltaX = right ? partial : -partial;
+ Vector reached = this->position;
+ if(reached.roundToInt() == (reached+Vector(deltaX, 0)).roundToInt()) {
+ return reached+Vector(deltaX, 0);
+ }
+ // Is there upward ramp
+ if(!possibleLocation(position+Vector(deltaX, 0))) {
+ // Yes. Then we check n pixels up
+ for(int i = 1; i < 3; i++) {
+ if(possibleLocation(position+Vector(deltaX, -i))) {
+ // and when there is finally EMPTY, we can walk
+ reached = position+Vector(deltaX, -i);
+ break;
+ }
+ }
+ } else {
+ // Or downward ramp or flat
+ for(int i = 0; 1; i++) {
+
+ // And when there is finally ground we can step on
+ // it. If there is no gound we still step there,
+ // but will fall one pixel down
+ if(possibleLocation(position+Vector(deltaX, i))) {
+ reached = position+Vector(deltaX, i);
+ } else {
+ break;
+ }
+
+ // If the fall is big enough, set the worm in the air
+ if (i >= 2) {
+// Vector back = walk(dt, !right);
+ this->inAir = true;
+// this->velocity.x = right ? velocity : -velocity;
+ // Avoid stepping two pixels down when it starts to free fall
+ reached.y -= 2;
+// this->velocity = (reached-back)*1000/dt;
+ break;
+ }
+ }
+ }
+ // And we return where we got
+ return reached;
+}
+void PhysicsObject::walk (TimeMS dt, bool right) {
+ float velocity = PLAYER_WALK_SPEED;
+ float walkAmount = (velocity*dt)/1000;
+ Vector reached = this->position;
+ while(walkAmount > 0 && !this->inAir) {
+ this->position = walk_one_step((1 < walkAmount ? 1 : walkAmount), right);
+ walkAmount--;
+ }
+ // TODO: Should the remaining walkAmount be handled somehow?
+}
+
+/**
+ * Makes the player jump in the air.
+ * @param direction -1: jump left, 0: jump up, 1: jump right
+ */
+void PhysicsObject::jump (int direction) {
+ // Jump only if player is "on the ground"
+ if (!this->inAir) {
+ velocity.y = -100;
+ switch (direction) {
+ case 1:
+ velocity.x += 20;
+ break;
+ case -1:
+ velocity.x -= 20;
+ break;
+ case 0:
+ break;
+ default:
+ throw std::logic_error("Invalid jump direction");
+ }
+ inAir = true;
+ }
+}
+
+bool PhysicsObject::possibleLocation (Vector loc) {
+ for(unsigned int i = 0; i < this->shape.size(); i++) {
+ if(world.collides(loc+shape[i]))
+ return false;
+ }
+ return true;
+}
+
+void func1() {
+
+}
+
+/**
+ * Updates object speed and position. This function organises force
+ * integration and collision detection.
+ */
+void PhysicsObject::updatePosition () {
+
+ // Reloads weapon if not reloaded
+ reloadTimer -= PHYSICS_TICK_MS;
+ if(reloadTimer < 0)
+ reloadTimer = 0;
+
+ // Add gravity to the force queue
+ forceq.push(world.gravity);
+
+ // Go trough every force in the queue
+ Force total;
+ while (!forceq.empty()) {
+ total += forceq.front();
+ forceq.pop();
+ }
+
+ // If the player has stopped and there's some ground under some of the 3 some of the 3t
+ // set inAir false
+ if (this->velocity == Vector(0,0)) {
+ this->inAir = !world.collides(this->position+shape[1]+Vector(0, 1))
+ && !world.collides(this->position+shape[2]+Vector(0, 1))
+ && !world.collides(this->position+shape[3]+Vector(0, 1));
+ // If, however, there's a force caused by a bomb, e.g., set it in air.
+ // Still, we have to be able to separate forces caused by walking attempts
+ // and bombs etc (+0.1 because float comparison can be dangerous)
+ if (total.y < 0 || abs(total.x) > PLAYER_MOVE_FORCE + 0.1)
+ this->inAir = true;
+ }
+
+ if(!possibleLocation(position)) {
+ //if we are trapped in ground form dirtball or something
+ //we might want to just return and set velocity to some value
+ //return;
+ }
+
+ // If the worm is not in the air make it walk,
+ // otherwise integrate the new position and velocity
+ if (!this->inAir) {
+ //std::cout << "Tryin to walk" << std::endl;
+ // It walks only if there's some vertical force
+ if (total.x != 0) {
+ std::cout << "Succeeding to walk" << std::endl;
+ walk(PHYSICS_TICK_MS, total.x > 0);
+ this->velocity = Vector(0,0);
+ }
+ }
+
+ if(!possibleLocation(position)) {
+ Engine::log(DEBUG, "great failure") << "great failure";
+ func1();
+ }
+ Vector newPosition;
+ Vector velAfterTick;
+ // Calculate new position and velocity to the given references
+ integrate(total, PHYSICS_TICK_MS, newPosition, velAfterTick);
+ this->velocity = velAfterTick;
+
+
+ // Collision detection
+ bool collided = false;
+
+ const Vector diffVec = newPosition-position;
+ const Vector unitVector = diffVec / diffVec.length();
+ Vector reached = position;
+
+ while ((position-reached).sqrLength() < diffVec.sqrLength()) {
+ reached += unitVector;
+ // Check if any of the shapes points collide
+ for (uint64_t i = 0; i < shape.size(); i++) {
+ if (world.collides(reached+shape[i])) { // Collision
+ if (inAir) {
+ // Engine::log(DEBUG, "Here");
+ this->bounce(world.getNormal(reached+shape[i],
+ reached-unitVector+shape[i]));
+ //this->velocity *= COLLISION_ELASTICITY;
+ }
+ reached = reached - unitVector; // Return to last point
+ collided = true;
+ if (this->velocity.sqrLength() < PLAYER_MIN_SPEED * PLAYER_MIN_SPEED) {
+ this->velocity = Vector(0,0);
+ }
+ break;
+ }
+ }
+ if (collided)
+ break;
+// reached += unitVector;
+ }
+
+
+ if(!possibleLocation(reached)) {
+ Engine::log(DEBUG, "PhysicsObject.updatePosition") << "logic error reached should not be possible to be impossible.. diffVec: " << diffVec;
+ func1();
+ }
+
+ // In case of some float error check the final coordinate
+ if(!collided) {
+ if(!possibleLocation(newPosition)) {
+ newPosition = reached;
+ } else {
+ // This means everything was ok, so no need to do anything
+ }
+ } else {
+ newPosition = reached;
+ onCollision();
+ //this->velocity = Vector(0, 0);
+ //TODO: it shouldn't just stop on collision
+ }
+ if(!possibleLocation(newPosition)) {
+ Engine::log(DEBUG, "great failure") << "great failure";
+ func1();
+ }
+ this->position = newPosition;
+ if(!possibleLocation(position)) {
+ Engine::log(DEBUG, "great failure") << "great failure";
+ func1();
+ }
+// Engine::log(DEBUG, "PhysicsObject.updatePosition") << "Pos: " << this->position;
+}
+
+/**
+ * Bounces from straight wall in any direction.
+ * Direction given as normal of that wall
+ */
+void PhysicsObject::bounce (Vector normal) {
+ // normal.sqrLength can't be 0 when got from getNormal()
+ if (normal.sqrLength() != 0) {
+ Vector nvel = velocity;
+ // We project the velocity on normal and remove twice that much from velocity
+ nvel = nvel - ((2)*((nvel*normal)/(normal*normal))*normal);
+ velocity = nvel;
+ // We lose some of our speed on collision
+ this->velocity *= this->collision_elasticity;
+ }
+}
+
+/**
+ * Integrates given force over time and stores new position to
+ * posAfterTick and new velocity to velAfterTick.
+ * @param force Force vector.
+ * @param dt The time the force is applied (<=PHYSICS_TICK_MS)
+ */
+void PhysicsObject::integrate(Force force, TimeMS dt, Vector &posAfterTick, Vector &velAfterTick) {
+ posAfterTick = position;
+ velAfterTick = velocity;
+ Derivative tmpd;
+ Derivative k1 = evaluate(force, 0, tmpd, posAfterTick, velAfterTick);
+ Derivative k2 = evaluate(force, 0.5f*dt, k1, posAfterTick, velAfterTick);
+ Derivative k3 = evaluate(force, 0.5f*dt, k2, posAfterTick, velAfterTick);
+ Derivative k4 = evaluate(force, dt, k3, posAfterTick, velAfterTick);
+
+
+ const Vector dxdt = (k1.dx + (k2.dx + k3.dx) * 2.0f + k4.dx) * 1.0f/6.0f;
+ const Vector dvdt = (k1.dv + (k2.dv + k3.dv) * 2.0f + k4.dv) * 1.0f/6.0f;
+
+ // Engine::log(DEBUG, "PhysicsObject.integrate") << "Changes: "<< dxdt << " " << dvdt << " Time: " <<dt;
+ posAfterTick = posAfterTick + (dxdt * dt)/1000;
+ velAfterTick = velAfterTick + (dvdt * dt)/1000;
+ //Engine::log(DEBUG, "PhysicsObject.integrate") << "velAfterTick: " << velAfterTick;
+}
+
+Derivative PhysicsObject::evaluate(Force force, TimeMS dt, Derivative &d, const Vector &posAfterTick, const Vector &velAfterTick) {
+ Vector curPos = posAfterTick + (d.dx*dt)/1000;
+ Vector curVel = velAfterTick + (d.dv*dt)/1000;
+
+ Derivative out;
+ out.dx = curVel;
+ out.dv = acceleration(force);
+ //Engine::log(DEBUG, "PhysicsObject.evaluate") << "Out.dx: " << out.dx;
+ return out;
+}
+
+Vector PhysicsObject::acceleration(const Force &force) {
+ return (force/mass);
+}
+
+void PhysicsObject::applyForce (Force force) {
+ // Add applied force to the queue
+ forceq.push(force);
+}
+
+void PhysicsObject::changeAim(float da) {
+ this->aim += da;
+
+ if (this->aim > PLAYER_AIM_MAX) this->aim = PLAYER_AIM_MAX;
+ if (this->aim < PLAYER_AIM_MIN) this->aim = PLAYER_AIM_MIN;
+ //Engine::log(DEBUG, "PhysicsObject.changeAim") << "Player aim: " << this->aim;
+}
+
+void PhysicsObject::setFacing(bool facingRight) {
+ //Engine::log(DEBUG, "PhysicsObject.setFacing") << "Facing: " << right;
+ this->facingRight = facingRight;
+}
+
+void PhysicsObject::updatePhysics (Vector position, Vector velocity, bool inAir) {
+ this->position = position;
+ this->velocity = velocity;
+ this->inAir = inAir;
+}
+
+Vector PhysicsObject::getPosition () {
+ return this->position;
+}
+
+bool PhysicsObject::getFacing() {
+ return this->facingRight;
+}
+
+float PhysicsObject::getAim() {
+ return this->aim;
+}
+
+std::vector<Vector>& PhysicsObject::getShape () {
+ return this->shape;
+}
+
+void PhysicsObject::setShape (std::vector<Vector> shape) {
+ this->shape = shape;
+}
+
+void PhysicsObject::tick () {
+ this->updatePosition();
+}
+
+bool PhysicsObject::canShoot() {
+ return this->reloadTimer <= 0;
+}
+
+void PhysicsObject::draw(CL_GraphicContext *gc) {
+ CL_Quad player(
+ (position+shape[0]).x, (position+shape[0]).y,
+ (position+shape[1]).x, (position+shape[1]).y,
+ (position+shape[2]).x, (position+shape[2]).y,
+ (position+shape[3]).x, (position+shape[3]).y
+ );
+
+ gc->fill_quad(player, CL_Color::green);
+
+ const uint16_t chlen = 10;
+ uint16_t x = player.center().x;
+ uint16_t y = player.center().y;
+ if (facingRight) {
+ gc->draw_line(x, y,
+ x + std::cos(aim)*chlen,
+ y - std::sin(aim)*chlen,
+ CL_Color::black);
+ } else {
+ gc->draw_line(x, y,
+ x - std::cos(aim)*chlen,
+ y - std::sin(aim)*chlen,
+ CL_Color::black);
+ }
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/PhysicsObject.hh Thu Dec 04 19:53:59 2008 +0000
@@ -0,0 +1,215 @@
+#ifndef PHYSICS_OBJECT_HH
+#define PHYSICS_OBJECT_HH
+
+#include <ClanLib/display.h>
+
+// Forward declares
+class PhysicsObject;
+struct Derivative;
+
+#include "PhysicsWorld.hh"
+#include "Vector.hh"
+#include "Config.hh"
+#include "Input.hh"
+
+// Type definitions
+typedef uint16_t TimeMS;
+typedef Vector Force;
+
+
+/**
+ * PhysicObject class. A basic PhysicsObject class.
+ */
+class PhysicsObject {
+protected:
+ // This probably shouldn't be done this way.
+ PhysicsWorld &world;
+
+ Vector position;
+ Vector velocity;
+ float mass;
+ bool inAir; // Is the object "on the ground"
+ float collision_elasticity;
+
+ // Attributes for players
+ float aim; // Aim direction (half circle)
+ bool facingRight; // Player facing
+
+ //
+ int reloadTimer;
+
+ PhysicsObject(PhysicsWorld &world, float mass, Vector position,
+ Vector velocity);
+ ~PhysicsObject() {}
+
+
+ /**
+ * Add force to the force queue to be applied on next tick.
+ *
+ * @param force Force vector
+ */
+ void applyForce(Force force);
+
+ /**
+ * Change player aim
+ *
+ * @param da Aim angle change
+ */
+ void changeAim(float da);
+
+ /**
+ * Set player facing.
+ *
+ * @param facingRight True if player is facing right.
+ */
+ void setFacing(bool facingRight);
+
+ /**
+ * Makes the player jump in the air.
+ * @param direction -1: jump left, 0: jump up, 1: jump right
+ */
+ void jump(int direction);
+
+ /**
+ * Handle ground-bounce
+ *
+ * @param normal Normal vector relative to which to bounce
+ */
+ void bounce(Vector normal);
+
+ /**
+ * Called on network clients to sync state from server
+ *
+ * @param position New position
+ * @param velocity New velocity
+ * @param inAir New inAir value
+ */
+ void updatePhysics(Vector position, Vector velocity, bool inAir);
+
+private:
+ // TODO: I'd be tempted to use some already made ClanLib structure
+ // here.
+ // Shape of the object. Edge points of the shape polygon.
+ std::vector<Vector> shape;
+
+ // TODO: Should these operations be moved to PhysicsWorld?
+ // Force queue that is emptied on every tick
+ std::queue<Force> forceq;
+
+ /**
+ * Handle player movement and apply forces.
+ */
+ void updatePosition();
+
+ // TODO: Should these be moved to PhysicsWorld?
+ /**
+ * Use RK4 to integrate the effects of force over a time interwall.
+ *
+ * @param force Force to integrate
+ * @param dt Time intervall
+ */
+ void integrate(Force force, TimeMS dt, Vector &posAfterTick, Vector &velAfterTick);
+
+ /**
+ * Evaluate the value of the derivative at given time
+ *
+ * @param force Force
+ * @param dt Time
+ * @param d Previous derivative
+ */
+ Derivative evaluate(Force force, TimeMS dt, Derivative &d, const Vector &posAfterTick, const Vector &velAfterTick);
+
+ /**
+ * Return object acceleration with given force.
+ *
+ * @param force Force
+ * @return Acceleration
+ */
+ Vector acceleration(const Force &force);
+
+ // TODO: If integration is moved to PhysicsWorld then this should
+ // also move there.
+ /**
+ * Handle ground movement.
+ *
+ * @param right Boolean describing the movement direction.
+ * @return New position
+ */
+ void walk(TimeMS, bool right);
+ Vector walk_one_step(float, bool);
+
+ /*
+ * Handle collision. TODO: This is not used. It probably should
+ * be?
+ */
+ virtual void onCollision() {}
+
+ /*
+ * TODO: This probably does some kind of collision
+ * detection. Could be named/documented better.
+ */
+ bool possibleLocation(Vector loc);
+
+public:
+ /**
+ * Get current object position.
+ *
+ * @return Position vector
+ */
+ Vector getPosition();
+
+ /**
+ * Return object shape.
+ *
+ * @return Polygon points
+ */
+ std::vector<Vector>& getShape();
+
+ /**
+ * Set object shape.
+ *
+ * @param shape Vector containing polygon poinst
+ */
+ void setShape(std::vector<Vector> shape);
+
+ /**
+ * Return object facing.
+ *
+ * @return Object facing (true if facing right)
+ */
+ bool getFacing();
+
+ /**
+ * Return object aim angle.
+ *
+ * @return Object aim angle
+ */
+ float getAim();
+
+ /**
+ * Update object in physics simulation.
+ */
+ void tick();
+
+ /**
+ * @return whether this PhysicsObject can shoot or not
+ * This is in PhysicsObject for larpa-like shots
+ */
+ bool canShoot();
+
+ /**
+ * Draw object
+ *
+ * @param gc CL_GraphicContext
+ */
+ virtual void draw(CL_GraphicContext *gc);
+};
+
+// TODO: This could probably be moved somewhere else or removed
+// completely.
+struct Derivative {
+ Vector dx; // Velocity
+ Vector dv; // Acceleration
+};
+
+#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/PhysicsWorld.cc Thu Dec 04 19:53:59 2008 +0000
@@ -0,0 +1,61 @@
+
+#include "GameState.hh"
+#include "PhysicsWorld.hh"
+#include "Engine.hh"
+
+PhysicsWorld::PhysicsWorld (Vector gravity, Vector dimensions)
+ : Terrain(1337), tick_timer(PHYSICS_TICK_MS), tick_counter(0), dimensions(dimensions),
+ gravity(gravity) {
+ slots.connect(tick_timer.sig_timer(), this, &PhysicsWorld::tick);
+ tick_timer.enable();
+}
+
+void PhysicsWorld::addPlayerObject (PhysicsObject *object) {
+ players.push_back(object);
+}
+
+void PhysicsWorld::addProjectile (Shot *projectile) {
+ projectiles.push_back(projectile);
+}
+
+/**
+ * Function pointer used to clear the projectile list
+ * from those that have already been destroyd.
+ */
+bool isDestroyedProjectile (Shot* po) { return (*po).isDestroyed(); }
+
+void PhysicsWorld::tick () {
+ // Engine::log(DEBUG, "physics.apply_force") << "*tick*";
+
+ for (std::list<PhysicsObject*>::iterator i = players.begin(); i != players.end(); i++) {
+ (*i)->tick();
+ }
+
+ for (std::list<Shot*>::iterator i = projectiles.begin(); i != projectiles.end(); i++) {
+ (*i)->tick();
+ }
+
+ // Delete destroyed projectiles
+ std::list<Shot*>::iterator new_end = remove_if(projectiles.begin(), projectiles.end(), isDestroyedProjectile);
+ projectiles.erase(new_end, projectiles.end());
+
+ tick_counter++;
+}
+
+uint32_t PhysicsWorld::getTick (void) {
+ return tick_counter;
+}
+
+void PhysicsWorld::draw(CL_GraphicContext *gc) {
+ Terrain::draw(gc);
+
+ // Draw players
+ for (std::list<PhysicsObject*>::iterator it = players.begin(); it != players.end(); it++) {
+ (*it)->draw(gc);
+ }
+ // Draw projectiles
+ for (std::list<Shot*>::iterator it = projectiles.begin(); it != projectiles.end(); it++) {
+ (*it)->draw(gc);
+ }
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/PhysicsWorld.hh Thu Dec 04 19:53:59 2008 +0000
@@ -0,0 +1,79 @@
+#ifndef PHYSICS_WORLD_HH
+#define PHYSICS_WORLD_HH
+
+#include <ClanLib/display.h>
+#include <ClanLib/core.h>
+
+#include <algorithm>
+#include <functional>
+#include <cmath>
+
+#include "Terrain.hh"
+class PhysicsWorld;
+
+#include "PhysicsObject.hh"
+#include "Vector.hh"
+#include "Config.hh"
+#include "Projectile.hh"
+
+/**
+* PhysicsWorld class. PhysicsWorld contains PhysicsObjects that are
+* simulated in the PhysicsWorld.
+*/
+class PhysicsWorld : public Terrain {
+ friend class PhysicsObject;
+
+private:
+ CL_Timer tick_timer;
+ uint32_t tick_counter;
+
+ // Terrain terrain;
+
+protected:
+ std::list<PhysicsObject*> players;
+ std::list<Shot*> projectiles;
+// std::vector<PhysicsObject*> objects;
+
+ // Contains connections between signals and slots
+ CL_SlotContainer slots;
+
+ PhysicsWorld(Vector gravity, Vector dimensions);
+
+ // TODO: Should these be somewhere else?
+ Vector dimensions;
+ Vector gravity;
+
+
+
+public:
+ // TODO: Replace addObject with these?
+ //void addPlayerObject(PlayerObject *object);
+ //void addProjectileObject(ProjectileObject *object);
+
+ /**
+ * Add object to the PhysicsWorld.
+ *
+ * @param object Pointer to the PhysicsObject to add.
+ */
+ void addPlayerObject(PhysicsObject *object);
+
+ void addProjectile(Shot *projectile);
+
+ /**
+ * Advance one time step in physics simulation.
+ */
+ void tick();
+
+ /**
+ * Get current tick in physics simulation.
+ *
+ * @return tick Current simulation tick.
+ */
+ uint32_t getTick();
+
+ virtual void draw(CL_GraphicContext *gc);
+
+ // TODO This should probably be protected or in GameStat or in GameStatee
+};
+
+#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/Projectile.cc Thu Dec 04 19:53:59 2008 +0000
@@ -0,0 +1,16 @@
+#include "Projectile.hh"
+
+Shot::Shot(GameState &state, Vector position, Vector velocity, bool visible) :
+ PhysicsObject((PhysicsWorld &) state, PLAYER_MASS, position, velocity), state(state), visible(visible), destroyed(false) {
+ // Looks kind of dumb, for ammunition to have shape
+ std::vector<Vector> shape(4);
+ shape[0] = Vector(-1, -1);
+ shape[1] = Vector(-1, 1);
+ shape[2] = Vector(1, 1);
+ shape[3] = Vector(1, -1);
+ setShape(shape);
+ target_visible = false;
+ collision_elasticity = 0.9; // = shotType.elasticity
+ world.addProjectile(this);
+}
+
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/src/Projectile.hh Thu Dec 04 19:53:59 2008 +0000
@@ -0,0 +1,26 @@
+#ifndef PROJECTILE_HH
+#define PROJECTILE_HH
+
+class Shot;
+
+#include "PhysicsObject.hh"
+#include "GameState.hh"
+
+class Shot : public PhysicsObject {
+protected:
+ GameState &state;
+ bool visible;
+ uint32_t birth_tick;
+ uint32_t death_tick;
+ bool target_visible;
+ bool destroyed;
+public:
+ Shot(GameState &state, Vector position, Vector velocity, bool visible);
+
+ bool isDestroyed (void);
+ virtual void draw(CL_GraphicContext *gc);
+private:
+ virtual void onCollision();
+};
+
+#endif