Browse Source

- Adding singleton template class
- Refactoring

Panagiotis Christopoulos Charitos 15 years ago
parent
commit
1f139643f8

File diff suppressed because it is too large
+ 0 - 1
build/debug/Makefile


+ 7 - 7
src/Core/App.cpp

@@ -77,7 +77,7 @@ App::App(int argc, char* argv[], Object* parent):
 	parseCommandLineArgs(argc, argv);
 
 	// send output to handleMessageHanlderMsgs
-	Logger::getInstance().getSignal().connect(boost::bind(&App::handleMessageHanlderMsgs, this, _1, _2, _3, _4));
+	LoggerSingleton::getInstance().getSignal().connect(boost::bind(&App::handleMessageHanlderMsgs, this, _1, _2, _3, _4));
 
 	printAppInfo();
 
@@ -118,23 +118,23 @@ App::App(int argc, char* argv[], Object* parent):
 	"\t\tline = sys._getframe(1).f_lineno\n"
 	"\t\tfile = sys._getframe(1).f_code.co_filename\n"
 	"\t\tfunc = sys._getframe(1).f_code.co_name\n"
-	"\t\tLogger.getInstance().write(file, line, func, str_ + \"\\n\")\n"
+	"\t\tLoggerSingleton.getInstance().write(file, line, func, str_ + \"\\n\")\n"
 	"\n"
 	"class StderrCatcher:\n"
 	"\tdef write(self, str_):\n"
 	"\t\tline = sys._getframe(2).f_lineno\n"
 	"\t\tfile = sys._getframe(2).f_code.co_filename\n"
 	"\t\tfunc = sys._getframe(2).f_code.co_name\n"
-	"\t\tLogger.getInstance().write(file, line, func, str_)\n"
+	"\t\tLoggerSingleton.getInstance().write(file, line, func, str_)\n"
 	"\n"
 	"sys.stdout = StdoutCatcher()\n"
-	"#sys.stderr = StderrCatcher()\n";
+	"sys.stderr = StderrCatcher()\n";
 	ScriptingEngine::getInstance().execScript(commonPythonCode);
 
 	mainRenderer = new MainRenderer(this);
 	scene = new Scene(this);
-	stdinListener = new StdinListener(this);
-	stdinListener->start();
+
+	StdinListenerSingleton::getInstance().start();
 
 	// other
 	activeCam = NULL;
