* and the duration that is how long the slide will be shown.
*/
- struct Frame
+ class Frame
{
- unsigned index; ///< Frame index.
- Mf::Scalar duration; ///< Frame duration.
+ friend class Impl;
+
+ unsigned mIndex; ///< Frame index.
+ Mf::Scalar mDuration; ///< Frame duration.
/**
* Construction is initialization. The frame data is loaded from a
*/
Frame(Mf::Script& script, Mf::Script::Value table) :
- index(0),
- duration(1.0)
+ mIndex(0),
+ mDuration(1.0)
{
table.pushField("index");
- script[-1].get(index);
+ script[-1].get(mIndex);
script.pop();
table.pushField("duration");
- script[-1].get(duration);
+ script[-1].get(mDuration);
script.pop();
}
};
struct Sequence
{
- std::vector<Frame> frames; ///< List of frames.
- Mf::Scalar delay; ///< Scale frame durations.
- bool loop; ///< Does the sequence repeat?
- std::string next; ///< Next sequence name.
+ friend class Impl;
+
+ std::vector<Frame> mFrames; ///< List of frames.
+ Mf::Scalar mDelay; ///< Scale frame durations.
+ bool mLoop; ///< Does the sequence repeat?
+ std::string mNext; ///< Next sequence name.
/**
* Construction is initialization. The constructor loads sequence
*/
Sequence(Mf::Script& script, Mf::Script::Value table) :
- delay(0.0),
- loop(true)
+ mDelay(0.0),
+ mLoop(true)
{
table.pushField("delay");
- script[-1].get(delay);
+ script[-1].get(mDelay);
script.pop();
table.pushField("loop");
- script[-1].get(loop);
+ script[-1].get(mLoop);
script.pop();
table.pushField("next");
- script[-1].get(next);
+ script[-1].get(mNext);
script.pop();
// TODO - sequence class/type not yet implemented
script.push(index);
frameTable.pushField();
- if (top.isTable()) frames.push_back(Frame(script, top));
+ if (top.isTable()) mFrames.push_back(Frame(script, top));
else break;
++index;
*/
Impl(const std::string& name) :
- data(Data::getInstance(name)),
- currentSequence(0),
- frameCounter(0),
- frameIndex(0),
- timeAccum(0),
- frameDuration(0) {}
+ mData(Data::getInstance(name)),
+ mCurrentSequence(0),
+ mFrameCounter(0),
+ mFrameIndex(0),
+ mTimeAccum(0),
+ mFrameDuration(0) {}
/**
{
std::map<std::string,Data::Sequence>::iterator it;
- it = data->sequences.find(name);
+ it = mData->sequences.find(name);
- if (it != data->sequences.end())
+ if (it != mData->sequences.end())
{
- currentSequence = &(*it).second;
- frameCounter = 0;
- frameIndex = currentSequence->frames[0].index;
- timeAccum = 0.0;
- frameDuration = currentSequence->delay *
- currentSequence->frames[0].duration;
+ mCurrentSequence = &(*it).second;
+ mFrameCounter = 0;
+ mFrameIndex = mCurrentSequence->mFrames[0].mIndex;
+ mTimeAccum = 0.0;
+ mFrameDuration = mCurrentSequence->mDelay *
+ mCurrentSequence->mFrames[0].mDuration;
}
}
void update(Mf::Scalar t, Mf::Scalar dt)
{
- if (currentSequence)
+ if (mCurrentSequence)
{
- timeAccum += dt;
+ mTimeAccum += dt;
- if (timeAccum >= frameDuration)
+ if (mTimeAccum >= mFrameDuration)
{
- if (++frameCounter >= currentSequence->frames.size())
+ if (++mFrameCounter >= mCurrentSequence->mFrames.size())
{
- if (!currentSequence->next.empty())
+ if (!mCurrentSequence->mNext.empty())
{
- startSequence(currentSequence->next);
+ startSequence(mCurrentSequence->mNext);
}
- else if (currentSequence->loop)
+ else if (mCurrentSequence->mLoop)
{
- frameCounter = 0;
+ mFrameCounter = 0;
}
else
{
- frameCounter--;
- currentSequence = 0;
+ mFrameCounter--;
+ mCurrentSequence = 0;
}
}
- frameIndex = currentSequence->frames[frameCounter].index;
- timeAccum = frameDuration - timeAccum;
- frameDuration = currentSequence->delay *
- currentSequence->frames[frameCounter].duration;
+ mFrameIndex = mCurrentSequence->mFrames[mFrameCounter].mIndex;
+ mTimeAccum = mFrameDuration - mTimeAccum;
+ mFrameDuration = mCurrentSequence->mDelay *
+ mCurrentSequence->mFrames[mFrameCounter].mDuration;
}
}
}
- boost::shared_ptr<Data> data; ///< Internal data.
+ boost::shared_ptr<Data> mData; ///< Internal data.
- Data::Sequence* currentSequence; ///< Active sequence.
- unsigned frameCounter; ///< Current frame.
- unsigned frameIndex; ///< Index of current frame.
- Mf::Scalar timeAccum; ///< Time accumulation.
- Mf::Scalar frameDuration; ///< Scaled frame duration.
+ Data::Sequence* mCurrentSequence; ///< Active sequence.
+ unsigned mFrameCounter; ///< Current frame.
+ unsigned mFrameIndex; ///< Index of current frame.
+ Mf::Scalar mTimeAccum; ///< Time accumulation.
+ Mf::Scalar mFrameDuration; ///< Scaled frame duration.
};
Animation::Animation(const std::string& name) :
// pass through
- impl_(new Animation::Impl(name)) {}
+ mImpl(new Animation::Impl(name)) {}
void Animation::startSequence(const std::string& name)
{
// pass through
- impl_->startSequence(name);
+ mImpl->startSequence(name);
}
void Animation::update(Mf::Scalar t, Mf::Scalar dt)
{
// pass through
- impl_->update(t, dt);
+ mImpl->update(t, dt);
}
unsigned Animation::getFrame() const
{
- return impl_->frameIndex;
+ return mImpl->mFrameIndex;
}
class Animation : public Mf::Resource
{
class Impl;
- boost::shared_ptr<Impl> impl_;
+ boost::shared_ptr<Impl> mImpl;
public:
Mf::Scalar d = 50.0;
// spring:
- //current.force += -15.0 * x - 1.5 * current.velocity;
- force = -20.0 * (mag - d) * (x / mag) - 2.0 * state.velocity;
+ //mState.force += -15.0 * x - 1.5 * mState.velocity;
+ force = SCALAR(-10.0) * (mag - d) * (x / mag) - 2.0 * state.velocity;
return force;
}
tilemap(name),
animation(name)
{
- current.init();
+ mState.init();
- current.mass = 1.0;
- current.inverseMass = 1.0 / current.mass;
+ mState.mass = 1.0;
+ mState.inverseMass = 1.0 / mState.mass;
// forces
- current.force = Mf::Vector2(0.0, 0.0);
- current.forces.push_back(SpringForce(Mf::Vector2(500.0, 200.0)));
- current.forces.push_back(ResistanceForce(2.0));
- current.forces.push_back(Mf::LinearState<2>::GravityForce(-1000.0));
+ mState.force = Mf::Vector2(0.0, 0.0);
+ //mState.forces.push_back(SpringForce(Mf::Vector2(500.0, 200.0)));
+ mState.forces.push_back(ResistanceForce(2.0));
+ //mState.forces.push_back(Mf::LinearState<2>::GravityForce(-100.0));
// starting position
- current.position = Mf::Vector2(64.0, 64.0);
- current.momentum = Mf::Vector2(0.0, 0.0);
- current.recalculate();
+ mState.position = Mf::Vector2(64.0, 64.0);
+ mState.momentum = Mf::Vector2(0.0, 0.0);
+ mState.recalculate();
- previous = current;
+ mPrevState = mState;
}
void Character::update(Mf::Scalar t, Mf::Scalar dt)
{
- previous = current;
+ Mf::RigidBody2::update(t, dt); // update physics
- //Mf::Vector2 x = current.position - Mf::Vector2(500.0, 200.0);
- //Mf::Scalar mag = x.length();
- //Mf::Scalar d = 50.0;
-
- //// gravity:
- //current.force = Mf::Vector2(0.0, -2000.0);
- //// spring:
- ////current.force += -15.0 * x - 1.5 * current.velocity;
- //current.force += -20.0 * (mag - d) * (x / mag) - 2.0 * current.velocity;
- //// internal:
- //current.force += userForce;
- //current.recalculate();
- //std::cout << "force: " << current.momentum << std::endl;
-
- //Mf::euler<State,Derivative>(current, t, dt);
-
- current.integrate(t, dt);
animation.update(t, dt);
- Mf::Vector3 center(current.position[0], current.position[1], z);
- Mf::Vector3 a(current.position[0] - 16.0, current.position[1] - 16.0, z);
- Mf::Vector3 b(current.position[0] + 16.0, current.position[1] + 16.0, z);
+ Mf::Vector3 center(mState.position[0], mState.position[1], z);
+ Mf::Vector3 a(mState.position[0] - 16.0, mState.position[1] - 16.0, z);
+ Mf::Vector3 b(mState.position[0] + 16.0, mState.position[1] + 16.0, z);
- aabb_.init(a, b);
- sphere_.init(center, a);
+ mAabb.init(a, b);
+ mSphere.init(center, a);
}
void Character::draw(Mf::Scalar alpha) const
{
- Mf::Vector2 position = cml::lerp(previous.position, current.position, alpha);
+ //Mf::Vector2 position = cml::lerp(mPrevState.position, mState.position, alpha);
+ Mf::State2 state = getState(alpha);
+ Mf::Vector2 position = state.position;
//glColor3f(1.0f, 1.0f, 1.0f);
tilemap.bind();
Tilemap::Orientation orientation = Tilemap::NORMAL;
- if (current.velocity[0] < 0.0) orientation = Tilemap::REVERSE;
+ if (mState.velocity[0] < 0.0) orientation = Tilemap::REVERSE;
Mf::Scalar coords[8];
tilemap.getTileCoords(frame, coords, orientation);
}
-bool Character::isInsideAabb(const Mf::Aabb& aabb) const
-{
- // make sure the entity is fully inside the volume
- if (!(aabb_.max[0] < aabb.max[0] &&
- aabb_.min[0] > aabb.min[0] &&
- aabb_.max[1] < aabb.max[1] &&
- aabb_.min[1] > aabb.min[1] &&
- aabb_.max[2] < aabb.max[2] &&
- aabb_.min[2] > aabb.min[2]))
- {
- return false;
- }
-
- return true;
-}
-
int Character::getOctant(const Mf::Aabb& aabb) const
{
int octantNum = -1;
Mf::Plane::Halfspace halfspace;
Mf::Plane xy = aabb.getPlaneXY();
- halfspace = xy.intersects(sphere_);
+ halfspace = xy.intersects(mSphere);
if (halfspace == Mf::Plane::INTERSECT)
{
- halfspace = xy.intersects(aabb_);
+ halfspace = xy.intersects(mAabb);
}
if (halfspace == Mf::Plane::POSITIVE)
{
Mf::Plane xz = aabb.getPlaneXZ();
- halfspace = xz.intersects(sphere_);
+ halfspace = xz.intersects(mSphere);
if (halfspace == Mf::Plane::INTERSECT)
{
- halfspace = xz.intersects(aabb_);
+ halfspace = xz.intersects(mAabb);
}
if (halfspace == Mf::Plane::POSITIVE)
{
Mf::Plane yz = aabb.getPlaneYZ();
- halfspace = yz.intersects(sphere_);
+ halfspace = yz.intersects(mSphere);
if (halfspace == Mf::Plane::INTERSECT)
{
- halfspace = yz.intersects(aabb_);
+ halfspace = yz.intersects(mAabb);
}
if (halfspace == Mf::Plane::POSITIVE)
else if (halfspace == Mf::Plane::NEGATIVE)
{
Mf::Plane yz = aabb.getPlaneYZ();
- halfspace = yz.intersects(sphere_);
+ halfspace = yz.intersects(mSphere);
if (halfspace == Mf::Plane::INTERSECT)
{
- halfspace = yz.intersects(aabb_);
+ halfspace = yz.intersects(mAabb);
}
if (halfspace == Mf::Plane::POSITIVE)
else if (halfspace == Mf::Plane::NEGATIVE)
{
Mf::Plane xz = aabb.getPlaneXZ();
- halfspace = xz.intersects(sphere_);
+ halfspace = xz.intersects(mSphere);
if (halfspace == Mf::Plane::INTERSECT)
{
- halfspace = xz.intersects(aabb_);
+ halfspace = xz.intersects(mAabb);
}
if (halfspace == Mf::Plane::POSITIVE)
{
Mf::Plane yz = aabb.getPlaneYZ();
- halfspace = yz.intersects(sphere_);
+ halfspace = yz.intersects(mSphere);
if (halfspace == Mf::Plane::INTERSECT)
{
- halfspace = yz.intersects(aabb_);
+ halfspace = yz.intersects(mAabb);
}
if (halfspace == Mf::Plane::POSITIVE)
else if (halfspace == Mf::Plane::NEGATIVE)
{
Mf::Plane yz = aabb.getPlaneYZ();
- halfspace = yz.intersects(sphere_);
+ halfspace = yz.intersects(mSphere);
if (halfspace == Mf::Plane::INTERSECT)
{
- halfspace = yz.intersects(aabb_);
+ halfspace = yz.intersects(mAabb);
}
if (halfspace == Mf::Plane::POSITIVE)
#include <Moof/Entity.hh>
#include <Moof/Math.hh>
#include <Moof/Octree.hh>
-#include <Moof/Physics.hh>
+#include <Moof/RigidBody.hh>
#include <Moof/Sphere.hh>
#include "Animation.hh"
* includes the heroine herself and the bad guys.
*/
-struct Character : public Mf::Entity, public Mf::OctreeInsertable
+class Character : public Mf::RigidBody2, public Mf::OctreeInsertable
{
-protected:
-
- Mf::Vector2 userForce;
-
public:
Character(const std::string& name);
virtual void update(Mf::Scalar t, Mf::Scalar dt);
virtual void draw(Mf::Scalar alpha) const;
- virtual bool isInsideAabb(const Mf::Aabb& aabb) const;
virtual int getOctant(const Mf::Aabb& aabb) const;
- Mf::State2 previous;
- Mf::State2 current;
-
- Tilemap tilemap;
- Animation animation;
-
- Mf::Aabb aabb_;
- Mf::Sphere sphere_;
+ Tilemap tilemap;
+ Animation animation;
private:
GameLayer::GameLayer() :
- music("BeatTheCube"),
- punchSound("Thump")
+ mMusic("BeatTheCube"),
+ mPunchSound("Thump")
{
- music.setLooping(true);
- music.enqueue("NightFusionLoop");
- music.stream();
+ mMusic.setLooping(true);
+ mMusic.enqueue("NightFusionLoop");
+ mMusic.stream();
- heroine = Heroine::alloc();
- heroine->animation.startSequence("FlyDiagonallyUp");
+ mHeroine = Heroine::alloc();
+ mHeroine->animation.startSequence("FlyDiagonallyUp");
Mf::Scalar a[6] = {0.0, 1.5, -0.5, 3.0, -2.0, 1.0};
- interp.init(a, 2.0, Mf::Interpolator::OSCILLATE);
+ mInterp.init(a, 2.0, Mf::Interpolator::OSCILLATE);
- scene = Scene::alloc("Classic");
+ mScene = Scene::alloc("Classic");
setProjection();
- hud = Hud::alloc();
+ mHud = Hud::alloc();
}
void GameLayer::pushed(Mf::Engine& engine)
{
- engine.push(hud);
+ engine.push(mHud);
}
void GameLayer::update(Mf::Scalar t, Mf::Scalar dt)
{
- camera.update(t, dt);
- heroine->update(t, dt);
+ mCamera.update(t, dt);
+ mHeroine->update(t, dt);
- scene->checkForCollision(*heroine);
+ mScene->checkForCollision(*mHeroine);
- //camera.lookAt(heroine->getSphere().point);
- camera.setPosition(Mf::Vector3(-heroine->current.position[0],
- -heroine->current.position[1], -256));
+ mCamera.setPosition(Mf::Vector3(-mHeroine->getState().position[0],
+ -mHeroine->getState().position[1], -256));
+ //mCamera.lookAt(Mf::promote(mHeroine->getState().position));
- //Mf::Vector3 heroinePosition = Mf::promote(heroine->current.position);
+ //Mf::Vector3 heroinePosition = Mf::promote(mHeroine->getState().position);
//Mf::Sound::setListenerPosition(heroinePosition);
- interp.update(t, dt);
- hud->setBar1Progress(interp.getState(dt));
- hud->setBar2Progress(1.0 - interp.getState(dt));
+ mInterp.update(t, dt);
+ mHud->setBar1Progress(mInterp.getState(dt));
+ mHud->setBar2Progress(1.0 - mInterp.getState(dt));
}
void GameLayer::draw(Mf::Scalar alpha) const
{
- camera.uploadToGL();
+ mCamera.uploadToGL(alpha);
// DRAW THE SCENE
Mf::Texture::resetBind();
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
- scene->drawIfVisible(alpha, camera.getFrustum());
+ mScene->drawIfVisible(alpha, mCamera.getFrustum());
- heroine->draw(alpha);
+ mHeroine->draw(alpha);
}
bool GameLayer::handleEvent(const Mf::Event& event)
case SDL_KEYDOWN:
if (event.key.keysym.sym == SDLK_SPACE)
{
- heroine->animation.startSequence("Flattened");
+ mHeroine->animation.startSequence("Flattened");
Mf::logInfo("thump!");
- punchSound.play();
+ mPunchSound.play();
return true;
}
else if (event.key.keysym.sym == SDLK_p)
{
- music.toggle();
+ mMusic.toggle();
return true;
}
else if (event.key.keysym.sym == SDLK_y)
}
case SDL_KEYUP:
- return heroine->handleEvent(event);
+ return mHeroine->handleEvent(event);
case SDL_MOUSEMOTION:
case SDL_MOUSEBUTTONDOWN:
- camera.handleEvent(event);
+ mCamera.handleEvent(event);
return true;
case SDL_VIDEORESIZE:
void GameLayer::setProjection(Mf::Scalar width, Mf::Scalar height)
{
- camera.setProjection(cml::rad(60.0), width / height, 32.0, 2500.0);
+ mCamera.setProjection(cml::rad(60.0), width / height, 32.0, 2500.0);
}
void setProjection();
void setProjection(Mf::Scalar width, Mf::Scalar height);
- Mf::Sound music;
- HeroineP heroine;
- SceneP scene;
- Mf::Sound punchSound;
+ Mf::Sound mMusic;
- Mf::PolynomialInterpolator<5> interp;
+ HeroineP mHeroine;
+ SceneP mScene;
+ Mf::Sound mPunchSound;
- Mf::Camera camera;
+ Mf::PolynomialInterpolator<5> mInterp;
- HudP hud;
+ Mf::Camera mCamera;
+
+ HudP mHud;
};
case SDL_KEYDOWN:
if (event.key.keysym.sym == SDLK_a)
{
- current.force += Mf::Vector2(-force, 0.0);
+ mState.force += Mf::Vector2(-force, 0.0);
return true;
}
else if (event.key.keysym.sym == SDLK_d)
{
- current.force += Mf::Vector2(force, 0.0);
+ mState.force += Mf::Vector2(force, 0.0);
return true;
}
else if (event.key.keysym.sym == SDLK_s)
{
- current.force += Mf::Vector2(0.0, -force);
+ mState.force += Mf::Vector2(0.0, -force);
return true;
}
else if (event.key.keysym.sym == SDLK_w)
{
- current.force += Mf::Vector2(0.0, force);
+ mState.force += Mf::Vector2(0.0, force);
return true;
}
case SDL_KEYUP:
if (event.key.keysym.sym == SDLK_a)
{
- current.force += Mf::Vector2(force, 0.0);
+ mState.force += Mf::Vector2(force, 0.0);
return true;
}
else if (event.key.keysym.sym == SDLK_d)
{
- current.force += Mf::Vector2(-force, 0.0);
+ mState.force += Mf::Vector2(-force, 0.0);
return true;
}
else if (event.key.keysym.sym == SDLK_s)
{
- current.force += Mf::Vector2(0.0, force);
+ mState.force += Mf::Vector2(0.0, force);
return true;
}
else if (event.key.keysym.sym == SDLK_w)
{
- current.force += Mf::Vector2(0.0, -force);
+ mState.force += Mf::Vector2(0.0, -force);
return true;
}
}
/**
- * Parent class of animate objects with "personalities." This basically
- * includes the heroine herself and the bad guys.
+ * The protagonist.
*/
-struct Heroine : public Character
+class Heroine : public Character
{
+public:
+
Heroine();
static HeroineP alloc()
ProgressBar::ProgressBar(const Tilemap& tilemap, Tilemap::Index index) :
- progress_(0.0),
- tilemap_(tilemap)
+ mProgress(0.0),
+ mTilemap(tilemap)
{
- tilemap.getTileCoords(index, texCoords_);
+ tilemap.getTileCoords(index, mTexCoords);
- Mf::Scalar half = (texCoords_[2] - texCoords_[0]) / 2.0 + texCoords_[0];
- midCoords_[0] = half - 0.01;
- midCoords_[1] = half + 0.01;
+ Mf::Scalar half = (mTexCoords[2] - mTexCoords[0]) / 2.0 + mTexCoords[0];
+ mMidCoords[0] = half - 0.01;
+ mMidCoords[1] = half + 0.01;
}
void ProgressBar::resize(const Mf::Rectangle& rect)
Mf::Scalar height = rect.max[1] - rect.min[1];
Mf::Scalar halfHeight = height / 2.0;
- width_ = rect.max[0] - rect.min[0] - height;
+ mWidth = rect.max[0] - rect.min[0] - height;
// assert width > 0
- vertices_[0] = rect.min;
- vertices_[1] = Mf::Vector2(rect.min[0] + halfHeight, rect.min[1]);
- vertices_[2] = vertices_[1];
- vertices_[3] = Mf::Vector2(rect.min[0] + height, rect.min[1]);
- vertices_[4] = Mf::Vector2(rect.min[0] + height, rect.max[1]);
- vertices_[5] = Mf::Vector2(rect.min[0] + halfHeight, rect.max[1]);
- vertices_[6] = vertices_[5];
- vertices_[7] = Mf::Vector2(rect.min[0], rect.max[1]);
+ mVertices[0] = rect.min;
+ mVertices[1] = Mf::Vector2(rect.min[0] + halfHeight, rect.min[1]);
+ mVertices[2] = mVertices[1];
+ mVertices[3] = Mf::Vector2(rect.min[0] + height, rect.min[1]);
+ mVertices[4] = Mf::Vector2(rect.min[0] + height, rect.max[1]);
+ mVertices[5] = Mf::Vector2(rect.min[0] + halfHeight, rect.max[1]);
+ mVertices[6] = mVertices[5];
+ mVertices[7] = Mf::Vector2(rect.min[0], rect.max[1]);
- setProgress(progress_);
+ setProgress(mProgress);
}
void ProgressBar::setProgress(Mf::Scalar progress)
{
- Mf::Scalar halfHeight = (vertices_[7][1] - vertices_[0][1]) / 2.0;
+ Mf::Scalar halfHeight = (mVertices[7][1] - mVertices[0][1]) / 2.0;
- vertices_[2][0] = vertices_[1][0] + progress * width_;
- vertices_[3][0] = vertices_[1][0] + progress * width_ + halfHeight;
- vertices_[4][0] = vertices_[1][0] + progress * width_ + halfHeight;
- vertices_[5][0] = vertices_[1][0] + progress * width_;
+ mVertices[2][0] = mVertices[1][0] + progress * mWidth;
+ mVertices[3][0] = mVertices[1][0] + progress * mWidth + halfHeight;
+ mVertices[4][0] = mVertices[1][0] + progress * mWidth + halfHeight;
+ mVertices[5][0] = mVertices[1][0] + progress * mWidth;
- progress_ = progress;
+ mProgress = progress;
}
void ProgressBar::draw(Mf::Scalar alpha) const
{
- if (Mf::isEqual(progress_, 0.0))
+ if (Mf::isEqual(mProgress, 0.0))
{
// don't draw anything if the progress is 0%
return;
}
glColor4f(1.0f, 1.0f, 1.0f, 0.85f);
- tilemap_.bind();
+ mTilemap.bind();
glBegin(GL_QUADS);
- glTexCoord2(texCoords_[0], texCoords_[1]);
- glVertex2v(vertices_[0].data());
- glTexCoord2(midCoords_[0], texCoords_[3]);
- glVertex2v(vertices_[1].data());
- glTexCoord2(midCoords_[0], texCoords_[5]);
- glVertex2v(vertices_[6].data());
- glTexCoord2(texCoords_[6], texCoords_[7]);
- glVertex2v(vertices_[7].data());
-
- glTexCoord2(midCoords_[0], texCoords_[1]);
- glVertex2v(vertices_[1].data());
- glTexCoord2(midCoords_[1], texCoords_[3]);
- glVertex2v(vertices_[2].data());
- glTexCoord2(midCoords_[1], texCoords_[5]);
- glVertex2v(vertices_[5].data());
- glTexCoord2(midCoords_[0], texCoords_[7]);
- glVertex2v(vertices_[6].data());
-
- glTexCoord2(midCoords_[1], texCoords_[1]);
- glVertex2v(vertices_[2].data());
- glTexCoord2(texCoords_[2], texCoords_[3]);
- glVertex2v(vertices_[3].data());
- glTexCoord2(texCoords_[4], texCoords_[5]);
- glVertex2v(vertices_[4].data());
- glTexCoord2(midCoords_[1], texCoords_[7]);
- glVertex2v(vertices_[5].data());
+ glTexCoord2(mTexCoords[0], mTexCoords[1]);
+ glVertex2v(mVertices[0].data());
+ glTexCoord2(mMidCoords[0], mTexCoords[3]);
+ glVertex2v(mVertices[1].data());
+ glTexCoord2(mMidCoords[0], mTexCoords[5]);
+ glVertex2v(mVertices[6].data());
+ glTexCoord2(mTexCoords[6], mTexCoords[7]);
+ glVertex2v(mVertices[7].data());
+
+ glTexCoord2(mMidCoords[0], mTexCoords[1]);
+ glVertex2v(mVertices[1].data());
+ glTexCoord2(mMidCoords[1], mTexCoords[3]);
+ glVertex2v(mVertices[2].data());
+ glTexCoord2(mMidCoords[1], mTexCoords[5]);
+ glVertex2v(mVertices[5].data());
+ glTexCoord2(mMidCoords[0], mTexCoords[7]);
+ glVertex2v(mVertices[6].data());
+
+ glTexCoord2(mMidCoords[1], mTexCoords[1]);
+ glVertex2v(mVertices[2].data());
+ glTexCoord2(mTexCoords[2], mTexCoords[3]);
+ glVertex2v(mVertices[3].data());
+ glTexCoord2(mTexCoords[4], mTexCoords[5]);
+ glVertex2v(mVertices[4].data());
+ glTexCoord2(mMidCoords[1], mTexCoords[7]);
+ glVertex2v(mVertices[5].data());
glEnd();
}
Hud::Hud() :
- bar1_(Tilemap("StatusBars"), 0),
- bar2_(Tilemap("StatusBars"), 2),
- font_("Font")
+ mBar1(Tilemap("StatusBars"), 0),
+ mBar2(Tilemap("StatusBars"), 2),
+ mFont("Font")
{
resize(800, 600);
}
void Hud::resize(int width, int height)
{
- cml::matrix_orthographic_RH(projection_,
+ cml::matrix_orthographic_RH(mProjection,
SCALAR(0.0),
Mf::Scalar(width), SCALAR(0.0), Mf::Scalar(height),
SCALAR(1.0), SCALAR(-1.0), cml::z_clip_neg_one);
// position the two progress bars at the top-left of the screen
- bar1_.resize(Mf::Rectangle(20, height - 51,
+ mBar1.resize(Mf::Rectangle(20, height - 51,
0.7 * width, height - 3));
- bar2_.resize(Mf::Rectangle(20, height - 28,
+ mBar2.resize(Mf::Rectangle(20, height - 28,
0.7 * width, height - 70));
setBar1Progress(0.05);
{
glMatrixMode(GL_PROJECTION);
glPushMatrix();
- glLoadMatrix(projection_.data());
+ glLoadMatrix(mProjection.data());
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
- bar1_.draw();
- bar2_.draw();
+ mBar1.draw();
+ mBar2.draw();
glDisable(GL_BLEND);
glEnable(GL_DEPTH_TEST);
#include "Tilemap.hh"
+// TODO this stuff is still just hacked up
+
class ProgressBar : public Mf::Drawable
{
public:
private:
- Mf::Scalar progress_;
+ Mf::Scalar mProgress;
- Mf::Vector2 vertices_[8];
- Mf::Scalar width_;
+ Mf::Vector2 mVertices[8];
+ Mf::Scalar mWidth;
- Tilemap tilemap_;
- Mf::Scalar texCoords_[8];
- Mf::Scalar midCoords_[2];
+ Tilemap mTilemap;
+ Mf::Scalar mTexCoords[8];
+ Mf::Scalar mMidCoords[2];
};
void setBar1Progress(Mf::Scalar progress)
{
// pass through
- bar1_.setProgress(progress);
+ mBar1.setProgress(progress);
}
void setBar2Progress(Mf::Scalar progress)
{
// pass through
- bar2_.setProgress(progress);
+ mBar2.setProgress(progress);
}
void setNumber(unsigned value);
private:
- ProgressBar bar1_;
- ProgressBar bar2_;
+ ProgressBar mBar1;
+ ProgressBar mBar2;
- unsigned number_;
- Tilemap font_;
+ unsigned mNumber;
+ Tilemap mFont;
- Mf::Matrix4 projection_;
+ Mf::Matrix4 mProjection;
};
}
-void MainLayer::pushed(Mf::Engine& e)
+void MainLayer::pushed(Mf::Engine& engine)
{
- engine = &e;
+ mEngine = &engine;
//Mf::Scalar coeff[] = {0.0, 1.0};
//Mf::Lerp interp(coeff, 0.25);
//Mf::Transition<Mf::Lerp>::alloc(gameLayer, Mf::LayerP(), interp);
//engine->push(transition);
//engine->push(GameLayer::alloc());
- engine->push(TitleLayer::alloc());
+ mEngine->push(TitleLayer::alloc());
}
}
else if (event.key.keysym.sym == SDLK_f)
{
- engine->getVideo().toggleFull();
+ mEngine->getVideo().toggleFull();
}
else if (event.key.keysym.sym == SDLK_l)
{
- Mf::Video& video = engine->getVideo();
+ Mf::Video& video = mEngine->getVideo();
video.toggleCursorGrab();
video.toggleCursorVisible();
}
else if (event.key.keysym.sym == SDLK_y)
{
- engine->push(GameLayer::alloc());
+ mEngine->push(GameLayer::alloc());
}
break;
// the operating system will take care of cleaning up
exit(0);
#else
- engine->clear();
+ mEngine->clear();
#endif
}
void printUsage()
{
- std::cout << "Usage: "PACKAGE" [-h|--help] [-i|--info] [OPTION=VALUE]..." << std::endl
+ std::cout << "Usage: "PACKAGE" [-h|--help] [-i|--info] [OPTION=VALUE]..."
+ << std::endl
<< "The alien-smashing action game." << std::endl
<< std::endl
<< "Options:" << std::endl
}
+typedef cml::matrix< Mf::Scalar, cml::fixed<5,5>,
+ cml::col_basis, cml::col_major > Matrix5;
int main(int argc, char* argv[])
{
class MainLayer;
typedef boost::shared_ptr<MainLayer> MainLayerP;
-struct MainLayer : public Mf::Layer
+class MainLayer : public Mf::Layer
{
+public:
+
MainLayer();
~MainLayer();
void setupGL();
void contextRecreated(const Mf::Notification* note);
- Mf::Engine* engine;
+ Mf::Engine* mEngine;
};
Moof/Rectangle.hh \
Moof/Resource.cc \
Moof/Resource.hh \
- Moof/RK4.hh \
+ Moof/RigidBody.hh \
Moof/Script.hh \
Moof/Settings.cc \
Moof/Settings.hh \
octant.init(Vector3(min[0], min[1], mid[2]),
Vector3(mid[0], mid[1], max[2]));
break;
+
case 1:
octant.init(Vector3(mid[0], min[1], mid[2]),
Vector3(max[0], mid[1], max[2]));
break;
+
case 2:
octant.init(mid, max);
break;
+
case 3:
octant.init(Vector3(min[0], mid[1], mid[2]),
Vector3(mid[0], max[1], max[2]));
break;
+
case 4:
octant.init(min, mid);
break;
+
case 5:
octant.init(Vector3(mid[0], min[1], min[2]),
Vector3(max[0], mid[1], mid[2]));
break;
+
case 6:
octant.init(Vector3(mid[0], mid[1], min[2]),
Vector3(max[0], max[1], mid[2]));
break;
+
case 7:
octant.init(Vector3(min[0], mid[1], min[2]),
Vector3(mid[0], max[1], mid[2]));
Vector3 min;
Vector3 max;
-
Aabb() {}
Aabb(const Vector3& a, const Vector3& b)
namespace Mf {
-void Camera::setPosition(const Vector3& point)
+void Camera::setPosition(const Vector3& position)
{
- position_ = point;
- calculateSecondary();
- //Vector3 coeff[2] = {position_, point};
- //pInterp_.init(coeff, 0.1);
+ mState.position = position;
}
+
void Camera::setRotation(const Quaternion& rotation)
{
- rotation_ = rotation;
+ mState.orientation = rotation;
+}
+
+void Camera::lookAt(const Vector3& point)
+{
+ // FIXME this doesn't work as expected
+ cml::quaternion_rotation_aim_at(mState.orientation, mState.position, point,
+ Vector3(0.0, 1.0, 0.0));
}
void Camera::setProjection(const Matrix4& projection)
{
- projection_ = projection;
+ mProjection = projection;
}
void Camera::setProjection(Scalar fovy, Scalar aspect, Scalar abutting,
Scalar distant)
{
- cml::matrix_perspective_yfov_RH(projection_, fovy, aspect, abutting,
+ cml::matrix_perspective_yfov_RH(mProjection, fovy, aspect, abutting,
distant, cml::z_clip_neg_one);
- calculateSecondary();
}
-void Camera::uploadToGL() const
+void Camera::uploadToGL(Scalar alpha) const
{
+ calculate(alpha);
+
glMatrixMode(GL_PROJECTION);
- glMultMatrix(projection_.data());
+ glMultMatrix(mProjection.data());
glMatrixMode(GL_MODELVIEW);
- glMultMatrix(modelview_.data());
+ glMultMatrix(mModelview.data());
}
-void Camera::update(Scalar t, Scalar dt)
+void Camera::calculate(Scalar alpha) const
{
- //pInterp_.update(dt);
- //position_ = pInterp_.getState(0.0);
+ State3 state = getState(alpha);
- //calculateSecondary();
+ cml::matrix_rotation_quaternion(mModelview, state.orientation);
+
+ Matrix4 translate;
+ cml::matrix_translation(translate, state.position);
+
+ mModelview *= translate;
+
+ mFrustum.init(mModelview, mProjection);
}
-void Camera::lookAt(const Vector3& point)
+void Camera::update(Scalar t, Scalar dt)
+{
+ RigidBody3::update(t, dt);
+}
+
+void Camera::draw(Scalar alpha) const
{
- cml::quaternion_rotation_aim_at(rotation_, position_, point,
- Vector3(0.0, -1.0, 0.0));
- calculateSecondary();
+ mSphere.draw(alpha);
}
+
void Camera::handleEvent(const Event& event)
{
+ const Scalar ds = 50.0;
+
switch (event.type)
{
case SDL_KEYDOWN:
if (event.key.keysym.sym == SDLK_RIGHT)
{
- Vector3 vec = position_;
- vec[0] -= 50.0;
- setPosition(vec);
+ mState.position[0] -= ds;
}
else if (event.key.keysym.sym == SDLK_LEFT)
{
- Vector3 vec = position_;
- vec[0] += 50.0;
- setPosition(vec);
+ mState.position[0] += ds;
}
else if (event.key.keysym.sym == SDLK_UP)
{
- Vector3 vec = position_;
- vec[1] -= 50.0;
- setPosition(vec);
+ mState.position[1] -= ds;
}
else if (event.key.keysym.sym == SDLK_DOWN)
{
- Vector3 vec = position_;
- vec[1] += 50.0;
- setPosition(vec);
+ mState.position[1] += ds;
}
else if (event.key.keysym.sym == SDLK_PAGEUP)
{
- Vector3 vec = position_;
- vec[2] += 50.0;
- setPosition(vec);
+ mState.position[2] += ds;
}
else if (event.key.keysym.sym == SDLK_PAGEDOWN)
{
- Vector3 vec = position_;
- vec[2] -= 50.0;
- setPosition(vec);
+ mState.position[2] -= ds;
}
break;
case SDL_MOUSEMOTION:
{
- Scalar xrel = cml::rad(Scalar(event.motion.xrel) / 5.0);
- Scalar yrel = cml::rad(Scalar(event.motion.yrel) / 5.0);
+ Scalar xrel = cml::rad(Scalar(event.motion.xrel) / 6.0);
+ Scalar yrel = cml::rad(Scalar(event.motion.yrel) / 6.0);
- Quaternion rotation = rotation_;
+ Quaternion rotation = mState.orientation;
- cml::quaternion_rotate_about_world_x(rotation, yrel);
- //rotation_.normalize();
- cml::quaternion_rotate_about_world_y(rotation, xrel);
- rotation.normalize();
+ cml::quaternion_rotate_about_world_x(rotation, yrel);
+ //mRotation.normalize();
+ cml::quaternion_rotate_about_world_y(rotation, xrel);
- setRotation(rotation);
- break;
+ rotation.normalize();
+ mState.orientation = rotation;
}
+ break;
case SDL_MOUSEBUTTONDOWN:
if (event.button.button == SDL_BUTTON_WHEELUP)
{
- Vector3 vec = position_;
- vec[2] += 50.0;
- setPosition(vec);
+ mState.position[2] -= ds;
}
else if (event.button.button == SDL_BUTTON_WHEELDOWN)
{
- Vector3 vec = position_;
- vec[2] -= 50.0;
- setPosition(vec);
+ mState.position[2] -= ds;
}
break;
}
-
- calculateSecondary();
-}
-
-void Camera::calculateSecondary()
-{
- cml::matrix_rotation_quaternion(modelview_, rotation_);
-
- Matrix4 translate;
- cml::matrix_translation(translate, position_);
-
- //modelview_.transpose();
- modelview_ *= translate;
- //modelview_ = translate * modelview_;
-
- frustum_.init(modelview_, projection_);
}
#include <Moof/Event.hh>
#include <Moof/Frustum.hh>
-#include <Moof/Interpolator.hh>
#include <Moof/Math.hh>
+#include <Moof/RigidBody.hh>
namespace Mf {
-class Camera
+class Camera : public RigidBody3
{
- void calculateSecondary();
-
public:
- Camera() :
- position_(0.0, 0.0, 0.0)
+
+ Camera()
{
- cml::quaternion_rotation_world_y(rotation_, SCALAR(0.0));
- calculateSecondary();
+ mState.init();
+ mPrevState.init();
+
+ cml::quaternion_rotation_world_y(mState.orientation, SCALAR(0.0));
}
- void setPosition(const Vector3& point);
+ void setPosition(const Vector3& position);
void setRotation(const Quaternion& rotation);
+ void lookAt(const Vector3& point);
+
void setProjection(const Matrix4& projection);
void setProjection(Scalar fovy, Scalar aspect, Scalar near, Scalar far);
- void uploadToGL() const;
-
- void lookAt(const Vector3& point);
+ const Matrix4& getModelview() const
+ {
+ return mModelview;
+ }
- const Matrix4& getModelviewMatrix() const
+ const Matrix4& getProjection() const
{
- return modelview_;
+ return mProjection;
}
const Frustum& getFrustum() const
{
- return frustum_;
+ return mFrustum;
}
- void handleEvent(const Event& event);
+
+ void uploadToGL(Scalar alpha = 0) const;
+
void update(Scalar t, Scalar dt);
+ void draw(Scalar alpha = 0) const;
+ void handleEvent(const Event& event);
private:
- Vector3 position_;
- Quaternion rotation_;
- Matrix4 projection_;
- Matrix4 modelview_;
- Frustum frustum_;
+ void calculate(Scalar alpha) const;
+
+ mutable Matrix4 mModelview;
+ Matrix4 mProjection;
- Lerp3 pInterp_;
+ mutable Frustum mFrustum;
};
namespace Mf {
-struct Dispatcher::Impl
+class Dispatcher::Impl
{
+ friend class Dispatcher;
+
Impl() :
- id(1) {}
+ mId(1) {}
Dispatcher::Handler getNewHandler()
{
- id += 2;
- return (Dispatcher::Handler)id;
+ mId += 2;
+ return (Dispatcher::Handler)mId;
}
typedef std::pair<Dispatcher::Handler,Dispatcher::Function> Callback;
inline Handler addHandler(const std::string& message,
const Function& callback, Handler id)
{
- callbacks.insert(std::make_pair(message, std::make_pair(id, callback)));
- handlers.insert(std::make_pair(id, message));
+ mCallbacks.insert(std::make_pair(message, std::make_pair(id, callback)));
+ mHandlers.insert(std::make_pair(id, message));
return id;
}
inline void removeHandler(Handler id)
{
- std::pair<HandlerIter,HandlerIter> matching(handlers.equal_range(id));
+ std::pair<HandlerIter,HandlerIter> matching(mHandlers.equal_range(id));
for (HandlerIter it = matching.first; it != matching.second; ++it)
{
- CallbackIter first = callbacks.find((*it).second);
- CallbackIter last = callbacks.end();
+ CallbackIter first = mCallbacks.find((*it).second);
+ CallbackIter last = mCallbacks.end();
for (CallbackIter jt = first; jt != last; ++jt)
{
if ((*jt).second.first == id)
{
- callbacks.erase(jt);
+ mCallbacks.erase(jt);
break;
}
}
}
- handlers.erase(id);
+ mHandlers.erase(id);
+ }
+
+ void dispatch(const std::string& message, const Notification* param)
+ {
+ std::pair<CallbackIter,CallbackIter>
+ callbacks(mCallbacks.equal_range(message));
+
+ for (CallbackIter it = callbacks.first; it != callbacks.second; ++it)
+ {
+ Function callback = (*it).second.second;
+ callback(param);
+ }
}
- unsigned long id;
- CallbackLookup callbacks;
- HandlerLookup handlers;
+ unsigned long mId;
+
+ CallbackLookup mCallbacks;
+ HandlerLookup mHandlers;
};
Dispatcher::Dispatcher() :
- impl_(new Dispatcher::Impl) {}
+ mImpl(new Dispatcher::Impl) {}
Dispatcher::~Dispatcher() {}
Dispatcher::Handler Dispatcher::addHandler(const std::string& message,
const Function& callback)
{
- return addHandler(message, callback, impl_->getNewHandler());
+ return addHandler(message, callback, mImpl->getNewHandler());
}
Dispatcher::Handler Dispatcher::addHandler(const std::string& message,
const Function& callback, Handler id)
{
// pass through
- return impl_->addHandler(message, callback, id);
+ return mImpl->addHandler(message, callback, id);
}
void Dispatcher::removeHandler(Handler id)
{
// pass through
- return impl_->removeHandler(id);
+ return mImpl->removeHandler(id);
}
void Dispatcher::dispatch(const std::string& message, const Notification* param)
{
- std::pair<Impl::CallbackIter,Impl::CallbackIter>
- callbacks(impl_->callbacks.equal_range(message));
-
- for (Impl::CallbackIter it = callbacks.first; it != callbacks.second; ++it)
- {
- Function callback = (*it).second.second;
- callback(param);
- }
+ // pass through
+ mImpl->dispatch(message, param);
}
class Dispatcher
{
class Impl;
- boost::shared_ptr<Impl> impl_;
+ boost::shared_ptr<Impl> mImpl;
public:
Dispatcher::getInstance().dispatch(message, param);
}
-} // namespace dispatch
+} // namespace dispatcher
} // namespace Mf
class Engine::Impl
{
public:
+
Impl(int argc, char* argv[], const std::string& name,
const std::string& iconFile, const std::string& configFile,
Engine& engine) :
- interface(engine),
- timestep(0.01),
- printFps(false)
+ mInterface(engine),
+ mTimestep(0.01),
+ mPrintFps(false)
{
#if defined(_WIN32) || defined (_WIN64) || defined(__WIN32__)
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER) != 0)
if (settings.get("rngseed", randomSeed)) setSeed(randomSeed);
else setSeed();
- Scalar timeStep = 80.0;
- settings.get("timestep", timeStep);
- timestep = 1.0 / timeStep;
+ Scalar timestep = 80.0;
+ settings.get("timestep", timestep);
+ mTimestep = 1.0 / timestep;
Scalar maxFps = 40.0;
settings.get("maxfps", maxFps);
- drawRate = 1.0 / maxFps;
+ mDrawRate = 1.0 / maxFps;
- settings.get("printfps", printFps);
+ settings.get("printfps", mPrintFps);
- video = Video::alloc(name, iconFile);
- video->makeActive();
+ mVideo = Video::alloc(name, iconFile);
+ mVideo->makeActive();
}
~Impl()
{
// the video object must be destroyed before we can shutdown SDL
- video.reset();
+ mVideo.reset();
alutExit();
FE_Quit();
Scalar totalTime = 0.0;
Scalar deltaTime = 0.0;
- Scalar accumulator = timestep;
+ Scalar accumulator = mTimestep;
- fps = 0;
+ mFps = 0;
int frameAccum = 0;
do
Timer::fireIfExpired(ticksNow);
- while (accumulator >= timestep)
+ while (accumulator >= mTimestep)
{
dispatchEvents();
- update(totalTime, timestep);
+ update(totalTime, mTimestep);
- totalTime += timestep;
- accumulator -= timestep;
+ totalTime += mTimestep;
+ accumulator -= mTimestep;
- nextStep += timestep;
+ nextStep += mTimestep;
}
if (ticksNow >= nextStep)
{
- nextStep = ticksNow + timestep;
+ nextStep = ticksNow + mTimestep;
}
if (ticksNow >= nextDraw)
if (ticksNow >= nextFpsUpdate) // determine the actual fps
{
- fps = frameAccum;
+ mFps = frameAccum;
frameAccum = 0;
nextFpsUpdate += 1.0;
nextFpsUpdate = ticksNow + 1.0;
}
- if (printFps)
+ if (mPrintFps)
{
- logInfo("%d fps", fps);
+ logInfo("%d fps", mFps);
}
}
- draw(accumulator / timestep);
- video->swap();
+ draw(accumulator / mTimestep);
+ mVideo->swap();
- nextDraw += drawRate;
+ nextDraw += mDrawRate;
if (ticksNow >= nextDraw)
{
// we missed some scheduled draws, so reset the schedule
- nextDraw = ticksNow + drawRate;
+ nextDraw = ticksNow + mDrawRate;
}
}
Timer::sleep(std::min(std::min(nextStep, nextDraw),
Timer::getNextFire()), true);
}
- while (!stack.empty());
+ while (!mStack.empty());
}
void dispatchEvents()
break;
case SDL_VIDEORESIZE:
- video->resize(event.resize.w, event.resize.h);
+ mVideo->resize(event.resize.w, event.resize.h);
break;
}
void update(Scalar t, Scalar dt)
{
- for (stackIt = stack.begin(); stackIt != stack.end(); ++stackIt)
+ for (mStackIt = mStack.begin(); mStackIt != mStack.end(); ++mStackIt)
{
- (*stackIt)->update(t, dt);
+ (*mStackIt)->update(t, dt);
}
}
{
// FIXME - this will crash if the layer being drawn pops itself
std::list<LayerP>::reverse_iterator it;
- for (it = stack.rbegin(); it != stack.rend(); ++it)
+ for (it = mStack.rbegin(); it != mStack.rend(); ++it)
{
(*it)->draw(alpha);
}
void handleEvent(const Event& event)
{
- for (stackIt = stack.begin(); stackIt != stack.end(); ++stackIt)
+ for (mStackIt = mStack.begin(); mStackIt != mStack.end(); ++mStackIt)
{
- if ((*stackIt)->handleEvent(event)) break;
+ if ((*mStackIt)->handleEvent(event)) break;
}
}
void push(LayerP layer)
{
ASSERT(layer && "cannot push null layer");
- stack.push_front(layer);
- logInfo(" push: %d", stack.size());
- layer->pushed(interface);
+ mStack.push_front(layer);
+ logInfo(" push: %d", mStack.size());
+ layer->pushed(mInterface);
}
LayerP pop()
{
bool fixIt = false;
- if (stack.begin() == stackIt) fixIt = true;
+ if (mStack.begin() == mStackIt) fixIt = true;
- LayerP popped = stack.front();
- stack.pop_front();
- logInfo(" pop: %d", stack.size());
- popped->popped(interface);
+ LayerP popped = mStack.front();
+ mStack.pop_front();
+ logInfo(" pop: %d", mStack.size());
+ popped->popped(mInterface);
- if (fixIt) stackIt = --stack.begin();
+ if (fixIt) mStackIt = --mStack.begin();
return popped;
}
std::list<LayerP> popped;
std::list<LayerP>::iterator it;
- for (it = stack.begin(); it != stack.end(); ++it)
+ for (it = mStack.begin(); it != mStack.end(); ++it)
{
popped.push_back(*it);
- if (it == stackIt) fixIt = true;
+ if (it == mStackIt) fixIt = true;
if ((*it).get() == layer)
{
++it;
- stack.erase(stack.begin(), it);
+ mStack.erase(mStack.begin(), it);
for (it = popped.begin(); it != popped.end(); ++it)
{
- (*it)->popped(interface);
+ (*it)->popped(mInterface);
}
- if (fixIt) stackIt = --stack.begin();
+ if (fixIt) mStackIt = --mStack.begin();
return popped.back();
}
void clear()
{
- stack.clear();
- stackIt = stack.begin();
- logInfo("clear: %d", stack.size());
+ mStack.clear();
+ mStackIt = mStack.begin();
+ logInfo("clear: %d", mStack.size());
}
- Engine& interface;
+ Engine& mInterface;
- VideoP video;
+ VideoP mVideo;
- std::list<LayerP> stack;
- std::list<LayerP>::iterator stackIt;
+ std::list<LayerP> mStack;
+ std::list<LayerP>::iterator mStackIt;
- Scalar timestep;
- Scalar drawRate;
+ Scalar mTimestep;
+ Scalar mDrawRate;
- long fps;
- bool printFps;
+ long mFps;
+ bool mPrintFps;
};
Engine::Engine(int argc, char* argv[], const std::string& name,
const std::string& iconFile, const std::string& configFile) :
- impl_(new Engine::Impl(argc, argv, name, iconFile, configFile, *this))
+ mImpl(new Engine::Impl(argc, argv, name, iconFile, configFile, *this))
{
instance = this;
}
{
ASSERT(instance && "dereferencing null pointer");
return *instance;
+ // TODO this has not been completely thought out
//static Engine engine;
//return engine;
}
void Engine::run()
{
- return impl_->run();
+ return mImpl->run();
}
void Engine::setTimestep(Scalar ts)
{
- impl_->timestep = ts;
+ mImpl->mTimestep = ts;
}
Scalar Engine::getTimestep() const
{
- return impl_->timestep;
+ return mImpl->mTimestep;
}
void Engine::setMaxFrameRate(long maxFps)
{
- impl_->drawRate = 1.0 / Scalar(maxFps);
+ mImpl->mDrawRate = 1.0 / Scalar(maxFps);
}
long Engine::getMaxFrameRate() const
{
- return long(1.0 / impl_->drawRate);
+ return long(1.0 / mImpl->mDrawRate);
}
Video& Engine::getVideo() const
{
- return *impl_->video;
+ return *mImpl->mVideo;
}
long Engine::getFrameRate() const
{
- return impl_->fps;
+ return mImpl->mFps;
}
void Engine::push(LayerP layer)
{
// pass through
- impl_->push(layer);
+ mImpl->push(layer);
}
LayerP Engine::pop()
{
// pass through
- return impl_->pop();
+ return mImpl->pop();
}
LayerP Engine::pop(Layer* layer)
{
// pass through
- return impl_->pop(layer);
+ return mImpl->pop(layer);
}
void Engine::clear()
{
// pass through
- impl_->clear();
+ mImpl->clear();
}
// forward declarations
class Video;
-struct Engine
+class Engine
{
+ class Impl;
+ boost::shared_ptr<Impl> mImpl;
+
+public:
+
Engine(int argc, char* argv[], const std::string& name,
const std::string& iconFile, const std::string& configFile);
~Engine() {}
throw *this;
}
};
-
-private:
- class Impl;
- boost::shared_ptr<Impl> impl_;
};
/**
* Interface for game objects that can be drawn to the screen and have a
- * specified size.
+ * specified volume (take up space).
*/
class Entity : public Cullable, public Drawable
{
+protected:
+
+ Aabb mAabb;
+ Sphere mSphere;
+
public:
+
virtual ~Entity() {}
virtual void drawIfVisible(Scalar alpha, const Frustum& frustum) const
{
if (isVisible(frustum)) draw(alpha);
}
+
+ virtual bool isVisible(const Frustum& frustum) const
+ {
+ return mSphere.isVisible(frustum) && mAabb.isVisible(frustum);
+ }
+
+ const Aabb& getAabb() const
+ {
+ return mAabb;
+ }
+
+ const Sphere& getSphere() const
+ {
+ return mSphere;
+ }
};
cml::extract_frustum_planes(modelview, projection, planes,
cml::z_clip_neg_one);
- planes_[0] = Plane(planes[0][0], planes[0][1], planes[0][2], planes[0][3]);
- planes_[1] = Plane(planes[1][0], planes[1][1], planes[1][2], planes[1][3]);
- planes_[2] = Plane(planes[2][0], planes[2][1], planes[2][2], planes[2][3]);
- planes_[3] = Plane(planes[3][0], planes[3][1], planes[3][2], planes[3][3]);
- planes_[4] = Plane(planes[4][0], planes[4][1], planes[4][2], planes[4][3]);
- planes_[5] = Plane(planes[5][0], planes[5][1], planes[5][2], planes[5][3]);
+ mPlanes[0] = Plane(planes[0][0], planes[0][1], planes[0][2], planes[0][3]);
+ mPlanes[1] = Plane(planes[1][0], planes[1][1], planes[1][2], planes[1][3]);
+ mPlanes[2] = Plane(planes[2][0], planes[2][1], planes[2][2], planes[2][3]);
+ mPlanes[3] = Plane(planes[3][0], planes[3][1], planes[3][2], planes[3][3]);
+ mPlanes[4] = Plane(planes[4][0], planes[4][1], planes[4][2], planes[4][3]);
+ mPlanes[5] = Plane(planes[5][0], planes[5][1], planes[5][2], planes[5][3]);
}
void Frustum::init(const Matrix4& modelview, Scalar fovy, Scalar aspect,
for (int j = 0; j < 8; ++j)
{
- if (planes_[i].intersects(corners[j]) ==
+ if (mPlanes[i].intersects(corners[j]) ==
Plane::NEGATIVE)
{
--nInside;
{
for (int i = 0; i < 6; ++i)
{
- Plane::Halfspace halfspace = planes_[i].intersects(sphere);
+ Plane::Halfspace halfspace = mPlanes[i].intersects(sphere);
if (halfspace == Plane::NEGATIVE) return OUTSIDE;
else if (halfspace == Plane::INTERSECT) return INTERSECT;
class Frustum
{
- Plane planes_[6]; // left, right, bottom, top, near, far
+ Plane mPlanes[6]; // left, right, bottom, top, near, far
public:
typedef enum
{
if (value > 1.0)
{
- switch (mode_)
+ switch (mMode)
{
case STOP:
value = 1.0;
- done_ = true;
+ mDone = true;
break;
case REPEAT:
value -= 1.0;
break;
case OSCILLATE:
value = 2.0 - value;
- scale_ *= -1.0;
+ mScale *= -1.0;
break;
}
}
else if (value < 0.0)
{
- switch (mode_)
+ switch (mMode)
{
case STOP:
value = 0.0;
- done_ = true;
+ mDone = true;
break;
case REPEAT:
value += 1.0;
break;
case OSCILLATE:
value = -value;
- scale_ *= -1.0;
+ mScale *= -1.0;
break;
}
}
}
public:
+
typedef enum
{
STOP = 0,
void init(Scalar seconds = 1.0, Mode mode = STOP)
{
- scale_ = 1.0 / seconds;
- alpha_ = 0.0;
+ mScale = 1.0 / seconds;
+ mAlpha = 0.0;
setMode(mode);
}
void setMode(Mode mode)
{
- mode_ = mode;
- done_ = false;
+ mMode = mode;
+ mDone = false;
}
void update(Scalar t, Scalar dt)
{
- if (!done_)
+ if (!mDone)
{
- alpha_ += dt * scale_;
- clamp(alpha_);
- calculate(alpha_);
+ mAlpha += dt * mScale;
+ clamp(mAlpha);
+ calculate(mAlpha);
}
}
bool isDone() const
{
- return done_;
+ return mDone;
}
virtual void calculate(Scalar alpha) = 0;
private:
- Scalar alpha_;
- Mode mode_;
- Scalar scale_;
- bool done_;
+ Scalar mAlpha;
+ Mode mMode;
+ Scalar mScale;
+ bool mDone;
};
template <class T = Scalar>
class InterpolatorBase : public Interpolator
{
public:
+
void init(Scalar seconds = 1.0, Mode mode = STOP)
{
Interpolator::init(seconds, mode);
calculate(0.0); // set value
- previous_ = value_;
+ mPrevious = mValue;
}
void calculate(Scalar alpha)
{
- previous_ = value_;
- calculate(value_, alpha);
+ mPrevious = mValue;
+ calculate(mValue, alpha);
}
virtual void calculate(T& value, Scalar alpha) = 0;
const T& getValue() const
{
- return value_;
+ return mValue;
}
const T getState(Scalar alpha) const
{
- return cml::lerp(previous_, value_, alpha);
+ return cml::lerp(mPrevious, mValue, alpha);
}
private:
- T value_;
- T previous_;
+
+ T mValue;
+ T mPrevious;
};
class PolynomialInterpolator : public InterpolatorBase<T>
{
public:
+
PolynomialInterpolator() {}
PolynomialInterpolator(const T coefficients[D+1],
for (int i = 0; i <= D; ++i)
{
// n! / (k! * (n - k)!)
- coefficients_[i] = coefficients[i] * fac[D] / (fac[i] * fac[D - i]);
+ mCoefficients[i] = coefficients[i] * fac[D] / (fac[i] * fac[D - i]);
}
InterpolatorBase<T>::init(seconds, mode);
{
Scalar beta = 1.0 - alpha;
- value = coefficients_[0] * std::pow(beta, D);
+ value = mCoefficients[0] * std::pow(beta, D);
for (int i = 1; i <= D; ++i)
{
- value += coefficients_[i] * std::pow(beta, D - i) *
+ value += mCoefficients[i] * std::pow(beta, D - i) *
std::pow(alpha, i);
}
}
private:
- T coefficients_[D+1];
+
+ T mCoefficients[D+1];
};
class PolynomialInterpolator<1,T> : public InterpolatorBase<T>
{
public:
+
PolynomialInterpolator() {}
PolynomialInterpolator(const T coefficients[2], Scalar seconds = 1.0,
void init(const T coefficients[2], Scalar seconds = 1.0,
Interpolator::Mode mode = Interpolator::STOP)
{
- a_ = coefficients[0];
- b_ = coefficients[1];
+ mA = coefficients[0];
+ mB = coefficients[1];
InterpolatorBase<T>::init(seconds, mode);
}
void calculate(T& value, Scalar alpha)
{
- value = cml::lerp(a_, b_, alpha);
+ value = cml::lerp(mA, mB, alpha);
}
private:
- T a_;
- T b_;
+
+ T mA;
+ T mB;
};
class Engine;
-struct Layer : public Drawable
+class Layer : public Drawable
{
+public:
+
virtual ~Layer() {}
virtual void pushed(Engine& engine) {}
-const Scalar EPSILON = 0.000001;
+const Scalar EPSILON = SCALAR(0.000001);
/**
* Check the equality of scalars with a certain degree of error allowed.
}
+
+// Here are some generic implementations of a few simple integrators. To use,
+// you need one type representing the state and another containing the
+// derivatives of the primary state variables. The state class must implement
+// these methods:
+//
+// void getDerivative(Derivative_Type& derivative, Scalar absoluteTime);
+// void step(const Derivative_Type& derivative, Scalar deltaTime);
+//
+// Additionally, the derivative class must overload a few operators:
+//
+// Derivative_Type operator+(const Derivative_Type& other) const
+// Derivative_Type operator*(const Derivative_Type& other) const
+
+template<typename S, typename D>
+inline D evaluate(const S& state, Scalar t)
+{
+ D derivative;
+ state.getDerivative(derivative, t);
+ return derivative;
+}
+
+template<typename S, typename D>
+inline D evaluate(S state, Scalar t, Scalar dt, const D& derivative)
+{
+ state.step(derivative, dt);
+ return evaluate<S,D>(state, t + dt);
+}
+
+
+template<typename S, typename D>
+inline void euler(S& state, Scalar t, Scalar dt)
+{
+ D a = evaluate<S,D>(state, t);
+
+ state.step(a, dt);
+}
+
+template<typename S, typename D>
+inline void rk2(S& state, Scalar t, Scalar dt)
+{
+ D a = evaluate<S,D>(state, t);
+ D b = evaluate<S,D>(state, t, dt * SCALAR(0.5), a);
+
+ state.step(b, dt);
+}
+
+template<typename S, typename D>
+inline void rk4(S& state, Scalar t, Scalar dt)
+{
+ D a = evaluate<S,D>(state, t);
+ D b = evaluate<S,D>(state, t, dt * SCALAR(0.5), a);
+ D c = evaluate<S,D>(state, t, dt * SCALAR(0.5), b);
+ D d = evaluate<S,D>(state, t, dt, c);
+
+ state.step((a + (b + c) * SCALAR(2.0) + d) * SCALAR(1.0/6.0), dt);
+}
+
+
} // namespace Mf
#endif // _MOOF_MATH_HH_
typedef std::pair<unsigned,T*> PtrValue;
typedef stlplus::hash<std::string,PtrValue,getHash> PtrMap;
- static PtrMap ptrs_;
- std::string name_;
+ static PtrMap mPtrMap;
+ std::string mName;
static T* retain(const std::string& name)
{
- typename PtrMap::iterator it = ptrs_.find(name);
+ typename PtrMap::iterator it = mPtrMap.find(name);
- if (it != ptrs_.end())
+ if (it != mPtrMap.end())
{
++((*it).second.first);
return (*it).second.second;
else
{
T* newObj = new T(name);
- ptrs_.insert(std::make_pair(name, std::make_pair(1, newObj)));
+ mPtrMap.insert(std::make_pair(name, std::make_pair(1, newObj)));
return newObj;
}
}
static void release(T* obj)
{
- releaseByName(obj->name_);
+ releaseByName(obj->mName);
}
static void releaseByName(const std::string& name)
{
typename PtrMap::iterator it;
- if ((it = ptrs_.find(name)) != ptrs_.end() && --(*it).second.first == 0)
+ if ((it = mPtrMap.find(name)) != mPtrMap.end() && --(*it).second.first == 0)
{
delete (*it).second.second;
- ptrs_.erase((*it).first);
+ mPtrMap.erase((*it).first);
}
}
public:
explicit Mippleton(const std::string& name) :
- name_(name) {}
+ mName(name) {}
const std::string& getName() const
{
- return name_;
+ return mName;
}
static boost::shared_ptr<T> getInstance(const std::string& name)
template <class T>
stlplus::hash< std::string,std::pair<unsigned,T*>,getHash >
- Mippleton<T>::ptrs_;
+ Mippleton<T>::mPtrMap;
} // namespace Mf
{
virtual ~OctreeInsertable() {}
- virtual bool isInsideAabb(const Aabb& aabb) const = 0;
virtual int getOctant(const Aabb& aabb) const = 0;
};
{
std::list<InsertableP> objects;
- Aabb aabb;
- Sphere sphere;
-
- Node(const Aabb& box) :
- aabb(box)
+ Node(const Aabb& aabb)
{
- sphere.point = aabb.getCenter();
- sphere.radius = (aabb.min - sphere.point).length();
+ mAabb = aabb;
+ mSphere.point = mAabb.getCenter();
+ mSphere.radius = (mAabb.min - mSphere.point).length();
}
void draw(Scalar alpha) const
{
- aabb.draw(alpha);
- }
-
- void drawIfVisible(Scalar alpha, const Frustum& frustum) const
- {
- if (isVisible(frustum))
- {
- aabb.draw(alpha);
- }
+ mAabb.draw(alpha);
}
void printSize()
if ((*it)->isVisible(frustum)) insertables.push_back(*it);
}
}
-
-
- bool isVisible(const Frustum& frustum) const
- {
- if (sphere.isVisible(frustum))
- {
- return aabb.isVisible(frustum);
- }
-
- return false;
- }
};
ASSERT(node.valid() && "invalid node passed");
ASSERT(entity && "null entity passed");
- if (entity->isInsideAabb(node->aabb))
+ Aabb entityAabb = entity->getAabb();
+ Aabb nodeAabb = node->getAabb();
+
+ if (!(entityAabb.max[0] < nodeAabb.max[0] &&
+ entityAabb.min[0] > nodeAabb.min[0] &&
+ entityAabb.max[1] < nodeAabb.max[1] &&
+ entityAabb.min[1] > nodeAabb.min[1] &&
+ entityAabb.max[2] < nodeAabb.max[2] &&
+ entityAabb.min[2] > nodeAabb.min[2]))
{
- return insert_recurse(entity, node);
+ node->objects.push_back(entity);
+ return node;
}
else
{
- node->objects.push_back(entity);
- return node;
+ return insert_recurse(entity, node);
}
}
ASSERT(node.valid() && "invalid node passed");
ASSERT(entity && "null entity passed");
- int octantNum = entity->getOctant(node->aabb);
+ int octantNum = entity->getOctant(node->getAabb());
if (octantNum == -1)
{
node->objects.push_back(entity);
}
else
{
- if ((int)tree_.children(node) <= octantNum)
+ if ((int)mTree.children(node) <= octantNum)
{
addChild(node, octantNum);
}
- NodeP child = tree_.child(node, octantNum);
+ NodeP child = mTree.child(node, octantNum);
ASSERT(child.valid() && "expected valid child node");
return insert_recurse(entity, child);
Aabb octant;
- for (int i = tree_.children(node); i <= index; ++i)
+ for (int i = mTree.children(node); i <= index; ++i)
{
- node->aabb.getOctant(octant, i);
- tree_.append(node, octant);
+ node->getAabb().getOctant(octant, i);
+ mTree.append(node, octant);
}
}
node->printSize();
- int octantNum = entity.getOctant(node->aabb);
+ int octantNum = entity.getOctant(node->getAabb());
if (octantNum != -1)
{
node->getAll(insertables);
- if (octantNum < (int)tree_.children(node))
+ if (octantNum < (int)mTree.children(node))
{
- NodeP child = tree_.child(node, octantNum);
+ NodeP child = mTree.child(node, octantNum);
ASSERT(child.valid() && "expected valid child node");
getNearbyObjects(insertables, entity, child);
node->getAll(insertables);
- for (unsigned i = 0; i < tree_.children(node); ++i)
+ for (unsigned i = 0; i < mTree.children(node); ++i)
{
- NodeP child = tree_.child(node, i);
+ NodeP child = mTree.child(node, i);
ASSERT(child.valid() && "expected valid child node");
getAll(insertables, child);
ASSERT(node.valid() && "invalid node passed");
// try to cull by sphere
- Frustum::Collision collision = frustum.contains(node->sphere);
+ Frustum::Collision collision = frustum.contains(node->getSphere());
if (collision == Frustum::OUTSIDE) return;
// try to cull by aabb
- collision = frustum.contains(node->aabb);
+ collision = frustum.contains(node->getAabb());
if (collision == Frustum::OUTSIDE) return;
node->getIfVisible(insertables, frustum);
}
- if (tree_.children(node) > 0)
+ if (mTree.children(node) > 0)
{
if (collision == Frustum::INSIDE)
{
- for (unsigned i = 0; i < tree_.children(node); ++i)
+ for (unsigned i = 0; i < mTree.children(node); ++i)
{
- NodeP child = tree_.child(node, i);
+ NodeP child = mTree.child(node, i);
ASSERT(child.valid() && "expected valid child node");
getAll(insertables, child);
}
else // collision == Frustum::INTERSECT
{
- for (unsigned i = 0; i < tree_.children(node); ++i)
+ for (unsigned i = 0; i < mTree.children(node); ++i)
{
- NodeP child = tree_.child(node, i);
+ NodeP child = mTree.child(node, i);
ASSERT(child.valid() && "expected valid child node");
getIfVisible(insertables, frustum, child);
}
- mutable stlplus::ntree<Node> tree_;
+ mutable stlplus::ntree<Node> mTree;
public:
void print(NodeP node)
{
logInfo("-----");
- logInfo("depth to node: %d", tree_.depth(node));
- logInfo("size of node: %d", tree_.size(node));
+ logInfo("depth to node: %d", mTree.depth(node));
+ logInfo("size of node: %d", mTree.size(node));
}
static Ptr alloc(const Node& rootNode)
explicit Octree(const Node& rootNode)
{
- tree_.insert(rootNode);
+ mTree.insert(rootNode);
}
NodeP insert(InsertableP entity)
{
- return insert(entity, tree_.root());
+ return insert(entity, mTree.root());
}
void remove(InsertableP entity, NodeP node)
void drawIfVisible(Scalar alpha, const Frustum& frustum) const
{
std::list<InsertableP> objects;
- //getIfVisible(objects, frustum);
- getNearbyObjects(objects, *savedObj);
+ getIfVisible(objects, frustum);
+ //getNearbyObjects(objects, *savedObj);
typename std::list<InsertableP>::const_iterator it;
for (it = objects.begin(); it != objects.end(); ++it)
void getAll(std::list<InsertableP>& insertables) const
{
- getAll(insertables, tree_.root());
+ getAll(insertables, mTree.root());
}
void getIfVisible(std::list<InsertableP>& insertables,
const Frustum& frustum) const
{
- getIfVisible(insertables, frustum, tree_.root());
+ getIfVisible(insertables, frustum, mTree.root());
}
mutable const OctreeInsertable* savedObj;
const OctreeInsertable& entity) const
{
logDebug("--- GETTING NEARBY");
- getNearbyObjects(insertables, entity, tree_.root());
+ getNearbyObjects(insertables, entity, mTree.root());
logDebug("---");
savedObj = &entity;
}
+++ /dev/null
-
-/*******************************************************************************
-
- Copyright (c) 2009, Charles McGarvey
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-*******************************************************************************/
-
-#ifndef _MOOF_RK4_HH_
-#define _MOOF_RK4_HH_
-
-#include <vector>
-
-#include <boost/bind.hpp>
-#include <boost/function.hpp>
-
-#include <Moof/Math.hh>
-
-
-namespace Mf {
-
-
-// Generic implementations of a few simple integrators. To use, you need one
-// type representing the state and another containing the derivatives of the
-// primary state variables. The state class must implement these methods:
-//
-// void getDerivative(Derivative_Type& derivative, Scalar absoluteTime);
-// void step(const Derivative_Type& derivative, Scalar deltaTime);
-//
-// Additionally, the derivative class must overload a few operators:
-//
-// Derivative_Type operator+(const Derivative_Type& other) const
-// Derivative_Type operator*(const Derivative_Type& other) const
-
-template<typename S, typename D>
-inline D evaluate(const S& state, Scalar t)
-{
- D derivative;
- state.getDerivative(derivative, t);
- return derivative;
-}
-
-template<typename S, typename D>
-inline D evaluate(S state, Scalar t, Scalar dt, const D& derivative)
-{
- state.step(derivative, dt);
- return evaluate<S,D>(state, t + dt);
-}
-
-
-template<typename S, typename D>
-inline void euler(S& state, Scalar t, Scalar dt)
-{
- D a = evaluate<S,D>(state, t);
-
- state.step(a, dt);
-}
-
-template<typename S, typename D>
-inline void rk2(S& state, Scalar t, Scalar dt)
-{
- D a = evaluate<S,D>(state, t);
- D b = evaluate<S,D>(state, t, dt * SCALAR(0.5), a);
-
- state.step(b, dt);
-}
-
-template<typename S, typename D>
-inline void rk4(S& state, Scalar t, Scalar dt)
-{
- D a = evaluate<S,D>(state, t);
- D b = evaluate<S,D>(state, t, dt * SCALAR(0.5), a);
- D c = evaluate<S,D>(state, t, dt * SCALAR(0.5), b);
- D d = evaluate<S,D>(state, t, dt, c);
-
- state.step((a + (b + c) * SCALAR(2.0) + d) * SCALAR(1.0/6.0), dt);
-}
-
-
-//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-
-template <int D = 3>
-struct LinearState
-{
- typedef cml::vector< Scalar, cml::fixed<D> > Vector;
- typedef boost::function<const Vector& (const LinearState&)> ForceFunction;
-
- // primary
-
- Vector position;
- Vector momentum;
-
- // secondary
-
- Vector velocity;
-
- // user
-
- Vector force;
- std::vector<ForceFunction> forces;
-
- // constant
-
- Scalar mass;
- Scalar inverseMass;
-
-
- void recalculateLinear()
- {
- velocity = momentum * inverseMass;
- }
-
-
- struct GravityForce
- {
- explicit GravityForce(Scalar a = -9.8)
- {
- force.zero();
- acceleration = a;
- }
-
- const Vector& operator () (const LinearState& state)
- {
- force[1] = state.mass * acceleration;
- return force;
- }
-
- private:
-
- Vector force;
- Scalar acceleration;
- };
-
-
- void init()
- {
- position.zero();
- momentum.zero();
-
- velocity.zero();
-
- force.zero();
- forces.clear();
-
- mass = SCALAR(1.0);
- inverseMass = 1.0 / mass;
- }
-
-
- struct Derivative
- {
- Vector velocity;
- Vector force;
-
- Derivative operator*(Scalar dt) const
- {
- Derivative derivative;
- derivative.velocity = dt * velocity;
- derivative.force = dt * force;
- return derivative;
- }
-
- Derivative operator+(const Derivative& other) const
- {
- Derivative derivative;
- derivative.velocity = velocity + other.velocity;
- derivative.force = force + other.force;
- return derivative;
- }
- };
-
-
- Vector getForce() const
- {
- Vector f(force);
-
- for (size_t i = 0; i < forces.size(); ++i)
- {
- f += forces[i](*this);
- }
-
- return f;
- }
-
- void getDerivative(Derivative& derivative, Scalar t) const
- {
- derivative.velocity = velocity;
- derivative.force = getForce();
- }
-
- void step(const Derivative& derivative, Scalar dt)
- {
- position += dt * derivative.velocity;
- momentum += dt * derivative.force;
- recalculateLinear();
- }
-};
-
-
-struct RotationalState2
-{
- // primary
-
- Scalar orientation;
- Scalar angularMomentum;
-
- // secondary
-
- Scalar angularVelocity;
-
- // constant
-
- Scalar inertia;
- Scalar inverseInertia;
-
-
- void recalculateRotational()
- {
- angularVelocity = angularMomentum * inertia;
- }
-
-
- struct Derivative
- {
- Scalar angularVelocity;
- Scalar torque;
- };
-
- void step(const Derivative& derivative, Scalar dt)
- {
- orientation += dt * derivative.angularVelocity;
- angularMomentum += dt * derivative.torque;
- recalculateRotational();
- }
-};
-
-struct RotationalState3
-{
- // primary
-
- Quaternion orientation;
- Vector3 angularMomentum;
-
- // secondary
-
- Quaternion spin;
- Vector3 angularVelocity;
-
- // constant
-
- Scalar inertia;
- Scalar inverseInertia;
-};
-
-
-struct State2 : public LinearState<2>, public RotationalState2
-{
- void recalculate()
- {
- recalculateLinear();
- recalculateRotational();
- }
-
- void integrate(Scalar t, Scalar dt)
- {
- rk4<LinearState<2>,LinearState<2>::Derivative>(*this, t, dt);
- }
-};
-
-struct State3 : public LinearState<3>, public RotationalState3 {};
-
-
-} // namespace Mf
-
-#endif // _MOOF_RK4_HH_
-
-/** vim: set ts=4 sw=4 tw=80: *************************************************/
-
* Interface for textures, sounds, and other types of resources.
*/
-#include <stdexcept>
#include <string>
#include <vector>
+#include <Moof/Exception.hh>
+
namespace Mf {
class Resource
{
public:
- struct Exception : public std::runtime_error
- {
- explicit Exception(const std::string& what_arg) :
- std::runtime_error(what_arg) {}
- };
virtual ~Resource();
static std::string getPath(const std::string& name);
+
+ struct Exception : public Mf::Exception
+ {
+ explicit Exception(unsigned error) :
+ Mf::Exception(error) {}
+
+ void raise()
+ {
+ throw *this;
+ }
+ };
+
private:
+
static std::vector<std::string> searchPaths_;
};
#ifndef _MOOF_RIGIDBODY_HH_
#define _MOOF_RIGIDBODY_HH_
+#include <vector>
+
+#include <boost/bind.hpp>
+#include <boost/function.hpp>
+
+#include <Moof/Entity.hh>
#include <Moof/Math.hh>
-#include <Moof/State.hh>
namespace Mf {
+template <int D = 3>
+struct LinearState
+{
+ typedef cml::vector< Scalar, cml::fixed<D> > Vector;
+ typedef boost::function<const Vector& (const LinearState&)> ForceFunction;
+
+ // primary
+
+ Vector position;
+ Vector momentum;
+
+ // secondary
+
+ Vector velocity;
+
+ // user
+
+ Vector force;
+ std::vector<ForceFunction> forces;
+
+ // constant
+
+ Scalar mass;
+ Scalar inverseMass;
+
+
+ void recalculateLinear()
+ {
+ velocity = momentum * inverseMass;
+ }
+
+
+ struct GravityForce
+ {
+ explicit GravityForce(Scalar a = -9.8)
+ {
+ force.zero();
+ acceleration = a;
+ }
+
+ const Vector& operator () (const LinearState& state)
+ {
+ force[1] = state.mass * acceleration;
+ return force;
+ }
+
+ private:
+
+ Vector force;
+ Scalar acceleration;
+ };
+
+
+ void init()
+ {
+ position.zero();
+ momentum.zero();
+
+ velocity.zero();
+
+ force.zero();
+ forces.clear();
+
+ mass = SCALAR(1.0);
+ inverseMass = 1.0 / mass;
+ }
+
+
+ struct Derivative
+ {
+ Vector velocity;
+ Vector force;
+
+ Derivative operator*(Scalar dt) const
+ {
+ Derivative derivative;
+ derivative.velocity = dt * velocity;
+ derivative.force = dt * force;
+ return derivative;
+ }
+
+ Derivative operator+(const Derivative& other) const
+ {
+ Derivative derivative;
+ derivative.velocity = velocity + other.velocity;
+ derivative.force = force + other.force;
+ return derivative;
+ }
+ };
+
+
+ Vector getForce() const
+ {
+ Vector f(force);
+
+ for (size_t i = 0; i < forces.size(); ++i)
+ {
+ f += forces[i](*this);
+ }
+
+ return f;
+ }
+
+ void getDerivative(Derivative& derivative, Scalar t) const
+ {
+ derivative.velocity = velocity;
+ derivative.force = getForce();
+ }
+
+ void step(const Derivative& derivative, Scalar dt)
+ {
+ position += dt * derivative.velocity;
+ momentum += dt * derivative.force;
+ recalculateLinear();
+ }
+};
+
+
+struct RotationalState2
+{
+ // primary
+
+ Scalar orientation;
+ Scalar angularMomentum;
+
+ // secondary
+
+ Scalar angularVelocity;
+
+ // constant
+
+ Scalar inertia;
+ Scalar inverseInertia;
+
+
+ void recalculateRotational()
+ {
+ angularVelocity = angularMomentum * inertia;
+ }
+
+
+ struct Derivative
+ {
+ Scalar angularVelocity;
+ Scalar torque;
+ };
+
+ void step(const Derivative& derivative, Scalar dt)
+ {
+ orientation += dt * derivative.angularVelocity;
+ angularMomentum += dt * derivative.torque;
+ recalculateRotational();
+ }
+};
+
+struct RotationalState3
+{
+ // primary
+
+ Quaternion orientation;
+ Vector3 angularMomentum;
+
+ // secondary
+
+ Quaternion spin;
+ Vector3 angularVelocity;
+
+ // constant
+
+ Scalar inertia;
+ Scalar inverseInertia;
+
+
+ void recalculateRotational()
+ {
+ angularVelocity = angularMomentum * inertia;
+ }
+};
+
+
+struct State2 : public LinearState<2>, public RotationalState2
+{
+ void recalculate()
+ {
+ recalculateLinear();
+ recalculateRotational();
+ }
+
+ void update(Scalar t, Scalar dt)
+ {
+ rk4<LinearState<2>,LinearState<2>::Derivative>(*this, t, dt);
+ }
+};
+
+struct State3 : public LinearState<3>, public RotationalState3
+{
+ void recalculate()
+ {
+ recalculateLinear();
+ recalculateRotational();
+ }
+
+ void update(Scalar t, Scalar dt)
+ {
+ rk4<LinearState<3>,LinearState<3>::Derivative>(*this, t, dt);
+ }
+};
+
+
+template <class T>
+inline T interpolate(const T& a, const T& b, Scalar alpha)
+{
+ return cml::lerp(a, b, alpha);
+}
+
+template <>
+inline State2 interpolate<State2>(const State2& a, const State2& b, Scalar alpha)
+{
+ State2 state(b);
+ state.position = interpolate(a.position, b.position, alpha);
+ state.momentum = interpolate(a.momentum, b.momentum, alpha);
+ state.orientation = interpolate(a.orientation, b.orientation, alpha);
+ state.angularMomentum = interpolate(a.angularMomentum, b.angularMomentum,
+ alpha);
+ return state;
+}
+
+template <>
+inline State3 interpolate<State3>(const State3& a, const State3& b, Scalar alpha)
+{
+ State3 state(b);
+ state.position = interpolate(a.position, b.position, alpha);
+ state.momentum = interpolate(a.momentum, b.momentum, alpha);
+ state.orientation = cml::slerp(a.orientation, b.orientation, alpha);
+ state.angularMomentum = interpolate(a.angularMomentum, b.angularMomentum,
+ alpha);
+ return state;
+}
+
+
+
/**
- * Interface for physical things with mass, momentum, yada yada yada.
+ * Interface for anything that can move.
*/
-template <typename T>
-class RigidBody
+template <class T>
+class RigidBody : public Entity
{
+protected:
+
+ T mState;
+ T mPrevState;
+
public:
+
virtual ~RigidBody() {}
virtual void update(Scalar t, Scalar dt)
{
- prevState_ = currentState_;
- currentState_.integrate(t, dt);
+ mPrevState = mState;
+ mState.update(t, dt);
}
- T getInterpolatedState(Scalar alpha) const
+ const T& getState() const
{
- return currentState_.interpolate(alpha, prevState_);
+ return mState;
}
-protected:
- T prevState_;
- T currentState_;
+ T getState(Scalar alpha) const
+ {
+ return interpolate(mPrevState, mState, alpha);
+ }
+
+ const T& getLastState() const
+ {
+ return mPrevState;
+ }
};
+typedef RigidBody<State2> RigidBody2;
+typedef RigidBody<State3> RigidBody3;
+
} // namespace Mf
/** vim: set ts=4 sw=4 tw=80: *************************************************/
-
Script() :
- state_(luaL_newstate())
+ mState(luaL_newstate())
{
- lua_pushlightuserdata(state_, this);
- lua_setfield(state_, LUA_REGISTRYINDEX, "_script_obj");
+ lua_pushlightuserdata(mState, this);
+ lua_setfield(mState, LUA_REGISTRYINDEX, "_script_obj");
}
~Script()
{
- if (isMainThread_) lua_close(state_);
+ if (mIsMainThread) lua_close(mState);
}
void importStandardLibraries()
{
- luaL_openlibs(state_);
+ luaL_openlibs(mState);
}
void importFunction(const std::string& name, const Function& function)
{
push(function);
- lua_setglobal(state_, name.c_str());
+ lua_setglobal(mState, name.c_str());
}
STATUS doString(const std::string& commands)
{
- return (STATUS)luaL_dostring(state_, commands.c_str());
+ return (STATUS)luaL_dostring(mState, commands.c_str());
}
STATUS doFile(const std::string& file)
{
- return (STATUS)luaL_dofile(state_, file.c_str());
+ return (STATUS)luaL_dofile(mState, file.c_str());
}
Script pushNewThread()
{
- return Script(state_);
+ return Script(mState);
}
void pushThread()
{
- lua_pushthread(state_);
+ lua_pushthread(mState);
}
STATUS resume(int nargs)
{
- return (STATUS)lua_resume(state_, nargs);
+ return (STATUS)lua_resume(mState, nargs);
}
STATUS getStatus() const
{
- return (STATUS)lua_status(state_);
+ return (STATUS)lua_status(mState);
}
int yield(int results)
{
- return lua_yield(state_, results);
+ return lua_yield(mState, results);
}
bool isMainThread() const
{
- return isMainThread_;
+ return mIsMainThread;
}
void throwError()
{
- lua_error(state_);
+ lua_error(mState);
}
Value getGlobalTable() const
{
- return Value(state_, GLOBALS);
+ return Value(mState, GLOBALS);
}
Value getRegistryTable() const
{
- return Value(state_, REGISTRY);
+ return Value(mState, REGISTRY);
}
Value getEnvironmentTable() const
{
- return Value(state_, ENVIRONMENT);
+ return Value(mState, ENVIRONMENT);
}
Value getTop() const
{
- return Value(state_, lua_gettop(state_));
+ return Value(mState, lua_gettop(mState));
}
/**
int getSize() const
{
- return lua_gettop(state_);
+ return lua_gettop(mState);
}
void setSize(int size)
{
- lua_settop(state_, size);
+ lua_settop(mState, size);
}
void clear()
bool checkStack(int extra)
{
- return (bool)lua_checkstack(state_, extra);
+ return (bool)lua_checkstack(mState, extra);
}
void concat(int n)
{
- lua_concat(state_, n);
+ lua_concat(mState, n);
}
template <typename T>
void push(T value)
{
- lua_pushinteger(state_, lua_Integer(value));
+ lua_pushinteger(mState, lua_Integer(value));
}
void push(bool value)
{
- lua_pushboolean(state_, int(value));
+ lua_pushboolean(mState, int(value));
}
void push(float value)
{
- lua_pushnumber(state_, (lua_Number)value);
+ lua_pushnumber(mState, (lua_Number)value);
}
void push(double value)
{
- lua_pushnumber(state_, (lua_Number)value);
+ lua_pushnumber(mState, (lua_Number)value);
}
void push(const std::string& value)
{
- lua_pushlstring(state_, value.c_str(), value.length());
+ lua_pushlstring(mState, value.c_str(), value.length());
}
void push(const char* value)
{
- lua_pushstring(state_, value);
+ lua_pushstring(mState, value);
}
void push(const char* value, size_t length)
{
- lua_pushlstring(state_, value, length);
+ lua_pushlstring(mState, value, length);
}
void push(const Function& function)
{
- functions_.push_back(function);
+ mFunctions.push_back(function);
- lua_pushlightuserdata(state_, (void*)&functions_.back());
- lua_pushcclosure(state_, dispatchCall, 1);
+ lua_pushlightuserdata(mState, (void*)&mFunctions.back());
+ lua_pushcclosure(mState, dispatchCall, 1);
}
void push(void* data)
{
- lua_pushlightuserdata(state_, data);
+ lua_pushlightuserdata(mState, data);
}
void pushNil()
{
- lua_pushnil(state_);
+ lua_pushnil(mState);
}
void pushFromThread(Script& thread, int n)
{
- lua_xmove(thread.state_, state_, n);
+ lua_xmove(thread.mState, mState, n);
}
STATUS pushCode(const std::string& filename)
{
- return (STATUS)luaL_loadfile(state_, filename.c_str());
+ return (STATUS)luaL_loadfile(mState, filename.c_str());
}
STATUS pushCode(const std::string& name, const char* buffer, size_t size)
{
- return (STATUS)luaL_loadbuffer(state_, buffer, size, name.c_str());
+ return (STATUS)luaL_loadbuffer(mState, buffer, size, name.c_str());
}
void* pushNewData(size_t size)
{
- return lua_newuserdata(state_, size);
+ return lua_newuserdata(mState, size);
}
void pushNewTable()
{
- lua_newtable(state_);
+ lua_newtable(mState);
}
STATUS call(int nargs, int nresults = LUA_MULTRET)
{
- return (STATUS)lua_pcall(state_, nargs, nresults, 0);
+ return (STATUS)lua_pcall(mState, nargs, nresults, 0);
}
void pop(int n = 1)
{
- lua_pop(state_, n);
+ lua_pop(mState, n);
}
Value operator [] (int index) const
{
- return Value(state_, index);
+ return Value(mState, index);
}
void get(const std::string& field, int index = GLOBALS) const
{
- lua_getfield(state_, index, field.c_str());
+ lua_getfield(mState, index, field.c_str());
}
void set(const std::string& field, int index = GLOBALS)
{
- lua_setfield(state_, index, field.c_str());
+ lua_setfield(mState, index, field.c_str());
}
void collectAll()
{
- lua_gc(state_, LUA_GCCOLLECT, 0);
+ lua_gc(mState, LUA_GCCOLLECT, 0);
}
void stopCollector()
{
- lua_gc(state_, LUA_GCSTOP, 0);
+ lua_gc(mState, LUA_GCSTOP, 0);
}
void restartCollector()
{
- lua_gc(state_, LUA_GCRESTART, 0);
+ lua_gc(mState, LUA_GCRESTART, 0);
}
int getUsedMemory() const
{
// in kilobytes
- return lua_gc(state_, LUA_GCCOUNT, 0);
+ return lua_gc(mState, LUA_GCCOUNT, 0);
}
void collectStep(int step)
{
- lua_gc(state_, LUA_GCSTEP, step);
+ lua_gc(mState, LUA_GCSTEP, step);
}
void tuneCollector(int pause, int step)
{
- lua_gc(state_, LUA_GCSETPAUSE, pause);
- lua_gc(state_, LUA_GCSETSTEPMUL, step);
+ lua_gc(mState, LUA_GCSETPAUSE, pause);
+ lua_gc(mState, LUA_GCSETSTEPMUL, step);
}
private:
Script(lua_State* state) :
- state_(lua_newthread(state)),
- isMainThread_(false) {}
+ mState(lua_newthread(state)),
+ mIsMainThread(false) {}
static int dispatchCall(lua_State* state)
{
return (*function)(*script);
}
- lua_State* state_;
- bool isMainThread_;
- std::list<Function> functions_;
+ lua_State* mState;
+ bool mIsMainThread;
+ std::list<Function> mFunctions;
};
{
for (int i = 1; i < argc; ++i)
{
- script_.doString(argv[i]);
+ mScript.doString(argv[i]);
}
}
boost::replace_all(path, "$HOME", home);
}
- if (script_.doFile(path) != Script::SUCCESS)
+ if (mScript.doFile(path) != Script::SUCCESS)
{
std::string str;
- script_[-1].get(str);
+ mScript[-1].get(str);
logScript("%s", str.c_str());
- script_.clear();
+ mScript.clear();
}
}
}
class Settings
{
public:
+
Settings() :
- globals_(script_.getGlobalTable()),
- top_(script_[-1])
+ mGlobals(mScript.getGlobalTable()),
+ mTop(mScript[-1])
{
- importLogScript(script_);
+ importLogScript(mScript);
}
// get global instance
bool get(const std::string& key, T& value);
private:
- Script script_;
- Script::Value globals_, top_;
+
+ Script mScript;
+ Script::Value mGlobals, mTop;
};
std::vector<std::string> fields;
boost::split(fields, key, boost::is_any_of("."));
- globals_.pushCopy();
+ mGlobals.pushCopy();
std::vector<std::string>::iterator it;
for (it = fields.begin(); it != fields.end(); ++it)
{
- if (top_.isTable())
+ if (mTop.isTable())
{
- top_.pushField(*it);
+ mTop.pushField(*it);
}
else
{
- script_.clear();
+ mScript.clear();
return false;
}
}
- bool got = top_.get(value);
- script_.clear();
+ bool got = mTop.get(value);
+ mScript.clear();
return got;
}
namespace Mf {
-struct Sound::Impl
+class Sound::Impl
{
+public:
static ALenum getAudioFormat(const vorbis_info* audioInfo)
{
else return AL_FORMAT_STEREO16;
}
+
class Buffer;
typedef boost::shared_ptr<Buffer> BufferP;
class Buffer : public Mippleton<Buffer>
{
- OggVorbis_File oggStream;
- ALenum audioFormat;
- ALsizei audioFreq;
- std::vector<ALuint> objects;
+ OggVorbis_File mOggStream;
+ ALenum mFormat;
+ ALsizei mFreq;
+ std::vector<ALuint> mObjects;
public:
Buffer(const std::string& name) :
Mippleton<Buffer>(name)
{
- oggStream.datasource = 0;
+ mOggStream.datasource = 0;
openFile();
}
~Buffer()
{
- while (!objects.empty())
+ while (!mObjects.empty())
{
- alDeleteBuffers(1, &objects.back());
- objects.pop_back();
+ alDeleteBuffers(1, &mObjects.back());
+ mObjects.pop_back();
}
- if (oggStream.datasource)
+ if (mOggStream.datasource)
{
- ov_clear(&oggStream);
+ ov_clear(&mOggStream);
}
}
void openFile()
{
- if (oggStream.datasource)
+ if (mOggStream.datasource)
{
- ov_clear(&oggStream);
- oggStream.datasource = 0;
+ ov_clear(&mOggStream);
+ mOggStream.datasource = 0;
}
std::string filePath = Sound::getPath(getName());
- int result = ov_fopen((char*)filePath.c_str(), &oggStream);
+ int result = ov_fopen((char*)filePath.c_str(), &mOggStream);
if (result < 0)
{
throw Exception(Exception::BAD_AUDIO_FORMAT);
}
- vorbis_info* vorbisInfo = ov_info(&oggStream, -1);
- audioFormat = getAudioFormat(vorbisInfo);
- audioFreq = vorbisInfo->rate;
+ vorbis_info* vorbisInfo = ov_info(&mOggStream, -1);
+ mFormat = getAudioFormat(vorbisInfo);
+ mFreq = vorbisInfo->rate;
logDebug(" channels: %d", vorbisInfo->channels);
logDebug(" frequency: %d", vorbisInfo->rate);
void loadAll(ALuint source)
{
- if (!oggStream.datasource) openFile();
- if (!oggStream.datasource) return;
+ if (!mOggStream.datasource) openFile();
+ if (!mOggStream.datasource) return;
char data[BUFFER_SIZE];
int size = 0;
for (;;)
{
int section;
- int result = ov_read(&oggStream, data + size,
+ int result = ov_read(&mOggStream, data + size,
BUFFER_SIZE - size, 0, 2, 1, §ion);
if (result > 0)
ALuint obj;
alGenBuffers(1, &obj);
- alBufferData(obj, audioFormat, data, size, audioFreq);
+ alBufferData(obj, mFormat, data, size, mFreq);
- objects.push_back(obj);
+ mObjects.push_back(obj);
alSourcei(source, AL_BUFFER, obj);
// don't need this anymore
- ov_clear(&oggStream);
- oggStream.datasource = 0;
+ ov_clear(&mOggStream);
+ mOggStream.datasource = 0;
}
void beginStream(ALuint source, int nBuffers = 8)
{
- if (!oggStream.datasource) openFile();
- if (!oggStream.datasource) return;
+ if (!mOggStream.datasource) openFile();
+ if (!mOggStream.datasource) return;
ALuint objs[nBuffers];
alGenBuffers(nBuffers, objs);
for (int i = 0; i < nBuffers; ++i)
{
- objects.push_back(objs[i]);
+ mObjects.push_back(objs[i]);
stream(objs[i]);
}
StreamStatus stream(ALuint buffer)
{
std::vector<ALuint>::iterator it =
- std::find(objects.begin(), objects.end(), buffer);
+ std::find(mObjects.begin(), mObjects.end(), buffer);
// that buffer doesn't belong to us
- if (it == objects.end()) return STREAM_WRONG;
+ if (it == mObjects.end()) return STREAM_WRONG;
char data[BUFFER_SIZE];
int size = 0;
while (size < BUFFER_SIZE)
{
int section;
- int result = ov_read(&oggStream, data + size,
+ int result = ov_read(&mOggStream, data + size,
BUFFER_SIZE - size, 0, 2, 1, §ion);
if (result > 0)
if (size == 0) return STREAM_EOF;
- alBufferData(buffer, audioFormat, data, size, audioFreq);
+ alBufferData(buffer, mFormat, data, size, mFreq);
return STREAM_OK;
}
inline void rewind()
{
- if (!oggStream.datasource) openFile();
- else ov_raw_seek(&oggStream, 0);
+ if (!mOggStream.datasource) openFile();
+ else ov_raw_seek(&mOggStream, 0);
}
// clear any openal errors
alGetError();
- while (!objects.empty())
+ while (!mObjects.empty())
{
- ALuint buffer = objects.back();
+ ALuint buffer = mObjects.back();
alDeleteBuffers(1, &buffer);
// if an error occured, the buffer was not deleted because it's
// still in use by some source
if (alGetError() != AL_NO_ERROR) return false;
- objects.pop_back();
+ mObjects.pop_back();
}
return true;
Impl(const std::string& name) :
- buffer_(Buffer::getInstance(name)),
- playing_(false),
- looping_(false)
+ mBuffer(Buffer::getInstance(name)),
+ mIsPlaying(false),
+ mIsLooping(false)
{
ALfloat zero[] = {0.0f, 0.0f, 0.0f};
- alGenSources(1, &source_);
+ alGenSources(1, &mSource);
- alSourcef(source_, AL_PITCH, 1.0f);
- alSourcef(source_, AL_GAIN, 1.0f);
- alSourcefv(source_, AL_POSITION, zero);
- alSourcefv(source_, AL_VELOCITY, zero);
+ alSourcef(mSource, AL_PITCH, 1.0f);
+ alSourcef(mSource, AL_GAIN, 1.0f);
+ alSourcefv(mSource, AL_POSITION, zero);
+ alSourcefv(mSource, AL_VELOCITY, zero);
}
~Impl()
{
- alDeleteSources(1, &source_);
+ alDeleteSources(1, &mSource);
}
void play()
{
ALenum type;
- alGetSourcei(source_, AL_SOURCE_TYPE, &type);
+ alGetSourcei(mSource, AL_SOURCE_TYPE, &type);
if (type != AL_STATIC)
{
- buffer_->loadAll(source_);
+ mBuffer->loadAll(mSource);
}
- alSourcei(source_, AL_LOOPING, looping_);
- alSourcePlay(source_);
- playing_ = true;
+ alSourcei(mSource, AL_LOOPING, mIsLooping);
+ alSourcePlay(mSource);
+ mIsPlaying = true;
}
void stream()
{
ALenum type;
- alGetSourcei(source_, AL_SOURCE_TYPE, &type);
+ alGetSourcei(mSource, AL_SOURCE_TYPE, &type);
- alSourcei(source_, AL_BUFFER, AL_NONE);
- buffer_->rewind();
- buffer_->beginStream(source_);
+ alSourcei(mSource, AL_BUFFER, AL_NONE);
+ mBuffer->rewind();
+ mBuffer->beginStream(mSource);
- alSourcei(source_, AL_LOOPING, AL_FALSE);
- alSourcePlay(source_);
- playing_ = true;
+ alSourcei(mSource, AL_LOOPING, AL_FALSE);
+ alSourcePlay(mSource);
+ mIsPlaying = true;
- streamTimer.init(boost::bind(&Impl::streamUpdate, this, _1, _2), 1.0,
+ mStreamTimer.init(boost::bind(&Impl::streamUpdate, this, _1, _2), 1.0,
Timer::REPEAT);
}
{
ALint finished = 0;
- alGetSourcei(source_, AL_BUFFERS_PROCESSED, &finished);
+ alGetSourcei(mSource, AL_BUFFERS_PROCESSED, &finished);
while (finished-- > 0)
{
ALuint buffer;
- alSourceUnqueueBuffers(source_, 1, &buffer);
+ alSourceUnqueueBuffers(mSource, 1, &buffer);
- Buffer::StreamStatus status = buffer_->stream(buffer);
+ Buffer::StreamStatus status = mBuffer->stream(buffer);
if (status == Buffer::STREAM_OK)
{
- alSourceQueueBuffers(source_, 1, &buffer);
+ alSourceQueueBuffers(mSource, 1, &buffer);
}
else if (status == Buffer::STREAM_EOF)
{
- if (!queue_.empty())
+ if (!mQueue.empty())
{
// begin the next buffer in the queue
- expired_.push_back(buffer_);
- buffer_ = queue_.front();
- queue_.pop();
- buffer_->beginStream(source_, 1);
+ mExpired.push_back(mBuffer);
+ mBuffer = mQueue.front();
+ mQueue.pop();
+ mBuffer->beginStream(mSource, 1);
}
- else if (looping_)
+ else if (mIsLooping)
{
// restart from the beginning
- buffer_->rewind();
- buffer_->stream(buffer);
- alSourceQueueBuffers(source_, 1, &buffer);
+ mBuffer->rewind();
+ mBuffer->stream(buffer);
+ alSourceQueueBuffers(mSource, 1, &buffer);
}
}
else if (status == Buffer::STREAM_WRONG)
{
clear();
- buffer_->beginStream(source_, 1);
+ mBuffer->beginStream(mSource, 1);
}
}
ALenum state;
- alGetSourcei(source_, AL_SOURCE_STATE, &state);
+ alGetSourcei(mSource, AL_SOURCE_STATE, &state);
// restart playing if we're stopped but supposed to be playing... this
// means we didn't queue enough and the audio skipped
- if (playing_ && state != AL_PLAYING)
+ if (mIsPlaying && state != AL_PLAYING)
{
- alSourcePlay(source_);
+ alSourcePlay(mSource);
}
}
{
// try to remove expired buffers
std::vector<BufferP>::iterator it;
- for (it = expired_.end() - 1; it >= expired_.begin(); --it)
+ for (it = mExpired.end() - 1; it >= mExpired.begin(); --it)
{
- if ((*it)->clear()) expired_.erase(it);
+ if ((*it)->clear()) mExpired.erase(it);
}
}
void stop()
{
- alSourceStop(source_);
- playing_ = false;
+ alSourceStop(mSource);
+ mIsPlaying = false;
}
inline void pause()
{
- alSourcePause(source_);
- playing_ = false;
+ alSourcePause(mSource);
+ mIsPlaying = false;
}
inline void resume()
{
- alSourcePlay(source_);
- playing_ = true;
+ alSourcePlay(mSource);
+ mIsPlaying = true;
}
{
bool playing = isPlaying();
ALenum type;
- alGetSourcei(source_, AL_SOURCE_TYPE, &type);
+ alGetSourcei(mSource, AL_SOURCE_TYPE, &type);
stop();
- //alSourcei(source_, AL_BUFFER, AL_NONE);
- buffer_ = Buffer::getInstance(name);
+ //alSourcei(mSource, AL_BUFFER, AL_NONE);
+ mBuffer = Buffer::getInstance(name);
if (type == AL_STREAMING)
{
inline void enqueue(const std::string& name)
{
BufferP buffer = Buffer::getInstance(name);
- queue_.push(buffer);
+ mQueue.push(buffer);
}
inline bool isPlaying() const
{
- if (playing_) return true;
+ if (mIsPlaying) return true;
ALenum state;
- alGetSourcei(source_, AL_SOURCE_STATE, &state);
+ alGetSourcei(mSource, AL_SOURCE_STATE, &state);
return state == AL_PLAYING;
}
inline void setLooping(bool looping)
{
- looping_ = looping;
+ mIsLooping = looping;
ALenum type;
- alGetSourcei(source_, AL_SOURCE_TYPE, &type);
+ alGetSourcei(mSource, AL_SOURCE_TYPE, &type);
if (type != AL_STREAMING)
{
- alSourcei(source_, AL_LOOPING, looping_);
+ alSourcei(mSource, AL_LOOPING, mIsLooping);
}
}
- ALuint source_;
- BufferP buffer_;
+ ALuint mSource;
+ BufferP mBuffer;
- bool playing_;
- bool looping_;
+ bool mIsPlaying;
+ bool mIsLooping;
- std::queue<BufferP> queue_;
- std::vector<BufferP> expired_;
+ std::queue<BufferP> mQueue;
+ std::vector<BufferP> mExpired;
- Timer streamTimer;
+ Timer mStreamTimer;
void streamUpdate(Timer& timer, Scalar t)
{
Sound::Sound(const std::string& name) :
// pass through
- impl_(new Sound::Impl(name)) {}
+ mImpl(new Sound::Impl(name)) {}
void Sound::play()
{
// pass through
- impl_->play();
+ mImpl->play();
}
void Sound::stream()
{
// pass through
- impl_->stream();
+ mImpl->stream();
}
void Sound::stop()
{
// pass through
- impl_->stop();
+ mImpl->stop();
}
void Sound::pause()
{
// pass through
- impl_->pause();
+ mImpl->pause();
}
void Sound::resume()
{
// pass through
- impl_->resume();
+ mImpl->resume();
}
void Sound::toggle()
{
- if (impl_->playing_) pause();
+ if (mImpl->mIsPlaying) pause();
else resume();
}
void Sound::setSample(const std::string& name)
{
// pass through
- impl_->setSample(name);
+ mImpl->setSample(name);
}
void Sound::enqueue(const std::string& name)
{
// pass through
- impl_->enqueue(name);
+ mImpl->enqueue(name);
}
bool Sound::isPlaying() const
{
// pass through
- return impl_->isPlaying();
+ return mImpl->isPlaying();
}
void Sound::setPosition(const Vector3& position)
{
float p[3] = {position[0], position[1], position[2]};
- alSourcefv(impl_->source_, AL_POSITION, p);
+ alSourcefv(mImpl->mSource, AL_POSITION, p);
}
void Sound::setVelocity(const Vector3& velocity)
{
float v[3] = {velocity[0], velocity[1], velocity[2]};
- alSourcefv(impl_->source_, AL_VELOCITY, v);
+ alSourcefv(mImpl->mSource, AL_VELOCITY, v);
}
void Sound::setGain(Scalar gain)
{
- alSourcef(impl_->source_, AL_GAIN, float(gain));
+ alSourcef(mImpl->mSource, AL_GAIN, float(gain));
}
void Sound::setPitch(Scalar pitch)
{
- alSourcef(impl_->source_, AL_PITCH, float(pitch));
+ alSourcef(mImpl->mSource, AL_PITCH, float(pitch));
}
void Sound::setLooping(bool looping)
{
// pass through
- impl_->setLooping(looping);
+ mImpl->setLooping(looping);
}
class Sound : public Resource
{
class Impl;
- boost::shared_ptr<Impl> impl_;
+ boost::shared_ptr<Impl> mImpl;
public:
void play();
void stream();
- // TODO - i don't like how there are two different methods that essentially
- // do the same thing; the API should be exactly the same for both types of
- // sounds; need a different way to distinguish how to handle the sound
+ // TODO - this API sucks
void stop();
void pause();
void unloadFromGL()
{
- if (object_)
+ if (mObject)
{
- if (object_ == globalObject_)
+ if (mObject == globalObject_)
{
globalObject_ = 0;
}
- glDeleteTextures(1, &object_);
- object_ = 0;
+ glDeleteTextures(1, &mObject);
+ mObject = 0;
}
}
void contextRecreated(const Notification* note)
{
- object_ = globalObject_ = 0;
+ mObject = globalObject_ = 0;
uploadToGL();
}
explicit Impl(const std::string& name) :
Mippleton<Impl>(name),
- surface_(0),
- width_(0),
- height_(0),
- mode_(0),
- minFilter_(GL_NEAREST),
- magFilter_(GL_NEAREST),
- wrapS_(GL_CLAMP),
- wrapT_(GL_CLAMP),
- object_(0)
+ mContext(0),
+ mWidth(0),
+ mHeight(0),
+ mMode(0),
+ mMinFilter(GL_NEAREST),
+ mMagFilter(GL_NEAREST),
+ mWrapS(GL_CLAMP),
+ mWrapT(GL_CLAMP),
+ mObject(0)
{
loadFromFile();
~Impl()
{
- if (surface_)
+ if (mContext)
{
- SDL_FreeSurface(surface_);
+ SDL_FreeSurface(mContext);
}
unloadFromGL();
if (temp->format->BytesPerPixel == 3)
{
- mode_ = GL_RGB;
+ mMode = GL_RGB;
}
else if (temp->format->BytesPerPixel == 4)
{
- mode_ = GL_RGBA;
+ mMode = GL_RGBA;
}
else
{
throw Exception(Exception::BAD_IMAGE_FORMAT);
}
- width_ = temp->w;
- height_ = temp->h;
+ mWidth = temp->w;
+ mHeight = temp->h;
- surface_ = temp;
+ mContext = temp;
}
void uploadToGL()
{
- if (object_)
+ if (mObject)
{
// already loaded
return;
}
- if (!surface_) loadFromFile();
+ if (!mContext) loadFromFile();
- glGenTextures(1, &object_);
- glBindTexture(GL_TEXTURE_2D, object_);
+ glGenTextures(1, &mObject);
+ glBindTexture(GL_TEXTURE_2D, mObject);
glTexImage2D
(
GL_TEXTURE_2D,
0,
- mode_,
- surface_->w,
- surface_->h,
+ mMode,
+ mContext->w,
+ mContext->h,
0,
- mode_,
+ mMode,
GL_UNSIGNED_BYTE,
- surface_->pixels
+ mContext->pixels
);
setProperties();
- SDL_FreeSurface(surface_);
- surface_ = 0;
+ SDL_FreeSurface(mContext);
+ mContext = 0;
}
void setProperties()
{
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter_);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter_);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS_);
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT_);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, mMinFilter);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mMagFilter);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, mWrapS);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, mWrapT);
}
inline void setMinFilter(GLuint filter)
{
bind();
- minFilter_ = filter;
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter_);
+ mMinFilter = filter;
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, mMinFilter);
}
inline void setMagFilter(GLuint filter)
{
bind();
- magFilter_ = filter;
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter_);
+ mMagFilter = filter;
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mMagFilter);
}
inline void setWrapS(GLuint wrap)
{
bind();
- wrapS_ = wrap;
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS_);
+ mWrapS = wrap;
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, mWrapS);
}
inline void setWrapT(GLuint wrap)
{
bind();
- wrapT_ = wrap;
- glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT_);
+ mWrapT = wrap;
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, mWrapT);
}
inline void bind()
{
- if (object_ == 0)
+ if (mObject == 0)
{
uploadToGL();
}
- if (object_ != globalObject_)
+ if (mObject != globalObject_)
{
- glBindTexture(GL_TEXTURE_2D, object_);
- globalObject_ = object_;
+ glBindTexture(GL_TEXTURE_2D, mObject);
+ globalObject_ = mObject;
}
}
- SDL_Surface* surface_;
- unsigned width_; ///< Horizontal dimension of the image.
- unsigned height_; ///< Vertical dimension.
+ SDL_Surface* mContext;
+ unsigned mWidth; ///< Horizontal dimension of the image.
+ unsigned mHeight; ///< Vertical dimension.
- GLuint mode_; ///< Depth of the image, GL_RGB or GL_RGBA.
- GLuint minFilter_; ///< Minifcation filter.
- GLuint magFilter_; ///< Magnification filter.
- GLuint wrapS_; ///< Wrapping behavior horizontally.
- GLuint wrapT_; ///< Wrapping behavior vertically.
+ GLuint mMode; ///< Depth of the image, GL_RGB or GL_RGBA.
+ GLuint mMinFilter; ///< Minifcation filter.
+ GLuint mMagFilter; ///< Magnification filter.
+ GLuint mWrapS; ///< Wrapping behavior horizontally.
+ GLuint mWrapT; ///< Wrapping behavior vertically.
- GLuint object_; ///< GL texture handle.
+ GLuint mObject; ///< GL texture handle.
static GLuint globalObject_; ///< Global GL texture handle.
};
Texture::Texture(const std::string& name) :
// pass through
- impl_(Texture::Impl::getInstance(name)) {}
+ mImpl(Texture::Impl::getInstance(name)) {}
/**
void Texture::bind() const
{
// pass through
- impl_->bind();
+ mImpl->bind();
}
GLuint Texture::getObject() const
{
// pass through
- return impl_->object_;
+ return mImpl->mObject;
}
unsigned Texture::getWidth() const
{
// pass through
- return impl_->width_;
+ return mImpl->mWidth;
}
unsigned Texture::getHeight() const
{
// pass through
- return impl_->height_;
+ return mImpl->mHeight;
}
void Texture::setMinFilter(GLuint filter)
{
// pass through
- impl_->setMinFilter(filter);
+ mImpl->setMinFilter(filter);
}
void Texture::setMagFilter(GLuint filter)
{
// pass through
- impl_->setMagFilter(filter);
+ mImpl->setMagFilter(filter);
}
void Texture::setWrapS(GLuint wrap)
{
// pass through
- impl_->setWrapS(wrap);
+ mImpl->setWrapS(wrap);
}
void Texture::setWrapT(GLuint wrap)
{
// pass through
- impl_->setWrapT(wrap);
+ mImpl->setWrapT(wrap);
}
class Texture : public Resource
{
class Impl;
- boost::shared_ptr<Impl> impl_;
+ boost::shared_ptr<Impl> mImpl;
public:
friend class Condition;
public:
+
Mutex()
{
- mutex_ = SDL_CreateMutex();
+ mMutex = SDL_CreateMutex();
}
~Mutex()
{
- SDL_DestroyMutex(mutex_);
+ SDL_DestroyMutex(mMutex);
}
bool acquireLock()
{
- return (SDL_LockMutex(mutex_) == 0);
+ return (SDL_LockMutex(mMutex) == 0);
}
bool releaseLock()
{
- return (SDL_UnlockMutex(mutex_) == 0);
+ return (SDL_UnlockMutex(mMutex) == 0);
}
class Lock
friend class Condition;
public:
+
Lock(Mutex& mutex)
{
- mutex_ = &mutex;
- isLocked_ = false;
+ mMutex = &mutex;
+ mIsLocked = false;
}
~Lock()
{
- if (isLocked_) release();
+ if (mIsLocked) release();
}
bool acquire()
{
- return (isLocked_ = mutex_->acquireLock());
+ return (mIsLocked = mMutex->acquireLock());
}
bool release()
{
- return mutex_->releaseLock();
- isLocked_ = false;
+ return mMutex->releaseLock();
+ mIsLocked = false;
}
bool isLocked() const
{
- return isLocked_;
+ return mIsLocked;
}
protected:
- Mutex* mutex_;
- bool isLocked_;
+
+ Mutex* mMutex;
+ bool mIsLocked;
};
class ScopedLock : public Lock
{
public:
+
ScopedLock(Mutex& mutex) :
Lock(mutex)
{
};
private:
- SDL_mutex* mutex_;
+
+ SDL_mutex* mMutex;
};
class Condition
{
public:
+
Condition()
{
condition_ = SDL_CreateCond();
bool wait(Mutex::Lock& lock)
{
- return (SDL_CondWait(condition_, lock.mutex_->mutex_) == 0);
+ return (SDL_CondWait(condition_, lock.mMutex->mMutex) == 0);
}
bool wait(Mutex::Lock& lock, unsigned ms)
{
// TODO for consistency, this function should take seconds
- return (SDL_CondWaitTimeout(condition_, lock.mutex_->mutex_, ms) == 0);
+ return (SDL_CondWaitTimeout(condition_, lock.mMutex->mMutex, ms) == 0);
}
bool notify()
}
private:
+
SDL_cond* condition_;
};
class Semaphore
{
public:
+
Semaphore(unsigned int value)
{
semaphore_ = SDL_CreateSemaphore(value);
class Lock
{
public:
+
Lock(Semaphore& semaphore)
{
semaphore_ = &semaphore;
- isLocked_ = false;
+ mIsLocked = false;
}
~Lock()
{
- if (isLocked_) release();
+ if (mIsLocked) release();
}
bool acquire()
{
- return (isLocked_ = semaphore_->acquireLock());
+ return (mIsLocked = semaphore_->acquireLock());
}
bool release()
{
- return semaphore_->releaseLock(); isLocked_ = false;
+ return semaphore_->releaseLock(); mIsLocked = false;
}
bool isLocked() const
{
- return isLocked_;
+ return mIsLocked;
}
protected:
+
Semaphore* semaphore_;
- bool isLocked_;
+ bool mIsLocked;
};
class ScopedLock : public Lock
{
public:
+
ScopedLock(Semaphore& semaphore) :
Lock(semaphore)
{
};
private:
+
SDL_sem* semaphore_;
};
{
invalidate();
- mode_ = mode;
+ mMode = mode;
- if (mode_ != INVALID)
+ if (mMode != INVALID)
{
- function_ = function;
+ mFunction = function;
if (mode == ABSOLUTEE)
{
- absolute_ = seconds;
+ mAbsolute = seconds;
}
else
{
- absolute_ = seconds - getTicks();
- interval_ = seconds;
+ mAbsolute = seconds - getTicks();
+ mInterval = seconds;
}
- id_ = getNewID();
- timers_.insert(std::pair<unsigned,Timer&>(id_, *this));
+ mId = getNewID();
+ timers_.insert(std::pair<unsigned,Timer&>(mId, *this));
- if (absolute_ < nextFire_) nextFire_ = absolute_;
+ if (mAbsolute < nextFire_) nextFire_ = mAbsolute;
}
}
bool Timer::isValid() const
{
- return mode_ != INVALID;
+ return mMode != INVALID;
}
void Timer::invalidate()
{
- if (mode_ != INVALID)
+ if (mMode != INVALID)
{
- timers_.erase(id_);
- mode_ = INVALID;
+ timers_.erase(mId);
+ mMode = INVALID;
- if (isEqual(absolute_, nextFire_)) nextFire_ = findNextFire();
+ if (isEqual(mAbsolute, nextFire_)) nextFire_ = findNextFire();
}
}
{
Scalar t = getTicks();
- if (function_) function_(*this, t);
+ if (mFunction) mFunction(*this, t);
if (isRepeating())
{
- Scalar absolute = absolute_;
+ Scalar absolute = mAbsolute;
- if (isEqual(absolute_, t, 1.0)) absolute_ += interval_;
- else absolute_ = interval_ + t;
+ if (isEqual(mAbsolute, t, 1.0)) mAbsolute += mInterval;
+ else mAbsolute = mInterval + t;
if (isEqual(absolute, nextFire_)) nextFire_ = findNextFire();
}
for (it = timers_.begin(); it != timers_.end(); ++it)
{
- Scalar absolute = (*it).second.absolute_;
+ Scalar absolute = (*it).second.mAbsolute;
if (absolute < nextFire) nextFire = absolute;
}
Scalar Timer::getSecondsRemaining() const
{
- return absolute_ - getTicks();
+ return mAbsolute - getTicks();
}
bool Timer::isExpired() const
bool Timer::isRepeating() const
{
- return mode_ == REPEAT;
+ return mMode == REPEAT;
}
Timer() :
- mode_(INVALID) {}
+ mMode(INVALID) {}
Timer(const Function& function, Scalar seconds, Mode mode = NORMAL)
{
static unsigned getNewID();
static Scalar findNextFire();
- Function function_;
- Mode mode_;
- Scalar absolute_;
- Scalar interval_;
- unsigned id_;
+ Function mFunction;
+ Mode mMode;
+ Scalar mAbsolute;
+ Scalar mInterval;
+ unsigned mId;
static Scalar nextFire_;
static std::map<unsigned,Timer&> timers_;
template <typename T>
class Transition : public Layer
{
- LayerP to;
- LayerP from;
+ LayerP mTo;
+ LayerP mFrom;
- T interpolator;
+ T mInterp;
- Engine* engine;
+ Engine* mEngine;
public:
Transition(LayerP t, LayerP f, const T& interp) :
- to(t),
- from(f),
- interpolator(interp),
- engine(0) {}
+ mTo(t),
+ mFrom(f),
+ mInterp(interp),
+ mEngine(0) {}
typedef boost::shared_ptr<Transition> Ptr;
}
- void pushed(Engine& e)
+ void pushed(Engine& engine)
{
- engine = &e;
+ mEngine = &engine;
}
- void popped(Engine& e)
+ void popped(Engine& engine)
{
- if (to) e.push(to);
+ if (mTo) engine.push(mTo);
}
void update(Scalar t, Scalar dt)
{
- interpolator.update(t, dt);
+ mInterp.update(t, dt);
- if (from) from->update(t, dt);
- if (to) to->update(t, dt);
+ if (mFrom) mFrom->update(t, dt);
+ if (mTo) mTo->update(t, dt);
- if (interpolator.isDone())
+ if (mInterp.isDone())
{
// to should /replace/ this
- engine->pop(this);
+ mEngine->pop(this);
}
}
void draw(Scalar alpha) const
{
- Scalar a = interpolator.getState(alpha);
+ Scalar a = mInterp.getState(alpha);
logInfo("draw state: %f", a);
//glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
- if (from)
+ if (mFrom)
{
glPushMatrix();
glLoadIdentity();
glRotate(180.0 * a, 0.0, 1.0, 0.0);
- from->draw(alpha);
+ mFrom->draw(alpha);
glPopMatrix();
}
//drawFade(a);
- if (to)
+ if (mTo)
{
glPushMatrix();
glLoadIdentity();
glRotate(180.0 * (1.0 - a), 0.0, 1.0, 0.0);
- to->draw(alpha);
+ mTo->draw(alpha);
glPopMatrix();
}
//drawFade(1.0 - a);
bool handleEvent(const Event& event)
{
- if (to)
+ if (mTo)
{
- return to->handleEvent(event);
+ return mTo->handleEvent(event);
}
- else if (from)
+ else if (mFrom)
{
- return from->handleEvent(event);
+ return mFrom->handleEvent(event);
}
return false;
}
Video::Video()
{
- init(attribs_);
+ init(mAttribs);
}
Video::Video(const Attributes& attribs)
Video::Video(const std::string& caption, const std::string& icon)
{
- if (attribs_.caption == "Untitled")
+ if (mAttribs.caption == "Untitled")
{
- attribs_.caption = caption;
+ mAttribs.caption = caption;
}
- if (attribs_.icon == "")
+ if (mAttribs.icon == "")
{
- attribs_.icon = icon;
+ mAttribs.icon = icon;
}
- init(attribs_);
+ init(mAttribs);
}
void Video::init(const Attributes& attribs)
{
- context_ = 0;
- flags_ = 0;
- attribs_ = attribs;
+ mContext = 0;
+ mFlags = 0;
+ mAttribs = attribs;
setFull(attribs.fullscreen);
setResizable(attribs.resizable);
void Video::recreateContext()
{
- SDL_FreeSurface(context_);
- context_ = 0;
- setVideoMode(attribs_.mode);
+ SDL_FreeSurface(mContext);
+ mContext = 0;
+ setVideoMode(mAttribs.mode);
}
void Video::setOpenGLAttributes()
{
- SDL_GL_SetAttribute(SDL_GL_RED_SIZE, attribs_.colorBuffer[0]);
- SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, attribs_.colorBuffer[1]);
- SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, attribs_.colorBuffer[2]);
- SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, attribs_.colorBuffer[3]);
- SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, attribs_.frameBuffer);
- SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, attribs_.doubleBuffer);
- SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, attribs_.depthBuffer);
- SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, attribs_.stencilBuffer);
- SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE, attribs_.accumBuffer[0]);
- SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE, attribs_.accumBuffer[1]);
- SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE, attribs_.accumBuffer[2]);
- SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, attribs_.accumBuffer[3]);
- SDL_GL_SetAttribute(SDL_GL_STEREO, attribs_.stereo);
- SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, attribs_.multisampleBuffers);
- SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, attribs_.multisampleSamples);
- SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, attribs_.swapControl);
- SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, attribs_.hardwareonly);
+ SDL_GL_SetAttribute(SDL_GL_RED_SIZE, mAttribs.colorBuffer[0]);
+ SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, mAttribs.colorBuffer[1]);
+ SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, mAttribs.colorBuffer[2]);
+ SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, mAttribs.colorBuffer[3]);
+ SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, mAttribs.frameBuffer);
+ SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, mAttribs.doubleBuffer);
+ SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, mAttribs.depthBuffer);
+ SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, mAttribs.stencilBuffer);
+ SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE, mAttribs.accumBuffer[0]);
+ SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE, mAttribs.accumBuffer[1]);
+ SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE, mAttribs.accumBuffer[2]);
+ SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, mAttribs.accumBuffer[3]);
+ SDL_GL_SetAttribute(SDL_GL_STEREO, mAttribs.stereo);
+ SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, mAttribs.multisampleBuffers);
+ SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, mAttribs.multisampleSamples);
+ SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, mAttribs.swapControl);
+ SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, mAttribs.hardwareonly);
}
Video::~Video()
{
- SDL_FreeSurface(context_);
+ SDL_FreeSurface(mContext);
}
void Video::setVideoMode(const long mode[3])
{
- if (mode != attribs_.mode || !context_)
+ if (mode != mAttribs.mode || !mContext)
{
- if (context_) SDL_FreeSurface(context_);
+ if (mContext) SDL_FreeSurface(mContext);
- context_ = SDL_SetVideoMode(mode[0], mode[1], mode[2],
- SDL_OPENGL | flags_);
+ mContext = SDL_SetVideoMode(mode[0], mode[1], mode[2],
+ SDL_OPENGL | mFlags);
- if (context_)
+ if (mContext)
{
- attribs_.mode[0] = mode[0];
- attribs_.mode[1] = mode[1];
- attribs_.mode[2] = mode[2];
+ mAttribs.mode[0] = mode[0];
+ mAttribs.mode[1] = mode[1];
+ mAttribs.mode[2] = mode[2];
#if defined(_WIN32) || defined (_WIN64) || defined(__WIN32__)
// on win32, creating a new context via SDL_SetVideoMode will wipe
Video::Attributes Video::getAttributes() const
{
- return attribs_;
+ return mAttribs;
}
void Video::resize(int width, int height)
{
- long mode[] = {width, height, attribs_.mode[2]};
+ long mode[] = {width, height, mAttribs.mode[2]};
setVideoMode(mode);
}
void Video::setCaption(const std::string& caption)
{
- attribs_.caption = caption;
+ mAttribs.caption = caption;
SDL_WM_SetCaption(caption.c_str(), 0);
}
void Video::setIcon()
{
- if (attribs_.icon != "")
+ if (mAttribs.icon != "")
{
- SDL_Surface* icon = IMG_Load(attribs_.icon.c_str());
+ SDL_Surface* icon = IMG_Load(mAttribs.icon.c_str());
if (icon)
{
SDL_WM_SetIcon(icon, 0);
std::string Video::getCaption() const
{
- return attribs_.caption;
+ return mAttribs.caption;
}
void Video::setFull(bool full)
{
- if (full != isFull() || !context_)
+ if (full != isFull() || !mContext)
{
- if (context_)
+ if (mContext)
{
- flags_ ^= SDL_FULLSCREEN;
+ mFlags ^= SDL_FULLSCREEN;
#if defined(linux) || defined(__linux) || defined(__linux__)
- if (SDL_WM_ToggleFullScreen(context_) == 0)
+ if (SDL_WM_ToggleFullScreen(mContext) == 0)
#endif
recreateContext();
}
else
{
- if (full) flags_ |= SDL_FULLSCREEN;
- else flags_ &= ~SDL_FULLSCREEN;
+ if (full) mFlags |= SDL_FULLSCREEN;
+ else mFlags &= ~SDL_FULLSCREEN;
}
}
}
bool Video::isFull() const
{
- return flags_ & SDL_FULLSCREEN;
+ return mFlags & SDL_FULLSCREEN;
}
void Video::setResizable(bool resizable)
{
- if (resizable != isResizable() || !context_)
+ if (resizable != isResizable() || !mContext)
{
- if (context_)
+ if (mContext)
{
- flags_ ^= SDL_RESIZABLE;
+ mFlags ^= SDL_RESIZABLE;
recreateContext();
}
else
{
- if (resizable) flags_ |= SDL_RESIZABLE;
- else flags_ &= ~SDL_RESIZABLE;
+ if (resizable) mFlags |= SDL_RESIZABLE;
+ else mFlags &= ~SDL_RESIZABLE;
}
}
}
bool Video::isResizable() const
{
- return flags_ & SDL_RESIZABLE;
+ return mFlags & SDL_RESIZABLE;
}
int Video::getWidth() const
{
- return context_->w;
+ return mContext->w;
}
int Video::getHeight() const
{
- return context_->h;
+ return mContext->h;
}
typedef boost::shared_ptr<Video> VideoP;
-struct Video
+class Video
{
+public:
+
struct Attributes
{
// OpenGL attributes
};
-private:
-
- void init(const Attributes& attribs);
-
- void recreateContext();
- void setOpenGLAttributes();
-
- void setIcon();
-
- SDL_Surface* context_;
- unsigned flags_;
- Attributes attribs_;
-
-public:
-
static VideoP alloc(const std::string& caption, const std::string& icon)
{
return VideoP(new Video(caption, icon));
throw *this;
}
};
+
+private:
+
+ void init(const Attributes& attribs);
+
+ void recreateContext();
+ void setOpenGLAttributes();
+
+ void setIcon();
+
+ // TODO this implementation should be hidden
+
+ SDL_Surface* mContext;
+ unsigned mFlags;
+ Attributes mAttribs;
};
Mf::Settings::getInstance().get("detail", detail);
script.push(detail); script.set("detail");
- script.push(Quad::LEFT); script.set("LEFT");
- script.push(Quad::RIGHT); script.set("RIGHT");
- script.push(Quad::TOP); script.set("TOP");
-
script.push(X); script.set("X");
script.push(Y); script.set("Y");
script.push(Z); script.set("Z");
+
+ script.push(Quad::LEFT); script.set("LEFT");
+ script.push(Quad::RIGHT); script.set("RIGHT");
+ script.push(Quad::TOP); script.set("TOP");
}
int rotate(Mf::Script& script)
{
- Mf::Script::Value axis = script[1].requireString();
+ Mf::Script::Value axis = script[1].requireNumber();
Mf::Script::Value angle = script[2].requireNumber();
size_t index = 0;
int setTexture(Mf::Script& script)
{
- Mf::Script::Value name = script[1].requireString();
-
- name.get(texture);
-
+ script[1].requireString().get(texture);
return 0;
}
height = nTiles / width;
indices.resize(height);
- // the indices are stored upside-down in the scene file so that they
- // are easier to edit as text, so we'll need to load them last row
- // first
+ // the indices are stored upside-down in the scene file so that they are
+ // easier to edit as text, so we'll need to load them last row first
i = 1;
for (h = height - 1; h >= 0; --h)
Scene::Scene(const std::string& name) :
// pass through
- impl_(Scene::Impl::getInstance(name)) {}
+ mImpl(Scene::Impl::getInstance(name)) {}
void Scene::draw(Mf::Scalar alpha) const
{
- impl_->octree->draw(alpha);
+ mImpl->octree->draw(alpha);
}
void Scene::drawIfVisible(Mf::Scalar alpha, const Mf::Frustum& frustum) const
{
- impl_->octree->drawIfVisible(alpha, frustum);
+ mImpl->octree->drawIfVisible(alpha, frustum);
}
{
std::list< boost::shared_ptr<Impl::Quad> > objects;
//std::list<Mf::Octree<Impl::Quad>::InsertableP> objects;
- impl_->octree->getNearbyObjects(objects, character);
- impl_->maximumBounds.draw();
+ mImpl->octree->getNearbyObjects(objects, character);
+ mImpl->maximumBounds.draw();
Mf::logDebug("nearby objects: %d", objects.size());
return false;
class Scene : public Mf::Cullable, public Mf::Drawable, public Mf::Resource
{
class Impl;
- boost::shared_ptr<Impl> impl_;
+ boost::shared_ptr<Impl> mImpl;
public:
{
Impl(const std::string& name) :
Mf::Mippleton<Impl>(name),
- magFilter_(GL_NEAREST),
- minFilter_(GL_NEAREST),
- nTilesS_(1),
- nTilesT_(1),
- wrapS_(GL_CLAMP),
- wrapT_(GL_CLAMP)
+ mMagFilter(GL_NEAREST),
+ mMinFilter(GL_NEAREST),
+ mTilesS(1),
+ mTilesT(1),
+ mWrapS(GL_CLAMP),
+ mWrapT(GL_CLAMP)
{
loadFromFile();
}
Mf::Script::Value top = script[-1];
globals.pushField("tiles_s");
- top.get(nTilesS_);
+ top.get(mTilesS);
globals.pushField("tiles_t");
- top.get(nTilesT_);
+ top.get(mTilesT);
globals.pushField("min_filter");
- top.get(minFilter_);
+ top.get(mMinFilter);
globals.pushField("mag_filter");
- top.get(magFilter_);
+ top.get(mMagFilter);
globals.pushField("wrap_s");
- top.get(wrapS_);
+ top.get(mWrapS);
globals.pushField("wrap_t");
- top.get(wrapT_);
+ top.get(mWrapT);
}
bool getTileCoords(Tilemap::Index index, Mf::Scalar coords[8]) const
{
// make sure the index represents a real tile
- if (index >= nTilesS_ * nTilesT_) return false;
+ if (index >= mTilesS * mTilesT) return false;
- Mf::Scalar w = 1.0 / Mf::Scalar(nTilesS_);
- Mf::Scalar h = 1.0 / Mf::Scalar(nTilesT_);
+ Mf::Scalar w = 1.0 / Mf::Scalar(mTilesS);
+ Mf::Scalar h = 1.0 / Mf::Scalar(mTilesT);
- coords[0] = Mf::Scalar(index % nTilesS_) * w;
- coords[1] = (Mf::Scalar(nTilesT_ - 1) -
- Mf::Scalar(index / nTilesS_)) * h;
+ coords[0] = Mf::Scalar(index % mTilesS) * w;
+ coords[1] = (Mf::Scalar(mTilesT - 1) -
+ Mf::Scalar(index / mTilesS)) * h;
coords[2] = coords[0] + w;
coords[3] = coords[1];
coords[4] = coords[2];
}
- GLuint magFilter_;
- GLuint minFilter_;
- unsigned nTilesS_;
- unsigned nTilesT_;
- GLuint wrapS_;
- GLuint wrapT_;
+ GLuint mMagFilter;
+ GLuint mMinFilter;
+ unsigned mTilesS;
+ unsigned mTilesT;
+ GLuint mWrapS;
+ GLuint mWrapT;
};
Tilemap::Tilemap(const std::string& name) :
Texture(name),
- impl_(Tilemap::Impl::getInstance(name))
+ mImpl(Tilemap::Impl::getInstance(name))
{
- setMinFilter(impl_->minFilter_);
- setMagFilter(impl_->magFilter_);
- setWrapS(impl_->wrapS_);
- setWrapT(impl_->wrapT_);
+ setMinFilter(mImpl->mMinFilter);
+ setMagFilter(mImpl->mMagFilter);
+ setWrapS(mImpl->mWrapS);
+ setWrapT(mImpl->mWrapT);
}
bool Tilemap::getTileCoords(Index index, Mf::Scalar coords[8]) const
{
// pass through
- return impl_->getTileCoords(index, coords);
+ return mImpl->getTileCoords(index, coords);
}
bool Tilemap::getTileCoords(Index index, Mf::Scalar coords[8],
class Tilemap : public Mf::Texture
{
public:
+
/**
* Possible orientations for texture coordinates.
*/
static std::string getPath(const std::string& name);
private:
+
class Impl;
- boost::shared_ptr<Impl> impl_;
+ boost::shared_ptr<Impl> mImpl;
};
class TilemapFont : public Tilemap
{
public:
+
TilemapFont();
void getTileCoords(char symbol, Mf::Scalar coords[8],
#include "TitleLayer.hh"
-void TitleLayer::pushed(Mf::Engine& e)
+void TitleLayer::pushed(Mf::Engine& engine)
{
- engine = &e;
+ mEngine = &engine;
Mf::Scalar coeff[] = {0.0, 1.0};
- fadeIn.init(coeff, 0.1);
+ mFadeIn.init(coeff, 0.1);
- gameLayer = GameLayer::alloc();
+ mGameLayer = GameLayer::alloc();
}
void TitleLayer::update(Mf::Scalar t, Mf::Scalar dt)
{
- if (!fadeIn.isDone()) fadeIn.update(t, dt);
+ if (!mFadeIn.isDone()) mFadeIn.update(t, dt);
}
void TitleLayer::draw(Mf::Scalar alpha) const
{
- glClearColor(0.0, 0.0, fadeIn.getState(alpha), 1.0);
+ glClearColor(0.0, 0.0, mFadeIn.getState(alpha), 1.0);
glClear(GL_COLOR_BUFFER_BIT);
}
switch (event.type)
{
case SDL_KEYUP:
- Mf::LayerP titleLayer = engine->pop(this);
- //engine->pushLayer(GameLayer::alloc());
+ Mf::LayerP titleLayer = mEngine->pop(this);
+ //mEngine->pushLayer(GameLayer::alloc());
Mf::Scalar coeff[] = {0.0, 1.0};
Mf::Lerp interp(coeff, 0.2);
- //Mf::LayerP gameLayer = GameLayer::alloc();
+ //Mf::LayerP mGameLayer = GameLayer::alloc();
Mf::Transition<Mf::Lerp>::Ptr transition =
- Mf::Transition<Mf::Lerp>::alloc(gameLayer, titleLayer, interp);
- engine->push(transition);
+ Mf::Transition<Mf::Lerp>::alloc(mGameLayer, titleLayer, interp);
+ mEngine->push(transition);
return true;
}
private:
- Mf::Lerp fadeIn;
- Mf::Engine* engine;
+ Mf::Lerp mFadeIn;
+ Mf::Engine* mEngine;
- Mf::LayerP gameLayer;
+ Mf::LayerP mGameLayer;
};
class Typesetter
{
public:
+
Typesetter();
void setLineSpacing(Mf::Scalar spacing);
void print(const std::string& format, ...);
private:
- Mf::Scalar leftBound;
- Mf::Scalar topBound;
- Mf::Scalar lineSpacing;
+
+ Mf::Scalar mLeftBound;
+ Mf::Scalar mTopBound;
+ Mf::Scalar mLineSpacing;
};