From: Charles McGarvey Date: Wed, 29 Jul 2009 09:22:35 +0000 (-0600) Subject: extreme refactoring X-Git-Url: https://git.dogcows.com/gitweb?a=commitdiff_plain;h=c2321281bf12a7efaedde930422c7ddbc92080d4;p=chaz%2Fyoink extreme refactoring --- diff --git a/src/Character.cc b/src/Character.cc index 64866c5..1797f00 100644 --- a/src/Character.cc +++ b/src/Character.cc @@ -30,8 +30,8 @@ Character::Character(const std::string& name) : - texture(name), - anim(name) {} + tilemap(name), + animation(name) {} Character::~Character() { @@ -40,16 +40,16 @@ Character::~Character() } -void Character::draw(dc::scalar alpha) {} +void Character::draw(Mf::Scalar alpha) {} -dc::tilemap& Character::getTilemap() +Mf::Tilemap& Character::getTilemap() { - return texture; + return tilemap; } -dc::animation& Character::getAnimation() +Mf::Animation& Character::getAnimation() { - return anim; + return animation; } diff --git a/src/Character.hh b/src/Character.hh index c9cf11a..b1965ce 100644 --- a/src/Character.hh +++ b/src/Character.hh @@ -29,36 +29,37 @@ #ifndef _CHARACTER_HH_ #define _CHARACTER_HH_ -#include "resource.hh" -#include "drawable.hh" -#include "animation.hh" -#include "tilemap.hh" +#include +#include +#include +#include /** * Parent class of animate objects with "personalities." */ -class Character : public dc::drawable +class Character : public Mf::Drawable { public: - struct exception : public std::runtime_error - { - explicit exception(const std::string& what_arg) : - std::runtime_error(what_arg) {} - }; - Character(const std::string& name); ~Character(); - void draw(dc::scalar alpha); + void draw(Mf::Scalar alpha); + + Mf::Tilemap& getTilemap(); + Mf::Animation& getAnimation(); - dc::tilemap& getTilemap(); - dc::animation& getAnimation(); + + struct Exception : public std::runtime_error + { + explicit Exception(const std::string& what_arg) : + std::runtime_error(what_arg) {} + }; private: - dc::tilemap texture; - dc::animation anim; + Mf::Tilemap tilemap; + Mf::Animation animation; }; diff --git a/src/Makefile.am b/src/Makefile.am index 0c9b062..9ea7843 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -1,55 +1,55 @@ -noinst_LTLIBRARIES = libdc.la +noinst_LTLIBRARIES = libmoof.la -libdc_la_SOURCES = \ - ConvertUTF.c \ - ConvertUTF.h \ - aabb.hh \ - animation.cc \ - animation.hh \ - deserializer.cc \ - deserializer.hh \ - dispatcher.cc \ - dispatcher.hh \ - drawable.hh \ - engine.cc \ - engine.hh \ - event.hh \ - fastevents.c \ - fastevents.h \ - interpolator.hh \ - math.hh \ - mippleton.hh \ - opengl.hh \ - profiler.hh \ - random.cc \ - random.hh \ - resource.cc \ - resource.hh \ - scene.cc \ - scene.hh \ - serializable.cc \ - serializable.hh \ - serializer.cc \ - serializer.hh \ - settings.cc \ - settings.hh \ - singleton.hh \ - stringtools.cc \ - stringtools.hh \ - texture.cc \ - texture.hh \ - thread.hh \ - tilemap.cc \ - tilemap.hh \ - timer.cc \ - timer.hh \ - video.cc \ - video.hh \ +libmoof_la_SOURCES = \ + Moof/Aabb.hh \ + Moof/Animation.cc \ + Moof/Animation.hh \ + Moof/ConvertUTF.c \ + Moof/ConvertUTF.h \ + Moof/Deserializer.cc \ + Moof/Deserializer.hh \ + Moof/Dispatcher.cc \ + Moof/Dispatcher.hh \ + Moof/Drawable.hh \ + Moof/Engine.cc \ + Moof/Engine.hh \ + Moof/Event.hh \ + Moof/Interpolator.hh \ + Moof/Math.hh \ + Moof/Mippleton.hh \ + Moof/OpenGL.hh \ + Moof/Profiler.hh \ + Moof/Random.cc \ + Moof/Random.hh \ + Moof/Resource.cc \ + Moof/Resource.hh \ + Moof/Scene.cc \ + Moof/Scene.hh \ + Moof/Serializable.cc \ + Moof/Serializable.hh \ + Moof/Serializer.cc \ + Moof/Serializer.hh \ + Moof/Settings.cc \ + Moof/Settings.hh \ + Moof/Singleton.hh \ + Moof/StringTools.cc \ + Moof/StringTools.hh \ + Moof/Texture.cc \ + Moof/Texture.hh \ + Moof/Thread.hh \ + Moof/Tilemap.cc \ + Moof/Tilemap.hh \ + Moof/Timer.cc \ + Moof/Timer.hh \ + Moof/Video.cc \ + Moof/Video.hh \ + Moof/fastevents.c \ + Moof/fastevents.h \ $(ENDLIST) -libdc_la_CPPFLAGS = -I$(top_srcdir)/yajl/src -libdc_la_LIBADD = $(top_srcdir)/yajl/libyajl.la +libmoof_la_CPPFLAGS = -I$(top_srcdir)/src/Moof -I$(top_srcdir)/yajl/src +libmoof_la_LIBADD = $(top_srcdir)/yajl/libyajl.la bin_PROGRAMS = yoink @@ -65,10 +65,11 @@ yoink_SOURCES = \ YoinkApp.hh \ $(ENDLIST) -yoink_LDADD = libdc.la +yoink_CPPFLAGS = -I$(top_srcdir)/src/Moof +yoink_LDADD = libmoof.la -EXTRA_DIST = cml +EXTRA_DIST = Moof/cml YOINK_ENVIRONMENT = YOINK_DATADIR="$(top_srcdir)/data" \ diff --git a/src/aabb.hh b/src/Moof/Aabb.hh similarity index 84% rename from src/aabb.hh rename to src/Moof/Aabb.hh index e608b21..f66fb24 100644 --- a/src/aabb.hh +++ b/src/Moof/Aabb.hh @@ -26,40 +26,40 @@ ******************************************************************************/ -#ifndef _AABB_HH_ -#define _AABB_HH_ +#ifndef _MOOF_AABB_HH_ +#define _MOOF_AABB_HH_ -#include "math.hh" +#include -namespace dc { +namespace Mf { /** * Axis-aligned Bounding Box */ -struct aabb +struct Aabb { - aabb() {} + Aabb() {} - aabb(const vector3& minPoint, const vector3& maxPoint) : + Aabb(const Vector3& minPoint, const Vector3& maxPoint) : min(minPoint), max(maxPoint) {} - aabb (scalar minX, scalar minY, scalar minZ, - scalar maxX, scalar maxY, scalar maxZ) : + Aabb (Scalar minX, Scalar minY, Scalar minZ, + Scalar maxX, Scalar maxY, Scalar maxZ) : min(minX, minY, minZ), max(maxX, maxY, maxZ) {} - vector3 min; - vector3 max; + Vector3 min; + Vector3 max; }; -} // namespace dc +} // namespace Mf -#endif // _AABB_HH_ +#endif // _MOOF_AABB_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/animation.cc b/src/Moof/Animation.cc similarity index 67% rename from src/animation.cc rename to src/Moof/Animation.cc index c03a49d..3c418f7 100644 --- a/src/animation.cc +++ b/src/Moof/Animation.cc @@ -29,24 +29,24 @@ #include #include -#include "serializable.hh" -#include "mippleton.hh" -#include "animation.hh" +#include "Animation.hh" +#include "Mippleton.hh" +#include "Serializable.hh" -namespace dc { +namespace Mf { /** * The collection of nested animation classes. The animation implementation - * consists of an animation_impl classes which is allocated and initialized with + * consists of an AnimationImpl classes which is allocated and initialized with * the interface object. This class contains the specific fields which are * required to run a single instance of an animation. The sequence data is * loaded in a difference class which can be shared amongst multiple animation * implementation instances. */ -struct animation::animation_impl +struct Animation::AnimationImpl { /** @@ -55,7 +55,7 @@ struct animation::animation_impl * which wants to use these loaded sequences. */ - struct animation_data : public mippleton + struct AnimationData : public Mippleton { /** * A frame of an animation sequence. A frame is merely an index which @@ -63,39 +63,40 @@ struct animation::animation_impl * and the duration that is how long the slide will be shown. */ - struct frame + struct Frame { unsigned index; ///< Frame index. - scalar duration; ///< Frame duration. + Scalar duration; ///< Frame duration. /** * Construction is initialization. The frame data is loaded from a * frame map which is probably loaded within an animation file. */ - frame(serializable_ptr root) : + Frame(SerializablePtr root) : index(0), duration(1.0) { - std::map rootObj; + std::map rootObj; if (root->get(rootObj)) { - std::map::iterator i; - for (i = rootObj.begin(); i != rootObj.end(); i++) + std::map::iterator it; + + for (it = rootObj.begin(); it != rootObj.end(); it++) { - std::string key = (*i).first; + std::string key = (*it).first; if (key == "index") { long value = 0; - (*i).second->get(value); + (*it).second->get(value); index = unsigned(value); } else if (key == "duration") { double value = 0.0; - (*i).second->getNumber(value); - duration = scalar(value); + (*it).second->getNumber(value); + duration = Scalar(value); } } } @@ -108,10 +109,10 @@ struct animation::animation_impl * that they should be played. */ - struct sequence + struct Sequence { - std::vector frames; ///< List of frames. - scalar delay; ///< Scale frame durations. + std::vector frames; ///< List of frames. + Scalar delay; ///< Scale frame durations. bool loop; ///< Does the sequence repeat? std::string next; ///< Next sequence name. @@ -122,33 +123,33 @@ struct animation::animation_impl * constructor which loads each individual frame. */ - sequence(serializable_ptr root) : + Sequence(SerializablePtr root) : delay(0.0), loop(true) { - std::map rootObj; + std::map rootObj; if (root->get(rootObj)) { - std::map::iterator i; - for (i = rootObj.begin(); i != rootObj.end(); i++) + std::map::iterator it; + for (it = rootObj.begin(); it != rootObj.end(); it++) { - std::string key = (*i).first; + std::string key = (*it).first; if (key == "frames") { - std::vector framesObj; + std::vector framesObj; - if ((*i).second->get(framesObj)) + if ((*it).second->get(framesObj)) { - std::vector::iterator j; + std::vector::iterator jt; - for (j = framesObj.begin(); - j != framesObj.end(); j++) + for (jt = framesObj.begin(); + jt != framesObj.end(); jt++) { - if (*j) + if (*jt) { - frames.push_back(frame(*j)); + frames.push_back(Frame(*jt)); } } } @@ -156,16 +157,16 @@ struct animation::animation_impl else if (key == "delay") { double value; - (*i).second->getNumber(value); - delay = scalar(value); + (*it).second->getNumber(value); + delay = Scalar(value); } else if (key == "loop") { - (*i).second->get(loop); + (*it).second->get(loop); } else if (key == "next") { - (*i).second->get(next); + (*it).second->get(next); } } } @@ -181,24 +182,24 @@ struct animation::animation_impl void loadFromFile() { - std::string filePath = animation::getPathToResource(getName()); + std::string filePath = Animation::getPathToResource(getName()); - deserializer in(filePath); + Deserializer deserializer(filePath); - serializable_ptr root = in.deserialize(); + SerializablePtr root = deserializer.deserialize(); if (root) { - std::map rootObj; + std::map rootObj; if (root->get(rootObj)) { - std::map::iterator i; + std::map::iterator it; - for (i = rootObj.begin(); i != rootObj.end(); i++) + for (it = rootObj.begin(); it != rootObj.end(); it++) { - sequences.insert(std::pair((*i).first, - sequence((*i).second))); + sequences.insert(std::pair((*it).first, + Sequence((*it).second))); } } } @@ -209,13 +210,13 @@ struct animation::animation_impl * registers itself as a mippleton and then loads the animation data. */ - explicit animation_data(const std::string& name) : - mippleton(name) + explicit AnimationData(const std::string& name) : + Mippleton(name) { loadFromFile(); } - std::map sequences; ///< List of sequences. + std::map sequences; ///< List of sequences. }; @@ -223,8 +224,8 @@ struct animation::animation_impl * Construction is intialization. */ - animation_impl(const std::string& name) : - data(animation_data::retain(name), &animation_data::release), + AnimationImpl(const std::string& name) : + data(AnimationData::retain(name), &AnimationData::release), currentSequence(0), frameCounter(0), frameIndex(0), @@ -238,15 +239,15 @@ struct animation::animation_impl * updates will progress the new sequence. */ - void startSequence(const std::string& sequenceName) + void startSequence(const std::string& name) { - std::map::iterator i; + std::map::iterator it; - i = data->sequences.find(sequenceName); + it = data->sequences.find(name); - if (i != data->sequences.end()) + if (it != data->sequences.end()) { - currentSequence = &(*i).second; + currentSequence = &(*it).second; frameCounter = 0; frameIndex = currentSequence->frames[0].index; timeAccum = 0.0; @@ -265,7 +266,7 @@ struct animation::animation_impl * starts over again. */ - void update(scalar t, scalar dt) + void update(Scalar t, Scalar dt) { if (currentSequence) { @@ -298,31 +299,31 @@ struct animation::animation_impl } } - boost::shared_ptr data; ///< Internal data. + boost::shared_ptr data; ///< Internal data. - animation_data::sequence* currentSequence; ///< Active sequence. + AnimationData::Sequence* currentSequence; ///< Active sequence. unsigned frameCounter; ///< Current frame. unsigned frameIndex; ///< Index of current frame. - scalar timeAccum; ///< Time accumulation. - scalar frameDuration; ///< Scaled frame duration. + Scalar timeAccum; ///< Time accumulation. + Scalar frameDuration; ///< Scaled frame duration. }; -animation::animation(const std::string& name) : +Animation::Animation(const std::string& name) : // pass through - impl(new animation::animation_impl(name)) {} + impl_(new Animation::AnimationImpl(name)) {} -void animation::startSequence(const std::string& sequenceName) +void Animation::startSequence(const std::string& name) { // pass through - impl->startSequence(sequenceName); + impl_->startSequence(name); } -void animation::update(scalar t, scalar dt) +void Animation::update(Scalar t, Scalar dt) { // pass through - impl->update(t, dt); + impl_->update(t, dt); } @@ -331,9 +332,9 @@ void animation::update(scalar t, scalar dt) * drawing code which will draw the correct current frame. */ -unsigned animation::getFrame() const +unsigned Animation::getFrame() const { - return impl->frameIndex; + return impl_->frameIndex; } @@ -342,13 +343,13 @@ unsigned animation::getFrame() const * "animations" subdirectory of any of the searched directories. */ -std::string animation::getPathToResource(const std::string& name) +std::string Animation::getPathToResource(const std::string& name) { - return resource::getPathToResource("animations/" + name + ".json"); + return Resource::getPathToResource("animations/" + name + ".json"); } -} // namespace dc +} // namespace Mf /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/animation.hh b/src/Moof/Animation.hh similarity index 84% rename from src/animation.hh rename to src/Moof/Animation.hh index ca56581..57ce6a8 100644 --- a/src/animation.hh +++ b/src/Moof/Animation.hh @@ -26,11 +26,11 @@ *******************************************************************************/ -#ifndef _ANIMATION_HH_ -#define _ANIMATION_HH_ +#ifndef _MOOF_ANIMATION_HH_ +#define _MOOF_ANIMATION_HH_ /** - * @file animation.hh + * @file Animation.hh * Motion picture!! */ @@ -38,11 +38,11 @@ #include -#include "resource.hh" -#include "math.hh" +#include +#include -namespace dc { +namespace Mf { /** @@ -53,27 +53,27 @@ namespace dc { * anything to whatever drawing context is used to render the frame. */ -class animation : public resource +class Animation : public Resource { public: - animation(const std::string& name); + Animation(const std::string& name); - void startSequence(const std::string& sequenceName); + void startSequence(const std::string& name); - void update(scalar t, scalar dt); + void update(Scalar t, Scalar dt); unsigned getFrame() const; static std::string getPathToResource(const std::string& name); private: - class animation_impl; - boost::shared_ptr impl; + class AnimationImpl; + boost::shared_ptr impl_; }; -} // namespace dc +} // namespace Mf -#endif // _ANIMATION_HH_ +#endif // _MOOF_ANIMATION_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/camera.hh b/src/Moof/Camera.hh similarity index 93% rename from src/camera.hh rename to src/Moof/Camera.hh index dcdc55d..8800e3b 100644 --- a/src/camera.hh +++ b/src/Moof/Camera.hh @@ -26,23 +26,23 @@ *******************************************************************************/ -#ifndef _CAMERA_HH_ -#define _CAMERA_HH_ +#ifndef _MOOF_CAMERA_HH_ +#define _MOOF_CAMERA_HH_ -namespace dc { +namespace Mf { -class camera +class Camera { public: private: }; -} // namespace dc +} // namespace Mf -#endif // _CAMERA_HH_ +#endif // _MOOF_CAMERA_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/ConvertUTF.c b/src/Moof/ConvertUTF.c similarity index 100% rename from src/ConvertUTF.c rename to src/Moof/ConvertUTF.c diff --git a/src/ConvertUTF.h b/src/Moof/ConvertUTF.h similarity index 100% rename from src/ConvertUTF.h rename to src/Moof/ConvertUTF.h diff --git a/src/cullable.hh b/src/Moof/Cullable.hh similarity index 84% rename from src/cullable.hh rename to src/Moof/Cullable.hh index e4fe4ca..d543d0f 100644 --- a/src/cullable.hh +++ b/src/Moof/Cullable.hh @@ -26,29 +26,30 @@ *******************************************************************************/ -#ifndef _CULLABLE_HH_ -#define _CULLABLE_HH_ +#ifndef _MOOF_CULLABLE_HH_ +#define _MOOF_CULLABLE_HH_ -#include "camera.hh" +#include -namespace dc { +namespace Mf { /** - * Interface for anything that can be culled given a camera's frustrum. + * Interface for anything that can be culled. This can include more than just + * frustrum culling. */ -class cullable +class Cullable { public: - virtual bool isVisible(const camera& cam) = 0; + virtual bool isVisible(const Camera& cam) = 0; }; -} // namespace dc +} // namespace Mf -#endif // _CULLABLE_HH_ +#endif // _MOOF_CULLABLE_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/deserializer.cc b/src/Moof/Deserializer.cc similarity index 66% rename from src/deserializer.cc rename to src/Moof/Deserializer.cc index 929c3c1..8bf230f 100644 --- a/src/deserializer.cc +++ b/src/Moof/Deserializer.cc @@ -31,30 +31,30 @@ #include -#include "serializable.hh" -#include "deserializer.hh" +#include "Deserializer.hh" +#include "Serializable.hh" -namespace dc { +namespace Mf { -class deserializer::deserializer_impl +class Deserializer::DeserializerImpl { public: - deserializer_impl(const std::string& filePath, bool comments = false, + DeserializerImpl(const std::string& filePath, bool comments = false, bool check = false) { std::ifstream* input = new std::ifstream(filePath.c_str()); init(*input, true, comments, check); } - deserializer_impl(std::istream& input, bool comments = false, + DeserializerImpl(std::istream& input, bool comments = false, bool check = false) { init(input, false, comments, check); } - ~deserializer_impl() + ~DeserializerImpl() { while (!parsed.empty()) { @@ -71,49 +71,49 @@ public: void throwError() { - unsigned char* errorMsg = yajl_get_error(hand, 0, 0, 0); - deserializer::exception problem((char*)errorMsg); - yajl_free_error(hand, errorMsg); - throw problem; + unsigned char* errorStr = yajl_get_error(hand, 0, 0, 0); + Deserializer::Exception exception((char*)errorStr); + yajl_free_error(hand, errorStr); + throw exception; } static int parsedNull(void* ctx) { - ((deserializer_impl*)ctx)->parsed.push(new null); + ((DeserializerImpl*)ctx)->parsed.push(new SerializableNull); return 1; } static int parsedBoolean(void* ctx, int value) { - ((deserializer_impl*)ctx)->parsed.push(new wrapped_boolean(value)); + ((DeserializerImpl*)ctx)->parsed.push(new SerializableBoolean(value)); return 1; } static int parsedInteger(void* ctx, long value) { - ((deserializer_impl*)ctx)->parsed.push(new wrapped_integer(value)); + ((DeserializerImpl*)ctx)->parsed.push(new SerializableInteger(value)); return 1; } static int parsedFloat(void* ctx, double value) { - ((deserializer_impl*)ctx)->parsed.push(new wrapped_real(value)); + ((DeserializerImpl*)ctx)->parsed.push(new SerializableReal(value)); return 1; } static int parsedString(void* ctx, const unsigned char* value, unsigned length) { - wrapped_string* parsed = new wrapped_string(std::string((char*)value, - length)); - ((deserializer_impl*)ctx)->parsed.push(parsed); + SerializableString* parsed = + new SerializableString(std::string((char*)value, length)); + ((DeserializerImpl*)ctx)->parsed.push(parsed); return 1; } static int parsedBeginMap(void* ctx) { - ((deserializer_impl*)ctx)->parsed.push(new wrapped_dictionary); + ((DeserializerImpl*)ctx)->parsed.push(new SerializableMap); return 1; } @@ -126,19 +126,19 @@ public: static int parsedEndMap(void* ctx) { - ((deserializer_impl*)ctx)->parsed.push(0); + ((DeserializerImpl*)ctx)->parsed.push(0); return 1; } static int parsedBeginArray(void* ctx) { - ((deserializer_impl*)ctx)->parsed.push(new wrapped_array); + ((DeserializerImpl*)ctx)->parsed.push(new SerializableArray); return 1; } static int parsedEndArray(void* ctx) { - ((deserializer_impl*)ctx)->parsed.push(0); + ((DeserializerImpl*)ctx)->parsed.push(0); return 1; } @@ -177,7 +177,7 @@ public: std::istream* in; bool deleteWhenDone; - std::queue parsed; + std::queue parsed; private: void init(std::istream& input, bool deleteIn, bool comments, bool check) @@ -186,17 +186,17 @@ private: // internal data structures but rather keeps a pointer to this static const yajl_callbacks callbacks = { - deserializer_impl::parsedNull, - deserializer_impl::parsedBoolean, - deserializer_impl::parsedInteger, - deserializer_impl::parsedFloat, + DeserializerImpl::parsedNull, + DeserializerImpl::parsedBoolean, + DeserializerImpl::parsedInteger, + DeserializerImpl::parsedFloat, 0, - deserializer_impl::parsedString, - deserializer_impl::parsedBeginMap, - deserializer_impl::parsedMapKey, - deserializer_impl::parsedEndMap, - deserializer_impl::parsedBeginArray, - deserializer_impl::parsedEndArray + DeserializerImpl::parsedString, + DeserializerImpl::parsedBeginMap, + DeserializerImpl::parsedMapKey, + DeserializerImpl::parsedEndMap, + DeserializerImpl::parsedBeginArray, + DeserializerImpl::parsedEndArray }; in = &input; @@ -208,46 +208,46 @@ private: }; -deserializer::deserializer(const std::string& filePath, bool comments, +Deserializer::Deserializer(const std::string& filePath, bool comments, bool check) : // pass through - impl(new deserializer::deserializer_impl(filePath, comments, check)) {} + impl_(new Deserializer::DeserializerImpl(filePath, comments, check)) {} -deserializer::deserializer(std::istream& input, bool comments, bool check) : +Deserializer::Deserializer(std::istream& input, bool comments, bool check) : // pass through - impl(new deserializer::deserializer_impl(input, comments, check)) {} + impl_(new Deserializer::DeserializerImpl(input, comments, check)) {} -serializable_ptr deserializer::deserialize() +SerializablePtr Deserializer::deserialize() { - serializable* ptr = pullNext(); + Serializable* ptr = pullNext(); if (ptr) { ptr->deserialize(*this); } - return serializable_ptr(ptr); + return SerializablePtr(ptr); } -serializable* deserializer::pullNext() +Serializable* Deserializer::pullNext() { - impl->parse(); - if (!impl->parsed.empty()) + impl_->parse(); + if (!impl_->parsed.empty()) { - serializable* ptr = impl->parsed.front(); + Serializable* ptr = impl_->parsed.front(); return ptr; } return 0; } -void deserializer::pop() +void Deserializer::pop() { // pass through - impl->parsed.pop(); + impl_->parsed.pop(); } -} // namespace dc +} // namespace Mf /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/deserializer.hh b/src/Moof/Deserializer.hh similarity index 86% rename from src/deserializer.hh rename to src/Moof/Deserializer.hh index f2b0bcc..8a771e8 100644 --- a/src/deserializer.hh +++ b/src/Moof/Deserializer.hh @@ -26,11 +26,11 @@ *******************************************************************************/ -#ifndef _DESERIALIZER_HH_ -#define _DESERIALIZER_HH_ +#ifndef _MOOF_DESERIALIZER_HH_ +#define _MOOF_DESERIALIZER_HH_ /** - * @file deserializer.hh + * @file Deserializer.hh * Deserialize structures and types from input on a stream. */ @@ -41,13 +41,13 @@ #include -namespace dc { +namespace Mf { -class serializable; // forward declaration -typedef boost::shared_ptr serializable_ptr; +class Serializable; // forward declaration +typedef boost::shared_ptr SerializablePtr; -class deserializer +class Deserializer { public: @@ -65,9 +65,9 @@ public: * checked. */ - deserializer(const std::string& filePath, bool comments = false, + Deserializer(const std::string& filePath, bool comments = false, bool check = false); - deserializer(std::istream& input, bool comments = false, bool check = false); + Deserializer(std::istream& input, bool comments = false, bool check = false); /** @@ -77,7 +77,7 @@ public: * deserializer. */ - serializable_ptr deserialize(); + SerializablePtr deserialize(); /** * Used by serializable objects to parse themselves. These methods should @@ -95,7 +95,7 @@ public: * method to return the next object as expected. */ - serializable* pullNext(); + Serializable* pullNext(); /** * If the object returned by pullNext() has been received successfully and @@ -110,22 +110,22 @@ public: * This exception is thrown upon deserialization errors. */ - struct exception : std::runtime_error + struct Exception : std::runtime_error { - explicit exception(const std::string& what_arg) : + explicit Exception(const std::string& what_arg) : std::runtime_error(what_arg) {} }; private: - class deserializer_impl; - boost::shared_ptr impl; + class DeserializerImpl; + boost::shared_ptr impl_; }; -} // namespace dc +} // namespace Mf -#endif // _DESERIALIZER_HH_ +#endif // _MOOF_DESERIALIZER_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/Moof/Dispatcher.cc b/src/Moof/Dispatcher.cc new file mode 100644 index 0000000..fa7b328 --- /dev/null +++ b/src/Moof/Dispatcher.cc @@ -0,0 +1,140 @@ + +/******************************************************************************* + + 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. + +*******************************************************************************/ + +#include + +#include "Dispatcher.hh" + + +namespace Mf { + + +Notification::~Notification() {} + + +class Dispatcher::DispatcherImpl +{ +public: + DispatcherImpl() : id(1) {} + + Dispatcher::Handler getNewHandlerID() + { + id += 4; + return (Dispatcher::Handler)id; + } + + typedef std::pair Callback; + typedef std::multimap CallbackLookup; + typedef CallbackLookup::iterator CallbackIter; + + typedef std::multimap HandlerLookup; + typedef HandlerLookup::iterator HandlerIter; + + unsigned long long id; + + CallbackLookup callbacks; + HandlerLookup handlers; +}; + + +Dispatcher::Dispatcher() : + impl_(new Dispatcher::DispatcherImpl) {} + + +// TODO these methods are ugly + +Dispatcher::Handler Dispatcher::addHandler(const std::string& message, + const Function& callback) +{ + return addHandler(message, callback, impl_->getNewHandlerID()); +} + +Dispatcher::Handler Dispatcher::addHandler(const std::string& message, + const Function& callback, Handler id) +{ + std::pair + callbackPair(message, Dispatcher::DispatcherImpl::Callback(id, callback)); + + std::pair handlerPair(id, message); + + impl_->callbacks.insert(callbackPair); + impl_->handlers.insert(handlerPair); + + return id; +} + + +void Dispatcher::removeHandler(Handler id) +{ + std::pair + handlers(impl_->handlers.equal_range(id)); + + Dispatcher::DispatcherImpl::HandlerIter i; + for (i = handlers.first; i != handlers.second; i++) + { + Dispatcher::DispatcherImpl::CallbackIter it = impl_->callbacks.find((*i).second); + Dispatcher::DispatcherImpl::CallbackIter last = impl_->callbacks.end(); + + Dispatcher::DispatcherImpl::CallbackIter j; + for (j = it; j != last; j++) + { + if (((*j).second).first == id) + { + impl_->callbacks.erase(j); + break; + } + } + } + + impl_->handlers.erase(id); +} + + +void Dispatcher::dispatch(const std::string& message) +{ + dispatch(message, Notification()); +} + +void Dispatcher::dispatch(const std::string& message, const Notification& param) +{ + std::pair + callbacks(impl_->callbacks.equal_range(message)); + + Dispatcher::DispatcherImpl::CallbackIter i; + for (i = callbacks.first; i != callbacks.second; i++) + { + Function callback = ((*i).second).second; + callback(param); + } +} + + +} // namespace Mf + +/** vim: set ts=4 sw=4 tw=80: *************************************************/ + diff --git a/src/dispatcher.hh b/src/Moof/Dispatcher.hh similarity index 74% rename from src/dispatcher.hh rename to src/Moof/Dispatcher.hh index 1a7744a..ec143b4 100644 --- a/src/dispatcher.hh +++ b/src/Moof/Dispatcher.hh @@ -26,28 +26,28 @@ *******************************************************************************/ -#ifndef _DISPATCHER_HH_ -#define _DISPATCHER_HH_ +#ifndef _MOOF_DISPATCHER_HH_ +#define _MOOF_DISPATCHER_HH_ #include #include #include -#include "singleton.hh" +#include -namespace dc { +namespace Mf { /** * Interface for a notification class. */ -class notification +class Notification { public: - virtual ~notification(); + virtual ~Notification(); }; @@ -55,33 +55,32 @@ public: * Dispatcher of notifications to interested parties. */ -class dispatcher : public singleton +class Dispatcher : public Singleton { public: - typedef void* handler; + typedef void* Handler; + typedef boost::function Function; - dispatcher(); + Dispatcher(); - typedef boost::function function; + Handler addHandler(const std::string& message, const Function& callback); + Handler addHandler(const std::string& message, const Function& callback, + Handler id); - handler addHandler(const std::string& message, const function& callback); - handler addHandler(const std::string& message, const function& callback, - handler id); - - void removeHandler(handler id); + void removeHandler(Handler id); void dispatch(const std::string& message); - void dispatch(const std::string& message, const notification& param); + void dispatch(const std::string& message, const Notification& param); private: - class dispatcher_impl; - boost::shared_ptr impl; + class DispatcherImpl; + boost::shared_ptr impl_; }; -} // namespace dc +} // namespace Mf -#endif // _DISPATCHER_HH_ +#endif // _MOOF_DISPATCHER_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/drawable.hh b/src/Moof/Drawable.hh similarity index 89% rename from src/drawable.hh rename to src/Moof/Drawable.hh index 031cf79..8d93f05 100644 --- a/src/drawable.hh +++ b/src/Moof/Drawable.hh @@ -26,29 +26,29 @@ *******************************************************************************/ -#ifndef _DRAWABLE_HH_ -#define _DRAWABLE_HH_ +#ifndef _MOOF_DRAWABLE_HH_ +#define _MOOF_DRAWABLE_HH_ -#include "math.hh" +#include -namespace dc { +namespace Mf { /** * Interface for anything that can be drawn. */ -class drawable +class Drawable { public: - virtual void draw(scalar alpha) = 0; + virtual void draw(Scalar alpha) = 0; }; -} // namespace dc +} // namespace Mf -#endif // _DRAWABLE_HH_ +#endif // _MOOF_DRAWABLE_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/engine.cc b/src/Moof/Engine.cc similarity index 61% rename from src/engine.cc rename to src/Moof/Engine.cc index 7284799..bcc336c 100644 --- a/src/engine.cc +++ b/src/Moof/Engine.cc @@ -26,32 +26,31 @@ *******************************************************************************/ -#include #include // exit -#include +#include #include +#include #include #include "fastevents.h" -#include "random.hh" -#include "timer.hh" -#include "video.hh" -#include "settings.hh" -#include "dispatcher.hh" - -#include "engine.hh" +#include "Dispatcher.hh" +#include "Engine.hh" +#include "Random.hh" +#include "Settings.hh" +#include "Timer.hh" +#include "Video.hh" -namespace dc { +namespace Mf { -class engine::engine_impl +class Engine::EngineImpl { public: - engine_impl(const std::string& name, int argc, char* argv[], - const std::string& configFile, engine* outer) : - config(argc, argv), + EngineImpl(const std::string& name, int argc, char* argv[], + const std::string& configFile, Engine* outer) : + settings(argc, argv), interface(outer) { if (SDL_Init(SDL_INIT_EVERYTHING | SDL_INIT_EVENTTHREAD) != 0) @@ -63,29 +62,29 @@ public: throw std::runtime_error(FE_GetError()); } - rng::seed(); + setSeed(); - config.loadFromFile(configFile); + settings.loadFromFile(configFile); - screen = video_ptr(new video(name)); - screen->makeActive(); + video = VideoPtr(new Video(name)); + video->makeActive(); double ts = 0.01; - config.get("engine.timestep", ts); - timestep = scalar(ts); + settings.get("engine.timestep", ts); + timestep = Scalar(ts); - long maxfps = 40; - config.getNumber("video.maxfps", maxfps); - drawrate = 1.0 / scalar(maxfps); + long maxFps = 40; + settings.getNumber("video.maxfps", maxFps); + drawRate = 1.0 / Scalar(maxFps); - printfps = false; - config.get("video.printfps", printfps); + printFps = false; + settings.get("video.printfps", printFps); } - ~engine_impl() + ~EngineImpl() { // The video object must be destroyed before we can shutdown SDL. - screen.reset(); + video.reset(); FE_Quit(); SDL_Quit(); @@ -101,15 +100,15 @@ public: int run() { - scalar ticksNow = ticks(); + Scalar ticksNow = getTicks(); - scalar nextStep = ticksNow; - scalar nextDraw = ticksNow; - scalar nextFPSUpdate = ticksNow + 1.0; + Scalar nextStep = ticksNow; + Scalar nextDraw = ticksNow; + Scalar nextFpsUpdate = ticksNow + 1.0; - scalar totalTime = 0.0; - scalar deltaTime = 0.0; - scalar accumulator = timestep; + Scalar totalTime = 0.0; + Scalar deltaTime = 0.0; + Scalar accumulator = timestep; fps = 0; int frameAccum = 0; @@ -117,7 +116,7 @@ public: running = true; do { - scalar newTicks = ticks(); + Scalar newTicks = getTicks(); deltaTime = newTicks - ticksNow; ticksNow = newTicks; @@ -139,31 +138,31 @@ public: { frameAccum++; - if (ticksNow >= nextFPSUpdate) // determine the actual fps + if (ticksNow >= nextFpsUpdate) // determine the actual fps { fps = frameAccum; frameAccum = 0; - nextFPSUpdate += 1.0; - if (ticksNow >= nextFPSUpdate) + nextFpsUpdate += 1.0; + if (ticksNow >= nextFpsUpdate) { - nextFPSUpdate = ticksNow + 1.0; + nextFpsUpdate = ticksNow + 1.0; } - if (printfps) + if (printFps) { std::cout << "FPS: " << fps << std::endl; } } interface->draw(accumulator / timestep); - screen->swap(); + video->swap(); - nextDraw += drawrate; + nextDraw += drawRate; if (ticksNow >= nextDraw) { // we missed some scheduled draws, so reset the schedule - nextDraw = ticksNow + drawrate; + nextDraw = ticksNow + drawRate; } } @@ -178,14 +177,14 @@ public: void dispatchEvents() { - SDL_Event e; + SDL_Event event; - while (FE_PollEvent(&e) == 1) + while (FE_PollEvent(&event) == 1) { - switch (e.type) + switch (event.type) { case SDL_KEYDOWN: - if (e.key.keysym.sym == SDLK_ESCAPE && + if (event.key.keysym.sym == SDLK_ESCAPE && (SDL_GetModState() & KMOD_CTRL) ) { exit(0); @@ -193,87 +192,87 @@ public: break; case SDL_VIDEORESIZE: - screen->resize(e.resize.w, e.resize.h); + video->resize(event.resize.w, event.resize.h); break; } - interface->handleEvent(e); + interface->handleEvent(event); } } - settings config; - dispatcher relay; - video_ptr screen; + Settings settings; + Dispatcher dispatcher; + VideoPtr video; - bool running; + bool running; - scalar timestep; - scalar drawrate; + Scalar timestep; + Scalar drawRate; - long fps; - bool printfps; + long fps; + bool printFps; - engine* interface; + Engine* interface; }; -engine::engine(const std::string& name, int argc, char* argv[], +Engine::Engine(const std::string& name, int argc, char* argv[], const std::string& configFile) : - impl(new engine::engine_impl(name, argc, argv, configFile, this)) {} + impl_(new Engine::EngineImpl(name, argc, argv, configFile, this)) {} -engine::~engine() {} +Engine::~Engine() {} -int engine::run() +int Engine::run() { - return impl->run(); + return impl_->run(); } -void engine::stop() +void Engine::stop() { - impl->running = false; + impl_->running = false; } -void engine::setTimestep(scalar ts) +void Engine::setTimestep(Scalar ts) { - impl->timestep = ts; + impl_->timestep = ts; } -scalar engine::getTimestep() +Scalar Engine::getTimestep() { - return impl->timestep; + return impl_->timestep; } -void engine::setMaxFPS(long maxfps) +void Engine::setMaxFrameRate(long maxFps) { - impl->drawrate = 1.0 / scalar(maxfps); + impl_->drawRate = 1.0 / Scalar(maxFps); } -long engine::getMaxFPS() +long Engine::getMaxFrameRate() { - return long(1.0 / impl->drawrate); + return long(1.0 / impl_->drawRate); } -video& engine::getVideo() +Video& Engine::getVideo() { - return *impl->screen; + return *impl_->video; } -long engine::getFPS() +long Engine::getFrameRate() { - return impl->fps; + return impl_->fps; } -void engine::update(scalar t, scalar dt) {} -void engine::draw(scalar alpha) {} -void engine::handleEvent(const SDL_Event& e) {} +void Engine::update(Scalar t, Scalar dt) {} +void Engine::draw(Scalar alpha) {} +void Engine::handleEvent(const Event& event) {} -} // namespace dc +} // namespace Mf /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/engine.hh b/src/Moof/Engine.hh similarity index 71% rename from src/engine.hh rename to src/Moof/Engine.hh index 98141cb..112b87e 100644 --- a/src/engine.hh +++ b/src/Moof/Engine.hh @@ -26,53 +26,55 @@ *******************************************************************************/ -#ifndef _ENGINE_HH_ -#define _ENGINE_HH_ +#ifndef _MOOF_ENGINE_HH_ +#define _MOOF_ENGINE_HH_ #include -#include "singleton.hh" -#include "event.hh" -#include "dispatcher.hh" +#include +#include +#include +#include -namespace dc { +namespace Mf { -class video; +// forward declaration +class Video; -class engine : public singleton +class Engine : public Singleton { public: - engine(const std::string& name, int argc, char* argv[], + Engine(const std::string& name, int argc, char* argv[], const std::string& configFile); - virtual ~engine(); + virtual ~Engine(); int run(); void stop(); - void setTimestep(scalar ts); - scalar getTimestep(); - void setMaxFPS(long maxfps); - long getMaxFPS(); + void setTimestep(Scalar ts); + Scalar getTimestep(); + void setMaxFrameRate(long maxFps); + long getMaxFrameRate(); - video& getVideo(); - long getFPS(); + Video& getVideo(); + long getFrameRate(); // Override these if you want. - virtual void update(scalar t, scalar dt); - virtual void draw(scalar alpha); - virtual void handleEvent(const event& e); + virtual void update(Scalar t, Scalar dt); + virtual void draw(Scalar alpha); + virtual void handleEvent(const Event& event); private: - class engine_impl; - boost::shared_ptr impl; + class EngineImpl; + boost::shared_ptr impl_; }; -} // namespace dc +} // namespace Mf -#endif // _ENGINE_HH_ +#endif // _MOOF_ENGINE_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/event.hh b/src/Moof/Event.hh similarity index 93% rename from src/event.hh rename to src/Moof/Event.hh index 8ca219a..51d7454 100644 --- a/src/event.hh +++ b/src/Moof/Event.hh @@ -26,13 +26,13 @@ *******************************************************************************/ -#ifndef _EVENT_HH_ -#define _EVENT_HH_ +#ifndef _MOOF_EVENT_HH_ +#define _MOOF_EVENT_HH_ #include -namespace dc { +namespace Mf { // The event handling in SDL is so big that it would take more time than it's @@ -41,12 +41,12 @@ namespace dc { // to work with, and it is not the purpose of this library to completely hide // its dependencies and provide full functionality. -typedef SDL_Event event; +typedef SDL_Event Event; -} // namespace dc +} // namespace Mf -#endif // _EVENT_HH_ +#endif // _MOOF_EVENT_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/Moof/Interpolator.hh b/src/Moof/Interpolator.hh new file mode 100644 index 0000000..87e3acd --- /dev/null +++ b/src/Moof/Interpolator.hh @@ -0,0 +1,268 @@ + +/******************************************************************************* + + 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_INTERPOLATOR_HH_ +#define _MOOF_INTERPOLATOR_HH_ + + +namespace Mf { + + +class Interpolator +{ + void clamp(Scalar& value) + { + if (value > 1.0) + { + switch (mode_) + { + case STOP: + value = 1.0; + stopped_ = true; + break; + case REPEAT: + value -= 1.0; + break; + case OSCILLATE: + value = 2.0 - value; + scale_ *= -1.0; + break; + } + } + else if (value < 0.0) + { + switch (mode_) + { + case STOP: + value = 0.0; + stopped_ = true; + break; + case REPEAT: + value += 1.0; + break; + case OSCILLATE: + value = -value; + scale_ *= -1.0; + break; + } + } + } + +public: + typedef enum + { + STOP = 0, + REPEAT = 1, + OSCILLATE = 2 + } Mode; + + void init(Scalar seconds = 1.0, Mode mode = STOP) + { + scale_ = 1.0 / seconds; + alpha_ = 0.0; + setMode(mode); + } + + + void setMode(Mode mode) + { + mode_ = mode; + stopped_ = false; + } + + + void update(Scalar dt) + { + if (!stopped_) + { + alpha_ += dt * scale_; + clamp(alpha_); + calculate(alpha_); + } + } + + virtual void calculate(Scalar alpha) = 0; + +private: + Scalar alpha_; + Mode mode_; + Scalar scale_; + bool stopped_; +}; + +template +class InterpolatorBase : public Interpolator +{ +public: + void init(Scalar seconds = 1.0, Mode mode = STOP) + { + Interpolator::init(seconds, mode); + + calculate(0.0); // set value + calculate(0.0); // set previous + } + + void calculate(Scalar alpha) + { + previous_ = value_; + calculate(value_, alpha); + } + + virtual void calculate(T& value, Scalar alpha) = 0; + + const T& getValue() + { + return value_; + } + + const T getState(Scalar alpha) + { + return cml::lerp(previous_, value_, alpha); + } + +private: + T value_; + T previous_; +}; + + +template +class BinomialInterpolator : public InterpolatorBase +{ +public: + BinomialInterpolator() {} + + explicit BinomialInterpolator(const T coefficients[D+1], + Scalar seconds = 1.0, Interpolator::Mode mode = Interpolator::STOP) + { + init(coefficients, seconds, mode); + } + + void init(const T coefficients[D+1], Scalar seconds = 1.0, + Interpolator::Mode mode = Interpolator::STOP) + { + Scalar fac[D+1]; + + fac[0] = 1.0; + fac[1] = 1.0; + + // build an array of the computed factorials we will need + for (int i = 2; i <= D; i++) + { + fac[i] = i * fac[i - 1]; + } + + // combine the coefficients for fast updating + for (int i = 0; i <= D; i++) + { + // n! / (k! * (n - k)!) + coefficients_[i] = coefficients[i] * fac[D] / (fac[i] * fac[D - i]); + } + + InterpolatorBase::init(seconds, mode); + } + + + void calculate(T& value, Scalar alpha) + { + Scalar beta = 1.0 - alpha; + + value = coefficients_[0] * std::pow(beta, D); + + for (int i = 1; i <= D; i++) + { + value += coefficients_[i] * std::pow(beta, D - i) * + std::pow(alpha, i); + } + } + +private: + T coefficients_[D+1]; +}; + + +template +class BinomialInterpolator : public InterpolatorBase +{ +public: + BinomialInterpolator() {} + + explicit BinomialInterpolator(const T coefficients[2], Scalar seconds = 1.0, + Interpolator::Mode mode = Interpolator::STOP) + //InterpolatorBase(seconds, mode) + { + init(coefficients, seconds, mode); + } + + void init(const T coefficients[2], Scalar seconds = 1.0, + Interpolator::Mode mode = Interpolator::STOP) + { + a_ = coefficients[0]; + b_ = coefficients[1]; + + InterpolatorBase::init(seconds, mode); + } + + + void calculate(T& value, Scalar alpha) + { + value = cml::lerp(a_, b_, alpha); + } + +private: + T a_; + T b_; +}; + + +// Here are some aliases for more common interpolators. Also see the +// interpolation functions in cml for other types of interpolation such as +// slerp and some multi-alpha interpolators. + +typedef BinomialInterpolator Lerps; // linear +typedef BinomialInterpolator Lerpv2; +typedef BinomialInterpolator Lerpv3; +typedef BinomialInterpolator Lerpv4; + +typedef BinomialInterpolator Qerps; // quadratic +typedef BinomialInterpolator Qerpv2; +typedef BinomialInterpolator Qerpv3; +typedef BinomialInterpolator Qerpv4; + +typedef BinomialInterpolator Cerps; // cubic +typedef BinomialInterpolator Cerpv2; +typedef BinomialInterpolator Cerpv3; +typedef BinomialInterpolator Cerpv4; + + +} // namespace Mf + +#endif // _MOOF_INTERPOLATOR_HH_ + +/** vim: set ts=4 sw=4 tw=80: *************************************************/ + diff --git a/src/math.hh b/src/Moof/Math.hh similarity index 78% rename from src/math.hh rename to src/Moof/Math.hh index ab80dcc..563746e 100644 --- a/src/math.hh +++ b/src/Moof/Math.hh @@ -26,54 +26,52 @@ *******************************************************************************/ -#ifndef _MATH_HH_ -#define _MATH_HH_ +#ifndef _MOOF_MATH_HH_ +#define _MOOF_MATH_HH_ /** - * @file math.hh + * @file Math.hh * General math-related types and functions. */ #include #include -#include - -namespace dc { +namespace Mf { // Basic types. -typedef float scalar; ///< Scalar type. +typedef float Scalar; ///< Scalar type. -typedef cml::vector2f vector2; -typedef cml::vector3f vector3; -typedef cml::vector4f vector4; +typedef cml::vector2f Vector2; +typedef cml::vector3f Vector3; +typedef cml::vector4f Vector4; -typedef cml::matrix33f_c matrix3; -typedef cml::matrix44f_c matrix4; +typedef cml::matrix33f_c Matrix3; +typedef cml::matrix44f_c Matrix4; -typedef cml::quaternionf_p quaternion; +typedef cml::quaternionf_p Quaternion; -typedef vector4 color; +typedef Vector4 Color; -const scalar default_epsilon = 0.00001; +const Scalar EPSILON = 0.000001f; /** * Check the equality of scalars with a certain degree of error allowed. */ -inline bool equals(scalar a, scalar b, scalar epsilon = default_epsilon) +inline bool checkEquality(Scalar a, Scalar b, Scalar epsilon = EPSILON) { return std::abs(a - b) < epsilon; } -} // namespace dc +} // namespace Mf -#endif // _MATH_HH_ +#endif // _MOOF_MATH_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/mippleton.hh b/src/Moof/Mippleton.hh similarity index 91% rename from src/mippleton.hh rename to src/Moof/Mippleton.hh index 16985a3..95d3f21 100644 --- a/src/mippleton.hh +++ b/src/Moof/Mippleton.hh @@ -26,11 +26,11 @@ *******************************************************************************/ -#ifndef _MIPPLETON_HH_ -#define _MIPPLETON_HH_ +#ifndef _MOOF_MIPPLETON_HH_ +#define _MOOF_MIPPLETON_HH_ /** - * @file mippleton.hh + * @file Mippleton.hh * Related to singletons, a mippleton is an object which can be obtained * globally using a unique name. Unlike singletons, there can be multiple * mippletons per class, each with a different name or identifier. Mippletons @@ -42,11 +42,11 @@ #include -namespace dc { +namespace Mf { template -class mippleton +class Mippleton { typedef std::pair ptr_value_t; typedef std::pair ptr_map_pair_t; @@ -56,7 +56,7 @@ class mippleton std::string name_; public: - explicit mippleton(const std::string& name) : name_(name) {} + explicit Mippleton(const std::string& name) : name_(name) {} inline const std::string& getName() const { @@ -98,12 +98,12 @@ public: }; template -std::map > mippleton::ptrs_; +std::map > Mippleton::ptrs_; -} // namespace dc +} // namespace Mf -#endif // _MIPPLETON_HH_ +#endif // _MOOF_MIPPLETON_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/opengl.hh b/src/Moof/OpenGL.hh similarity index 87% rename from src/opengl.hh rename to src/Moof/OpenGL.hh index aa95164..0e793f6 100644 --- a/src/opengl.hh +++ b/src/Moof/OpenGL.hh @@ -26,20 +26,12 @@ *******************************************************************************/ -#ifndef _OPENGL_HH_ -#define _OPENGL_HH_ - -#ifdef __APPLE__ -#include -#include -#include -#else -#include -#include -#include -#endif - -#endif // _OPENGL_HH_ +#ifndef _MOOF_OPENGL_HH_ +#define _MOOF_OPENGL_HH_ + +#include + +#endif // _MOOF_OPENGL_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/profiler.hh b/src/Moof/Profiler.hh similarity index 91% rename from src/profiler.hh rename to src/Moof/Profiler.hh index 7b38e52..40199df 100644 --- a/src/profiler.hh +++ b/src/Moof/Profiler.hh @@ -26,27 +26,27 @@ *******************************************************************************/ -#ifndef _PROFILER_HH_ -#define _PROFILER_HH_ +#ifndef _MOOF_PROFILER_HH_ +#define _MOOF_PROFILER_HH_ /** - * @file profiler.hh + * @file Profiler.hh * Braindead-simple profiler. */ #include -namespace dc { +namespace Mf { -class profiler +class Profiler { public: - profiler(const char* name = "") + Profiler(const char* name = "") { start(name); } - ~profiler() + ~Profiler() { stop(); } @@ -74,10 +74,10 @@ private: std::clock_t begin; }; -} // namespace dc +} // namespace Mf -#endif // _PROFILER_HH_ +#endif // _MOOF_PROFILER_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/random.cc b/src/Moof/Random.cc similarity index 82% rename from src/random.cc rename to src/Moof/Random.cc index 6cd25cf..a881008 100644 --- a/src/random.cc +++ b/src/Moof/Random.cc @@ -26,30 +26,31 @@ *******************************************************************************/ +#include // ULONG_MAX +#include // log #include // srand, rand, RAND_MAX #include // time -#include // log -#include // ULONG_MAX -#include "random.hh" +#include "Random.hh" + +namespace Mf { -namespace rng { -unsigned seed(unsigned theSeed) +unsigned setSeed(unsigned theSeed) { srand(theSeed); return theSeed; } -unsigned seed() +unsigned setSeed() { - return seed(time(0)); + return setSeed(time(0)); } template -T get() +T getRandom() { const float ln2 = 0.693147; static const unsigned bitsPerPiece = std::log(float(RAND_MAX)) / ln2; @@ -72,46 +73,46 @@ T get() template <> -bool get() +bool getRandom() { return rand() % 2; } template -T get(T lower, T upper) +T getRandom(T lower, T upper) { - unsigned short randInt = get(); + unsigned short randInt = getRandom(); return lower + T(randInt % (upper - lower + 1)); } template <> -float get(float lower, float upper) +float getRandom(float lower, float upper) { - unsigned long randInt = get(); + unsigned long randInt = getRandom(); return (float(randInt) / float(ULONG_MAX)) * (upper - lower) + lower; } template <> -double get(double lower, double upper) +double getRandom(double lower, double upper) { - unsigned long long randInt = get(); + unsigned long long randInt = getRandom(); return (double(randInt) / double(ULLONG_MAX)) * (upper - lower) + lower; } template <> -float get() +float getRandom() { - return get(0.0, 1.0); + return getRandom(0.0, 1.0); } template <> -double get() +double getRandom() { - return get(0.0, 1.0); + return getRandom(0.0, 1.0); } -}; // namespace rng +}; // namespace Mf /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/random.hh b/src/Moof/Random.hh similarity index 88% rename from src/random.hh rename to src/Moof/Random.hh index ac308c8..3e6b1cf 100644 --- a/src/random.hh +++ b/src/Moof/Random.hh @@ -26,16 +26,16 @@ *******************************************************************************/ -#ifndef _RNG_RANDOM_HH_ -#define _RNG_RANDOM_HH_ +#ifndef _MOOF_RANDOM_HH_ +#define _MOOF_RANDOM_HH_ /** - * @file random.hh + * @file Random.hh * Simple pseudo-random number generators. */ -namespace rng { +namespace Mf { /** * Provide the RNG with a seed. @@ -43,14 +43,14 @@ namespace rng { * @return theSeed */ -unsigned seed(unsigned theSeed); +unsigned setSeed(unsigned theSeed); /** * Seed the RNG with the current time. This is good enough in most cases. * @return The seed used. */ -unsigned seed(); +unsigned setSeed(); /** @@ -59,7 +59,7 @@ unsigned seed(); */ template -T get(); +T getRandom(); /** @@ -68,7 +68,7 @@ T get(); */ template <> -bool get(); +bool getRandom(); /** @@ -79,7 +79,7 @@ bool get(); */ template -T get(T lower, T upper); +T getRandom(T lower, T upper); /** @@ -90,7 +90,7 @@ T get(T lower, T upper); */ template <> -float get(float lower, float upper); +float getRandom(float lower, float upper); /** * Get a random double with a limited domain. @@ -100,7 +100,7 @@ float get(float lower, float upper); */ template <> -double get(double lower, double upper); +double getRandom(double lower, double upper); /** * Get a random float with a domain limited to [0.0, 1.0]. @@ -108,7 +108,7 @@ double get(double lower, double upper); */ template <> -float get(); +float getRandom(); /** * Get a random double with a domain limited to [0.0, 1.0]. @@ -116,13 +116,13 @@ float get(); */ template <> -double get(); +double getRandom(); -}; // namespace rng +} // namespace Mf -#endif // _RNG_RANDOM_HH_ +#endif // _MOOF_RANDOM_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/resource.cc b/src/Moof/Resource.cc similarity index 81% rename from src/resource.cc rename to src/Moof/Resource.cc index 16b5f21..5efe8f5 100644 --- a/src/resource.cc +++ b/src/Moof/Resource.cc @@ -28,19 +28,20 @@ #include -#include "resource.hh" +#include "Resource.hh" -namespace dc { +namespace Mf { -std::vector resource::searchPaths_; +// static member +std::vector Resource::searchPaths_; -resource::~resource() {} +Resource::~Resource() {} -void resource::addSearchPath(const std::string& directory) +void Resource::addSearchPath(const std::string& directory) { // add a slash if there isn't one already if (directory[directory.length() - 1] != '/') @@ -53,16 +54,16 @@ void resource::addSearchPath(const std::string& directory) } } -std::string resource::getPathToResource(const std::string& name) +std::string Resource::getPathToResource(const std::string& name) { - std::vector::iterator i; + std::vector::iterator it; - for (i = searchPaths_.begin(); i != searchPaths_.end(); i++) + for (it = searchPaths_.begin(); it != searchPaths_.end(); it++) { - std::string fullPath(*i); + std::string fullPath(*it); fullPath += name; - // TODO access(2) is not all that portable + // TODO this could be more portable if (access(fullPath.c_str(), R_OK) == 0) { return fullPath; @@ -74,7 +75,7 @@ std::string resource::getPathToResource(const std::string& name) } -} // namespace dc +} // namespace Mf /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/resource.hh b/src/Moof/Resource.hh similarity index 87% rename from src/resource.hh rename to src/Moof/Resource.hh index c5020f6..716e906 100644 --- a/src/resource.hh +++ b/src/Moof/Resource.hh @@ -26,12 +26,12 @@ *******************************************************************************/ -#ifndef _RESOURCE_HH_ -#define _RESOURCE_HH_ +#ifndef _MOOF_RESOURCE_HH_ +#define _MOOF_RESOURCE_HH_ /** - * @file resource.hh - * Parent class of textures, sounds, other assets. + * @file Resource.hh + * Interface for textures, sounds, and other types of resources. */ #include @@ -39,23 +39,23 @@ #include -namespace dc { +namespace Mf { /** * Generic resource class. */ -class resource +class Resource { public: - struct exception : public std::runtime_error + struct Exception : public std::runtime_error { - explicit exception(const std::string& what_arg) : + explicit Exception(const std::string& what_arg) : std::runtime_error(what_arg) {} }; - virtual ~resource(); + virtual ~Resource(); /** @@ -79,9 +79,9 @@ private: }; -} // namespace dc +} // namespace Mf -#endif // _RESOURCE_HH_ +#endif // _MOOF_RESOURCE_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/scene.cc b/src/Moof/Scene.cc similarity index 70% rename from src/scene.cc rename to src/Moof/Scene.cc index 04754ea..f4dd1c0 100644 --- a/src/scene.cc +++ b/src/Moof/Scene.cc @@ -30,54 +30,53 @@ #include #include -#include "aabb.hh" -#include "camera.hh" -#include "cullable.hh" -#include "deserializer.hh" -#include "drawable.hh" -#include "math.hh" -#include "mippleton.hh" -#include "opengl.hh" -#include "serializable.hh" -#include "tilemap.hh" +#include "Aabb.hh" +#include "Camera.hh" +#include "Cullable.hh" +#include "Deserializer.hh" +#include "Drawable.hh" +#include "Math.hh" +#include "Mippleton.hh" +#include "OpenGL.hh" +#include "Scene.hh" +#include "Serializable.hh" +#include "Tilemap.hh" -#include "scene.hh" +namespace Mf { -namespace dc { - -class scene::scene_impl : public mippleton +class Scene::SceneImpl : public Mippleton { - class scenery : public drawable, public cullable + class Scenery : public Drawable, public Cullable { public: - scenery(const matrix4& transform, const std::string& textureName) : + Scenery(const Matrix4& transform, const std::string& textureName) : transformation(transform), image(textureName) {} protected: - matrix4 transformation; - tilemap image; + Matrix4 transformation; + Tilemap image; bool blending; long detail; bool fog; }; - class tiles : public scenery + class TilePanel : public Scenery { public: - tiles(const matrix4& transform, const std::string& textureName, - serializable_ptr root) : - scenery(transform, textureName), + TilePanel(const Matrix4& transform, const std::string& textureName, + SerializablePtr root) : + Scenery(transform, textureName), width(1), height(1) { - std::map rootObj; + std::map rootObj; if (root->get(rootObj)) { - std::map::iterator it; + std::map::iterator it; if ((it = rootObj.find("width")) != rootObj.end()) { @@ -85,11 +84,11 @@ class scene::scene_impl : public mippleton } if ((it = rootObj.find("tiles")) != rootObj.end()) { - std::vector theTiles; + std::vector theTiles; if ((*it).second->get(theTiles)) { - std::vector::iterator jt; + std::vector::iterator jt; height = theTiles.size() / width; int w, h; @@ -99,7 +98,7 @@ class scene::scene_impl : public mippleton for (h = height - 1, jt = theTiles.begin(); jt != theTiles.end(); h--) { - std::vector row; + std::vector row; for (w = 0; w < width && jt != theTiles.end(); w++, jt++) @@ -108,7 +107,7 @@ class scene::scene_impl : public mippleton if ((*jt)->get(index)) { - row.push_back(unsigned(index)); + row.push_back(Tilemap::Index(index)); } } @@ -119,7 +118,7 @@ class scene::scene_impl : public mippleton } } - void draw(scalar alpha) + void draw(Scalar alpha) { glPushMatrix(); //std::cout << "transforming..." << std::endl; @@ -130,15 +129,15 @@ class scene::scene_impl : public mippleton image.bind(); long x, y; - scalar xf, yf; + Scalar xf, yf; for (y = 0, yf = 0.0; y < height; y++, yf += 1.0) { for (x = 0, xf = 0.0; x < width; x++, xf += 1.0) { - scalar texCoords[8]; + Scalar texCoords[8]; - unsigned index = indices[y][x]; + Tilemap::Index index = indices[y][x]; if (image.getTileCoords(index, texCoords)) { @@ -159,36 +158,36 @@ class scene::scene_impl : public mippleton glPopMatrix(); } - bool isVisible(const camera& cam) + bool isVisible(const Camera& cam) { return true; } private: long width, height; - std::vector > indices; + std::vector > indices; }; - class billboard : public scenery + class Billboard : public Scenery { public: - billboard(const matrix4& transform, const std::string& textureName, - serializable_ptr root) : - scenery(transform, textureName), + Billboard(const Matrix4& transform, const std::string& textureName, + SerializablePtr root) : + Scenery(transform, textureName), index(0) { - std::map rootObj; + std::map rootObj; if (root->get(rootObj)) { - std::map::iterator it; + std::map::iterator it; if ((it = rootObj.find("tile")) != rootObj.end()) { long value; if ((*it).second->get(value)) { - index = unsigned(value); + index = Tilemap::Index(value); } } } @@ -196,7 +195,7 @@ class scene::scene_impl : public mippleton image.getTileCoords(index, texCoords); } - void draw(scalar alpha) + void draw(Scalar alpha) { glPushMatrix(); glMultMatrixf(transformation.data()); @@ -218,20 +217,20 @@ class scene::scene_impl : public mippleton glPopMatrix(); } - bool isVisible(const camera& cam) + bool isVisible(const Camera& cam) { return false; } private: - unsigned index; - scalar texCoords[8]; + Tilemap::Index index; + Scalar texCoords[8]; }; - static bool loadBox(aabb& theBox, serializable_ptr obj) + static bool loadBox(Aabb& theBox, SerializablePtr obj) { - std::vector numbers; + std::vector numbers; if (obj->get(numbers)) { @@ -250,23 +249,23 @@ class scene::scene_impl : public mippleton } public: - scene_impl(const std::string& name) : - mippleton(name) + SceneImpl(const std::string& name) : + Mippleton(name) { loadFromFile(); } - void loadInstructions(serializable_ptr root) + void loadInstructions(SerializablePtr root) { - std::vector rootObj; + std::vector rootObj; if (root->get(rootObj)) { - std::vector::iterator it; + std::vector::iterator it; - matrix4 transform; - std::string texture; + Matrix4 transform; + std::string texture; for (it = rootObj.begin(); it != rootObj.end(); it++) { @@ -281,14 +280,14 @@ public: } else if (instruction == "translate") { - std::vector values; + std::vector values; it++; if ((*it)->get(values)) { - vector3 vec; + Vector3 vec; - for (unsigned i = 0; i < values.size(); i++) + for (size_t i = 0; i < values.size(); i++) { double value; @@ -298,7 +297,7 @@ public: } } - matrix4 translation; + Matrix4 translation; cml::matrix_translation(translation, vec); transform = translation * transform; //std::cout << "TRANSLATE\t" << vec << std::endl @@ -307,7 +306,7 @@ public: } else if (instruction == "scale") { - std::vector values; + std::vector values; it++; if ((*it)->get(values)) @@ -318,17 +317,17 @@ public: values[0]->getNumber(value); - matrix4 scaling; - cml::matrix_uniform_scale(scaling, scalar(value)); + Matrix4 scaling; + cml::matrix_uniform_scale(scaling, Scalar(value)); transform = scaling * transform; //std::cout << "SCALE\t\t" << value << std::endl //<< transform << std::endl; } else if (values.size() == 3) { - vector3 vec; + Vector3 vec; - for (unsigned i = 0; i < values.size(); i++) + for (size_t i = 0; i < values.size(); i++) { double value; @@ -338,7 +337,7 @@ public: } } - matrix4 scaling; + Matrix4 scaling; cml::matrix_scale(scaling, vec); transform = scaling * transform; //std::cout << "SCALE\t\t" << vec << std::endl @@ -348,7 +347,7 @@ public: } else if (instruction == "rotate") { - std::vector values; + std::vector values; it++; if ((*it)->get(values)) @@ -377,7 +376,7 @@ public: } cml::matrix_rotate_about_local_axis(transform, - axisIndex, scalar(value * cml::constantsd::rad_per_deg())); + axisIndex, Scalar(value * cml::constantsd::rad_per_deg())); //std::cout << "ROTATE\t" << axis << " " << value << std::endl //<< transform << std::endl; } @@ -394,8 +393,9 @@ public: //std::cout << transform << std::endl; it++; - tiles* newTiles = new tiles(transform, texture, *it); - boost::shared_ptr sceneItem(newTiles); + TilePanel* tilePanel = new TilePanel(transform, texture, + *it); + boost::shared_ptr sceneItem(tilePanel); objects.push_back(sceneItem); } else if (instruction == "billboard") @@ -404,9 +404,9 @@ public: //std::cout << transform << std::endl; it++; - billboard* newBB = new billboard(transform, texture, + Billboard* billboard = new Billboard(transform, texture, *it); - boost::shared_ptr sceneItem(newBB); + boost::shared_ptr sceneItem(billboard); objects.push_back(sceneItem); } } @@ -417,19 +417,19 @@ public: void loadFromFile() { - std::string filePath = scene::getPathToResource(getName()); + std::string filePath = Scene::getPathToResource(getName()); - deserializer in(filePath, true); + Deserializer deserializer(filePath, true); - serializable_ptr root = in.deserialize(); + SerializablePtr root = deserializer.deserialize(); if (root) { - std::map rootObj; + std::map rootObj; if (root->get(rootObj)) { - std::map::iterator it; + std::map::iterator it; if ((it = rootObj.find("playfield_bounds")) != rootObj.end()) { @@ -448,9 +448,9 @@ public: } - void draw(scalar alpha) + void draw(Scalar alpha) { - scenery_list::iterator it; + SceneryVector::iterator it; for (it = objects.begin(); it != objects.end(); it++) { @@ -460,23 +460,23 @@ public: } - aabb playfieldBounds; - aabb maximumBounds; + Aabb playfieldBounds; + Aabb maximumBounds; - typedef std::vector > scenery_list; - scenery_list objects; + typedef std::vector > SceneryVector; + SceneryVector objects; }; -scene::scene(const std::string& name) : +Scene::Scene(const std::string& name) : // pass through - impl(scene::scene_impl::retain(name), &scene::scene_impl::release) {} + impl_(Scene::SceneImpl::retain(name), &Scene::SceneImpl::release) {} -void scene::draw(scalar alpha) +void Scene::draw(Scalar alpha) { // pass through - impl->draw(alpha); + impl_->draw(alpha); } @@ -485,13 +485,13 @@ void scene::draw(scalar alpha) * "scenes" subdirectory of any of the searched directories. */ -std::string scene::getPathToResource(const std::string& name) +std::string Scene::getPathToResource(const std::string& name) { - return resource::getPathToResource("scenes/" + name + ".json"); + return Resource::getPathToResource("scenes/" + name + ".json"); } -} // namespace dc +} // namespace Mf /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/scene.hh b/src/Moof/Scene.hh similarity index 84% rename from src/scene.hh rename to src/Moof/Scene.hh index 2938db8..66a54a9 100644 --- a/src/scene.hh +++ b/src/Moof/Scene.hh @@ -26,37 +26,38 @@ *******************************************************************************/ -#ifndef _SCENE_HH_ -#define _SCENE_HH_ +#ifndef _MOOF_SCENE_HH_ +#define _MOOF_SCENE_HH_ #include + #include -#include "resource.hh" -#include "drawable.hh" +#include +#include -namespace dc { +namespace Mf { -class scene : public resource, public drawable +class Scene : public Resource, public Drawable { public: - scene(const std::string& name); + Scene(const std::string& name); - void draw(scalar alpha); + void draw(Scalar alpha); static std::string getPathToResource(const std::string& name); private: - class scene_impl; - boost::shared_ptr impl; + class SceneImpl; + boost::shared_ptr impl_; }; -} // namespace dc +} // namespace Mf -#endif // _SCENE_HH_ +#endif // _MOOF_SCENE_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/serializable.cc b/src/Moof/Serializable.cc similarity index 74% rename from src/serializable.cc rename to src/Moof/Serializable.cc index 1da0613..583fce3 100644 --- a/src/serializable.cc +++ b/src/Moof/Serializable.cc @@ -26,60 +26,60 @@ *******************************************************************************/ -#include "serializable.hh" +#include "Serializable.hh" -namespace dc { +namespace Mf { -serializable::~serializable() +Serializable::~Serializable() { } -bool serializable::get(long& value) +bool Serializable::get(long& value) { return false; } -bool serializable::get(double& value) +bool Serializable::get(double& value) { return false; } -bool serializable::get(bool& value) +bool Serializable::get(bool& value) { return false; } -bool serializable::get(std::string& value) +bool Serializable::get(std::string& value) { return false; } -bool serializable::get(std::wstring& value) +bool Serializable::get(std::wstring& value) { return false; } -bool serializable::get(std::vector& value) +bool Serializable::get(std::vector& value) { return false; } -bool serializable::get(std::map& value) +bool Serializable::get(std::map& value) { return false; } -bool serializable::isNull() +bool Serializable::isNull() { return false; } -bool serializable::getNumber(long& value) +bool Serializable::getNumber(long& value) { if (get(value)) { @@ -87,17 +87,17 @@ bool serializable::getNumber(long& value) } else { - double dValue; - if (get(dValue)) + double doubleValue; + if (get(doubleValue)) { - value = long(dValue); + value = long(doubleValue); return true; } } return false; } -bool serializable::getNumber(double& value) +bool Serializable::getNumber(double& value) { if (get(value)) { @@ -105,10 +105,10 @@ bool serializable::getNumber(double& value) } else { - long lValue; - if (get(lValue)) + long longValue; + if (get(longValue)) { - value = double(lValue); + value = double(longValue); return true; } } @@ -116,7 +116,7 @@ bool serializable::getNumber(double& value) } -} // namespace dc +} // namespace Mf /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/serializable.hh b/src/Moof/Serializable.hh similarity index 50% rename from src/serializable.hh rename to src/Moof/Serializable.hh index 967b213..458dbe8 100644 --- a/src/serializable.hh +++ b/src/Moof/Serializable.hh @@ -26,29 +26,33 @@ *******************************************************************************/ -#ifndef _SERIALIZABLE_HH_ -#define _SERIALIZABLE_HH_ +#ifndef _MOOF_SERIALIZABLE_HH_ +#define _MOOF_SERIALIZABLE_HH_ #include -#include #include +#include #include -#include "stringtools.hh" -#include "serializer.hh" -#include "deserializer.hh" +#include +#include +#include + +namespace Mf { -namespace dc { +/** + * Interface for a type which can be serialized and deserialized. + */ -class serializable +class Serializable { public: - virtual ~serializable(); + virtual ~Serializable(); - virtual void serialize(serializer& out) const = 0; - virtual void deserialize(deserializer& in) = 0; + virtual void serialize(Serializer& out) const = 0; + virtual void deserialize(Deserializer& in) = 0; virtual void print() const = 0; @@ -57,12 +61,12 @@ public: virtual bool get(bool& value); virtual bool get(std::string& value); virtual bool get(std::wstring& value); - virtual bool get(std::vector& value); - virtual bool get(std::map& value); + virtual bool get(std::vector& value); + virtual bool get(std::map& value); /* * To get a number value which may have been parsed as either an integer or - * double, use these instead. + * double, use these getters instead. */ bool getNumber(long&); @@ -73,58 +77,60 @@ public: template -class wrapper : public serializable +class SerializableBase : public Serializable { public: - wrapper() {} - wrapper(const T& var) : variable(var) {} + SerializableBase() {} + SerializableBase(const T& value) : + value_(value) {} - void serialize(serializer& out) const; - void deserialize(deserializer& in); + void serialize(Serializer& out) const; + void deserialize(Deserializer& in); void print() const; bool get(T& value); public: - T variable; + T value_; }; -class null : public serializable +class SerializableNull : public Serializable { public: - null() {} - void serialize(serializer& out) const; - void deserialize(deserializer& in); + SerializableNull() {} + void serialize(Serializer& out) const; + void deserialize(Deserializer& in); void print() const; bool isNull(); }; -typedef wrapper wrapped_integer; -typedef wrapper wrapped_real; -typedef wrapper wrapped_boolean; -typedef wrapper wrapped_string; -typedef wrapper wrapped_wstring; -typedef wrapper > wrapped_array; -typedef wrapper > wrapped_dictionary; +typedef SerializableBase SerializableInteger; +typedef SerializableBase SerializableReal; +typedef SerializableBase SerializableBoolean; +typedef SerializableBase SerializableString; +typedef SerializableBase SerializableWideString; +typedef SerializableBase > SerializableArray; +typedef SerializableBase > + SerializableMap; template -inline void wrapper::serialize(serializer& out) const +inline void SerializableBase::serialize(Serializer& out) const { - out.push(variable); + out.push(value_); } template <> inline void -wrapper >::serialize(serializer& out) const +SerializableBase >::serialize(Serializer& out) const { out.pushArrayHead(); - std::vector::const_iterator i; - for (i = variable.begin(); i < variable.end(); i++) + std::vector::const_iterator i; + for (i = value_.begin(); i < value_.end(); i++) { (*i)->serialize(out); } @@ -134,12 +140,12 @@ wrapper >::serialize(serializer& out) const template <> inline void -wrapper >::serialize(serializer& out) const +SerializableBase >::serialize(Serializer& out) const { out.pushMapHead(); - std::map::const_iterator i; - for (i = variable.begin(); i != variable.end(); i++) + std::map::const_iterator i; + for (i = value_.begin(); i != value_.end(); i++) { out.push((*i).first); (*i).second->serialize(out); @@ -148,28 +154,28 @@ wrapper >::serialize(serializer& out) con out.pushMapTail(); } -inline void null::serialize(serializer& out) const +inline void SerializableNull::serialize(Serializer& out) const { out.pushNull(); } template -inline void wrapper::deserialize(deserializer& in) +inline void SerializableBase::deserialize(Deserializer& in) { in.pop(); } template <> -inline void wrapper >::deserialize(deserializer& in) +inline void SerializableBase >::deserialize(Deserializer& in) { - serializable_ptr obj; + SerializablePtr obj; in.pop(); while (obj = in.deserialize()) { - variable.push_back(serializable_ptr(obj)); + value_.push_back(SerializablePtr(obj)); } in.pop(); @@ -177,9 +183,9 @@ inline void wrapper >::deserialize(deserializer& i template <> inline void -wrapper >::deserialize(deserializer& in) +SerializableBase >::deserialize(Deserializer& in) { - serializable_ptr obj; + SerializablePtr obj; in.pop(); @@ -188,65 +194,65 @@ wrapper >::deserialize(deserializer& in) std::string key; if (obj->get(key)) { - variable[key] = in.deserialize(); + value_[key] = in.deserialize(); } } in.pop(); } -inline void null::deserialize(deserializer& in) +inline void SerializableNull::deserialize(Deserializer& in) { in.pop(); } template -inline void wrapper::print() const +inline void SerializableBase::print() const { - std::cout << std::boolalpha << typeid(T).name() << "(" << variable << ")"; + std::cout << std::boolalpha << typeid(T).name() << "(" << value_ << ")"; } template <> -inline void wrapper::print() const +inline void SerializableBase::print() const { - std::wcout << variable; + std::wcout << value_; } template <> -inline void wrapper >::print() const +inline void SerializableBase >::print() const { std::cout << "array"; } template <> -inline void wrapper >::print() const +inline void SerializableBase >::print() const { - std::cout << "dictionary"; + std::cout << "map"; } -inline void null::print() const +inline void SerializableNull::print() const { std::cout << "null"; } template -inline bool wrapper::get(T& value) +inline bool SerializableBase::get(T& value) { - value = variable; + value = value_; return true; } -inline bool null::isNull() +inline bool SerializableNull::isNull() { return true; } -} // namespace dc +} // namespace Mf -#endif // _SERIALIZABLE_HH_ +#endif // _MOOF_SERIALIZABLE_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/serializer.cc b/src/Moof/Serializer.cc similarity index 56% rename from src/serializer.cc rename to src/Moof/Serializer.cc index 7b7596d..a93eb5a 100644 --- a/src/serializer.cc +++ b/src/Moof/Serializer.cc @@ -30,28 +30,28 @@ #include -#include "stringtools.hh" -#include "serializer.hh" +#include "Serializer.hh" +#include "StringTools.hh" -namespace dc { +namespace Mf { -class serializer::serializer_impl +class Serializer::SerializerImpl { public: - serializer_impl(const std::string& filePath, const std::string& indent = "") + SerializerImpl(const std::string& filePath, const std::string& indent = "") { std::ofstream* output = new std::ofstream(filePath.c_str()); init(*output, true, indent); } - serializer_impl(std::ostream& output, const std::string& indent = "") + SerializerImpl(std::ostream& output, const std::string& indent = "") { init(output, false, indent); } - ~serializer_impl() + ~SerializerImpl() { if (deleteWhenDone) { @@ -65,22 +65,22 @@ public: switch (err) { case yajl_gen_generation_complete: - throw serializer::exception("the archive has already terminated"); + throw Serializer::Exception("the archive has already terminated"); case yajl_gen_keys_must_be_strings: - throw serializer::exception("map keys must be strings"); + throw Serializer::Exception("map keys must be strings"); case yajl_max_depth_exceeded: - throw serializer::exception("maximum archive depth exceeded"); + throw Serializer::Exception("maximum archive depth exceeded"); case yajl_gen_in_error_state: - throw serializer::exception("serializer already in error state"); + throw Serializer::Exception("serializer already in error state"); case yajl_gen_status_ok: ; // There is no error here. Move along... } } - yajl_gen gen; + yajl_gen gen; - std::ostream* out; - bool deleteWhenDone; + std::ostream* out; + bool deleteWhenDone; private: void init(std::ostream& output, bool deleteOut, const std::string& indent) @@ -94,7 +94,7 @@ private: { config.beautify = true; config.indentString = 0; - // FIXME: a yajl bug prevents using heap-allocated strings + // FIXME a yajl bug prevents using heap-allocated strings //config.indentString = indent.c_str(); } else @@ -106,103 +106,103 @@ private: }; -serializer::serializer(const std::string& filePath, const std::string& indent) : +Serializer::Serializer(const std::string& filePath, const std::string& indent) : // pass through - impl(new serializer::serializer_impl(filePath, indent)) {} + impl_(new Serializer::SerializerImpl(filePath, indent)) {} -serializer::serializer(std::ostream& output, const std::string& indent) : +Serializer::Serializer(std::ostream& output, const std::string& indent) : // pass through - impl(new serializer::serializer_impl(output, indent)) {} + impl_(new Serializer::SerializerImpl(output, indent)) {} -serializer::~serializer() +Serializer::~Serializer() { flush(); } -void serializer::push(long value) +void Serializer::push(long value) { - yajl_gen_status stat = yajl_gen_integer(impl->gen, value); + yajl_gen_status stat = yajl_gen_integer(impl_->gen, value); if (stat != yajl_gen_status_ok) - serializer::serializer_impl::throwError(stat); + Serializer::SerializerImpl::throwError(stat); } -void serializer::push(double value) +void Serializer::push(double value) { - yajl_gen_status stat = yajl_gen_double(impl->gen, value); + yajl_gen_status stat = yajl_gen_double(impl_->gen, value); if (stat != yajl_gen_status_ok) - serializer::serializer_impl::throwError(stat); + Serializer::SerializerImpl::throwError(stat); } -void serializer::push(bool value) +void Serializer::push(bool value) { - yajl_gen_status stat = yajl_gen_bool(impl->gen, value); + yajl_gen_status stat = yajl_gen_bool(impl_->gen, value); if (stat != yajl_gen_status_ok) - serializer::serializer_impl::throwError(stat); + Serializer::SerializerImpl::throwError(stat); } -void serializer::push(const std::string& value) +void Serializer::push(const std::string& value) { - yajl_gen_status stat = yajl_gen_string(impl->gen, + yajl_gen_status stat = yajl_gen_string(impl_->gen, (const unsigned char*)value.c_str(), value.length()); if (stat != yajl_gen_status_ok) - serializer::serializer_impl::throwError(stat); + Serializer::SerializerImpl::throwError(stat); } -void serializer::push(const std::wstring& value) +void Serializer::push(const std::wstring& value) { push(wideToMulti(value)); } -void serializer::pushNull() +void Serializer::pushNull() { - yajl_gen_status stat = yajl_gen_null(impl->gen); + yajl_gen_status stat = yajl_gen_null(impl_->gen); if (stat != yajl_gen_status_ok) - serializer::serializer_impl::throwError(stat); + Serializer::SerializerImpl::throwError(stat); } -void serializer::pushMapHead() +void Serializer::pushMapHead() { - yajl_gen_status stat = yajl_gen_map_open(impl->gen); + yajl_gen_status stat = yajl_gen_map_open(impl_->gen); if (stat != yajl_gen_status_ok) - serializer::serializer_impl::throwError(stat); + Serializer::SerializerImpl::throwError(stat); } -void serializer::pushMapTail() +void Serializer::pushMapTail() { - yajl_gen_status stat = yajl_gen_map_close(impl->gen); + yajl_gen_status stat = yajl_gen_map_close(impl_->gen); if (stat != yajl_gen_status_ok) - serializer::serializer_impl::throwError(stat); + Serializer::SerializerImpl::throwError(stat); } -void serializer::pushArrayHead() +void Serializer::pushArrayHead() { - yajl_gen_status stat = yajl_gen_array_open(impl->gen); + yajl_gen_status stat = yajl_gen_array_open(impl_->gen); if (stat != yajl_gen_status_ok) - serializer::serializer_impl::throwError(stat); + Serializer::SerializerImpl::throwError(stat); } -void serializer::pushArrayTail() +void Serializer::pushArrayTail() { - yajl_gen_status stat = yajl_gen_array_close(impl->gen); + yajl_gen_status stat = yajl_gen_array_close(impl_->gen); if (stat != yajl_gen_status_ok) - serializer::serializer_impl::throwError(stat); + Serializer::SerializerImpl::throwError(stat); } -void serializer::flush() +void Serializer::flush() { const unsigned char* buffer; unsigned length; - yajl_gen_get_buf(impl->gen, &buffer, &length); - impl->out->write((const char*)buffer, length); - yajl_gen_clear(impl->gen); + yajl_gen_get_buf(impl_->gen, &buffer, &length); + impl_->out->write((const char*)buffer, length); + yajl_gen_clear(impl_->gen); } -} // namespace dc +} // namespace Mf /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/serializer.hh b/src/Moof/Serializer.hh similarity index 86% rename from src/serializer.hh rename to src/Moof/Serializer.hh index 206a793..7d54834 100644 --- a/src/serializer.hh +++ b/src/Moof/Serializer.hh @@ -26,25 +26,25 @@ *******************************************************************************/ -#ifndef _SERIALIZER_HH_ -#define _SERIALIZER_HH_ +#ifndef _MOOF_SERIALIZER_HH_ +#define _MOOF_SERIALIZER_HH_ /** - * @file serializer.hh + * @file Serializer.hh * Serialize structures and types for output on a stream. */ -#include -#include #include +#include +#include #include -namespace dc { +namespace Mf { -class serializer +class Serializer { public: @@ -57,10 +57,10 @@ public: * but will be tightly packed. */ - serializer(const std::string& filePath, const std::string& indent = ""); - serializer(std::ostream& output, const std::string& indent = ""); + Serializer(const std::string& filePath, const std::string& indent = ""); + Serializer(std::ostream& output, const std::string& indent = ""); - ~serializer(); + ~Serializer(); /** * Push various types of data onto the stream. @@ -99,21 +99,21 @@ public: * This exception is thrown for serializer-related exceptional errors. */ - struct exception : std::runtime_error + struct Exception : std::runtime_error { - explicit exception(const std::string& what_arg) : + explicit Exception(const std::string& what_arg) : std::runtime_error(what_arg) {} }; private: - class serializer_impl; - boost::shared_ptr impl; + class SerializerImpl; + boost::shared_ptr impl_; }; -} // namespace dc +} // namespace Mf -#endif // _SERIALIZER_HH_ +#endif // _MOOF_SERIALIZER_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/settings.cc b/src/Moof/Settings.cc similarity index 78% rename from src/settings.cc rename to src/Moof/Settings.cc index 74ab384..d13302d 100644 --- a/src/settings.cc +++ b/src/Moof/Settings.cc @@ -32,19 +32,19 @@ #include -#include "settings.hh" +#include "Settings.hh" -namespace dc { +namespace Mf { -settings::settings(int argc, char* argv[]) +Settings::Settings(int argc, char* argv[]) { parseArgs(argc, argv); } -void settings::parseArgs(int argc, char* argv[]) +void Settings::parseArgs(int argc, char* argv[]) { for (int i = 1; i < argc; i++) { @@ -58,25 +58,25 @@ void settings::parseArgs(int argc, char* argv[]) std::stringstream stream; stream << stringValue << std::endl; - deserializer in(stream); + Deserializer deserializer(stream); try { - serializable_ptr value(in.deserialize()); - map[key] = value; + SerializablePtr value(deserializer.deserialize()); + map_[key] = value; } catch (std::exception e) { // it doesn't deserialize to anything we know, so just store it // as a string - map[key] = serializable_ptr(new wrapped_string(stringValue)); + map_[key] = SerializablePtr(new SerializableString(stringValue)); } } } } -void settings::loadFromFile(const std::string& filePath, bool precedence) +void Settings::loadFromFile(const std::string& filePath, bool precedence) { std::vector paths; boost::split(paths, filePath, boost::is_any_of(":")); @@ -84,7 +84,7 @@ void settings::loadFromFile(const std::string& filePath, bool precedence) loadFromFiles(paths, precedence); } -void settings::loadFromFiles(const std::vector& filePaths, +void Settings::loadFromFiles(const std::vector& filePaths, bool precedence) { std::vector::const_iterator it; @@ -100,27 +100,27 @@ void settings::loadFromFiles(const std::vector& filePaths, boost::replace_first(path, "$HOME", home); } - deserializer in(*it, true); + Deserializer deserializer(*it, true); std::cout << "Looking for a config file at " << path << std::endl; try { - serializable_ptr obj = in.deserialize(); - std::map dict; - if (obj && obj->get(dict)) + SerializablePtr obj = deserializer.deserialize(); + std::map map; + if (obj && obj->get(map)) { if (!precedence) { - map.insert(dict.begin(), dict.end()); + map_.insert(map.begin(), map.end()); } else { - dict.insert(map.begin(), map.end()); - map = dict; + map.insert(map_.begin(), map_.end()); + map_ = map; } } } - catch (deserializer::exception e) + catch (Deserializer::Exception e) { std::cerr << "Cannot load settings from " << *it << " because an exception was thrown: " << e.what() << std::endl; @@ -129,7 +129,7 @@ void settings::loadFromFiles(const std::vector& filePaths, } -} // namepsace dc +} // namepsace Mf /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/settings.hh b/src/Moof/Settings.hh similarity index 75% rename from src/settings.hh rename to src/Moof/Settings.hh index f2a7aed..9c29007 100644 --- a/src/settings.hh +++ b/src/Moof/Settings.hh @@ -26,29 +26,29 @@ *******************************************************************************/ -#ifndef _SETTINGS_HH_ -#define _SETTINGS_HH_ +#ifndef _MOOF_SETTINGS_HH_ +#define _MOOF_SETTINGS_HH_ /** - * @file settings.hh + * @file Settings.hh * Load, store, save program settings. */ -#include #include +#include -#include "singleton.hh" -#include "serializable.hh" +#include +#include -namespace dc { +namespace Mf { -class settings : public singleton +class Settings : public Singleton { public: - settings() {} - settings(int argc, char* argv[]); + Settings() {} + Settings(int argc, char* argv[]); void parseArgs(int argc, char* argv[]); @@ -62,18 +62,18 @@ public: bool getNumber(const std::string& key, T& value); private: - std::map map; + std::map map_; }; template -bool settings::get(const std::string& key, T& value) +bool Settings::get(const std::string& key, T& value) { - std::map::const_iterator i = map.find(key); + std::map::const_iterator it = map_.find(key); - if (i != map.end()) + if (it != map_.end()) { - serializable_ptr obj = (*i).second; + SerializablePtr obj = (*it).second; return obj->get(value); } else @@ -83,13 +83,13 @@ bool settings::get(const std::string& key, T& value) } template -bool settings::getNumber(const std::string& key, T& value) +bool Settings::getNumber(const std::string& key, T& value) { - std::map::const_iterator i = map.find(key); + std::map::const_iterator it = map_.find(key); - if (i != map.end()) + if (it != map_.end()) { - serializable_ptr obj = (*i).second; + SerializablePtr obj = (*it).second; return obj->getNumber(value); } else @@ -98,9 +98,10 @@ bool settings::getNumber(const std::string& key, T& value) } } -} // namepsace dc -#endif // _SETTINGS_HH_ +} // namepsace Mf + +#endif // _MOOF_SETTINGS_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/singleton.hh b/src/Moof/Singleton.hh similarity index 80% rename from src/singleton.hh rename to src/Moof/Singleton.hh index ec0d01e..3d60ff2 100644 --- a/src/singleton.hh +++ b/src/Moof/Singleton.hh @@ -26,39 +26,39 @@ *******************************************************************************/ -#ifndef _SINGLETON_HH_ -#define _SINGLETON_HH_ +#ifndef _MOOF_SINGLETON_HH_ +#define _MOOF_SINGLETON_HH_ #include -namespace dc { +namespace Mf { template -class singleton +class Singleton { static T* ptr_; public: - struct exception : public std::runtime_error + struct Exception : public std::runtime_error { - explicit exception(const std::string& what_arg) : + explicit Exception(const std::string& what_arg) : std::runtime_error(what_arg) {} }; - singleton() + Singleton() { if (!ptr_) { // This hack is from Game Programming Gems. - long long offset = (long long)(T*)1 - (long long)(singleton*)(T*)1; + long long offset = (long long)(T*)1 - (long long)(Singleton*)(T*)1; ptr_ = (T*)((long long)this + offset); } } - ~singleton() + ~Singleton() { - long long offset = (long long)(T*)1 - (long long)(singleton*)(T*)1; + long long offset = (long long)(T*)1 - (long long)(Singleton*)(T*)1; if (ptr_ == (T*)((long long)this + offset)) { ptr_ = 0; @@ -69,7 +69,7 @@ public: { if (!ptr_) { - throw exception("accessing uninstantiated singleton"); + throw Exception("accessing uninstantiated singleton"); } return *ptr_; } @@ -80,12 +80,12 @@ public: } }; -template T* singleton::ptr_ = 0; +template T* Singleton::ptr_ = 0; -} // namespace dc +} // namespace Mf -#endif // _SINGLETON_HH_ +#endif // _MOOF_SINGLETON_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/stringtools.cc b/src/Moof/StringTools.cc similarity index 98% rename from src/stringtools.cc rename to src/Moof/StringTools.cc index 91d2a6c..f4bd967 100644 --- a/src/stringtools.cc +++ b/src/Moof/StringTools.cc @@ -30,10 +30,10 @@ #include "ConvertUTF.h" -#include "stringtools.hh" +#include "StringTools.hh" -namespace dc { +namespace Mf { std::wstring multiToWide(const std::string& multiStr) @@ -60,6 +60,7 @@ std::wstring multiToWide(const std::string& multiStr) *targetStart = 0; std::wstring convertedStr(wideStr); delete[] wideStr; + return convertedStr; } else if (sizeof(wchar_t) == 4) @@ -82,6 +83,7 @@ std::wstring multiToWide(const std::string& multiStr) *targetStart = 0; std::wstring convertedStr(wideStr); delete[] wideStr; + return convertedStr; } else @@ -116,6 +118,7 @@ std::string wideToMulti(const std::wstring& wideStr) *targetStart = 0; std::string convertedStr(multiStr); delete[] multiStr; + return convertedStr; } else if (sizeof(wchar_t) == 4) @@ -139,6 +142,7 @@ std::string wideToMulti(const std::wstring& wideStr) *targetStart = 0; std::string convertedStr(multiStr); delete[] multiStr; + return convertedStr; } else @@ -149,7 +153,7 @@ std::string wideToMulti(const std::wstring& wideStr) } -} // namespace dc +} // namespace Mf /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/stringtools.hh b/src/Moof/StringTools.hh similarity index 93% rename from src/stringtools.hh rename to src/Moof/StringTools.hh index bd79eab..44bd74f 100644 --- a/src/stringtools.hh +++ b/src/Moof/StringTools.hh @@ -26,21 +26,21 @@ *******************************************************************************/ -#ifndef _STRINGTOOLS_HH_ -#define _STRINGTOOLS_HH_ +#ifndef _MOOF_STRINGTOOLS_HH_ +#define _MOOF_STRINGTOOLS_HH_ #include -namespace dc { +namespace Mf { std::wstring multiToWide(const std::string& multiStr); std::string wideToMulti(const std::wstring& wideStr); -} // namespace dc +} // namespace Mf -#endif // _STRINGTOOLS_HH_ +#endif // _MOOF_STRINGTOOLS_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/texture.cc b/src/Moof/Texture.cc similarity index 83% rename from src/texture.cc rename to src/Moof/Texture.cc index 6d3e912..44a0b42 100644 --- a/src/texture.cc +++ b/src/Moof/Texture.cc @@ -33,15 +33,13 @@ #include #include -#include "mippleton.hh" +#include "Dispatcher.hh" +#include "Mippleton.hh" +#include "OpenGL.hh" +#include "Texture.hh" -#include "dispatcher.hh" -#include "opengl.hh" -#include "texture.hh" - - -namespace dc { +namespace Mf { /** @@ -53,7 +51,7 @@ namespace dc { * objects and avoid having duplicate textures loaded to GL. */ -class texture::texture_impl : public mippleton +class Texture::TextureImpl : public Mippleton { /** @@ -75,7 +73,7 @@ class texture::texture_impl : public mippleton * smart enough to cache it if the client has plenty of RAM. */ - void contextRecreated(const notification& note) + void contextRecreated(const Notification& note) { unloadFromGL(); uploadToGL(); @@ -103,8 +101,8 @@ public: * Construction is initialization. */ - explicit texture_impl(const std::string& name) : - mippleton(name), + explicit TextureImpl(const std::string& name) : + Mippleton(name), width_(0), height_(0), mode_(0), @@ -117,15 +115,15 @@ public: uploadToGL(); // we want to know when the GL context is recreated - dispatcher::instance().addHandler("video.context_recreated", - boost::bind(&texture_impl::contextRecreated, this, _1), this); + Dispatcher::instance().addHandler("video.context_recreated", + boost::bind(&TextureImpl::contextRecreated, this, _1), this); } - ~texture_impl() + ~TextureImpl() { unloadFromGL(); - dispatcher::instance().removeHandler(this); + Dispatcher::instance().removeHandler(this); } @@ -223,11 +221,11 @@ public: { SDL_Surface* surface; - surface = IMG_Load(texture::getPathToResource(getName()).c_str()); + surface = IMG_Load(Texture::getPathToResource(getName()).c_str()); if (!surface) { - throw texture::exception("loading failed"); + throw Texture::Exception("loading failed"); } SDL_Surface* temp = prepareImageForGL(surface); @@ -235,7 +233,7 @@ public: if (!temp) { - throw texture::exception("image couldn't be prepared for GL"); + throw Texture::Exception("image couldn't be prepared for GL"); } if (temp->format->BytesPerPixel == 3) @@ -249,7 +247,7 @@ public: else { SDL_FreeSurface(temp); - throw texture::exception("image is not the required 24 or 32 bpp"); + throw Texture::Exception("image is not the required 24 or 32 bpp"); } width_ = temp->w; @@ -322,9 +320,9 @@ public: }; -texture::texture(const std::string& name) : +Texture::Texture(const std::string& name) : // pass through - impl(texture::texture_impl::retain(name), &texture::texture_impl::release) + impl_(Texture::TextureImpl::retain(name), &Texture::TextureImpl::release) {} @@ -332,7 +330,7 @@ texture::texture(const std::string& name) : * Bind the GL texture for mapping, etc. */ -void texture::bind() +void Texture::bind() { glBindTexture(GL_TEXTURE_2D, getObject()); } @@ -342,63 +340,63 @@ void texture::bind() * Get the texture object, for the curious. */ -GLuint texture::getObject() +GLuint Texture::getObject() { // pass through - return impl->object_; + return impl_->object_; } -unsigned texture::getWidth() +unsigned Texture::getWidth() { // pass through - return impl->width_; + return impl_->width_; } -unsigned texture::getHeight() +unsigned Texture::getHeight() { // pass through - return impl->height_; + return impl_->height_; } -void texture::setMinFilter(GLuint filter) +void Texture::setMinFilter(GLuint filter) { - impl->minFilter_ = filter; + impl_->minFilter_ = filter; } -void texture::setMaxFilter(GLuint filter) +void Texture::setMaxFilter(GLuint filter) { - impl->maxFilter_ = filter; + impl_->maxFilter_ = filter; } -void texture::setWrapU(GLuint wrap) +void Texture::setWrapU(GLuint wrap) { - impl->wrapU_ = wrap; + impl_->wrapU_ = wrap; } -void texture::setWrapV(GLuint wrap) +void Texture::setWrapV(GLuint wrap) { - impl->wrapV_ = wrap; + impl_->wrapV_ = wrap; } -void texture::applyChanges() +void Texture::applyChanges() { bind(); - impl->setProperties(); + impl_->setProperties(); } -std::string texture::getPathToResource(const std::string& name) +std::string Texture::getPathToResource(const std::string& name) { // TODO since this is a generic library class, more than PNG should be // supported - return resource::getPathToResource("textures/" + name + ".png"); + return Resource::getPathToResource("textures/" + name + ".png"); } -} // namespace dc +} // namespace Mf /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/texture.hh b/src/Moof/Texture.hh similarity index 83% rename from src/texture.hh rename to src/Moof/Texture.hh index f92ad23..e858093 100644 --- a/src/texture.hh +++ b/src/Moof/Texture.hh @@ -26,11 +26,11 @@ *******************************************************************************/ -#ifndef _TEXTURE_HH_ -#define _TEXTURE_HH_ +#ifndef _MOOF_TEXTURE_HH_ +#define _MOOF_TEXTURE_HH_ /** - * @file texture.hh + * @file Texture.hh * Image-loading and OpenGL texture loading. */ @@ -38,17 +38,17 @@ #include -#include "opengl.hh" -#include "resource.hh" +#include +#include -namespace dc { +namespace Mf { -class texture : public resource +class Texture : public Resource { public: - texture(const std::string& name); + Texture(const std::string& name); void bind(); GLuint getObject(); @@ -65,21 +65,21 @@ public: static std::string getPathToResource(const std::string& name); - struct exception : std::runtime_error + struct Exception : std::runtime_error { - explicit exception(const std::string& what_arg) : + explicit Exception(const std::string& what_arg) : std::runtime_error(what_arg) {} }; private: - class texture_impl; - boost::shared_ptr impl; + class TextureImpl; + boost::shared_ptr impl_; }; -} // namespace dc +} // namespace Mf -#endif // _TEXTURE_HH_ +#endif // _MOOF_TEXTURE_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/Moof/Thread.hh b/src/Moof/Thread.hh new file mode 100644 index 0000000..a5e0225 --- /dev/null +++ b/src/Moof/Thread.hh @@ -0,0 +1,297 @@ + +/******************************************************************************* + + 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_THREAD_HH_ +#define _MOOF_THREAD_HH_ + +/** + * @file Thread.hh + * Light C++ wrapper around SDL threads. + */ + +#include + +#include + + +namespace Mf { + +// +// The detach function detaches a separate thread by calling 'func' with +// the 'arg' parameter. +// + +typedef SDL_Thread* Thread; + +typedef boost::function Function; + + +int detach_(void* arg) +{ + Function function = *(Function*)arg; + int ret = function(); + + delete (Function*)arg; + return ret; +} + +Thread detachFunction(const Function& function) +{ + Thread thread; + Function* fcopy = new Function(function); + + thread = SDL_CreateThread(detach_, (void*)fcopy); + if (thread == 0) delete fcopy; + return thread; +} + + +int waitOnThread(Thread thread) +{ + int i; + SDL_WaitThread(thread, &i); + return i; +} + +void killThread(Thread thread) +{ + SDL_KillThread(thread); +} + + +// +// The identifier function returns a unique integer for the calling thread. +// + +unsigned int getThreadIdentifier() +{ + return SDL_ThreadID(); +} + +unsigned int getThreadIdentifier(Thread thread) +{ + return SDL_GetThreadID(thread); +} + + +// ============================================================================= + +class Mutex +{ + friend class Condition; + +public: + Mutex() + { + mutex_ = SDL_CreateMutex(); + } + ~Mutex() + { + SDL_DestroyMutex(mutex_); + } + + bool acquireLock() + { + return (SDL_LockMutex(mutex_) == 0); + } + bool releaseLock() + { + return (SDL_UnlockMutex(mutex_) == 0); + } + + class Lock + { + friend class Condition; + + public: + Lock(Mutex& mutex) + { + mutex_ = &mutex; + isLocked_ = false; + } + ~Lock() + { + if (isLocked_) release(); + } + + bool acquire() + { + return (isLocked_ = mutex_->acquireLock()); + } + bool release() + { + return mutex_->releaseLock(); + isLocked_ = false; + } + + bool isLocked() const + { + return isLocked_; + } + + protected: + Mutex* mutex_; + bool isLocked_; + }; + + class ScopedLock : public Lock + { + public: + ScopedLock(Mutex& mutex) : + Lock(mutex) + { + acquire(); + } + }; + +private: + SDL_mutex* mutex_; +}; + + +class Condition +{ +public: + Condition() + { + condition_ = SDL_CreateCond(); + } + ~Condition() + { + SDL_DestroyCond(condition_); + } + + bool wait(Mutex::Lock& lock) + { + return (SDL_CondWait(condition_, lock.mutex_->mutex_) == 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); + } + + bool notify() + { + return (SDL_CondSignal(condition_) == 0); + } + bool notifyAll() + { + return (SDL_CondBroadcast(condition_) == 0); + } + +private: + SDL_cond* condition_; +}; + + +class Semaphore +{ +public: + Semaphore(unsigned int value) + { + semaphore_ = SDL_CreateSemaphore(value); + } + ~Semaphore() + { + SDL_DestroySemaphore(semaphore_); + } + + bool acquireLock() + { + return (SDL_SemWait(semaphore_) == 0); + } + bool releaseLock() + { + return (SDL_SemPost(semaphore_) == 0); + } + + bool tryLock() + { + return (SDL_SemTryWait(semaphore_) == 0); + } + bool tryLock(unsigned ms) + { + // TODO for consistency, this function should take seconds + return (SDL_SemWaitTimeout(semaphore_, ms) == 0); + } + + class Lock + { + public: + Lock(Semaphore& semaphore) + { + semaphore_ = &semaphore; + isLocked_ = false; + } + ~Lock() + { + if (isLocked_) release(); + } + + bool acquire() + { + return (isLocked_ = semaphore_->acquireLock()); + } + bool release() + { + return semaphore_->releaseLock(); isLocked_ = false; + } + + bool isLocked() const + { + return isLocked_; + } + + protected: + Semaphore* semaphore_; + bool isLocked_; + }; + + class ScopedLock : public Lock + { + public: + ScopedLock(Semaphore& semaphore) : + Lock(semaphore) + { + acquire(); + } + }; + +private: + SDL_sem* semaphore_; +}; + + +} // namespace Mf + + +#endif // _MOOF_THREAD_HH_ + +/** vim: set ts=4 sw=4 tw=80: *************************************************/ + diff --git a/src/tilemap.cc b/src/Moof/Tilemap.cc similarity index 64% rename from src/tilemap.cc rename to src/Moof/Tilemap.cc index 4a55c65..6accbd1 100644 --- a/src/tilemap.cc +++ b/src/Moof/Tilemap.cc @@ -26,22 +26,21 @@ *******************************************************************************/ -#include "deserializer.hh" -#include "mippleton.hh" -#include "opengl.hh" -#include "serializable.hh" +#include "Deserializer.hh" +#include "Mippleton.hh" +#include "OpenGL.hh" +#include "Serializable.hh" +#include "Tilemap.hh" -#include "tilemap.hh" +namespace Mf { -namespace dc { - -class tilemap::tilemap_impl : public mippleton +class Tilemap::TilemapImpl : public Mippleton { public: - tilemap_impl(const std::string& name) : - mippleton(name), + TilemapImpl(const std::string& name) : + Mippleton(name), tilesU_(1), tilesV_(1), minFilter_(GL_NEAREST), @@ -54,19 +53,19 @@ public: void loadFromFile() { - deserializer in(tilemap::getPathToResource(getName())); + Deserializer deserializer(Tilemap::getPathToResource(getName())); - serializable_ptr root = in.deserialize(); + SerializablePtr root = deserializer.deserialize(); if (root) { - std::map rootMap; + std::map rootObj; - if (root->get(rootMap)) + if (root->get(rootObj)) { - std::map::iterator it; + std::map::iterator it; - if ((it = rootMap.find("TilesU")) != rootMap.end()) + if ((it = rootObj.find("TilesU")) != rootObj.end()) { long value; if ((*it).second->get(value)) @@ -74,7 +73,7 @@ public: tilesU_ = unsigned(value); } } - if ((it = rootMap.find("TilesV")) != rootMap.end()) + if ((it = rootObj.find("TilesV")) != rootObj.end()) { long value; if ((*it).second->get(value)) @@ -82,7 +81,7 @@ public: tilesV_ = unsigned(value); } } - if ((it = rootMap.find("MinFilter")) != rootMap.end()) + if ((it = rootObj.find("MinFilter")) != rootObj.end()) { std::string value; if ((*it).second->get(value)) @@ -93,7 +92,7 @@ public: } } } - if ((it = rootMap.find("MaxFilter")) != rootMap.end()) + if ((it = rootObj.find("MaxFilter")) != rootObj.end()) { std::string value; if ((*it).second->get(value)) @@ -104,7 +103,7 @@ public: } } } - if ((it = rootMap.find("WrapU")) != rootMap.end()) + if ((it = rootObj.find("WrapU")) != rootObj.end()) { std::string value; if ((*it).second->get(value)) @@ -115,7 +114,7 @@ public: } } } - if ((it = rootMap.find("WrapV")) != rootMap.end()) + if ((it = rootObj.find("WrapV")) != rootObj.end()) { std::string value; if ((*it).second->get(value)) @@ -130,37 +129,38 @@ public: } } - unsigned tilesU_; - unsigned tilesV_; - GLuint minFilter_; - GLuint maxFilter_; - GLuint wrapU_; - GLuint wrapV_; + unsigned tilesU_; + unsigned tilesV_; + GLuint minFilter_; + GLuint maxFilter_; + GLuint wrapU_; + GLuint wrapV_; }; -tilemap::tilemap(const std::string& name) : - texture(name), - impl(tilemap::tilemap_impl::retain(name), &tilemap::tilemap_impl::release) +Tilemap::Tilemap(const std::string& name) : + Texture(name), + impl_(Tilemap::TilemapImpl::retain(name), &Tilemap::TilemapImpl::release) { - setMinFilter(impl->minFilter_); - setMaxFilter(impl->maxFilter_); - setWrapU(impl->wrapU_); - setWrapV(impl->wrapV_); + setMinFilter(impl_->minFilter_); + setMaxFilter(impl_->maxFilter_); + setWrapU(impl_->wrapU_); + setWrapV(impl_->wrapV_); applyChanges(); } -bool tilemap::getTileCoords(unsigned index, scalar coords[8]) +bool Tilemap::getTileCoords(unsigned index, Scalar coords[8]) { // make sure the index represents a real tile - if (index >= impl->tilesU_ * impl->tilesV_) return false; + if (index >= impl_->tilesU_ * impl_->tilesV_) return false; - scalar w = 1.0 / scalar(impl->tilesU_); - scalar h = 1.0 / scalar(impl->tilesV_); + Scalar w = 1.0 / Scalar(impl_->tilesU_); + Scalar h = 1.0 / Scalar(impl_->tilesV_); - coords[0] = scalar(index % impl->tilesU_) * w; - coords[1] = (scalar(impl->tilesV_ - 1) - scalar(index / impl->tilesU_)) * h; + coords[0] = Scalar(index % impl_->tilesU_) * w; + coords[1] = (Scalar(impl_->tilesV_ - 1) - + Scalar(index / impl_->tilesU_)) * h; coords[2] = coords[0] + w; coords[3] = coords[1]; coords[4] = coords[2]; @@ -171,11 +171,12 @@ bool tilemap::getTileCoords(unsigned index, scalar coords[8]) return true; } -bool tilemap::getTileCoords(unsigned index, scalar coords[8], orientation what) +bool Tilemap::getTileCoords(unsigned index, Scalar coords[8], + Orientation orientation) { if (getTileCoords(index, coords)) { - if (what & flip) + if (orientation & FLIP) { // this looks kinda weird, but it's just swapping in a way that // doesn't require an intermediate variable @@ -184,7 +185,7 @@ bool tilemap::getTileCoords(unsigned index, scalar coords[8], orientation what) coords[3] = coords[7]; coords[7] = coords[5]; } - if (what & reverse) + if (orientation & REVERSE) { coords[0] = coords[2]; coords[2] = coords[6]; @@ -199,13 +200,13 @@ bool tilemap::getTileCoords(unsigned index, scalar coords[8], orientation what) } -std::string tilemap::getPathToResource(const std::string& name) +std::string Tilemap::getPathToResource(const std::string& name) { - return resource::getPathToResource("tilemaps/" + name + ".json"); + return Resource::getPathToResource("tilemaps/" + name + ".json"); } -} // namespace dc +} // namespace Mf /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/tilemap.hh b/src/Moof/Tilemap.hh similarity index 82% rename from src/tilemap.hh rename to src/Moof/Tilemap.hh index df8d9af..d8708f1 100644 --- a/src/tilemap.hh +++ b/src/Moof/Tilemap.hh @@ -26,21 +26,21 @@ *******************************************************************************/ -#ifndef _TILEMAP_HH_ -#define _TILEMAP_HH_ +#ifndef _MOOF_TILEMAP_HH_ +#define _MOOF_TILEMAP_HH_ /** - * @file tilemap.hh + * @file Tilemap.hh * Small subclass to give some basic tile-mapping functionality to textures. */ #include -#include "texture.hh" -#include "math.hh" +#include +#include -namespace dc { +namespace Mf { /** @@ -50,23 +50,25 @@ namespace dc { * simplicity, this class assumes square tiles. */ -class tilemap : public texture +class Tilemap : public Texture { public: /** * Possible orientations for texture coordinates. */ + typedef unsigned Index; + typedef enum { - normal = 0, ///< Normal orientation. - flip = 1, ///< Flip over a horizontal axis. - reverse = 2, ///< Flip over a vertical axis. - flip_and_reverse = 3 ///< Flip over both. - } orientation; + NORMAL = 0, ///< Normal orientation. + FLIP = 1, ///< Flip over a horizontal axis. + REVERSE = 2, ///< Flip over a vertical axis. + FLIP_AND_REVERSE = 3 ///< Flip over both. + } Orientation; - tilemap(const std::string& name); + Tilemap(const std::string& name); /** * Calculate texture coordinates for a tile at a certain index. Tiles are @@ -80,7 +82,7 @@ public: * @return True if index is valid, false otherwise. */ - bool getTileCoords(unsigned index, scalar coords[8]); + bool getTileCoords(Index index, Scalar coords[8]); /** @@ -91,20 +93,20 @@ public: * @return True if index is valid, false otherwise. */ - bool getTileCoords(unsigned index, scalar coords[8], orientation what); + bool getTileCoords(Index index, Scalar coords[8], Orientation what); static std::string getPathToResource(const std::string& name); private: - class tilemap_impl; - boost::shared_ptr impl; + class TilemapImpl; + boost::shared_ptr impl_; }; -} // namespace dc +} // namespace Mf -#endif // _TILEMAP_HH_ +#endif // _MOOF_TILEMAP_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/timer.cc b/src/Moof/Timer.cc similarity index 86% rename from src/timer.cc rename to src/Moof/Timer.cc index d73d94f..4eea488 100644 --- a/src/timer.cc +++ b/src/Moof/Timer.cc @@ -26,18 +26,18 @@ *******************************************************************************/ -#include -#include #include +#include +#include + +#include "Timer.hh" #if HAVE_CONFIG_H #include "config.h" #endif -#include "timer.hh" - -namespace dc { +namespace Mf { #if HAVE_CLOCK_GETTIME @@ -49,7 +49,7 @@ namespace dc { // program starts). Of course this isn't much of an issue if scalar is a // double-precision number. -static time_t setReference() +static time_t setReference_() { struct timespec ts; @@ -61,10 +61,10 @@ static time_t setReference() return ts.tv_sec; } -static const time_t reference = setReference(); +static const time_t reference = setReference_(); -scalar ticks() +Scalar getTicks() { struct timespec ts; @@ -73,7 +73,7 @@ scalar ticks() throw std::runtime_error("cannot access monotonic clock"); } - return scalar(ts.tv_sec - reference) + scalar(ts.tv_nsec) / 1000000000.0; + return Scalar(ts.tv_sec - reference) + Scalar(ts.tv_nsec) / 1000000000.0; } @@ -86,24 +86,24 @@ scalar ticks() #include -scalar ticks() +Scalar getTicks() { Uint32 ms = SDL_GetTicks(); - return scalar(ms / 1000) + scalar(ms % 1000) / 1000.0; + return Scalar(ms / 1000) + Scalar(ms % 1000) / 1000.0; } #endif // HAVE_CLOCK_GETTIME -void sleep(scalar seconds, bool absolute) +void sleep(Scalar seconds, bool absolute) { struct timespec ts; int ret; - if (absolute) seconds -= ticks(); + if (absolute) seconds -= getTicks(); ts.tv_sec = time_t(seconds); - ts.tv_nsec = long((seconds - scalar(ts.tv_sec)) * 1000000000.0); + ts.tv_nsec = long((seconds - Scalar(ts.tv_sec)) * 1000000000.0); do { @@ -113,7 +113,7 @@ void sleep(scalar seconds, bool absolute) } -} // namespace dc +} // namespace Mf /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/timer.hh b/src/Moof/Timer.hh similarity index 91% rename from src/timer.hh rename to src/Moof/Timer.hh index 8506327..340f79f 100644 --- a/src/timer.hh +++ b/src/Moof/Timer.hh @@ -26,18 +26,18 @@ *******************************************************************************/ -#ifndef _TIMER_HH_ -#define _TIMER_HH_ +#ifndef _MOOF_TIMER_HH_ +#define _MOOF_TIMER_HH_ /** - * @file timer.hh + * @file Timer.hh * Functions for measuring time in a friendly unit. */ -#include "math.hh" +#include -namespace dc { +namespace Mf { /** @@ -45,7 +45,7 @@ namespace dc { * @return Seconds. */ -scalar ticks(); +Scalar getTicks(); /** @@ -57,13 +57,13 @@ scalar ticks(); * sleep for the requested amount of time. */ -void sleep(scalar seconds, bool absolute = false); +void sleep(Scalar seconds, bool absolute = false); -} // namespace dc +} // namespace Mf -#endif // _TIMER_HH_ +#endif // _MOOF_TIMER_HH_ /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/video.cc b/src/Moof/Video.cc similarity index 72% rename from src/video.cc rename to src/Moof/Video.cc index 7ad8efc..c41517e 100644 --- a/src/video.cc +++ b/src/Moof/Video.cc @@ -28,20 +28,19 @@ #include -#include "serializable.hh" -#include "settings.hh" -#include "dispatcher.hh" +#include "Dispatcher.hh" +#include "Serializable.hh" +#include "Settings.hh" +#include "Video.hh" -#include "video.hh" +namespace Mf { -namespace dc { - -video::video() +Video::Video() { std::string caption; - if (settings::instance().get("video.caption", caption)) + if (Settings::instance().get("video.caption", caption)) { init(attribs_, caption); } @@ -51,15 +50,15 @@ video::video() } } -video::video(const attributes& attribs, const std::string& caption) +Video::Video(const Attributes& attribs, const std::string& caption) { init(attribs, caption); } -video::video(const attributes& attribs) +Video::Video(const Attributes& attribs) { std::string caption; - if (settings::instance().get("video.caption", caption)) + if (Settings::instance().get("video.caption", caption)) { init(attribs, caption); } @@ -69,12 +68,12 @@ video::video(const attributes& attribs) } } -video::video(const std::string& caption) +Video::Video(const std::string& caption) { init(attribs_, caption); } -void video::init(const attributes& attribs, const std::string& caption) +void Video::init(const Attributes& attribs, const std::string& caption) { context_ = 0; flags_ = 0; @@ -89,15 +88,15 @@ void video::init(const attributes& attribs, const std::string& caption) setVideoMode(attribs.mode); } -void video::recreateContext() +void Video::recreateContext() { SDL_FreeSurface(context_); context_ = 0; setVideoMode(attribs_.mode); - dc::dispatcher::instance().dispatch("video.context_recreated"); + Mf::Dispatcher::instance().dispatch("video.context_recreated"); } -void video::setOpenGLAttributes() +void Video::setOpenGLAttributes() { SDL_GL_SetAttribute(SDL_GL_RED_SIZE, attribs_.colorBuffer[0]); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, attribs_.colorBuffer[1]); @@ -119,13 +118,13 @@ void video::setOpenGLAttributes() } -video::~video() +Video::~Video() { SDL_FreeSurface(context_); } -void video::setVideoMode(const long mode[3]) +void Video::setVideoMode(const long mode[3]) { if (mode != attribs_.mode || !context_) { @@ -140,34 +139,34 @@ void video::setVideoMode(const long mode[3]) attribs_.mode[1] = mode[1]; attribs_.mode[2] = mode[2]; } - else throw std::runtime_error(SDL_GetError()); + else throw Exception(SDL_GetError()); } } -video::attributes video::getAttributes() const +Video::Attributes Video::getAttributes() const { return attribs_; } -void video::resize(int width, int height) +void Video::resize(int width, int height) { long mode[] = {width, height, attribs_.mode[2]}; setVideoMode(mode); } -bool video::iconify() +bool Video::iconify() { return SDL_WM_IconifyWindow(); } -void video::setCaption(const std::string& caption) +void Video::setCaption(const std::string& caption) { SDL_WM_SetCaption(caption.c_str(), 0); } -std::string video::getCaption() const +std::string Video::getCaption() const { char* str; SDL_WM_GetCaption(&str, 0); @@ -175,7 +174,7 @@ std::string video::getCaption() const } -void video::setFull(bool full) +void Video::setFull(bool full) { if (full != isFull() || !context_) { @@ -196,34 +195,34 @@ void video::setFull(bool full) } } -void video::toggleFull() +void Video::toggleFull() { setFull(!isFull()); } -bool video::isFull() const +bool Video::isFull() const { return flags_ & SDL_FULLSCREEN; } -void video::setCursorVisible(bool hasCursor) +void Video::setCursorVisible(bool hasCursor) { SDL_ShowCursor(hasCursor? SDL_ENABLE : SDL_DISABLE); } -void video::toggleCursorVisible() +void Video::toggleCursorVisible() { setCursorVisible(!isCursorVisible()); } -bool video::isCursorVisible() const +bool Video::isCursorVisible() const { return (SDL_ShowCursor(SDL_QUERY) == SDL_ENABLE); } -void video::setResizable(bool resizable) +void Video::setResizable(bool resizable) { if (resizable != isResizable() || !context_) { @@ -240,46 +239,46 @@ void video::setResizable(bool resizable) } } -void video::toggleResizable() +void Video::toggleResizable() { setResizable(!isResizable()); } -bool video::isResizable() const +bool Video::isResizable() const { return flags_ & SDL_RESIZABLE; } -bool video::isCursorGrab() const +bool Video::isCursorGrab() const { return (SDL_WM_GrabInput(SDL_GRAB_QUERY) == SDL_GRAB_ON); } -void video::toggleCursorGrab() +void Video::toggleCursorGrab() { setCursorGrab(!isCursorGrab()); } -void video::setCursorGrab(bool cursorGrab) +void Video::setCursorGrab(bool cursorGrab) { SDL_WM_GrabInput(cursorGrab? SDL_GRAB_ON : SDL_GRAB_OFF); } -void video::makeActive() +void Video::makeActive() { // NOP until the day SDL supports more than only one window. // Still waiting... } -void video::swap() +void Video::swap() { SDL_GL_SwapBuffers(); } -video::attributes::attributes() +Video::Attributes::Attributes() { // Set some sane GL and window defaults (see SDL_video.c:217) colorBuffer[0] = 3; @@ -307,45 +306,45 @@ video::attributes::attributes() cursorVisible = true; cursorGrab = false; - std::vector colors; - settings::instance().get("video.colorbuffers", colors); + std::vector colors; + Settings::instance().get("video.colorbuffers", colors); if (colors.size() > 0) colors[0]->get(colorBuffer[0]); if (colors.size() > 1) colors[1]->get(colorBuffer[1]); if (colors.size() > 2) colors[2]->get(colorBuffer[2]); if (colors.size() > 3) colors[3]->get(colorBuffer[3]); - settings::instance().get("video.framebuffer", frameBuffer); - settings::instance().get("video.doublebuffer", doubleBuffer); - settings::instance().get("video.depthbuffer", depthBuffer); - settings::instance().get("video.stencilbuffer", stencilBuffer); + Settings::instance().get("video.framebuffer", frameBuffer); + Settings::instance().get("video.doublebuffer", doubleBuffer); + Settings::instance().get("video.depthbuffer", depthBuffer); + Settings::instance().get("video.stencilbuffer", stencilBuffer); - std::vector accum; - settings::instance().get("video.accumbuffers", accum); + std::vector accum; + Settings::instance().get("video.accumbuffers", accum); if (accum.size() > 0) accum[0]->get(accumBuffer[0]); if (accum.size() > 1) accum[1]->get(accumBuffer[1]); if (accum.size() > 2) accum[2]->get(accumBuffer[2]); if (accum.size() > 3) accum[3]->get(accumBuffer[3]); - settings::instance().get("video.stereo", stereo); - settings::instance().get("video.multiesamplebuffers", multisampleBuffers); - settings::instance().get("video.multiesamplesamples", multisampleSamples); - settings::instance().get("video.swapcontrol", swapControl); - settings::instance().get("video.hardwareonly", hardwareonly); + Settings::instance().get("video.stereo", stereo); + Settings::instance().get("video.multiesamplebuffers", multisampleBuffers); + Settings::instance().get("video.multiesamplesamples", multisampleSamples); + Settings::instance().get("video.swapcontrol", swapControl); + Settings::instance().get("video.hardwareonly", hardwareonly); - std::vector dimensions; - settings::instance().get("video.mode", dimensions); + std::vector dimensions; + Settings::instance().get("video.mode", dimensions); if (dimensions.size() > 0) dimensions[0]->get(mode[0]); if (dimensions.size() > 1) dimensions[1]->get(mode[1]); if (dimensions.size() > 2) dimensions[2]->get(mode[2]); - settings::instance().get("video.fullscreen", fullscreen); - settings::instance().get("video.resizable", resizable); - settings::instance().get("video.showcursor", cursorVisible); - settings::instance().get("input.grab", cursorGrab); + Settings::instance().get("video.fullscreen", fullscreen); + Settings::instance().get("video.resizable", resizable); + Settings::instance().get("video.showcursor", cursorVisible); + Settings::instance().get("input.grab", cursorGrab); } -} // namespace dc +} // namespace Mf /** vim: set ts=4 sw=4 tw=80: *************************************************/ diff --git a/src/video.hh b/src/Moof/Video.hh similarity index 82% rename from src/video.hh rename to src/Moof/Video.hh index ad89650..a76dca2 100644 --- a/src/video.hh +++ b/src/Moof/Video.hh @@ -26,8 +26,8 @@ *******************************************************************************/ -#ifndef _VIDEO_HH_ -#define _VIDEO_HH_ +#ifndef _MOOF_VIDEO_HH_ +#define _MOOF_VIDEO_HH_ #include @@ -36,13 +36,13 @@ #include -namespace dc { +namespace Mf { -class video +class Video { public: - struct attributes + struct Attributes { // OpenGL attributes long colorBuffer[4]; // rgba @@ -64,17 +64,17 @@ public: bool cursorVisible; bool cursorGrab; - attributes(); + Attributes(); }; - video(); - video(const attributes& attribs); - video(const attributes& attribs, const std::string& caption); - video(const std::string& caption); - ~video(); + Video(); + Video(const Attributes& attribs); + Video(const Attributes& attribs, const std::string& caption); + Video(const std::string& caption); + ~Video(); void setVideoMode(const long mode[3]); - attributes getAttributes() const; + Attributes getAttributes() const; void resize(int width, int height); bool iconify(); @@ -101,22 +101,29 @@ public: void makeActive(); void swap(); + + struct Exception : public std::runtime_error + { + explicit Exception(const std::string& what_arg) : + std::runtime_error(what_arg) {} + }; + private: - void init(const attributes& attribs, const std::string& caption); + void init(const Attributes& attribs, const std::string& caption); void recreateContext(); void setOpenGLAttributes(); SDL_Surface* context_; unsigned flags_; - attributes attribs_; + Attributes attribs_; }; -typedef boost::shared_ptr