@@ -326,7 +326,7 @@ void App::execStdinScpripts()
 {
 	while(1)
 	{
-		std::string cmd = app->getStdinLintener().getLine();
+		std::string cmd = StdinListenerSingleton::getInstance().getLine();
 
 		if(cmd.length() < 1)
 		{

+ 0 - 9
src/Core/App.h

@@ -53,7 +53,6 @@ class App: public Object
 		/// @{
 		bool isTerminalColoringEnabled() const;
 		Scene& getScene();
-		StdinListener& getStdinLintener();
 		MainRenderer& getMainRenderer();
 		Camera* getActiveCam() {return activeCam;}
 		void setActiveCam(Camera* cam) {activeCam = cam;}
@@ -76,7 +75,6 @@ class App: public Object
 		/// @{
 		Scene* scene;
 		MainRenderer* mainRenderer;
-		StdinListener* stdinListener;
 		/// @}
 
 		void parseCommandLineArgs(int argc, char* argv[]);
@@ -99,13 +97,6 @@ inline Scene& App::getScene()
 }
 
 
-inline StdinListener& App::getStdinLintener()
-{
-	RASSERT_THROW_EXCEPTION(stdinListener == NULL);
-	return *stdinListener;
-}
-
-
 inline MainRenderer& App::getMainRenderer()
 {
 	RASSERT_THROW_EXCEPTION(mainRenderer == NULL);

+ 0 - 3
src/Core/Logger.cpp

@@ -2,9 +2,6 @@
 #include "Logger.h"
 
 
-Logger* Logger::instance = NULL;
-
-
 //======================================================================================================================
 // operator<< [const char*]                                                                                            =
 //======================================================================================================================

+ 11 - 22
src/Core/Logger.h

@@ -4,6 +4,7 @@
 #include <boost/array.hpp>
 #include <boost/signals2.hpp>
 #include <boost/lexical_cast.hpp>
+#include "Singleton.h"
 
 
 struct LoggerSender;
@@ -15,8 +16,7 @@ class Logger
 	public:
 		typedef boost::signals2::signal<void (const char*, int, const char*, const char*)> Signal; ///< Signal type
 
-		/// Singleton stuff
-		static Logger& getInstance();
+		Logger() {execCommonConstructionCode();}
 
 		/// Accessor
 		Signal& getSignal() {return sig;}
@@ -45,7 +45,6 @@ class Logger
 		void write(const char* file, int line, const char* func, const char* msg);
 
 	private:
-		static Logger* instance; ///< Singleton stuff
 		static const int STREAM_SIZE = 512;
 		boost::array<char, STREAM_SIZE> streamBuf;
 		char* sptr; ///< Pointer to @ref streamBuf
@@ -54,13 +53,6 @@ class Logger
 		const char* file; ///< Sender info
 		int line; ///< Sender info
 
-		/// @name Ensure its singleton
-		/// @{
-		Logger() {execCommonConstructionCode();}
-		Logger(const Logger&) {execCommonConstructionCode();}
-		void operator=(const Logger&) {}
-		/// @}
-
 		/// Called by all the constructors
 		void execCommonConstructionCode();
 
@@ -80,16 +72,6 @@ class Logger
 // Inlines                                                                                                             =
 //======================================================================================================================
 
-inline Logger& Logger::getInstance()
-{
-	if(instance == NULL)
-	{
-		instance = new Logger();
-	}
-	return *instance;
-}
-
-
 template<typename Type>
 Logger& Logger::appendUsingLexicalCast(const Type& val)
 {
@@ -108,7 +90,7 @@ Logger& Logger::appendUsingLexicalCast(const Type& val)
 
 
 //======================================================================================================================
-// Non-members                                                                                                         =
+// IO manipulation non-members                                                                                         =
 //======================================================================================================================
 
 /// Add a new line and flush the Logger
@@ -147,7 +129,7 @@ inline LoggerSender setSender(const char* file, int line, const char* func)
 //======================================================================================================================
 
 #define LOGGER_MESSAGE(x) \
-	Logger::getInstance()  << setSender(__FILE__, __LINE__, __func__) << x << endl;
+	LoggerSingleton::getInstance()  << setSender(__FILE__, __LINE__, __func__) << x << endl;
 
 #define INFO(x) LOGGER_MESSAGE("Info: " << x)
 
@@ -156,4 +138,11 @@ inline LoggerSender setSender(const char* file, int line, const char* func)
 #define ERROR(x) LOGGER_MESSAGE("Error: " << x)
 
 
+//======================================================================================================================
+// Singleton                                                                                                           =
+//======================================================================================================================
+
+typedef Singleton<Logger> LoggerSingleton;
+
+
 #endif

+ 12 - 8
src/Core/StdinListener.h

@@ -5,26 +5,30 @@
 #include <boost/thread/mutex.hpp>
 #include <string>
 #include <queue>
-#include "Object.h"
+#include <Singleton.h>
 
 
-/// The listener of the stdin
-class StdinListener: public Object
+/// The listener of the stdin.
+/// It initiates a thread that constantly reads the stdin and puts the results in a queue
+class StdinListener
 {
 	public:
-		StdinListener(Object* parent = NULL): Object(parent) {}
-		~StdinListener() {}
+		/// Get line from the queue or return an empty string
 		std::string getLine();
+
+		/// Start reading
 		void start();
 
 	private:
 		std::queue<std::string> q;
-		boost::mutex mtx;
-		boost::thread thrd;
+		boost::mutex mtx; ///< Protect the queue
+		boost::thread thrd; ///< The thread
 
-		StdinListener(const StdinListener&); ///< Non copyable
 		void workingFunc(); ///< The thread function
 };
 
 
+typedef Singleton<StdinListener> StdinListenerSingleton;
+
+
 #endif

+ 0 - 3
src/Input/Input.cpp

@@ -4,9 +4,6 @@
 #include "Logger.h"
 
 
-Input* Input::instance = NULL;
-
-
 //======================================================================================================================
 // init                                                                                                                =
 //======================================================================================================================

+ 15 - 21
src/Input/Input.h

@@ -4,22 +4,20 @@
 #include <SDL/SDL_scancode.h>
 #include <boost/array.hpp>
 #include "Math.h"
+#include "Singleton.h"
 
 
 /// Handle the SDL input
 class Input
 {
 	public:
-		/// Singleton stuff
-		static Input& getInstance();
-
-		// keys and btns
-		boost::array<short, SDL_NUM_SCANCODES> keys;  ///< Shows the current key state. 0: unpressed, 1: pressed once, n is >1: kept pressed 'n' times continuously
-		boost::array<short, 8> mouseBtns; ///< Mouse btns. Supporting 3 btns & wheel. @see keys
-
+		Input() {init();}
 		void reset();
 		void handleEvents();
 
+		short getKey(uint i) const {return keys[i];}
+		short getMouseBtn(uint i) const {return mouseBtns[i];}
+
 		// mouse stuff
 		Vec2 mousePosNdc; ///< The coords are in the NDC space
 		Vec2 mousePos;     ///< The coords are in the window space. (0, 0) is in the upper left corner
@@ -28,27 +26,23 @@ class Input
 		bool hideCursor;
 
 	private:
-		static Input* instance;
-
-		/// @name Ensure its singleton
+		/// @name Keys and btns
 		/// @{
-		Input() {init();}
-		Input(const Input&) {init();}
-		void operator=(const Input&) {}
+
+		/// Shows the current key state
+		/// - 0 times: unpressed
+		/// - 1 times: pressed once
+		/// - >1 times: Kept pressed 'n' times continuously
+		boost::array<short, SDL_NUM_SCANCODES> keys;
+
+		boost::array<short, 8> mouseBtns; ///< Mouse btns. Supporting 3 btns & wheel. @see keys
 		/// @}
 
 		void init();
 };
 
 
-inline Input& Input::getInstance()
-{
-	if(instance == NULL)
-	{
-		instance = new Input();
-	}
-	return *instance;
-}
+typedef Singleton<Input> InputSingleton;
 
 
 #endif

+ 33 - 33
src/Main.cpp

@@ -264,7 +264,7 @@ void mainLoop()
 	do
 	{
 		float crntTime = App::getTicks() / 1000.0;
-		Input::getInstance().handleEvents();
+		InputSingleton::getInstance().handleEvents();
 
 		float dist = 0.2;
 		float ang = toRad(3.0);
@@ -273,45 +273,45 @@ void mainLoop()
 		// move the camera
 		static SceneNode* mover = app->getActiveCam();
 
-		if(Input::getInstance().keys[SDL_SCANCODE_1]) mover = app->getActiveCam();
-		if(Input::getInstance().keys[SDL_SCANCODE_2]) mover = point_lights[0];
-		if(Input::getInstance().keys[SDL_SCANCODE_3]) mover = spot_lights[0];
-		if(Input::getInstance().keys[SDL_SCANCODE_4]) mover = point_lights[1];
-		if(Input::getInstance().keys[SDL_SCANCODE_5]) mover = spot_lights[1];
-		if(Input::getInstance().keys[SDL_SCANCODE_6]) mover = partEmitter;
-		if(Input::getInstance().keys[SDL_SCANCODE_M] == 1) Input::getInstance().warpMouse = !Input::getInstance().warpMouse;
-
-		if(Input::getInstance().keys[SDL_SCANCODE_A]) mover->moveLocalX(-dist);
-		if(Input::getInstance().keys[SDL_SCANCODE_D]) mover->moveLocalX(dist);
-		if(Input::getInstance().keys[SDL_SCANCODE_LSHIFT]) mover->moveLocalY(dist);
-		if(Input::getInstance().keys[SDL_SCANCODE_SPACE]) mover->moveLocalY(-dist);
-		if(Input::getInstance().keys[SDL_SCANCODE_W]) mover->moveLocalZ(-dist);
-		if(Input::getInstance().keys[SDL_SCANCODE_S]) mover->moveLocalZ(dist);
-		if(!Input::getInstance().warpMouse)
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_1)) mover = app->getActiveCam();
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_2)) mover = point_lights[0];
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_3)) mover = spot_lights[0];
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_4)) mover = point_lights[1];
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_5)) mover = spot_lights[1];
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_6)) mover = partEmitter;
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_M) == 1) InputSingleton::getInstance().warpMouse = !InputSingleton::getInstance().warpMouse;
+
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_A)) mover->moveLocalX(-dist);
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_D)) mover->moveLocalX(dist);
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_LSHIFT)) mover->moveLocalY(dist);
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_SPACE)) mover->moveLocalY(-dist);
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_W)) mover->moveLocalZ(-dist);
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_S)) mover->moveLocalZ(dist);
+		if(!InputSingleton::getInstance().warpMouse)
 		{
-			if(Input::getInstance().keys[SDL_SCANCODE_UP]) mover->rotateLocalX(ang);
-			if(Input::getInstance().keys[SDL_SCANCODE_DOWN]) mover->rotateLocalX(-ang);
-			if(Input::getInstance().keys[SDL_SCANCODE_LEFT]) mover->rotateLocalY(ang);
-			if(Input::getInstance().keys[SDL_SCANCODE_RIGHT]) mover->rotateLocalY(-ang);
+			if(InputSingleton::getInstance().getKey(SDL_SCANCODE_UP)) mover->rotateLocalX(ang);
+			if(InputSingleton::getInstance().getKey(SDL_SCANCODE_DOWN)) mover->rotateLocalX(-ang);
+			if(InputSingleton::getInstance().getKey(SDL_SCANCODE_LEFT)) mover->rotateLocalY(ang);
+			if(InputSingleton::getInstance().getKey(SDL_SCANCODE_RIGHT)) mover->rotateLocalY(-ang);
 		}
 		else
 		{
 			float accel = 44.0;
-			mover->rotateLocalX(ang * Input::getInstance().mouseVelocity.y * accel);
-			mover->rotateLocalY(-ang * Input::getInstance().mouseVelocity.x * accel);
+			mover->rotateLocalX(ang * InputSingleton::getInstance().mouseVelocity.y * accel);
+			mover->rotateLocalY(-ang * InputSingleton::getInstance().mouseVelocity.x * accel);
 		}
