src/proto2/Physics.hh
author saiam
Thu, 20 Nov 2008 21:25:09 +0000
changeset 83 cbba9729e92b
parent 79 295ecb26d8ff
child 85 351cb6b69c04
permissions -rw-r--r--
Integrointia fyssaan, jotain pikkubugausta havaittavissa.
#ifndef PHYSICS_HH
#define PHYSICS_HH

#include "Vector.hh"

#include <vector>
#include <queue>
#include <ClanLib/core.h>

typedef uint16_t TimeMS;

const TimeMS PHYSICS_TICK_MS = 10;

enum TerrainType {EMPTY, DIRT, ROCK};

// forward-declare
class PhysicsObject;
class Force;
struct Derivative;

class PhysicsWorld {
    friend class PhysicsObject;
    
private:
    CL_Timer tick_timer;
    
protected:
    std::vector<PhysicsObject*> objects;
    Vector gravity;
    Vector dimensions; //const requested
    
    std::vector<std::vector<TerrainType> > terrain;

    CL_SlotContainer slots;
    
    PhysicsWorld (Vector gravity, Vector dimensions);
    
public:
    void addObject (PhysicsObject *object);

    void tick (void);
    void generateTerrain (int seed);
    bool collided (Vector oldPos, Vector newPos);

    TerrainType getType(Vector pos) const;
};

class PhysicsObject {
protected:
    PhysicsWorld &world;
    
    float mass;
    Vector position;
    Vector velocity;
    // Whether the object (worms mainly) is in the air 
    // or firmly on the ground. Affects to physics.
    bool inAir;

    // Force queue that is emptied on every tick
    std::queue<Force> forceq;
    Vector posAfterTick;
    Vector velAfterTick;

    PhysicsObject (PhysicsWorld &world, float mass, Vector position, Vector velocity);
    
    virtual void applyForce (Vector force, TimeMS dt);
    void updatePhysics (Vector position, Vector velocity);
    
private:
    void updatePosition (void);

    /**
     * Use RK4 to integrate the effects of force over a time intervall.
     */
    void integrate(Vector force, TimeMS dt);
    Derivative evaluate(Vector force, TimeMS dt, Derivative &d);
    Vector acceleration(const Vector &force);

public:
    Vector getPosition (void);
    
    void tick (void);
};

class Force {
public:
    Vector force;
    TimeMS dt;
    
    Force() {}
    Force(Vector force, TimeMS dt) : force(force), dt(dt) {}
};

struct Derivative {
    Vector dx; // Velocity
    Vector dv; // Acceleration
};



#endif