#include "PhysicsObject.hh"
#include "Engine.hh"
#include <cmath>
PhysicsObject::PhysicsObject (PhysicsWorld &world, float mass, Vector position, Vector velocity, bool enabled) :
world(world), position(position), velocity(velocity), mass(mass), inAir(true), aim(0), facingRight(true),
alive(false), shouldDelete(false), pivot(NULL)
{
if (enabled)
enable();
}
PhysicsObject::~PhysicsObject (void) {
// Engine::log(DEBUG, "PhysicsObject.destructor") << this /* << ": objects.size=" << ((int) world.objects.size()) */;
}
/**
* 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;
}
/**
* Updates object speed and position. This function organises force
* integration and collision detection.
*/
void PhysicsObject::updatePosition (TimeMS dt) {
// Add gravity to the force queue
forceq.push(world.gravity);
// If the object (practically player) has a pivot point add
// a force towards that
if (pivot != NULL) {
Vector direction(pivot->getPosition()-position);
float magnitude = pivot->getPivotForce(this);
float length = direction.length();
if (length > 0) {
direction = direction / length * magnitude;
forceq.push(direction);
}
}
// 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) {
// It walks only if there's some vertical force
if (total.x != 0) {
walk(dt, total.x > 0);
this->velocity = Vector(0,0);
}
}
if (!possibleLocation(position))
Engine::log(DEBUG, "PhysicsObject.updatePosition") << "impossible location: " << position;
Vector newPosition;
Vector velAfterTick;
// Calculate new position and velocity to the given references
integrate(total, dt, 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") << "impossible location: " << position << ", diffVec=" << diffVec;
// 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
}
this->position = newPosition;
} else {
newPosition = reached;
this->position = newPosition;
// the following may delete this object, so it must be the last thing called
onCollision();
return;
}
}
/**
* 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, bool facingRight, float aim) {
this->position = position;
this->velocity = velocity;
this->inAir = inAir;
this->facingRight = facingRight;
this->aim = aim;
}
Vector PhysicsObject::getPosition () {
return this->position;
}
Vector PhysicsObject::getVelocity () {
return this->velocity;
}
bool PhysicsObject::getFacing() {
return this->facingRight;
}
float PhysicsObject::getAim() {
return this->aim;
}
Vector PhysicsObject::getDirection (void) {
return facingRight ? Vector(cos(aim), -sin(aim)) : Vector(-cos(aim), -sin(aim));
}
std::vector<Vector>& PhysicsObject::getShape () {
return this->shape;
}
void PhysicsObject::setShape (std::vector<Vector> shape) {
this->shape = shape;
}
void PhysicsObject::setPivot (PhysicsObject *pivot) {
this->pivot = pivot;
}
void PhysicsObject::tick (TimeMS tick_length) {
this->updatePosition(tick_length);
}
void PhysicsObject::enable (void) {
// only enable once until disabled
if (alive)
return;
// mark as alive
alive = true;
// add the world objects list
world.addPhysicsObject(this);
}
void PhysicsObject::disable (void) {
// mark as disabled
alive = false;
}
void PhysicsObject::destroy (void) {
// mark as disabled and for deletion
alive = false;
shouldDelete = true;
}
bool PhysicsObject::isDestroyed (void) {
return !alive;
}
bool PhysicsObject::removeIfDestroyed (void) {
if (!alive) {
if (shouldDelete)
delete this;
return true;
} else {
return false;
}
}
float PhysicsObject::getPivotForce (PhysicsObject *bob) { return 0.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);
}
}