-		if(Input::getInstance().keys[SDL_SCANCODE_Q]) mover->rotateLocalZ(ang);
-		if(Input::getInstance().keys[SDL_SCANCODE_E]) mover->rotateLocalZ(-ang);
-		if(Input::getInstance().keys[SDL_SCANCODE_PAGEUP]) mover->getLocalTransform().scale += scale ;
-		if(Input::getInstance().keys[SDL_SCANCODE_PAGEDOWN]) mover->getLocalTransform().scale -= scale ;
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_Q)) mover->rotateLocalZ(ang);
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_E)) mover->rotateLocalZ(-ang);
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_PAGEUP)) mover->getLocalTransform().scale += scale ;
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_PAGEDOWN)) mover->getLocalTransform().scale -= scale ;
 
-		if(Input::getInstance().keys[SDL_SCANCODE_K]) app->getActiveCam()->lookAtPoint(point_lights[0]->getWorldTransform().origin);
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_K)) app->getActiveCam()->lookAtPoint(point_lights[0]->getWorldTransform().origin);
 
-		if(Input::getInstance().keys[SDL_SCANCODE_I])
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_I))
 			character->moveForward(0.1);
 
 
-		if(Input::getInstance().keys[SDL_SCANCODE_O] == 1)
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_O) == 1)
 		{
 			btRigidBody* body = static_cast<btRigidBody*>(boxes[0]);
 			//body->getMotionState()->setWorldTransform(toBt(Mat4(Vec3(0.0, 10.0, 0.0), Mat3::getIdentity(), 1.0)));
@@ -320,7 +320,7 @@ void mainLoop()
 			body->forceActivationState(ACTIVE_TAG);
 		}
 
-		if(Input::getInstance().keys[SDL_SCANCODE_Y] == 1)
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_Y) == 1)
 		{
 			INFO("Exec script");
 			ScriptingEngine::getInstance().exposeVar("app", app);
@@ -347,11 +347,11 @@ void mainLoop()
 		/*Ui::printf("Mover: Pos(%.2f %.2f %.2f) Angs(%.2f %.2f %.2f)", mover->translationWspace.x, mover->translationWspace.y, mover->translationWspace.z,
 								 toDegrees(Euler(mover->rotationWspace).x), toDegrees(Euler(mover->rotationWspace).y), toDegrees(Euler(mover->rotationWspace).z));*/
 
-		if(Input::getInstance().keys[SDL_SCANCODE_ESCAPE])
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_ESCAPE))
 			break;
-		if(Input::getInstance().keys[SDL_SCANCODE_F11])
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_F11))
 			app->togleFullScreen();
-		if(Input::getInstance().keys[SDL_SCANCODE_F12] == 1)
+		if(InputSingleton::getInstance().getKey(SDL_SCANCODE_F12) == 1)
 			app->getMainRenderer().takeScreenshot("gfx/screenshot.jpg");
 
 		/*char str[128];

+ 1 - 0
src/Scripting/BoostPythonInterfaces.cpp

@@ -12,6 +12,7 @@ BOOST_PYTHON_MODULE(Anki)
 	CALL_WRAP(Vec4);
 
 	CALL_WRAP(Logger);
+	CALL_WRAP(LoggerSingleton);
 
 	CALL_WRAP(Scene);
 

+ 3 - 2
src/Scripting/Core/Logger.bpi.cpp

@@ -5,8 +5,9 @@
 WRAP(Logger)
 {
 	class_<Logger, noncopyable>("Logger", no_init)
-		.def("getInstance", &Logger::getInstance, return_value_policy<reference_existing_object>())
-		.staticmethod("getInstance")
 		.def("write", &Logger::write)
 	;
 }
+
+
+WRAP_SINGLETON(LoggerSingleton)

+ 10 - 0
src/Scripting/ScriptingCommon.h

@@ -12,6 +12,16 @@ using namespace boost::python;
 	void boostPythonWrap##x()
 
 
+/// Wrap a singleton class
+#define WRAP_SINGLETON(x) \
+	WRAP(x) { \
+		class_<x, noncopyable>(#x, no_init) \
+			.def("getInstance", & x ::getInstance, return_value_policy<reference_existing_object>()) \
+			.staticmethod("getInstance") \
+		; \
+	}
+
+
 /// Boost python property read write
 #define BP_PROPERTY_RW(name__, getter__, setter__) \
 	.add_property(name__, & getter__##Value, & setter__##Value)

+ 27 - 0
src/Util/Singleton.h

@@ -0,0 +1,27 @@
+#ifndef SINGLETON_H
+#define SINGLETON_H
+
+
+/// This template makes a class singleton
+template<typename Type>
+class Singleton
+{
+	public:
+		static Type& getInstance() {return *(instance ? instance : (instance = new Type));}
+
+	protected:
+		Singleton();
+		~Singleton();
+
+	private:
+		static Type* instance;
+		Singleton(Singleton const&);
+		Singleton& operator=(const Singleton&);
+};
+
+
+template <typename Type>
+Type* Singleton<Type>::instance = NULL;
+
+
+#endif

Some files were not shown because too many files changed in this diff