Thread: [Yake-svn] SF.net SVN: yake: [1726] trunk/yake (Page 4)
Status: Beta
Brought to you by:
psyclonist
From: <psy...@us...> - 2007-04-20 21:29:39
|
Revision: 1726 http://svn.sourceforge.net/yake/?rev=1726&view=rev Author: psyclonist Date: 2007-04-20 14:29:41 -0700 (Fri, 20 Apr 2007) Log Message: ----------- enabled new plugin inputOgreOIS, fixed build settings Modified Paths: -------------- trunk/yake/samples/vehicle/yakeDemo.cpp trunk/yake/scripts/premake/config.lua trunk/yake/scripts/premake/plugins.lua trunk/yake/scripts/premake/tools.lua Modified: trunk/yake/samples/vehicle/yakeDemo.cpp =================================================================== --- trunk/yake/samples/vehicle/yakeDemo.cpp 2007-04-20 21:26:23 UTC (rev 1725) +++ trunk/yake/samples/vehicle/yakeDemo.cpp 2007-04-20 21:29:41 UTC (rev 1726) @@ -19,7 +19,7 @@ struct TheConfiguration : public raf::ApplicationConfiguration { virtual StringVector getLibraries() - { return MakeStringVector() << YAKE_DYNLIB_NAME("graphicsOgre") << YAKE_DYNLIB_NAME("inputOgre") << YAKE_DYNLIB_NAME("physicsOde"); } + { return MakeStringVector() << YAKE_DYNLIB_NAME("graphicsOgre") << YAKE_DYNLIB_NAME("inputOgreOIS") << YAKE_DYNLIB_NAME("physicsOde"); } //virtual StringVector getScriptingSystems() //{ return MakeStringVector() << "lua"; } @@ -28,7 +28,7 @@ { return MakeStringVector() << "ogre3d"; } virtual StringVector getInputSystems() - { return MakeStringVector() << "ogre"; } + { return MakeStringVector() << "ois"; } virtual StringVector getPhysicsSystems() { return MakeStringVector() << "ode"; } Modified: trunk/yake/scripts/premake/config.lua =================================================================== --- trunk/yake/scripts/premake/config.lua 2007-04-20 21:26:23 UTC (rev 1725) +++ trunk/yake/scripts/premake/config.lua 2007-04-20 21:29:41 UTC (rev 1726) @@ -26,10 +26,14 @@ -- Plugins -------------------------------------- --- !! UNUSED FOR NOW !! +-- NB only some of these are implemented: --PLUGIN_SCRIPTING_LUA = true PLUGIN_AUDIO_OPENAL = true PLUGIN_GRAPHICS_OGRE = true + +PLUGIN_INPUT_OGRE_OIS = true -- enable for OGRE 1.4+ +PLUGIN_INPUT_OGRE = false -- enable for OGRE 1.2 and 1.3 + PLUGIN_PHYSICS_ODE = true PLUGIN_PHYSICS_NX = false Modified: trunk/yake/scripts/premake/plugins.lua =================================================================== --- trunk/yake/scripts/premake/plugins.lua 2007-04-20 21:26:23 UTC (rev 1725) +++ trunk/yake/scripts/premake/plugins.lua 2007-04-20 21:29:41 UTC (rev 1726) @@ -65,13 +65,25 @@ useDep("cegui") -------------------------------------- -makeComponentPlugin("inputOgre") -addDependency("base") -addDependency("input") +if PLUGIN_INPUT_OGRE then + makeComponentPlugin("inputOgre") + addDependency("base") + addDependency("input") -useDep("ogre") + useDep("ogre") +end -------------------------------------- +if PLUGIN_INPUT_OGRE_OIS then + makeComponentPlugin("inputOgreOIS") + addDependency("base") + addDependency("input") + + useDep("ogre") + useDep("ois") +end + +-------------------------------------- makeComponentPlugin("graphicsOgre","YAKE_GRAPHICSCONCRETEAPI_EXPORTS") addDependency("base") addDependency("graphics") Modified: trunk/yake/scripts/premake/tools.lua =================================================================== --- trunk/yake/scripts/premake/tools.lua 2007-04-20 21:26:23 UTC (rev 1725) +++ trunk/yake/scripts/premake/tools.lua 2007-04-20 21:29:41 UTC (rev 1726) @@ -177,7 +177,7 @@ end release = package.config.Release - release.target = targetBaseDir.."release/"..(LIBFILE_PREFIX)..name + release.target = (LIBFILE_PREFIX)..name release.defines = {} release.buildflags = { "no-symbols", This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-04-26 21:52:57
|
Revision: 1756 http://svn.sourceforge.net/yake/?rev=1756&view=rev Author: psyclonist Date: 2007-04-26 14:52:57 -0700 (Thu, 26 Apr 2007) Log Message: ----------- merged v0-6-0 into trunk Modified Paths: -------------- trunk/yake/samples/base/vehicle/yakeDemo.cpp trunk/yake/samples/bin/debug/commclient.cfg trunk/yake/samples/bin/debug/commserver.cfg trunk/yake/samples/bin/debug/yake.graphics.ogre_plugins.cfg trunk/yake/samples/cmdrmayhem/yakeDemo.cpp trunk/yake/samples/common/exapp/yakeExampleApplication.h trunk/yake/samples/gui/console/yakeConsoleDemo.cpp trunk/yake/samples/net/commclient/demo.cpp trunk/yake/samples/net/common/commonEvents.h trunk/yake/samples/net/commserver/demo.cpp trunk/yake/samples/net/roclient/ROClient.cpp trunk/yake/samples/net/roserver/ROServer.cpp trunk/yake/samples/net/roserver/ROServer.h trunk/yake/samples/physics/paging_terrain/yakeDemo.cpp trunk/yake/samples/raf/demo1/yakeDemo.cpp trunk/yake/samples/vehicle/yakeDemo.cpp trunk/yake/scripts/msvc80/build.cmd trunk/yake/scripts/premake/deps.lua trunk/yake/scripts/premake/samples.lua trunk/yake/scripts/premake/yake.lua trunk/yake/src/base/yake.cpp trunk/yake/src/input/yakeActionMap.cpp trunk/yake/src/netsvc/netServiceHost.cpp trunk/yake/src/netsvc/service/netServerCommService.cpp trunk/yake/src/plugins/physicsODE/OdeAvatar.cpp trunk/yake/src/plugins/physicsODE/OdeRay.cpp trunk/yake/yake/base/templates/yakeSignals.h trunk/yake/yake/base/yakeConfigFile.h trunk/yake/yake/gui_addons/console/cegui/yakeCEGUIInputArea.h trunk/yake/yake/input/yakeActionMap.h trunk/yake/yake/input/yakeInputSystem.h trunk/yake/yake/netrepsvc/netEvents.h trunk/yake/yake/netsvc/netServiceHost.h trunk/yake/yake/netsvc/service/netServerCommService.h trunk/yake/yake/physics/yakePhysicsAvatar.h Added Paths: ----------- trunk/yake/samples/bin/release/yake.graphics.ogre_config.cfg trunk/yake/samples/bin/release/yake.graphics.ogre_plugins.cfg trunk/yake/samples/bin/release/yake.graphics.ogre_resources.cfg trunk/yake/samples/net/common/thread_application.h trunk/yake/scripts/msvc80/yake.suo trunk/yake/scripts/tools/make_manual.pl trunk/yake/src/base/templates/yakeSignals.cpp trunk/yake/src/base/yakeConfigFile.cpp trunk/yake/src/plugins/inputOgreOIS/ trunk/yake/src/plugins/inputOgreOIS/InputSystemOgreOIS.cpp trunk/yake/src/plugins/inputOgreOIS/yakePCH.cpp trunk/yake/yake/plugins/inputOgreOIS/ trunk/yake/yake/plugins/inputOgreOIS/InputSystemOgreOIS.h trunk/yake/yake/plugins/inputOgreOIS/yakePCH.h Removed Paths: ------------- trunk/yake/src/plugins/inputOgreOIS/InputSystemOgreOIS.cpp trunk/yake/src/plugins/inputOgreOIS/yakePCH.cpp trunk/yake/yake/plugins/inputOgreOIS/InputSystemOgreOIS.h trunk/yake/yake/plugins/inputOgreOIS/yakePCH.h Modified: trunk/yake/samples/base/vehicle/yakeDemo.cpp =================================================================== --- trunk/yake/samples/base/vehicle/yakeDemo.cpp 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/samples/base/vehicle/yakeDemo.cpp 2007-04-26 21:52:57 UTC (rev 1756) @@ -14,7 +14,7 @@ struct TheConfiguration : public raf::ApplicationConfiguration { virtual StringVector getLibraries() - { return MakeStringVector() << "graphicsOgre" << "inputOgre" << "physicsODE"; } + { return MakeStringVector() << "graphicsOgre" << "inputOgreOIS" << "physicsODE"; } //virtual StringVector getScriptingSystems() //{ return MakeStringVector() << "lua"; } @@ -23,7 +23,7 @@ { return MakeStringVector() << "ogre3d"; } virtual StringVector getInputSystems() - { return MakeStringVector() << "ogre"; } + { return MakeStringVector() << "ois"; } virtual StringVector getPhysicsSystems() { return MakeStringVector() << "ode"; } Modified: trunk/yake/samples/bin/debug/commclient.cfg =================================================================== --- trunk/yake/samples/bin/debug/commclient.cfg 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/samples/bin/debug/commclient.cfg 2007-04-26 21:52:57 UTC (rev 1756) @@ -2,6 +2,7 @@ { client { - server 192.168.1.33:40000 + ;server 192.168.1.33:40000 + server 127.0.0.1:40000 } } Modified: trunk/yake/samples/bin/debug/commserver.cfg =================================================================== --- trunk/yake/samples/bin/debug/commserver.cfg 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/samples/bin/debug/commserver.cfg 2007-04-26 21:52:57 UTC (rev 1756) @@ -2,6 +2,6 @@ { server { - bind 192.168.1.33:40000 + ;bind 192.168.1.33:40000 } } Modified: trunk/yake/samples/bin/debug/yake.graphics.ogre_plugins.cfg =================================================================== --- trunk/yake/samples/bin/debug/yake.graphics.ogre_plugins.cfg 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/samples/bin/debug/yake.graphics.ogre_plugins.cfg 2007-04-26 21:52:57 UTC (rev 1756) @@ -1,7 +1,6 @@ PluginFolder=OgrePlugins -Plugin=RenderSystem_Direct3D9.dll -#Plugin=RenderSystem_Direct3D7.dll -Plugin=RenderSystem_GL.dll -Plugin=Plugin_OctreeSceneManager.dll -Plugin=Plugin_ParticleFX.dll -Plugin=Plugin_CgProgramManager.dll +Plugin=RenderSystem_Direct3D9_d.dll +Plugin=RenderSystem_GL_d.dll +Plugin=Plugin_OctreeSceneManager_d.dll +Plugin=Plugin_ParticleFX_d.dll +Plugin=Plugin_CgProgramManager_d.dll Copied: trunk/yake/samples/bin/release/yake.graphics.ogre_config.cfg (from rev 1755, branches/v0-6-0/yake/samples/bin/release/yake.graphics.ogre_config.cfg) =================================================================== --- trunk/yake/samples/bin/release/yake.graphics.ogre_config.cfg (rev 0) +++ trunk/yake/samples/bin/release/yake.graphics.ogre_config.cfg 2007-04-26 21:52:57 UTC (rev 1756) @@ -0,0 +1,4 @@ +;scenemanager=exterior_close +;world=terrain.cfg +shadowtype=modulated_texture +;show_config_dialog=no Copied: trunk/yake/samples/bin/release/yake.graphics.ogre_plugins.cfg (from rev 1755, branches/v0-6-0/yake/samples/bin/release/yake.graphics.ogre_plugins.cfg) =================================================================== --- trunk/yake/samples/bin/release/yake.graphics.ogre_plugins.cfg (rev 0) +++ trunk/yake/samples/bin/release/yake.graphics.ogre_plugins.cfg 2007-04-26 21:52:57 UTC (rev 1756) @@ -0,0 +1,7 @@ +PluginFolder=OgrePlugins +Plugin=RenderSystem_Direct3D9.dll +#Plugin=RenderSystem_Direct3D7.dll +Plugin=RenderSystem_GL.dll +Plugin=Plugin_OctreeSceneManager.dll +Plugin=Plugin_ParticleFX.dll +Plugin=Plugin_CgProgramManager.dll Copied: trunk/yake/samples/bin/release/yake.graphics.ogre_resources.cfg (from rev 1755, branches/v0-6-0/yake/samples/bin/release/yake.graphics.ogre_resources.cfg) =================================================================== --- trunk/yake/samples/bin/release/yake.graphics.ogre_resources.cfg (rev 0) +++ trunk/yake/samples/bin/release/yake.graphics.ogre_resources.cfg 2007-04-26 21:52:57 UTC (rev 1756) @@ -0,0 +1,27 @@ +# Resource locations to be added to the 'boostrap' path +# This also contains the minimum you need to use the Ogre example framework +[Bootstrap] +Zip=../../../common/media/OgreCore.zip + +# Resource locations to be added to the default path +[General] +FileSystem=../../../common/media/ +FileSystem=../../../common/media/graphics.delorean/ +FileSystem=../../../common/media/graphics.meshes/ +FileSystem=../../../common/media/graphics.scenes/r2t/ +FileSystem=../../../common/media/graphics.scenes/arena0/ +FileSystem=../../../common/media/graphics.textures/ +FileSystem=../../../common/media/graphics.materials/programs/ +FileSystem=../../../common/media/graphics.materials/scripts/ +FileSystem=../../../common/media/graphics.materials/textures/ +FileSystem=../../../common/media/graphics.fx/ +FileSystem=../../../common/media/samples/dotLink/DynTest/ +FileSystem=../../../common/media/samples/dotScene/ +FileSystem=../../../common/media/gui/configs/ +FileSystem=../../../common/media/gui/fonts/ +FileSystem=../../../common/media/gui/imagesets/ +FileSystem=../../../common/media/gui/layouts/ +FileSystem=../../../common/media/gui/looknfeel/ +FileSystem=../../../common/media/gui/lua_scripts/ +FileSystem=../../../common/media/gui/schemes/ +Zip=../../../common/media/skybox.zip Modified: trunk/yake/samples/cmdrmayhem/yakeDemo.cpp =================================================================== --- trunk/yake/samples/cmdrmayhem/yakeDemo.cpp 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/samples/cmdrmayhem/yakeDemo.cpp 2007-04-26 21:52:57 UTC (rev 1756) @@ -94,8 +94,9 @@ /** Configuration of the application */ struct TheConfiguration : public raf::ApplicationConfiguration { + // Use "inputOgre" for Ogre 1.2/1.3, "inputOgreOIS" for Ogre 1.4+. virtual StringVector getLibraries() - { return MakeStringVector() << YAKE_DYNLIB_NAME("graphicsOgre") << YAKE_DYNLIB_NAME("inputOgre") << YAKE_DYNLIB_NAME("physicsODE"); } + { return MakeStringVector() << YAKE_DYNLIB_NAME("graphicsOgre") << YAKE_DYNLIB_NAME("inputOgreOIS") << YAKE_DYNLIB_NAME("physicsODE"); } //virtual StringVector getScriptingSystems() //{ return MakeStringVector() << "lua"; } @@ -103,8 +104,9 @@ virtual StringVector getGraphicsSystems() { return MakeStringVector() << "ogre3d"; } + // Use "ogre" for Ogre 1.2/1.3, "ois" for Ogre 1.4+. virtual StringVector getInputSystems() - { return MakeStringVector() << "ogre"; } + { return MakeStringVector() << "ois"; } virtual StringVector getPhysicsSystems() { return MakeStringVector() << "ode"; } @@ -589,7 +591,7 @@ // Rotate camera around camera's 'up' axis // when user presses RMB and moves the mouse. - if (this->getApp().getMouse()->isButtonDown( input::MB_RIGHT )) + if (this->getApp().getMouse()->isButtonDown( input::MBT_RIGHT )) { // @todo adjust rotation over several frames for smoother rotation. const real angle = mMouseMovement.x * real(100.) * timeElapsed; Modified: trunk/yake/samples/common/exapp/yakeExampleApplication.h =================================================================== --- trunk/yake/samples/common/exapp/yakeExampleApplication.h 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/samples/common/exapp/yakeExampleApplication.h 2007-04-26 21:52:57 UTC (rev 1756) @@ -196,7 +196,7 @@ // input if (mLoadInputSystem) { - SharedPtr<base::Library> pLib = loadLib(YAKE_DYNLIB_NAME("inputOgre" )); + SharedPtr<base::Library> pLib = loadLib(YAKE_DYNLIB_NAME("inputOgreOIS" )); YAKE_ASSERT( pLib ).debug("Cannot load input plugin."); mInputSystem = create_default< input::IInputSystem >(); Modified: trunk/yake/samples/gui/console/yakeConsoleDemo.cpp =================================================================== --- trunk/yake/samples/gui/console/yakeConsoleDemo.cpp 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/samples/gui/console/yakeConsoleDemo.cpp 2007-04-26 21:52:57 UTC (rev 1756) @@ -377,23 +377,23 @@ YAKE_LOG("demo", "Loading scheme..." ); - SchemeManager::getSingleton().loadScheme("yake1skin.scheme"); - System::getSingleton().setDefaultMouseCursor("yake1-images","MouseArrow"); + SchemeManager::getSingleton().loadScheme("VanillaSkin.scheme"); + System::getSingleton().setDefaultMouseCursor("Vanilla-Images","MouseArrow"); FontManager::getSingleton().createFont("Iconified-12.font"); WindowManager& winMgr = WindowManager::getSingleton(); - Window* background = winMgr.createWindow("yake1/StaticImage"); + Window* background = winMgr.createWindow("Vanilla/StaticImage"); background->setArea(URect(cegui_reldim(0), cegui_reldim(0), cegui_reldim(1), cegui_reldim(1))); background->setProperty("FrameEnabled", "false"); background->setProperty("BackgroundEnabled", "false"); - background->setProperty("Image", "set:BackgroundImage image:full_image"); + //@todo background->setProperty("Image", "set:BackgroundImage image:full_image"); System::getSingleton().setGUISheet(background); background->addChildWindow(winMgr.loadWindowLayout("VanillaConsole.layout")); background->activate(); -#if 0 +#if 1 mEditBox = static_cast<CEGUI::Editbox*>(CEGUI::WindowManager::getSingleton().getWindow("/Console/Wnd/Edit")); mListBox = static_cast<CEGUI::Listbox*>(CEGUI::WindowManager::getSingleton().getWindow("/Console/Wnd/History")); #endif Modified: trunk/yake/samples/net/commclient/demo.cpp =================================================================== --- trunk/yake/samples/net/commclient/demo.cpp 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/samples/net/commclient/demo.cpp 2007-04-26 21:52:57 UTC (rev 1756) @@ -145,7 +145,7 @@ { this->requestStop(); } - else if (key == '\n' || key == '0x13' || key == '1') + else if (key == 13) { commService_->sendMessageToChannel("#lobby",currInput_); std::cout << '\n' << "I said: " << currInput_ << "\n"; @@ -179,8 +179,11 @@ String currInput_; }; +#include <yake/base/yakeStderrLog.h> int main(int argc, char* argv[]) { + SharedPtr<logging::log_listener> to_stderr( new logging::stderr_listener() ); + logging::addListener( to_stderr.get() ); try { Configuration cfg; Modified: trunk/yake/samples/net/common/commonEvents.h =================================================================== --- trunk/yake/samples/net/common/commonEvents.h 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/samples/net/common/commonEvents.h 2007-04-26 21:52:57 UTC (rev 1756) @@ -2,6 +2,8 @@ #define TEST_COMMONEVENTS_H #include <yake/ent/ent.h> +#include <yake/net/net.h> +#include <yake/netsvc/netSvc.h> #include <map> @@ -11,50 +13,7 @@ const yake::net::ChannelId CHANNELID_COMM = 3; //--- -/* -// pull in types -typedef yake::net::INetEventConnection::CreateEventFn CreateEventFn; -typedef yake::net::INetEventConnection::DestroyEventFn DestroyEventFn; -// event pool -struct EventPool -{ - EventPool(); - ~EventPool(); - void register_class(const yake::net::NetEvent::id_type id, const CreateEventFn&, const DestroyEventFn&); - { - classes_.insert( std::make_pair( id, ClassEntry(createFn,destroyFn) ) ); - } - yake::net::NetEvent* create(const yake::net::NetEvent::id_type); - void destroy(yake::net::NetEvent*); - void lookup(const yake::net::NetEvent::id_type id, CreateEventFn&, DestroyEventFn&); -private: - typedef std::deque<yake::net::NetEvent*> EventList; - struct ClassEntry - { - CreateEventFn createFn_; - DestroyEventFn destroyFn_; - EventList avail_; - EventList taken_; - }; - typedef std::map<yake::net::NetEvent::id_type,ClassEntry> ClassMap; //<= perfect candidate for AssocVector - ClassMap classes_; -}; - -// event registrator for use with pooled events and event connections -template<typename evt_type> -bool s_registerEvent(const EventPool& evtpool, - const yake::net::IEventConnection& conn, - const yake::net::NetEvent::id_type id, - const yake::net::NetEvent::Direction dir) -{ - CreateEventFn createFn = boost::bind(&EventPool::create,&evtpool,_1); - DestroyEventFn destroyFn = boost::bind(&EventPool::destroy,&evtpool,_1);; - conn.registerEvent(id,dir,ce.createFn,ce.destroyFn); -} -*/ -//--- - struct version_t { yake::uint8 ver[3]; Copied: trunk/yake/samples/net/common/thread_application.h (from rev 1755, branches/v0-6-0/yake/samples/net/common/thread_application.h) =================================================================== --- trunk/yake/samples/net/common/thread_application.h (rev 0) +++ trunk/yake/samples/net/common/thread_application.h 2007-04-26 21:52:57 UTC (rev 1756) @@ -0,0 +1,93 @@ +#ifndef YAKE_SAMPLES_NET_THREADED_APP_H +#define YAKE_SAMPLES_NET_THREADED_APP_H + +#include <samples/net/common/common.h> + +namespace yake { + struct ThreadedApp : public boost::noncopyable + { + ThreadedApp() : stop_app_(false) + { + } + void requestStop() + { + stop_app_ = true; + } + bool stopRequested() const + { + return stop_app_; + } + void run() + { + try { + this->onRun(); + } + catch (const net::Exception& e) + { + YAKE_LOG_ERROR("app",String("Caught yake::net exception: ") + e.what()); + } + catch (const Exception& e) + { + YAKE_LOG_ERROR("app",String("Caught yake exception: ") + e.what()); + } + catch (const std::exception& e) + { + YAKE_LOG_ERROR("app",String("Caught exception: ") + e.what()); + } + catch (...) + { + YAKE_LOG_ERROR("app",String("Caught unknown exception.")); + } + } + private: + virtual void onRun() = 0; + private: + volatile bool stop_app_; + }; + struct NetServerApp : public ThreadedApp + { + NetServerApp() + { + } + typedef SignalX<void(void)> StepSignal; + yake::SignalConnection connectToStep(const StepSignal::slot_type& slot) + { + return stepSig_.connect(slot); + } + yake::SignalConnection connectToSynchronizedNetStep(const StepSignal::slot_type& slot) + { + return netStepSig_.connect(slot); + } + private: + virtual void onInit() = 0; + virtual void onStep() = 0; + virtual void onShutdown() = 0; + private: + StepSignal stepSig_; + StepSignal netStepSig_; + virtual void onRun() + { + ::SetThreadAffinityMask( ::GetCurrentThread(), 0x1 ); + this->onInit(); + + // main loop + while (!stopRequested()) + { + net::update(); + { + net::scoped_lock lck; + netStepSig_(); + } + stepSig_(); + this->onStep(); + net::native::sleep(0); + } + + this->onShutdown(); + //stepSig_.disconnectAll(); + } + }; +} // namespace yake + + +#endif Modified: trunk/yake/samples/net/commserver/demo.cpp =================================================================== --- trunk/yake/samples/net/commserver/demo.cpp 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/samples/net/commserver/demo.cpp 2007-04-26 21:52:57 UTC (rev 1756) @@ -5,95 +5,10 @@ #include <samples/net/common/common.h> #include <samples/net/roserver/ROServer.h> +#include <samples/net/common/thread_application.h> #include <conio.h> -namespace yake { - struct ThreadedApp : public boost::noncopyable - { - ThreadedApp() : stop_app_(false) - { - } - void requestStop() - { - stop_app_ = true; - } - bool stopRequested() const - { - return stop_app_; - } - void run() - { - try { - this->onRun(); - } - catch (const net::Exception& e) - { - YAKE_LOG_ERROR("app",String("Caught yake::net exception: ") + e.what()); - } - catch (const Exception& e) - { - YAKE_LOG_ERROR("app",String("Caught yake exception: ") + e.what()); - } - catch (const std::exception& e) - { - YAKE_LOG_ERROR("app",String("Caught exception: ") + e.what()); - } - catch (...) - { - YAKE_LOG_ERROR("app",String("Caught unknown exception.")); - } - } - private: - virtual void onRun() = 0; - private: - volatile bool stop_app_; - }; - struct NetServerApp : public ThreadedApp - { - NetServerApp() - { - } - typedef SignalX<void(void)> StepSignal; - yake::SignalConnection connectToStep(const StepSignal::slot_type& slot) - { - return stepSig_.connect(slot); - } - yake::SignalConnection connectToSynchronizedNetStep(const StepSignal::slot_type& slot) - { - return netStepSig_.connect(slot); - } - private: - virtual void onInit() = 0; - virtual void onStep() = 0; - virtual void onShutdown() = 0; - private: - StepSignal stepSig_; - StepSignal netStepSig_; - virtual void onRun() - { - ::SetThreadAffinityMask( ::GetCurrentThread(), 0x1 ); - this->onInit(); - - // main loop - while (!stopRequested()) - { - net::update(); - { - net::scoped_lock lck; - netStepSig_(); - } - stepSig_(); - this->onStep(); - net::native::sleep(0); - } - - this->onShutdown(); - //stepSig_.disconnectAll(); - } - }; -} // namespace yake - using namespace yake; struct ServerApp : public yake::NetServerApp @@ -111,10 +26,6 @@ // register services { net::ServerCommService* commService = new net::ServerCommService(CHANNELID_COMM); - host_.subscribeToClientAccepted( - boost::bind(&net::ServerCommService::onClientConnected,commService,_1) ); - host_.subscribeToClientDisconnected( - boost::bind(&net::ServerCommService::onClientDisconnected,commService,_1) ); host_.addService( net::IServicePtr(commService), "comm" ); /* @@ -185,8 +96,11 @@ }; +#include <yake/base/yakeStderrLog.h> int main(int argc, char* argv[]) { + SharedPtr<logging::log_listener> to_stderr( new logging::stderr_listener() ); + logging::addListener( to_stderr.get() ); try { Configuration cfg; if (argc > 1) Modified: trunk/yake/samples/net/roclient/ROClient.cpp =================================================================== --- trunk/yake/samples/net/roclient/ROClient.cpp 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/samples/net/roclient/ROClient.cpp 2007-04-26 21:52:57 UTC (rev 1756) @@ -1,6 +1,7 @@ #include <samples/net/inprocess/common.h> #include <yake/netrepsvc/netEvents.h> #include <samples/net/roclient/ROClient.h> +#include <samples/net/common/commonEvents.h> namespace yake { namespace ro { @@ -61,7 +62,7 @@ evtConn_->setPolling( true ); - evtConn_->registerEvent( yake::net::c2sEvtJoinReq::ID, net::NetEvent::DIR_ANY, + evtConn_->registerEvent( c2sEvtJoinReq::ID, net::NetEvent::DIR_ANY, c2sEvtJoinReq::create, c2sEvtJoinReq::destroy ); evtConn_->registerEvent( s2cEvtJoinReqReply::ID, net::NetEvent::DIR_ANY, s2cEvtJoinReqReply::create, s2cEvtJoinReqReply::destroy ); Modified: trunk/yake/samples/net/roserver/ROServer.cpp =================================================================== --- trunk/yake/samples/net/roserver/ROServer.cpp 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/samples/net/roserver/ROServer.cpp 2007-04-26 21:52:57 UTC (rev 1756) @@ -85,14 +85,6 @@ outEvtQ_.push_back( EventQEntry(id,evt,cId) ); } */ - SignalConnection server::subscribeToClientAccepted(const ClientAcceptedSignal::slot_type& slot) - { - return sigClientAccepted_.connect(slot); - } - SignalConnection server::subscribeToClientDisconnected(const ClientDisconnectedSignal::slot_type& slot) - { - return sigClientDisconnected_.connect(slot); - } void server::onClientAccepted(iclient&c) { sigClientAccepted_(c.getPeerId()); Modified: trunk/yake/samples/net/roserver/ROServer.h =================================================================== --- trunk/yake/samples/net/roserver/ROServer.h 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/samples/net/roserver/ROServer.h 2007-04-26 21:52:57 UTC (rev 1756) @@ -10,7 +10,7 @@ class client; } - struct server : public net::IServiceHost + struct server : public net::IServerServiceHost { public: server(); @@ -43,12 +43,6 @@ //void queueEvent(const net::PeerId, net::NetEvent*, const net::ChannelId); //void queueEventBroadcast(net::NetEvent*, const net::ChannelId); - typedef SignalX<void(const net::PeerId)> PeerIdSignal; - typedef PeerIdSignal ClientAcceptedSignal; - typedef PeerIdSignal ClientDisconnectedSignal; - yake::SignalConnection subscribeToClientAccepted(const ClientAcceptedSignal::slot_type&); - yake::SignalConnection subscribeToClientDisconnected(const ClientDisconnectedSignal::slot_type&); - //private: const net::s2cEvtClassTable& getClassTableMessage() const; private: @@ -92,8 +86,6 @@ //mutable boost::mutex outEvtQMtx_; //InitEvtClassTableFn initEvtClassTableFn_; - ClientAcceptedSignal sigClientAccepted_; - ClientDisconnectedSignal sigClientDisconnected_; }; } // namespace ro Modified: trunk/yake/samples/physics/paging_terrain/yakeDemo.cpp =================================================================== --- trunk/yake/samples/physics/paging_terrain/yakeDemo.cpp 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/samples/physics/paging_terrain/yakeDemo.cpp 2007-04-26 21:52:57 UTC (rev 1756) @@ -29,13 +29,13 @@ struct TheConfiguration : public raf::ApplicationConfiguration { virtual StringVector getLibraries() - { return MakeStringVector() << "graphicsOgre" << "inputOgre" << "physicsODE"; } + { return MakeStringVector() << "graphicsOgre" << "inputOgreOIS" << "physicsODE"; } virtual StringVector getGraphicsSystems() { return MakeStringVector() << "ogre3d"; } virtual StringVector getInputSystems() - { return MakeStringVector() << "ogre"; } + { return MakeStringVector() << "ois"; } virtual StringVector getPhysicsSystems() { return MakeStringVector() << "ode"; } Modified: trunk/yake/samples/raf/demo1/yakeDemo.cpp =================================================================== --- trunk/yake/samples/raf/demo1/yakeDemo.cpp 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/samples/raf/demo1/yakeDemo.cpp 2007-04-26 21:52:57 UTC (rev 1756) @@ -8,11 +8,13 @@ /** Configuration of the application */ struct TheConfiguration : public raf::ApplicationConfiguration { + // Use "inputOgre" for Ogre 1.2/1.3, "inputOgreOIS" for Ogre 1.4+. virtual StringVector getLibraries() - { return MakeStringVector() << YAKE_LIB("scriptingLua") << YAKE_LIB("graphicsOgre") << YAKE_LIB("inputOgre"); } + { return MakeStringVector() << YAKE_LIB("scriptingLua") << YAKE_LIB("graphicsOgre") << YAKE_LIB("inputOgreOIS"); } + // Use "ogre" for Ogre 1.2/1.3, "ois" for Ogre 1.4+. virtual StringVector getInputSystems() - { return MakeStringVector() << "ogre"; } + { return MakeStringVector() << "ois"; } virtual StringVector getScriptingSystems() { return MakeStringVector() << "lua"; } Modified: trunk/yake/samples/vehicle/yakeDemo.cpp =================================================================== --- trunk/yake/samples/vehicle/yakeDemo.cpp 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/samples/vehicle/yakeDemo.cpp 2007-04-26 21:52:57 UTC (rev 1756) @@ -18,6 +18,7 @@ /** Configuration of the application */ struct TheConfiguration : public raf::ApplicationConfiguration { + // Use "inputOgre" for Ogre 1.2/1.3, "inputOgreOIS" for Ogre 1.4+. virtual StringVector getLibraries() { return MakeStringVector() << YAKE_DYNLIB_NAME("graphicsOgre") << YAKE_DYNLIB_NAME("inputOgreOIS") << YAKE_DYNLIB_NAME("physicsOde"); } @@ -27,6 +28,7 @@ virtual StringVector getGraphicsSystems() { return MakeStringVector() << "ogre3d"; } + // Use "ogre" for Ogre 1.2/1.3, "ois" for Ogre 1.4+. virtual StringVector getInputSystems() { return MakeStringVector() << "ois"; } Modified: trunk/yake/scripts/msvc80/build.cmd =================================================================== --- trunk/yake/scripts/msvc80/build.cmd 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/scripts/msvc80/build.cmd 2007-04-26 21:52:57 UTC (rev 1756) @@ -1,10 +1,10 @@ @echo off +setlocal pushd ..\premake if not exist premake.exe ( echo warning: premake.exe not found in yake/scripts/premake. echo This file is expected to be found in yake/scripts/premake or in global path. ) -setlocal set SOLUTION_TARGET_DIR=msvc80 premake --file yake.lua --target vs2005 %1 %2 %3 popd Copied: trunk/yake/scripts/msvc80/yake.suo (from rev 1755, branches/v0-6-0/yake/scripts/msvc80/yake.suo) =================================================================== (Binary files differ) Modified: trunk/yake/scripts/premake/deps.lua =================================================================== --- trunk/yake/scripts/premake/deps.lua 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/scripts/premake/deps.lua 2007-04-26 21:52:57 UTC (rev 1756) @@ -10,14 +10,18 @@ -------------------------------------- defDep("ogre") defDepIncludePath("ogre", "dependencies/ogrenew/include") -defDepIncludePath("ogre", "dependencies/ogrenew/CEGUIRenderer/include") +defDepIncludePath("ogre", "dependencies/ogrenew/samples/include") defDepLibraryPath("ogre","dependencies/ogrenew/lib") defDepLibrary("ogre","OgreMain","Release") +defDepLibrary("ogre","OgreMain","ReleaseLib") defDepLibrary("ogre","OgreMain","ReleaseWithSymbols") defDepLibrary("ogre","OgreMain_d","Debug") +defDepLibrary("ogre","OgreMain_d","DebugLib") defDepLibrary("ogre","OgreGUIRenderer","Release") +defDepLibrary("ogre","OgreGUIRenderer","ReleaseLib") defDepLibrary("ogre","OgreGUIRenderer","ReleaseWithSymbols") defDepLibrary("ogre","OgreGUIRenderer_d","Debug") +defDepLibrary("ogre","OgreGUIRenderer_d","DebugLib") -------------------------------------- -- Dependency package OIS @@ -26,8 +30,10 @@ defDepIncludePath("ois", "dependencies/ogrenew/include/OIS") defDepLibraryPath("ois","dependencies/ogrenew/lib") defDepLibrary("ois","OIS","Release") +defDepLibrary("ois","OIS","ReleaseLib") defDepLibrary("ois","OIS","ReleaseWithSymbols") defDepLibrary("ois","OIS_d","Debug") +defDepLibrary("ois","OIS_d","DebugLib") -------------------------------------- -- Dependency package OSM @@ -55,8 +61,10 @@ defDepIncludePath("cegui", "dependencies/ogrenew/include/CEGUI") defDepLibraryPath("cegui","dependencies/ogrenew/lib") defDepLibrary("cegui","CEGUIBase","Release") +defDepLibrary("cegui","CEGUIBase","ReleaseLib") defDepLibrary("cegui","CEGUIBase","ReleaseWithSymbols") defDepLibrary("cegui","CEGUIBase_d","Debug") +defDepLibrary("cegui","CEGUIBase_d","DebugLib") -------------------------------------- -- Dependency package ENET (standalone - i.e. compiled into yake::net) @@ -110,8 +118,10 @@ defDepLibraryPath("oalpp","dependencies/openalpp/lib") if (windows) then defDepLibrary("oalpp","oalpp","Release") + defDepLibrary("oalpp","oalpp","ReleaseLib") defDepLibrary("oalpp","oalpp","ReleaseWithSymbols") defDepLibrary("oalpp","oalppd","Debug") + defDepLibrary("oalpp","oalppd","DebugLib") elseif (linux) then defDepLibrary("oalpp","libopenalpp") end Modified: trunk/yake/scripts/premake/samples.lua =================================================================== --- trunk/yake/scripts/premake/samples.lua 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/scripts/premake/samples.lua 2007-04-26 21:52:57 UTC (rev 1756) @@ -123,7 +123,7 @@ end -------------------------------------- -if SAMPLES_NET then +if SAMPLES_NET and SAMPLES_USE_ASIO then makeSample("sampleNetInprocess","samples/net/inprocess") sampleUsesConsole() useComponent("base") Modified: trunk/yake/scripts/premake/yake.lua =================================================================== --- trunk/yake/scripts/premake/yake.lua 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/scripts/premake/yake.lua 2007-04-26 21:52:57 UTC (rev 1756) @@ -105,6 +105,7 @@ elseif (linux) then addMatching("src/base/native/Linux/*.cpp") end + useDep("boost") Copied: trunk/yake/scripts/tools/make_manual.pl (from rev 1755, branches/v0-6-0/yake/scripts/tools/make_manual.pl) =================================================================== --- trunk/yake/scripts/tools/make_manual.pl (rev 0) +++ trunk/yake/scripts/tools/make_manual.pl 2007-04-26 21:52:57 UTC (rev 1756) @@ -0,0 +1,4 @@ +print "Generating manual...\n\n"; + +`cd ../../documentation/manual && rst2html.py --link-stylesheet --stylesheet "yake-manual.css" yake-manual.txt > yake-manual.html`; + Copied: trunk/yake/src/base/templates/yakeSignals.cpp (from rev 1755, branches/v0-6-0/yake/src/base/templates/yakeSignals.cpp) =================================================================== --- trunk/yake/src/base/templates/yakeSignals.cpp (rev 0) +++ trunk/yake/src/base/templates/yakeSignals.cpp 2007-04-26 21:52:57 UTC (rev 1756) @@ -0,0 +1,53 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#include <yake/base/yakePCH.h> +#include <yake/base/templates/yakeSignals.h> + +namespace yake { + + //----------------------------------------------------- + SignalConnectionGroup::SignalConnectionGroup() + { + } + SignalConnectionGroup::~SignalConnectionGroup() + { + this->clearAndDisconnectAll(); + } + void SignalConnectionGroup::clearAndDisconnectAll() + { + for (SignalConnectionList::const_iterator it = connections_.begin(); + it != connections_.end(); ++it) + (*it).disconnect(); + connections_.clear(); + } + SignalConnectionGroup& SignalConnectionGroup::operator += (const SignalConnection& connection) + { + connections_.push_back( connection ); + return *this; + } + +} // yake Modified: trunk/yake/src/base/yake.cpp =================================================================== --- trunk/yake/src/base/yake.cpp 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/src/base/yake.cpp 2007-04-26 21:52:57 UTC (rev 1756) @@ -26,3 +26,5 @@ */ #include <yake/base/yakePCH.h> #include <yake/base/yake.h> + + Copied: trunk/yake/src/base/yakeConfigFile.cpp (from rev 1755, branches/v0-6-0/yake/src/base/yakeConfigFile.cpp) =================================================================== --- trunk/yake/src/base/yakeConfigFile.cpp (rev 0) +++ trunk/yake/src/base/yakeConfigFile.cpp 2007-04-26 21:52:57 UTC (rev 1756) @@ -0,0 +1,149 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ + +#include <yake/base/yakePCH.h> +#include <yake/base/yakeConfigFile.h> + +namespace yake { +namespace base { + + namespace detail { + } // namespace detail + + Configuration::Configuration() : tree_( new tree_type() ) + { + } + Configuration::Configuration(const Configuration& other) : tree_(other.tree_), prefix_(other.prefix_) + { + } + const Configuration& Configuration::operator=(const Configuration& rhs) + { + if (this == &rhs) + return *this; + tree_ = rhs.tree_; + prefix_ = rhs.prefix_; + return *this; + } + Configuration::Configuration(const Configuration& cfg, const String& path) : tree_( cfg.tree_ ), prefix_(path) + { + if (!prefix_.empty()) + { + // make sure there's a trailing '/' + if (prefix_.at( prefix_.size() -1 ) != '/') + prefix_ += '/'; + } + } + void Configuration::copyFrom(const Configuration& other) + { + tree_.reset( new tree_type() ); + if (other.tree_) + *tree_ = *other.tree_; + prefix_ = other.prefix_; + } + Configuration::~Configuration() + { + } + Configuration::const_iterator Configuration::begin(const String& path) const + { + try { + return tree_->get_child('/',prefix_+path).begin(); + } + catch (boost::property_tree::ptree_error&) + { + return tree_->end(); + } + } + Configuration::const_iterator Configuration::end(const String& path) const + { + try { + return tree_->get_child('/',prefix_+path).end(); + } + catch (boost::property_tree::ptree_error&) + { + return tree_->end(); + } + } + bool Configuration::exists(const String& path) const + { + try { + tree_->get_child('/',prefix_+path); + return true; + } + catch (boost::property_tree::ptree_error&) + { + return false; + } + } + String Configuration::get(const String& pathToValue, const String& defaultValue) const + { + try { + return tree_->get<String>('/',prefix_+pathToValue); + } + catch (...) + { + return defaultValue; + } + } + void Configuration::readFromFile(const String& fn, const String& insertAt) + { + YAKE_ASSERT( insertAt.empty() && "not yet supported" ); + std::ifstream in(fn.c_str()); + if (!in.is_open()) + return; //@todo + boost::property_tree::read_info(in,*tree_); + } + void Configuration::readFromXML(const String& fn, const String& insertAt) + { + YAKE_ASSERT( insertAt.empty() && "not yet supported" ); + std::ifstream in(fn.c_str()); + if (!in.is_open()) + return; //@todo + boost::property_tree::read_xml(in,*tree_); + } + void Configuration::writeToFile(const String& fn, const String& startAt) + { + YAKE_ASSERT( startAt.empty() && "not yet supported" ); + //boost::property_tree::write_info(cout,*tree_); + + std::ofstream out(fn.c_str()); + if (!out.is_open()) + return; //@todo + boost::property_tree::write_info(out,*tree_); + } + void Configuration::writeToXML(const String& fn, const String& startAt) + { + YAKE_ASSERT( startAt.empty() && "not yet supported" ); + //boost::property_tree::write_xml(cout,*tree_); + + std::ofstream out(fn.c_str()); + if (!out.is_open()) + return; //@todo + boost::property_tree::write_xml(out,*tree_); + } + +} // base +} // yake Modified: trunk/yake/src/input/yakeActionMap.cpp =================================================================== --- trunk/yake/src/input/yakeActionMap.cpp 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/src/input/yakeActionMap.cpp 2007-04-26 21:52:57 UTC (rev 1756) @@ -476,8 +476,6 @@ ActionCondition::Result MouseMoveActionCondition::operator()() { - real FALSE = 0.0f; - const math::Rectangle& maxMovement = mMouse->getClip(); const real maxMovementX = maxMovement.getWidth(); const real maxMovementY = maxMovement.getWidth(); Modified: trunk/yake/src/netsvc/netServiceHost.cpp =================================================================== --- trunk/yake/src/netsvc/netServiceHost.cpp 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/src/netsvc/netServiceHost.cpp 2007-04-26 21:52:57 UTC (rev 1756) @@ -32,6 +32,22 @@ namespace net { //----------------------------------------------------------------------------- + IServerServiceHost::IServerServiceHost() + { + } + IServerServiceHost::~IServerServiceHost() + { + } + SignalConnection IServerServiceHost::subscribeToClientAccepted(const ClientAcceptedSignal::slot_type& slot) + { + return sigClientAccepted_.connect( slot ); + } + SignalConnection IServerServiceHost::subscribeToClientDisconnected(const ClientDisconnectedSignal::slot_type& slot) + { + return sigClientDisconnected_.connect( slot ); + } + + //----------------------------------------------------------------------------- IServiceHost::IServiceHost() : running_(false) { } Modified: trunk/yake/src/netsvc/service/netServerCommService.cpp =================================================================== --- trunk/yake/src/netsvc/service/netServerCommService.cpp 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/src/netsvc/service/netServerCommService.cpp 2007-04-26 21:52:57 UTC (rev 1756) @@ -40,20 +40,37 @@ void ServerCommService::onStart(IServiceHost& host) { YAKE_LOG_INFORMATION("server-comm", "starting comm service"); + + // + try { + IServerServiceHost& serverHost = dynamic_cast<IServerServiceHost&>(host); + connections_ += serverHost.subscribeToClientAccepted( + boost::bind(&net::ServerCommService::onClientConnected,this,_1) ); + connections_ += serverHost.subscribeToClientDisconnected( + boost::bind(&net::ServerCommService::onClientDisconnected,this,_1) ); + } + catch (std::bad_cast&) + { + YAKE_LOG_ERROR("server-comm", "service host is not a 'server service host'!"); + throw net::Exception("service host is not a 'server service host'",__FILE__,__LINE__); + } + + // evtConn_ = host.getEventConnection(); evtConn_->registerEvent( s2cEvtCommMsg::ID, NetEvent::DIR_ANY, s2cEvtCommMsg::create, s2cEvtCommMsg::destroy ); evtConn_->registerEvent( c2sEvtCommJoinChannel::ID, NetEvent::DIR_ANY, c2sEvtCommJoinChannel::create, c2sEvtCommJoinChannel::destroy ); - host.subscribeToNetEvent( s2cEvtCommMsg::ID, commChannelId_, - boost::bind(&ServerCommService::onProcessMsg,this,_1,_2,_3)); - host.subscribeToNetEvent( c2sEvtCommJoinChannel::ID, commChannelId_, - boost::bind(&ServerCommService::onProcessJoinRequest,this,_1,_2,_3)); + connections_ += host.subscribeToNetEvent( s2cEvtCommMsg::ID, commChannelId_, + boost::bind(&ServerCommService::onProcessMsg,this,_1,_2,_3)); + connections_ += host.subscribeToNetEvent( c2sEvtCommJoinChannel::ID, commChannelId_, + boost::bind(&ServerCommService::onProcessJoinRequest,this,_1,_2,_3)); } void ServerCommService::onStop(IServiceHost&) { YAKE_LOG_INFORMATION("server-comm", "stopping comm service"); + connections_.clearAndDisconnectAll(); } void ServerCommService::onClientConnected(const PeerId pId) { Copied: trunk/yake/src/plugins/inputOgreOIS (from rev 1755, branches/v0-6-0/yake/src/plugins/inputOgreOIS) Deleted: trunk/yake/src/plugins/inputOgreOIS/InputSystemOgreOIS.cpp =================================================================== --- branches/v0-6-0/yake/src/plugins/inputOgreOIS/InputSystemOgreOIS.cpp 2007-04-26 21:35:36 UTC (rev 1755) +++ trunk/yake/src/plugins/inputOgreOIS/InputSystemOgreOIS.cpp 2007-04-26 21:52:57 UTC (rev 1756) @@ -1,299 +0,0 @@ -/* - ------------------------------------------------------------------------------------ - This file is part of YAKE - Copyright (c) 2004 - 2008 The YAKE Team - For the latest information visit http://www.yake.org - ------------------------------------------------------------------------------------ - This program is free software; you can redistribute it and/or modify it under - the terms of the GNU Lesser General Public License as published by the Free Software - Foundation; either version 2 of the License, or (at your option) any later - version. - - This program is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License along with - this program; if not, write to the Free Software Foundation, Inc., 59 Temple - Place - Suite 330, Boston, MA 02111-1307, USA, or go to - http://www.gnu.org/copyleft/lesser.txt. - ------------------------------------------------------------------------------------ - If you are interested in another license model contact the Yake Team via - E-Mail: te...@ya.... - For more information see the LICENSE file in the root directory of the - source code distribution. - ------------------------------------------------------------------------------------ -*/ -#include <yake/plugins/inputOgreOIS/yakePCH.h> -#include <yake/input/yakeInputSystem.h> -#include <yake/plugins/inputOgreOIS/InputSystemOgreOIS.h> -#include <OIS.h> -#include <Ogre.h> - -namespace yake { -namespace input { - - YAKE_REGISTER_CONCRETE( InputSystemOgreOIS ); - - //----------------------------------------------------------------------- - MouseDeviceOgreOIS::MouseDeviceOgreOIS(OIS::Mouse * pMouse) : - mMouse(pMouse), - mPosition(math::Vector3::kZero) - { - mButtons[0] = mButtons[1] = mButtons[2] = false; - - Rectangle rect; - rect.min = Point3(0,0,0); - rect.max = Point3(Ogre::Root::getSingleton().getAutoCreatedWindow()->getWidth(), - Ogre::Root::getSingleton().getAutoCreatedWindow()->getHeight(), - 0); - setClip( rect ); - } - - //----------------------------------------------------------------------- - MouseDeviceOgreOIS::~MouseDeviceOgreOIS() - { - } - - //----------------------------------------------------------------------- - int MouseDeviceOgreOIS::getNumButtons() const - { - return MB_LAST; - } - - //----------------------------------------------------------------------- - bool MouseDeviceOgreOIS::isButtonDown( MouseButton button ) const - { - YAKE_ASSERT( 0 <= button && button <= MB_LAST )(button)(MB_LAST); - if (button > MB_LAST) return false; - if (button < 0) return false; - return mButtons[ button ]; - } - - //----------------------------------------------------------------------- - math::Vector3 MouseDeviceOgreOIS::getPosition() const - { - return mPosition; - } - - //----------------------------------------------------------------------- - void MouseDeviceOgreOIS::poll() - { - if (mMouse) - { - mMouse->capture(); - - const OIS::MouseState &state = mMouse->getMouseState(); - mButtons[MBT_LEFT] = state.buttonDown(OIS::MB_Left); - mButtons[MBT_RIGHT] = state.buttonDown(OIS::MB_Right); - mButtons[MBT_MIDDLE] = state.buttonDown(OIS::MB_Middle); - mPosition.x += state.X.rel; - mPosition.y += state.Y.rel; - mPosition.z += state.Z.rel; - } - } - - //----------------------------------------------------------------------- - KeyboardDeviceOgreOIS::KeyboardDeviceOgreOIS(OIS::Keyboard * pKeyboard) : mKeyboard(pKeyboard) - { - } - - //----------------------------------------------------------------------- - KeyboardDeviceOgreOIS::~KeyboardDeviceOgreOIS() - { - } - - //----------------------------------------------------------------------- - void KeyboardDeviceOgreOIS::poll() - { - if (mKeyboard) - mKeyboard->capture(); - } - - //----------------------------------------------------------------------- - bool KeyboardDeviceOgreOIS::isKeyDown( KeyCode key ) const - { - if (!mKeyboard) - return false; - return mKeyboard->isKeyDown( static_cast<OIS::KeyCode>(key) ); - } - - //----------------------------------------------------------------------- - JoystickDeviceOgreOIS::JoystickDeviceOgreOIS(OIS::Joystick * pJoystick) : mJoystick(pJoystick) - { - // TODO - } - - JoystickDeviceOgreOIS::~JoystickDeviceOgreOIS() - { - // TODO - } - - bool JoystickDeviceOgreOIS::isButtonDown( int button ) const - { - // TODO - return false; - } - - uint16 JoystickDeviceOgreOIS::getHatPosition() const - { - // TODO - return 0; - } - - int JoystickDeviceOgreOIS::getNumAxes() const - { - // TODO - return 0; - } - - real JoystickDeviceOgreOIS::getAxisPosition( int axis ) const - { - // TODO - return 0; - } - - void JoystickDeviceOgreOIS::setAxisDeadZone( int axis, real deadzoneMin, real deadzoneMax) - { - // TODO - return; - } - - std::pair<real,real> JoystickDeviceOgreOIS::getBallPosition() const - { - // TODO - return std::make_pair(0,0); - } - - //----------------------------------------------------------------------- - InputSystemOgreOIS::InputSystemOgreOIS() - { - OIS::ParamList paramList; - size_t hWnd = 0; - Ogre::RenderWindow* pWin = Ogre::Root::getSingleton().getAutoCreatedWindow(); - YAKE_ASSERT( pWin ).error("Need a valid render window!"); - mInputManager = 0; - if (pWin) - { - pWin->getCustomAttribute("WINDOW", &hWnd); - paramList.insert(OIS::ParamList::value_type("WINDOW", Ogre::StringConverter::toString(hWnd))); - mInputManager = OIS::InputManager::createInputSystem( paramList ); - } - YAKE_ASSERT( mInputManager ).debug("Could not create input manager."); - } - - //----------------------------------------------------------------------- - InputSystemOgreOIS::~InputSystemOgreOIS() - { - for (ActiveDeviceList::const_iterator it = mActiveDevices.begin(); it != mActiveDevices.end(); ++it) - { - if (mInputManager && (*it).oisDev) - mInputManager->destroyInputObject((*it).oisDev); - delete (*it).device; - } - if (mInputManager) - OIS::InputManager::destroyInputSystem( mInputManager ); - } - - //----------------------------------------------------------------------- - void InputSystemOgreOIS::update() - { - for (ActiveDeviceList::const_iterator it = mActiveDevices.begin(); it != mActiveDevices.end(); ++it) - (*it).device->poll(); - } - - //----------------------------------------------------------------------- - void InputSystemOgreOIS::getActiveDevices( std::vector< InputDevice* > & devices ) const - { - devices.clear(); - for (ActiveDeviceList::const_iterator it = mActiveDevices.begin(); it != mActiveDevices.end(); ++it) - devices.push_back( (*it).device ); - } - - //----------------------------------------------------------------------- - InputDevice* InputSystemOgreOIS::activateDevice( const String & deviceName ) - { - if (getDevice(deviceName)) - return 0; - - if (deviceName == "Keyboard") - { - OIS::Keyboard* pOISKeyboard = 0; - if (mInputManager) - pOISKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject(OIS::OISKeyboard, false)); - input::KeyboardDevice* pKeyboard = new KeyboardDeviceOgreOIS( pOISKeyboard ); - YAKE_ASSERT( pKeyboard ).debug("Out of memory ?"); - if (!pKeyboard) - { - if (pOISKeyboard) - mInputManager->destroyInputObject(pOISKeyboard); - return 0; - } - - ActiveDevice dev; - dev.name = "Keyboard"; - dev.type = IDT_KEYBOARD; - dev.oisDev = pOISKeyboard; - dev.device = pKeyboard; - mActiveDevices.push_back( dev ); - return pKeyboard; - } - else if (deviceName == "Mouse") - { - OIS::Mouse* pOISMouse = 0; - if (mInputManager) - pOISMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject(OIS::OISMouse, false)); - input::MouseDevice* pMouse = new MouseDeviceOgreOIS( pOISMouse ); - YAKE_ASSERT( pMouse ).debug("Out of memory ?"); - if (!pMouse) - { - if (pOISMouse) - mInputManager->destroyInputObject(pOISMouse); - return 0; - } - - ActiveDevice dev; - dev.name = "Mouse"; - dev.type = IDT_MOUSE; - dev.oisDev = pOISMouse; - dev.device = pMouse; - mActiveDevices.push_back( dev ); - return pMouse; - } - else if (deviceName == "Joystick") - { - // TODO - return 0; - } - return 0; - } - - //----------------------------------------------------------------------- - InputDevice* InputSystemOgreOIS::getDevice( const String & deviceName ) const - { - for (ActiveDeviceList::const_iterator it = mActiveDevices.begin(); it != mActiveDevices.end(); ++it) - if ((*it).name == deviceName) - return (*it).device; - return 0; - } - - //----------------------------------------------------------------------- - InputSystemOgreOIS::DeviceEntryList InputSystemOgreOIS::getAvailableDevices() - { - DeviceEntryList list; - DeviceListEntry entry; - - entry.name = "Mouse"; - entry.type = IDT_MOUSE; - list.push_back( entry ); - - entry.name = "Keyboard"; - entry.type = IDT_KEYBOARD; - list.push_back( entry ); - - return list; - } - -} -} - Copied: trunk/yake/src/plugins/inputOgreOIS/InputSystemOgreOIS.cpp (from rev 1755, branches/v0-6-0/yake/src/plugins/inputOgreOIS/InputSystemOgreOIS.cpp) =================================================================== --- trunk/yake/src/plugins/inputOgreOIS/InputSystemOgreOIS.cpp (rev 0) +++ trunk/yake/src/plugins/inputOgreOIS/InputSystemOgreOIS.cpp 2007-04-26 21:52:57 UTC (rev 1756) @@ -0,0 +1,299 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#include <yake/plugins/inputOgreOIS/yakePCH.h> +#include <yake/input/yakeInputSystem.h> +#include <yake/plugins/inputOgreOIS/InputSystemOgreOIS.h> +#include <OIS.h> +#include <Ogre.h> + +namespace yake { +namespace input { + + YAKE_REGISTER_CONCRETE( InputSystemOgreOIS ); + + //----------------------------------------------------------------------- + MouseDeviceOgreOIS::MouseDeviceOgreOIS(OIS::Mouse * pMouse) : + mMouse(pMouse), + mPosition(math::Vector3::kZero) + { + mButtons[0] = mButtons[1] = mButtons[2] = false; + + Rectangle rect; + rect.min = Point3(0,0,0); + rect.max = Point3(Ogre::Root::getSingleton().getAutoCreatedWindow()->getWidth(), + Ogre::Root::getSingleton().getAutoCreatedWindow()->getHeight(), + 0); + setClip( rect ); + } + + //----------------------------------------------------------------------- + MouseDeviceOgreOIS::~MouseDeviceOgreOIS() + { + } + + //----------------------------------------------------------------------- + int MouseDeviceOgreOIS::getNumButtons() const + { + return MB_LAST; + } + + //----------------------------------------------------------------------- + bool MouseDeviceOgreOIS::isButtonDown( MouseButton button ) const + { + YAKE_ASSERT( 0 <= button && button <= MB_LAST )(button)(MB_LAST); + if (button > MB_LAST) return false; + if (button < 0) return false; + return mButtons[ button ]; + } + + //----------------------------------------------------------------------- + math::Vector3 MouseDeviceOgreOIS::getPosition() const + { + return mPosition; + } + + //----------------------------------------------------------------------- + void MouseDeviceOgreOIS::poll() + { + if (mMouse) + { + mMouse->capture(); + + const OIS::MouseState &state = mMouse->getMouseState(); + mButtons[MBT_LEFT] = state.buttonDown(OIS::MB_Left); + mButtons[MBT_RIGHT] = state.buttonDown(OIS::MB_Right); + mButtons[MBT_MIDDLE] = state.buttonDown(OIS::MB_Middle); + mPosition.x += state.X.rel; + mPosition.y += state.Y.rel; + mPosition.z += state.Z.rel; + } + } + + //----------------------------------------------------------------------- + KeyboardDeviceOgreOIS::KeyboardDeviceOgreOIS(OIS::Keyboard * pKeyboard) : mKeyboard(pKeyboard) + { + } + + //----------------------------------------------------------------------- + KeyboardDeviceOgreOIS::~KeyboardDeviceOgreOIS() + { + } + + //----------------------------------------------------------------------- + void KeyboardDeviceOgreOIS::poll() + { + if (mKeyboard) + mKeyboard->capture(); + } + + //----------------------------------------------------------------------- + bool KeyboardDeviceOgreOIS::isKeyDown( KeyCode key ) const + { + if (!mKeyboard) + return false; + return mKeyboard->isKeyDown( static_cast<OIS::KeyCode>(key) ); + } + + //----------------------------------------------------------------------- + JoystickDeviceOgreOIS::JoystickDeviceOgreOIS(OIS::Joystick * pJoystick) : mJoystick(pJoystick) + { + // TODO + } + + JoystickDeviceOgreOIS::~JoystickDeviceOgreOIS() + { + // TODO + } + + bool JoystickDeviceOgreOIS::isButtonDown( int button ) const + { + // TODO + return false; + } + + uint16 JoystickDeviceOgreOIS::getHatPosition() const + { + // TODO + return 0; + } + + int JoystickDeviceOgreOIS::getNumAxes() const + { + // TODO + return 0; + } + + real JoystickDeviceOgreOIS::getAxisPosition( int axis ) const + { + // TODO + return 0; + } + + void JoystickDeviceOgreOIS::setAxisDeadZone( int axis, real deadzoneMin, real deadzoneMax) + { + // TODO + return; + } + + std::pair<real,real> JoystickDeviceOgreOIS::getBallPosition() const + { + // TODO + return std::make_pair(0,0); + } + + //----------------------------------------------------------------------- + InputSystemOgreOIS::InputSystemOgreOIS() + { + OIS::ParamList paramList; + size_t hWnd = 0; + Ogre::RenderWindow* pWin = Ogre::Root::getSingleton().getAutoCreatedWindow(); + YAKE_ASSERT( pWin ).error("Need a valid render window!"); + mInputManager = 0; + if (pWin) + { + pWin->getCustomAttribute("WINDOW", &hWnd); + paramList.insert(OIS::ParamList::value_type("WINDOW", Ogre::StringConverter::toString(hWnd))); + mInputManager = OIS::InputManager::createInputSystem( paramList ); + } + YAKE_ASSERT( mInputManager ).debug("Could not create input manager."); + } + + //----------------------------------------------------------------------- + InputSystemOgreOIS::~InputSystemOgreOIS() + { + for (ActiveDeviceList::const_iterator it = mActiveDevices.begin(); it != mActiveDevices.end(); ++it) + { + if (mInputManager && (*it).oisDev) + mInputManager->destroyInputObject((*it).oisDev); + delete (*it).device; + } + if (mInputManager) + OIS::InputManager::destroyInputSystem( mInputManager ); + } + + //----------------------------------------------------------------------- + void InputSystemOgreOIS::update() + { + for (ActiveDeviceList::const_iterator it = mActiveDevices.begin(); it != mActiveDevices.end(); ++it) + (*it).device->poll(); + } + + //----------------------------------------------------------------------- + void InputSystemOgreOIS::getActiveDevices( std::vector< InputDevice* > & devices ) const + { + devices.clear(); + for (ActiveDeviceList::const_iterator it = mActiveDevices.begin(); it != mActiveDevices.end(); ++it) + devices.push_back( (*it).device ); + } + + //----------------------------------------------------------------------- + InputDevice* InputSystemOgreOIS::activateDevice( const String & deviceName ) + { + if (getDevice(deviceName)) + return 0; + + if (deviceName == "Keyboard") + { + OIS::Keyboard* pOISKeyboard = 0; + if (mInputManager) + pOISKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject(OIS::OISKeyboard, false)); + input::KeyboardDevice* pKeyboard = new KeyboardDeviceOgreOIS( pOISKeyboard ); + YAKE_ASSERT( pKeyboard ).debug("Out of memory ?"); + if (!pKeyboard) + { + if (pOISKeyboard) + mInputManager->destroyInputObject(pOISKeyboard); + return 0; + } + + ActiveDevice dev; + dev.name = "Keyboard"; + dev.type = IDT_KEYBOARD; + dev.oisDev = pOISKeyboard; + dev.device = pKeyboard; + mActiveDevices.push_back( dev ); + return pKeyboard; + } + else if (deviceName == "Mouse") + { + OIS::Mouse* pOISMouse = 0; + if (mInputManager) + ... [truncated message content] |
From: <psy...@us...> - 2007-06-13 17:24:14
|
Revision: 1760 http://svn.sourceforge.net/yake/?rev=1760&view=rev Author: psyclonist Date: 2007-06-13 10:24:14 -0700 (Wed, 13 Jun 2007) Log Message: ----------- added library "net2" and first sample "net2/message1" Modified Paths: -------------- trunk/yake/scripts/premake/samples.lua trunk/yake/scripts/premake/yake.lua Added Paths: ----------- trunk/yake/samples/net2/ trunk/yake/samples/net2/message1/ trunk/yake/samples/net2/message1/demo.cpp trunk/yake/yake/net2/ trunk/yake/yake/net2/async_send.h trunk/yake/yake/net2/error.h trunk/yake/yake/net2/message_decoder.h trunk/yake/yake/net2/net.h trunk/yake/yake/net2/packet.h trunk/yake/yake/net2/packet_connection.h trunk/yake/yake/net2/packet_dispatcher.h trunk/yake/yake/net2/resolver.h trunk/yake/yake/net2/server.h trunk/yake/yake/net2/simple_serialization.h trunk/yake/yake/net2/stats.h trunk/yake/yake/net2/types.h trunk/yake/yake/net2/utils.h Added: trunk/yake/samples/net2/message1/demo.cpp =================================================================== --- trunk/yake/samples/net2/message1/demo.cpp (rev 0) +++ trunk/yake/samples/net2/message1/demo.cpp 2007-06-13 17:24:14 UTC (rev 1760) @@ -0,0 +1,151 @@ +#include <yake/base/yakePrerequisites.h> +#include <yake/net2/net.h> +#undef min +#undef max +#include <yake/base/yake.h> // for YAKE_ASSERT etc +#include <boost/bind.hpp> + +using namespace yake; + +/** A simple server class for managing packet connections. +*/ +struct server +{ +private: + server& operator=(const server&); + server(const server&); +public: + server(const net::address&, const uint16 port, const uint32 maxClients); + ~server(); + +private: + void onConnectionError(const net::Error& e); +private: + net::address addr_; + uint32 maxClients_; +}; + +#define YAKE_LOG_INFORMATION_X(X) \ +{ \ +std::stringstream ss; \ +ss << X; \ +YAKE_LOG_INFORMATION("demo",(ss.str())); \ +} + +struct Hello +{ + enum { ID = 1 }; + Hello(const std::string& msg = "") : message(msg) + {} + std::string message; +}; +namespace yake { +namespace net { + template<class Ar> + Ar& serialize(Ar& ar, Hello& rhs) + { + ar & rhs.message; + return ar; + } +} // namespace net +} // namespace yake + +#include <yake/base/yakeStderrLog.h> +#include <boost/thread/thread.hpp> +int main(int argc, char* argv[]) +{ + SharedPtr<logging::log_listener> to_stderr( new logging::stderr_listener() ); + logging::addListener( to_stderr.get() ); + + // server + try { + YAKE_LOG("demo", "starting server..."); + + namespace placeholders = net::placeholders; + + net::io_service io; + typedef net::TCPServer<net::TCPPacketConnection<>,net::ConnectionFilterByIP> server_type; + + + // Create a server object for listening at localhost's port 40000 and + // creating TCPPacketConnection<> objects for each incoming TCP connections. + //typedef net::TCPServer<> server_type; + typedef net::TCPServer<net::TCPPacketConnection<>,net::ConnectionFilterByIP> server_type; + struct ServerHandler + { + typedef server_type::packet_type packet_type; + + // NOT THREAD SAFE: We need one per connection, right? + static net::IncomingPacketDispatcher<>& dispatcher(/*server_type::connection_weakptr conn*/) + { + static net::IncomingPacketDispatcher<> s_dispatcher; + return s_dispatcher; + } + + static void onConnection(server_type::connection_weakptr conn, const net::Error& e) + { + std::cout << "app:onConnection: " << e.code() << "=" << e.what() << "\n"; + if (e == net::Error::connected) + { + net::setDecoder<Hello>( dispatcher(), + boost::bind(&ServerHandler::onHello,conn,placeholders::error,placeholders::message) ); + } + else if (!e) + { + net::setDecoder<Hello>( dispatcher(), 0 ); + } + } + static void onHello(server_type::connection_weakptr conn, const net::Error& e, const Hello& hello) + { + if (!e) + std::cerr << "app: recv'd but FAILED to decode HELLO: " << e << "\n"; + else + { + std::cout << "app: recv'd & decoded HELLO: " << hello.message << "\n"; + if (conn.lock()) + net::async_send( *conn.lock(), Hello("PONG") ); + } + } + static void onPacket(server_type::connection_weakptr conn, const packet_type& pckt) + { + std::cout << "app: recv'd packet. payload: " << pckt.header().payloadSize << " byte(s)\n"; + + dispatcher().dispatch( pckt ); + } + }; + //static boost::asio::strand ServerHandler::strand_(io); + server_type server(io, + "localhost", // <- throws exception of invalid + 40000, + boost::bind(&ServerHandler::onConnection,_1,_2), + boost::bind(&ServerHandler::onPacket,_1,_2)); + + // Test access of policy-enriched interface: + net::TCPIncomingConnectionFilter::address_set blackList; + //blackList.insert( net::detail::makeIpAddress("localhost") ); + server.ipFilter().setBlackList(blackList); + + // Run the server processing in a different thread. + // Note that, by subsequently creating additional threads + // running the same io_service::run() method we can increase + // the number of threads for the TCP server. + boost::thread netThread( boost::bind(&net::io_service::run,&io) ); + //boost::thread netThread2( boost::bind(&net::io_service::run,&io) ); + + // Wait for the server process to finish. + // @todo At the moment, it only finishes if it fails. + netThread.join(); + //netThread2.join(); + } + catch (boost::asio::error& ex) + { + YAKE_LOG_ERROR("demo",String("ASIO EXCEPTION: ") + ex.what()); + } + catch (std::exception& ex) + { + YAKE_LOG_ERROR("demo",String("EXCEPTION: ") + ex.what()); + } + + return 0; +} + Modified: trunk/yake/scripts/premake/samples.lua =================================================================== --- trunk/yake/scripts/premake/samples.lua 2007-06-11 20:52:23 UTC (rev 1759) +++ trunk/yake/scripts/premake/samples.lua 2007-06-13 17:24:14 UTC (rev 1760) @@ -13,7 +13,7 @@ makeExeProject("yake_samples") -------------------------------------- - -- create dependency packages + -- create dependency p -------------------------------------- dofile("deps.lua") else @@ -116,6 +116,14 @@ -------------------------------------- if SAMPLES_NET then + makeSample("sampleNetMessage1","samples/net2/message1") + sampleUsesConsole() + useComponent("base") + --useComponent("net") +end + +-------------------------------------- +if SAMPLES_NET then makeSample("sampleNetPacket","samples/net/packet") sampleUsesConsole() useComponent("base") Modified: trunk/yake/scripts/premake/yake.lua =================================================================== --- trunk/yake/scripts/premake/yake.lua 2007-06-11 20:52:23 UTC (rev 1759) +++ trunk/yake/scripts/premake/yake.lua 2007-06-13 17:24:14 UTC (rev 1760) @@ -157,6 +157,10 @@ addDependency("model") -------------------------------------- +makeComponent("net2","YAKE_NET_EXPORTS") +--addDependency("base") -- for logging + +-------------------------------------- makeComponent("net","YAKE_NET_EXPORTS") addDependency("base") Added: trunk/yake/yake/net2/async_send.h =================================================================== --- trunk/yake/yake/net2/async_send.h (rev 0) +++ trunk/yake/yake/net2/async_send.h 2007-06-13 17:24:14 UTC (rev 1760) @@ -0,0 +1,77 @@ +#ifndef NET_ASYNC_SEND_H +#define NET_ASYNC_SEND_H + +#include "types.h" +#include "packet.h" +#include "packet_connection.h" + +namespace yake { +namespace net { + + /** Serialize and send message asynchronously over the + given packet connection, providing a handler for handling + result information (ok, failed_to_send, etc). + The packet passed in will be used for sending. + + @note Handler is to have the signature: void(const net::Error&) + + @note Pt has to be of type:: PacketType<..>::pointer, i.e. it's a shared_ptr. + + @note For details on the requirements for the message type + see IncomingMessageDecoderDispatcher<>::setHandler() and + MessageDecoder<>. + */ + template<class Mt, class Pt, class Ct, typename Handler> + void async_send(Ct& conn, Pt pckt, const Mt& msg, Handler handler) + { + assert( pckt ); + BinaryOutArchive ar( pckt->payload(), Pt::value_type::nMaxPayloadSize ); + ar & const_cast<Mt&>(msg); + pckt->setId(Mt::ID); + pckt->setPayloadSize(ar.curr()); + conn.async_send( pckt, handler ); + } + /** Serialize and send message asynchronously over the + given packet connection, providing a handler for handling + result information (ok, failed_to_send, etc). + + @note Handler is to have the signature: void(const net::Error&) + + @note For details on the requirements for the message type + see IncomingMessageDecoderDispatcher<>::setHandler() and + MessageDecoder<>. + */ + template<class Mt, class Ct, typename Handler> + void async_send(Ct& conn, const Mt& msg, Handler handler) + { + typedef typename Ct::packet_type packet_type; + typename packet_type::pointer pckt(new packet_type()); + BinaryOutArchive ar( pckt->payload(), packet_type::nMaxPayloadSize ); + ar & const_cast<Mt&>(msg); + pckt->setId(Mt::ID); + pckt->setPayloadSize(ar.curr()); + conn.async_send( pckt, handler ); + } + /** Serialize and send message asynchronously over the + given packet connection. + + @note For details on the requirements for the message type + see IncomingMessageDecoderDispatcher<>::setHandler() and + MessageDecoder<>. + */ + template<class Mt, class Ct> + void async_send(Ct& conn, const Mt& msg) + { + typedef typename Ct::packet_type packet_type; + typename packet_type::pointer pckt(new packet_type()); + BinaryOutArchive ar( pckt->payload(), packet_type::nMaxPayloadSize ); + ar & const_cast<Mt&>(msg); + pckt->setId(Mt::ID); + pckt->setPayloadSize(ar.curr()); + conn.async_send( pckt ); + } + +} // namespace net +} // namespace yake + +#endif \ No newline at end of file Added: trunk/yake/yake/net2/error.h =================================================================== --- trunk/yake/yake/net2/error.h (rev 0) +++ trunk/yake/yake/net2/error.h 2007-06-13 17:24:14 UTC (rev 1760) @@ -0,0 +1,71 @@ +#ifndef NET_ERROR_H +#define NET_ERROR_H + +#include "types.h" + +namespace yake { +namespace net { + + struct Error + { + enum Code + { + ok = 0, + // the following codes can occur during connection lifetime: + connected, + disconnected, + could_not_resolve, + could_not_connect, + time_out, + // during packet sending: + failed_to_send, + // + failed_to_receive, + // + operation_aborted, + // message(s): + failed_to_decode + }; + Error(const Code code = ok) : code_(code) + { + } + Code code() const + { + return code_; + } + operator bool() const + { + return (code_ == ok); + } + bool operator == (const Code code) const + { + return (code_ == code); + } + const char* what() const + { + return codeAsString(code_); + } + static const char* codeAsString(const Code code) + { + static const char* msg[] = { + "ok", + "connected", + "disconnected", + "failed to resolve", + "failed to connect", + "timed out", + "failed to send", + "failed to receive", + "operation aborted" + }; + static char unknown[] = "unknown"; + return (code < (sizeof(msg)/sizeof(msg[0]))) ? msg[code] : unknown; + } + private: + Code code_; + }; + +} // namespace net +} // namespace yake + +#endif \ No newline at end of file Added: trunk/yake/yake/net2/message_decoder.h =================================================================== --- trunk/yake/yake/net2/message_decoder.h (rev 0) +++ trunk/yake/yake/net2/message_decoder.h 2007-06-13 17:24:14 UTC (rev 1760) @@ -0,0 +1,109 @@ +#ifndef NET_MESSAGE_DECODER_H +#define NET_MESSAGE_DECODER_H + +#include "types.h" +#include "packet_dispatcher.h" +#include "simple_serialization.h" + +namespace yake { +namespace net { + + /** Base class for message decoders, declares types and interface. + */ + template<class PacketType = net::Packet<net::DefaultPacketTraits> > + struct MessageDecoderBase : public boost::noncopyable + { + typedef boost::shared_ptr<MessageDecoderBase> pointer; + typedef PacketType packet_type; + virtual ~MessageDecoderBase() {} + + virtual void decode(const packet_type& msg) = 0; + }; + + /** Template class for providing decoders for messages that adhere + to a certain standard. + + For the given message type 'Mt' a specialization of serialize<> needs to exist + in the correct namespace. For an example, see IncomingMessageDecoderDispatcher::setHandler(). + + Furthermore, the the message type 'Mt' needs to have a default constructor. + + see @IncomingMessageDecoderDispatcher::setHandler() + */ + template<typename Mt, class PacketType = net::Packet<net::DefaultPacketTraits> > + struct MessageDecoder : MessageDecoderBase<PacketType> + { + typedef Mt message_type; + typedef boost::shared_ptr<MessageDecoder<message_type,packet_type> > pointer; + + MessageDecoder(boost::function<void(const net::Error&,const message_type&)> handler) : handler_(handler) + { + assert( handler_ ); + } + /** Implements decoding of a binary packet into a message struct. */ + virtual void decode(const packet_type& pckt) + { + assert( handler_ ); + if (!handler_) + return; + + std::cout << "decoding '" << typeid(message_type).name() << "'\n"; + message_type msg; //in try block? + try { + net::BinaryInArchive ar( pckt.payload(), pckt.payloadSize() ); + ::yake::net::serialize(ar,msg); + + handler_( net::Error::ok, msg ); + } + catch (std::exception& ex) + { + std::cerr << "ser: FAILED to DECODE: " << ex.what() << "\n"; + //@todo move this out of the exception handler so that the handler + // can throw, too? + handler_( net::Error::failed_to_decode, msg ); + } + } + private: + boost::function<void(const net::Error&,const Mt&)> handler_; + }; + + /** (Helper) function to create & register a message decoder + with a packet dispatcher. + + For details on the requirements for the message type + see IncomingMessageDecoderDispatcher<>::setHandler() and + MessageDecoder<>. + + @code + IncomingMessageDecoderDispatcher<> decoder; + setDecoder<MyMessage>( decoder, &onMyMessage ); + @endcode + + @code + // member function of 'this': + setDecoder<MyMessage>( decoder, boost::bind(&MyClass::onMessage,this,_1,_2) ); + @endcode + */ + template<typename Mt, class PacketDispatcherType> + void setDecoder(PacketDispatcherType& dispatcher, + boost::function<void(const net::Error&,const Mt&)> handler) + { + // types + typedef typename PacketDispatcherType::traits_type packet_traits; + typedef typename PacketDispatcherType::packet_type packet_type; + typedef MessageDecoder<Mt,packet_type> decoder_type; + + // create, bind & store decoder + if (handler) + { + typename decoder_type::pointer decoder( new decoder_type(handler) ); + dispatcher.setHandler(Mt::ID, boost::bind(&decoder_type::decode,decoder,_1)); + } + else + dispatcher.setHandler(Mt::ID, 0); + } + +} // namespace net +} // namespace yake + +#endif \ No newline at end of file Added: trunk/yake/yake/net2/net.h =================================================================== --- trunk/yake/yake/net2/net.h (rev 0) +++ trunk/yake/yake/net2/net.h 2007-06-13 17:24:14 UTC (rev 1760) @@ -0,0 +1,17 @@ +#ifndef YAKE_NET_H +#define YAKE_NET_H + +#include "types.h" +#include "error.h" +#include "stats.h" +#include "resolver.h" +#include "packet.h" +#include "packet_connection.h" +#include "packet_dispatcher.h" +#include "simple_serialization.h" +#include "message_decoder.h" +#include "utils.h" +#include "server.h" +#include "async_send.h" + +#endif Added: trunk/yake/yake/net2/packet.h =================================================================== --- trunk/yake/yake/net2/packet.h (rev 0) +++ trunk/yake/yake/net2/packet.h 2007-06-13 17:24:14 UTC (rev 1760) @@ -0,0 +1,133 @@ +#ifndef NET_PACKET_H +#define NET_PACKET_H + +#include "types.h" + +namespace yake { +namespace net { + + struct DefaultPacketTraits + { + typedef uint16 id_type; + typedef uint16 size_type; + struct Header + { + id_type id; + size_type payloadSize; + }; + + static const size_t nHeaderSize = sizeof(Header); + BOOST_STATIC_ASSERT( nHeaderSize == 4 ); + static const size_t nMaxPayloadSize = 2048; + }; + template<class PacketTraits> + struct Packet : public boost::noncopyable + { + typedef PacketTraits traits_type; + static const size_t nHeaderSize = traits_type::nHeaderSize; + static const size_t nMaxPayloadSize = traits_type::nMaxPayloadSize; + typedef typename traits_type::id_type id_type; + + /* Minimal interface: + typedef ... id_type; + typedef boost::shared_ptr<Packet> pointer; + bool empty() const; + std::vector<boost::asio::const_buffer> sendBuffer() const; + boost::asio::mutable_buffer recvHeaderBuffer(); + bool decodeHeader(); + size_t payloadSize() const; + */ + typedef boost::shared_ptr<Packet> pointer; + Packet() : payloadSize_(0) + { + header_.assign( 0 ); + } + bool empty() const + { + return (payloadSize_ == 0); + } + std::vector<boost::asio::const_buffer> sendBuffer() const + { + std::vector<boost::asio::const_buffer> bufs; + bufs.push_back( boost::asio::buffer(header_) ); + if (!data_.empty()) + { + bufs.push_back( boost::asio::buffer(data_,payloadSize_) ); + } + return bufs; + } + boost::asio::mutable_buffer recvHeaderBuffer() + { + return boost::asio::buffer(header_); + } + bool decodeHeader() + { + BOOST_STATIC_ASSERT( PacketTraits::nHeaderSize >= 4 ); + // uint16 packet id + // uint16 payload size + payloadSize_ = 0; + if (header().payloadSize >= PacketTraits::nMaxPayloadSize) + return false; + payloadSize_ = header().payloadSize; // safely assign now. + return true; + } + typedef typename traits_type::Header header_type; + const header_type& header() const + { + return *reinterpret_cast<const header_type*>(header_.data()); + } + private: + header_type& header() + { + return *reinterpret_cast<header_type*>(header_.c_array()); + } + public: + uint8* payload(const size_t requestedSize = PacketTraits::nMaxPayloadSize) + { + if (requestedSize > PacketTraits::nMaxPayloadSize) + return 0; + return data_.c_array(); + } + const uint8* payload(const size_t requestedSize = PacketTraits::nMaxPayloadSize) const + { + if (requestedSize > PacketTraits::nMaxPayloadSize) + return 0; + return data_.data(); + } + id_type id() const + { + return header().id; + } + void setId(const id_type id) + { + header().id = id; + } + void setPayloadSize(const size_t size) + { + if (size >= PacketTraits::nMaxPayloadSize) + { + throw std::out_of_range("Packet<>::setPayloadSize(size): size out of max range"); + } + payloadSize_ = size; + header().payloadSize = size; + } + size_t payloadSize() const + { + return payloadSize_; + } + std::vector<boost::asio::mutable_buffer> recvBodyBuffer() + { + std::vector<boost::asio::mutable_buffer> bufs; + bufs.push_back( boost::asio::buffer(data_,payloadSize_) ); + return bufs; + } + private: + size_t payloadSize_; + boost::array<uint8,nHeaderSize> header_; + boost::array<uint8,nMaxPayloadSize> data_; + }; + +} // namespace net +} // namespace yake + +#endif Added: trunk/yake/yake/net2/packet_connection.h =================================================================== --- trunk/yake/yake/net2/packet_connection.h (rev 0) +++ trunk/yake/yake/net2/packet_connection.h 2007-06-13 17:24:14 UTC (rev 1760) @@ -0,0 +1,411 @@ +#ifndef NET_TCP_PACKET_CONNECTION_H +#define NET_TCP_PACKET_CONNECTION_H + +#include "types.h" +#include "error.h" +#include "stats.h" +#include "resolver.h" +#include "packet.h" +#include <boost/enable_shared_from_this.hpp> + +namespace yake { +namespace net { + + /** Represents a TCP connection (client or server). + */ + template<class PacketType = Packet<DefaultPacketTraits> > + struct TCPPacketConnection : public boost::enable_shared_from_this<TCPPacketConnection<PacketType> > //public boost::noncopyable + { + typedef typename PacketType::traits_type packet_traits; + typedef PacketType packet_type; + typedef typename packet_type::pointer packet_pointer; + + typedef boost::function<void(const Error&)> ErrorHandler; + typedef boost::function<void(const packet_type&)> PacketHandler; + + typedef boost::shared_ptr<TCPPacketConnection> pointer; + typedef tcp::socket socket_type; + typedef tcp::socket::endpoint_type endpoint_type; + + static pointer createServerConnection(io_service& io) + { + return pointer(new TCPPacketConnection(io)); + } + static pointer createClientConnection(io_service& io) + { + return pointer(new TCPPacketConnection(io)); + } + + private: // Enforce creation as shared_ptr !!! + TCPPacketConnection(io_service& io): + io_(io), + timeout_(io), + running_(false), + connected_(false) + { + std::cout << "tcp:conn:ctor()\n"; + } + public: + ~TCPPacketConnection() + { + std::cout << "tcp:conn:~dtor()\n"; + } + /** + @note Call blocks until connection is dead (disconnection, failure, ...). + You can run this function in a thread if you need a threaded connection object. + @note Do not run this function more than once before it returns! (For example, in different threads!) + */ + void connect(const std::string& remoteIp, const uint16 remotePort, + ErrorHandler handler, PacketHandler packetHandler, const long timeoutSec = 5) + { + if (running_) + return; + running_ = true; + + assert( handler && "need a valid connection handler" ); + handler_ = handler; + assert( packetHandler && "need a valid packet handler" ); + packetHandler_ = packetHandler; + + resolver_.reset( new TcpResolver(io_,remoteIp,remotePort) ); + resolver_->async_resolve( boost::bind(&TCPPacketConnection::onResolved,shared_from_this(),boost::asio::placeholders::error,_2) ); + + timeout_.expires_from_now( boost::posix_time::seconds(timeoutSec) ); + timeout_.async_wait( boost::bind(&TCPPacketConnection::onConnectionTimeout,shared_from_this(),boost::asio::placeholders::error) ); + + //io_.run(); + } + + /** @note Do not call directly! */ + void startAsServerConnection(ErrorHandler handler, PacketHandler packetHandler) + { + assert( handler && "need a valid connection handler" ); + handler_ = handler; + assert( packetHandler && "need a valid packet handler" ); + packetHandler_ = packetHandler; + + assert( socket_ && "socket needs to have been set up by acceptor" ); + remoteEndPoint_ = socket_->lowest_layer().remote_endpoint(); + + std::cout << "tcp::conn:startAsServerConnection(): connected to " << remoteEndPoint_ << "\n"; + + // start timeout for connection establishment + timeout_.expires_from_now( boost::posix_time::seconds(5) ); //@todo make timeout configurable + timeout_.async_wait(boost::bind(&TCPPacketConnection::onConnectionTimeout,shared_from_this(),boost::asio::error::timed_out)); + + // listen for incoming data etc pp + start(); + } + + void async_send(packet_pointer pckt) + { + /* + if (pckt->empty()) + return; + */ + io_.post( boost::bind(&TCPPacketConnection::doSend,shared_from_this(),pckt) ); + } + //template<typename Handler> + //void async_send(packet_pointer pckt, Handler handler) + void async_send(packet_pointer pckt, const boost::function<void(const Error&)>& handler) + { + io_.post( boost::bind(&TCPPacketConnection::doSend,shared_from_this(),pckt,handler) ); + } + void async_send(packet_type* pckt) + { + this->async_send( packet_pointer(pckt) ); + } + //template<typename Handler> + //void async_send(packet_type* pckt, Handler handler) + void async_send(packet_type* pckt, const boost::function<void(const Error&)>& handler) + { + this->async_send( packet_pointer(pckt), handler ); + } + + void stop() + { + io_.post( boost::bind(&TCPPacketConnection::doStop,shared_from_this(),Error::operation_aborted) ); + } + + //protocol for TcpServer<> only: + socket_type& socket() + { + if (!socket_) + socket_.reset( new socket_type(io_) ); + return *socket_; + } + private: + using boost::enable_shared_from_this<TCPPacketConnection<PacketType> >::shared_from_this; + void onConnectionTimeout(const boost::asio::error& e) + { + if (e == boost::asio::error::operation_aborted) + return; + std::cerr << "nc: connection attempt timed out.\n"; + doStop(Error::time_out); + } + void onResolved(const boost::asio::error& e, tcp::resolver::iterator endptIt) + { + if (e) + { + std::cerr << "nc: failed to resolve\n"; + doStop(Error::could_not_resolve); + return; + } + + tcp::endpoint endpt = *endptIt; + + socket_.reset( new tcp::socket(io_) ); + socket_->async_connect( endpt, + boost::bind(&TCPPacketConnection::handleConnect,shared_from_this(),boost::asio::placeholders::error,++endptIt) ); + } + void handleConnect(const boost::asio::error& e, tcp::resolver::iterator endptIt) + { + if (!e) + { + assert( socket_ && "socket should've been set up by connection's connect()." ); + + // start reading + remoteEndPoint_ = socket_->lowest_layer().remote_endpoint(); + + std::cout << "nc: connected to " << remoteEndPoint_ << "\n"; + timeout_.cancel(); + + start(); + } + else if (endptIt != tcp::resolver::iterator()) // as long as endpoints are available... + { + socket_->close(); + tcp::endpoint endpt = *endptIt; + socket_->async_connect( endpt, + boost::bind(&TCPPacketConnection::handleConnect,shared_from_this(),boost::asio::placeholders::error,++endptIt) ); + } + else //if(e) + { + std::cerr << "nc: failed to connect\n"; + doStop(Error::could_not_connect); + } + } + void start() + { + assert( !connected_ ); + if (connected_) + return; + connected_ = true; + assert( packetHandler_ ); + + if (handler_) + handler_( Error::connected ); + + // Resolver isn't needed anymore (actually, we probably can destroy it + // sooner...) + resolver_.reset(); + + // + assert( socket_ ); + boost::asio::async_read(*socket_, + boost::asio::buffer(incomingData_.recvHeaderBuffer()), + boost::bind(&TCPPacketConnection::handleReadHeader, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); + + // already packets in outgoing queue? + if (!outgoingQ_.empty()) + { + this->async_write_first_in_queue(); + } + } + void handleReadHeader(const boost::asio::error& e, size_t bytes_transferred) + { + if (e) + { + if (e == boost::asio::error::operation_aborted) + std::cerr << "nc: aborting read(header) operation.\n"; + else + std::cerr << "nc: read(header) failed: " << e << "\n"; + doStop(Error::disconnected); + } + else + { + stats_.in_.totalBytes_ += bytes_transferred; + stats_.in_.totalPackets_ += 1; + + std::cout << "nc: read(header) " << bytes_transferred << " byte(s)\n"; + if (incomingData_.decodeHeader()) + { + std::cerr << "nc: successfully decoded header\n"; + + // read body: + if (incomingData_.payloadSize() > 0) + { + boost::asio::async_read(*socket_, + incomingData_.recvBodyBuffer(), + boost::bind(&TCPPacketConnection::handleReadBody, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); + } + else //payloadSize == 0 + { + assert( packetHandler_ ); + packetHandler_( incomingData_ ); + + // read next packet header: + boost::asio::async_read(*socket_, + boost::asio::buffer(incomingData_.recvHeaderBuffer()), + boost::bind(&TCPPacketConnection::handleReadHeader, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); + } + } + else + { + stats_.in_.totalErrors_ += 1; + std::cerr << "nc: failed to decode header\n"; + doStop(Error::failed_to_receive); + } + } + } + void handleReadBody(const boost::asio::error& e, size_t bytes_transferred) + { + stats_.in_.totalBytes_ += bytes_transferred; + + if (e) + { + if (e == boost::asio::error::operation_aborted) + std::cerr << "nc: aborting read(body) operation.\n"; + else + std::cerr << "nc: read(body) failed: " << e << "\n"; + doStop(Error::disconnected); + } + else + { + std::cout << "nc: read(body) " << bytes_transferred << " byte(s)\n"; + if (incomingData_.payloadSize() != bytes_transferred) + { + //@todo implement multi-step read: + std::cerr << "nc: ERROR: could not receive body in one step\n"; + doStop(Error::failed_to_receive); + } + else + { + std::cout << "nc: recv'd body\n"; + + packetHandler_( incomingData_ ); + + // read next packet header: + boost::asio::async_read(*socket_, + boost::asio::buffer(incomingData_.recvHeaderBuffer()), + boost::bind(&TCPPacketConnection::handleReadHeader, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); + } + } + } + void doStop(const Error& e) + { + timeout_.cancel(); + + // + for (PacketList::const_iterator it = outgoingQ_.begin(); it != outgoingQ_.end(); ++it) + { + if (it->second) + (it->second)(Error::failed_to_send); + } + outgoingQ_.clear(); + + // + if (socket_) + { + boost::asio::error err; + socket_->close(boost::asio::assign_error(err)); + } + handler_( e ); + + connected_ = false; + running_ = false; //!? + } + void doSend(packet_pointer pckt) + { + this->doSend( pckt, 0 ); + } + void doSend(packet_pointer pckt, const ErrorHandler& handler) + { + assert( pckt ); + const bool writeInProgress = !outgoingQ_.empty(); + + outgoingQ_.push_back( std::make_pair(pckt,handler) ); + + if (connected_ && socket_ && !writeInProgress) // no write in progress? start writing. + { + this->async_write_first_in_queue(); + } + } + void handleWrite(const boost::asio::error& error, size_t bytes_transferred) + { + stats_.out_.totalBytes_ += bytes_transferred; + + if (error) + { + std::cerr << "nc: failed to write: " << error << "\n"; + + // remove packet from queue + if (!outgoingQ_.empty()) + { + if (outgoingQ_.front().second) + outgoingQ_.front().second(Error::failed_to_send); // trigger callback + outgoingQ_.pop_front(); + } + + // + this->doStop(Error::failed_to_send); + } + else + { + stats_.out_.totalPackets_ += 1; + + // remove sent packet from queue + assert( !outgoingQ_.empty() ); + if (!outgoingQ_.empty()) + { + if (outgoingQ_.front().second) + outgoingQ_.front().second(Error::ok); // trigger callback + outgoingQ_.pop_front(); + } + + // continue writing if packets left: + if (!outgoingQ_.empty()) + { + this->async_write_first_in_queue(); + } + } + } + void async_write_first_in_queue() + { + assert( socket_ ); + assert( connected_ ); + + boost::asio::async_write(*socket_, + outgoingQ_.front().first->sendBuffer(), + boost::bind(&TCPPacketConnection::handleWrite, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); + } + private: + io_service& io_; + + typedef boost::shared_ptr<socket_type> socket_ptr; + socket_ptr socket_; + endpoint_type remoteEndPoint_; + + TcpResolver::pointer resolver_; + + boost::asio::deadline_timer timeout_; + + volatile bool running_; + volatile bool connected_; + + // handlers + ErrorHandler handler_; + PacketHandler packetHandler_; + + // incoming/outgoing data + packet_type incomingData_; + typedef std::list<std::pair<packet_pointer,ErrorHandler> > PacketList; + PacketList outgoingQ_; + + ConnectionStats stats_; + }; + +} // namespace net +} // namespace yake + +#endif Added: trunk/yake/yake/net2/packet_dispatcher.h =================================================================== --- trunk/yake/yake/net2/packet_dispatcher.h (rev 0) +++ trunk/yake/yake/net2/packet_dispatcher.h 2007-06-13 17:24:14 UTC (rev 1760) @@ -0,0 +1,68 @@ +#ifndef NET_PACKET_DISPATCHER_H +#define NET_PACKET_DISPATCHER_H + +#include "types.h" +#include "packet.h" + +namespace yake { +namespace net { + + /** Dispatches packets to registered handlers depending on packet id. + @note This class is not thread-safe. Be careful which thread you + use to register/unregister handlers. + */ + template<class PacketTraits = DefaultPacketTraits> + struct IncomingPacketDispatcher : public boost::noncopyable + { + typedef PacketTraits traits_type; + typedef typename traits_type::id_type id_type; + typedef Packet<PacketTraits> packet_type; + typedef typename packet_type::pointer packet_ptr; + + IncomingPacketDispatcher() + {} + + // NB Be careful with thread safety! + //template<typename Handler> + typedef boost::function<void(const packet_type&)> HandlerFn; + void setHandler(const id_type id, HandlerFn handler) + { + //boost::mutex::scoped_lock lck(mtx_); + if (handler) + handlers_[ id ] = handler; + else + { + HandlerMap::iterator it = handlers_.find( id ); + if (it != handlers_.end()) + handlers_.erase( it ); + } + } + + void dispatch(const packet_type& pckt) + { + //boost::mutex::scoped_lock lck(mtx_); + //if (pckt) + // io_.post( boost::bind(&IncomingPacketDispatcher::doDispatch,this,pckt) ); + doDispatch(pckt); + } + private: + typedef std::map<id_type,HandlerFn> HandlerMap; + HandlerMap handlers_; + + //boost::mutex mtx_; + + void doDispatch(const packet_type& pckt) + { + HandlerMap::const_iterator it = handlers_.find( pckt.id() ); + if (it != handlers_.end()) + { + HandlerFn fn = it->second; + fn( pckt ); + } + } + }; + +} // namespace net +} // namespace yake + +#endif \ No newline at end of file Added: trunk/yake/yake/net2/resolver.h =================================================================== --- trunk/yake/yake/net2/resolver.h (rev 0) +++ trunk/yake/yake/net2/resolver.h 2007-06-13 17:24:14 UTC (rev 1760) @@ -0,0 +1,33 @@ +#ifndef NET_RESOLVER_H +#define NET_RESOLVER_H + +#include "types.h" + +namespace yake { +namespace net { + + struct TcpResolver : public boost::noncopyable + { + typedef boost::shared_ptr<TcpResolver> pointer; + + TcpResolver(io_service& io, const std::string& ip, const uint16 port) : + io_(io), + resolver_(io), + query_(ip,boost::lexical_cast<std::string>(port)) + { + } + template<typename Handler> + void async_resolve(Handler handler) + { + resolver_.async_resolve( query_, handler ); + } + private: + tcp::resolver resolver_; + tcp::resolver_query query_; + io_service& io_; + }; + +} // namespace net +} // namespace yake + +#endif Added: trunk/yake/yake/net2/server.h =================================================================== --- trunk/yake/yake/net2/server.h (rev 0) +++ trunk/yake/yake/net2/server.h 2007-06-13 17:24:14 UTC (rev 1760) @@ -0,0 +1,231 @@ +#ifndef NET_TCP_SERVER_H +#define NET_TCP_SERVER_H + +#include "types.h" +#include "error.h" +#include "stats.h" +#include "resolver.h" +#include "packet.h" +#include <boost/enable_shared_from_this.hpp> +#include "packet_connection.h" +#include "utils.h" + +namespace yake { +namespace net { + + /** Use io_service to communicate! + */ + struct TCPIncomingConnectionFilter : public boost::noncopyable + { + TCPIncomingConnectionFilter(io_service& io) : io_(io) + { + } + + typedef boost::asio::ip::address address; + typedef std::set<address> address_set; + + void setWhiteList(const address_set& addresses)// <-- not thread-safe! + { + whiteList_ = addresses; + } + void setBlackList(const address_set& addresses)// <-- not thread-safe! + { + blackList_ = addresses; + } + + /** Handler signature: void(bool) + */ + void async_check(const address& addr, boost::function<void(bool)> handler) + { + io_.post( boost::bind(&TCPIncomingConnectionFilter::doCheck,this,addr,handler) ); + } + private: + void doCheck(const address& addr, const boost::function<void(bool)>& handler) + { + assert( handler ); + if (!handler) + return; + if (blackList_.find( addr ) != blackList_.end()) + { + handler( false ); + return; + } + if (!whiteList_.empty()) // white list actually in use? + { + if (whiteList_.find( addr ) == whiteList_.end()) + { + handler( false ); + return; + } + } + handler(true); + } + private: + io_service& io_; + address_set whiteList_; + address_set blackList_; + }; + + //ConnectionFilterPolicy + template<class ServerType> + struct NoConnectionFilter + { + NoConnectionFilter(io_service&) + {} + protected: // NB Could be made public to enrich interface... + template<typename Handler> + void async_check(const TCPIncomingConnectionFilter::address&, Handler handler) + { + handler(true); // always return true + } + }; + template<class ServerType> + struct ConnectionFilterByIP + { + ConnectionFilterByIP(io_service& io) : filter_(io) + {} + protected: // NB Could be made public to enrich interface... + template<typename Handler> + void async_check(const TCPIncomingConnectionFilter::address& addr, Handler handler) + { + filter_.async_check( addr, handler ); + } + public: + /** Enrich the owner class's interface: */ + TCPIncomingConnectionFilter& ipFilter() + { + return filter_; + } + private: + TCPIncomingConnectionFilter filter_; + }; + + /** Listens for and accepts connections, creates connection objects, + and informs derived class of accepted connections. + */ + template< class ConnectionType = TCPPacketConnection<>, template <class> class ConnectionFilterPolicy = NoConnectionFilter> + struct TCPServer : public boost::noncopyable, public ConnectionFilterPolicy<TCPServer<ConnectionType,ConnectionFilterPolicy> > + { + typedef ConnectionFilterPolicy<TCPServer<ConnectionType,ConnectionFilterPolicy> > connection_filter_policy; + typedef ConnectionType connection_type; + typedef typename ConnectionType::pointer connection_ptr; + typedef boost::weak_ptr<connection_type> connection_weakptr; + typedef typename ConnectionType::packet_type packet_type; + + typedef boost::function<void(connection_weakptr,const net::Error&)> ConnectionHandler; + typedef boost::function<void(connection_weakptr,const packet_type&)> PacketHandler; + + + /** + @note connection lifetime is managed by the connection itself. + In multi-threaded applications this can cause problems if not used with care... + + @todo Are the callbacks weak connection pointers safe to access from different threads? + */ + TCPServer(io_service& io, unsigned short port, ConnectionHandler connectionHandler, PacketHandler packetHandler) : + connection_filter_policy(io), + acceptor_(io, tcp::endpoint(tcp::v4(), port)), + connectionHandler_(connectionHandler), + packetHandler_(packetHandler) + { + assert( connectionHandler_ ); + assert( packetHandler ); + start(); + } + TCPServer(io_service& io, const std::string& address, unsigned short port, ConnectionHandler connectionHandler, PacketHandler packetHandler) : + connection_filter_policy(io), + acceptor_(io, makeTcpEndpoint(address,port)), + connectionHandler_(connectionHandler), + packetHandler_(packetHandler) + { + assert( connectionHandler_ ); + assert( packetHandler ); + start(); + } + private: + virtual connection_ptr createConnection(io_service& io) + { + return connection_type::createServerConnection( io ); + } + private: + tcp::acceptor acceptor_; + PacketHandler packetHandler_; + ConnectionHandler connectionHandler_; + + //typedef std::set<connection_weakptr> connection_list; + //connection_list conns_; + void onConnection(connection_weakptr conn, const net::Error& e) + { + if (!conn.lock()) // should never happen... + return; + if (!e) + { + //std::cerr << "s:onConnection: " << e.code() << "=" << e.what() << "\n"; + //conns_.erase( conn ); // destroy connection + //std::cout << "s: connection count = " << conns_.size() << "\n"; + //conn->stop(); + } + assert( packetHandler_ ); + connectionHandler_( conn, e ); + } + void onPacket(connection_weakptr conn, const packet_type& pckt) + { + assert( packetHandler_ ); + packetHandler_( conn, pckt ); + } + + void start() + { + std::cout << "s:listen: listening at " << acceptor_.local_endpoint() << "\n"; + startAccept(); + } + void startAccept() + { + std::cout << "s:listen: waiting...\n"; + + // Create connection object (+ socket) and start listening... + + connection_ptr conn = this->createConnection( acceptor_.io_service() ); + + acceptor_.async_accept( conn->socket(), + boost::bind(&TCPServer::handleAccept, this, conn, boost::asio::placeholders::error ) ); + } + void onConnectionAccepted(connection_ptr conn, const bool accepted) + { + std::cout << "s:listen: accepted=" << accepted << "\n"; + if (accepted) + { + conn->startAsServerConnection( + boost::bind(&TCPServer::onConnection,this,connection_weakptr(conn),_1), + boost::bind(&TCPServer::onPacket,this,connection_weakptr(conn),_1) + ); + } + //else: Let conn go out of scope. As the conn's shared_ptrs go out of scope + // it will eventually be destroyed (returning from this + // callback results in destruction of the boost::function object + // used for this callback which results in the bound objects to be destroyed + // (one of which is the last existing shared_ptr to 'conn'). + } + // NB In handleAccept() we can let the connection_ptr go out of scope safely + // as conn->startAsServerConnection() controls its own lifetime via shared_from_this(). + void handleAccept(connection_ptr conn, const boost::asio::error& error) + { + if (!error) + { + tcp::endpoint remoteEndpoint = conn->socket().lowest_layer().remote_endpoint(); + std::cout << "s:listen: accepted " << remoteEndpoint << ". listening...\n"; + + // Let address filter policy check the remote endpoint's address. + this->async_check(remoteEndpoint.address(), + boost::bind(&TCPServer::onConnectionAccepted,this,conn,_1)); + + // continue listening for / accepting incoming connections... + startAccept(); + } + } + }; + +} // namespace net +} // namespace yake + +#endif Added: trunk/yake/yake/net2/simple_serialization.h =================================================================== --- trunk/yake/yake/net2/simple_serialization.h (rev 0) +++ trunk/yake/yake/net2/simple_serialization.h 2007-06-13 17:24:14 UTC (rev 1760) @@ -0,0 +1,207 @@ +#ifndef NET_SIMPLE_SERIALIZATION_H +#define NET_SIMPLE_SERIALIZATION_H + +#include <boost/static_assert.hpp> +#include "types.h" + +namespace yake { +namespace net { + + struct BinaryOutArchive + { + static const int saving = 1; + BinaryOutArchive(uint8* data, size_t size) : + data_(data), size_(size), curr_(0) + { + assert( data_ ); + assert( size_ > 0 ); + } + void write(const void* data, const size_t size) + { + if (curr_ + size > size_) + throw std::out_of_range("write() out of range"); + memcpy(data_ + curr_, data, size); + curr_ += size; + } + void write(uint8 rhs) + { + write(&rhs,sizeof(rhs)); + } + void write(uint16 rhs) + { + write(&rhs,sizeof(rhs)); + } + void write(uint32 rhs) + { + write(&rhs,sizeof(rhs)); + } + void write(uint64 rhs) + { + write(&rhs,sizeof(rhs)); + } + + template<typename T> + BinaryOutArchive& operator & (T& rhs) + { + ::yake::net::serialize(*this,rhs); + return *this; + } + + size_t curr() const + { + return curr_; + } + private: + uint8* data_; + size_t size_; + + size_t curr_; + }; + struct BinaryInArchive + { + static const int saving = 0; + BinaryInArchive(const uint8* data, size_t size) : + data_(data), size_(size), curr_(0) + { + assert( data_ ); + } + void read(void* data, const size_t size) + { + if (curr_ + size > size_) + throw std::out_of_range("read() out of range"); + memcpy(data, data_ + curr_, size); + curr_ += size; + } + void read(uint8& rhs) + { + read(&rhs,sizeof(rhs)); + } + void read(uint16& rhs) + { + read(&rhs,sizeof(rhs)); + } + void read(uint32& rhs) + { + read(&rhs,sizeof(rhs)); + } + void read(uint64& rhs) + { + read(&rhs,sizeof(rhs)); + } + + template<typename T> + BinaryInArchive& operator & (T& rhs) + { + ::yake::net::serialize(*this,rhs); + return *this; + } + private: + const uint8* data_; + size_t size_; + + size_t curr_; + }; + + template<int n> + struct Int2Type + { + static const int value = n; + }; + + template<class Ar, typename T> + void serialize(Ar& ar, T& rhs) + { + do_serialize(ar,rhs,Int2Type<Ar::saving>()); + } + template<class Ar, typename T> + inline void do_serialize(Ar& ar, T& rhs, Int2Type<0>) + { + ar >> rhs; + } + template<class Ar, typename T> + inline void do_serialize(Ar& ar, T& rhs, Int2Type<1>) + { + ar << rhs; + } + + /////////////////////////////////////////////////////////////////////////// + template<class Ar> + Ar& operator << (Ar& ar, int rhs) + { + ar.write(&rhs,sizeof(int)); + return ar; + } + template<class Ar> + Ar& operator >> (Ar& ar, int& rhs) + { + ar.read(&rhs,sizeof(int)); + return ar; + } + template<class Ar> + Ar& operator << (Ar& ar, const std::string& rhs) + { + BOOST_STATIC_ASSERT( sizeof(size_t) == sizeof(uint32) ); + ar.write( uint32(rhs.size()) ); + ar.write( rhs.c_str(), rhs.size() ); + return ar; + } + template<class Ar> + Ar& operator >> (Ar& ar, std::string& rhs) + { + rhs.clear(); + uint32 size = 0; + ar.read(size); + rhs.resize(size); + ar.read((void*)rhs.data(),size); + return ar; + } + template<class Ar, class _Ty, class _Ax> + Ar& operator << (Ar& ar, const std::vector<_Ty,_Ax>& rhs) + { + typedef std::vector<_Ty,_Ax> ctr_type; + BOOST_STATIC_ASSERT( sizeof(size_t) == sizeof(uint32) ); + ar.write( uint32(rhs.size()) ); + for (size_t i=0;i<rhs.size(); ++i) + ar & rhs.at(i); + return ar; + } + template<class Ar, class _Ty, class _Ax> + Ar& operator >> (Ar& ar, std::vector<_Ty,_Ax>& rhs) + { + rhs.clear(); + uint32 size = 0; + ar.read(size); + rhs.resize(size); + for (size_t i=0; i<size; ++i) + ar & rhs.at(i); + return ar; + } + // Enable for improved performance for containers with integral types. + // Available: vector<int,...> +#if 0 + template<class Ar, class _Ax> + Ar& operator << (Ar& ar, const std::vector<int,_Ax>& rhs) + { + std::cout << "boosted\n"; + typedef std::vector<int,_Ax> ctr_type; + BOOST_STATIC_ASSERT( sizeof(size_t) == sizeof(uint32) ); + ar.write( uint32(rhs.size()) ); + ar.write( &rhs[0], sizeof(int)*rhs.size() ); + return ar; + } + template<class Ar, class _Ax> + Ar& operator >> (Ar& ar, std::vector<int,_Ax>& rhs) + { + rhs.clear(); + uint32 size = 0; + ar.read(size); + rhs.resize(size); + ar.read(&rhs[0],sizeof(int)*size); + return ar; + } +#endif + +} // namespace net +} // namespace yake + +#endif \ No newline at end of file Added: trunk/yake/yake/net2/stats.h =================================================================== --- trunk/yake/yake/net2/stats.h (rev 0) +++ trunk/yake/yake/net2/stats.h 2007-06-13 17:24:14 UTC (rev 1760) @@ -0,0 +1,49 @@ +#ifndef NET_STATS_H +#define NET_STATS_H + +#include "types.h" + +namespace yake { +namespace net { + + struct ConnectionStats : public boost::noncopyable + { + struct DirectionStats + { + size_t totalBytes_; + size_t totalPackets_; + size_t totalErrors_; + void dump(std::ostream& out) + { + out << totalPackets_ << " packet(s) " << totalBytes_ << " byte(s)"; + } + DirectionStats() : + totalPackets_(0), + totalBytes_(0) + { + } + }; + DirectionStats in_; + DirectionStats out_; + + ConnectionStats() + { + } + ~ConnectionStats() + { + std::cout << "\nstats:\n"; + + std::cout << " in : "; + in_.dump(std::cout); + std::cout << "\n"; + + std::cout << " out: "; + out_.dump(std::cout); + std::cout << "\n"; + } + }; + +} // namespace net +} // namespace yake + +#endif Added: trunk/yake/yake/net2/types.h =================================================================== --- trunk/yake/yake/net2/types.h (rev 0) +++ trunk/yake/yake/net2/types.h 2007-06-13 17:24:14 UTC (rev 1760) @@ -0,0 +1,42 @@ +#ifndef NET_TYPES_H +#define NET_TYPES_H + +#pragma warning(disable: 4311) // because of tcp::socket instantiation +#pragma warning(disable: 4312) // because of tcp::socket instantiation +#pragma warning(disable: 4503) // ... + +#pragma warning(push) +#pragma warning(disable: 4267) +#include <boost/asio.hpp> +#pragma warning(pop) + +#include <boost/bind.hpp> +#include <boost/function.hpp> +#include <boost/lexical_cast.hpp> +#include <exception> + +namespace yake { +namespace net { + + typedef unsigned __int8 uint8; + typedef unsigned __int16 uint16; + typedef unsigned __int32 uint32; + typedef unsigned __int64 uint64; + typedef signed __int8 int8; + typedef signed __int16 int16; + typedef signed __int32 int32; + typedef signed __int64 int64; + + typedef boost::asio::io_service io_service; + typedef boost::asio::ip::tcp tcp; + typedef boost::asio::ip::address address; + typedef boost::asio::ip::tcp::endpoint tcp_endpoint; + + namespace placeholders { + boost::arg<1> error; + boost::arg<2> message; + } // namespace placeholders +} +} + +#endif Added: trunk/yake/yake/net2/utils.h =================================================================== --- trunk/yake/yake/net2/utils.h (rev 0) +++ trunk/yake/yake/net2/utils.h 2007-06-13 17:24:14 UTC (rev 1760) @@ -0,0 +1,34 @@ +#ifndef NET_UTILS_H +#define NET_UTILS_H + +#include "types.h" +#include "packet.h" +#include "packet_connection.h" + +namespace yake { +namespace net { + + /** Creates asio ip address from string. + In contrast to boost::asio::ip::address::from_string() + it converts 'localhost' to 127.0.0.1. + */ + inline address makeIpAddress(const std::string& in) + { + if (in == "localhost") + return boost::asio::ip::address::from_string("127.0.0.1"); + return boost::asio::ip::address::from_string(in); + } + + /** Creates asio ip endpoint from string and port number. + In contrast to boost::asio::ip::address::from_string() + it converts 'localhost' to 127.0.0.1. + */ + inline tcp_endpoint makeTcpEndpoint(const std::string& in, const uint16 port) + { + return tcp_endpoint(makeIpAddress(in),port); + } + +} // namespace net +} // namespace yake + +#endif \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-06-18 20:49:33
|
Revision: 1761 http://svn.sourceforge.net/yake/?rev=1761&view=rev Author: psyclonist Date: 2007-06-18 13:47:29 -0700 (Mon, 18 Jun 2007) Log Message: ----------- improved net2 + sample Modified Paths: -------------- trunk/yake/samples/net2/message1/demo.cpp trunk/yake/yake/net2/packet_connection.h trunk/yake/yake/net2/server.h Modified: trunk/yake/samples/net2/message1/demo.cpp =================================================================== --- trunk/yake/samples/net2/message1/demo.cpp 2007-06-13 17:24:14 UTC (rev 1760) +++ trunk/yake/samples/net2/message1/demo.cpp 2007-06-18 20:47:29 UTC (rev 1761) @@ -7,24 +7,6 @@ using namespace yake; -/** A simple server class for managing packet connections. -*/ -struct server -{ -private: - server& operator=(const server&); - server(const server&); -public: - server(const net::address&, const uint16 port, const uint32 maxClients); - ~server(); - -private: - void onConnectionError(const net::Error& e); -private: - net::address addr_; - uint32 maxClients_; -}; - #define YAKE_LOG_INFORMATION_X(X) \ { \ std::stringstream ss; \ @@ -57,85 +39,179 @@ SharedPtr<logging::log_listener> to_stderr( new logging::stderr_listener() ); logging::addListener( to_stderr.get() ); + namespace placeholders = net::placeholders; + // server try { - YAKE_LOG("demo", "starting server..."); + if (argc > 1) + { + YAKE_LOG("demo", "starting server..."); - namespace placeholders = net::placeholders; + net::io_service io; + typedef net::TCPServer<net::TCPPacketConnection<>,net::ConnectionFilterByIP> server_type; - net::io_service io; - typedef net::TCPServer<net::TCPPacketConnection<>,net::ConnectionFilterByIP> server_type; + // Create a server object for listening at localhost's port 40000 and + // creating TCPPacketConnection<> objects for each incoming TCP connections. + //typedef net::TCPServer<> server_type; + typedef net::TCPServer<net::TCPPacketConnection<>,net::ConnectionFilterByIP> server_type; + struct ServerHandler + { + typedef server_type::packet_type packet_type; - // Create a server object for listening at localhost's port 40000 and - // creating TCPPacketConnection<> objects for each incoming TCP connections. - //typedef net::TCPServer<> server_type; - typedef net::TCPServer<net::TCPPacketConnection<>,net::ConnectionFilterByIP> server_type; - struct ServerHandler - { - typedef server_type::packet_type packet_type; + struct Client : public boost::noncopyable + { + //typedef yake::SharedPtr<Client> pointer; + typedef Client* pointer; + net::IncomingPacketDispatcher<>& dispatcher() + { return dispatcher_; } - // NOT THREAD SAFE: We need one per connection, right? - static net::IncomingPacketDispatcher<>& dispatcher(/*server_type::connection_weakptr conn*/) - { - static net::IncomingPacketDispatcher<> s_dispatcher; - return s_dispatcher; - } + Client() + { + std::cout << "app: new Client\n"; + } + ~Client() + { + std::cout << "app: ~Client\n"; + } + private: + net::IncomingPacketDispatcher<> dispatcher_; + }; - static void onConnection(server_type::connection_weakptr conn, const net::Error& e) - { - std::cout << "app:onConnection: " << e.code() << "=" << e.what() << "\n"; - if (e == net::Error::connected) + // + static void onConnection(Client::pointer client,server_type::connection_weakptr conn, const net::Error& e) { - net::setDecoder<Hello>( dispatcher(), - boost::bind(&ServerHandler::onHello,conn,placeholders::error,placeholders::message) ); + std::cout << "app:onConnection: " << e.code() << "=" << e.what() << "\n"; + assert( client ); + if (e == net::Error::connected) + { + net::setDecoder<Hello>( client->dispatcher(), + boost::bind(&ServerHandler::onHello,client,conn,placeholders::error,placeholders::message) ); + } + else if (!e) + { + net::setDecoder<Hello>( client->dispatcher(), 0 ); + } } - else if (!e) + static void onPacket(Client::pointer client,server_type::connection_weakptr conn, const packet_type& pckt) { - net::setDecoder<Hello>( dispatcher(), 0 ); + std::cout << "app: recv'd packet. payload: " << pckt.header().payloadSize << " byte(s)\n"; + assert( client ); + + client->dispatcher().dispatch( pckt ); } - } - static void onHello(server_type::connection_weakptr conn, const net::Error& e, const Hello& hello) + static void onCreateConnection(server_type::ConnectionHandler& connHandler, server_type::PacketHandler& pcktHandler) + { + Client::pointer client = new Client(); + connHandler = boost::bind(&onConnection,client,_1,_2); + pcktHandler = boost::bind(&onPacket,client,_1,_2); + } + // + static void onHello(Client::pointer, server_type::connection_weakptr conn, const net::Error& e, const Hello& hello) + { + if (!e) + std::cerr << "app: recv'd but FAILED to decode HELLO: " << e << "\n"; + else + { + std::cout << "app: recv'd & decoded HELLO: " << hello.message << "\n"; + if (conn.lock()) + net::async_send( *conn.lock(), Hello("PONG!") ); + } + } + }; + server_type server(io, + "localhost", // <- throws exception of invalid + 40000, + boost::bind(&ServerHandler::onCreateConnection,_1,_2)); + + // Test access of policy-enriched interface: + net::TCPIncomingConnectionFilter::address_set blackList; + //blackList.insert( net::detail::makeIpAddress("localhost") ); + server.ipFilter().setBlackList(blackList); + + // Run the server processing in a different thread. + // Note that, by subsequently creating additional threads + // running the same io_service::run() method we can increase + // the number of threads for the TCP server. + boost::thread_group netThreads; + + // NB At the moment, only 1 is safe for the current implementation of ServerHandler. + const size_t numThreads = 1; + for (size_t i=0; i<numThreads; ++i) + netThreads.create_thread( boost::bind(&net::io_service::run,&io) ); + + // Wait for the server process to finish. + // @todo At the moment, it only finishes if it fails. + netThreads.join_all(); + } + else + { + YAKE_LOG("demo", "starting client..."); + // The io_service manages the asynchronous operations + net::io_service netIo_; + + // Create a TCPPacketConnection object for connecting to + // a server. + net::TCPPacketConnection<>::pointer c = net::TCPPacketConnection<>::createClientConnection(netIo_); + + // Add compression filter (ZLib): + //c->filters().add( new StatefulZipCompressorFilter() ); + + // Create a dispatcher object for incoming packets. + net::IncomingPacketDispatcher<> pcktDispatcher; + + struct ClientHandler { - if (!e) - std::cerr << "app: recv'd but FAILED to decode HELLO: " << e << "\n"; - else + static void onHello(const net::Error& e, const Hello&) { - std::cout << "app: recv'd & decoded HELLO: " << hello.message << "\n"; - if (conn.lock()) - net::async_send( *conn.lock(), Hello("PONG") ); + if (e) + std::cout << "app: recv'd HELLO\n"; + else + std::cerr << "app: recv'd HELLO but something did go wrong...\n"; } - } - static void onPacket(server_type::connection_weakptr conn, const packet_type& pckt) - { - std::cout << "app: recv'd packet. payload: " << pckt.header().payloadSize << " byte(s)\n"; + static void onConnection(const net::Error& e) + { + if (!e) + std::cout << "app: status = " << e << "\n"; + } + }; - dispatcher().dispatch( pckt ); - } - }; - //static boost::asio::strand ServerHandler::strand_(io); - server_type server(io, - "localhost", // <- throws exception of invalid - 40000, - boost::bind(&ServerHandler::onConnection,_1,_2), - boost::bind(&ServerHandler::onPacket,_1,_2)); + // Subscribe to specific packet ids. + //pcktDispatcher.setHandler( 1, &onRecvPacket ); + net::setDecoder<Hello>( pcktDispatcher, + boost::bind(&ClientHandler::onHello,placeholders::error,placeholders::message) ); - // Test access of policy-enriched interface: - net::TCPIncomingConnectionFilter::address_set blackList; - //blackList.insert( net::detail::makeIpAddress("localhost") ); - server.ipFilter().setBlackList(blackList); + // Start asynchronous connection attempt to server at port 40000. + // * onConnection receives connection related errors and status information. + // * onPacket is called when incoming packets have arrived. + // OR in this case we forward it to the IncomingPacketDispatcher + // * 5 is the maxmimum timeout (in seconds) for the connection attempt. + c->connect("localhost",40000,&ClientHandler::onConnection, + /*&onPacket OR*/ boost::bind(&net::IncomingPacketDispatcher<>::dispatch,&pcktDispatcher,_1), + 5); - // Run the server processing in a different thread. - // Note that, by subsequently creating additional threads - // running the same io_service::run() method we can increase - // the number of threads for the TCP server. - boost::thread netThread( boost::bind(&net::io_service::run,&io) ); - //boost::thread netThread2( boost::bind(&net::io_service::run,&io) ); + // Start the io_service for the connection in a seperate thread. + // As soon as the connection is closed or in case it couldn't be + // established the thread will be terminated. + boost::thread netThread( boost::bind(&net::io_service::run,&netIo_) ); - // Wait for the server process to finish. - // @todo At the moment, it only finishes if it fails. - netThread.join(); - //netThread2.join(); + // Send some data (or enqueue, depending on connection state) + for (size_t i=0; i<10; ++i) + { +#if 0 + MyPacket::pointer p( new MyPacket() ); + p->setId( Hello::ID ); + p->setPayloadSize( 0 ); + c->async_send(p,&onConnection); + //net::async_send( *c, p, Hello("yeeha"), &onConnection ); +#else + net::async_send( *c, Hello("yeeha"), &ClientHandler::onConnection ); +#endif + } + + // Wait for the connection thread to exit. + netThread.join(); + } } catch (boost::asio::error& ex) { Modified: trunk/yake/yake/net2/packet_connection.h =================================================================== --- trunk/yake/yake/net2/packet_connection.h 2007-06-13 17:24:14 UTC (rev 1760) +++ trunk/yake/yake/net2/packet_connection.h 2007-06-18 20:47:29 UTC (rev 1761) @@ -43,12 +43,12 @@ running_(false), connected_(false) { - std::cout << "tcp:conn:ctor()\n"; + //std::cout << "tcp:conn:ctor()\n"; } public: ~TCPPacketConnection() { - std::cout << "tcp:conn:~dtor()\n"; + //std::cout << "tcp:conn:~dtor()\n"; } /** @note Call blocks until connection is dead (disconnection, failure, ...). @@ -87,7 +87,7 @@ assert( socket_ && "socket needs to have been set up by acceptor" ); remoteEndPoint_ = socket_->lowest_layer().remote_endpoint(); - std::cout << "tcp::conn:startAsServerConnection(): connected to " << remoteEndPoint_ << "\n"; + //std::cout << "tcp::conn:startAsServerConnection(): connected to " << remoteEndPoint_ << "\n"; // start timeout for connection establishment timeout_.expires_from_now( boost::posix_time::seconds(5) ); //@todo make timeout configurable @@ -140,14 +140,14 @@ { if (e == boost::asio::error::operation_aborted) return; - std::cerr << "nc: connection attempt timed out.\n"; + //std::cerr << "nc: connection attempt timed out.\n"; doStop(Error::time_out); } void onResolved(const boost::asio::error& e, tcp::resolver::iterator endptIt) { if (e) { - std::cerr << "nc: failed to resolve\n"; + //std::cerr << "nc: failed to resolve\n"; doStop(Error::could_not_resolve); return; } @@ -167,7 +167,7 @@ // start reading remoteEndPoint_ = socket_->lowest_layer().remote_endpoint(); - std::cout << "nc: connected to " << remoteEndPoint_ << "\n"; + //std::cout << "nc: connected to " << remoteEndPoint_ << "\n"; timeout_.cancel(); start(); @@ -181,7 +181,7 @@ } else //if(e) { - std::cerr << "nc: failed to connect\n"; + //std::cerr << "nc: failed to connect\n"; doStop(Error::could_not_connect); } } @@ -217,9 +217,9 @@ if (e) { if (e == boost::asio::error::operation_aborted) - std::cerr << "nc: aborting read(header) operation.\n"; + ;//std::cerr << "nc: aborting read(header) operation.\n"; else - std::cerr << "nc: read(header) failed: " << e << "\n"; + ;//std::cerr << "nc: read(header) failed: " << e << "\n"; doStop(Error::disconnected); } else @@ -227,10 +227,10 @@ stats_.in_.totalBytes_ += bytes_transferred; stats_.in_.totalPackets_ += 1; - std::cout << "nc: read(header) " << bytes_transferred << " byte(s)\n"; + //std::cout << "nc: read(header) " << bytes_transferred << " byte(s)\n"; if (incomingData_.decodeHeader()) { - std::cerr << "nc: successfully decoded header\n"; + //std::cerr << "nc: successfully decoded header\n"; // read body: if (incomingData_.payloadSize() > 0) @@ -253,7 +253,7 @@ else { stats_.in_.totalErrors_ += 1; - std::cerr << "nc: failed to decode header\n"; + //std::cerr << "nc: failed to decode header\n"; doStop(Error::failed_to_receive); } } @@ -265,23 +265,23 @@ if (e) { if (e == boost::asio::error::operation_aborted) - std::cerr << "nc: aborting read(body) operation.\n"; + ;//std::cerr << "nc: aborting read(body) operation.\n"; else - std::cerr << "nc: read(body) failed: " << e << "\n"; + ;//std::cerr << "nc: read(body) failed: " << e << "\n"; doStop(Error::disconnected); } else { - std::cout << "nc: read(body) " << bytes_transferred << " byte(s)\n"; + //std::cout << "nc: read(body) " << bytes_transferred << " byte(s)\n"; if (incomingData_.payloadSize() != bytes_transferred) { //@todo implement multi-step read: - std::cerr << "nc: ERROR: could not receive body in one step\n"; + //std::cerr << "nc: ERROR: could not receive body in one step\n"; doStop(Error::failed_to_receive); } else { - std::cout << "nc: recv'd body\n"; + //std::cout << "nc: recv'd body\n"; packetHandler_( incomingData_ ); @@ -337,7 +337,7 @@ if (error) { - std::cerr << "nc: failed to write: " << error << "\n"; + //std::cerr << "nc: failed to write: " << error << "\n"; // remove packet from queue if (!outgoingQ_.empty()) Modified: trunk/yake/yake/net2/server.h =================================================================== --- trunk/yake/yake/net2/server.h 2007-06-13 17:24:14 UTC (rev 1760) +++ trunk/yake/yake/net2/server.h 2007-06-18 20:47:29 UTC (rev 1761) @@ -17,7 +17,7 @@ */ struct TCPIncomingConnectionFilter : public boost::noncopyable { - TCPIncomingConnectionFilter(io_service& io) : io_(io) + TCPIncomingConnectionFilter(io_service& io) : io_(io), strand_(io) { } @@ -37,7 +37,7 @@ */ void async_check(const address& addr, boost::function<void(bool)> handler) { - io_.post( boost::bind(&TCPIncomingConnectionFilter::doCheck,this,addr,handler) ); + io_.post( strand_.wrap(boost::bind(&TCPIncomingConnectionFilter::doCheck,this,addr,handler)) ); } private: void doCheck(const address& addr, const boost::function<void(bool)>& handler) @@ -64,6 +64,7 @@ io_service& io_; address_set whiteList_; address_set blackList_; + boost::asio::strand strand_; }; //ConnectionFilterPolicy @@ -102,6 +103,7 @@ /** Listens for and accepts connections, creates connection objects, and informs derived class of accepted connections. + @todo Passing connection_weakptr makes this non-thread-safe in the case of multiple server threads. Have to improve this! */ template< class ConnectionType = TCPPacketConnection<>, template <class> class ConnectionFilterPolicy = NoConnectionFilter> struct TCPServer : public boost::noncopyable, public ConnectionFilterPolicy<TCPServer<ConnectionType,ConnectionFilterPolicy> > @@ -114,6 +116,7 @@ typedef boost::function<void(connection_weakptr,const net::Error&)> ConnectionHandler; typedef boost::function<void(connection_weakptr,const packet_type&)> PacketHandler; + typedef boost::function<void(ConnectionHandler&,PacketHandler&)> NewConnectionHandler; /** @@ -122,24 +125,22 @@ @todo Are the callbacks weak connection pointers safe to access from different threads? */ - TCPServer(io_service& io, unsigned short port, ConnectionHandler connectionHandler, PacketHandler packetHandler) : + TCPServer(io_service& io, unsigned short port, NewConnectionHandler newConnectionHandler) : connection_filter_policy(io), acceptor_(io, tcp::endpoint(tcp::v4(), port)), - connectionHandler_(connectionHandler), - packetHandler_(packetHandler) + newConnectionHandler_(newConnectionHandler) { assert( connectionHandler_ ); assert( packetHandler ); + assert( newConnectionHandler_ ); start(); } - TCPServer(io_service& io, const std::string& address, unsigned short port, ConnectionHandler connectionHandler, PacketHandler packetHandler) : + TCPServer(io_service& io, const std::string& address, unsigned short port, NewConnectionHandler newConnectionHandler) : connection_filter_policy(io), acceptor_(io, makeTcpEndpoint(address,port)), - connectionHandler_(connectionHandler), - packetHandler_(packetHandler) + newConnectionHandler_(newConnectionHandler) { - assert( connectionHandler_ ); - assert( packetHandler ); + assert( newConnectionHandler_ ); start(); } private: @@ -149,12 +150,11 @@ } private: tcp::acceptor acceptor_; - PacketHandler packetHandler_; - ConnectionHandler connectionHandler_; + NewConnectionHandler newConnectionHandler_; //typedef std::set<connection_weakptr> connection_list; //connection_list conns_; - void onConnection(connection_weakptr conn, const net::Error& e) + void onConnection(ConnectionHandler connHandler, connection_weakptr conn, const net::Error& e) { if (!conn.lock()) // should never happen... return; @@ -165,13 +165,13 @@ //std::cout << "s: connection count = " << conns_.size() << "\n"; //conn->stop(); } - assert( packetHandler_ ); - connectionHandler_( conn, e ); + assert( connHandler ); + connHandler( conn, e ); } - void onPacket(connection_weakptr conn, const packet_type& pckt) + void onPacket(PacketHandler pcktHandler, connection_weakptr conn, const packet_type& pckt) { - assert( packetHandler_ ); - packetHandler_( conn, pckt ); + assert( pcktHandler ); + pcktHandler( conn, pckt ); } void start() @@ -186,18 +186,23 @@ // Create connection object (+ socket) and start listening... connection_ptr conn = this->createConnection( acceptor_.io_service() ); + ConnectionHandler connHandler; + PacketHandler pcktHandler; + newConnectionHandler_( boost::ref(connHandler), boost::ref(pcktHandler) ); + assert( connHandler ); + assert( pcktHandler ); acceptor_.async_accept( conn->socket(), - boost::bind(&TCPServer::handleAccept, this, conn, boost::asio::placeholders::error ) ); + boost::bind(&TCPServer::handleAccept, this, connHandler, pcktHandler, conn, boost::asio::placeholders::error ) ); } - void onConnectionAccepted(connection_ptr conn, const bool accepted) + void onConnectionAccepted(ConnectionHandler connHandler, PacketHandler pcktHandler, connection_ptr conn, const bool accepted) { std::cout << "s:listen: accepted=" << accepted << "\n"; if (accepted) { conn->startAsServerConnection( - boost::bind(&TCPServer::onConnection,this,connection_weakptr(conn),_1), - boost::bind(&TCPServer::onPacket,this,connection_weakptr(conn),_1) + boost::bind(&TCPServer::onConnection,this,connHandler,connection_weakptr(conn),_1), + boost::bind(&TCPServer::onPacket,this,pcktHandler,connection_weakptr(conn),_1) ); } //else: Let conn go out of scope. As the conn's shared_ptrs go out of scope @@ -208,7 +213,7 @@ } // NB In handleAccept() we can let the connection_ptr go out of scope safely // as conn->startAsServerConnection() controls its own lifetime via shared_from_this(). - void handleAccept(connection_ptr conn, const boost::asio::error& error) + void handleAccept(ConnectionHandler connHandler, PacketHandler pcktHandler, connection_ptr conn, const boost::asio::error& error) { if (!error) { @@ -217,7 +222,7 @@ // Let address filter policy check the remote endpoint's address. this->async_check(remoteEndpoint.address(), - boost::bind(&TCPServer::onConnectionAccepted,this,conn,_1)); + boost::bind(&TCPServer::onConnectionAccepted,this,connHandler,pcktHandler,conn,_1)); // continue listening for / accepting incoming connections... startAccept(); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-07-17 19:31:14
|
Revision: 1763 http://svn.sourceforge.net/yake/?rev=1763&view=rev Author: psyclonist Date: 2007-07-17 12:31:14 -0700 (Tue, 17 Jul 2007) Log Message: ----------- fixed GCC 4.1.2 related standard compliance issues and added a workaround for a Luabind bug regarding get_const_holder overloads Modified Paths: -------------- trunk/yake/src/bindings.lua/detail/task.lua.cpp trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.cpp Modified: trunk/yake/src/bindings.lua/detail/task.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/task.lua.cpp 2007-06-22 17:31:05 UTC (rev 1762) +++ trunk/yake/src/bindings.lua/detail/task.lua.cpp 2007-07-17 19:31:14 UTC (rev 1763) @@ -27,6 +27,20 @@ #include <yake/config.h> #if YAKE_ENABLE_LUA_TASK == 1 +// We include yake.lua.shared_ptr.h PRIOR to including any Luabind headers. +// Reasoning: While on MSVC 8 there's no problem GCC 4.1.x fails miserably complaining +// about "you_need_to_define_a_get_const_holder_function_for_your_smart_ptr". +// This is intended to be the indicator that the luabind::get_const_holder() +// overload was not defined for the smart pointer. +// BUT: +// This is actually a bug in Luabind as "it assumes that overloaded functions +// are bound at instantiation time of templates, but overloaded functions are +// bound at definition time, so the luabind" code "only sees the +// luabind::get_const_holder(...) catch all handler. +// (Source: http://osdir.com/ml/lang.lua.bind.user/2006-02/msg00008.html) +// Solution: Include the overloads for our smart pointers PRIOR to any Luabind headers. +#include <yake/bindings.lua/common/yake.lua.shared_ptr.h> + #include <yake/bindings.lua/bindings.lua.h> // Don't forget to include this for proper dllexport! #include <yake/base/templates/yakeSmartAssert.h> @@ -34,11 +48,11 @@ #include <yake/bindings.lua/detail/private.h> #include <yake/bindings.lua/common/lua.helpers.h> #include <yake/bindings.lua/common/vminfo.lua.h> -#include <yake/bindings.lua/common/yake.lua.shared_ptr.h> #include <yake/bindings.lua/common/yake.lua.any_converter.h> #include <yake/task/task.h> + namespace yake { namespace task { Modified: trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.cpp =================================================================== --- trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.cpp 2007-06-22 17:31:05 UTC (rev 1762) +++ trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.cpp 2007-07-17 19:31:14 UTC (rev 1763) @@ -41,7 +41,7 @@ void convert_cpp_to_lua(lua_State* L, const boost::any& a) { typedef void(*conv_t)(lua_State* L, const boost::any&); - const type_info* ti = &a.type(); + const std::type_info* ti = &a.type(); // special case: 'boost::any(void)' is converted to 'nil' if (ti == &typeid(void)) @@ -69,9 +69,9 @@ case LUA_TSTRING: return boost::any( object_cast<std::string>(o) ); //@todo fixme default: - throw std::exception("encountered unsupported type in convert_lua_to_cpp()"); + throw yake::Exception("encountered unsupported type in convert_lua_to_cpp()"); } - throw std::exception("encountered unsupported type in convert_lua_to_cpp()"); + throw yake::Exception("encountered unsupported type in convert_lua_to_cpp()"); } boost::any convert_lua_to_cpp(lua_State* L, by_const_reference<boost::any>, int index) { @@ -85,9 +85,9 @@ case LUA_TSTRING: return boost::any( object_cast<std::string>(o) ); //@todo fixme default: - throw std::exception("encountered unsupported type in convert_lua_to_cpp()"); + throw yake::Exception("encountered unsupported type in convert_lua_to_cpp()"); } - throw std::exception("encountered unsupported type in convert_lua_to_cpp()"); + throw yake::Exception("encountered unsupported type in convert_lua_to_cpp()"); } int match_lua_to_cpp(lua_State* L, by_value<boost::any>, int index) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-07-18 16:38:36
|
Revision: 1769 http://svn.sourceforge.net/yake/?rev=1769&view=rev Author: psyclonist Date: 2007-07-18 09:38:32 -0700 (Wed, 18 Jul 2007) Log Message: ----------- * added sample 'property/lua1' demonstrating the Lua bindings for the 'property' library * added Lua bindings for the 'property' library * general improvements of Lua bindings code * improved interface of 'property' library Modified Paths: -------------- trunk/yake/scripts/premake/samples.lua trunk/yake/src/bindings.lua/bindings.lua.cpp trunk/yake/yake/bindings.lua/bindings.lua.h trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.h trunk/yake/yake/property/detail/property.impl.h trunk/yake/yake/property/property_container.h Added Paths: ----------- trunk/yake/common/media/samples/property/ trunk/yake/common/media/samples/property/demo.lua trunk/yake/samples/property/lua1/ trunk/yake/samples/property/lua1/demo.cpp trunk/yake/src/bindings.lua/detail/property.lua.cpp Added: trunk/yake/common/media/samples/property/demo.lua =================================================================== --- trunk/yake/common/media/samples/property/demo.lua (rev 0) +++ trunk/yake/common/media/samples/property/demo.lua 2007-07-18 16:38:32 UTC (rev 1769) @@ -0,0 +1,42 @@ + +print("create yake.NamedPropertyContainer"); +props = yake.NamedPropertyContainer(); + +print("create property 'visible' of implicit type 'bool'"); +assert( not props:has("visible") ); +--props:add( "visible", yake.createProperty(true) ); +props:create("visible",true); +assert( props:has("visible") ); + +print("acquire property object 'visible'"); +p = props:get("visible"); +assert(p); +print(" type = " .. p:type()); + +print("read & modify property"); +print( " value of 'visible' = " .. tostring(p:get()) ); +assert( p:set( not p:get() ) ); +print( " value of 'visible' = " .. tostring(p:get()) ); + +print("test for type mismatch when setting the value") +assert( not p:set("aloha") ); + +print("create property 'name' of implicit type 'String'"); +p = props:create("name","aloha"); +print(" type = " .. p:type()); +print(" value = " .. tostring(p:get()) ); +p:set("waikiki"); +print(" value = " .. tostring(p:get()) ); + +print("store a function in a property 'sayHello'"); +p = props:create("sayHello",function() print("'hello, i'm property 'sayHello'!'"); end); +print(" type = " .. p:type()); +print("running function stored in property 'sayHello'"); +assert( p:get() ); +p:get()(); + +print("attempt to create property of unsupported type 'thread'"); +p = props:create("thread", coroutine.create(function() print("thread"); end)); +assert( not p ); + +print("\nAll tests done."); \ No newline at end of file Added: trunk/yake/samples/property/lua1/demo.cpp =================================================================== --- trunk/yake/samples/property/lua1/demo.cpp (rev 0) +++ trunk/yake/samples/property/lua1/demo.cpp 2007-07-18 16:38:32 UTC (rev 1769) @@ -0,0 +1,35 @@ +#include <yake/task/task.h> +#include <yake/plugins/scriptingLua/ScriptingSystemLua.h> +#include <yake/bindings.lua/bindings.lua.h> +#include <luabind/luabind.hpp> + + +void main() +{ + using namespace yake; + + try { + // init scripting VM + typedef scripting::ScriptingSystemLua scripting_t; + scripting_t scriptingSys; + + scripting::VMPtr vm( scriptingSys.createVM() ); + YAKE_ASSERT( vm ); + lua_State* L = static_cast<scripting::LuaVM*>(vm.get())->getLuaState(); + YAKE_ASSERT( L ); + + bind_base( L ); + bind_property( vm.get() ); + + // run Lua script + scripting::ScriptPtr demoScript( scriptingSys.createScriptFromFile("../../../common/media/samples/property/demo.lua") ); + vm->execute( demoScript ); + + // clean up + vm.reset(); + } + catch (Exception& ex) + { + std::cerr << "Exception: " << ex.what() << "\n"; + } +} Modified: trunk/yake/scripts/premake/samples.lua =================================================================== --- trunk/yake/scripts/premake/samples.lua 2007-07-17 22:27:43 UTC (rev 1768) +++ trunk/yake/scripts/premake/samples.lua 2007-07-18 16:38:32 UTC (rev 1769) @@ -125,6 +125,18 @@ useComponent("base") -------------------------------------- +if LUA_BINDINGS and ENABLE_LUA_BASE and ENABLE_LUA_PROPERTY then + makeSample("samplePropertyLua1","samples/property/lua1") + sampleUsesConsole() + useComponent("base") + useComponent("scripting") + useComponent("bindings.lua") + useComponent("scriptingLua") + useDep("lua") + useDep("luabind") +end + +-------------------------------------- if SAMPLES_NET then makeSample("sampleNetMessage1","samples/net2/message1") sampleUsesConsole() @@ -195,15 +207,15 @@ -------------------------------------- if LUA_BINDINGS and ENABLE_LUA_BASE and ENABLE_LUA_TASK then - makeSample("sampleTaskLua1","samples/task/lua1") - sampleUsesConsole() - useComponent("base") - useComponent("task") - useComponent("scripting") - useComponent("bindings.lua") - useComponent("scriptingLua") - useDep("lua") - useDep("luabind") + makeSample("sampleTaskLua1","samples/task/lua1") + sampleUsesConsole() + useComponent("base") + useComponent("task") + useComponent("scripting") + useComponent("bindings.lua") + useComponent("scriptingLua") + useDep("lua") + useDep("luabind") end end Modified: trunk/yake/src/bindings.lua/bindings.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/bindings.lua.cpp 2007-07-17 22:27:43 UTC (rev 1768) +++ trunk/yake/src/bindings.lua/bindings.lua.cpp 2007-07-18 16:38:32 UTC (rev 1769) @@ -38,19 +38,27 @@ #include <yake/bindings.lua/common/yake.lua.any_converter.cpp> namespace yake { + namespace { + struct RegisterDefaultAnyConverters + { + RegisterDefaultAnyConverters() + { + register_any_converter<int>(); + register_any_converter<float>(); + register_any_converter<double>(); + register_any_converter<bool>(); + register_any_converter<String>(); + register_any_converter<luabind::object>(); + } + } g_registerDefaultAnyConverters; + } // namespace + void bind_all(lua_State* L) { YAKE_ASSERT( L ); // - register_any_converter<int>(); - register_any_converter<float>(); - register_any_converter<double>(); - register_any_converter<bool>(); - register_any_converter<String>(); - // - #if YAKE_ENABLE_LUA_BASE == 1 bind_base(L); bind_math(L); @@ -64,6 +72,9 @@ #if YAKE_ENABLE_LUA_ENT == 1 bind_ent(L); #endif +#if YAKE_ENABLE_LUA_PROPERTY == 1 + bind_property(L); +#endif } void bind_all(scripting::IVM* vm) { Added: trunk/yake/src/bindings.lua/detail/property.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/property.lua.cpp (rev 0) +++ trunk/yake/src/bindings.lua/detail/property.lua.cpp 2007-07-18 16:38:32 UTC (rev 1769) @@ -0,0 +1,137 @@ +/* +------------------------------------------------------------------------------------ +This file is part of YAKE +Copyright (c) 2004 - 2008 The YAKE Team +For the latest information visit http://www.yake.org +------------------------------------------------------------------------------------ +This program is free software; you can redistribute it and/or modify it under +the terms of the GNU Lesser General Public License as published by the Free Software +Foundation; either version 2 of the License, or (at your option) any later +version. + +This program is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along with +this program; if not, write to the Free Software Foundation, Inc., 59 Temple +Place - Suite 330, Boston, MA 02111-1307, USA, or go to +http://www.gnu.org/copyleft/lesser.txt. +------------------------------------------------------------------------------------ +If you are interested in another license model contact the Yake Team via +E-Mail: te...@ya.... +For more information see the LICENSE file in the root directory of the +source code distribution. +------------------------------------------------------------------------------------ +*/ +#include <yake/config.h> +#if YAKE_ENABLE_LUA_PROPERTY == 1 + +#include <yake/bindings.lua/common/yake.lua.shared_ptr.h> + +#include <yake/bindings.lua/bindings.lua.h> // Don't forget to include this for proper dllexport! + +#include <yake/base/templates/yakeSmartAssert.h> +#include <yake/base/yake.h> +#include <yake/property/property.h> + +#include <yake/bindings.lua/common/yake.lua.any_converter.h> +#include <yake/bindings.lua/detail/private.h> + +namespace yake { + namespace property { + typedef PropertyContainer<String> NamedPropertyContainer; + PropertyPtr createProperty(luabind::object o) + { + assert( o.is_valid() ); + switch (luabind::type(o)) + { + case LUA_TBOOLEAN: + return PropertyPtr(makeValueProperty<bool>( luabind::object_cast<bool>(o) )); + case LUA_TNUMBER: + return PropertyPtr(makeValueProperty<double>( luabind::object_cast<double>(o) )); + case LUA_TSTRING: + return PropertyPtr(makeValueProperty<String>( luabind::object_cast<String>(o) )); + case LUA_TFUNCTION: + return PropertyPtr(makeValueProperty<luabind::object>( o )); + default: + //throw Exception("bindings.lua:yake.property.createProperty: unhandled type"); + //@todo use proper logging: + std::cerr << "ERROR: bindings.lua:yake.property.createProperty: unhandled type\n"; + return PropertyPtr(); + } + } + PropertyBase* createAndAddProperty(NamedPropertyContainer& ctr, const char* name, luabind::object o) + { + PropertyPtr prop = createProperty(o); + if (!prop.get()) + return 0; + ctr.add( name, prop ); + return prop.get(); + } + PropertyBase* getProperty(NamedPropertyContainer& ctr, const char* name) + { + PropertyPtr prop = ctr.getPtr(name); + return prop.get(); + } + bool setPropertyValue(PropertyBase& prop, const boost::any& value) + { + try { + prop.setAny( value ); + return true; + } + catch (BadCastException& ex) + { + return false; + } + } + + + void bind( lua_State* L ) + { + YAKE_ASSERT( L ); + if (!L) + return; + + using namespace luabind; + +#define YAKE_MODEL_MODULE L, "yake" + + module( YAKE_MODEL_MODULE ) + [ + //def( "createProperty", &createProperty ), + class_<PropertyBase/*,PropertyPtr*/>( "PropertyBase" ) + .def( "type", &PropertyBase::type ) + //.def( "set", &PropertyBase::setAny ) + .def( "set", &setPropertyValue ) + .def( "get", (boost::any(PropertyBase::*)()const)&PropertyBase::getAny ) + ]; + module( YAKE_MODEL_MODULE ) + [ + class_<NamedPropertyContainer>( "NamedPropertyContainer" ) + .def( constructor<>() ) + .def( "add", (void(NamedPropertyContainer::*)(const String&,PropertyPtr))&NamedPropertyContainer::add ) + .def( "has", &NamedPropertyContainer::has ) + //.def( "get", (PropertyBase&(NamedPropertyContainer::*)(const String&))&NamedPropertyContainer::get ) + //.def( "get", (PropertyPtr(NamedPropertyContainer::*)(const String&)const)&NamedPropertyContainer::getPtr ) + .def( "get", &getProperty ) + .def( "create", &createAndAddProperty ) + ]; + } + + YAKE_WRAP_BINDER(model,::yake::property::bind); + + } // namespace model + void bind_property(lua_State* L) + { + YAKE_ASSERT(L); + property::bind(L); + } + void bind_property(scripting::IVM* vm) + { + scripting::LuaVM* luavm = static_cast<scripting::LuaVM*>(vm); + YAKE_ASSERT( luavm ); + bind_property(luavm->getLuaState()); + } +} // namespace yake +#endif // YAKE_ENABLE_LUA_PROPERTY \ No newline at end of file Modified: trunk/yake/yake/bindings.lua/bindings.lua.h =================================================================== --- trunk/yake/yake/bindings.lua/bindings.lua.h 2007-07-17 22:27:43 UTC (rev 1768) +++ trunk/yake/yake/bindings.lua/bindings.lua.h 2007-07-18 16:38:32 UTC (rev 1769) @@ -52,6 +52,10 @@ YAKE_BINDINGS_LUA_API void bind_ent(lua_State*); YAKE_BINDINGS_LUA_API void bind_ent(scripting::IVM*); #endif +#if YAKE_ENABLE_LUA_PROPERTY == 1 + YAKE_BINDINGS_LUA_API void bind_property(lua_State*); + YAKE_BINDINGS_LUA_API void bind_property(scripting::IVM*); +#endif } // namespace yake #endif Modified: trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.h =================================================================== --- trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.h 2007-07-17 22:27:43 UTC (rev 1768) +++ trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.h 2007-07-18 16:38:32 UTC (rev 1769) @@ -29,6 +29,7 @@ // #include <yake/base/yakePrerequisites.h> +#include <yake/bindings.lua/prerequisites.h> #include <yake/bindings.lua/common/yake.lua.common.h> #include <map> #include <boost/any.hpp> @@ -47,11 +48,7 @@ typedef std::map<const std::type_info*, void(*)(lua_State*, const boost::any&)> any_converter_map; -#if defined(YAKE_EXPORT_LUA_ANY_CONVERTER) -# define YAKE_LUA_ANY_CONVERTER_API YAKE_EXPORT_API -#else -# define YAKE_LUA_ANY_CONVERTER_API YAKE_IMPORT_API -#endif +#define YAKE_LUA_ANY_CONVERTER_API YAKE_BINDINGS_LUA_API YAKE_LUA_ANY_CONVERTER_API any_converter_map& any_converters(); Modified: trunk/yake/yake/property/detail/property.impl.h =================================================================== --- trunk/yake/yake/property/detail/property.impl.h 2007-07-17 22:27:43 UTC (rev 1768) +++ trunk/yake/yake/property/detail/property.impl.h 2007-07-18 16:38:32 UTC (rev 1769) @@ -113,7 +113,7 @@ } catch (boost::bad_any_cast&) { - throw; + throw BadCastException("Property<>::setAny(): bad_any_cast"); } } virtual void getAny(boost::any& out) const Modified: trunk/yake/yake/property/property_container.h =================================================================== --- trunk/yake/yake/property/property_container.h 2007-07-17 22:27:43 UTC (rev 1768) +++ trunk/yake/yake/property/property_container.h 2007-07-18 16:38:32 UTC (rev 1769) @@ -37,7 +37,7 @@ template<typename Kt> struct DefaultErrorPolicy { - void onNotFound(const Kt& key) + void onNotFound(const Kt& key) const { throw NotFoundException("id/key not found"); } @@ -67,8 +67,10 @@ typedef ErrorPolicy<Kt> error_policy_t; typedef Kt key_type; void add(const key_type& id, PropertyBase* prop); + void add(const key_type& id, PropertyPtr prop); const PropertyBase& get(const key_type& id) const; PropertyBase& get(const key_type& id); + PropertyPtr getPtr(const key_type& id) const; // <= doesn't throw. bool has(const key_type& id) const; private: @@ -100,6 +102,22 @@ properties_.insert( std::make_pair(id,PropertyPtr(prop)) ); } template<typename Kt, template <typename> class ErrorPolicy> + void PropertyContainer<Kt,ErrorPolicy>::add(const key_type &id, PropertyPtr prop) + { + if (!prop) + { + this->onInvalidInput("null pointer"); + return; + } + PropertyMap::const_iterator it = properties_.find( id ); + if (it != properties_.end()) + { + this->onAlreadyExists(id); //@todo possible memory leak if client doesn't clean up "prop" + return; + } + properties_.insert( std::make_pair(id,prop) ); + } + template<typename Kt, template <typename> class ErrorPolicy> const PropertyBase& PropertyContainer<Kt,ErrorPolicy>::get(const key_type& id) const { PropertyMap::const_iterator it = properties_.find( id ); @@ -122,6 +140,18 @@ return *it->second; } template<typename Kt, template <typename> class ErrorPolicy> + PropertyPtr PropertyContainer<Kt,ErrorPolicy>::getPtr(const key_type& id) const + { + PropertyMap::const_iterator it = properties_.find( id ); + if (it == properties_.end()) + { + //this->onNotFound(id); // should throw! + //throw NotFoundException("property with this id not found"); // fallback if error handler doesn't throw + return PropertyPtr(); + } + return it->second; + } + template<typename Kt, template <typename> class ErrorPolicy> bool PropertyContainer<Kt,ErrorPolicy>::has(const key_type& id) const { PropertyMap::const_iterator it = properties_.find( id ); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-07-18 19:04:11
|
Revision: 1771 http://svn.sourceforge.net/yake/?rev=1771&view=rev Author: psyclonist Date: 2007-07-18 12:04:13 -0700 (Wed, 18 Jul 2007) Log Message: ----------- improved library "yake::property": * 'boost::any' converters do now also automatically register 'property' value setters * Modified Paths: -------------- trunk/yake/common/media/samples/property/demo.lua trunk/yake/samples/property/lua1/demo.cpp trunk/yake/src/bindings.lua/bindings.lua.cpp trunk/yake/src/bindings.lua/detail/base.lua.cpp trunk/yake/src/bindings.lua/detail/property.lua.cpp trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.h Modified: trunk/yake/common/media/samples/property/demo.lua =================================================================== --- trunk/yake/common/media/samples/property/demo.lua 2007-07-18 16:43:58 UTC (rev 1770) +++ trunk/yake/common/media/samples/property/demo.lua 2007-07-18 19:04:13 UTC (rev 1771) @@ -23,20 +23,36 @@ print("create property 'name' of implicit type 'String'"); p = props:create("name","aloha"); +assert( p ); print(" type = " .. p:type()); print(" value = " .. tostring(p:get()) ); -p:set("waikiki"); +assert( p:get() == "aloha" ); +assert( p:set("waikiki") ); print(" value = " .. tostring(p:get()) ); +assert( p:get() == "waikiki" ); print("store a function in a property 'sayHello'"); p = props:create("sayHello",function() print("'hello, i'm property 'sayHello'!'"); end); +assert( p ); print(" type = " .. p:type()); print("running function stored in property 'sayHello'"); assert( p:get() ); p:get()(); +--NB At the moment you can store ANY kind of Lua object in a property! +-- On the C++ side any 'unknown' or unregistered property type will be stored +-- as a luabind::object. Be careful! print("attempt to create property of unsupported type 'thread'"); p = props:create("thread", coroutine.create(function() print("thread"); end)); -assert( not p ); +--assert( not p ); +print("attempt to create property of type 'Vector3'"); +p = props:create("position", yake.Vector3(1,2,3)); +print(" value = (" .. p:get().x .. "," .. p:get().y .. "," .. p:get().z .. ")" ); +--assert( p:get():isEqualTo( yake.Vector(1,2,3) ) ); +assert( p:get().x == 1 ); +assert( not p:set(yake.Quaternion(1,0,0,1)) ); --will fail because of type mismatch +assert( p:set( yake.Vector3(2,3,4) ) ); +print(" value = (" .. p:get().x .. "," .. p:get().y .. "," .. p:get().z .. ")" ); + print("\nAll tests done."); \ No newline at end of file Modified: trunk/yake/samples/property/lua1/demo.cpp =================================================================== --- trunk/yake/samples/property/lua1/demo.cpp 2007-07-18 16:43:58 UTC (rev 1770) +++ trunk/yake/samples/property/lua1/demo.cpp 2007-07-18 19:04:13 UTC (rev 1771) @@ -14,6 +14,7 @@ YAKE_ASSERT( vm ); bind_base( vm.get() ); + bind_math( vm.get() ); bind_property( vm.get() ); // run Lua script Modified: trunk/yake/src/bindings.lua/bindings.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/bindings.lua.cpp 2007-07-18 16:43:58 UTC (rev 1770) +++ trunk/yake/src/bindings.lua/bindings.lua.cpp 2007-07-18 19:04:13 UTC (rev 1771) @@ -48,6 +48,7 @@ register_any_converter<double>(); register_any_converter<bool>(); register_any_converter<String>(); + register_any_converter<luabind::object>(); } } g_registerDefaultAnyConverters; Modified: trunk/yake/src/bindings.lua/detail/base.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/base.lua.cpp 2007-07-18 16:43:58 UTC (rev 1770) +++ trunk/yake/src/bindings.lua/detail/base.lua.cpp 2007-07-18 19:04:13 UTC (rev 1771) @@ -45,7 +45,13 @@ YAKE_ASSERT(L); if (!L) return; + // + register_any_converter<Color>(); + register_any_converter<Vector3>(); + register_any_converter<Quaternion>(); + register_any_converter<Matrix3>(); + // using namespace luabind; #define YAKE_MATH_MODULE L, "yake" @@ -85,6 +91,7 @@ .def_readwrite( "x", &yake::math::Vector3::x ) .def_readwrite( "y", &yake::math::Vector3::y ) .def_readwrite( "z", &yake::math::Vector3::z ) + .def( constructor<>() ) .def( constructor< real, real, real >() ) .def( constructor< const real* const >() ) .def( constructor< Vector3 const& >() ) @@ -167,6 +174,8 @@ if (!L) return; + // + using namespace luabind; #define YAKE_BASE_MODULE L, "yake" Modified: trunk/yake/src/bindings.lua/detail/property.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/property.lua.cpp 2007-07-18 16:43:58 UTC (rev 1770) +++ trunk/yake/src/bindings.lua/detail/property.lua.cpp 2007-07-18 19:04:13 UTC (rev 1771) @@ -40,7 +40,31 @@ namespace yake { namespace property { + PropertyFromAnyMap& any_property_creators() + { + static PropertyFromAnyMap s_creators; + return s_creators; + } + PropertyFromObjectMap& object_property_creators() + { + static PropertyFromObjectMap s_creators; + return s_creators; + } + BindSetPropertyFnList& setPropertyValue_binders() + { + static BindSetPropertyFnList s_binders; + return s_binders; + } typedef PropertyContainer<String> NamedPropertyContainer; + PropertyPtr createPropertyFromAny(const boost::any& o) + { + const std::type_info* ti = &o.type(); + PropertyFromAnyMap::const_iterator it = any_property_creators().find( ti ); + if (it == any_property_creators().end() || !it->second) + return PropertyPtr(); //@todo log this? + PropertyBase* prop = (*it->second)(o); + return PropertyPtr(prop); + } PropertyPtr createProperty(luabind::object o) { assert( o.is_valid() ); @@ -56,6 +80,18 @@ return PropertyPtr(makeValueProperty<luabind::object>( o )); default: //throw Exception("bindings.lua:yake.property.createProperty: unhandled type"); + + // Brute-force through list of 'luabind::object -> c++' converters: + // @todo performance? + for (PropertyFromObjectMap::const_iterator it = object_property_creators().begin(); it != object_property_creators().end(); ++it) + { + PropertyFromObjectFn fn = it->second; + YAKE_ASSERT( fn ); + PropertyPtr prop( fn( o ) ); + if (prop.get()) + return prop; + } + //@todo use proper logging: std::cerr << "ERROR: bindings.lua:yake.property.createProperty: unhandled type\n"; return PropertyPtr(); @@ -69,6 +105,14 @@ ctr.add( name, prop ); return prop.get(); } + PropertyBase* createAndAddPropertyFromAny(NamedPropertyContainer& ctr, const char* name, const boost::any& o) + { + PropertyPtr prop = createPropertyFromAny(o); + if (!prop.get()) + return 0; + ctr.add( name, prop ); + return prop.get(); + } PropertyBase* getProperty(NamedPropertyContainer& ctr, const char* name) { PropertyPtr prop = ctr.getPtr(name); @@ -86,6 +130,10 @@ } } + void bind_PropertyBase_set(luabind::class_<PropertyBase>& x) + { + x.def("set", &setPropertyValue_Generic<Vector3>); + } void bind( lua_State* L ) { @@ -97,17 +145,26 @@ #define YAKE_MODEL_MODULE L, "yake" + //class: PropertyBase + class_<PropertyBase/*,PropertyPtr*/> x( "PropertyBase" ); + x + .def( "type", &PropertyBase::type ) + //.def( "set", &PropertyBase::setAny ) + .def( "set", &setPropertyValue ) // for boost::any + .def( "get", (boost::any(PropertyBase::*)()const)&PropertyBase::getAny ) + ; + // register additional 'set' overloads: + for (BindSetPropertyFnList::const_iterator it = setPropertyValue_binders().begin(); + it != setPropertyValue_binders().end(); ++it) + { + (*it)(x); + } + // + module( YAKE_MODEL_MODULE )[ x ] ; + + // module( YAKE_MODEL_MODULE ) [ - //def( "createProperty", &createProperty ), - class_<PropertyBase/*,PropertyPtr*/>( "PropertyBase" ) - .def( "type", &PropertyBase::type ) - //.def( "set", &PropertyBase::setAny ) - .def( "set", &setPropertyValue ) - .def( "get", (boost::any(PropertyBase::*)()const)&PropertyBase::getAny ) - ]; - module( YAKE_MODEL_MODULE ) - [ class_<NamedPropertyContainer>( "NamedPropertyContainer" ) .def( constructor<>() ) .def( "add", (void(NamedPropertyContainer::*)(const String&,PropertyPtr))&NamedPropertyContainer::add ) @@ -115,7 +172,11 @@ //.def( "get", (PropertyBase&(NamedPropertyContainer::*)(const String&))&NamedPropertyContainer::get ) //.def( "get", (PropertyPtr(NamedPropertyContainer::*)(const String&)const)&NamedPropertyContainer::getPtr ) .def( "get", &getProperty ) - .def( "create", &createAndAddProperty ) + + // For native Lua types which can simply mapped to C++: + .def( "create", (PropertyBase*(*)(NamedPropertyContainer&,const char*,const boost::any&))&createAndAddPropertyFromAny ) + // For all other 'custom' registered and unknown types: + .def( "create", (PropertyBase*(*)(NamedPropertyContainer&,const char*,luabind::object))&createAndAddProperty ) ]; } Modified: trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.h =================================================================== --- trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.h 2007-07-18 16:43:58 UTC (rev 1770) +++ trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.h 2007-07-18 19:04:13 UTC (rev 1771) @@ -34,6 +34,46 @@ #include <map> #include <boost/any.hpp> +#define YAKE_LUA_ANY_CONVERTER_API YAKE_BINDINGS_LUA_API + + +#if YAKE_ENABLE_LUA_PROPERTY == 1 // extension for yake::property: +# include <yake/property/property.h> + namespace yake { + namespace property { + struct PropertyBase; + + typedef PropertyBase*(*PropertyFromAnyFn)(const boost::any&); + typedef std::map<const std::type_info*,PropertyFromAnyFn> PropertyFromAnyMap; + YAKE_LUA_ANY_CONVERTER_API PropertyFromAnyMap& any_property_creators(); + + typedef PropertyBase*(*PropertyFromObjectFn)(const luabind::object&); + typedef std::map<const std::type_info*,PropertyFromObjectFn> PropertyFromObjectMap; + YAKE_LUA_ANY_CONVERTER_API PropertyFromObjectMap& object_property_creators(); + + typedef void(*BindSetPropertyFn)(luabind::class_<PropertyBase>&); + typedef std::vector<BindSetPropertyFn> BindSetPropertyFnList; + YAKE_LUA_ANY_CONVERTER_API BindSetPropertyFnList& setPropertyValue_binders(); + + template<typename T> + bool setPropertyValue_Generic(PropertyBase& prop, const T& value) + { + try { + prop.setAny( value ); + return true; + } + catch (BadCastException&) + { + //@todo report error! throw exception? + std::cerr << ">>> Warning: Type mismatch on setting of property value!\n"; + std::cerr << " value type=" << typeid(T).name() << " expected type=" << prop.type() << "\n"; + return false; + } + } + } // namespace property + } // namespace yake +#endif + // boost::any bindings template<class T> struct convert_any @@ -44,12 +84,39 @@ //conv.apply(L, *boost::any_cast<T>(&a)); luabind::detail::convert_to_lua(L, *boost::any_cast<T>(&a)); } +#if YAKE_ENABLE_LUA_PROPERTY == 1 // extension for yake::property: + static yake::property::PropertyBase* yake_createValuePropertyFromAny(const boost::any& a) + { + try + { + yake::property::Property<T>* prop = yake::property::makeValueProperty<T>( boost::any_cast<T>(a) ); + YAKE_ASSERT( prop ); + return prop; + } + catch (boost::bad_any_cast&) + { + return 0;//@todo report error + } + } + static yake::property::PropertyBase* yake_createValuePropertyFromObject(const luabind::object& a) + { + //int type = luabind::type(a); + boost::optional<T> value = luabind::object_cast_nothrow<T>(a); + if (!value) + return 0; //@todo report error + // + yake::property::Property<T>* prop = yake::property::makeValueProperty<T>( *value ); + YAKE_ASSERT( prop ); + return prop; + } + static void yake_bind_setPropertyValue(luabind::class_<yake::property::PropertyBase>& x) + { + x.def("set",&yake::property::setPropertyValue_Generic<T>); + } +#endif }; typedef std::map<const std::type_info*, void(*)(lua_State*, const boost::any&)> any_converter_map; - -#define YAKE_LUA_ANY_CONVERTER_API YAKE_BINDINGS_LUA_API - YAKE_LUA_ANY_CONVERTER_API any_converter_map& any_converters(); //any_converter_map any_converters; @@ -58,6 +125,11 @@ void register_any_converter() { any_converters()[&typeid(T)] = convert_any<T>::convert; +#if YAKE_ENABLE_LUA_PROPERTY == 1 // extension for yake::property: + yake::property::any_property_creators()[&typeid(T)] = convert_any<T>::yake_createValuePropertyFromAny; + yake::property::object_property_creators()[&typeid(T)] = convert_any<T>::yake_createValuePropertyFromObject; + yake::property::setPropertyValue_binders().push_back( convert_any<T>::yake_bind_setPropertyValue ); +#endif } namespace luabind This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-07-26 17:57:19
|
Revision: 1774 http://yake.svn.sourceforge.net/yake/?rev=1774&view=rev Author: psyclonist Date: 2007-07-26 10:57:16 -0700 (Thu, 26 Jul 2007) Log Message: ----------- * improved Lua bindings for yake.property, yake.ent, yake.object and other components * fixed boost::any conversions where it failed in special cases * improved samples using Lua bindings * added properties to yake.ent (using yake.properties instead of yake.prop) along with default properties for ent::Object and ent::Entity etc pp * added 'default binder' functionality to basic IVM scripting interface Modified Paths: -------------- trunk/yake/samples/README.TXT trunk/yake/samples/property/lua1/demo.cpp trunk/yake/scripts/premake/samples.lua trunk/yake/src/bindings.lua/bindings.lua.cpp trunk/yake/src/bindings.lua/detail/ent.lua.cpp trunk/yake/src/bindings.lua/detail/property.lua.cpp trunk/yake/src/ent/entity.cpp trunk/yake/src/ent/object.cpp trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.cpp trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.h trunk/yake/yake/ent/component.h trunk/yake/yake/ent/entity.h trunk/yake/yake/ent/object.h trunk/yake/yake/ent/prerequisites.h trunk/yake/yake/plugins/scriptingLua/ScriptingSystemLua.h trunk/yake/yake/property/accessors.h trunk/yake/yake/property/property.h trunk/yake/yake/property/property_container.h trunk/yake/yake/scripting/yakeScriptingSystem.h Added Paths: ----------- trunk/yake/yake/bindings.lua/detail/property.lua.h Modified: trunk/yake/samples/README.TXT =================================================================== --- trunk/yake/samples/README.TXT 2007-07-26 17:51:59 UTC (rev 1773) +++ trunk/yake/samples/README.TXT 2007-07-26 17:57:16 UTC (rev 1774) @@ -11,11 +11,14 @@ raf/minimal - bare-bones RAF application raf/demo1 - initialisation of graphics and creation of a very basic scene ent/sampleEntFsm - entity scripting +ent/lua1 - C++/Lua demo demonstrating yake.ent bindings (properties, ObjectIds etc) physics/demo - basic physics demo (multiple viewports, simplistic objects) vehicle - different vehicles can be controlled (car,jet). uses RAF, entities and models. base/scripting/lua - basic scripting demo task/demo1 - basic task/executor demo task/lua1 - Lua task/execution demo +property/demo1 - C++ demo demonstrating how to use properties +property/lua1 - C++/Lua demo demonstrating the yake.properties bindings ---- in flux: (i.e. in process of being added to the main build scripts) Modified: trunk/yake/samples/property/lua1/demo.cpp =================================================================== --- trunk/yake/samples/property/lua1/demo.cpp 2007-07-26 17:51:59 UTC (rev 1773) +++ trunk/yake/samples/property/lua1/demo.cpp 2007-07-26 17:57:16 UTC (rev 1774) @@ -10,13 +10,15 @@ typedef scripting::ScriptingSystemLua scripting_t; scripting_t scriptingSys; + // use default binder instead of: bind_base(vm); etc + typedef void(*FreeBinderFn)(scripting::IVM*); + scriptingSys.addDefaultBinder( (FreeBinderFn)&bind_base ); + scriptingSys.addDefaultBinder( (FreeBinderFn)&bind_math ); + scriptingSys.addDefaultBinder( (FreeBinderFn)&bind_property ); + scripting::VMPtr vm( scriptingSys.createVM() ); YAKE_ASSERT( vm ); - bind_base( vm.get() ); - bind_math( vm.get() ); - bind_property( vm.get() ); - // run Lua script scripting::ScriptPtr demoScript( scriptingSys.createScriptFromFile("../../../common/media/samples/property/demo.lua") ); vm->execute( demoScript ); Modified: trunk/yake/scripts/premake/samples.lua =================================================================== --- trunk/yake/scripts/premake/samples.lua 2007-07-26 17:51:59 UTC (rev 1773) +++ trunk/yake/scripts/premake/samples.lua 2007-07-26 17:57:16 UTC (rev 1774) @@ -40,12 +40,14 @@ useComponent("base") -------------------------------------- -makeSample("sampleEntFsm","samples/ent/sampleEntFsm") -sampleUsesConsole() -useComponent("base") -useComponent("scripting") -useComponent("ent") -useComponent("bindings.lua") +if LUA_BINDINGS and ENABLE_LUA_BASE and ENABLE_LUA_PROPERTY and ENABLE_LUA_ENT then + makeSample("sampleEntFsm","samples/ent/sampleEntFsm") + sampleUsesConsole() + useComponent("base") + useComponent("scripting") + useComponent("ent") + useComponent("bindings.lua") +end -------------------------------------- makeSample("sampleAudio1","samples/audio/demo1") Modified: trunk/yake/src/bindings.lua/bindings.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/bindings.lua.cpp 2007-07-26 17:51:59 UTC (rev 1773) +++ trunk/yake/src/bindings.lua/bindings.lua.cpp 2007-07-26 17:57:16 UTC (rev 1774) @@ -70,12 +70,12 @@ #if YAKE_ENABLE_LUA_MODEL == 1 bind_model(L); #endif +#if YAKE_ENABLE_LUA_PROPERTY == 1 + bind_property(L); +#endif #if YAKE_ENABLE_LUA_ENT == 1 bind_ent(L); #endif -#if YAKE_ENABLE_LUA_PROPERTY == 1 - bind_property(L); -#endif } void bind_all(scripting::IVM* vm) { Modified: trunk/yake/src/bindings.lua/detail/ent.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/ent.lua.cpp 2007-07-26 17:51:59 UTC (rev 1773) +++ trunk/yake/src/bindings.lua/detail/ent.lua.cpp 2007-07-26 17:57:16 UTC (rev 1774) @@ -35,17 +35,92 @@ #include <yake/bindings.lua/common/yake.lua.shared_ptr.h> #include <yake/bindings.lua/common/yake.lua.any_converter.h> #include <yake/bindings.lua/detail/private.h> +#include <yake/bindings.lua/detail/property.lua.h> +#include <luabind/iterator_policy.hpp> +#include <luabind/operator.hpp> + namespace yake { namespace ent { + // For Lua's tostring(): +// std::ostream& operator<<(std::ostream& out, const ObjectId& rhs) +// { +// out << "ObjectId(" << rhs.classId() << ":" << rhs.serialNo() << ")"; +// return out; +// } + std::ostream& operator<<(std::ostream& out, const Object& rhs) + { + out << "Object(id=" << rhs.id() << ")"; + return out; + } + + // + typedef luabind::class_<Object> LuabindClass_Object; + typedef luabind::class_<Object::PropertyAccess> LuabindClass_Object_PropertyAccess; + //------------------------------------------------------------------------- + static property::PropertyBase* getPropertyOfObject(Object& o, const PropertyId& id) + { + return o.properties().get(id).get(); + } + static Object::PropertyAccess* getObjectPoperties(Object& o) + { + Object::PropertyAccess& x = o.properties(); + return &x; + } + static property::PropertyBase* Object_PropertyAccess_get(Object::PropertyAccess& o, const char* id) + { + return o.get( id ).get(); + } + //------------------------------------------------------------------------- + // Helper struct so that we gain access to the private member + // "properties_" in Object::PropertyAccess: + struct LuaBinder + { + static void bind(LuabindClass_Object& x_Object) + { + using namespace luabind; + //x_Object.def_readonly( "properties", &Object::properties_, return_stl_iterator); + } + //------------------------------------------------------------------------- + static property::PropertyBase* createAndAddProperty(Object::PropertyAccess& access, const char* name, luabind::object o) + { + try { + return property::createAndAddProperty( access.properties_, name, o ); + } + catch (yake::AlreadyExistsException& ex) + { + //@todo properly report error/warning + std::cerr << "WARNING: " << ex.what() << "\n"; + return 0; + } + } + static property::PropertyBase* createAndAddPropertyFromAny(Object::PropertyAccess& access, const char* name, const boost::any& o) + { + try { + return property::createAndAddPropertyFromAny( access.properties_, name, o ); + } + catch (yake::AlreadyExistsException& ex) + { + //@todo properly report error/warning + std::cerr << "WARNING: " << ex.what() << "\n"; + return 0; + } + } + }; + //------------------------------------------------------------------------- void bind( lua_State* L ) { YAKE_ASSERT( L ); if (!L) return; + // + register_any_converter<ObjectId>(); + //register_property_value_converter<ObjectId>(); + + // using namespace luabind; using namespace yake::model; @@ -59,16 +134,48 @@ module( YAKE_MODEL_MODULE ) [ - class_<Object>( "Object" ) - .def( constructor<>() ) - .def( "setId", &Object::setId ) - .def( "id", &Object::getId ) + class_<ObjectId>( "ObjectId" ) + .def( constructor<>() ) + .def( constructor<ClassId,ObjectSerialNo>() ) + .def("isNull", &ObjectId::isNull) + .property("classId", &ObjectId::classId) + .property("serialNo", &ObjectId::serialNo) + .def(tostring(const_self)) + .def(const_self == other<ObjectId>()) ]; + LuabindClass_Object_PropertyAccess x_Object_PropertyAccess("Object::PropertyAccess"); + x_Object_PropertyAccess + .def( "get", &Object_PropertyAccess_get ) + .def( "has", &Object::PropertyAccess::has ) + + // For native Lua types which can simply mapped to C++: + .def( "create", (property::PropertyBase*(*)(Object::PropertyAccess&,const char*,const boost::any&))&LuaBinder::createAndAddPropertyFromAny ) + // For all other 'custom' registered and unknown types: + .def( "create", (property::PropertyBase*(*)(Object::PropertyAccess&,const char*,luabind::object))&LuaBinder::createAndAddProperty ) + ; module( YAKE_MODEL_MODULE ) + [ x_Object_PropertyAccess ]; + + LuabindClass_Object x_Object("Object"); + x_Object + //.def( constructor<>() ) + //.def( "setId", &Object::setId ) + //.def( "id", &Object::getId ) + .property( "id", &Object::getId, &Object::setId ) + .def( "property", &getPropertyOfObject ) + .def( "properties", &getObjectPoperties ) + //.def( "properties", return_reference_to(_1) ) + .def(tostring(const_self)) + ; + LuaBinder::bind(x_Object); + module( YAKE_MODEL_MODULE ) + [ x_Object ]; + + module( YAKE_MODEL_MODULE ) [ class_<Entity,Object>( "Entity" ) - .def( constructor<>() ) + //.def( constructor<>() ) .def( "setModel", &Entity::setModel ) .def( "getModel", &Entity::getModel ) @@ -97,11 +204,10 @@ namespace detail { void executeOfTable_2(scripting::IVM& vm, const std::string& tbl1name, const std::string& tbl2name, const std::string& fn) { + scripting::LuaVM& luaVM = static_cast<scripting::LuaVM&>(vm); + lua_State* luaState = luaVM.getLuaState(); + YAKE_ASSERT( luaState ); try { - scripting::LuaVM& luaVM = static_cast<scripting::LuaVM&>(vm); - lua_State* luaState = luaVM.getLuaState(); - YAKE_ASSERT( luaState ); - luabind::object tbl1 = luabind::globals(luaState)[tbl1name.c_str()]; if (luabind::type(tbl1) == LUA_TNIL) //if (!tbl1) @@ -109,7 +215,7 @@ std::cerr << "vm error: could not find table '" << tbl1name << "'.\n"; return; } - assert( luabind::type(tbl1) == LUA_TTABLE ); + YAKE_ASSERT( luabind::type(tbl1) == LUA_TTABLE ); luabind::object tbl2 = tbl1[tbl2name.c_str()]; if (luabind::type(tbl2) == LUA_TNIL) @@ -118,16 +224,22 @@ std::cerr << "vm error: could not find table '" << tbl1name << "." << tbl2name << "'.\n"; return; } - assert( luabind::type(tbl2) == LUA_TTABLE ); + YAKE_ASSERT( luabind::type(tbl2) == LUA_TTABLE ); luabind::object fnObj = tbl2[fn.c_str()]; - assert( luabind::type(fnObj) == LUA_TFUNCTION ); + YAKE_ASSERT( luabind::type(fnObj) == LUA_TFUNCTION ); fnObj(); } + catch (luabind::error& e) + { + std::string err = lua_tostring(luaState, -1); + lua_pop(luaState, 2); + YAKE_EXCEPT(String("Luabind error:") + e.what() + ": " + err); + } catch (...) { - YAKE_EXCEPT("executeOfTable_2(): Bad cast! VM is not a Lua VM!"); + YAKE_EXCEPT("executeOfTable_2(): Exception caught!"); } } } Modified: trunk/yake/src/bindings.lua/detail/property.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/property.lua.cpp 2007-07-26 17:51:59 UTC (rev 1773) +++ trunk/yake/src/bindings.lua/detail/property.lua.cpp 2007-07-26 17:57:16 UTC (rev 1774) @@ -37,6 +37,7 @@ #include <yake/bindings.lua/common/yake.lua.any_converter.h> #include <yake/bindings.lua/detail/private.h> +#include <yake/bindings.lua/detail/property.lua.h> namespace yake { namespace property { @@ -55,7 +56,6 @@ static BindSetPropertyFnList s_binders; return s_binders; } - typedef PropertyContainer<String> NamedPropertyContainer; PropertyPtr createPropertyFromAny(const boost::any& o) { const std::type_info* ti = &o.type(); @@ -83,7 +83,8 @@ // Brute-force through list of 'luabind::object -> c++' converters: // @todo performance? - for (PropertyFromObjectMap::const_iterator it = object_property_creators().begin(); it != object_property_creators().end(); ++it) + const PropertyFromObjectMap& creators = object_property_creators(); + for (PropertyFromObjectMap::const_iterator it = creators.begin(); it != creators.end(); ++it) { PropertyFromObjectFn fn = it->second; YAKE_ASSERT( fn ); @@ -91,6 +92,12 @@ if (prop.get()) return prop; } + // As a last resort try to convert to luabind::object property: + // For details read the comments for register_any_converter<luabind::object>() + // specialization. + PropertyPtr prop( convert_any<luabind::object>::yake_createValuePropertyFromObject( o ) ); + if (prop.get()) + return prop; //@todo use proper logging: std::cerr << "ERROR: bindings.lua:yake.property.createProperty: unhandled type\n"; @@ -146,11 +153,10 @@ #define YAKE_MODEL_MODULE L, "yake" //class: PropertyBase - class_<PropertyBase/*,PropertyPtr*/> x( "PropertyBase" ); + LuabindClass_PropertyBase x( "PropertyBase" ); x .def( "type", &PropertyBase::type ) - //.def( "set", &PropertyBase::setAny ) - .def( "set", &setPropertyValue ) // for boost::any + //.def( "set", &setPropertyValue ) // for boost::any .def( "get", (boost::any(PropertyBase::*)()const)&PropertyBase::getAny ) ; // register additional 'set' overloads: @@ -167,7 +173,7 @@ [ class_<NamedPropertyContainer>( "NamedPropertyContainer" ) .def( constructor<>() ) - .def( "add", (void(NamedPropertyContainer::*)(const String&,PropertyPtr))&NamedPropertyContainer::add ) + //.def( "add", (void(NamedPropertyContainer::*)(const String&,PropertyPtr))&NamedPropertyContainer::add ) .def( "has", &NamedPropertyContainer::has ) //.def( "get", (PropertyBase&(NamedPropertyContainer::*)(const String&))&NamedPropertyContainer::get ) //.def( "get", (PropertyPtr(NamedPropertyContainer::*)(const String&)const)&NamedPropertyContainer::getPtr ) @@ -180,7 +186,7 @@ ]; } - YAKE_WRAP_BINDER(model,::yake::property::bind); + YAKE_WRAP_BINDER(property,::yake::property::bind); } // namespace model void bind_property(lua_State* L) Modified: trunk/yake/src/ent/entity.cpp =================================================================== --- trunk/yake/src/ent/entity.cpp 2007-07-26 17:51:59 UTC (rev 1773) +++ trunk/yake/src/ent/entity.cpp 2007-07-26 17:57:16 UTC (rev 1774) @@ -32,6 +32,10 @@ IMPL_OBJECT(Entity) + Entity::Entity() + { + properties().add("model", property::makePointerProperty<ModelPtr>(&model_) ); + } void Entity::processFsmEvent(const fsm_event_type& evt) { // On MSVC8 the following line of code works but fails miserable with GCC 3.4.2 (MinGW). Modified: trunk/yake/src/ent/object.cpp =================================================================== --- trunk/yake/src/ent/object.cpp 2007-07-26 17:51:59 UTC (rev 1773) +++ trunk/yake/src/ent/object.cpp 2007-07-26 17:57:16 UTC (rev 1774) @@ -32,6 +32,10 @@ IMPL_OBJECT(Object) + Object::Object() : propertyAcess_(properties_) + { + properties().add("id", property::makePointerProperty<ObjectId>(&id_) ); + } void Object::setId(const ObjectId& id) { YAKE_ASSERT( id != MessageTraits::kNoSource )(MessageTraits::kNoSource)(id); @@ -78,6 +82,33 @@ } listenerConnections_.clear(); } + Object::PropertyAccess& Object::properties() + { + return propertyAcess_; + } + const Object::PropertyAccess& Object::properties() const + { + return propertyAcess_; + } + Object::PropertyAccess::PropertyAccess(NamedProperties& props) : properties_(props) + { + } + PropertyPtr Object::PropertyAccess::get(const PropertyId& id) const + { + return properties_.getPtr(id); + } + bool Object::PropertyAccess::has(const PropertyId& id) const + { + return properties_.has(id); + } + void Object::PropertyAccess::add(const PropertyId& id, property::PropertyBase* prop) + { + this->add( id, PropertyPtr(prop) ); + } + void Object::PropertyAccess::add(const PropertyId& id, PropertyPtr prop) + { + properties_.add( id, prop ); + } } } Modified: trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp =================================================================== --- trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp 2007-07-26 17:51:59 UTC (rev 1773) +++ trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp 2007-07-26 17:57:16 UTC (rev 1774) @@ -87,9 +87,16 @@ //------------------------------------------------------ void LuaVM::execute( const String & rData ) { + YAKE_ASSERT( mLuaState ); + if (!mLuaState) + return; + std::string err; try { - if (mLuaState) - luaL_dostring( mLuaState, rData.c_str() ); + if (luaL_dostring( mLuaState, rData.c_str() )) + { + err = lua_tostring(mLuaState, -1); + lua_pop(mLuaState, 2); + } } catch (luabind::error& e) { @@ -103,12 +110,15 @@ { throw Exception(String("LuaVM: caught exception: ") + e.what()); } + if (!err.empty()) + throw Exception(String("LuaVM: error: ") + err); } //------------------------------------------------------ void LuaVM::execute( ScriptPtr pScript ) { YAKE_ASSERT( pScript ); + std::string err; try { YAKE_ASSERT( pScript->getCreator()->getLanguage() == scripting::IScriptingSystem::L_LUA ); if ( ( pScript->getCreator()->getLanguage() != scripting::IScriptingSystem::L_LUA ) || @@ -122,19 +132,19 @@ if (luaL_loadfile(mLuaState, rFileName.c_str())) { - std::string err(lua_tostring(mLuaState, -1)); + err = lua_tostring(mLuaState, -1); lua_pop(mLuaState, 2); // pop 2: cclosure and error string - throw Exception( err.c_str() ); } - - if (lua_pcall(mLuaState, 0, 0, -2)) + else { - std::string err(lua_tostring(mLuaState, -1)); - lua_pop(mLuaState, 2); - throw Exception( err.c_str() ); + if (lua_pcall(mLuaState, 0, 0, -2)) + { + err = lua_tostring(mLuaState, -1); + lua_pop(mLuaState, 2); + } + else + lua_pop(mLuaState, 1); } - - lua_pop(mLuaState, 1); } catch (luabind::error& e) { @@ -152,6 +162,8 @@ { throw Exception(String("LuaVM: caught exception: ") + e.what()); } + if (!err.empty()) + throw Exception(String("LuaVM: error: ") + err); } //------------------------------------------------------ @@ -168,6 +180,12 @@ VMPtr ScriptingSystemLua::createVM() { VMPtr vm( new LuaVM(this/*this->shared_from_this()*/) ); + + YAKE_FOR_EACH( BinderList::const_iterator, it, mDefaultBinders ) + { + (*it)( vm.get() ); + } + return vm; } Modified: trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.cpp =================================================================== --- trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.cpp 2007-07-26 17:51:59 UTC (rev 1773) +++ trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.cpp 2007-07-26 17:57:16 UTC (rev 1774) @@ -51,8 +51,17 @@ return; } // lookup converter & run (or bail out if no converter found) - any_converter_map::const_iterator it = any_converters().find(ti); + const any_converter_map& convs = any_converters(); + any_converter_map::const_iterator it = convs.begin(); + while (it != convs.end()) + { + if (*(it->first) == *ti) + break; + ++it; + } + //any_converter_map::const_iterator it = convs.find(ti); if (it == any_converters().end()) + //@todo We could just push nil ? throw yake::Exception(std::string("convert_cpp_to_lua() failed to convert '") + ti->name() + "'."); conv_t conv = it->second; conv(L, a); @@ -68,6 +77,8 @@ return boost::any( object_cast<int>(o) ); case LUA_TSTRING: return boost::any( object_cast<std::string>(o) ); //@todo fixme + //case LUA_TFUNCTION: + // return boost::any( o ); default: throw yake::Exception("encountered unsupported type in convert_lua_to_cpp()"); } @@ -84,6 +95,8 @@ return boost::any( object_cast<int>(o) ); case LUA_TSTRING: return boost::any( object_cast<std::string>(o) ); //@todo fixme + //case LUA_TFUNCTION: + // return boost::any( o ); default: throw yake::Exception("encountered unsupported type in convert_lua_to_cpp()"); } @@ -97,6 +110,7 @@ case LUA_TBOOLEAN: case LUA_TNUMBER: case LUA_TSTRING: + //case LUA_TFUNCTION: return 0; default: return -1; @@ -111,6 +125,7 @@ case LUA_TBOOLEAN: case LUA_TNUMBER: case LUA_TSTRING: + //case LUA_TFUNCTION: return 0; default: return -1; Modified: trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.h =================================================================== --- trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.h 2007-07-26 17:51:59 UTC (rev 1773) +++ trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.h 2007-07-26 17:57:16 UTC (rev 1774) @@ -51,7 +51,10 @@ typedef std::map<const std::type_info*,PropertyFromObjectFn> PropertyFromObjectMap; YAKE_LUA_ANY_CONVERTER_API PropertyFromObjectMap& object_property_creators(); - typedef void(*BindSetPropertyFn)(luabind::class_<PropertyBase>&); + typedef luabind::class_<PropertyBase> LuabindClass_PropertyBase; + //typedef luabind::class_<PropertyBase,PropertyPtr> LuabindClass_PropertyBase; + + typedef void(*BindSetPropertyFn)(LuabindClass_PropertyBase&); typedef std::vector<BindSetPropertyFn> BindSetPropertyFnList; YAKE_LUA_ANY_CONVERTER_API BindSetPropertyFnList& setPropertyValue_binders(); @@ -109,7 +112,7 @@ YAKE_ASSERT( prop ); return prop; } - static void yake_bind_setPropertyValue(luabind::class_<yake::property::PropertyBase>& x) + static void yake_bind_setPropertyValue(::yake::property::LuabindClass_PropertyBase& x) { x.def("set",&yake::property::setPropertyValue_Generic<T>); } @@ -121,17 +124,40 @@ //any_converter_map any_converters; +#if YAKE_ENABLE_LUA_PROPERTY == 1 // extension for yake::property: template<class T> - void register_any_converter() + inline void register_property_value_converter() { - any_converters()[&typeid(T)] = convert_any<T>::convert; -#if YAKE_ENABLE_LUA_PROPERTY == 1 // extension for yake::property: yake::property::any_property_creators()[&typeid(T)] = convert_any<T>::yake_createValuePropertyFromAny; yake::property::object_property_creators()[&typeid(T)] = convert_any<T>::yake_createValuePropertyFromObject; yake::property::setPropertyValue_binders().push_back( convert_any<T>::yake_bind_setPropertyValue ); + } #endif + + template<class T> + inline void register_any_converter() + { + any_converters()[&typeid(T)] = convert_any<T>::convert; +#if YAKE_ENABLE_LUA_PROPERTY == 1 // extension for yake::property: + register_property_value_converter<T>(); +#endif } + // NB The specialization for luabind::object is required as for + // this type we do not store a creator in object_property_creators(). + // This creator is to be used as a last resort only. If it is stored + // with all the other creators it may get called before a better option + // can be called. + template<> + inline void register_any_converter<luabind::object>() + { + any_converters()[&typeid(luabind::object)] = convert_any<luabind::object>::convert; +#if YAKE_ENABLE_LUA_PROPERTY == 1 // extension for yake::property: + yake::property::any_property_creators()[&typeid(luabind::object)] = convert_any<luabind::object>::yake_createValuePropertyFromAny; + yake::property::setPropertyValue_binders().push_back( convert_any<luabind::object>::yake_bind_setPropertyValue ); +#endif + } + namespace luabind { namespace converters Added: trunk/yake/yake/bindings.lua/detail/property.lua.h =================================================================== --- trunk/yake/yake/bindings.lua/detail/property.lua.h (rev 0) +++ trunk/yake/yake/bindings.lua/detail/property.lua.h 2007-07-26 17:57:16 UTC (rev 1774) @@ -0,0 +1,52 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#ifndef YAKE_LUA_BINDINGS_PROPERTYLUA_H +#define YAKE_LUA_BINDINGS_PROPERTYLUA_H + +#include <yake/config.h> + +#if YAKE_ENABLE_LUA_PROPERTY == 1 +#include <yake/bindings.lua/bindings.lua.h> // Don't forget to include this for proper dllexport! +#include <yake/base/yake.h> +#include <yake/property/property.h> +#include <boost/any.hpp> + +namespace yake { +namespace property { + typedef PropertyContainer<String> NamedPropertyContainer; + PropertyPtr createPropertyFromAny(const boost::any& o); + PropertyPtr createProperty(luabind::object o); + PropertyBase* createAndAddProperty(NamedPropertyContainer& ctr, const char* name, luabind::object o); + PropertyBase* createAndAddPropertyFromAny(NamedPropertyContainer& ctr, const char* name, const boost::any& o); + PropertyBase* getProperty(NamedPropertyContainer& ctr, const char* name); + bool setPropertyValue(PropertyBase& prop, const boost::any& value); +} // namespace property +} // namespace yake + +#endif // YAKE_ENABLE_LUA_PROPERTY + +#endif Modified: trunk/yake/yake/ent/component.h =================================================================== --- trunk/yake/yake/ent/component.h 2007-07-26 17:51:59 UTC (rev 1773) +++ trunk/yake/yake/ent/component.h 2007-07-26 17:57:16 UTC (rev 1774) @@ -28,7 +28,8 @@ #define YAKE_ENT_OBJECT_COMPONENT_H #include "yake/ent/prerequisites.h" -#include "yake/prop/yakeProperty.h" +#include "yake/prop/prop_def.h" +#include "yake/prop/rtti_class.h" namespace yake { namespace ent { @@ -48,7 +49,7 @@ @note If only property storage is needed this class can be used in its current form. @note Derived classes have to use the DECL_CO() and IMPL_CO_1() macros. */ - struct YAKE_ENT_API Component : public PropHolder<Component> + struct YAKE_ENT_API Component : public boost::noncopyable { virtual ~Component() {} Modified: trunk/yake/yake/ent/entity.h =================================================================== --- trunk/yake/yake/ent/entity.h 2007-07-26 17:51:59 UTC (rev 1773) +++ trunk/yake/yake/ent/entity.h 2007-07-26 17:57:16 UTC (rev 1774) @@ -28,6 +28,7 @@ #define YAKE_ENT_ENTITY_H #include "yake/ent/prerequisites.h" +#include "yake/property/property.h" #include "yake/ent/object.h" #include "yake/model/model.h" //@todo reduce dependency ... @@ -36,11 +37,12 @@ typedef model::ModelPtr ModelPtr; /** Represents complex objects with components, unique ids, properties, state machines, scripting machines. + @note properties: model (ModelPtr) */ struct YAKE_ENT_API Entity : public Object { DECL_OBJECT(Entity,"Entity") - Entity() {} + Entity(); virtual ~Entity() {} typedef object_fsm::state_type fsm_state_type; @@ -66,30 +68,11 @@ scripting::VMPtr getFsmVM() const; + // Model / components + void setModel(ModelPtr); ModelPtr getModel() const; -#if 0 //@todo fixme replace this with a simple contained Model (which is component based). - //@group name Component management - //@{ - /** Adds a component with the given tag. */ - void addComponent(const CoTag&, Component*); - - /** Removes the component with the given pointer. */ - Component* removeComponent(const Component*); - - /** Removes a component by its tag. - Returns the pointer to the component object on successful removal, otherwise 0. - */ - Component* removeComponent(const CoTag&); - - /** Returns the pointer to the component object for the given tag, or 0 if no - component has been registered with this tag. */ - Component* getComponent(const CoTag&) const; - - //@} -#endif - // signals typedef boost::signal<void(const String&,scripting::VMPtr)> VmInitializedSignal; boost::signals::connection subscribeToVmInitialized(const VmInitializedSignal::slot_type&); Modified: trunk/yake/yake/ent/object.h =================================================================== --- trunk/yake/yake/ent/object.h 2007-07-26 17:51:59 UTC (rev 1773) +++ trunk/yake/yake/ent/object.h 2007-07-26 17:57:16 UTC (rev 1774) @@ -31,8 +31,14 @@ #include "yake/ent/object_listener.h" #include "yake/ent/vm_holder.h" +#include "yake/prop/prop_def.h" +#include "yake/prop/rtti_class.h" + +struct lua_State; + namespace yake { namespace ent { + struct LuaBinder; #define DECL_OBJECT(CLASS,DESC) \ DECL_CLASS_RTTI(CLASS,DESC) \ @@ -54,11 +60,14 @@ } /** Base class for complex objects with unique ids, properties and default events. + @note properties: id (ObjectId) */ - struct YAKE_ENT_API Object : public yake::PropHolder<Object>, public ObjectListenerManager + struct YAKE_ENT_API Object : public ObjectListenerManager { + friend struct LuaBinder; + DECL_OBJECT(Object,"Object") - Object() {} + Object(); virtual ~Object() {} // id operations @@ -83,6 +92,29 @@ void processMessage(const int&); void registerMessageListeners(detail::message_router_type& msgRouter); + + // Properties + public: + struct YAKE_ENT_API PropertyAccess : public noncopyable + { + friend struct LuaBinder; + friend struct Object; + private: + PropertyAccess(NamedProperties&); + NamedProperties& properties_; + public: + PropertyPtr get(const PropertyId&) const; + bool has(const PropertyId&) const; + void add(const PropertyId&, property::PropertyBase*); // <- may throw on error! + void add(const PropertyId&, PropertyPtr); // <- may throw on error! + size_t size() const + { return properties_.size(); } + }; + PropertyAccess& properties(); + const PropertyAccess& properties() const; + + NamedProperties* __properties() + { return &properties_; } protected: virtual void onInit() {} virtual void onTick() {} @@ -90,6 +122,8 @@ ObjectId id_; typedef std::deque<detail::ListenerConnection> listenerconnetion_list; listenerconnetion_list listenerConnections_; + NamedProperties properties_; + PropertyAccess propertyAcess_; }; } // namespace ent Modified: trunk/yake/yake/ent/prerequisites.h =================================================================== --- trunk/yake/yake/ent/prerequisites.h 2007-07-26 17:51:59 UTC (rev 1773) +++ trunk/yake/yake/ent/prerequisites.h 2007-07-26 17:57:16 UTC (rev 1774) @@ -27,7 +27,7 @@ #ifndef YAKE_OBJECT_PREREQUISITES_H #define YAKE_OBJECT_PREREQUISITES_H -#include "yake/prop/yakeProperty.h" +#include "yake/property/property.h" #include "yake/statemachine/fsm_core.h" #include "yake/base/yakeTaggedListenerManager.h" #include "yake/base/templates/yakeVector.h" @@ -51,6 +51,7 @@ typedef object::ObjectId<object::default_objectid_traits> ObjectId; typedef ObjectId::ClassId ClassId; + typedef ObjectId::SerialNo ObjectSerialNo; } // namespace ent } // namespace yake @@ -95,6 +96,10 @@ //static const MessageSource kAnySource = MessageTraits::kAnySource; //static const MessageTarget kBroadcastTarget = MessageTraits::kBroadcastTarget; + typedef property::PropertyPtr PropertyPtr; + typedef String PropertyId; + typedef property::PropertyContainer<PropertyId> NamedProperties; + } // namespace ent } // namespace yake Modified: trunk/yake/yake/plugins/scriptingLua/ScriptingSystemLua.h =================================================================== --- trunk/yake/yake/plugins/scriptingLua/ScriptingSystemLua.h 2007-07-26 17:51:59 UTC (rev 1773) +++ trunk/yake/yake/plugins/scriptingLua/ScriptingSystemLua.h 2007-07-26 17:57:16 UTC (rev 1774) @@ -75,9 +75,14 @@ */ virtual ScriptPtr createScriptFromFile( const String & rFile ); + virtual void addDefaultBinder(BinderFn fn) + { if (fn) mDefaultBinders.push_back(fn); } protected: // not for pulic use: using boost::enable_shared_from_this<ScriptingSystemLua>::shared_from_this; + private: + typedef std::deque<BinderFn> BinderList; + BinderList mDefaultBinders; }; //----------------------------------------------------- Modified: trunk/yake/yake/property/accessors.h =================================================================== --- trunk/yake/yake/property/accessors.h 2007-07-26 17:51:59 UTC (rev 1773) +++ trunk/yake/yake/property/accessors.h 2007-07-26 17:57:16 UTC (rev 1774) @@ -71,12 +71,12 @@ return new ValueHolder<T>(defaultValue); } - template<typename T> + template<typename T, typename PtrT = T*> class PointerAccessor : public AccessorBase<T> { public: - typedef T* value_ptr; - PointerAccessor(value_ptr px) : px_(px) + typedef PtrT value_ptr; + PointerAccessor(PtrT px) : px_(px) { assert( px_ ); } @@ -91,7 +91,7 @@ return *px_; } private: - value_ptr px_; + PtrT px_; }; template<typename T> inline PointerAccessor<T>* makePointerAccessor(T* px) Modified: trunk/yake/yake/property/property.h =================================================================== --- trunk/yake/yake/property/property.h 2007-07-26 17:51:59 UTC (rev 1773) +++ trunk/yake/yake/property/property.h 2007-07-26 17:57:16 UTC (rev 1774) @@ -41,7 +41,7 @@ template<typename T> inline Property<T>* makePointerProperty(T* px) { - return new Property<T>(makePointerAccessor(px)); + return new Property<T>(makePointerAccessor<T>(px)); } template<typename T, typename ArgT> inline Property<T>* makeValueProperty(const ArgT& defaultValue = ArgT()) Modified: trunk/yake/yake/property/property_container.h =================================================================== --- trunk/yake/yake/property/property_container.h 2007-07-26 17:51:59 UTC (rev 1773) +++ trunk/yake/yake/property/property_container.h 2007-07-26 17:57:16 UTC (rev 1774) @@ -64,6 +64,12 @@ template<typename Kt, template <typename> class ErrorPolicy = DefaultErrorPolicy> struct PropertyContainer : public boost::noncopyable, public ErrorPolicy<Kt>//, public OperatorPolicy<PropertyContainer<Kt,ErrorPolicy> > { + PropertyContainer() + { + } + ~PropertyContainer() + { + } typedef ErrorPolicy<Kt> error_policy_t; typedef Kt key_type; void add(const key_type& id, PropertyBase* prop); @@ -72,16 +78,29 @@ PropertyBase& get(const key_type& id); PropertyPtr getPtr(const key_type& id) const; // <= doesn't throw. bool has(const key_type& id) const; + size_t size() const + { return properties_.size(); } + // private: typedef std::map<key_type,PropertyPtr> PropertyMap; public: - typedef typename PropertyMap::const_iterator const_property_iterator; - const_property_iterator begin() const + typedef typename PropertyMap::const_iterator const_iterator; + const_iterator begin() const { return properties_.begin(); } - const_property_iterator end() const + const_iterator end() const { return properties_.end(); } + // Private interface used in Lua bindings: + /* + const PropertyMap& __getInternalMap() const + { return properties_; } + typedef typename PropertyMap::iterator iterator; + iterator begin() + { return properties_.begin(); } + iterator end() + { return properties_.end(); } + */ private: PropertyMap properties_; }; Modified: trunk/yake/yake/scripting/yakeScriptingSystem.h =================================================================== --- trunk/yake/yake/scripting/yakeScriptingSystem.h 2007-07-26 17:51:59 UTC (rev 1773) +++ trunk/yake/yake/scripting/yakeScriptingSystem.h 2007-07-26 17:57:16 UTC (rev 1774) @@ -34,6 +34,7 @@ #include <yake/base/templates/yakePointer.h> #include <yake/base/templates/yakeManager.h> #include <yake/base/templates/yakeRegistry.h> +#include <yake/base/templates/yakeFunction.h> #if defined( YAKE_SCRIPTING_EXPORTS ) # define YAKE_SCRIPTING_API YAKE_EXPORT_API @@ -174,6 +175,12 @@ \see IVM */ virtual ScriptPtr createScriptFromFile( const String & file ) = 0; + + /** Add a default binding function. Will applied to all + newly created VMs. + */ + typedef boost::function<void(IVM*)> BinderFn; + virtual void addDefaultBinder(BinderFn) = 0; }; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-07-27 16:09:12
|
Revision: 1775 http://yake.svn.sourceforge.net/yake/?rev=1775&view=rev Author: psyclonist Date: 2007-07-27 09:09:14 -0700 (Fri, 27 Jul 2007) Log Message: ----------- * added events to yake::ent Objects * added Lua bindings for yake::ent::Object events * provided "luabind::object to boost::any" conversion for non-built-in-Lua types (performance overhead) for all registered "boost::any to Lua converts" Modified Paths: -------------- trunk/yake/src/bindings.lua/detail/ent.lua.cpp trunk/yake/src/ent/object.cpp trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.cpp trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.h trunk/yake/yake/ent/object.h Modified: trunk/yake/src/bindings.lua/detail/ent.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/ent.lua.cpp 2007-07-26 17:57:16 UTC (rev 1774) +++ trunk/yake/src/bindings.lua/detail/ent.lua.cpp 2007-07-27 16:09:14 UTC (rev 1775) @@ -60,6 +60,24 @@ typedef luabind::class_<Object::PropertyAccess> LuabindClass_Object_PropertyAccess; //------------------------------------------------------------------------- + static void Object_Event_fire_noparams(Object::Event& evt) + { + evt.fire(); + } + static void Object_Event_fire_1param(Object::Event& evt, const boost::any& a0) + { + evt.fire(a0); + } + static bool Object_Event_connect(Object::Event& evt, luabind::object o) + { + if (!o || (luabind::type(o) != LUA_TFUNCTION)) + { + std::cerr << "WARNING: Object::Event::connect: Parameter is not a function!\n"; + return false; + } + evt.connect( o ); + return true; + } static property::PropertyBase* getPropertyOfObject(Object& o, const PropertyId& id) { return o.properties().get(id).get(); @@ -73,6 +91,11 @@ { return o.get( id ).get(); } + static Object::EventAccess* getObjectEvents(Object& o) + { + Object::EventAccess& x = o.events(); + return &x; + } //------------------------------------------------------------------------- // Helper struct so that we gain access to the private member // "properties_" in Object::PropertyAccess: @@ -157,12 +180,34 @@ module( YAKE_MODEL_MODULE ) [ x_Object_PropertyAccess ]; + module( YAKE_MODEL_MODULE ) + [ + class_<Object::Event::ID>("Object::Event::ID") + .def(tostring(const_self)) + , + class_<Object::Event>("ObjectEvent") + .def( constructor<>() ) + .def( "connect", &Object::Event::connect ) + .def( "connect", &Object_Event_connect ) + //.def( self(Object::Event()) ) // call () operator + .def( "fire", &Object_Event_fire_noparams ) // without params + //.def( "fire", &Object::Event::fire ) // with 1 param + .def( "fire", &Object_Event_fire_1param ) + , + class_<Object::EventAccess>("Object::PropertyAccess") + .def( "has", &Object::EventAccess::has ) + .def( "get", &Object::EventAccess::get ) + .def( "add", &Object::EventAccess::add ) + .def( "create", &Object::EventAccess::createAndAdd ) + ]; + LuabindClass_Object x_Object("Object"); x_Object //.def( constructor<>() ) //.def( "setId", &Object::setId ) //.def( "id", &Object::getId ) .property( "id", &Object::getId, &Object::setId ) + .def( "events", &getObjectEvents ) .def( "property", &getPropertyOfObject ) .def( "properties", &getObjectPoperties ) //.def( "properties", return_reference_to(_1) ) Modified: trunk/yake/src/ent/object.cpp =================================================================== --- trunk/yake/src/ent/object.cpp 2007-07-26 17:57:16 UTC (rev 1774) +++ trunk/yake/src/ent/object.cpp 2007-07-27 16:09:14 UTC (rev 1775) @@ -82,6 +82,14 @@ } listenerConnections_.clear(); } + Object::EventAccess& Object::events() + { + return eventAccess_; + } + const Object::EventAccess& Object::events() const + { + return eventAccess_; + } Object::PropertyAccess& Object::properties() { return propertyAcess_; @@ -90,6 +98,32 @@ { return propertyAcess_; } + Object::Event::Event() + { + } + bool Object::EventAccess::has(const Event::ID& id) const + { + return (events_.find(id) != events_.end()); + } + Object::Event::pointer Object::EventAccess::get(const Event::ID& id) + { + EventMap::iterator it = events_.find(id); + return (it == events_.end()) ? 0 : it->second.get(); + } + void Object::EventAccess::add(const Event::ID& id, Event::pointer evt) + { + YAKE_ASSERT( !has(id) ).debug("duplicate entry - replacing original"); + events_[ id ] = storage(evt); + } + Object::Event::pointer Object::EventAccess::createAndAdd(const Event::ID& id) + { + YAKE_ASSERT( !has(id) ).debug("event with this id already exists"); + if (has(id)) + return 0; + storage evt( new Event() ); + events_[ id ] = evt; + return evt.get(); + } Object::PropertyAccess::PropertyAccess(NamedProperties& props) : properties_(props) { } Modified: trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.cpp =================================================================== --- trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.cpp 2007-07-26 17:57:16 UTC (rev 1774) +++ trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.cpp 2007-07-27 16:09:14 UTC (rev 1775) @@ -31,9 +31,18 @@ static any_converter_map s_converters; return s_converters; } +AnyFromObjectMap& any_from_object_map() +{ + static AnyFromObjectMap s_converters; + return s_converters; +} +TryAnyFromObjectMap& try_any_from_object_map() +{ + static TryAnyFromObjectMap s_converters; + return s_converters; +} - namespace luabind { namespace converters @@ -79,6 +88,20 @@ return boost::any( object_cast<std::string>(o) ); //@todo fixme //case LUA_TFUNCTION: // return boost::any( o ); + case LUA_TUSERDATA: + { + //@todo optimize? + boost::any out; + const AnyFromObjectMap& convs = any_from_object_map(); + for (AnyFromObjectMap::const_iterator it = convs.begin(); + it != convs.end(); ++it) + { + const AnyFromObjectFn& fn = it->second; + if (fn(o,out)) + return out; + } + } + // fall-through: default: throw yake::Exception("encountered unsupported type in convert_lua_to_cpp()"); } @@ -97,6 +120,20 @@ return boost::any( object_cast<std::string>(o) ); //@todo fixme //case LUA_TFUNCTION: // return boost::any( o ); + case LUA_TUSERDATA: + { + //@todo optimize? + boost::any out; + const AnyFromObjectMap& convs = any_from_object_map(); + for (AnyFromObjectMap::const_iterator it = convs.begin(); + it != convs.end(); ++it) + { + const AnyFromObjectFn& fn = it->second; + if (fn(o,out)) + return out; + } + } + // fall-through: default: throw yake::Exception("encountered unsupported type in convert_lua_to_cpp()"); } @@ -112,6 +149,19 @@ case LUA_TSTRING: //case LUA_TFUNCTION: return 0; + case LUA_TUSERDATA: + { + //@todo optimize? + const TryAnyFromObjectMap& convs = try_any_from_object_map(); + for (TryAnyFromObjectMap::const_iterator it = convs.begin(); + it != convs.end(); ++it) + { + const TryAnyFromObjectFn& fn = it->second; + if (fn(o)) + return 0; + } + } + return -1; default: return -1; } @@ -127,6 +177,19 @@ case LUA_TSTRING: //case LUA_TFUNCTION: return 0; + case LUA_TUSERDATA: + { + //@todo optimize? + const TryAnyFromObjectMap& convs = try_any_from_object_map(); + for (TryAnyFromObjectMap::const_iterator it = convs.begin(); + it != convs.end(); ++it) + { + const TryAnyFromObjectFn& fn = it->second; + if (fn(o)) + return 0; + } + } + return -1; default: return -1; } Modified: trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.h =================================================================== --- trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.h 2007-07-26 17:57:16 UTC (rev 1774) +++ trunk/yake/yake/bindings.lua/common/yake.lua.any_converter.h 2007-07-27 16:09:14 UTC (rev 1775) @@ -77,6 +77,14 @@ } // namespace yake #endif + // luabind::object -> boost::any (for everything except native Lua types): + typedef bool(*TryAnyFromObjectFn)(const luabind::object&); + typedef std::map<const std::type_info*,TryAnyFromObjectFn> TryAnyFromObjectMap; + YAKE_LUA_ANY_CONVERTER_API TryAnyFromObjectMap& try_any_from_object_map(); + typedef bool(*AnyFromObjectFn)(const luabind::object&,boost::any&); + typedef std::map<const std::type_info*,AnyFromObjectFn> AnyFromObjectMap; + YAKE_LUA_ANY_CONVERTER_API AnyFromObjectMap& any_from_object_map(); + // boost::any bindings template<class T> struct convert_any @@ -117,6 +125,21 @@ x.def("set",&yake::property::setPropertyValue_Generic<T>); } #endif + static bool yake_anyFromObject(const luabind::object& a, boost::any& out) + { + boost::optional<T> value = luabind::object_cast_nothrow<T>(a); + if (!value) + return false; //@todo report error ? + out = *value; + return true; + } + static bool yake_tryAnyFromObject(const luabind::object& a) + { + boost::optional<T> value = luabind::object_cast_nothrow<T>(a); + if (!value) + return false; //@todo report error ? + return true; + } }; typedef std::map<const std::type_info*, void(*)(lua_State*, const boost::any&)> any_converter_map; @@ -138,6 +161,8 @@ inline void register_any_converter() { any_converters()[&typeid(T)] = convert_any<T>::convert; + any_from_object_map()[&typeid(T)] = convert_any<T>::yake_anyFromObject; + try_any_from_object_map()[&typeid(T)] = convert_any<T>::yake_tryAnyFromObject; #if YAKE_ENABLE_LUA_PROPERTY == 1 // extension for yake::property: register_property_value_converter<T>(); #endif Modified: trunk/yake/yake/ent/object.h =================================================================== --- trunk/yake/yake/ent/object.h 2007-07-26 17:57:16 UTC (rev 1774) +++ trunk/yake/yake/ent/object.h 2007-07-27 16:09:14 UTC (rev 1775) @@ -30,6 +30,7 @@ #include "yake/ent/prerequisites.h" #include "yake/ent/object_listener.h" #include "yake/ent/vm_holder.h" +#include "yake/base/yakeNoncopyable.h" #include "yake/prop/prop_def.h" #include "yake/prop/rtti_class.h" @@ -115,6 +116,44 @@ NamedProperties* __properties() { return &properties_; } + + // Events + struct EventAccess; + struct YAKE_ENT_API Event : public noncopyable + { + friend struct EventAccess; + //private: + Event(); + public: + typedef Event* pointer; + typedef String ID; + typedef boost::any param_type; + private: + typedef boost::signal<void(const param_type&)> EventFireSignal; + public: + typedef SignalConnection connection; + connection connect(const EventFireSignal::slot_type& slot) + { return this->sig_.connect(slot); } + void fire(const param_type& a0 = param_type()) + { this->sig_(a0); } + void operator()(const param_type& a0 = param_type()) + { this->fire(a0); } + private: + EventFireSignal sig_; + }; + struct YAKE_ENT_API EventAccess : public noncopyable + { + Event::pointer get(const Event::ID&); + bool has(const Event::ID&) const; + void add(const Event::ID&, Event::pointer); + Event::pointer createAndAdd(const Event::ID&); + private: + typedef SharedPtr<Event> storage; + typedef std::map<Event::ID,storage> EventMap; + EventMap events_; + }; + EventAccess& events(); + const EventAccess& events() const; protected: virtual void onInit() {} virtual void onTick() {} @@ -124,6 +163,7 @@ listenerconnetion_list listenerConnections_; NamedProperties properties_; PropertyAccess propertyAcess_; + EventAccess eventAccess_; }; } // namespace ent This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-08-10 15:26:28
|
Revision: 1787 http://yake.svn.sourceforge.net/yake/?rev=1787&view=rev Author: psyclonist Date: 2007-08-10 08:26:25 -0700 (Fri, 10 Aug 2007) Log Message: ----------- * [scripting] added bindings for graphics, physics and raf * [scripting] extended bindings for base,math,model * [model] added missing implementations of a few member functions * [physics,*] improved/cleaned-up interfaces Modified Paths: -------------- trunk/yake/scripts/premake/config.lua trunk/yake/scripts/premake/yake.lua trunk/yake/src/bindings.lua/detail/base.lua.cpp trunk/yake/src/bindings.lua/detail/model.lua.cpp trunk/yake/src/loader/yakeXODEParser.cpp trunk/yake/src/model/yakeModel.cpp trunk/yake/src/model/yakeModelComponentContainer.cpp trunk/yake/src/model/yakeModelMovableLink.cpp trunk/yake/src/physics/yakePhysicsCommon.cpp trunk/yake/src/raf/yakeApplicationState.cpp trunk/yake/yake/base/math/yakeRay.h trunk/yake/yake/bindings.lua/bindings.lua.h trunk/yake/yake/model/model_component.h trunk/yake/yake/physics/yakePhysicsCommon.h trunk/yake/yake/physics/yakePhysicsJoint.h trunk/yake/yake/physics/yakePhysicsShape.h trunk/yake/yake/physics/yakePhysicsWorld.h trunk/yake/yake/raf/yakeApplicationState.h Added Paths: ----------- trunk/yake/src/bindings.lua/detail/graphics.lua.cpp trunk/yake/src/bindings.lua/detail/physics.lua.cpp trunk/yake/src/bindings.lua/detail/raf.lua.cpp Modified: trunk/yake/scripts/premake/config.lua =================================================================== --- trunk/yake/scripts/premake/config.lua 2007-08-06 22:21:06 UTC (rev 1786) +++ trunk/yake/scripts/premake/config.lua 2007-08-10 15:26:25 UTC (rev 1787) @@ -49,11 +49,14 @@ -- For example, if you do *not* use yake::model then you can disable -- the compilation of the binding code for this component and thereby -- save compilation time. -ENABLE_LUA_BASE = true -- includes 'base' and 'math' binders -ENABLE_LUA_MODEL = true -- 'model' binder +ENABLE_LUA_BASE = true -- also includes 'math' binders +ENABLE_LUA_MODEL = true ENABLE_LUA_TASK = true -- 'task' binder (+executor) -ENABLE_LUA_PROPERTY = true -- 'property' binder +ENABLE_LUA_PROPERTY = true -- 'property' binder (with specialization for string based indexing) ENABLE_LUA_ENT = true -- 'ent' binder (requires BASE, MODEL and PROPERTY binders!) +ENABLE_LUA_GRAPHICS = true +ENABLE_LUA_PHYSICS = true +ENABLE_LUA_RAF = true -------------------------------------- -- Samples Modified: trunk/yake/scripts/premake/yake.lua =================================================================== --- trunk/yake/scripts/premake/yake.lua 2007-08-06 22:21:06 UTC (rev 1786) +++ trunk/yake/scripts/premake/yake.lua 2007-08-10 15:26:25 UTC (rev 1787) @@ -73,6 +73,9 @@ f:write("#define YAKE_ENABLE_LUA_TASK " .. bool_to_int(ENABLE_LUA_TASK) .. "\n") f:write("#define YAKE_ENABLE_LUA_ENT " .. bool_to_int(ENABLE_LUA_ENT) .. "\n") f:write("#define YAKE_ENABLE_LUA_PROPERTY " .. bool_to_int(ENABLE_LUA_PROPERTY) .. "\n") + f:write("#define YAKE_ENABLE_LUA_GRAPHICS " .. bool_to_int(ENABLE_LUA_GRAPHICS) .. "\n") + f:write("#define YAKE_ENABLE_LUA_PHYSICS " .. bool_to_int(ENABLE_LUA_PHYSICS) .. "\n") + f:write("#define YAKE_ENABLE_LUA_RAF " .. bool_to_int(ENABLE_LUA_RAF) .. "\n") f:write("\n") f:write("#endif\n") io.close(f) Modified: trunk/yake/src/bindings.lua/detail/base.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/base.lua.cpp 2007-08-06 22:21:06 UTC (rev 1786) +++ trunk/yake/src/bindings.lua/detail/base.lua.cpp 2007-08-10 15:26:25 UTC (rev 1787) @@ -37,8 +37,18 @@ #include <yake/bindings.lua/common/yake.lua.shared_ptr.h> #include <yake/bindings.lua/common/yake.lua.any_converter.h> +#include <luabind/operator.hpp> + namespace yake { namespace math { + Vector3 operator * (const Vector3& lhs, const Quaternion& rhs) + { + return rhs * lhs; + } + Vector3 operator * (const Vector3& lhs, const Matrix3& rhs) + { + return rhs * lhs; + } //------------------------------------------------------------------------- namespace { struct AnyConverterIniter @@ -89,27 +99,34 @@ value( "AU_RADIAN", 1 ) ] .def( constructor< unsigned int >() ) - //,def( "IAbs", &yake::math::Math::IAbs ) + //,def( "IAbs", &Math::IAbs ) ]; // Vector3 module( YAKE_MATH_MODULE ) [ class_< Vector3 >( "Vector3" ) - .def_readwrite( "x", &yake::math::Vector3::x ) - .def_readwrite( "y", &yake::math::Vector3::y ) - .def_readwrite( "z", &yake::math::Vector3::z ) + .def_readwrite( "x", &Vector3::x ) + .def_readwrite( "y", &Vector3::y ) + .def_readwrite( "z", &Vector3::z ) .def( constructor<>() ) .def( constructor< real, real, real >() ) .def( constructor< const real* const >() ) .def( constructor< Vector3 const& >() ) - .def( "length", &yake::math::Vector3::length ) - .def( "normalise", &yake::math::Vector3::normalise ) - .def( "crossProduct", &yake::math::Vector3::crossProduct ) - .def( "dotProduct", &yake::math::Vector3::dotProduct ) - .def( "reflect", &yake::math::Vector3::reflect ) - .def( "perpendicular", &yake::math::Vector3::perpendicular ) - .def( "getRotationTo", &yake::math::Vector3::getRotationTo ) + .def( "length", &Vector3::length ) + .def( "normalise", &Vector3::normalise ) + .def( "crossProduct", &Vector3::crossProduct ) + .def( "dotProduct", &Vector3::dotProduct ) + .def( "reflect", &Vector3::reflect ) + .def( "perpendicular", &Vector3::perpendicular ) + .def( "getRotationTo", &Vector3::getRotationTo ) + .def(const_self + other<Vector3>()) + .def(const_self - other<Vector3>()) + .def(const_self == other<Vector3>()) + .def(const_self / real()) + .def(const_self * other<real>()) + .def(const_self * Quaternion()) + .def(const_self * Matrix3()) ]; // Vector4 @@ -128,21 +145,35 @@ class_< Matrix3 >( "Matrix3" ) .def( constructor<>() ) .def( constructor< Matrix3 const& >() ) - .def( "getColumn", &yake::math::Matrix3::GetColumn ) + .def( "getColumn", &Matrix3::GetColumn ) + .def(const_self * other<Matrix3>()) ]; // Quaternion module( YAKE_MATH_MODULE ) [ class_< Quaternion >( "Quaternion" ) - .def_readwrite( "x", &yake::math::Quaternion::x ) - .def_readwrite( "y", &yake::math::Quaternion::y ) - .def_readwrite( "z", &yake::math::Quaternion::z ) - .def_readwrite( "w", &yake::math::Quaternion::w ) + .def_readwrite( "x", &Quaternion::x ) + .def_readwrite( "y", &Quaternion::y ) + .def_readwrite( "z", &Quaternion::z ) + .def_readwrite( "w", &Quaternion::w ) .def( constructor< real, real, real, real >() ) .def( constructor< Quaternion const& >() ) + .def("inverse", &Quaternion::Inverse) + .def(const_self * other<Quaternion>()) ]; + // Ray + module( YAKE_MATH_MODULE ) + [ + class_< Ray >( "Ray" ) + .def( constructor<>() ) + .def( constructor<const Vector3&, const Vector3&>() ) + .property( "origin", &Ray::getOrigin, &Ray::setOrigin ) + .property( "direction", &Ray::getDirection, &Ray::setDirection ) + .def("getPoint", &Ray::getPoint) + ]; + // RandomNumberGenerator typedef RandomNumberGenerator rng_type; module( YAKE_MATH_MODULE ) @@ -195,6 +226,10 @@ .def( "getPosition", &Movable::getPosition ) .def( "getOrientation", &Movable::getOrientation ) .def( "translate", &Movable::translate ) + .property("position", &Movable::getPosition, &Movable::setPosition) + .property("derived_position", &Movable::getDerivedPosition) + .property("orientation", &Movable::getOrientation, &Movable::setOrientation) + .property("derived_orientation", &Movable::getDerivedOrientation) ]; module( YAKE_BASE_MODULE ) Added: trunk/yake/src/bindings.lua/detail/graphics.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/graphics.lua.cpp (rev 0) +++ trunk/yake/src/bindings.lua/detail/graphics.lua.cpp 2007-08-10 15:26:25 UTC (rev 1787) @@ -0,0 +1,170 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#include <yake/config.h> +#if YAKE_ENABLE_LUA_GRAPHICS == 1 + +// See task.lua.cpp +#include <yake/bindings.lua/common/yake.lua.shared_ptr.h> + +#include <yake/bindings.lua/bindings.lua.h> // Don't forget to include this for proper dllexport! + +#include <yake/base/templates/yakeSmartAssert.h> +#include <yake/base/yake.h> +#include <yake/graphics/yakeGraphics.h> + +#include <yake/bindings.lua/detail/private.h> +#include <yake/bindings.lua/common/yake.lua.any_converter.h> + +#include <luabind/discard_result_policy.hpp> +#include <luabind/iterator_policy.hpp> +#include <luabind/operator.hpp> + +namespace yake { +namespace graphics { + ISceneNode* ISceneNode_getChildByName_NameOnly(ISceneNode* n, const String& name) + { + return (n ? n->getChildByName(name,false) : 0); + } + ISceneNode* IWorld_createSceneNode_NoName(IWorld* w) + { + return (w ? w->createSceneNode() : 0); + } + + void bind( lua_State* L ) + { + YAKE_ASSERT( L ); + if (!L) + return; + + using namespace luabind; + +#define YAKE_GRAPHICS_MODULE L, "yake" + + module( YAKE_GRAPHICS_MODULE ) + [ + namespace_("graphics") + [ + class_<ISceneNode,Movable>("SceneNode") + .enum_("TransformSpace") + [ + value("TS_LOCAL",ISceneNode::TS_LOCAL), + value("TS_PARENT",ISceneNode::TS_PARENT), + value("TS_WORLD",ISceneNode::TS_WORLD) + ] + .property("name", &ISceneNode::getName, &ISceneNode::setName) + .property("scale", &ISceneNode::getScale, &ISceneNode::setScale) + .property("parent", &ISceneNode::getParent) + .def("setInheritScale", &ISceneNode::setInheritScale) + .def("addChild", &ISceneNode::addChildNode) + .def("createChildNode", &ISceneNode::createChildNode) + .def("attach", &ISceneNode::attachEntity) + .def("attach", &ISceneNode::attachCamera) + .def("attach", &ISceneNode::attachLight) + .def("attach", &ISceneNode::attachParticleSystem) + .def("detach", (void(ISceneNode::*)(IEntity*))&ISceneNode::detach) + .def("detach", (void(ISceneNode::*)(ILight*))&ISceneNode::detach) + .def("detach", (void(ISceneNode::*)(ICamera*))&ISceneNode::detach) + .def("detach", (void(ISceneNode::*)(IParticleSystem*))&ISceneNode::detach) + .def("getChildByName", &ISceneNode::getChildByName) + .def("getChildByName", &ISceneNode_getChildByName_NameOnly) + .def("translate", &ISceneNode::translate) + .def("rotate", &ISceneNode::rotate) + , + class_<IEntity>("Entity") + .property("name", &IEntity::getName) + .def("setVisible", &IEntity::setVisible) + .def("setMaterial", &IEntity::setMaterial) + .def("setSubEntityMaterial", &IEntity::setSubEntityMaterial) + .def("setCastsShadow", &IEntity::setCastsShadow) + , + class_<ILight>("Light") + .enum_("LightType") + [ + value("LT_POINT",ILight::LT_POINT), + value("LT_DIRECTIONAL",ILight::LT_DIRECTIONAL), + value("LT_SPOT",ILight::LT_SPOT) + ] + .property("name", &ILight::getName) + .property("type", &ILight::getType, &ILight::setType) + .property("direction", &ILight::getDirection, &ILight::setDirection) + //@todo property "enabled" + .def("setEnabled", &ILight::setEnabled) + .def("setCastsShadows", &ILight::setCastsShadows) + .def("setDiffuseColour", &ILight::setDiffuseColour) + .def("setSpecularColour", &ILight::setSpecularColour) + .def("setAttenuation", &ILight::setAttenuation) + .property("attenuationRange", &ILight::getAttenuationRange) + .property("attenuationConstFactor", &ILight::getAttenuationConstFactor) + .property("attenuationLinearFactor", &ILight::getAttenuationLinearFactor) + .property("attenuationQuadraticFactor", &ILight::getAttenuationQuadraticFactor) + .def("setSpotlightRange", &ILight::setSpotlightRange) + .property("spotInnerAngle", &ILight::getSpotlightInnerAngle) + .property("spotOuterAngle", &ILight::getSpotlightOuterAngle) + .property("spotFalloff", &ILight::getSpotlightFalloff) + , + class_<IParticleSystem>("ParticleSystem") + //@todo + , + class_<ICamera,Movable>("Camera") + //@todo + , + class_<IViewport>("Viewport") + //@todo + , + //@todo ISkeleton etc pp + // + class_<IWorld>("World") + .def("createSceneNode", &IWorld::createSceneNode) + .def("createSceneNode", &IWorld_createSceneNode_NoName) + .def("createEntity", &IWorld::createEntity) + .def("createParticleSystem", &IWorld::createParticleSystem) + .def("createCamera", &IWorld::createCamera) + .def("createViewport", &IWorld::createViewport) + .def("load", &IWorld::load) + .def("setShadowsEnabled", &IWorld::setShadowsEnabled) + .def("setAmbientLight", &IWorld::setAmbientLight) + .def("pickEntity", &IWorld::pickEntity) + ] + ]; + } + + YAKE_WRAP_BINDER(graphics,::yake::graphics::bind); + +} // namespace graphics + void bind_graphics(lua_State* L) + { + YAKE_ASSERT(L); + graphics::bind(L); + } + void bind_graphics(scripting::IVM* vm) + { + scripting::LuaVM* luavm = static_cast<scripting::LuaVM*>(vm); + YAKE_ASSERT( luavm ); + bind_graphics(luavm->getLuaState()); + } +} // namespace yake +#endif // YAKE_ENABLE_LUA_MODEL Modified: trunk/yake/src/bindings.lua/detail/model.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/model.lua.cpp 2007-08-06 22:21:06 UTC (rev 1786) +++ trunk/yake/src/bindings.lua/detail/model.lua.cpp 2007-08-10 15:26:25 UTC (rev 1787) @@ -36,8 +36,30 @@ #include <yake/bindings.lua/common/yake.lua.any_converter.h> #include <yake/bindings.lua/detail/private.h> +#include <luabind/discard_result_policy.hpp> +#include <luabind/iterator_policy.hpp> + namespace yake { namespace model { + Model* ModelManager_createModel(ModelManager* mgr, const String& modelName, const String& def) + { + return (mgr ? mgr->createModel(modelName,def).get() : 0); + } + Model* ModelManager_createModelFromTemplate(ModelManager* mgr, const String& modelName, const String& tplName) + { + return (mgr ? mgr->createModelFromTemplate(modelName,tplName).get() : 0); + } + bool ModelMovableLink_subscribeToPositionChanged(ModelMovableLink* link, const luabind::object& o) + { + YAKE_ASSERT( luabind::type(o) == LUA_TFUNCTION ); + if (luabind::type(o) != LUA_TFUNCTION) + return false; + if (!link) + return false; + typedef boost::function<void(const Vector3&)> Fn; + link->subscribeToPositionChanged( boost::bind(Fn(o),_1) ); + return true; + } void bind( lua_State* L ) { @@ -52,6 +74,11 @@ module( YAKE_MODEL_MODULE ) [ + class_<ModelComponent::Desc>( "ModelComponentDesc" ) + .def_readwrite("name", &ModelComponent::Desc::name) + .def_readwrite("type", &ModelComponent::Desc::type) + .def_readwrite("params", &ModelComponent::Desc::params, return_stl_iterator) + , class_<ModelComponent>( "ModelComponent" ) //.def( constructor<>() ) ]; @@ -86,6 +113,33 @@ //.def( "translate", &Physical::translate ) .def( "updateAffectors", &Physical::updateAffectors ) ]; + + module( YAKE_MODEL_MODULE ) + [ + class_<ModelLink>( "ModelLink" ) + , + class_<ModelMovableLink,ModelLink>( "ModelMovableLink" ) + .def( "subscribeToPositionChanged", &ModelMovableLink_subscribeToPositionChanged) + , + class_<Model>( "Model" ) + .def( constructor<>() ) + .property( "name", &Model::getName, &Model::setName ) + .def( "getName", &Model::getName ) + .def( "setName", &Model::setName ) + .def( "getComponentByTag", &Model::getComponentByTag) + //@todo .def( "getComponentByIndex", &Model::getComponentByIndex) + .def( "removeComponent", &Model::removeComponent, discard_result) + .def( "numComponents", &Model::numComponents) + .def( "createLink", &Model::createLink) + .def( "createDirectLink", &Model::createDirectLink) + .def( "createWorldSpaceLink", &Model::createWorldSpaceLink) + , + class_<ModelManager>( "ModelManager" ) + .def("clear", &ModelManager::clear) + .def("loadTemplates", &ModelManager::loadTemplatesFromDotModel) + .def("createModel", &ModelManager_createModel) + .def("createModelFromTemplate", &ModelManager_createModelFromTemplate) + ]; } YAKE_WRAP_BINDER(model,::yake::model::bind); Added: trunk/yake/src/bindings.lua/detail/physics.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/physics.lua.cpp (rev 0) +++ trunk/yake/src/bindings.lua/detail/physics.lua.cpp 2007-08-10 15:26:25 UTC (rev 1787) @@ -0,0 +1,286 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#include <yake/config.h> +#if YAKE_ENABLE_LUA_PHYSICS == 1 + +#pragma warning(disable:4267) // VC8-32Bit: conversion from 'size_t' to 'unsigned int', possible loss of data + +// See task.lua.cpp +#include <yake/bindings.lua/common/yake.lua.shared_ptr.h> + +#include <yake/bindings.lua/bindings.lua.h> // Don't forget to include this for proper dllexport! + +#include <yake/base/templates/yakeSmartAssert.h> +#include <yake/base/yake.h> +#include <yake/physics/yakePhysics.h> + +#include <yake/bindings.lua/detail/private.h> +#include <yake/bindings.lua/common/yake.lua.any_converter.h> + +#include <luabind/discard_result_policy.hpp> +#include <luabind/iterator_policy.hpp> +#include <luabind/operator.hpp> + +namespace yake { +namespace physics { + IShape* IActor_createShape(IActor* actor, const IShape::Desc& desc) + { + return (actor ? actor->createShape(desc) : 0); + } + IAvatar* IWorld_createAvatar(IWorld* world) + { + return (world ? world->createAvatar(IAvatar::Desc()) : 0); + } + + void bind( lua_State* L ) + { + YAKE_ASSERT( L ); + if (!L) + return; + + using namespace luabind; + +#define YAKE_PHYSICS_MODULE L, "yake" + + module( YAKE_PHYSICS_MODULE ) + [ + class_<Force>("Force") + .enum_("ReferenceFrame") + [ + value("LOCAL", RF_LOCAL), + value("GLOBAL", RF_GLOBAL) + ] + .def_readwrite("value", &Force::value_) + .def_readwrite("position", &Force::pos_) + .def_readwrite("duration", &Force::duration_) + .def_readwrite("posref", &Force::posRef_) + .def_readwrite("valref", &Force::valueRef_) + .def(const_self + other<Force>()) + .def(const_self * real()) + .def(const_self == Force()) + .def(constructor<const Vector3&,const ReferenceFrame,const Point3&, const ReferenceFrame,const real>()) + .def(constructor<const Vector3&,const ReferenceFrame,const Point3&, const ReferenceFrame>()) + .def(constructor<const Vector3&,const ReferenceFrame,const real>()) + .def(constructor<const Vector3&,const ReferenceFrame>()) + , + namespace_("physics") + [ + class_<IBody>("Body") + .property("mass", &IBody::getMass) + .def("addForce", &IBody::addForce) + .def("addTorque", &IBody::addTorque) + .def("setMass", (void(IBody::*)(const real))&IBody::setMass) + .def("translateMass", &IBody::translateMass) + .def("setLinearVelocity", &IBody::setLinearVelocity) + .def("getLinearVelocity", &IBody::getLinearVelocity) + .def("setAngularVelocity", &IBody::setAngularVelocity) + .def("getAngularVelocity", &IBody::getAngularVelocity) + , + class_<IShape,Movable>("Shape") + .enum_("ShapeType") + [ + value("ST_PLANE", ST_PLANE), + value("ST_BOX", ST_BOX), + value("ST_SPHERE", ST_SPHERE), + value("ST_CAPSULE", ST_CAPSULE), + value("ST_CYLINDER", ST_CYLINDER), + value("ST_TRIANGLE_MESH", ST_TRIANGLE_MESH), + value("ST_VOXEL_SET", ST_VOXEL_SET), + value("ST_OTHER", ST_OTHER) + ] + .property("type", &IShape::getType) + .property("material", &IShape::getMaterial, &IShape::setMaterial) + .scope + [ + class_<IShape::Desc>("Desc") + .def_readonly("type", &IShape::Desc::type) + .def_readwrite("material", &IShape::Desc::material) + .def_readwrite("position", &IShape::Desc::position) + .def_readwrite("orientation", &IShape::Desc::orientation) + , + class_<IShape::SphereDesc,IShape::Desc>("SphereDesc") + .def(constructor<real>()) + .def(constructor<real,const Vector3&>()) + .def(constructor<real,const Vector3&,const Quaternion&>()) + , + class_<IShape::BoxDesc,IShape::Desc>("BoxDesc") + .def(constructor<const Vector3&>()) + .def(constructor<const Vector3&,const Vector3&>()) + .def(constructor<const Vector3&,const Vector3&,const Quaternion&>()) + , + class_<IShape::PlaneDesc,IShape::Desc>("PlaneDesc") + .def(constructor<const Vector3&,real>()) + .def(constructor<const Vector3&,real,const Vector3&>()) + .def(constructor<const Vector3&,real,const Vector3&,const Quaternion&>()) + , + class_<IShape::CapsuleDesc,IShape::Desc>("CapsuleDesc") + .def(constructor<real,real>()) + .def(constructor<real,real,const Vector3&>()) + .def(constructor<real,real,const Vector3&,const Quaternion&>()) + , + class_<IShape::TriMeshDesc,IShape::Desc>("TriMeshDesc") + .def(constructor<TriangleMeshId>()) + .def(constructor<TriangleMeshId,const Vector3&>()) + .def(constructor<TriangleMeshId,const Vector3&,const Quaternion&>()) + ] + , + class_<IActor,Movable>("Actor") + .enum_("ActorType") + [ + value("ACTOR_STATIC",ACTOR_STATIC), + value("ACTOR_MOVABLE",ACTOR_MOVABLE), + value("ACTOR_DYNAMIC",ACTOR_DYNAMIC) + ] + .property("creator", &IActor::getCreator) + .property("enabled", &IActor::isEnabled, &IActor::setEnabled) + .property("type", &IActor::getType) + .property("body", &IActor::getBodyPtr) + .def("createShape", &IActor_createShape) + .def("destroyShape", &IActor::destroyShape) + //@todo signals CollisionEntered, CollisionExited + , + class_<IAvatar,Movable>("Avatar") + .property("creator", &IActor::getCreator) + .property("speed", &IAvatar::getSpeed, &IAvatar::setSpeed) + .property("acceleration", &IAvatar::getAcceleration, &IAvatar::setAcceleration) + .def("move", &IAvatar::move) // takes normalized vector + .def("jump", &IAvatar::jump) + .def("duck", &IAvatar::duck) + .property("jumping", &IAvatar::isJumping) + .property("ducking", &IAvatar::isDucking) + .def("setGravityDirection", &IAvatar::setGravityDirection) + //@todo signals + , + class_<IJoint>("Joint") + .enum_("JointType") + [ + value("JT_BALL",JT_BALL), + value("JT_HINGE",JT_HINGE), + value("JT_HINGE2",JT_HINGE2), + value("JT_FIXED",JT_FIXED), + value("JT_SLIDER",JT_SLIDER), + value("JT_UNIVERSAL",JT_UNIVERSAL), + value("JT_ANGULAR_MOTOR",JT_ANGULAR_MOTOR), + value("JT_OTHER",JT_OTHER) + ] + .scope + [ + class_<Limit>("JointLimit") + .def(constructor<>()) + .def(constructor<size_t,real,real>()) + .def_readwrite("axis",&Limit::axis) + .def_readwrite("low",&Limit::low) + .def_readwrite("high",&Limit::high) + , + class_<IJoint::DescBase>("JointDesc") + .def_readonly("type", &IJoint::DescBase::type) + .def_readwrite("actor0", &IJoint::DescBase::actor0) + .def_readwrite("actor1", &IJoint::DescBase::actor1) + .def_readwrite("breakable", &IJoint::DescBase::breakable) + .def_readwrite("breakingForce", &IJoint::DescBase::breakingForce) + .def_readwrite("breakingTorque", &IJoint::DescBase::breakingTorque) + // @todo LimitList + , + class_<IJoint::DescFixed,IJoint::DescBase>("DescFixed") + .def(constructor<IActor*,IActor*>()) + , + class_<IJoint::DescHinge,IJoint::DescBase>("DescHinge") + .def(constructor<IActor*,IActor*>()) + .def_readwrite("axis", &IJoint::DescHinge::axis) + .def_readwrite("anchor", &IJoint::DescHinge::anchor) + , + class_<IJoint::DescHinge2,IJoint::DescBase>("DescHinge2") + .def(constructor<IActor*,IActor*>()) + .def_readwrite("axis0", &IJoint::DescHinge2::axis0) + .def_readwrite("axis1", &IJoint::DescHinge2::axis1) + .def_readwrite("anchor", &IJoint::DescHinge2::anchor) + , + class_<IJoint::DescUniversal,IJoint::DescBase>("DescUniversal") + .def(constructor<IActor*,IActor*>()) + .def_readwrite("axis0", &IJoint::DescUniversal::axis0) + .def_readwrite("axis1", &IJoint::DescUniversal::axis1) + .def_readwrite("anchor", &IJoint::DescUniversal::anchor) + , + class_<IJoint::DescBall,IJoint::DescBase>("DescBall") + .def(constructor<IActor*,IActor*>()) + .def_readwrite("anchor", &IJoint::DescBall::anchor) + , + class_<IJoint::DescSlider,IJoint::DescBase>("DescSlider") + .def(constructor<IActor*,IActor*>()) + .def_readwrite("axis", &IJoint::DescSlider::axis) + ] + .property("creator", &IJoint::getCreator) + .property("type", &IJoint::getType) + .property("spring", &IJoint::getSpring, &IJoint::setSpring) + .property("damping", &IJoint::getDamping, &IJoint::setDamping) + .def("setAnchor", &IJoint::setAnchor) + .def("getNumAnchors", &IJoint::getNumAnchors) + .def("setAxis", &IJoint::setAxis) + .def("getNumAxis", &IJoint::getNumAxis) + .def("setMotor", &IJoint::setMotor) + .def("setMotorEnabled", &IJoint::setMotorEnabled) + .def("setLimit", &IJoint::setLimits) + .def("setBreakable", &IJoint::setBreakable) + .def("setBreakableForce", &IJoint::setBreakableForce) + .def("setBreakableTorque", &IJoint::setBreakableTorque) + .def("setConnectedBodiesCollide", &IJoint::setConnectedBodiesCollide) + //@todo signals OnBreaking + , + class_<IWorld>("World") + .property("gravity", &IWorld::getGlobalGravity, &IWorld::setGlobalGravity) + .property("stepsize", &IWorld::getStepSize) + .property("solver", &IWorld::getCurrentSolver) + // + .def("createActor", (IActorPtr(IWorld::*)(const ActorType))&IWorld::createActor) + .def("destroyActor", &IWorld::destroyActor) + .def("createAvatar", &IWorld_createAvatar) + .def("destroyAvatar", &IWorld::destroyAvatar) + .def("createJoint", &IWorld::createJoint) + .def("destroyJoint", &IWorld::destroyJoint) + // createAvatar + // createTriangleMesh + // createMaterial + ] + ]; + } + + YAKE_WRAP_BINDER(physics,::yake::physics::bind); + +} // namespace physics + void bind_physics(lua_State* L) + { + YAKE_ASSERT(L); + physics::bind(L); + } + void bind_physics(scripting::IVM* vm) + { + scripting::LuaVM* luavm = static_cast<scripting::LuaVM*>(vm); + YAKE_ASSERT( luavm ); + bind_physics(luavm->getLuaState()); + } +} // namespace yake +#endif // YAKE_ENABLE_LUA_MODEL Added: trunk/yake/src/bindings.lua/detail/raf.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/raf.lua.cpp (rev 0) +++ trunk/yake/src/bindings.lua/detail/raf.lua.cpp 2007-08-10 15:26:25 UTC (rev 1787) @@ -0,0 +1,118 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#include <yake/config.h> +#if YAKE_ENABLE_LUA_RAF == 1 + +#include <yake/base/yake.h> +#include <yake/raf/yakeRaf.h> + +#include <yake/bindings.lua/bindings.lua.h> // Don't forget to include this for proper dllexport! + +#include <yake/bindings.lua/detail/private.h> +#include <yake/bindings.lua/common/lua.helpers.h> +#include <yake/bindings.lua/common/vminfo.lua.h> +#include <yake/bindings.lua/common/yake.lua.shared_ptr.h> +#include <yake/bindings.lua/common/yake.lua.any_converter.h> + +namespace yake { +namespace raf { + //------------------------------------------------------------------------- + namespace { + struct AnyConverterIniter + { + /* + AnyConverterIniter() + { + register_any_converter<Color>(); + register_any_converter<Vector3>(); + register_any_converter<Quaternion>(); + register_any_converter<Matrix3>(); + } + */ + } g_initer; + } // namespace + input::KeyboardDevice* getAppKeyboard(raf::Application* app) + { + return app ? app->getKeyboard() : 0; + } + graphics::IGraphicsSystem* getAppDefaultGraphics(raf::Application* app) + { + return app ? app->getGraphicsSystem() : 0; + } + physics::IPhysicsSystem* getAppDefaultPhysics(raf::Application* app) + { + return app ? app->getPhysicsSystem() : 0; + } + audio::IAudioSystem* getAppDefaultAudio(raf::Application* app) + { + return app ? app->getAudioSystem(): 0; + } + //------------------------------------------------------------------------- + void bind(lua_State* L) + { + YAKE_ASSERT(L); + if (!L) + return; + // + using namespace luabind; +#define YAKE_RAF_MODULE L, "yake" + + + module( YAKE_RAF_MODULE ) + [ + namespace_("raf") + [ + class_<raf::Application>("Application") + .property("keyboard", &getAppKeyboard) + .property("graphics", &getAppDefaultGraphics) + .property("physics", &getAppDefaultPhysics) + .property("audio", &getAppDefaultAudio) + , + class_<raf::AppMachine>("AppMachine") + .property("currentState", &raf::AppMachine::currentState) + ] + ]; + + } + + YAKE_WRAP_BINDER(raf,::yake::raf::bind); + +} // namespace raf + void bind_raf(lua_State* L) + { + YAKE_ASSERT( L ); + raf::bind(L); + } + void bind_raf(scripting::IVM* vm) + { + scripting::LuaVM* luavm = static_cast<scripting::LuaVM*>(vm); + YAKE_ASSERT( luavm ); + bind_raf(luavm->getLuaState()); + } +} // namespace yake + +#endif // YAKE_ENABLE_LUA_RAF Modified: trunk/yake/src/loader/yakeXODEParser.cpp =================================================================== --- trunk/yake/src/loader/yakeXODEParser.cpp 2007-08-06 22:21:06 UTC (rev 1786) +++ trunk/yake/src/loader/yakeXODEParser.cpp 2007-08-10 15:26:25 UTC (rev 1787) @@ -651,7 +651,7 @@ YAKE_LOG("xode", "XODE: box with sizes: " + strSizeX + ", " + strSizeY + ", " + strSizeZ ); - shapeDesc = new IShape::BoxDesc( math::Vector3( sizeX, sizeY, sizeZ ), "", + shapeDesc = new IShape::BoxDesc( math::Vector3( sizeX, sizeY, sizeZ ), geomTransform.position_, geomTransform.rotation_ ); } else if ( nodeName == "cappedCylinder" ) @@ -668,7 +668,6 @@ shapeDesc = new IShape::CapsuleDesc( length, radius, - "", geomTransform.position_, geomTransform.rotation_ ); } @@ -700,7 +699,6 @@ shapeDesc = new IShape::CapsuleDesc( length, radius, - "", geomTransform.position_, geomTransform.rotation_ ); } @@ -710,7 +708,6 @@ readPlane( *it, a, b, c, d ); shapeDesc = new IShape::PlaneDesc( math::Vector3( a, b, c ), d, - "", geomTransform.position_, geomTransform.rotation_ ); } @@ -740,7 +737,6 @@ shapeDesc = new IShape::SphereDesc( radius, - "", geomTransform.position_, geomTransform.rotation_ ); } Modified: trunk/yake/src/model/yakeModel.cpp =================================================================== --- trunk/yake/src/model/yakeModel.cpp 2007-08-06 22:21:06 UTC (rev 1786) +++ trunk/yake/src/model/yakeModel.cpp 2007-08-10 15:26:25 UTC (rev 1787) @@ -53,6 +53,14 @@ { return components_.getComponentByTag(tag); } + size_t Model::numComponents() const + { + return components_.numComponents(); + } + ModelComponent* Model::removeComponent(ModelComponent* c) + { + return components_.removeComponent(c); + } ModelMovableLink* Model::createLink(yake::Movable* from, yake::Movable* to, const yake::String &linkType) { //SharedPtr<ModelMovableLink> link = create<ModelMovableLink>(linkType); //@todo USE FACTORY! Modified: trunk/yake/src/model/yakeModelComponentContainer.cpp =================================================================== --- trunk/yake/src/model/yakeModelComponentContainer.cpp 2007-08-06 22:21:06 UTC (rev 1786) +++ trunk/yake/src/model/yakeModelComponentContainer.cpp 2007-08-10 15:26:25 UTC (rev 1787) @@ -86,6 +86,23 @@ #endif tag2components_[ tag ] = c; } + ModelComponent* ModelComponentContainer::removeComponent(ModelComponent* c) + { + if (!c) + return 0; + ModelComponentList::iterator it = std::find(components_.begin(),components_.end(),c); + if (it != components_.end()) + components_.erase(it); + YAKE_FOR_EACH( TagModelComponentMap::iterator, it, tag2components_ ) + { + if (it->second == c) + { + tag2components_.erase( it ); + break; + } + } + return c; + } ModelComponent* ModelComponentContainer::getComponentByTag(const ComponentTag& tag) const { TagModelComponentMap::const_iterator it = tag2components_.find(tag); Modified: trunk/yake/src/model/yakeModelMovableLink.cpp =================================================================== --- trunk/yake/src/model/yakeModelMovableLink.cpp 2007-08-06 22:21:06 UTC (rev 1786) +++ trunk/yake/src/model/yakeModelMovableLink.cpp 2007-08-10 15:26:25 UTC (rev 1787) @@ -41,6 +41,10 @@ { return mSource; } + SignalConnection ModelMovableLink::subscribeToPositionChanged(const PositionSignal::slot_type& slot) + { + return mPositionSignal.connect( slot ); + } SignalConnection ModelMovableLink::subscribeToPositionChanged( Movable* pMovable ) { const Vector3 srcPos = getSource()->getPosition(); @@ -56,6 +60,10 @@ return mOrientationSignal.connect( Bind1( &Movable::setOrientation, pMovable ) ); } + SignalConnection ModelMovableLink::subscribeToOrientationChanged(const OrientationSignal::slot_type& slot) + { + return mOrientationSignal.connect( slot ); + } YAKE_REGISTER_CONCRETE(ModelMovableDirectLink) ModelMovableDirectLink::ModelMovableDirectLink() Modified: trunk/yake/src/physics/yakePhysicsCommon.cpp =================================================================== --- trunk/yake/src/physics/yakePhysicsCommon.cpp 2007-08-06 22:21:06 UTC (rev 1786) +++ trunk/yake/src/physics/yakePhysicsCommon.cpp 2007-08-10 15:26:25 UTC (rev 1787) @@ -115,7 +115,7 @@ value_ *= rhs; return *this; } - Force Force::operator * (const real rhs) + Force Force::operator * (const real rhs) const { Force tmp(*this); tmp *= rhs; @@ -137,7 +137,7 @@ } return *this; } - Force Force::operator + (const Force& rhs) + Force Force::operator + (const Force& rhs) const { Force tmp(*this); tmp += rhs; Modified: trunk/yake/src/raf/yakeApplicationState.cpp =================================================================== --- trunk/yake/src/raf/yakeApplicationState.cpp 2007-08-06 22:21:06 UTC (rev 1786) +++ trunk/yake/src/raf/yakeApplicationState.cpp 2007-08-10 15:26:25 UTC (rev 1787) @@ -76,6 +76,10 @@ {} AppMachine::~AppMachine() {} + ApplicationState* AppMachine::currentState() const + { + return machine_.current(); + } void AppMachine::addState(const String& stateId, ApplicationState* state) { YAKE_ASSERT( !stateId.empty() ); Modified: trunk/yake/yake/base/math/yakeRay.h =================================================================== --- trunk/yake/yake/base/math/yakeRay.h 2007-08-06 22:21:06 UTC (rev 1786) +++ trunk/yake/yake/base/math/yakeRay.h 2007-08-10 15:26:25 UTC (rev 1787) @@ -41,6 +41,9 @@ class YAKE_BASE_API Ray { public: + Ray() : mOrigin(0,0,0), mDirection(1,0,0) + { + } Ray( const Vector3 & rOrigin, const Vector3 & rDirection ) : mOrigin( rOrigin ), mDirection( rDirection ) { } Modified: trunk/yake/yake/bindings.lua/bindings.lua.h =================================================================== --- trunk/yake/yake/bindings.lua/bindings.lua.h 2007-08-06 22:21:06 UTC (rev 1786) +++ trunk/yake/yake/bindings.lua/bindings.lua.h 2007-08-10 15:26:25 UTC (rev 1787) @@ -56,6 +56,18 @@ YAKE_BINDINGS_LUA_API void bind_property(lua_State*); YAKE_BINDINGS_LUA_API void bind_property(scripting::IVM*); #endif +#if YAKE_ENABLE_LUA_PHYSICS == 1 + YAKE_BINDINGS_LUA_API void bind_physics(lua_State*); + YAKE_BINDINGS_LUA_API void bind_physics(scripting::IVM*); +#endif +#if YAKE_ENABLE_LUA_GRAPHICS == 1 + YAKE_BINDINGS_LUA_API void bind_graphics(lua_State*); + YAKE_BINDINGS_LUA_API void bind_graphics(scripting::IVM*); +#endif +#if YAKE_ENABLE_LUA_RAF == 1 + YAKE_BINDINGS_LUA_API void bind_raf(lua_State*); + YAKE_BINDINGS_LUA_API void bind_raf(scripting::IVM*); +#endif } // namespace yake #endif Modified: trunk/yake/yake/model/model_component.h =================================================================== --- trunk/yake/yake/model/model_component.h 2007-08-06 22:21:06 UTC (rev 1786) +++ trunk/yake/yake/model/model_component.h 2007-08-10 15:26:25 UTC (rev 1787) @@ -159,6 +159,7 @@ //@{ void addComponent(ModelComponent*); void addComponent(ModelComponent*, const ComponentTag&); + ModelComponent* removeComponent(ModelComponent*); ModelComponent* getComponentByTag(const ComponentTag&) const; ModelComponent* getComponentByIndex(const size_t) const; size_t numComponents() const; Modified: trunk/yake/yake/physics/yakePhysicsCommon.h =================================================================== --- trunk/yake/yake/physics/yakePhysicsCommon.h 2007-08-06 22:21:06 UTC (rev 1786) +++ trunk/yake/yake/physics/yakePhysicsCommon.h 2007-08-10 15:26:25 UTC (rev 1787) @@ -58,13 +58,13 @@ bool operator != (const Force&) const; Force& operator *= (const real); - Force operator * (const real); + Force operator * (const real) const; /** @note The frames of reference for the value and position have to be the same! */ Force& operator += (const Force&); /** @note The frames of reference for the value and position have to be the same! */ - Force operator + (const Force&); + Force operator + (const Force&) const; //private: Vector3 value_; Modified: trunk/yake/yake/physics/yakePhysicsJoint.h =================================================================== --- trunk/yake/yake/physics/yakePhysicsJoint.h 2007-08-06 22:21:06 UTC (rev 1786) +++ trunk/yake/yake/physics/yakePhysicsJoint.h 2007-08-10 15:26:25 UTC (rev 1787) @@ -117,6 +117,9 @@ struct DescHinge : DescBase { + DescHinge(IActor* pFirst, IActor* pSecond) : + DescBase( JT_HINGE, pFirst, pSecond ) + {} DescHinge( IActor* pFirst, IActor* pSecond, const math::Vector3& rAxis, @@ -131,6 +134,9 @@ struct DescHinge2 : DescBase { + DescHinge2(IActor* pFirst, IActor* pSecond) : + DescBase( JT_HINGE2, pFirst, pSecond ) + {} DescHinge2( IActor* pFirst, IActor* pSecond, const math::Vector3& rAxis0, @@ -148,6 +154,9 @@ struct DescBall : DescBase { + DescBall(IActor* pFirst, IActor* pSecond) : + DescBase( JT_BALL, pFirst, pSecond ) + {} DescBall( IActor* pFirst, IActor* pSecond, const math::Vector3& rAnchor ) : @@ -159,6 +168,9 @@ struct DescSlider : DescBase { + DescSlider(IActor* pFirst, IActor* pSecond) : + DescBase( JT_SLIDER, pFirst, pSecond ) + {} DescSlider( IActor* pFirst, IActor* pSecond, const math::Vector3& rAxis ) : @@ -170,6 +182,9 @@ struct DescUniversal : DescBase { + DescUniversal(IActor* pFirst, IActor* pSecond) : + DescBase( JT_UNIVERSAL, pFirst, pSecond ) + {} DescUniversal( IActor* pFirst, IActor* pSecond, const math::Vector3& rAxis0, Modified: trunk/yake/yake/physics/yakePhysicsShape.h =================================================================== --- trunk/yake/yake/physics/yakePhysicsShape.h 2007-08-06 22:21:06 UTC (rev 1786) +++ trunk/yake/yake/physics/yakePhysicsShape.h 2007-08-10 15:26:25 UTC (rev 1787) @@ -65,8 +65,8 @@ struct Desc { Desc( const ShapeType type_, - const math::Vector3& rPosition = math::Vector3::kZero, - const math::Quaternion& rOrientation = math::Quaternion::kIdentity, + const Vector3& rPosition = Vector3::kZero, + const Quaternion& rOrientation = Quaternion::kIdentity, const String& material_ = "" ) : type( type_ ), position( rPosition ), @@ -78,8 +78,8 @@ //virtual Desc* clone() const = 0; ShapeType type; // superfluous as shape type is determined by dynamic_cast on Desc struct... - math::Vector3 position; - math::Quaternion orientation; + Vector3 position; + Quaternion orientation; String material; }; @@ -87,11 +87,10 @@ { SphereDesc( real radius_ = real(1.), // base class: - const String& material_ = "", - const math::Vector3& rPosition = math::Vector3::kZero, - const math::Quaternion& rOrientation = math::Quaternion::kIdentity + const Vector3& rPosition = Vector3::kZero, + const Quaternion& rOrientation = Quaternion::kIdentity ) : - Desc( ST_SPHERE, rPosition, rOrientation, material_ ), + Desc( ST_SPHERE, rPosition, rOrientation ), radius( radius_ ) {} real radius; @@ -99,32 +98,29 @@ struct BoxDesc : Desc { - BoxDesc( const math::Vector3& rDimensions = math::Vector3(1,1,1), - // base class: - const String& material_ = "", - const math::Vector3& rPosition = math::Vector3::kZero, - const math::Quaternion& rOrientation = math::Quaternion::kIdentity - ) : - Desc( ST_BOX, rPosition, rOrientation, material_ ), - dimensions( rDimensions ) - {} - math::Vector3 dimensions; + BoxDesc( const Vector3& rDimensions = Vector3(1,1,1), + const Vector3& rPosition = Vector3::kZero, + const Quaternion& rOrientation = Quaternion::kIdentity + ) : + Desc( ST_BOX, rPosition, rOrientation ), + dimensions( rDimensions ) + {} + Vector3 dimensions; }; struct PlaneDesc : Desc { - PlaneDesc( const math::Vector3& rNormal = math::Vector3(0,1,0), + PlaneDesc( const Vector3& rNormal = Vector3(0,1,0), const real d_ = real(1.), // base class: - const String& material_ = "", - const math::Vector3& rPosition = math::Vector3::kZero, - const math::Quaternion& rOrientation = math::Quaternion::kIdentity + const Vector3& rPosition = Vector3::kZero, + const Quaternion& rOrientation = Quaternion::kIdentity ) : - Desc( ST_PLANE, rPosition, rOrientation, material_ ), + Desc( ST_PLANE, rPosition, rOrientation ), normal( rNormal ), d( d_ ) {} - math::Vector3 normal; + Vector3 normal; real d; }; @@ -133,11 +129,10 @@ CapsuleDesc(const real height_ = real(2.), const real radius_ = real(1.), // base class: - const String& material_ = "", - const math::Vector3& rPosition = math::Vector3::kZero, - const math::Quaternion& rOrientation = math::Quaternion::kIdentity + const Vector3& rPosition = Vector3::kZero, + const Quaternion& rOrientation = Quaternion::kIdentity ) : - Desc( ST_CAPSULE, rPosition, rOrientation, material_ ), + Desc( ST_CAPSULE, rPosition, rOrientation ), height( height_ ), radius( radius_ ) {} @@ -150,8 +145,8 @@ TriMeshDesc( const TriangleMeshDesc trimesh, // base class: const String& material_ = "", - const math::Vector3& rPosition = math::Vector3::kZero, - const math::Quaternion& rOrientation = math::Quaternion::kIdentity + const Vector3& rPosition = Vector3::kZero, + const Quaternion& rOrientation = Quaternion::kIdentity ) : Desc( ST_TRIANGLE_MESH, rPosition, rOrientation, material_ ), trimesh_( trimesh ), @@ -159,11 +154,10 @@ {} TriMeshDesc( const TriangleMeshId trimeshId, // base class: - const String& material_ = "", - const math::Vector3& rPosition = math::Vector3::kZero, - const math::Quaternion& rOrientation = math::Quaternion::kIdentity + const Vector3& rPosition = Vector3::kZero, + const Quaternion& rOrientation = Quaternion::kIdentity ) : - Desc( ST_TRIANGLE_MESH, rPosition, rOrientation, material_ ), + Desc( ST_TRIANGLE_MESH, rPosition, rOrientation ), trimeshId_( trimeshId ) {} TriangleMeshDesc trimesh_; @@ -177,10 +171,10 @@ virtual void setMaterial( IMaterial* pMaterial ) = 0; virtual IMaterial* getMaterial() const = 0; - //virtual math::Vector3 getDerivedPosition() const = 0; - //virtual math::Quaternion getDerivedOrientation() const = 0; + //virtual Vector3 getDerivedPosition() const = 0; + //virtual Quaternion getDerivedOrientation() const = 0; - virtual math::Vector3 getPropertyVector3(const String&) const = 0; + virtual Vector3 getPropertyVector3(const String&) const = 0; virtual real getPropertyReal(const String&) const = 0; }; YAKE_PHYSICS_COMMON_POINTERS( IShape ); Modified: trunk/yake/yake/physics/yakePhysicsWorld.h =================================================================== --- trunk/yake/yake/physics/yakePhysicsWorld.h 2007-08-06 22:21:06 UTC (rev 1786) +++ trunk/yake/yake/physics/yakePhysicsWorld.h 2007-08-10 15:26:25 UTC (rev 1787) @@ -79,8 +79,8 @@ virtual const StringVector getCurrentSolverParams() const = 0; virtual void setCurrentSolverParam( const String& rName, const boost::any& rValue ) = 0; - virtual void setGlobalGravity( const math::Vector3& g ) = 0; - virtual math::Vector3 getGlobalGravity() const = 0; + virtual void setGlobalGravity( const Vector3& g ) = 0; + virtual Vector3 getGlobalGravity() const = 0; virtual void step(const real timeElapsed) = 0; virtual real getStepSize() const = 0; Modified: trunk/yake/yake/raf/yakeApplicationState.h =================================================================== --- trunk/yake/yake/raf/yakeApplicationState.h 2007-08-06 22:21:06 UTC (rev 1786) +++ trunk/yake/yake/raf/yakeApplicationState.h 2007-08-10 15:26:25 UTC (rev 1787) @@ -72,6 +72,8 @@ //const String& currentName() const; void step(); + + ApplicationState* currentState() const; private: typedef fsm::oomachine<ApplicationState,String> fsm_type; fsm_type machine_; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-08-12 21:11:10
|
Revision: 1788 http://yake.svn.sourceforge.net/yake/?rev=1788&view=rev Author: psyclonist Date: 2007-08-12 14:11:12 -0700 (Sun, 12 Aug 2007) Log Message: ----------- * [raf/scripting] added demo 'raf/lua1' (same as raf/demo1 but done with Lua) * [scripting.Lua] IVM::execute() now also logs errors via yake.logging * [bindings.lua] added additional constructor for class Color * [bindings.lua] added graphics::Camera related bindings * [bindings.lua] fixed dependencies in premake scripts Modified Paths: -------------- trunk/yake/scripts/premake/samples.lua trunk/yake/scripts/premake/yake.lua trunk/yake/src/bindings.lua/bindings.lua.cpp trunk/yake/src/bindings.lua/detail/base.lua.cpp trunk/yake/src/bindings.lua/detail/graphics.lua.cpp trunk/yake/src/bindings.lua/detail/raf.lua.cpp trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp Added Paths: ----------- trunk/yake/common/media/scripts/raf1.lua trunk/yake/samples/raf/lua1/ trunk/yake/samples/raf/lua1/demo.cpp Added: trunk/yake/common/media/scripts/raf1.lua =================================================================== --- trunk/yake/common/media/scripts/raf1.lua (rev 0) +++ trunk/yake/common/media/scripts/raf1.lua 2007-08-12 21:11:12 UTC (rev 1788) @@ -0,0 +1,23 @@ +local gfx = yake.graphics + +-- +--local gsys = app.graphics +--local gsys = app:getGraphics("") + +-- configure basic scene properties +gworld:setShadowsEnabled(false) +gworld:setAmbientLight(yake.Color(0,0,0,1)) + +-- create ninja +local sn = gworld:createSceneNode() +local e = gworld:createEntity("ninja.mesh") +sn:attach(e) + +-- create direction light +local lightnode = gworld:createSceneNode() +local l = gworld:createLight() +lightnode:attach(l) +l.type = gfx.Light.LT_DIRECTIONAL +l:setDiffuseColour(yake.Color(1,1,1,1)) +l.direction = yake.Vector3(0,-1,1) + Added: trunk/yake/samples/raf/lua1/demo.cpp =================================================================== --- trunk/yake/samples/raf/lua1/demo.cpp (rev 0) +++ trunk/yake/samples/raf/lua1/demo.cpp 2007-08-12 21:11:12 UTC (rev 1788) @@ -0,0 +1,92 @@ +#include <yake/audio/yakeAudio.h> +#include <yake/input/yakeInput.h> +#include <yake/graphics/yakeGraphics.h> +#include <yake/physics/yakePhysics.h> +#include <yake/scripting/yakeScriptingSystem.h> +#include <yake/raf/yakeRaf.h> + +#include <yake/plugins/scriptingLua/ScriptingSystemLua.h> +#include <yake/bindings.lua/bindings.lua.h> +#include <yake/bindings.lua/common/yake.lua.common.h> + +using namespace yake; + +/** Configuration of the application */ +struct TheConfiguration : public raf::ApplicationConfiguration +{ + // Use "inputOgre" for Ogre 1.2/1.3, "inputOgreOIS" for Ogre 1.4+. + virtual StringVector getLibraries() + { return MakeStringVector() << YAKE_LIB("scriptingLua") << YAKE_LIB("graphicsOgre") << YAKE_LIB("inputOgreOIS"); } + + // Use "ogre" for Ogre 1.2/1.3, "ois" for Ogre 1.4+. + virtual StringVector getInputSystems() + { return MakeStringVector() << "ois"; } + + virtual StringVector getScriptingSystems() + { return MakeStringVector() << "lua"; } + + virtual StringVector getGraphicsSystems() + { return MakeStringVector() << "ogre3d"; } +}; + +/** Main application state */ +class TheMainState : public raf::RtMainState +{ +public: + TheMainState(raf::Application& owner) : raf::RtMainState(owner), app_(owner) + { + enableInstantQuitByKey( input::KC_ESCAPE ); + } +protected: + virtual void onCreateScene() + { + YAKE_LOG_INFORMATION("demo","Creating scene"); + + scripting::IScriptingSystem* sys = app_.getScriptingSystem(); + YAKE_ASSERT( sys ); + scripting::VMPtr vm = sys->createVM(); + bind_all(vm.get()); + + //bind + { + scripting::LuaVM* lvm = static_cast<scripting::LuaVM*>(vm.get()); + luabind::globals(lvm->getLuaState())["app"] = &app_; + luabind::globals(lvm->getLuaState())["gworld"] = this->getGraphicalWorld(); + luabind::globals(lvm->getLuaState())["defaultCam"] = this->getDefaultCamera(); + } + + // + scripting::ScriptPtr script = sys->createScriptFromFile("../../../common/media/scripts/raf1.lua"); + vm->execute( script ); + + // position camera and look at the ninja + getDefaultCamera()->setFixedYawAxis(Vector3::kUnitY); + getDefaultCamera()->setPosition(Vector3(100,20,-400)); + getDefaultCamera()->lookAt(Vector3(0,100,0)); + } + virtual void onFrame(const real timeElapsed) + { + } +private: + raf::Application& app_; +}; + +/** The mighty application itself! */ +class TheApp : public raf::ExampleApplication<TheConfiguration> +{ +public: + TheApp() {} +protected: + virtual raf::MainState* createMainState() + { + return new TheMainState(*this); + } +}; + +int main( int argc, char** argv ) +{ + // Use default executor for convenience. + // It's always possible to manually execute TheApp::initialise() etc. + return (raf::runApplication( TheApp() )) ? 0 : 1; +} + Modified: trunk/yake/scripts/premake/samples.lua =================================================================== --- trunk/yake/scripts/premake/samples.lua 2007-08-10 15:26:25 UTC (rev 1787) +++ trunk/yake/scripts/premake/samples.lua 2007-08-12 21:11:12 UTC (rev 1788) @@ -104,6 +104,14 @@ useComponent("base") useComponent("raf") end + + -------------------------------------- + if ENABLE_LUA_RAF then + makeSample("sampleRafLuaDemo1","samples/raf/lua1") + useComponent("base") + useComponent("raf") + useComponent("bindings.lua") + end end -------------------------------------- Modified: trunk/yake/scripts/premake/yake.lua =================================================================== --- trunk/yake/scripts/premake/yake.lua 2007-08-10 15:26:25 UTC (rev 1787) +++ trunk/yake/scripts/premake/yake.lua 2007-08-12 21:11:12 UTC (rev 1788) @@ -245,6 +245,15 @@ if ENABLE_LUA_TASK then addDependency("task") end + if ENABLE_LUA_GRAPHICS then + addDependency("graphics") + end + if ENABLE_LUA_PHYSICS then + addDependency("physics") + end + if ENABLE_LUA_RAF then + addDependency("raf") + end if (windows) then useDep("lua") useDep("luabind") Modified: trunk/yake/src/bindings.lua/bindings.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/bindings.lua.cpp 2007-08-10 15:26:25 UTC (rev 1787) +++ trunk/yake/src/bindings.lua/bindings.lua.cpp 2007-08-12 21:11:12 UTC (rev 1788) @@ -76,6 +76,15 @@ #if YAKE_ENABLE_LUA_ENT == 1 bind_ent(L); #endif +#if YAKE_ENABLE_LUA_GRAPHICS == 1 + bind_graphics(L); +#endif +#if YAKE_ENABLE_LUA_PHYSICS == 1 + bind_physics(L); +#endif +#if YAKE_ENABLE_LUA_RAF == 1 + bind_raf(L); +#endif } void bind_all(scripting::IVM* vm) { Modified: trunk/yake/src/bindings.lua/detail/base.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/base.lua.cpp 2007-08-10 15:26:25 UTC (rev 1787) +++ trunk/yake/src/bindings.lua/detail/base.lua.cpp 2007-08-12 21:11:12 UTC (rev 1788) @@ -79,6 +79,7 @@ [ class_<Color>("Color") .def( constructor<>() ) + .def( constructor<real,real,real>() ) .def( constructor<real,real,real,real>() ) .def( constructor< const Color& >() ) //FIXME some strange members in anonymous union::struct Modified: trunk/yake/src/bindings.lua/detail/graphics.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/graphics.lua.cpp 2007-08-10 15:26:25 UTC (rev 1787) +++ trunk/yake/src/bindings.lua/detail/graphics.lua.cpp 2007-08-12 21:11:12 UTC (rev 1788) @@ -131,6 +131,8 @@ , class_<ICamera,Movable>("Camera") //@todo + .def("lookAt", &ICamera::lookAt) + .property("aspectRatio", &ICamera::getAspectRatio, &ICamera::setAspectRatio) , class_<IViewport>("Viewport") //@todo @@ -142,6 +144,7 @@ .def("createSceneNode", &IWorld_createSceneNode_NoName) .def("createEntity", &IWorld::createEntity) .def("createParticleSystem", &IWorld::createParticleSystem) + .def("createLight", &IWorld::createLight) .def("createCamera", &IWorld::createCamera) .def("createViewport", &IWorld::createViewport) .def("load", &IWorld::load) Modified: trunk/yake/src/bindings.lua/detail/raf.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/raf.lua.cpp 2007-08-10 15:26:25 UTC (rev 1787) +++ trunk/yake/src/bindings.lua/detail/raf.lua.cpp 2007-08-12 21:11:12 UTC (rev 1788) @@ -91,6 +91,7 @@ .property("graphics", &getAppDefaultGraphics) .property("physics", &getAppDefaultPhysics) .property("audio", &getAppDefaultAudio) + .def("getGraphics", &raf::Application::getGraphicsSystem) , class_<raf::AppMachine>("AppMachine") .property("currentState", &raf::AppMachine::currentState) Modified: trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp =================================================================== --- trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp 2007-08-10 15:26:25 UTC (rev 1787) +++ trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp 2007-08-12 21:11:12 UTC (rev 1788) @@ -148,22 +148,29 @@ } catch (luabind::error& e) { + logging::log(logging::S_ERROR,"scriptingLua","Luabind error"); throw Exception(String("LuaVM: caught Luabind error") + e.what()); } catch (luabind::cast_failed& e) { + logging::log(logging::S_ERROR,"scriptingLua","Luabind cast failed"); throw Exception(String("LuaVM: caught Luabind cast_failed") + e.what()); } catch (Exception&) { + logging::log(logging::S_ERROR,"scriptingLua","unknown exception"); throw; } catch (std::exception& e) { + logging::log(logging::S_ERROR,"scriptingLua",e.what()); throw Exception(String("LuaVM: caught exception: ") + e.what()); } if (!err.empty()) + { + logging::log(logging::S_ERROR,"scriptingLua",err); throw Exception(String("LuaVM: error: ") + err); + } } //------------------------------------------------------ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-08-16 18:54:26
|
Revision: 1791 http://yake.svn.sourceforge.net/yake/?rev=1791&view=rev Author: psyclonist Date: 2007-08-16 11:54:29 -0700 (Thu, 16 Aug 2007) Log Message: ----------- [physics,vehicle,loader] improved interface clarity Modified Paths: -------------- trunk/yake/src/loader/yakeXODEParser.cpp trunk/yake/src/vehicle/yakeDotVehicle.cpp trunk/yake/src/vehicle/yakeNativeOde.cpp trunk/yake/yake/physics/yakePhysicsShape.h Modified: trunk/yake/src/loader/yakeXODEParser.cpp =================================================================== --- trunk/yake/src/loader/yakeXODEParser.cpp 2007-08-16 18:42:07 UTC (rev 1790) +++ trunk/yake/src/loader/yakeXODEParser.cpp 2007-08-16 18:54:29 UTC (rev 1791) @@ -759,8 +759,7 @@ TriangleMeshDesc dataDesc( vertices, indices ); - shapeDesc = new IShape::TriMeshDesc( dataDesc, "", - geomTransform.position_, geomTransform.rotation_ ); + shapeDesc = new IShape::TriMeshDesc( dataDesc, geomTransform.position_, geomTransform.rotation_ ); } else if ( nodeName == "ext" ) { Modified: trunk/yake/src/vehicle/yakeDotVehicle.cpp =================================================================== --- trunk/yake/src/vehicle/yakeDotVehicle.cpp 2007-08-16 18:42:07 UTC (rev 1790) +++ trunk/yake/src/vehicle/yakeDotVehicle.cpp 2007-08-16 18:54:29 UTC (rev 1791) @@ -144,7 +144,7 @@ if (n.getNodeByName("position")) parsePosition( *n.getNodeByName("position"), pos ); mpCurrVehTpl->mChassis.mChassisShapes.push_back( - new physics::IShape::BoxDesc( dim, matId, pos ) ); + new physics::IShape::BoxDesc( dim, pos, Quaternion::kIdentity, matId ) ); } void DotVehicleParser::parseShapeSphere( const data::dom::INode& n, const String& matId ) @@ -154,7 +154,7 @@ if (n.getNodeByName("position")) parsePosition( *n.getNodeByName("position"), pos ); mpCurrVehTpl->mChassis.mChassisShapes.push_back( - new physics::IShape::SphereDesc( radius, matId, pos ) ); + new physics::IShape::SphereDesc( radius, pos, Quaternion::kIdentity, matId ) ); } void DotVehicleParser::parseEngine( const data::dom::INode& n ) Modified: trunk/yake/src/vehicle/yakeNativeOde.cpp =================================================================== --- trunk/yake/src/vehicle/yakeNativeOde.cpp 2007-08-16 18:42:07 UTC (rev 1790) +++ trunk/yake/src/vehicle/yakeNativeOde.cpp 2007-08-16 18:54:29 UTC (rev 1791) @@ -537,7 +537,7 @@ YAKE_ASSERT( chassisObj ); mpWheel = PWorld.createActor( physics::ACTOR_DYNAMIC ); - mpWheel->createShape( physics::IShape::SphereDesc( mRadius, tpl.mMaterial ) ); + mpWheel->createShape( physics::IShape::SphereDesc( mRadius, Vector3::kZero, Quaternion::kIdentity, tpl.mMaterial ) ); real mass = tpl.mMassRelativeToChassis ? (tpl.mMass * chassisObj->getBody().getMass()) : tpl.mMass; mpWheel->setPosition( tpl.mPosition ); Modified: trunk/yake/yake/physics/yakePhysicsShape.h =================================================================== --- trunk/yake/yake/physics/yakePhysicsShape.h 2007-08-16 18:42:07 UTC (rev 1790) +++ trunk/yake/yake/physics/yakePhysicsShape.h 2007-08-16 18:54:29 UTC (rev 1791) @@ -88,9 +88,10 @@ SphereDesc( real radius_ = real(1.), // base class: const Vector3& rPosition = Vector3::kZero, - const Quaternion& rOrientation = Quaternion::kIdentity + const Quaternion& rOrientation = Quaternion::kIdentity, + const String& material_ = "" ) : - Desc( ST_SPHERE, rPosition, rOrientation ), + Desc( ST_SPHERE, rPosition, rOrientation, material_ ), radius( radius_ ) {} real radius; @@ -100,9 +101,10 @@ { BoxDesc( const Vector3& rDimensions = Vector3(1,1,1), const Vector3& rPosition = Vector3::kZero, - const Quaternion& rOrientation = Quaternion::kIdentity + const Quaternion& rOrientation = Quaternion::kIdentity, + const String& material_ = "" ) : - Desc( ST_BOX, rPosition, rOrientation ), + Desc( ST_BOX, rPosition, rOrientation, material_ ), dimensions( rDimensions ) {} Vector3 dimensions; @@ -114,9 +116,10 @@ const real d_ = real(1.), // base class: const Vector3& rPosition = Vector3::kZero, - const Quaternion& rOrientation = Quaternion::kIdentity + const Quaternion& rOrientation = Quaternion::kIdentity, + const String& material_ = "" ) : - Desc( ST_PLANE, rPosition, rOrientation ), + Desc( ST_PLANE, rPosition, rOrientation, material_ ), normal( rNormal ), d( d_ ) {} @@ -130,9 +133,10 @@ const real radius_ = real(1.), // base class: const Vector3& rPosition = Vector3::kZero, - const Quaternion& rOrientation = Quaternion::kIdentity + const Quaternion& rOrientation = Quaternion::kIdentity, + const String& material_ = "" ) : - Desc( ST_CAPSULE, rPosition, rOrientation ), + Desc( ST_CAPSULE, rPosition, rOrientation, material_ ), height( height_ ), radius( radius_ ) {} @@ -144,9 +148,9 @@ { TriMeshDesc( const TriangleMeshDesc trimesh, // base class: - const String& material_ = "", const Vector3& rPosition = Vector3::kZero, - const Quaternion& rOrientation = Quaternion::kIdentity + const Quaternion& rOrientation = Quaternion::kIdentity, + const String& material_ = "" ) : Desc( ST_TRIANGLE_MESH, rPosition, rOrientation, material_ ), trimesh_( trimesh ), This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-08-17 19:15:10
|
Revision: 1792 http://yake.svn.sourceforge.net/yake/?rev=1792&view=rev Author: psyclonist Date: 2007-08-17 12:15:13 -0700 (Fri, 17 Aug 2007) Log Message: ----------- * [samples] improved raf/lua1: scene setup is now done completely in Lua Modified Paths: -------------- trunk/yake/common/media/scripts/raf1.lua trunk/yake/samples/raf/lua1/demo.cpp Modified: trunk/yake/common/media/scripts/raf1.lua =================================================================== --- trunk/yake/common/media/scripts/raf1.lua 2007-08-16 18:54:29 UTC (rev 1791) +++ trunk/yake/common/media/scripts/raf1.lua 2007-08-17 19:15:13 UTC (rev 1792) @@ -1,9 +1,6 @@ -local gfx = yake.graphics +local gworld = scene.gworld +local defaultCam = scene.activeCamera --- ---local gsys = app.graphics ---local gsys = app:getGraphics("") - -- configure basic scene properties gworld:setShadowsEnabled(false) gworld:setAmbientLight(yake.Color(0,0,0,1)) @@ -17,7 +14,13 @@ local lightnode = gworld:createSceneNode() local l = gworld:createLight() lightnode:attach(l) -l.type = gfx.Light.LT_DIRECTIONAL +l.type = yake.graphics.Light.LT_DIRECTIONAL l:setDiffuseColour(yake.Color(1,1,1,1)) l.direction = yake.Vector3(0,-1,1) +-- +local cam = scene.activeCamera +assert(cam) +cam.position = yake.Vector3(100,20,-200) +cam:setFixedYawAxis( yake.Vector3.UnitY ) +cam:lookAt( yake.Vector3(0,100,0) ) Modified: trunk/yake/samples/raf/lua1/demo.cpp =================================================================== --- trunk/yake/samples/raf/lua1/demo.cpp 2007-08-16 18:54:29 UTC (rev 1791) +++ trunk/yake/samples/raf/lua1/demo.cpp 2007-08-17 19:15:13 UTC (rev 1792) @@ -51,8 +51,11 @@ { scripting::LuaVM* lvm = static_cast<scripting::LuaVM*>(vm.get()); luabind::globals(lvm->getLuaState())["app"] = &app_; - luabind::globals(lvm->getLuaState())["gworld"] = this->getGraphicalWorld(); - luabind::globals(lvm->getLuaState())["defaultCam"] = this->getDefaultCamera(); + + luabind::object scene = luabind::newtable(lvm->getLuaState()); + scene["gworld"] = this->getGraphicalWorld(); + scene["activeCamera"] = this->getDefaultCamera(); + luabind::globals(lvm->getLuaState())["scene"] = scene; } // @@ -60,9 +63,6 @@ vm->execute( script ); // position camera and look at the ninja - getDefaultCamera()->setFixedYawAxis(Vector3::kUnitY); - getDefaultCamera()->setPosition(Vector3(100,20,-400)); - getDefaultCamera()->lookAt(Vector3(0,100,0)); } virtual void onFrame(const real timeElapsed) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-08-17 19:15:55
|
Revision: 1793 http://yake.svn.sourceforge.net/yake/?rev=1793&view=rev Author: psyclonist Date: 2007-08-17 12:15:52 -0700 (Fri, 17 Aug 2007) Log Message: ----------- [graphics] added graphics::ILight::isEnabled() Modified Paths: -------------- trunk/yake/src/plugins/graphicsOgre/graphicsOgreLight.cpp trunk/yake/yake/graphics/yakeGraphicalWorld.h trunk/yake/yake/plugins/graphicsOgre/graphicsOgreLight.h Modified: trunk/yake/src/plugins/graphicsOgre/graphicsOgreLight.cpp =================================================================== --- trunk/yake/src/plugins/graphicsOgre/graphicsOgreLight.cpp 2007-08-17 19:15:13 UTC (rev 1792) +++ trunk/yake/src/plugins/graphicsOgre/graphicsOgreLight.cpp 2007-08-17 19:15:52 UTC (rev 1793) @@ -138,6 +138,13 @@ } //------------------------------------------------------ + bool OgreLight::isEnabled() const + { + YAKE_ASSERT( mLight ).debug( "need actual light!" ); + return mLight->isVisible(); + } + + //------------------------------------------------------ void OgreLight::setEnabled( bool enabled ) { YAKE_ASSERT( mLight ).debug( "need actual light!" ); Modified: trunk/yake/yake/graphics/yakeGraphicalWorld.h =================================================================== --- trunk/yake/yake/graphics/yakeGraphicalWorld.h 2007-08-17 19:15:13 UTC (rev 1792) +++ trunk/yake/yake/graphics/yakeGraphicalWorld.h 2007-08-17 19:15:52 UTC (rev 1793) @@ -100,6 +100,7 @@ virtual void setType( const LightType type ) = 0; virtual LightType getType() const = 0; + virtual bool isEnabled() const = 0; virtual void setEnabled( bool enabled ) = 0; virtual void setCastsShadows( bool enabled ) = 0; Modified: trunk/yake/yake/plugins/graphicsOgre/graphicsOgreLight.h =================================================================== --- trunk/yake/yake/plugins/graphicsOgre/graphicsOgreLight.h 2007-08-17 19:15:13 UTC (rev 1792) +++ trunk/yake/yake/plugins/graphicsOgre/graphicsOgreLight.h 2007-08-17 19:15:52 UTC (rev 1793) @@ -55,6 +55,7 @@ virtual void setDiffuseColour( const math::Color& colour ); virtual void setSpecularColour( const math::Color& colour ); + virtual bool isEnabled() const; virtual void setEnabled( bool enabled ); virtual void setCastsShadows( bool enabled ); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-08-18 21:26:54
|
Revision: 1797 http://yake.svn.sourceforge.net/yake/?rev=1797&view=rev Author: psyclonist Date: 2007-08-18 14:25:29 -0700 (Sat, 18 Aug 2007) Log Message: ----------- * [sample] raf/lua1: graphics + input completely handled from Lua now * [bindings.lua] added bindings for yake.input * [bindings.lua] improved bindings for Vector3, Matrix3 and Quaternion * [input] small non-breaking improvements in the ActionMap API Modified Paths: -------------- trunk/yake/common/media/scripts/raf1.lua trunk/yake/samples/raf/lua1/demo.cpp trunk/yake/samples/task/demo1/demo.cpp trunk/yake/scripts/premake/config.lua trunk/yake/scripts/premake/yake.lua trunk/yake/src/bindings.lua/bindings.lua.cpp trunk/yake/src/bindings.lua/detail/base.lua.cpp trunk/yake/src/input/yakeActionMap.cpp trunk/yake/yake/bindings.lua/bindings.lua.h trunk/yake/yake/input/yakeActionMap.h Added Paths: ----------- trunk/yake/src/bindings.lua/detail/input.lua.cpp Modified: trunk/yake/common/media/scripts/raf1.lua =================================================================== --- trunk/yake/common/media/scripts/raf1.lua 2007-08-17 19:20:50 UTC (rev 1796) +++ trunk/yake/common/media/scripts/raf1.lua 2007-08-18 21:25:29 UTC (rev 1797) @@ -1,6 +1,12 @@ local gworld = scene.gworld local defaultCam = scene.activeCamera +local actionMap = app.actionMap +local input = yake.input +-------------------------------------- +-- Configure graphics +-------------------------------------- + -- configure basic scene properties gworld:setShadowsEnabled(false) gworld:setAmbientLight(yake.Color(0,0,0,1)) @@ -10,17 +16,74 @@ local e = gworld:createEntity("ninja.mesh") sn:attach(e) --- create direction light -local lightnode = gworld:createSceneNode() -local l = gworld:createLight() -lightnode:attach(l) -l.type = yake.graphics.Light.LT_DIRECTIONAL -l:setDiffuseColour(yake.Color(1,1,1,1)) -l.direction = yake.Vector3(0,-1,1) +-- create directional light --- +local light = gworld:createLight() -- create light + +local lightnode = gworld:createSceneNode() -- attach light to node +lightnode:attach(light) + +light.type = yake.graphics.Light.LT_DIRECTIONAL -- configure light +light:setDiffuseColour(yake.Color(1,1,1,1)) +light.direction = yake.Vector3(0,-1,1) + +-- configure active (=default) camera + local cam = scene.activeCamera assert(cam) cam.position = yake.Vector3(100,20,-200) -cam:setFixedYawAxis( yake.Vector3.UnitY ) -cam:lookAt( yake.Vector3(0,100,0) ) +cam:setFixedYawAxis( yake.Vector3.UnitY ) -- keep upwards direction constant +cam:lookAt( yake.Vector3(0,100,0) ) -- look at our ninja! + +-------------------------------------- +-- Configure input +-------------------------------------- + +-- We demonstrate two ways to bind Lua callbacks to a keyboard action. +-- #1 demonstrates the details +-- #2 shows how to achieve the same thing fast and Lua-style + +------ #1: "The Long Way" + +--local idLeft = input.ActionId.fromName("left") -- look up ActionId by its name (useful for user-defined ones) +local idLeft = input.ACTIONID_LEFT -- using an ActionId constant + +-- Connect key "Cursor Left" to action "left": +local acLeft = input.KeyboardActionCondition(app.keyboard, input.KC_LEFT, input.KAM_CONTINUOUS) +actionMap:reg(idLeft,acLeft) + +-- Our Lua callback handler: +function onLeft() + cam:translate(yake.Vector3(-1,0,0)) +end + +actionMap:connectToAction(idLeft,onLeft) -- by Action ID + +------ #2: "Shortcut" (using action names and anonymous Lua functions) + +actionMap:reg("right", input.KeyboardActionCondition(app.keyboard, input.KC_RIGHT, input.KAM_CONTINUOUS)) +actionMap:connectToAction("right", + function() + cam:translate(yake.Vector3(1,0,0)) + end) + +------- Let's define a few helper functions to make things easier: + +function createKeyAction(action, key, keymode) + return actionMap:reg(action, input.KeyboardActionCondition(app.keyboard, key, keymode )) +end +function bindAction(action, handler) + return actionMap:connectToAction(action, handler) +end + +------- Bind the rest of the keys to actions: + +createKeyAction("forward", input.KC_UP, input.KAM_CONTINUOUS) +bindAction("forward", function() + cam:translate(yake.Vector3(0,0,-1)) + end) + +createKeyAction("reverse", input.KC_DOWN, input.KAM_CONTINUOUS) +bindAction("reverse", function() + cam:translate(yake.Vector3(0,0,1)) + end) Modified: trunk/yake/samples/raf/lua1/demo.cpp =================================================================== --- trunk/yake/samples/raf/lua1/demo.cpp 2007-08-17 19:20:50 UTC (rev 1796) +++ trunk/yake/samples/raf/lua1/demo.cpp 2007-08-18 21:25:29 UTC (rev 1797) @@ -38,36 +38,59 @@ enableInstantQuitByKey( input::KC_ESCAPE ); } protected: + virtual void onEnter() + { + raf::RtMainState::onEnter(); + actionMap_.start(); + } + virtual void onExit() + { + raf::RtMainState::onExit(); + actionMap_.stop(); + + actionMap_.clear(); // Do NOT forget to clear this! Otherwise we keep references to + // the callback functions created from the Lua VM which is about to + // be destroyed, too! + // @todo find a nice solution to this + vm_.reset(); // destroy the VM *before* the ActionMap gets destroyed! + } virtual void onCreateScene() { YAKE_LOG_INFORMATION("demo","Creating scene"); scripting::IScriptingSystem* sys = app_.getScriptingSystem(); YAKE_ASSERT( sys ); - scripting::VMPtr vm = sys->createVM(); - bind_all(vm.get()); + YAKE_ASSERT( !vm_ ); + vm_ = sys->createVM(); + bind_all(vm_.get()); //bind { - scripting::LuaVM* lvm = static_cast<scripting::LuaVM*>(vm.get()); - luabind::globals(lvm->getLuaState())["app"] = &app_; + scripting::LuaVM* lvm = static_cast<scripting::LuaVM*>(vm_.get()); + lua_State* L = lvm->getLuaState(); + luabind::globals(L)["app"] = &app_; - luabind::object scene = luabind::newtable(lvm->getLuaState()); + luabind::globals(L)["app"]["actionMap"] = &actionMap_; + + luabind::object scene = luabind::newtable(L); scene["gworld"] = this->getGraphicalWorld(); scene["activeCamera"] = this->getDefaultCamera(); - luabind::globals(lvm->getLuaState())["scene"] = scene; + luabind::globals(L)["scene"] = scene; } // Create ninja model, position camera and look at the ninja: All done in Lua script: scripting::ScriptPtr script = sys->createScriptFromFile("../../../common/media/scripts/raf1.lua"); - vm->execute( script ); + vm_->execute( script ); } virtual void onFrame(const real timeElapsed) { + actionMap_.update(); //@todo here OK? ... } private: raf::Application& app_; + input::ActionMap actionMap_; + scripting::VMPtr vm_; }; /** The mighty application itself! */ Modified: trunk/yake/samples/task/demo1/demo.cpp =================================================================== --- trunk/yake/samples/task/demo1/demo.cpp 2007-08-17 19:20:50 UTC (rev 1796) +++ trunk/yake/samples/task/demo1/demo.cpp 2007-08-18 21:25:29 UTC (rev 1797) @@ -30,7 +30,7 @@ // run executor for (size_t t=0; t<10; ++t) - exec->update(1); - + exec->update(1); + return 0; } Modified: trunk/yake/scripts/premake/config.lua =================================================================== --- trunk/yake/scripts/premake/config.lua 2007-08-17 19:20:50 UTC (rev 1796) +++ trunk/yake/scripts/premake/config.lua 2007-08-18 21:25:29 UTC (rev 1797) @@ -56,6 +56,7 @@ ENABLE_LUA_ENT = true -- 'ent' binder (requires BASE, MODEL and PROPERTY binders!) ENABLE_LUA_GRAPHICS = true ENABLE_LUA_PHYSICS = true +ENABLE_LUA_INPUT = true ENABLE_LUA_RAF = true -------------------------------------- Modified: trunk/yake/scripts/premake/yake.lua =================================================================== --- trunk/yake/scripts/premake/yake.lua 2007-08-17 19:20:50 UTC (rev 1796) +++ trunk/yake/scripts/premake/yake.lua 2007-08-18 21:25:29 UTC (rev 1797) @@ -75,6 +75,7 @@ f:write("#define YAKE_ENABLE_LUA_PROPERTY " .. bool_to_int(ENABLE_LUA_PROPERTY) .. "\n") f:write("#define YAKE_ENABLE_LUA_GRAPHICS " .. bool_to_int(ENABLE_LUA_GRAPHICS) .. "\n") f:write("#define YAKE_ENABLE_LUA_PHYSICS " .. bool_to_int(ENABLE_LUA_PHYSICS) .. "\n") + f:write("#define ENABLE_LUA_INPUT " .. bool_to_int(ENABLE_LUA_INPUT) .. "\n") f:write("#define YAKE_ENABLE_LUA_RAF " .. bool_to_int(ENABLE_LUA_RAF) .. "\n") f:write("\n") f:write("#endif\n") @@ -251,10 +252,13 @@ if ENABLE_LUA_PHYSICS then addDependency("physics") end + if ENABLE_LUA_INPUT then + addDependency("input") + end if ENABLE_LUA_RAF then addDependency("raf") end - if (windows) then + if (windows) then --@todo still required? or does this get picked up automatically already? useDep("lua") useDep("luabind") end Modified: trunk/yake/src/bindings.lua/bindings.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/bindings.lua.cpp 2007-08-17 19:20:50 UTC (rev 1796) +++ trunk/yake/src/bindings.lua/bindings.lua.cpp 2007-08-18 21:25:29 UTC (rev 1797) @@ -82,6 +82,9 @@ #if YAKE_ENABLE_LUA_PHYSICS == 1 bind_physics(L); #endif +#if YAKE_ENABLE_LUA_INPUT == 1 + bind_input(L); +#endif #if YAKE_ENABLE_LUA_RAF == 1 bind_raf(L); #endif Modified: trunk/yake/src/bindings.lua/detail/base.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/base.lua.cpp 2007-08-17 19:20:50 UTC (rev 1796) +++ trunk/yake/src/bindings.lua/detail/base.lua.cpp 2007-08-18 21:25:29 UTC (rev 1797) @@ -128,6 +128,7 @@ .def(const_self * other<real>()) .def(const_self * Quaternion()) .def(const_self * Matrix3()) + .def(tostring(const_self)) ]; luabind::globals(L)["yake"]["Vector3"]["Zero"] = Vector3::kZero; luabind::globals(L)["yake"]["Vector3"]["UnitScale"] = Vector3::kUnitScale; @@ -153,7 +154,10 @@ .def( constructor< Matrix3 const& >() ) .def( "getColumn", &Matrix3::GetColumn ) .def(const_self * other<Matrix3>()) + .def(tostring(const_self)) ]; + luabind::globals(L)["yake"]["Matrix3"]["Zero"] = Matrix3::ZERO; + luabind::globals(L)["yake"]["Matrix3"]["Identity"] = Matrix3::IDENTITY; // Quaternion module( YAKE_MATH_MODULE ) @@ -168,6 +172,8 @@ .def("inverse", &Quaternion::Inverse) .def(const_self * other<Quaternion>()) ]; + luabind::globals(L)["yake"]["Quaternion"]["Zero"] = Quaternion::kZero; + luabind::globals(L)["yake"]["Quaternion"]["Identity"] = Quaternion::kIdentity; // Ray module( YAKE_MATH_MODULE ) Added: trunk/yake/src/bindings.lua/detail/input.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/input.lua.cpp (rev 0) +++ trunk/yake/src/bindings.lua/detail/input.lua.cpp 2007-08-18 21:25:29 UTC (rev 1797) @@ -0,0 +1,221 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#include <yake/config.h> +#if YAKE_ENABLE_LUA_INPUT == 1 + +// See task.lua.cpp +#include <yake/bindings.lua/common/yake.lua.shared_ptr.h> + +#include <yake/bindings.lua/bindings.lua.h> // Don't forget to include this for proper dllexport! + +#include <yake/base/templates/yakeSmartAssert.h> +#include <yake/base/yake.h> +#include <yake/input/yakeInput.h> + +#include <yake/bindings.lua/detail/private.h> +#include <yake/bindings.lua/common/yake.lua.any_converter.h> + +#include <luabind/discard_result_policy.hpp> +#include <luabind/iterator_policy.hpp> +#include <luabind/operator.hpp> +#include <luabind/adopt_policy.hpp> + +namespace yake { +namespace input { + struct NullType {}; + SignalConnection* ActionMap_connectToAction(ActionMap* map, const ActionId& id, luabind::object o) + { + YAKE_ASSERT( map ); + //YAKE_ASSERT( luabind::type(o) == LUA_TFUNCTION ); + if (luabind::type(o) != LUA_TFUNCTION) + return 0; + return new SignalConnection(map->subscribeToActionIdV( id, o )); + } + SignalConnection* ActionMap_connectToActionByName(ActionMap* map, const char* name, luabind::object o) + { + const ActionId id = ActionIdRegistry::getByName(name); + return ActionMap_connectToAction( map, id, o ); + } + SignalConnection* ActionMap_connectToActionResult(ActionMap* map, const ActionId& id, luabind::object o) + { + YAKE_ASSERT( map ); + //YAKE_ASSERT( luabind::type(o) == LUA_TFUNCTION ); + if (luabind::type(o) != LUA_TFUNCTION) + return 0; + return new SignalConnection(map->subscribeToActionIdR( id, o )); + } + ConditionConnection* ActionMap_reg(ActionMap* map, const ActionId & actionId, SharedPtr<ActionCondition> condition) + { + if (!map) + return 0; + if (!condition) + return 0; + return new ConditionConnection( map->reg(actionId, condition) ); + } + ConditionConnection* ActionMap_regByName(ActionMap* map, const char* name, SharedPtr<ActionCondition> condition) + { + const ActionId id = ActionIdRegistry::getByName(name); + return ActionMap_reg( map, id, condition ); + } + luabind::object InputSystem_getAvailableDevices(IInputSystem* sys, lua_State* L) + { + YAKE_ASSERT( sys ); + luabind::object o = luabind::newtable(L); + + IInputSystem::DeviceEntryList devices = sys->getAvailableDevices(); + YAKE_FOR_EACH(IInputSystem::DeviceEntryList::const_iterator, it, devices) + { + const IInputSystem::DeviceListEntry& dev = *it; + o[ dev.name ] = dev.type; + } + + return o; + } + void bind( lua_State* L ) + { + YAKE_ASSERT( L ); + if (!L) + return; + + using namespace luabind; + +#define YAKE_INPUT_MODULE L, "yake" + + module( YAKE_INPUT_MODULE ) + [ + namespace_("input") + [ + class_<NullType>("MouseButton") + .enum_("MouseButton") + [ + value("MBT_LEFT",MBT_LEFT), + value("MBT_RIGHT",MBT_RIGHT), + value("MBT_MIDDLE",MBT_MIDDLE) + ] + , + class_<InputDevice>("InputDevice") + .property("type", &InputDevice::getType) + , + class_<MouseDevice,InputDevice>("MouseDevice") + , + class_<KeyboardDevice,InputDevice>("KeyboardDevice") + , + class_<IInputSystem>("InputSystem") + .def("getAvailableDevices", &InputSystem_getAvailableDevices, raw(_2)) + .def("getDevice", &IInputSystem::getDevice) + .def("activateDevice", &IInputSystem::activateDevice) + , + class_<ActionId>("ActionId") + .property("id", &ActionId::id) + .property("name", &ActionId::getName) + .scope + [ + def("fromName", &ActionIdRegistry::getByName) + ] + , + class_<ActionMap::ActionResult>("ActionResult") + .def_readonly("id", &ActionMap::ActionResult::id) + .def_readonly("signal", &ActionMap::ActionResult::signal) + , + class_<ActionCondition,SharedPtr<ActionCondition> >("ActionCondition") + , + class_<MouseActionCondition,ActionCondition>("MouseActionCondition") + //.def(constructor<MouseDevice*>()) + , + class_<MouseButtonActionCondition,MouseActionCondition>("MouseButtonActionCondition") + .def(constructor<MouseDevice*,MouseButton,MouseButtonActionMode>()) + , + class_<KeyboardActionCondition,ActionCondition,SharedPtr<ActionCondition> >("KeyboardActionCondition") + .def(constructor<KeyboardDevice*,KeyCode,KeyboardActionMode>()) + .def("setKey", &KeyboardActionCondition::setKey) + .def("setMode", &KeyboardActionCondition::setMode) + , + class_<ConditionConnection>("ConditionConnection") + .def("disconnect",&ConditionConnection::disconnect) + , + class_<SignalConnection>("SignalConnection") //@todo move out from "yake.input" into "yake" + .def("disconnect",&SignalConnection::disconnect) + , + class_<ActionMap>("ActionMap") + .def("start", &ActionMap::start) + .def("stop", &ActionMap::stop) + .def("clear", &ActionMap::clear) + .def("connectToAction", &ActionMap_connectToAction, adopt(result)) + .def("connectToAction", &ActionMap_connectToActionByName, adopt(result)) + .def("connectToActionResult", &ActionMap_connectToActionResult, adopt(result)) + .def("reg", &ActionMap_reg, adopt(result)) + .def("reg", &ActionMap_regByName, adopt(result)) + .def("save", &ActionMap::saveToFile) + ] + ]; + luabind::globals(L)["yake"]["input"]["KAM_CONTINUOUS"] = KAM_CONTINUOUS; + luabind::globals(L)["yake"]["input"]["KAM_PRESSED"] = KAM_PRESSED; + luabind::globals(L)["yake"]["input"]["KAM_RELEASED"] = KAM_RELEASED; + luabind::globals(L)["yake"]["input"]["KAM_PRESSED_AND_RELEASED"] = KAM_PRESSED_AND_RELEASED; + + //@todo keep this in sync with yake/input/yakeActionMap.h: + luabind::globals(L)["yake"]["input"]["ACTIONID_NONE"] = ACTIONID_NONE; + luabind::globals(L)["yake"]["input"]["ACTIONID_FORWARD"] = ACTIONID_FORWARD; + luabind::globals(L)["yake"]["input"]["ACTIONID_REVERSE"] = ACTIONID_REVERSE; + luabind::globals(L)["yake"]["input"]["ACTIONID_STRAFE_LEFT"] = ACTIONID_STRAFE_LEFT; + luabind::globals(L)["yake"]["input"]["ACTIONID_STRAFE_RIGHT"] = ACTIONID_STRAFE_RIGHT; + luabind::globals(L)["yake"]["input"]["ACTIONID_ROTATE_LEFT"] = ACTIONID_ROTATE_LEFT; + luabind::globals(L)["yake"]["input"]["ACTIONID_ROTATE_RIGHT"] = ACTIONID_ROTATE_RIGHT; + luabind::globals(L)["yake"]["input"]["ACTIONID_UP"] = ACTIONID_UP; + luabind::globals(L)["yake"]["input"]["ACTIONID_DOWN"] = ACTIONID_DOWN; + luabind::globals(L)["yake"]["input"]["ACTIONID_LEFT"] = ACTIONID_LEFT; + luabind::globals(L)["yake"]["input"]["ACTIONID_RIGHT"] = ACTIONID_RIGHT; + luabind::globals(L)["yake"]["input"]["ACTIONID_PITCH_UP"] = ACTIONID_PITCH_UP; + luabind::globals(L)["yake"]["input"]["ACTIONID_PITCH_DOWN"] = ACTIONID_PITCH_DOWN; + luabind::globals(L)["yake"]["input"]["ACTIONID_USE"] = ACTIONID_USE; + luabind::globals(L)["yake"]["input"]["ACTIONID_FIRE1"] = ACTIONID_FIRE1; + luabind::globals(L)["yake"]["input"]["ACTIONID_FIRE2"] = ACTIONID_FIRE2; + luabind::globals(L)["yake"]["input"]["ACTIONID_USER"] = ACTIONID_USER; + + luabind::globals(L)["yake"]["input"]["KC_ESCAPE"] = KC_ESCAPE; + luabind::globals(L)["yake"]["input"]["KC_LEFT"] = KC_LEFT; + luabind::globals(L)["yake"]["input"]["KC_RIGHT"] = KC_RIGHT; + luabind::globals(L)["yake"]["input"]["KC_UP"] = KC_UP; + luabind::globals(L)["yake"]["input"]["KC_DOWN"] = KC_DOWN; + } + + YAKE_WRAP_BINDER(input,::yake::input::bind); + +} // namespace input + void bind_input(lua_State* L) + { + YAKE_ASSERT(L); + input::bind(L); + } + void bind_input(scripting::IVM* vm) + { + scripting::LuaVM* luavm = static_cast<scripting::LuaVM*>(vm); + YAKE_ASSERT( luavm ); + bind_input(luavm->getLuaState()); + } +} // namespace yake +#endif // YAKE_ENABLE_LUA_INPUT Modified: trunk/yake/src/input/yakeActionMap.cpp =================================================================== --- trunk/yake/src/input/yakeActionMap.cpp 2007-08-17 19:20:50 UTC (rev 1796) +++ trunk/yake/src/input/yakeActionMap.cpp 2007-08-18 21:25:29 UTC (rev 1797) @@ -668,6 +668,12 @@ //----------------------------------------------------- ConditionConnection ActionMap::reg( const ActionId & actionId, ActionCondition* condition ) { + return this->reg( actionId, SharedPtr<ActionCondition>(condition) ); + } + + //----------------------------------------------------- + ConditionConnection ActionMap::reg( const ActionId & actionId, SharedPtr<ActionCondition> condition ) + { YAKE_ASSERT( condition ); ActionList::iterator it = mEntries.find( actionId ); @@ -675,15 +681,15 @@ { std::pair<ActionList::iterator,bool> vt = mEntries.insert( std::make_pair( actionId, new ActionMapEntry() ) ); YAKE_ASSERT( vt.second ); - vt.first->second->conditions.push_back( SharedPtr<ActionCondition>(condition)); + vt.first->second->conditions.push_back( condition ); } else - it->second->conditions.push_back( SharedPtr<ActionCondition>(condition)); + it->second->conditions.push_back( condition ); if (mProcessingInProgress) condition->onStartConditionProcessing(); - return ConditionConnection(this,actionId,condition); + return ConditionConnection(this,actionId,condition.get()); } //----------------------------------------------------- @@ -789,6 +795,10 @@ //----------------------------------------------------- void ActionMap::start() { + // guard against multiple calls to start(): + if (mProcessingInProgress) + return; + // for (ActionList::const_iterator it = mEntries.begin(); it != mEntries.end(); ++it) { ActionMapEntry* pEntry = it->second.get(); @@ -805,6 +815,10 @@ //----------------------------------------------------- void ActionMap::stop() { + // guard against multiple calls to stop(): + if (!mProcessingInProgress) + return; + // for (ActionList::const_iterator it = mEntries.begin(); it != mEntries.end(); ++it) { ActionMapEntry* pEntry = it->second.get(); Modified: trunk/yake/yake/bindings.lua/bindings.lua.h =================================================================== --- trunk/yake/yake/bindings.lua/bindings.lua.h 2007-08-17 19:20:50 UTC (rev 1796) +++ trunk/yake/yake/bindings.lua/bindings.lua.h 2007-08-18 21:25:29 UTC (rev 1797) @@ -64,6 +64,10 @@ YAKE_BINDINGS_LUA_API void bind_graphics(lua_State*); YAKE_BINDINGS_LUA_API void bind_graphics(scripting::IVM*); #endif +#if YAKE_ENABLE_LUA_INPUT == 1 + YAKE_BINDINGS_LUA_API void bind_input(lua_State*); + YAKE_BINDINGS_LUA_API void bind_input(scripting::IVM*); +#endif #if YAKE_ENABLE_LUA_RAF == 1 YAKE_BINDINGS_LUA_API void bind_raf(lua_State*); YAKE_BINDINGS_LUA_API void bind_raf(scripting::IVM*); Modified: trunk/yake/yake/input/yakeActionMap.h =================================================================== --- trunk/yake/yake/input/yakeActionMap.h 2007-08-17 19:20:50 UTC (rev 1796) +++ trunk/yake/yake/input/yakeActionMap.h 2007-08-18 21:25:29 UTC (rev 1797) @@ -126,7 +126,7 @@ }; enum KeyboardActionMode { - KAM_CONTINUOUS, + KAM_CONTINUOUS = 0, KAM_PRESSED, KAM_RELEASED, KAM_PRESSED_AND_RELEASED @@ -284,6 +284,12 @@ @note Any number of conditions can be registered for a single ActionId. */ ConditionConnection reg( const ActionId & actionId, ActionCondition* condition ); + + /** Add a condition for an action id. + @note Any number of conditions can be registered for a single ActionId. + */ + ConditionConnection reg( const ActionId & actionId, SharedPtr<ActionCondition> condition ); + /*@todo typedef ConditionConnection ConditionConnectionPtr; ConditionConnectionPtr addActionCondition( const ActionId & actionId, ActionCondition* condition ); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-08-18 23:54:07
|
Revision: 1798 http://yake.svn.sourceforge.net/yake/?rev=1798&view=rev Author: psyclonist Date: 2007-08-18 16:54:05 -0700 (Sat, 18 Aug 2007) Log Message: ----------- * [tools] added scripts/tools/extract_input_kc.pl * [bindings.lua] input::KeyCode values can now be batch-extracted by running scripts/tools/extract_input_kc.pl Modified Paths: -------------- trunk/yake/src/bindings.lua/detail/input.lua.cpp trunk/yake/yake/input/yakeInputSystem.h Added Paths: ----------- trunk/yake/scripts/tools/extract_input_kc.pl trunk/yake/yake/bindings.lua/detail/input.lua.keycodes.inl Added: trunk/yake/scripts/tools/extract_input_kc.pl =================================================================== --- trunk/yake/scripts/tools/extract_input_kc.pl (rev 0) +++ trunk/yake/scripts/tools/extract_input_kc.pl 2007-08-18 23:54:05 UTC (rev 1798) @@ -0,0 +1,55 @@ +print "Extracting...\n\n"; + +$FILE = "../../yake/input/yakeInputSystem.h"; +$OUTFILE = ">../../yake/bindings.lua/detail/input.lua.keycodes.inl"; + +open OUT, $OUTFILE or die("Could not open '$OUT'."); + +$FIND = "enum KeyCode"; +$stage = "enumsearch"; + +$luatpl = "luabind::globals(L)[\"yake\"][\"input\"][\"%ID%\"] = %VALUE%;"; + +print($luatpl); + +open(FILE) or die("Could not open '$FILE'."); +foreach $line (<FILE>) { + #print($line); + chomp($line); # remove newline + if ($stage =~ m/enumsearch/) + { + if ($line =~ m/$FIND/) + { + #print("found"); + $stage = "extract"; + } + } + elsif ($stage =~ m/extract/) + { + if ($line =~ m/}/) + { + last; + } + #print($line); + ($id,$value) = split(' ',$line); + if (length($value) == 0) + { + next; + } + # value typically has the form: =0xCA, + #$value =~ s/=//; # remove = + #$value =~ s/,//; # remove , + + $decl = $luatpl; + $decl =~ s/%ID%/$id/; + $decl =~ s/%VALUE%/$id/; + print($decl,"\n"); + print OUT $decl,"\n"; + + #print($id, " => ", $value, "\n"); + print() + } +} +close(FILE); +close(OUT); + Modified: trunk/yake/src/bindings.lua/detail/input.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/input.lua.cpp 2007-08-18 21:25:29 UTC (rev 1797) +++ trunk/yake/src/bindings.lua/detail/input.lua.cpp 2007-08-18 23:54:05 UTC (rev 1798) @@ -196,11 +196,7 @@ luabind::globals(L)["yake"]["input"]["ACTIONID_FIRE2"] = ACTIONID_FIRE2; luabind::globals(L)["yake"]["input"]["ACTIONID_USER"] = ACTIONID_USER; - luabind::globals(L)["yake"]["input"]["KC_ESCAPE"] = KC_ESCAPE; - luabind::globals(L)["yake"]["input"]["KC_LEFT"] = KC_LEFT; - luabind::globals(L)["yake"]["input"]["KC_RIGHT"] = KC_RIGHT; - luabind::globals(L)["yake"]["input"]["KC_UP"] = KC_UP; - luabind::globals(L)["yake"]["input"]["KC_DOWN"] = KC_DOWN; +#include "yake/bindings.lua/detail/input.lua.keycodes.inl" } YAKE_WRAP_BINDER(input,::yake::input::bind); Added: trunk/yake/yake/bindings.lua/detail/input.lua.keycodes.inl =================================================================== --- trunk/yake/yake/bindings.lua/detail/input.lua.keycodes.inl (rev 0) +++ trunk/yake/yake/bindings.lua/detail/input.lua.keycodes.inl 2007-08-18 23:54:05 UTC (rev 1798) @@ -0,0 +1,144 @@ +luabind::globals(L)["yake"]["input"]["KC_ESCAPE"] = KC_ESCAPE; +luabind::globals(L)["yake"]["input"]["KC_1"] = KC_1; +luabind::globals(L)["yake"]["input"]["KC_2"] = KC_2; +luabind::globals(L)["yake"]["input"]["KC_3"] = KC_3; +luabind::globals(L)["yake"]["input"]["KC_4"] = KC_4; +luabind::globals(L)["yake"]["input"]["KC_5"] = KC_5; +luabind::globals(L)["yake"]["input"]["KC_6"] = KC_6; +luabind::globals(L)["yake"]["input"]["KC_7"] = KC_7; +luabind::globals(L)["yake"]["input"]["KC_8"] = KC_8; +luabind::globals(L)["yake"]["input"]["KC_9"] = KC_9; +luabind::globals(L)["yake"]["input"]["KC_0"] = KC_0; +luabind::globals(L)["yake"]["input"]["KC_MINUS"] = KC_MINUS; +luabind::globals(L)["yake"]["input"]["KC_EQUALS"] = KC_EQUALS; +luabind::globals(L)["yake"]["input"]["KC_BACK"] = KC_BACK; +luabind::globals(L)["yake"]["input"]["KC_TAB"] = KC_TAB; +luabind::globals(L)["yake"]["input"]["KC_Q"] = KC_Q; +luabind::globals(L)["yake"]["input"]["KC_W"] = KC_W; +luabind::globals(L)["yake"]["input"]["KC_E"] = KC_E; +luabind::globals(L)["yake"]["input"]["KC_R"] = KC_R; +luabind::globals(L)["yake"]["input"]["KC_T"] = KC_T; +luabind::globals(L)["yake"]["input"]["KC_Y"] = KC_Y; +luabind::globals(L)["yake"]["input"]["KC_U"] = KC_U; +luabind::globals(L)["yake"]["input"]["KC_I"] = KC_I; +luabind::globals(L)["yake"]["input"]["KC_O"] = KC_O; +luabind::globals(L)["yake"]["input"]["KC_P"] = KC_P; +luabind::globals(L)["yake"]["input"]["KC_LBRACKET"] = KC_LBRACKET; +luabind::globals(L)["yake"]["input"]["KC_RBRACKET"] = KC_RBRACKET; +luabind::globals(L)["yake"]["input"]["KC_RETURN"] = KC_RETURN; +luabind::globals(L)["yake"]["input"]["KC_LCONTROL"] = KC_LCONTROL; +luabind::globals(L)["yake"]["input"]["KC_A"] = KC_A; +luabind::globals(L)["yake"]["input"]["KC_S"] = KC_S; +luabind::globals(L)["yake"]["input"]["KC_D"] = KC_D; +luabind::globals(L)["yake"]["input"]["KC_F"] = KC_F; +luabind::globals(L)["yake"]["input"]["KC_G"] = KC_G; +luabind::globals(L)["yake"]["input"]["KC_H"] = KC_H; +luabind::globals(L)["yake"]["input"]["KC_J"] = KC_J; +luabind::globals(L)["yake"]["input"]["KC_K"] = KC_K; +luabind::globals(L)["yake"]["input"]["KC_L"] = KC_L; +luabind::globals(L)["yake"]["input"]["KC_SEMICOLON"] = KC_SEMICOLON; +luabind::globals(L)["yake"]["input"]["KC_APOSTROPHE"] = KC_APOSTROPHE; +luabind::globals(L)["yake"]["input"]["KC_GRAVE"] = KC_GRAVE; +luabind::globals(L)["yake"]["input"]["KC_LSHIFT"] = KC_LSHIFT; +luabind::globals(L)["yake"]["input"]["KC_BACKSLASH"] = KC_BACKSLASH; +luabind::globals(L)["yake"]["input"]["KC_Z"] = KC_Z; +luabind::globals(L)["yake"]["input"]["KC_X"] = KC_X; +luabind::globals(L)["yake"]["input"]["KC_C"] = KC_C; +luabind::globals(L)["yake"]["input"]["KC_V"] = KC_V; +luabind::globals(L)["yake"]["input"]["KC_B"] = KC_B; +luabind::globals(L)["yake"]["input"]["KC_N"] = KC_N; +luabind::globals(L)["yake"]["input"]["KC_M"] = KC_M; +luabind::globals(L)["yake"]["input"]["KC_COMMA"] = KC_COMMA; +luabind::globals(L)["yake"]["input"]["KC_PERIOD"] = KC_PERIOD; +luabind::globals(L)["yake"]["input"]["KC_SLASH"] = KC_SLASH; +luabind::globals(L)["yake"]["input"]["KC_RSHIFT"] = KC_RSHIFT; +luabind::globals(L)["yake"]["input"]["KC_MULTIPLY"] = KC_MULTIPLY; +luabind::globals(L)["yake"]["input"]["KC_LMENU"] = KC_LMENU; +luabind::globals(L)["yake"]["input"]["KC_SPACE"] = KC_SPACE; +luabind::globals(L)["yake"]["input"]["KC_CAPITAL"] = KC_CAPITAL; +luabind::globals(L)["yake"]["input"]["KC_F1"] = KC_F1; +luabind::globals(L)["yake"]["input"]["KC_F2"] = KC_F2; +luabind::globals(L)["yake"]["input"]["KC_F3"] = KC_F3; +luabind::globals(L)["yake"]["input"]["KC_F4"] = KC_F4; +luabind::globals(L)["yake"]["input"]["KC_F5"] = KC_F5; +luabind::globals(L)["yake"]["input"]["KC_F6"] = KC_F6; +luabind::globals(L)["yake"]["input"]["KC_F7"] = KC_F7; +luabind::globals(L)["yake"]["input"]["KC_F8"] = KC_F8; +luabind::globals(L)["yake"]["input"]["KC_F9"] = KC_F9; +luabind::globals(L)["yake"]["input"]["KC_F10"] = KC_F10; +luabind::globals(L)["yake"]["input"]["KC_NUMLOCK"] = KC_NUMLOCK; +luabind::globals(L)["yake"]["input"]["KC_SCROLL"] = KC_SCROLL; +luabind::globals(L)["yake"]["input"]["KC_NUMPAD7"] = KC_NUMPAD7; +luabind::globals(L)["yake"]["input"]["KC_NUMPAD8"] = KC_NUMPAD8; +luabind::globals(L)["yake"]["input"]["KC_NUMPAD9"] = KC_NUMPAD9; +luabind::globals(L)["yake"]["input"]["KC_SUBTRACT"] = KC_SUBTRACT; +luabind::globals(L)["yake"]["input"]["KC_NUMPAD4"] = KC_NUMPAD4; +luabind::globals(L)["yake"]["input"]["KC_NUMPAD5"] = KC_NUMPAD5; +luabind::globals(L)["yake"]["input"]["KC_NUMPAD6"] = KC_NUMPAD6; +luabind::globals(L)["yake"]["input"]["KC_ADD"] = KC_ADD; +luabind::globals(L)["yake"]["input"]["KC_NUMPAD1"] = KC_NUMPAD1; +luabind::globals(L)["yake"]["input"]["KC_NUMPAD2"] = KC_NUMPAD2; +luabind::globals(L)["yake"]["input"]["KC_NUMPAD3"] = KC_NUMPAD3; +luabind::globals(L)["yake"]["input"]["KC_NUMPAD0"] = KC_NUMPAD0; +luabind::globals(L)["yake"]["input"]["KC_DECIMAL"] = KC_DECIMAL; +luabind::globals(L)["yake"]["input"]["KC_OEM_102"] = KC_OEM_102; +luabind::globals(L)["yake"]["input"]["KC_F11"] = KC_F11; +luabind::globals(L)["yake"]["input"]["KC_F12"] = KC_F12; +luabind::globals(L)["yake"]["input"]["KC_F13"] = KC_F13; +luabind::globals(L)["yake"]["input"]["KC_F14"] = KC_F14; +luabind::globals(L)["yake"]["input"]["KC_F15"] = KC_F15; +luabind::globals(L)["yake"]["input"]["KC_KANA"] = KC_KANA; +luabind::globals(L)["yake"]["input"]["KC_ABNT_C1"] = KC_ABNT_C1; +luabind::globals(L)["yake"]["input"]["KC_CONVERT"] = KC_CONVERT; +luabind::globals(L)["yake"]["input"]["KC_NOCONVERT"] = KC_NOCONVERT; +luabind::globals(L)["yake"]["input"]["KC_YEN"] = KC_YEN; +luabind::globals(L)["yake"]["input"]["KC_ABNT_C2"] = KC_ABNT_C2; +luabind::globals(L)["yake"]["input"]["KC_NUMPADEQUALS"] = KC_NUMPADEQUALS; +luabind::globals(L)["yake"]["input"]["KC_PREVTRACK"] = KC_PREVTRACK; +luabind::globals(L)["yake"]["input"]["KC_AT"] = KC_AT; +luabind::globals(L)["yake"]["input"]["KC_COLON"] = KC_COLON; +luabind::globals(L)["yake"]["input"]["KC_UNDERLINE"] = KC_UNDERLINE; +luabind::globals(L)["yake"]["input"]["KC_KANJI"] = KC_KANJI; +luabind::globals(L)["yake"]["input"]["KC_STOP"] = KC_STOP; +luabind::globals(L)["yake"]["input"]["KC_AX"] = KC_AX; +luabind::globals(L)["yake"]["input"]["KC_UNLABELED"] = KC_UNLABELED; +luabind::globals(L)["yake"]["input"]["KC_NEXTTRACK"] = KC_NEXTTRACK; +luabind::globals(L)["yake"]["input"]["KC_NUMPADENTER"] = KC_NUMPADENTER; +luabind::globals(L)["yake"]["input"]["KC_RCONTROL"] = KC_RCONTROL; +luabind::globals(L)["yake"]["input"]["KC_MUTE"] = KC_MUTE; +luabind::globals(L)["yake"]["input"]["KC_CALCULATOR"] = KC_CALCULATOR; +luabind::globals(L)["yake"]["input"]["KC_PLAYPAUSE"] = KC_PLAYPAUSE; +luabind::globals(L)["yake"]["input"]["KC_MEDIASTOP"] = KC_MEDIASTOP; +luabind::globals(L)["yake"]["input"]["KC_VOLUMEDOWN"] = KC_VOLUMEDOWN; +luabind::globals(L)["yake"]["input"]["KC_VOLUMEUP"] = KC_VOLUMEUP; +luabind::globals(L)["yake"]["input"]["KC_WEBHOME"] = KC_WEBHOME; +luabind::globals(L)["yake"]["input"]["KC_NUMPADCOMMA"] = KC_NUMPADCOMMA; +luabind::globals(L)["yake"]["input"]["KC_DIVIDE"] = KC_DIVIDE; +luabind::globals(L)["yake"]["input"]["KC_SYSRQ"] = KC_SYSRQ; +luabind::globals(L)["yake"]["input"]["KC_RMENU"] = KC_RMENU; +luabind::globals(L)["yake"]["input"]["KC_PAUSE"] = KC_PAUSE; +luabind::globals(L)["yake"]["input"]["KC_HOME"] = KC_HOME; +luabind::globals(L)["yake"]["input"]["KC_UP"] = KC_UP; +luabind::globals(L)["yake"]["input"]["KC_PGUP"] = KC_PGUP; +luabind::globals(L)["yake"]["input"]["KC_LEFT"] = KC_LEFT; +luabind::globals(L)["yake"]["input"]["KC_RIGHT"] = KC_RIGHT; +luabind::globals(L)["yake"]["input"]["KC_END"] = KC_END; +luabind::globals(L)["yake"]["input"]["KC_DOWN"] = KC_DOWN; +luabind::globals(L)["yake"]["input"]["KC_PGDOWN"] = KC_PGDOWN; +luabind::globals(L)["yake"]["input"]["KC_INSERT"] = KC_INSERT; +luabind::globals(L)["yake"]["input"]["KC_DELETE"] = KC_DELETE; +luabind::globals(L)["yake"]["input"]["KC_LWIN"] = KC_LWIN; +luabind::globals(L)["yake"]["input"]["KC_RWIN"] = KC_RWIN; +luabind::globals(L)["yake"]["input"]["KC_APPS"] = KC_APPS; +luabind::globals(L)["yake"]["input"]["KC_POWER"] = KC_POWER; +luabind::globals(L)["yake"]["input"]["KC_SLEEP"] = KC_SLEEP; +luabind::globals(L)["yake"]["input"]["KC_WAKE"] = KC_WAKE; +luabind::globals(L)["yake"]["input"]["KC_WEBSEARCH"] = KC_WEBSEARCH; +luabind::globals(L)["yake"]["input"]["KC_WEBFAVORITES"] = KC_WEBFAVORITES; +luabind::globals(L)["yake"]["input"]["KC_WEBREFRESH"] = KC_WEBREFRESH; +luabind::globals(L)["yake"]["input"]["KC_WEBSTOP"] = KC_WEBSTOP; +luabind::globals(L)["yake"]["input"]["KC_WEBFORWARD"] = KC_WEBFORWARD; +luabind::globals(L)["yake"]["input"]["KC_WEBBACK"] = KC_WEBBACK; +luabind::globals(L)["yake"]["input"]["KC_MYCOMPUTER"] = KC_MYCOMPUTER; +luabind::globals(L)["yake"]["input"]["KC_MAIL"] = KC_MAIL; +luabind::globals(L)["yake"]["input"]["KC_MEDIASELECT"] = KC_MEDIASELECT; Modified: trunk/yake/yake/input/yakeInputSystem.h =================================================================== --- trunk/yake/yake/input/yakeInputSystem.h 2007-08-18 21:25:29 UTC (rev 1797) +++ trunk/yake/yake/input/yakeInputSystem.h 2007-08-18 23:54:05 UTC (rev 1798) @@ -36,6 +36,12 @@ // Keyboard scan codes - copied from DirectInput for now for speed. // (SK: actually I copied them from Ogre again...) + // + // NB For the Lua bindings we parse this header and extract the + // key codes. This is done by: scripts/tools/extract_input_kc.pl + // + // If this enum is updated, remember to run this script (and commit + // the changes to the source repository, too)! enum KeyCode { KC_ESCAPE =0x01, This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-08-20 19:53:46
|
Revision: 1801 http://yake.svn.sourceforge.net/yake/?rev=1801&view=rev Author: psyclonist Date: 2007-08-20 12:53:47 -0700 (Mon, 20 Aug 2007) Log Message: ----------- * updated reference to Luabind version Modified Paths: -------------- trunk/yake/BUILD trunk/yake/documentation/manual/yake-manual.txt Modified: trunk/yake/BUILD =================================================================== --- trunk/yake/BUILD 2007-08-19 00:06:49 UTC (rev 1800) +++ trunk/yake/BUILD 2007-08-20 19:53:47 UTC (rev 1801) @@ -84,7 +84,7 @@ * ODE 0.6/0.7 for physicsODE * OGRE 1.4.x+ for graphicsOGRE * Lua 5.x for scriptingLua, entLua etc - * Luabind 0.7+ for scriptingLua, entLua etc + * Luabind (.7+1, i.e. SVN) for scriptingLua, entLua etc * CEGUI 0.5.x * OpenAL 1.1 SDK for audioAL * OpenAL++ Modified: trunk/yake/documentation/manual/yake-manual.txt =================================================================== --- trunk/yake/documentation/manual/yake-manual.txt 2007-08-19 00:06:49 UTC (rev 1800) +++ trunk/yake/documentation/manual/yake-manual.txt 2007-08-20 19:53:47 UTC (rev 1801) @@ -94,7 +94,7 @@ 1. ODE 0.7/0.8 for physicsODE #. OGRE 1.3/1.4 for graphicsOGRE #. Lua 5.x for scriptingLua, entLua etc -#. Luabind 0.7+ for scriptingLua, entLua etc +#. Luabind (0.7+1, i.e. SVN) for scriptingLua, entLua etc #. CEGUI 0.5.x for graphical UI #. OpenAL 1.1 SDK for audioOpenAL #. OpenAL++ for audioOpenAL This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-08-23 22:34:37
|
Revision: 1811 http://yake.svn.sourceforge.net/yake/?rev=1811&view=rev Author: psyclonist Date: 2007-08-23 15:34:37 -0700 (Thu, 23 Aug 2007) Log Message: ----------- * [res] added library 'resource management' * [bindings.lua] added bindings for yake.res (resource management) * [samples] added sample 'res/lua' demonstrating the use of Lua bindings for yake.res * [premake] fixed naming in config.h Modified Paths: -------------- trunk/yake/scripts/premake/config.lua trunk/yake/scripts/premake/samples.lua trunk/yake/scripts/premake/yake.lua trunk/yake/yake/bindings.lua/bindings.lua.h Added Paths: ----------- trunk/yake/common/media/scripts/res1.lua trunk/yake/samples/res/ trunk/yake/samples/res/lua1/ trunk/yake/samples/res/lua1/demo.cpp trunk/yake/src/bindings.lua/detail/res.lua.cpp trunk/yake/src/res/ trunk/yake/src/res/datastream.cpp trunk/yake/src/res/res.cpp trunk/yake/src/res/resource_manager.cpp trunk/yake/src/res/source.cpp trunk/yake/src/res/source_manager.cpp trunk/yake/yake/res/ trunk/yake/yake/res/async_loader.h trunk/yake/yake/res/datastream.h trunk/yake/yake/res/prerequisites.h trunk/yake/yake/res/res.h trunk/yake/yake/res/resource.h trunk/yake/yake/res/resource_manager.h trunk/yake/yake/res/source.h trunk/yake/yake/res/source_manager.h Added: trunk/yake/common/media/scripts/res1.lua =================================================================== --- trunk/yake/common/media/scripts/res1.lua (rev 0) +++ trunk/yake/common/media/scripts/res1.lua 2007-08-23 22:34:37 UTC (rev 1811) @@ -0,0 +1,17 @@ +-- acquire global res::SourceManager +assert( yake.res ) +local res = yake.res +assert( res.global.sourceManager ) +local sourceManager = res.global.sourceManager + +-- add some sources +sourceManager:addSource("file","./") +sourceManager:addSource("file","e:/dev/yake.trunk/yake/scripts/tools/luadocs/") + +-- find resource using sourceManager: +local find = sourceManager:find("project.txt") +if find.valid then + print("found project.txt at: "..find.location) +else + print("could not find project.txt") +end \ No newline at end of file Added: trunk/yake/samples/res/lua1/demo.cpp =================================================================== --- trunk/yake/samples/res/lua1/demo.cpp (rev 0) +++ trunk/yake/samples/res/lua1/demo.cpp 2007-08-23 22:34:37 UTC (rev 1811) @@ -0,0 +1,86 @@ +#include <yake/scripting/yakeScriptingSystem.h> +#include <yake/raf/yakeRaf.h> + +#include <yake/plugins/scriptingLua/ScriptingSystemLua.h> +#include <yake/bindings.lua/bindings.lua.h> +#include <yake/bindings.lua/common/yake.lua.common.h> + +using namespace yake; + +/** Configuration of the application */ +struct TheConfiguration : public raf::ApplicationConfiguration +{ + virtual StringVector getLibraries() + { return MakeStringVector() << YAKE_LIB("scriptingLua"); } + + virtual StringVector getScriptingSystems() + { return MakeStringVector() << "lua"; } +}; + +/** Main application state */ +class TheMainState : public raf::RtMainState +{ +public: + TheMainState(raf::Application& owner) : raf::RtMainState(owner), app_(owner) + { + } +protected: + virtual void onEnter() + { + raf::RtMainState::onEnter(); + } + virtual void onExit() + { + raf::RtMainState::onExit(); + vm_.reset(); + } + virtual void onCreateScene() + { + YAKE_LOG_INFORMATION("demo","Starting"); + + scripting::IScriptingSystem* sys = app_.getScriptingSystem(); + YAKE_ASSERT( sys ); + YAKE_ASSERT( !vm_ ); + vm_ = sys->createVM(); + bind_all(vm_.get()); + + //bind + { + /* + lua_State* L = static_cast<scripting::LuaVM*>(vm_.get())->getLuaState(); + luabind::globals(L)["app"] = &app_; + */ + } + + scripting::ScriptPtr script = sys->createScriptFromFile("../../../common/media/scripts/res1.lua"); + vm_->execute( script ); + + this->requestQuit(); + } + virtual void onFrame(const real timeElapsed) + { + } +private: + raf::Application& app_; + scripting::VMPtr vm_; +}; + +/** The mighty application itself! */ +class TheApp : public raf::ExampleApplication<TheConfiguration> +{ +public: + TheApp() {} +protected: + virtual raf::MainState* createMainState() + { + return new TheMainState(*this); + } +}; + +int main( int argc, char** argv ) +{ + // Use default executor for convenience. + // It's always possible to manually execute TheApp::initialise() etc. + return (raf::runApplication( TheApp() )) ? 0 : 1; +} + Modified: trunk/yake/scripts/premake/config.lua =================================================================== --- trunk/yake/scripts/premake/config.lua 2007-08-23 16:32:21 UTC (rev 1810) +++ trunk/yake/scripts/premake/config.lua 2007-08-23 22:34:37 UTC (rev 1811) @@ -57,7 +57,8 @@ ENABLE_LUA_GRAPHICS = true ENABLE_LUA_PHYSICS = true ENABLE_LUA_INPUT = true -ENABLE_LUA_RAF = true +ENABLE_LUA_RAF = true -- example application framework +ENABLE_LUA_RES = true -- resource management -------------------------------------- -- Samples Modified: trunk/yake/scripts/premake/samples.lua =================================================================== --- trunk/yake/scripts/premake/samples.lua 2007-08-23 16:32:21 UTC (rev 1810) +++ trunk/yake/scripts/premake/samples.lua 2007-08-23 22:34:37 UTC (rev 1811) @@ -90,6 +90,19 @@ end -------------------------------------- +--if SAMPLES_RES then + -------------------------------------- + if ENABLE_LUA_RES then + makeSample("sampleResLuaDemo1","samples/res/lua1") + useComponent("base") + useComponent("res") + useComponent("bindings.lua") + useDep("lua") + useDep("luabind") + end +--end + +-------------------------------------- if SAMPLES_RAF then -------------------------------------- makeSample("sampleRafMinimal","samples/raf/minimal") Modified: trunk/yake/scripts/premake/yake.lua =================================================================== --- trunk/yake/scripts/premake/yake.lua 2007-08-23 16:32:21 UTC (rev 1810) +++ trunk/yake/scripts/premake/yake.lua 2007-08-23 22:34:37 UTC (rev 1811) @@ -75,8 +75,9 @@ f:write("#define YAKE_ENABLE_LUA_PROPERTY " .. bool_to_int(ENABLE_LUA_PROPERTY) .. "\n") f:write("#define YAKE_ENABLE_LUA_GRAPHICS " .. bool_to_int(ENABLE_LUA_GRAPHICS) .. "\n") f:write("#define YAKE_ENABLE_LUA_PHYSICS " .. bool_to_int(ENABLE_LUA_PHYSICS) .. "\n") - f:write("#define ENABLE_LUA_INPUT " .. bool_to_int(ENABLE_LUA_INPUT) .. "\n") + f:write("#define YAKE_ENABLE_LUA_INPUT " .. bool_to_int(ENABLE_LUA_INPUT) .. "\n") f:write("#define YAKE_ENABLE_LUA_RAF " .. bool_to_int(ENABLE_LUA_RAF) .. "\n") + f:write("#define YAKE_ENABLE_LUA_RES " .. bool_to_int(ENABLE_LUA_RES) .. "\n") f:write("\n") f:write("#endif\n") io.close(f) @@ -161,6 +162,10 @@ addDependency("model") -------------------------------------- +makeComponent("res","YAKE_RES_EXPORTS") +addDependency("base") + +-------------------------------------- -- net2 is a header-only library -- For MSVC8: Create project. -- For Linux/GCC: Do not create project. @@ -258,6 +263,9 @@ if ENABLE_LUA_RAF then addDependency("raf") end + if ENABLE_LUA_RES then + addDependency("res") + end if (windows) then --@todo still required? or does this get picked up automatically already? useDep("lua") useDep("luabind") Added: trunk/yake/src/bindings.lua/detail/res.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/res.lua.cpp (rev 0) +++ trunk/yake/src/bindings.lua/detail/res.lua.cpp 2007-08-23 22:34:37 UTC (rev 1811) @@ -0,0 +1,133 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#include <yake/config.h> +#if YAKE_ENABLE_LUA_RES == 1 + +// See task.lua.cpp +#include <yake/bindings.lua/common/yake.lua.shared_ptr.h> + +#include <yake/bindings.lua/bindings.lua.h> // Don't forget to include this for proper dllexport! + +#include <yake/base/templates/yakeSmartAssert.h> +#include <yake/base/yake.h> +#include <yake/res/res.h> + +#include <yake/bindings.lua/detail/private.h> +#include <yake/bindings.lua/common/yake.lua.any_converter.h> + +#include <luabind/discard_result_policy.hpp> +#include <luabind/iterator_policy.hpp> +#include <luabind/operator.hpp> +#include <luabind/adopt_policy.hpp> + +namespace yake { +namespace res { + + void bind( lua_State* L ) + { + YAKE_ASSERT( L ); + if (!L) + return; + + using namespace luabind; + +#define YAKE_RES_MODULE L, "yake" + + module( YAKE_RES_MODULE ) + [ + namespace_("res") + [ + class_<DataStreamBase,DataStreamPtr>("DataStreamBase") + , + class_<ResourceBase,ResourcePtr>("ResourceBase") + , + class_<SourceId>("SourceId") + , + class_<Location>("Location") + , + class_<Source,SourcePtr>("Source") + .def("open",&Source::open) + .def("exists",&Source::exists) + , + class_<SourceFactory>("SourceFactory") + .def("create",&SourceFactory::create) + .scope + [ + def("global",&SourceFactory::global) + ] + , + class_<FindResult>("FindResult") + .def(constructor<>()) + .property("location",&FindResult::location) + .property("source",&FindResult::source) + .property("valid",&FindResult::isValid) + , + class_<SourceManager>("SourceManager") + .def(constructor<>()) + .def("addSource", (void(SourceManager::*)(SourcePtr,const Location&))&SourceManager::addSource) + .def("addSource", (void(SourceManager::*)(const SourceId&,const SourceFactory&,const Location&))&SourceManager::addSource) + .def("addSource", (void(SourceManager::*)(const SourceId&,const Location&))&SourceManager::addSource) + .def("find", &SourceManager::find) + .def("open", (DataStreamPtr(SourceManager::*)(const Location&))&SourceManager::open) + .def("open", (DataStreamPtr(SourceManager::*)(const FindResult&))&SourceManager::open) + .scope + [ + def("global",&SourceFactory::global) + ] + , + class_<ResourceManagerBase>("ResourceManagerBase") + .def("find", &ResourceManagerBase::find) + .def("attach", &ResourceManagerBase::attach) + .def("detach", &ResourceManagerBase::detach, discard_result) + .def("create", (ResourcePtr(ResourceManagerBase::*)(const FindResult&))&ResourceManagerBase::create) + .def("create", (ResourcePtr(ResourceManagerBase::*)(const Location&))&ResourceManagerBase::create) + ] + ]; + { + luabind::object tblGlobal = luabind::newtable(L); + tblGlobal["sourceManager"] = &SourceManager::global(); + tblGlobal["sourceFactory"] = &SourceFactory::global(); + luabind::globals(L)["yake"]["res"]["global"] = tblGlobal; + } + } + + YAKE_WRAP_BINDER(res,::yake::res::bind); + +} // namespace input + void bind_res(lua_State* L) + { + YAKE_ASSERT(L); + res::bind(L); + } + void bind_res(scripting::IVM* vm) + { + scripting::LuaVM* luavm = static_cast<scripting::LuaVM*>(vm); + YAKE_ASSERT( luavm ); + bind_res(luavm->getLuaState()); + } +} // namespace yake +#endif // YAKE_ENABLE_LUA_RES Added: trunk/yake/src/res/datastream.cpp =================================================================== --- trunk/yake/src/res/datastream.cpp (rev 0) +++ trunk/yake/src/res/datastream.cpp 2007-08-23 22:34:37 UTC (rev 1811) @@ -0,0 +1,74 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#include "yake/base/templates/yakeSmartAssert.h" +#include "yake/res/datastream.h" + +#include <fstream> +#include <sys/stat.h> + +namespace yake { +namespace res { + + DataStreamBase::~DataStreamBase() {} + + + FileDataStream::FileDataStream(const std::string & fn) : in_(fn.c_str()), size_(0) + { + assert( in_.is_open() ); + + struct _stat32 s; + const int code = _stat32(fn.c_str(), &s); + assert(code == 0); + size_ = s.st_size; + } + size_t FileDataStream::read(void * out, size_t size) + { + assert( in_.is_open() ); + assert( !eof() ); + if (eof()) + return 0; + // NB use readsome() for async + std::streampos pre = in_.tellg(); + in_.read((char*)(out),std::streampos(size)); //@todo use boost safe numeric cast + return size_t(in_.tellg() - pre); + } + bool FileDataStream::eof() const + { + return in_.is_open() ? in_.eof() : false; + } + size_t FileDataStream::size() const + { + return size_; + } + void FileDataStream::close() + { + if (!in_.is_open()) + in_.close(); + } + +} // namespace res +} // namespace yake Added: trunk/yake/src/res/res.cpp =================================================================== --- trunk/yake/src/res/res.cpp (rev 0) +++ trunk/yake/src/res/res.cpp 2007-08-23 22:34:37 UTC (rev 1811) @@ -0,0 +1,36 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#include "yake/base/templates/yakeSmartAssert.h" +#include "yake/res/res.h" + +namespace yake { +namespace res { + + ResourceBase::~ResourceBase() {} + +} // namespace res +} // namespace yake Added: trunk/yake/src/res/resource_manager.cpp =================================================================== --- trunk/yake/src/res/resource_manager.cpp (rev 0) +++ trunk/yake/src/res/resource_manager.cpp 2007-08-23 22:34:37 UTC (rev 1811) @@ -0,0 +1,80 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#include "yake/base/templates/yakeSmartAssert.h" +#include "yake/res/resource_manager.h" + +namespace yake { +namespace res { + + //----------------------------------------------------- + + ResourceManagerBase::~ResourceManagerBase() {} + + ResourcePtr ResourceManagerBase::create(const FindResult& what) + { + if (!sourceMgr()) + return ResourcePtr(); + DataStreamPtr data = sourceMgr()->open( what ); + if (!data) + return ResourcePtr(); + return this->createAndInitResource( *data ); + } + ResourcePtr ResourceManagerBase::create(const Location& loc) + { + if (!sourceMgr()) + return ResourcePtr(); + DataStreamPtr data = sourceMgr()->open( loc ); + if (!data) + return ResourcePtr(); + return this->createAndInitResource( *data ); + } + FindResult ResourceManagerBase::find(const Location& loc) const + { + if (!sourceMgr_) + return FindResult(); + return sourceMgr_->find(loc); + } + void ResourceManagerBase::attach(SourceManager* mgr) + { + sourceMgr_ = mgr; + } + SourceManager* ResourceManagerBase::detach() + { + SourceManager* mgr = sourceMgr_; + sourceMgr_ = 0; + return mgr; + } + ResourceManagerBase::ResourceManagerBase() : sourceMgr_(&SourceManager::global()) + { + } + SourceManager* ResourceManagerBase::sourceMgr() + { + return sourceMgr_; + } + +} // namespace res +} // namespace yake Added: trunk/yake/src/res/source.cpp =================================================================== --- trunk/yake/src/res/source.cpp (rev 0) +++ trunk/yake/src/res/source.cpp 2007-08-23 22:34:37 UTC (rev 1811) @@ -0,0 +1,83 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#include "yake/base/templates/yakeSmartAssert.h" +#include "yake/res/source.h" + +#include <sys/stat.h> + +namespace yake { +namespace res { + + Source::~Source() {} + + //----------------------------------------------------- + + DataStreamPtr FileSource::open(const res::Location &loc) + { + if (exists(loc)) + return DataStreamPtr(new FileDataStream(loc)); + return DataStreamPtr(); + } + bool FileSource::exists(const Location& loc) const + { + struct _stat32 s; + const int code = _stat32(loc.c_str(), &s); + return (code == 0); + } + + //----------------------------------------------------- + + void SourceFactory::reg(const SourceId& id, CreateSourceFn creator) + { + assert( !id.empty() ); + if (id.empty()) + throw InvalidInputException("id is empty/null"); + assert( creator ); + if (!creator) + throw InvalidInputException("creator function is null"); + creators_[ id ] = creator; + } + SourcePtr SourceFactory::create(const SourceId& id) const + { + CreatorMap::const_iterator it = creators_.find(id); + //assert( it != creators_.end() ); + if (it == creators_.end()) + { + //return SourcePtr(); + throw UnknownResourceSourceTypeException(id); + } + assert( it->second ); + return SourcePtr(it->second()); + } + SourceFactory& SourceFactory::global() + { + static SourceFactory s_sourceFactory; + return s_sourceFactory; + } + +} // namespace res +} // namespace yake Added: trunk/yake/src/res/source_manager.cpp =================================================================== --- trunk/yake/src/res/source_manager.cpp (rev 0) +++ trunk/yake/src/res/source_manager.cpp 2007-08-23 22:34:37 UTC (rev 1811) @@ -0,0 +1,101 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#include "yake/base/templates/yakeSmartAssert.h" +#include "yake/res/source_manager.h" + +namespace yake { +namespace res { + + //----------------------------------------------------- + + SourceManager::SourceManager() + { + } + void SourceManager::addSource(SourcePtr source, const Location& locBase) + { + sources_[ locBase ] = source; + } + void SourceManager::addSource(const SourceId& id, const SourceFactory& factory, const Location& locBase) + { + SourcePtr source = factory.create( id ); + assert( source ); + addSource( source, locBase ); + } + void SourceManager::addSource(const SourceId& id, const Location& locBase) + { + addSource( id, SourceFactory::global(), locBase ); + } + FindResult SourceManager::find(const Location& loc) const + { + for (SourceMap::const_iterator it = sources_.begin(); it != sources_.end(); ++it) + { + const Location& locBase = it->first; + SourcePtr src = it->second; + const Location locToTest = locBase + loc; + if (src->exists(locToTest)) + { + assert( it->second ); + return FindResult( locToTest, src ); + } + } + return FindResult(); + } + DataStreamPtr SourceManager::open(const FindResult& what) + { + assert( what.isValid() ); + if (!what.isValid()) + return DataStreamPtr(); + assert( what.source_ != 0 ); + assert( !what.location_.empty() ); + DataStreamPtr stream = what.source_->open( what.location_ ); + assert( stream && "failed to open data stream" ); + return stream; + } + DataStreamPtr SourceManager::open(const Location& loc) + { + for (SourceMap::const_iterator it = sources_.begin(); it != sources_.end(); ++it) + { + const Location& locBase = it->first; + SourcePtr src = it->second; + const Location locToTest = locBase + loc; + if (src->exists(locToTest)) + { + assert( it->second ); + DataStreamPtr stream = it->second->open(locToTest); + return stream; + } + } + return DataStreamPtr(); + } + SourceManager& SourceManager::global() + { + static SourceManager s_sourceMgr; + return s_sourceMgr; + } + +} // namespace res +} // namespace yake Modified: trunk/yake/yake/bindings.lua/bindings.lua.h =================================================================== --- trunk/yake/yake/bindings.lua/bindings.lua.h 2007-08-23 16:32:21 UTC (rev 1810) +++ trunk/yake/yake/bindings.lua/bindings.lua.h 2007-08-23 22:34:37 UTC (rev 1811) @@ -72,6 +72,10 @@ YAKE_BINDINGS_LUA_API void bind_raf(lua_State*); YAKE_BINDINGS_LUA_API void bind_raf(scripting::IVM*); #endif +#if YAKE_ENABLE_LUA_RES == 1 + YAKE_BINDINGS_LUA_API void bind_res(lua_State*); + YAKE_BINDINGS_LUA_API void bind_res(scripting::IVM*); +#endif } // namespace yake #endif Added: trunk/yake/yake/res/async_loader.h =================================================================== --- trunk/yake/yake/res/async_loader.h (rev 0) +++ trunk/yake/yake/res/async_loader.h 2007-08-23 22:34:37 UTC (rev 1811) @@ -0,0 +1,60 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#ifndef YAKE_RES_ASYNCLOADER_H +#define YAKE_RES_ASYNCLOADER_H + +#include "prerequisites.h" +#include "source.h" + +namespace yake { +namespace res { + + typedef int TicketId; + struct AsyncLoaderManager : public noncopyable //@todo move into "detail"? + { + typedef boost::function<void(const Location&,DataStreamPtr)> HandlerFn; + + template<typename Handler> + TicketId async_open(Location loc, Handler handler) + { + io_.post( boost::bind(&AsyncLoaderManager::onOpen,loc,handler) ) + } + private: + void onOpen(const Location& loc, const HandlerFn& handler) + { + DataStreamPtr stream; // = ? + if (handler) + handler(loc,stream); + } + private: + boost::asio::io_service io_; + }; + +} // namespace res +} // namespace yake + +#endif Added: trunk/yake/yake/res/datastream.h =================================================================== --- trunk/yake/yake/res/datastream.h (rev 0) +++ trunk/yake/yake/res/datastream.h 2007-08-23 22:34:37 UTC (rev 1811) @@ -0,0 +1,70 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#ifndef YAKE_RES_DATASTREAM_H +#define YAKE_RES_DATASTREAM_H + +#include "prerequisites.h" +#include <fstream> +#include <boost/shared_ptr.hpp> + +namespace yake { +namespace res { + + /** Basic interface for data streams. + */ + struct YAKE_RES_API DataStreamBase : public noncopyable + { + virtual ~DataStreamBase() = 0; + + virtual size_t read(void*,size_t) = 0; + virtual bool eof() const = 0; + //virtual size_t tell() const = 0; + //virtual void skip(const size_t) = 0; + virtual size_t size() const = 0; + virtual void close() = 0; + }; + typedef boost::shared_ptr<DataStreamBase> DataStreamPtr; + + /** Implements the data stream interface for files. + */ + struct YAKE_RES_API FileDataStream : public DataStreamBase + { + FileDataStream(const std::string&); + + virtual size_t read(void*,size_t); + virtual bool eof() const; + virtual size_t size() const; + virtual void close(); + private: + std::ifstream in_; + size_t size_; //@todo fails if file is modified during read! + }; + +} // namespace res +} // namespace yake + +#endif Added: trunk/yake/yake/res/prerequisites.h =================================================================== --- trunk/yake/yake/res/prerequisites.h (rev 0) +++ trunk/yake/yake/res/prerequisites.h 2007-08-23 22:34:37 UTC (rev 1811) @@ -0,0 +1,48 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#ifndef YAKE_RES_PREREQUISITES_H +#define YAKE_RES_PREREQUISITES_H + +#include <yake/config.h> +#include <yake/base/yakePrerequisites.h> +#include <yake/base/yakeException.h> +#include <yake/base/yakeNoncopyable.h> + +#if defined(YAKE_RES_EXPORTS) +# define YAKE_RES_API YAKE_EXPORT_API +#else +# define YAKE_RES_API YAKE_IMPORT_API +#endif + +namespace yake { + YAKE_DEFINE_EXCEPTION(UnknownResourceSourceTypeException); +namespace res { + +} // namespace res +} // namespace yake + +#endif Added: trunk/yake/yake/res/res.h =================================================================== --- trunk/yake/yake/res/res.h (rev 0) +++ trunk/yake/yake/res/res.h 2007-08-23 22:34:37 UTC (rev 1811) @@ -0,0 +1,43 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#ifndef YAKE_RES_H +#define YAKE_RES_H + +#include "prerequisites.h" +#include "datastream.h" +#include "resource.h" +#include "source.h" +#include "source_manager.h" +#include "resource_manager.h" + +namespace yake { +namespace res { + +} // namespace res +} // namespace yake + +#endif Added: trunk/yake/yake/res/resource.h =================================================================== --- trunk/yake/yake/res/resource.h (rev 0) +++ trunk/yake/yake/res/resource.h 2007-08-23 22:34:37 UTC (rev 1811) @@ -0,0 +1,57 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#ifndef YAKE_RES_RESOURCE_H +#define YAKE_RES_RESOURCE_H + +#include "prerequisites.h" +#include <boost/shared_ptr.hpp> + +namespace yake { +namespace res { + + /** Base class for resource. */ + struct YAKE_RES_API ResourceBase : public noncopyable + { + virtual ~ResourceBase() = 0; + + typedef boost::shared_ptr<ResourceBase> pointer; + }; + typedef ResourceBase::pointer ResourcePtr; + + /** Optional intermediate class for user-defined resource types. + It provides information in a common way. + */ + template<typename T> + struct Resource : public ResourceBase + { + typedef T resource_type; + }; + +} // namespace res +} // namespace yake + +#endif Added: trunk/yake/yake/res/resource_manager.h =================================================================== --- trunk/yake/yake/res/resource_manager.h (rev 0) +++ trunk/yake/yake/res/resource_manager.h 2007-08-23 22:34:37 UTC (rev 1811) @@ -0,0 +1,86 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#ifndef YAKE_RES_RESOURCEMANAGER_H +#define YAKE_RES_RESOURCEMANAGER_H + +#include "prerequisites.h" +#include "source_manager.h" +#include "resource.h" + +namespace yake { +namespace res { + + /** Base class for resource managers. + This base class handles most of the dirty work (like + finding files/locations, opening data streams etc) + and provides a hook for derived classes to create + and initialize custom resources from data streams. + Derived classes have to override createAndInitResource(). + + For finding sources any instance of a ResourceManager + by default uses the global SourceManager. + A custom SourceManager can be specified + with attach(). + */ + struct YAKE_RES_API ResourceManagerBase : public noncopyable + { + virtual ~ResourceManagerBase() = 0; + + //virtual TicketId async_create(const Location&) = 0; + ResourcePtr create(const FindResult& what); + ResourcePtr create(const Location& loc); + FindResult find(const Location& loc) const; + void attach(SourceManager* mgr); + SourceManager* detach(); + private: + virtual ResourcePtr createAndInitResource(DataStreamBase& data) = 0; + protected: + ResourceManagerBase(); + SourceManager* sourceMgr(); + private: + SourceManager* sourceMgr_; + }; + + template<typename T> + struct ResourceManager : public ResourceManagerBase + { + typedef boost::shared_ptr<T> res_pointer; + public: + res_pointer create(const Location& loc) + { + return boost::static_pointer_cast<T>( ResourceManagerBase::create(loc) ); + } + res_pointer create(const FindResult& loc) + { + return boost::static_pointer_cast<T>( ResourceManagerBase::create(loc) ); + } + }; + +} // namespace res +} // namespace yake + +#endif Added: trunk/yake/yake/res/source.h =================================================================== --- trunk/yake/yake/res/source.h (rev 0) +++ trunk/yake/yake/res/source.h 2007-08-23 22:34:37 UTC (rev 1811) @@ -0,0 +1,111 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#ifndef YAKE_RES_SOURCE_H +#define YAKE_RES_SOURCE_H + +#include "prerequisites.h" +#include "datastream.h" +#include <deque> +#include <boost/shared_ptr.hpp> +#include <boost/function.hpp> + +namespace yake { +namespace res { + + /** ID of a ResourceSource in a ResourceFactory. + Such IDs are unique only within a given ResourceFactory. + */ + typedef std::string SourceId; + + /** Represents a location of a resource. + The string can be anything that ResourceSource's can handle. + */ + typedef std::string Location; + typedef std::deque<Location> LocationList; + + /** Interface for resource sources for querying information + on possible locations and opening data streams. + */ + struct YAKE_RES_API Source : public noncopyable + { + virtual ~Source() = 0; + virtual DataStreamPtr open(const Location&) = 0; + virtual bool exists(const Location&) const = 0; + //virtual LocationList list(/*const bool recursive = false*/) = 0; + }; + typedef boost::shared_ptr<Source> SourcePtr; + + /** Implements a resource source for files using the OS's file system + functionality (mostly through C++ streams). + */ + struct YAKE_RES_API FileSource : public Source + { + virtual DataStreamPtr open(const Location& loc); + virtual bool exists(const Location&) const; + + static Source* create() + { return new FileSource(); } + }; + + /** Implements a factory for ResourceSources. + Any number of factories can be created, but + to ease use in applications a single global + SourceFactory can be accessed through + SourceFactory::global(). + + @see Source + */ + struct YAKE_RES_API SourceFactory : public noncopyable + { + typedef boost::function<Source*()> CreateSourceFn; + + // @exception InvalidParameterException + void reg(const SourceId& id, CreateSourceFn creator); + + // @exception InvalidParameterException + template<typename T> + void reg(const SourceId& id) + { + assert( !id.empty() ); + if (id.empty()) + throw InvalidParameterException("id is empty/null"); + creators_[ id ] = boost::bind(&T::create); + } + + // @exception UnknownSourceTypeException + SourcePtr create(const SourceId& id) const; + // Helper: + static SourceFactory& global(); + private: + typedef std::map<SourceId,CreateSourceFn> CreatorMap; + CreatorMap creators_; + }; + +} // namespace res +} // namespace yake + +#endif Added: trunk/yake/yake/res/source_manager.h =================================================================== --- trunk/yake/yake/res/source_manager.h (rev 0) +++ trunk/yake/yake/res/source_manager.h 2007-08-23 22:34:37 UTC (rev 1811) @@ -0,0 +1,113 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#ifndef YAKE_RES_SOURCEMANAGER_H +#define YAKE_RES_SOURCEMANAGER_H + +#include "prerequisites.h" +#include "source.h" + +namespace yake { +namespace res { + + struct SourceManager; + struct ResourceManagerBase; + /** Contains information about the result of a 'find resource location' + operation. + @code + // Using a SourceManager: + FindResult findinfo = sourceMgr.find("myfile.txt"); + if (findinfo) + DataStreamPtr data = sourceMgr.open(findinfo); + @codeend + @code + // Using a ResourceManager: + FindResult findinfo = resourceMgr.find("myfile.txt"); + if (findinfo) + ResourcePtr res = resourceMgr.create(findinfo); + @codeend + */ + struct FindResult + { + friend struct SourceManager; + friend struct ResourceManagerBase; + private: + Location location_; + SourcePtr source_; //@todo use weak ptr? + public: + bool isValid() const + { + return (source_ != 0 && !location_.empty()); + } + operator bool() const + { + return isValid(); + } + FindResult() + { + } + const Location& location() const + { + return location_; + } + SourcePtr source() const + { + return source_; + } + private: + FindResult(const Location& loc, SourcePtr src) : location_(loc), source_(src) + { + } + }; + + /** Manages resource sources by Location base and SourceId and provides + functionality to search for 'locations/files' and open data streams. + + While it's possible to create any number of SourceManagers, + for simple uses there's also a global instance available through + SourceManager::global(). + */ + struct YAKE_RES_API SourceManager : public noncopyable + { + SourceManager(); + void addSource(SourcePtr source, const Location& locBase); + // @exception see SourceFactory::create() + void addSource(const SourceId& id, const SourceFactory& factory, const Location& locBase); + void addSource(const SourceId& id, const Location& locBase); + FindResult find(const Location& loc) const; + DataStreamPtr open(const FindResult& what); + DataStreamPtr open(const Location& loc); + // Helper: + static SourceManager& global(); + private: + typedef std::map<Location,SourcePtr> SourceMap; + SourceMap sources_; + }; + +} // namespace res +} // namespace yake + +#endif This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-08-23 23:25:11
|
Revision: 1812 http://yake.svn.sourceforge.net/yake/?rev=1812&view=rev Author: psyclonist Date: 2007-08-23 16:25:11 -0700 (Thu, 23 Aug 2007) Log Message: ----------- * [samples] fixed configuration for 'res/lua1' * [res] fixed typoes and invalid type name * [scripting.lua] scripting::LuaScript can now be used as a Resource * [scripting.lua] scripting::LuaScriptManager manages LuaScript resources Modified Paths: -------------- trunk/yake/common/media/scripts/res1.lua trunk/yake/samples/res/lua1/demo.cpp trunk/yake/scripts/premake/plugins.lua trunk/yake/scripts/premake/samples.lua trunk/yake/src/bindings.lua/bindings.lua.cpp trunk/yake/src/bindings.lua/detail/res.lua.cpp trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp trunk/yake/src/res/source_manager.cpp trunk/yake/yake/plugins/scriptingLua/ScriptingSystemLua.h trunk/yake/yake/res/source.h trunk/yake/yake/scripting/yakeScriptingSystem.h Modified: trunk/yake/common/media/scripts/res1.lua =================================================================== --- trunk/yake/common/media/scripts/res1.lua 2007-08-23 22:34:37 UTC (rev 1811) +++ trunk/yake/common/media/scripts/res1.lua 2007-08-23 23:25:11 UTC (rev 1812) @@ -1,14 +1,17 @@ -- acquire global res::SourceManager +print("acquire SourceManager") assert( yake.res ) local res = yake.res assert( res.global.sourceManager ) local sourceManager = res.global.sourceManager -- add some sources +print("add sources") sourceManager:addSource("file","./") -sourceManager:addSource("file","e:/dev/yake.trunk/yake/scripts/tools/luadocs/") +sourceManager:addSource("file","../../../scripts/tools/luadocs/") -- find resource using sourceManager: +print("locate project.txt...") local find = sourceManager:find("project.txt") if find.valid then print("found project.txt at: "..find.location) Modified: trunk/yake/samples/res/lua1/demo.cpp =================================================================== --- trunk/yake/samples/res/lua1/demo.cpp 2007-08-23 22:34:37 UTC (rev 1811) +++ trunk/yake/samples/res/lua1/demo.cpp 2007-08-23 23:25:11 UTC (rev 1812) @@ -5,6 +5,8 @@ #include <yake/bindings.lua/bindings.lua.h> #include <yake/bindings.lua/common/yake.lua.common.h> +#include <yake/res/res.h> + using namespace yake; /** Configuration of the application */ @@ -17,32 +19,20 @@ { return MakeStringVector() << "lua"; } }; -/** Main application state */ -class TheMainState : public raf::RtMainState +/** The mighty application itself! */ +class TheApp : public raf::ExampleApplication<TheConfiguration> { public: - TheMainState(raf::Application& owner) : raf::RtMainState(owner), app_(owner) - { - } + TheApp() {} protected: - virtual void onEnter() + virtual bool onRun() { - raf::RtMainState::onEnter(); - } - virtual void onExit() - { - raf::RtMainState::onExit(); - vm_.reset(); - } - virtual void onCreateScene() - { YAKE_LOG_INFORMATION("demo","Starting"); - scripting::IScriptingSystem* sys = app_.getScriptingSystem(); + scripting::IScriptingSystem* sys = getScriptingSystem("lua"); YAKE_ASSERT( sys ); - YAKE_ASSERT( !vm_ ); - vm_ = sys->createVM(); - bind_all(vm_.get()); + scripting::VMPtr vm = sys->createVM(); + bind_all(vm.get()); //bind { @@ -51,32 +41,27 @@ luabind::globals(L)["app"] = &app_; */ } + // + res::SourceFactory::global().reg<res::FileSource>("file"); + res::SourceManager::global().addSource("file","../../../common/media/scripts/"); - scripting::ScriptPtr script = sys->createScriptFromFile("../../../common/media/scripts/res1.lua"); - vm_->execute( script ); + //scripting::LuaScriptManager::global().create("res1.lua"); + //res::SourceManager::global().find("res1.lua"); + // + try + { + scripting::ScriptPtr script = sys->createScriptFromFile("res1.lua"); + vm->execute( script ); + } + catch (Exception& ex) + { + YAKE_LOG_INFORMATION("demo",ex.what()); + } - this->requestQuit(); + return true; } - virtual void onFrame(const real timeElapsed) - { - } -private: - raf::Application& app_; - scripting::VMPtr vm_; }; -/** The mighty application itself! */ -class TheApp : public raf::ExampleApplication<TheConfiguration> -{ -public: - TheApp() {} -protected: - virtual raf::MainState* createMainState() - { - return new TheMainState(*this); - } -}; - int main( int argc, char** argv ) { // Use default executor for convenience. Modified: trunk/yake/scripts/premake/plugins.lua =================================================================== --- trunk/yake/scripts/premake/plugins.lua 2007-08-23 22:34:37 UTC (rev 1811) +++ trunk/yake/scripts/premake/plugins.lua 2007-08-23 23:25:11 UTC (rev 1812) @@ -42,6 +42,7 @@ -------------------------------------- makeComponentPlugin("scriptingLua","YAKE_SCRIPTINGLUA_EXPORTS") addDependency("base") +addDependency("res") addDependency("scripting") if (windows) then Modified: trunk/yake/scripts/premake/samples.lua =================================================================== --- trunk/yake/scripts/premake/samples.lua 2007-08-23 22:34:37 UTC (rev 1811) +++ trunk/yake/scripts/premake/samples.lua 2007-08-23 23:25:11 UTC (rev 1812) @@ -94,6 +94,7 @@ -------------------------------------- if ENABLE_LUA_RES then makeSample("sampleResLuaDemo1","samples/res/lua1") + sampleUsesConsole() useComponent("base") useComponent("res") useComponent("bindings.lua") Modified: trunk/yake/src/bindings.lua/bindings.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/bindings.lua.cpp 2007-08-23 22:34:37 UTC (rev 1811) +++ trunk/yake/src/bindings.lua/bindings.lua.cpp 2007-08-23 23:25:11 UTC (rev 1812) @@ -88,6 +88,9 @@ #if YAKE_ENABLE_LUA_RAF == 1 bind_raf(L); #endif +#if YAKE_ENABLE_LUA_RES == 1 + bind_res(L); +#endif } void bind_all(scripting::IVM* vm) { Modified: trunk/yake/src/bindings.lua/detail/res.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/res.lua.cpp 2007-08-23 22:34:37 UTC (rev 1811) +++ trunk/yake/src/bindings.lua/detail/res.lua.cpp 2007-08-23 23:25:11 UTC (rev 1812) @@ -64,11 +64,11 @@ class_<DataStreamBase,DataStreamPtr>("DataStreamBase") , class_<ResourceBase,ResourcePtr>("ResourceBase") + //, + //class_<SourceId>("SourceId") + //, + //class_<Location>("Location") , - class_<SourceId>("SourceId") - , - class_<Location>("Location") - , class_<Source,SourcePtr>("Source") .def("open",&Source::open) .def("exists",&Source::exists) Modified: trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp =================================================================== --- trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp 2007-08-23 22:34:37 UTC (rev 1811) +++ trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp 2007-08-23 23:25:11 UTC (rev 1812) @@ -120,17 +120,24 @@ YAKE_ASSERT( pScript ); std::string err; try { - YAKE_ASSERT( pScript->getCreator()->getLanguage() == scripting::IScriptingSystem::L_LUA ); - if ( ( pScript->getCreator()->getLanguage() != scripting::IScriptingSystem::L_LUA ) || - ( 0 == mLuaState ) ) + //YAKE_ASSERT( pScript->getCreator()->getLanguage() == scripting::IScriptingSystem::L_LUA ); + //if ( ( pScript->getCreator()->getLanguage() != scripting::IScriptingSystem::L_LUA ) || + // ( 0 == mLuaState ) ) + // return; + YAKE_ASSERT( dynamic_cast<LuaScript*>(pScript.get()) != 0 ).debug("incompatible language"); + if (dynamic_cast<LuaScript*>(pScript.get()) == 0) return; LuaScript* pLuaScript = static_cast<LuaScript*>( pScript.get() ); - const String& rFileName = pLuaScript->getData(); + const LuaScript::CodeBuffer& code = pLuaScript->getData(); + if (code.empty()) + return; //nothing to do lua_pushcclosure(mLuaState, &pcall_handler, 0); - if (luaL_loadfile(mLuaState, rFileName.c_str())) + //if (luaL_loadbuffer(mLuaState,(const char*)&code[0],code.size(),"buffer")) + if (luaL_loadstring(mLuaState,(const char*)&code[0])) + //if (luaL_loadfile(mLuaState, rFileName.c_str())) { err = lua_tostring(mLuaState, -1); lua_pop(mLuaState, 2); // pop 2: cclosure and error string @@ -199,17 +206,13 @@ //------------------------------------------------------ ScriptPtr ScriptingSystemLua::createScriptFromFile( const String & rFile ) { - ScriptPtr script( new LuaScript(this/*this->shared_from_this()*/) ); - - script->setData( rFile ); - + ScriptPtr script = LuaScriptManager::global().create( rFile ); return script; } //------------------------------------------------------ - LuaScript::LuaScript( ScriptingSystemLua* pCreator ) : mCreator( pCreator ) + LuaScript::LuaScript() { - YAKE_ASSERT( mCreator ).debug( "creator scripting system undefined!" ); } //------------------------------------------------------ @@ -218,29 +221,64 @@ } //------------------------------------------------------ - const IScriptingSystem* LuaScript::getCreator() const - { - return mCreator; - } - - //------------------------------------------------------ bool LuaScript::isLoaded() { - return mFileName.size() != 0; + return !mCode.empty(); } //------------------------------------------------------ void LuaScript::setData( const String& rData ) { - mFileName = rData; + if (rData.empty()) + { + mCode.clear(); + return; + } + mCode.resize( (rData.size()+1) * sizeof(String::value_type) ); + memcpy( &mCode[0], rData.c_str(), rData.size() * sizeof(String::value_type) ); + mCode[ rData.size() ] = '\0'; } + void LuaScript::setData(const yake::uint8 *data, const size_t length) + { + if (length == 0 || !data) + { + mCode.clear(); + return; + } + mCode.resize(length); + memcpy( &mCode[0], data, length ); + } + uint8* LuaScript::resizeData(const size_t length) + { + mCode.resize(length); + if (mCode.empty()) + return 0; + return &mCode[0]; + } //------------------------------------------------------ - const String& LuaScript::getData() const + const LuaScript::CodeBuffer& LuaScript::getData() const { - return mFileName; + return mCode; } + //------------------------------------------------------ + LuaScriptManager& LuaScriptManager::global() + { + static LuaScriptManager s_global; + return s_global; + } + res::ResourcePtr LuaScriptManager::createAndInitResource(res::DataStreamBase& data) + { + boost::shared_ptr<LuaScript> script( new LuaScript() ); + uint8* code = script->resizeData( data.size() ); + YAKE_ASSERT( code != 0 ).debug("stream empty? no data to fill the code buffer with."); + if (!code) + return res::ResourcePtr(); + data.read(code,data.size()); + return script; + } + //------------------------------------------------------ LuaThread::LuaThread(lua_State* parent) : parent_(parent), state_(0), parentRef_(-1) { parentRef_ = luaL_ref( parent, LUA_REGISTRYINDEX ); Modified: trunk/yake/src/res/source_manager.cpp =================================================================== --- trunk/yake/src/res/source_manager.cpp 2007-08-23 22:34:37 UTC (rev 1811) +++ trunk/yake/src/res/source_manager.cpp 2007-08-23 23:25:11 UTC (rev 1812) @@ -89,6 +89,7 @@ return stream; } } + assert( false && "failed to open data stream: could not locate" ); return DataStreamPtr(); } SourceManager& SourceManager::global() Modified: trunk/yake/yake/plugins/scriptingLua/ScriptingSystemLua.h =================================================================== --- trunk/yake/yake/plugins/scriptingLua/ScriptingSystemLua.h 2007-08-23 22:34:37 UTC (rev 1811) +++ trunk/yake/yake/plugins/scriptingLua/ScriptingSystemLua.h 2007-08-23 23:25:11 UTC (rev 1812) @@ -31,6 +31,7 @@ #include <boost/enable_shared_from_this.hpp> #include <boost/shared_ptr.hpp> #include <boost/noncopyable.hpp> +#include <yake/res/res.h> #if defined( YAKE_SCRIPTINGLUA_EXPORTS ) # define YAKE_SCRIPTINLUA_API YAKE_EXPORT_API @@ -149,25 +150,31 @@ }; //---------------------------------------------------- - class YAKE_SCRIPTINLUA_API LuaScript : public scripting::IScript + class YAKE_SCRIPTINLUA_API LuaScript : public res::Resource<LuaScript>, public scripting::IScript { public: - LuaScript( ScriptingSystemLua* pCreator ); + LuaScript(); virtual ~LuaScript(); - /** Get a pointer to the scripting system that - created this IScript object. - */ - virtual const IScriptingSystem* getCreator() const; + typedef std::vector<uint8> CodeBuffer; + virtual bool isLoaded(); virtual void setData( const String& rData ); + virtual void setData( const uint8* data, const size_t length ); + const CodeBuffer& getData() const; + uint8* resizeData(const size_t length); - const String& getData() const; + private: + CodeBuffer mCode; + }; + //---------------------------------------------------- + struct YAKE_SCRIPTINLUA_API LuaScriptManager : public res::ResourceManager<LuaScript> + { private: - String mFileName; - //SharedPtr<ScriptingSystemLua> mCreator; // to avoid destruction of system when VMs are still active - ScriptingSystemLua* mCreator; + virtual res::ResourcePtr createAndInitResource(res::DataStreamBase& data); + public: + static LuaScriptManager& global(); }; //---------------------------------------------------- @@ -186,6 +193,7 @@ lua_State* state_; }; + } // scripting } // yake #endif Modified: trunk/yake/yake/res/source.h =================================================================== --- trunk/yake/yake/res/source.h 2007-08-23 22:34:37 UTC (rev 1811) +++ trunk/yake/yake/res/source.h 2007-08-23 23:25:11 UTC (rev 1812) @@ -92,7 +92,7 @@ { assert( !id.empty() ); if (id.empty()) - throw InvalidParameterException("id is empty/null"); + throw InvalidInputException("id is empty/null"); creators_[ id ] = boost::bind(&T::create); } Modified: trunk/yake/yake/scripting/yakeScriptingSystem.h =================================================================== --- trunk/yake/yake/scripting/yakeScriptingSystem.h 2007-08-23 22:34:37 UTC (rev 1811) +++ trunk/yake/yake/scripting/yakeScriptingSystem.h 2007-08-23 23:25:11 UTC (rev 1812) @@ -100,7 +100,7 @@ /** Get a pointer to the scripting system that created this IScript object. */ - virtual const IScriptingSystem* getCreator() const = 0; + //virtual const IScriptingSystem* getCreator() const = 0; virtual bool isLoaded() = 0; virtual void setData( const String & data ) = 0; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-08-23 23:26:39
|
Revision: 1813 http://yake.svn.sourceforge.net/yake/?rev=1813&view=rev Author: psyclonist Date: 2007-08-23 16:26:41 -0700 (Thu, 23 Aug 2007) Log Message: ----------- * [raf] made code more reliable / avoid crashes :) * [base] removed references to deprecated IOutputStream * [various] fixed includes (added missing ones - under certain include conditions) Modified Paths: -------------- trunk/yake/src/raf/yakeRtApplicationState.cpp trunk/yake/yake/base/math/yakeColor.h trunk/yake/yake/base/math/yakeColor.inl trunk/yake/yake/graphics/yakeGraphicalWorld.h trunk/yake/yake/input/yakeInputSystem.h trunk/yake/yake/physics/yakePhysicsCommon.h Modified: trunk/yake/src/raf/yakeRtApplicationState.cpp =================================================================== --- trunk/yake/src/raf/yakeRtApplicationState.cpp 2007-08-23 23:25:11 UTC (rev 1812) +++ trunk/yake/src/raf/yakeRtApplicationState.cpp 2007-08-23 23:26:41 UTC (rev 1813) @@ -44,7 +44,8 @@ {} graphics::ICamera* RtMainState::onCreateDefaultCamera() { - return getGraphicalWorld()->createCamera(); + graphics::IWorld* w = getGraphicalWorld(); + return w ? w->createCamera() : 0; } graphics::IViewport* RtMainState::onCreateDefaultViewport() { @@ -185,7 +186,9 @@ if (!mGWorld.get()) { graphics::IGraphicsSystem* pSys = getApp().getGraphicsSystem(); - YAKE_ASSERT( pSys ); + YAKE_ASSERT( pSys ).debug("no graphics system available"); + if (!pSys) + return 0; mGWorld = pSys->createWorld(); } if (!mGWorld.get()) Modified: trunk/yake/yake/base/math/yakeColor.h =================================================================== --- trunk/yake/yake/base/math/yakeColor.h 2007-08-23 23:25:11 UTC (rev 1812) +++ trunk/yake/yake/base/math/yakeColor.h 2007-08-23 23:26:41 UTC (rev 1813) @@ -97,7 +97,7 @@ real getSquaredLength() const; // The Serialization Function. - base::IOutputStream& operator << (base::IOutputStream& rStream) const; + //base::IOutputStream& operator << (base::IOutputStream& rStream) const; // The Data. union Modified: trunk/yake/yake/base/math/yakeColor.inl =================================================================== --- trunk/yake/yake/base/math/yakeColor.inl 2007-08-23 23:25:11 UTC (rev 1812) +++ trunk/yake/yake/base/math/yakeColor.inl 2007-08-23 23:26:41 UTC (rev 1813) @@ -239,6 +239,7 @@ return ( r * r ) + ( g * g ) + ( b * b ) + ( a * a ); } +/* inline base::IOutputStream& Color::operator << (base::IOutputStream& rStream) const { rStream << r; @@ -247,6 +248,7 @@ rStream << a; return rStream; } +*/ } // math } // yake Modified: trunk/yake/yake/graphics/yakeGraphicalWorld.h =================================================================== --- trunk/yake/yake/graphics/yakeGraphicalWorld.h 2007-08-23 23:25:11 UTC (rev 1812) +++ trunk/yake/yake/graphics/yakeGraphicalWorld.h 2007-08-23 23:26:41 UTC (rev 1813) @@ -34,6 +34,10 @@ #include <yake/graphics/yakeGraphicsSystem.h> #include <yake/graphics/yakeEntity.h> #include <yake/base/templates/yakeSignals.h> +#include <yake/base/math/yakeColor.h> +#include <yake/base/math/yakeRay.h> +#include <yake/base/math/yakeMatrix4.h> +#include <yake/base/templates/yakeDeque.h> //============================================================================ // INTERFACE STRUCTURES / UTILITY CLASSES Modified: trunk/yake/yake/input/yakeInputSystem.h =================================================================== --- trunk/yake/yake/input/yakeInputSystem.h 2007-08-23 23:25:11 UTC (rev 1812) +++ trunk/yake/yake/input/yakeInputSystem.h 2007-08-23 23:26:41 UTC (rev 1813) @@ -30,6 +30,7 @@ #ifndef YAKE_INPUT_PREREQUISITES_H #include <yake/input/yakePrerequisites.h> #endif +#include <yake/base/math/yakeGeometry.h> namespace yake { namespace input { Modified: trunk/yake/yake/physics/yakePhysicsCommon.h =================================================================== --- trunk/yake/yake/physics/yakePhysicsCommon.h 2007-08-23 23:25:11 UTC (rev 1812) +++ trunk/yake/yake/physics/yakePhysicsCommon.h 2007-08-23 23:26:41 UTC (rev 1813) @@ -28,6 +28,7 @@ #define YAKE_PHYSICS_COMMON_H #include <yake/physics/yakePhysicsPrerequisites.h> +#include <yake/base/math/yakeVector3.h> namespace yake { namespace physics { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-08-23 23:28:45
|
Revision: 1815 http://yake.svn.sourceforge.net/yake/?rev=1815&view=rev Author: psyclonist Date: 2007-08-23 16:28:48 -0700 (Thu, 23 Aug 2007) Log Message: ----------- * [demo] improved 'raf/lua1' (aka "ninja"): Lua movement handler now uses frame handler Modified Paths: -------------- trunk/yake/common/media/scripts/raf1.lua trunk/yake/samples/raf/lua1/demo.cpp Modified: trunk/yake/common/media/scripts/raf1.lua =================================================================== --- trunk/yake/common/media/scripts/raf1.lua 2007-08-23 23:27:11 UTC (rev 1814) +++ trunk/yake/common/media/scripts/raf1.lua 2007-08-23 23:28:48 UTC (rev 1815) @@ -39,6 +39,8 @@ -- Configure input -------------------------------------- +local activeKeys = {} -- Store the keys that are active in current frame. + -- We demonstrate two ways to bind Lua callbacks to a keyboard action. -- #1 demonstrates the details -- #2 shows how to achieve the same thing fast and Lua-style @@ -54,7 +56,7 @@ -- Our Lua callback handler: function onLeft() - cam:translate(yake.Vector3(-1,0,0)) + activeKeys["left"] = true end actionMap:connectToAction(idLeft,onLeft) -- by Action ID @@ -64,7 +66,7 @@ actionMap:reg("right", input.KeyboardActionCondition(app.keyboard, input.KC_RIGHT, input.KAM_CONTINUOUS)) actionMap:connectToAction("right", function() - cam:translate(yake.Vector3(1,0,0)) + activeKeys["right"] = true end) ------- Let's define a few helper functions to make things easier: @@ -80,10 +82,28 @@ createKeyAction("forward", input.KC_UP, input.KAM_CONTINUOUS) bindAction("forward", function() - cam:translate(yake.Vector3(0,0,-1)) + activeKeys["forward"] = true end) createKeyAction("reverse", input.KC_DOWN, input.KAM_CONTINUOUS) bindAction("reverse", function() - cam:translate(yake.Vector3(0,0,1)) + activeKeys["reverse"] = true end) + +----------------------------------- +function onFrame(timeElapsed) + local distance = 25 * timeElapsed + for k,v in pairs(activeKeys) do + if k == "left" then + cam:translate( -1 * yake.Vector3.UnitX * distance ) + elseif k == "right" then + cam:translate( 1 * yake.Vector3.UnitX * distance ) + elseif k == "forward" then + cam:translate( -1 * yake.Vector3.UnitZ * distance ) + elseif k == "reverse" then + cam:translate( 1 * yake.Vector3.UnitZ * distance ) + end + end + -- prepare for next frame: + activeKeys = {} +end \ No newline at end of file Modified: trunk/yake/samples/raf/lua1/demo.cpp =================================================================== --- trunk/yake/samples/raf/lua1/demo.cpp 2007-08-23 23:27:11 UTC (rev 1814) +++ trunk/yake/samples/raf/lua1/demo.cpp 2007-08-23 23:28:48 UTC (rev 1815) @@ -66,8 +66,7 @@ //bind { - scripting::LuaVM* lvm = static_cast<scripting::LuaVM*>(vm_.get()); - lua_State* L = lvm->getLuaState(); + lua_State* L = static_cast<scripting::LuaVM*>(vm_.get())->getLuaState(); luabind::globals(L)["app"] = &app_; luabind::globals(L)["app"]["actionMap"] = &actionMap_; @@ -86,6 +85,9 @@ virtual void onFrame(const real timeElapsed) { actionMap_.update(); //@todo here OK? ... + + lua_State* L = static_cast<scripting::LuaVM*>(vm_.get())->getLuaState(); + luabind::call_function<void>( L, "onFrame", timeElapsed ); } private: raf::Application& app_; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-08-24 17:49:37
|
Revision: 1817 http://yake.svn.sourceforge.net/yake/?rev=1817&view=rev Author: psyclonist Date: 2007-08-24 10:49:39 -0700 (Fri, 24 Aug 2007) Log Message: ----------- [res] fixed assertions and use of posix compliant stat() Modified Paths: -------------- trunk/yake/src/res/datastream.cpp trunk/yake/src/res/source.cpp trunk/yake/yake/res/source.h Modified: trunk/yake/src/res/datastream.cpp =================================================================== --- trunk/yake/src/res/datastream.cpp 2007-08-23 23:29:00 UTC (rev 1816) +++ trunk/yake/src/res/datastream.cpp 2007-08-24 17:49:39 UTC (rev 1817) @@ -40,15 +40,15 @@ { assert( in_.is_open() ); - struct _stat32 s; - const int code = _stat32(fn.c_str(), &s); - assert(code == 0); + struct stat s; + const int code = ::stat(fn.c_str(), &s); + YAKE_ASSERT(code == 0)(code); // @todo throw exception of ENOENT or ENOTDIR? size_ = s.st_size; } size_t FileDataStream::read(void * out, size_t size) { - assert( in_.is_open() ); - assert( !eof() ); + YAKE_ASSERT( in_.is_open() ); + YAKE_ASSERT( !eof() ); if (eof()) return 0; // NB use readsome() for async Modified: trunk/yake/src/res/source.cpp =================================================================== --- trunk/yake/src/res/source.cpp 2007-08-23 23:29:00 UTC (rev 1816) +++ trunk/yake/src/res/source.cpp 2007-08-24 17:49:39 UTC (rev 1817) @@ -28,6 +28,7 @@ #include "yake/res/source.h" #include <sys/stat.h> +#include <sys/types.h> namespace yake { namespace res { @@ -44,8 +45,8 @@ } bool FileSource::exists(const Location& loc) const { - struct _stat32 s; - const int code = _stat32(loc.c_str(), &s); + struct stat s; + const int code = ::stat(loc.c_str(), &s); return (code == 0); } @@ -53,10 +54,10 @@ void SourceFactory::reg(const SourceId& id, CreateSourceFn creator) { - assert( !id.empty() ); + YAKE_ASSERT( !id.empty() ); if (id.empty()) throw InvalidInputException("id is empty/null"); - assert( creator ); + YAKE_ASSERT( creator )(id); if (!creator) throw InvalidInputException("creator function is null"); creators_[ id ] = creator; @@ -64,13 +65,13 @@ SourcePtr SourceFactory::create(const SourceId& id) const { CreatorMap::const_iterator it = creators_.find(id); - //assert( it != creators_.end() ); + //YAKE_ASSERT( it != creators_.end() )(id); if (it == creators_.end()) { //return SourcePtr(); throw UnknownResourceSourceTypeException(id); } - assert( it->second ); + YAKE_ASSERT( it->second )(id); return SourcePtr(it->second()); } SourceFactory& SourceFactory::global() Modified: trunk/yake/yake/res/source.h =================================================================== --- trunk/yake/yake/res/source.h 2007-08-23 23:29:00 UTC (rev 1816) +++ trunk/yake/yake/res/source.h 2007-08-24 17:49:39 UTC (rev 1817) @@ -32,6 +32,7 @@ #include <deque> #include <boost/shared_ptr.hpp> #include <boost/function.hpp> +#include <boost/bind.hpp> namespace yake { namespace res { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-08-24 21:22:06
|
Revision: 1819 http://yake.svn.sourceforge.net/yake/?rev=1819&view=rev Author: psyclonist Date: 2007-08-24 14:22:03 -0700 (Fri, 24 Aug 2007) Log Message: ----------- [premake] add yake.res as dependency for yake.raf [raf] reconfigured raf::Application to use ini-style configuration 'raf_common.cfg' [sample:res/lua1] reconfigured to use custom configuration file to setup resource paths [base] added ini style configuration loader/holder/accessor: yake::IniFile [scriptingLua] use luaL_loadbuffer() instead of luaL_loadstring() Modified Paths: -------------- trunk/yake/samples/res/lua1/demo.cpp trunk/yake/scripts/premake/yake.lua trunk/yake/src/base/yakeConfigFile.cpp trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp trunk/yake/src/raf/yakeApplication.cpp trunk/yake/yake/base/yakeConfigFile.h trunk/yake/yake/raf/yakeApplication.h Added Paths: ----------- trunk/yake/samples/bin/debug/raf_common.cfg trunk/yake/samples/bin/debug/sampleResLua1.cfg trunk/yake/samples/bin/release/raf_common.cfg trunk/yake/samples/bin/release/sampleResLua1.cfg Added: trunk/yake/samples/bin/debug/raf_common.cfg =================================================================== --- trunk/yake/samples/bin/debug/raf_common.cfg (rev 0) +++ trunk/yake/samples/bin/debug/raf_common.cfg 2007-08-24 21:22:03 UTC (rev 1819) @@ -0,0 +1,23 @@ +#----------------------------------- +[raf.options] +useCEGUI=no + +#----------------------------------- +[raf.startup.libraries] +# Libraries to be loaded automatically at startup + +scriptingLua + +#----------------------------------- +[raf.startup.systems] +# System to be created & initialized automatically + +scripting=lua + +#----------------------------------- +[raf.startup.scripts] +# Scripts to be run at startup + +# run = <scripting_system>,<filename> +run=lua,raf1_startup.lua +#run=ruby,raf1_startup.ruby Added: trunk/yake/samples/bin/debug/sampleResLua1.cfg =================================================================== --- trunk/yake/samples/bin/debug/sampleResLua1.cfg (rev 0) +++ trunk/yake/samples/bin/debug/sampleResLua1.cfg 2007-08-24 21:22:03 UTC (rev 1819) @@ -0,0 +1,2 @@ +[resource.sources] # <- evaluated by RAF +file=../../../common/media/scripts/ # <- do NOT forget trialing '/' !! Added: trunk/yake/samples/bin/release/raf_common.cfg =================================================================== --- trunk/yake/samples/bin/release/raf_common.cfg (rev 0) +++ trunk/yake/samples/bin/release/raf_common.cfg 2007-08-24 21:22:03 UTC (rev 1819) @@ -0,0 +1,14 @@ +[raf.options] +useCEGUI=no + +[raf.startup.libraries] +scriptingLua + +[raf.startup.systems] +scripting=lua + +[raf.startup.scripts] + +# run = <scripting_system>,<filename> +run=lua,raf1_startup.lua +#run=ruby,raf1_startup.ruby Added: trunk/yake/samples/bin/release/sampleResLua1.cfg =================================================================== --- trunk/yake/samples/bin/release/sampleResLua1.cfg (rev 0) +++ trunk/yake/samples/bin/release/sampleResLua1.cfg 2007-08-24 21:22:03 UTC (rev 1819) @@ -0,0 +1,2 @@ +[resource.sources] # <- evaluated by RAF +file=../../../common/media/scripts/ # <- do NOT forget trialing '/' !! Modified: trunk/yake/samples/res/lua1/demo.cpp =================================================================== --- trunk/yake/samples/res/lua1/demo.cpp 2007-08-24 17:55:44 UTC (rev 1818) +++ trunk/yake/samples/res/lua1/demo.cpp 2007-08-24 21:22:03 UTC (rev 1819) @@ -9,21 +9,14 @@ using namespace yake; -/** Configuration of the application */ -struct TheConfiguration : public raf::ApplicationConfiguration -{ - virtual StringVector getLibraries() - { return MakeStringVector() << YAKE_LIB("scriptingLua"); } - - virtual StringVector getScriptingSystems() - { return MakeStringVector() << "lua"; } -}; - /** The mighty application itself! */ -class TheApp : public raf::ExampleApplication<TheConfiguration> +class TheApp : public raf::ExampleApplication<> { public: - TheApp() {} + TheApp() + { + getConfiguration().get().load("sampleResLua1.cfg"); + } protected: virtual bool onRun() { @@ -41,13 +34,10 @@ luabind::globals(L)["app"] = &app_; */ } - // - res::SourceFactory::global().reg<res::FileSource>("file"); - res::SourceManager::global().addSource("file","../../../common/media/scripts/"); - //scripting::LuaScriptManager::global().create("res1.lua"); - //res::SourceManager::global().find("res1.lua"); - // + // NB Resource configuration is done in RAF application (via sampleResLua1.cfg). + + // Load & run script try { scripting::ScriptPtr script = sys->createScriptFromFile("res1.lua"); @@ -62,6 +52,7 @@ } }; +#include <yake/base/yakeConfigFile.h> int main( int argc, char** argv ) { // Use default executor for convenience. Modified: trunk/yake/scripts/premake/yake.lua =================================================================== --- trunk/yake/scripts/premake/yake.lua 2007-08-24 17:55:44 UTC (rev 1818) +++ trunk/yake/scripts/premake/yake.lua 2007-08-24 21:22:03 UTC (rev 1819) @@ -210,6 +210,7 @@ -------------------------------------- makeComponent("raf","YAKE_RAF_EXPORTS") addDependency("base") +addDependency("res") addDependency("audio") addDependency("input") addDependency("graphics") Modified: trunk/yake/src/base/yakeConfigFile.cpp =================================================================== --- trunk/yake/src/base/yakeConfigFile.cpp 2007-08-24 17:55:44 UTC (rev 1818) +++ trunk/yake/src/base/yakeConfigFile.cpp 2007-08-24 21:22:03 UTC (rev 1819) @@ -29,7 +29,6 @@ #include <yake/base/yakeConfigFile.h> namespace yake { -namespace base { namespace detail { } // namespace detail @@ -145,5 +144,136 @@ boost::property_tree::write_xml(out,*tree_); } -} // base + //----------------------------------------------------- + + IniFile::IniFile() + { + } + /* + ini::const_key_iterator ini::begin(const String& section) const + { + Sections::const_iterator itSect = sections_.find(section); + if (itSect == sections_.end()) + return empty_.end(); + return itSect->second.begin(); + } + ini::const_key_iterator ini::end(const String& section) const + { + Sections::const_iterator itSect = sections_.find(section); + if (itSect == sections_.end()) + return empty_.end(); + return itSect->second.end(); + } + */ + StringVector IniFile::getKeys(const String& section) const + { + Sections::const_iterator itSect = sections_.find(section); + if (itSect == sections_.end()) + return StringVector(); + KeyValueMap::const_iterator it = itSect->second.begin(); + KeyValueMap::const_iterator itEnd = itSect->second.end(); + StringVector ret; + for (; it != itEnd; ++it) + ret.push_back( it->first ); + return ret; + } + StringPairVector IniFile::getKeysAndValues(const String& section) const + { + Sections::const_iterator itSect = sections_.find(section); + if (itSect == sections_.end()) + return StringPairVector(); + StringPairVector ret; + YAKE_FOR_EACH( KeyValueMap::const_iterator, itKey, itSect->second ) + { + const ValueList& values = itKey->second; + YAKE_FOR_EACH( ValueList::const_iterator, itValue, values ) + ret.push_back( StringPair( itKey->first, *itValue ) ); + } + return ret; + } + IniFile::KeyValueMap IniFile::getKeysAndValues2(const String& section) const + { + Sections::const_iterator itSect = sections_.find(section); + if (itSect == sections_.end()) + return IniFile::KeyValueMap(); + return itSect->second; + } + bool IniFile::hasSection(const String& section) const + { + Sections::const_iterator itSect = sections_.find(section); + return (itSect != sections_.end()); + } + IniFile::value IniFile::getFirstValue(const String& section, const String& key) const + { + Sections::const_iterator itSect = sections_.find(section); + if (itSect == sections_.end()) + return false; + KeyValueMap::const_iterator itKey = itSect->second.find(key); + if (itKey == itSect->second.end()) + return false; + const ValueList& values = itKey->second; + if (values.empty()) + return false; + return values.front(); + } + StringVector IniFile::getAllValues(const String& section, const String& key) const + { + Sections::const_iterator itSect = sections_.find(section); + if (itSect == sections_.end()) + return StringVector(); + KeyValueMap::const_iterator itKey = itSect->second.find(key); + if (itKey == itSect->second.end()) + return StringVector(); + const ValueList& values = itKey->second; + return values; + } + bool IniFile::load(const String& filename) + { + std::ifstream in(filename.c_str(), std::ios::in); + if (!in) + return false; + String currSection; + String line; + while (std::getline(in,line)) + { + StringUtil::trim( line, true, true ); // trim left and right + // skip comments (full line and trailing ones) + { + String::size_type commentStart = line.find("#"); + if (String::npos != commentStart) + { + line = line.substr(0,commentStart); + StringUtil::trim(line); + } + } + if (line.empty()) // skip empty lines + continue; + // + if (line[0] == '[') + { + String::size_type endMarker = line.find("]"); + YAKE_ASSERT( endMarker != String::npos ).debug("syntax error in section declaration: missing ']'."); + if (endMarker == String::npos) + continue; + currSection = line.substr(1,endMarker-1); + StringUtil::trim(currSection); + } + else + { + String key,value; + String::size_type splitAt = line.find("="); + if (splitAt != String::npos) + { + key = line.substr(0,splitAt); + value = line.substr(splitAt+1); + StringUtil::trim(key); + StringUtil::trim(value); + } + else + key = line; + sections_[currSection][key].push_back( value ); + } + } + return true; + } } // yake Modified: trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp =================================================================== --- trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp 2007-08-24 17:55:44 UTC (rev 1818) +++ trunk/yake/src/plugins/scriptingLua/ScriptingSystemLua.cpp 2007-08-24 21:22:03 UTC (rev 1819) @@ -132,11 +132,13 @@ const LuaScript::CodeBuffer& code = pLuaScript->getData(); if (code.empty()) return; //nothing to do + const char* str_code = reinterpret_cast<const char*>(&code[0]); lua_pushcclosure(mLuaState, &pcall_handler, 0); + if (luaL_loadbuffer(mLuaState,str_code,std::strlen(str_code),"chunk_name")) //if (luaL_loadbuffer(mLuaState,(const char*)&code[0],code.size(),"buffer")) - if (luaL_loadstring(mLuaState,(const char*)&code[0])) + //if (luaL_loadstring(mLuaState,(const char*)&code[0])) //if (luaL_loadfile(mLuaState, rFileName.c_str())) { err = lua_tostring(mLuaState, -1); Modified: trunk/yake/src/raf/yakeApplication.cpp =================================================================== --- trunk/yake/src/raf/yakeApplication.cpp 2007-08-24 17:55:44 UTC (rev 1818) +++ trunk/yake/src/raf/yakeApplication.cpp 2007-08-24 21:22:03 UTC (rev 1819) @@ -39,6 +39,8 @@ //# pragma comment(lib,"CEGUIBase.lib") #endif #endif +#include <yake/base/yakeConfigFile.h> +#include <yake/res/res.h> namespace yake { namespace raf { @@ -343,29 +345,80 @@ // YAKE_LOG_INFORMATION("raf","loading configuration..."); - ApplicationConfiguration& cfg = getConfiguration(); - mUseExtGraphicsSystem = cfg.useExternalGraphicsSystem().get() != 0; + // + ApplicationConfiguration& cfg = this->getConfiguration(); - // load libs - YAKE_LOG_INFORMATION("raf","loading libraries..."); - StringVector libs = cfg.getLibraries(); - ConstVectorIterator<StringVector> itLib( libs ); - while (itLib.hasMoreElements()) + // load from file + IniFile& cfgfile = cfg.get(); + if (!cfgfile.load("raf_common.cfg")) { - loadLibrary(itLib.getNext()); + YAKE_LOG_ERROR("raf","failed to load raf_common.cfg"); + return false; } + // setup resource configuration + { // register global 'file' source + YAKE_LOG_INFORMATION("raf","registering (global) 'file' resource source"); + res::SourceFactory::global().reg<res::FileSource>("file"); + } + { // load global sources + StringPairVector sources = cfgfile.getKeysAndValues("resource.sources"); + YAKE_FOR_EACH( StringPairVector::const_iterator, it, sources ) + { + const String& id = it->first; + const String& locationBase = it->second; + YAKE_LOG_INFORMATION("raf","adding (global) '"+id+"' source '"+locationBase+"'..."); + res::SourceManager::global().addSource(id, locationBase); + } + } + + {// load libraries + StringVector plugins = cfgfile.getKeys("raf.startup.libraries"); + YAKE_FOR_EACH( StringVector::const_iterator, it, plugins ) + { + const String libname = YAKE_LIB(*it); + YAKE_LOG_INFORMATION("raf","loading '" + libname + "'..."); + loadLibrary(libname); + } + } + + // use external graphics system? + mUseExtGraphicsSystem = cfg.getExternalGraphicsSystem() != 0; + if (mUseExtGraphicsSystem) + mGraphicsSystems["default"] = cfg.getExternalGraphicsSystem(); + + { // create & init systems + // e.g. "scripting=lua" + IniFile::KeyValueMap systems = cfgfile.getKeysAndValues2("raf.startup.systems"); + YAKE_FOR_EACH( IniFile::KeyValueMap::const_iterator, it, systems ) + { + const String& systype = it->first; + const IniFile::ValueList& sysnames = it->second; + YAKE_LOG_INFORMATION("raf","creating and initialising systems of type '"+systype+"'..."); + if (systype == "scripting") + loadAndInitSystems<scripting::IScriptingSystem>( sysnames, mScriptingSystems ); + else if (systype == "audio") + loadAndInitSystems<audio::IAudioSystem>( sysnames, mAudioSystems ); + else if (systype == "graphics") + { + if (mUseExtGraphicsSystem) + { + YAKE_LOG_WARNING("raf","ignoring graphics systems as an external one has been specified"); + continue; + } + else + loadAndInitSystems<graphics::IGraphicsSystem>( sysnames, mGraphicsSystems ); + } + else if (systype == "physics") + loadAndInitSystems<physics::IPhysicsSystem>( sysnames, mPhysicsSystems ); + else if (systype == "input") + loadAndInitSystems<input::IInputSystem>( sysnames, mInputSystems ); + } + } + // load & init systems - YAKE_LOG_INFORMATION("raf","loading and initialising systems..."); - loadAndInitSystems<scripting::IScriptingSystem>( cfg.getScriptingSystems(), mScriptingSystems ); - loadAndInitSystems<audio::IAudioSystem>( cfg.getAudioSystems(), mAudioSystems ); - if (mUseExtGraphicsSystem) - mGraphicsSystems["default"] = cfg.useExternalGraphicsSystem(); - else - loadAndInitSystems<graphics::IGraphicsSystem>( cfg.getGraphicsSystems(), mGraphicsSystems ); - loadAndInitSystems<physics::IPhysicsSystem>( cfg.getPhysicsSystems(), mPhysicsSystems ); - loadAndInitSystems<input::IInputSystem>( cfg.getInputSystems(), mInputSystems ); + YAKE_LOG_INFORMATION("raf","2nd stage initialisations ..."); if (!mInputSystems.empty()) initInput(); if (!mPhysicsSystems.empty()) @@ -373,10 +426,9 @@ #if YAKE_RAF_USES_CEGUI == 1 // CEGUI - if (cfg.loadCEGUI()) - { + IniFile::value useCEGUI = cfgfile.getFirstValue("raf.options","useCEGUI"); + if (StringUtil::parseBool( *useCEGUI )) initCEGUI(); - } #endif // application state machine Modified: trunk/yake/yake/base/yakeConfigFile.h =================================================================== --- trunk/yake/yake/base/yakeConfigFile.h 2007-08-24 17:55:44 UTC (rev 1818) +++ trunk/yake/yake/base/yakeConfigFile.h 2007-08-24 21:22:03 UTC (rev 1819) @@ -32,6 +32,7 @@ # include <yake/base/yakePrerequisites.h> #endif #include <yake/base/templates/yakePointer.h> +#include <yake/base/yakeNoncopyable.h> // for Configuration #if YAKE_COMPILER == COMPILER_MSVC @@ -61,7 +62,6 @@ #endif namespace yake { -namespace base { struct YAKE_BASE_API Configuration { @@ -152,10 +152,36 @@ String prefix_; }; -} // base + /** NB Multiple keys in a single section allowed! */ + struct YAKE_BASE_API IniFile : public noncopyable + { + public: + typedef StringVector ValueList; + typedef std::map<String,ValueList> KeyValueMap; - // pull in type - typedef base::Configuration Configuration; + public: + typedef boost::optional<String> value; + IniFile(); + bool load(const String& filename); + + value getFirstValue(const String& section, const String& key) const; + StringVector getAllValues(const String& section, const String& key) const; + + bool hasSection(const String& section) const; + StringVector getKeys(const String& section) const; + StringPairVector getKeysAndValues(const String& section) const; + KeyValueMap getKeysAndValues2(const String& section) const; + + private: + typedef std::map<String,KeyValueMap> Sections; + public: + typedef KeyValueMap::const_iterator const_key_iterator; + //const_key_iterator begin(const String& section) const; + //const_key_iterator end(const String& section) const; + private: + Sections sections_; + KeyValueMap empty_; + }; } // yake #endif // YAKE_BASE_CONFIGFILE_H Modified: trunk/yake/yake/raf/yakeApplication.h =================================================================== --- trunk/yake/yake/raf/yakeApplication.h 2007-08-24 17:55:44 UTC (rev 1818) +++ trunk/yake/yake/raf/yakeApplication.h 2007-08-24 21:22:03 UTC (rev 1819) @@ -28,6 +28,7 @@ #define YAKE_RAF_APPLICATION_H #include <yake/base/yakeLibrary.h> +#include <yake/base/yakeConfigFile.h> namespace yake { namespace audio { @@ -60,34 +61,22 @@ struct ApplicationConfiguration { - virtual ~ApplicationConfiguration() {} + IniFile& get() + { return cfg_; } + const IniFile& get() const + { return cfg_; } - /** List the libraries to load. - For example, "graphicsOgre" for OGRE3D graphics or - "physicsNx" for the Novodex based physics plugin. - */ - virtual StringVector getLibraries() = 0; - - /** An empty list will not create any systems. - If the list contains an empty string, then the default system for the specific type will - be created! (using create_default<>()) - */ - virtual StringVector getGraphicsSystems() - { return MakeStringVector(); } - virtual StringVector getScriptingSystems() - { return MakeStringVector(); } - virtual StringVector getAudioSystems() - { return MakeStringVector(); } - virtual StringVector getPhysicsSystems() - { return MakeStringVector(); } - virtual StringVector getInputSystems() - { return MakeStringVector(); } - - virtual SharedPtr<graphics::IGraphicsSystem> useExternalGraphicsSystem() { return SharedPtr<graphics::IGraphicsSystem>(); } -#if YAKE_RAF_USES_CEGUI == 1 - /** I could need some Dihydrogendinatriumethylendiamintetraacetat. */ - virtual bool loadCEGUI() { return false; } -#endif + void setExternalGraphicsSystem(SharedPtr<graphics::IGraphicsSystem> gfx) + { + extGfx_ = gfx; + } + SharedPtr<graphics::IGraphicsSystem> getExternalGraphicsSystem() const + { + return extGfx_; + } + private: + IniFile cfg_; + SharedPtr<graphics::IGraphicsSystem> extGfx_; }; class YAKE_RAF_API Application @@ -210,7 +199,7 @@ One thing less to worry about. Usage: class MyApp : public ExampleApplication<MyConfig> {} */ - template<class ConfigType> + template<class ConfigType = raf::ApplicationConfiguration> class ExampleApplication : public raf::Application { public: This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2007-08-27 14:24:55
|
Revision: 1822 http://yake.svn.sourceforge.net/yake/?rev=1822&view=rev Author: psyclonist Date: 2007-08-27 06:45:58 -0700 (Mon, 27 Aug 2007) Log Message: ----------- * set svn:eol-style to native for latest additions Modified Paths: -------------- trunk/yake/common/media/samples/property/demo.lua trunk/yake/common/media/samples/task/demo.lua trunk/yake/common/media/samples/task/events.lua trunk/yake/common/media/scripts/raf1.lua trunk/yake/common/media/scripts/res1.lua trunk/yake/src/base/templates/yakeSignals.cpp trunk/yake/src/base/yakeConfigFile.cpp trunk/yake/src/base/yakeFileLog.cpp trunk/yake/src/base/yakeStderrLog.cpp trunk/yake/src/bindings.lua/detail/graphics.lua.cpp trunk/yake/src/bindings.lua/detail/input.lua.cpp trunk/yake/src/bindings.lua/detail/physics.lua.cpp trunk/yake/src/bindings.lua/detail/property.lua.cpp trunk/yake/src/bindings.lua/detail/raf.lua.cpp trunk/yake/src/bindings.lua/detail/res.lua.cpp trunk/yake/src/plugins/inputOgreOIS/InputSystemOgreOIS.cpp trunk/yake/src/plugins/inputOgreOIS/yakePCH.cpp trunk/yake/src/res/datastream.cpp trunk/yake/src/res/res.cpp trunk/yake/src/res/resource_manager.cpp trunk/yake/yake/base/yakeFileLog.h trunk/yake/yake/base/yakeStderrLog.h trunk/yake/yake/bindings.lua/detail/input.lua.keycodes.inl trunk/yake/yake/bindings.lua/detail/property.lua.h trunk/yake/yake/net2/async_send.h trunk/yake/yake/net2/error.h trunk/yake/yake/net2/message_decoder.h trunk/yake/yake/net2/net.h trunk/yake/yake/net2/packet.h trunk/yake/yake/net2/packet_connection.h trunk/yake/yake/net2/packet_dispatcher.h trunk/yake/yake/net2/resolver.h trunk/yake/yake/net2/server.h trunk/yake/yake/net2/simple_serialization.h trunk/yake/yake/net2/stats.h trunk/yake/yake/net2/types.h trunk/yake/yake/net2/utils.h trunk/yake/yake/plugins/graphicsOgre/graphicsOgrePrerequisites.h trunk/yake/yake/plugins/inputOgreOIS/InputSystemOgreOIS.h trunk/yake/yake/plugins/inputOgreOIS/yakePCH.h trunk/yake/yake/property/accessors.h trunk/yake/yake/property/function_accessor.h trunk/yake/yake/property/prerequisites.h trunk/yake/yake/property/property.h trunk/yake/yake/property/property_container.h trunk/yake/yake/property/stream_operators.h trunk/yake/yake/res/async_loader.h trunk/yake/yake/res/datastream.h trunk/yake/yake/res/prerequisites.h trunk/yake/yake/res/res.h trunk/yake/yake/res/resource.h trunk/yake/yake/res/resource_manager.h trunk/yake/yake/res/source.h trunk/yake/yake/res/source_manager.h trunk/yake/yake/scripting/scripting.h Property Changed: ---------------- trunk/yake/common/media/samples/property/demo.lua trunk/yake/common/media/samples/task/demo.lua trunk/yake/common/media/samples/task/events.lua trunk/yake/common/media/scripts/raf1.lua trunk/yake/common/media/scripts/res1.lua trunk/yake/src/base/templates/yakeSignals.cpp trunk/yake/src/base/yakeConfigFile.cpp trunk/yake/src/base/yakeFileLog.cpp trunk/yake/src/base/yakeStderrLog.cpp trunk/yake/src/bindings.lua/detail/graphics.lua.cpp trunk/yake/src/bindings.lua/detail/input.lua.cpp trunk/yake/src/bindings.lua/detail/physics.lua.cpp trunk/yake/src/bindings.lua/detail/property.lua.cpp trunk/yake/src/bindings.lua/detail/raf.lua.cpp trunk/yake/src/bindings.lua/detail/res.lua.cpp trunk/yake/src/plugins/inputOgreOIS/InputSystemOgreOIS.cpp trunk/yake/src/plugins/inputOgreOIS/yakePCH.cpp trunk/yake/src/res/datastream.cpp trunk/yake/src/res/res.cpp trunk/yake/src/res/resource_manager.cpp trunk/yake/yake/base/yakeFileLog.h trunk/yake/yake/base/yakeStderrLog.h trunk/yake/yake/bindings.lua/detail/input.lua.keycodes.inl trunk/yake/yake/bindings.lua/detail/property.lua.h trunk/yake/yake/net2/async_send.h trunk/yake/yake/net2/error.h trunk/yake/yake/net2/message_decoder.h trunk/yake/yake/net2/net.h trunk/yake/yake/net2/packet.h trunk/yake/yake/net2/packet_connection.h trunk/yake/yake/net2/packet_dispatcher.h trunk/yake/yake/net2/resolver.h trunk/yake/yake/net2/server.h trunk/yake/yake/net2/simple_serialization.h trunk/yake/yake/net2/stats.h trunk/yake/yake/net2/types.h trunk/yake/yake/net2/utils.h trunk/yake/yake/plugins/graphicsOgre/graphicsOgrePrerequisites.h trunk/yake/yake/plugins/inputOgreOIS/InputSystemOgreOIS.h trunk/yake/yake/plugins/inputOgreOIS/yakePCH.h trunk/yake/yake/property/accessors.h trunk/yake/yake/property/function_accessor.h trunk/yake/yake/property/prerequisites.h trunk/yake/yake/property/property.h trunk/yake/yake/property/property_container.h trunk/yake/yake/property/stream_operators.h trunk/yake/yake/res/async_loader.h trunk/yake/yake/res/datastream.h trunk/yake/yake/res/prerequisites.h trunk/yake/yake/res/res.h trunk/yake/yake/res/resource.h trunk/yake/yake/res/resource_manager.h trunk/yake/yake/res/source.h trunk/yake/yake/res/source_manager.h trunk/yake/yake/scripting/scripting.h Modified: trunk/yake/common/media/samples/property/demo.lua =================================================================== --- trunk/yake/common/media/samples/property/demo.lua 2007-08-24 21:25:15 UTC (rev 1821) +++ trunk/yake/common/media/samples/property/demo.lua 2007-08-27 13:45:58 UTC (rev 1822) @@ -1,58 +1,58 @@ - -print("create yake.NamedPropertyContainer"); -props = yake.NamedPropertyContainer(); - -print("create property 'visible' of implicit type 'bool'"); -assert( not props:has("visible") ); ---props:add( "visible", yake.createProperty(true) ); -props:create("visible",true); -assert( props:has("visible") ); - -print("acquire property object 'visible'"); -p = props:get("visible"); -assert(p); -print(" type = " .. p:type()); - -print("read & modify property"); -print( " value of 'visible' = " .. tostring(p:get()) ); -assert( p:set( not p:get() ) ); -print( " value of 'visible' = " .. tostring(p:get()) ); - -print("test for type mismatch when setting the value") -assert( not p:set("aloha") ); - -print("create property 'name' of implicit type 'String'"); -p = props:create("name","aloha"); -assert( p ); -print(" type = " .. p:type()); -print(" value = " .. tostring(p:get()) ); -assert( p:get() == "aloha" ); -assert( p:set("waikiki") ); -print(" value = " .. tostring(p:get()) ); -assert( p:get() == "waikiki" ); - -print("store a function in a property 'sayHello'"); -p = props:create("sayHello",function() print("'hello, i'm property 'sayHello'!'"); end); -assert( p ); -print(" type = " .. p:type()); -print("running function stored in property 'sayHello'"); -assert( p:get() ); -p:get()(); - ---NB At the moment you can store ANY kind of Lua object in a property! --- On the C++ side any 'unknown' or unregistered property type will be stored --- as a luabind::object. Be careful! -print("attempt to create property of unsupported type 'thread'"); -p = props:create("thread", coroutine.create(function() print("thread"); end)); ---assert( not p ); - -print("attempt to create property of type 'Vector3'"); -p = props:create("position", yake.Vector3(1,2,3)); -print(" value = (" .. p:get().x .. "," .. p:get().y .. "," .. p:get().z .. ")" ); ---assert( p:get():isEqualTo( yake.Vector(1,2,3) ) ); -assert( p:get().x == 1 ); -assert( not p:set(yake.Quaternion(1,0,0,1)) ); --will fail because of type mismatch -assert( p:set( yake.Vector3(2,3,4) ) ); -print(" value = (" .. p:get().x .. "," .. p:get().y .. "," .. p:get().z .. ")" ); - + +print("create yake.NamedPropertyContainer"); +props = yake.NamedPropertyContainer(); + +print("create property 'visible' of implicit type 'bool'"); +assert( not props:has("visible") ); +--props:add( "visible", yake.createProperty(true) ); +props:create("visible",true); +assert( props:has("visible") ); + +print("acquire property object 'visible'"); +p = props:get("visible"); +assert(p); +print(" type = " .. p:type()); + +print("read & modify property"); +print( " value of 'visible' = " .. tostring(p:get()) ); +assert( p:set( not p:get() ) ); +print( " value of 'visible' = " .. tostring(p:get()) ); + +print("test for type mismatch when setting the value") +assert( not p:set("aloha") ); + +print("create property 'name' of implicit type 'String'"); +p = props:create("name","aloha"); +assert( p ); +print(" type = " .. p:type()); +print(" value = " .. tostring(p:get()) ); +assert( p:get() == "aloha" ); +assert( p:set("waikiki") ); +print(" value = " .. tostring(p:get()) ); +assert( p:get() == "waikiki" ); + +print("store a function in a property 'sayHello'"); +p = props:create("sayHello",function() print("'hello, i'm property 'sayHello'!'"); end); +assert( p ); +print(" type = " .. p:type()); +print("running function stored in property 'sayHello'"); +assert( p:get() ); +p:get()(); + +--NB At the moment you can store ANY kind of Lua object in a property! +-- On the C++ side any 'unknown' or unregistered property type will be stored +-- as a luabind::object. Be careful! +print("attempt to create property of unsupported type 'thread'"); +p = props:create("thread", coroutine.create(function() print("thread"); end)); +--assert( not p ); + +print("attempt to create property of type 'Vector3'"); +p = props:create("position", yake.Vector3(1,2,3)); +print(" value = (" .. p:get().x .. "," .. p:get().y .. "," .. p:get().z .. ")" ); +--assert( p:get():isEqualTo( yake.Vector(1,2,3) ) ); +assert( p:get().x == 1 ); +assert( not p:set(yake.Quaternion(1,0,0,1)) ); --will fail because of type mismatch +assert( p:set( yake.Vector3(2,3,4) ) ); +print(" value = (" .. p:get().x .. "," .. p:get().y .. "," .. p:get().z .. ")" ); + print("\nAll tests done."); \ No newline at end of file Property changes on: trunk/yake/common/media/samples/property/demo.lua ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/yake/common/media/samples/task/demo.lua =================================================================== --- trunk/yake/common/media/samples/task/demo.lua 2007-08-24 21:25:15 UTC (rev 1821) +++ trunk/yake/common/media/samples/task/demo.lua 2007-08-27 13:45:58 UTC (rev 1822) @@ -1,43 +1,43 @@ --- event callbacks/handlers -function onTick() - print("onTick() (time=" .. sched:time() .. ")") -end - -function test() - print("test: cancel task " .. " (current time: " .. sched:time() .. ")") - - -- schedule function to be called after 3 time steps: - sched:add(onTick,3) - - -- schedule anonymous function to be called after 3 time steps: - sched:add( - function() - print("hello from anonymous! (time=" .. sched:time() .. ")") - end, - 3) - - -- schedule task and cancel it before it can be executed - t = sched:add(onTick,3) - t:cancel() - - wait(4) --wait until tasks at time 3 have been executed... - - print("test done (time=" .. sched:time() ..")") - assert( sched:time() == 4 ) -end - -function test2() - --local waypoints = {"work", "the bar", "home"}; - local waypoints = {"work", "the bar"}; - - print("note: waiting 2 time steps between waypoints") - for i,next in pairs(waypoints) do - print(sched:time() .. " waypoint " .. tostring(i) .. ": going to " .. next) - wait(2) -- could be: walkTo(next) - - assert(i*2 == sched:time()) - end - print(tostring(sched:time()) .. " lua: staying some more...") - wait(1) - print(tostring(sched:time()) .. " lua: i'm dead :( no more waypoints") -end +-- event callbacks/handlers +function onTick() + print("onTick() (time=" .. sched:time() .. ")") +end + +function test() + print("test: cancel task " .. " (current time: " .. sched:time() .. ")") + + -- schedule function to be called after 3 time steps: + sched:add(onTick,3) + + -- schedule anonymous function to be called after 3 time steps: + sched:add( + function() + print("hello from anonymous! (time=" .. sched:time() .. ")") + end, + 3) + + -- schedule task and cancel it before it can be executed + t = sched:add(onTick,3) + t:cancel() + + wait(4) --wait until tasks at time 3 have been executed... + + print("test done (time=" .. sched:time() ..")") + assert( sched:time() == 4 ) +end + +function test2() + --local waypoints = {"work", "the bar", "home"}; + local waypoints = {"work", "the bar"}; + + print("note: waiting 2 time steps between waypoints") + for i,next in pairs(waypoints) do + print(sched:time() .. " waypoint " .. tostring(i) .. ": going to " .. next) + wait(2) -- could be: walkTo(next) + + assert(i*2 == sched:time()) + end + print(tostring(sched:time()) .. " lua: staying some more...") + wait(1) + print(tostring(sched:time()) .. " lua: i'm dead :( no more waypoints") +end Property changes on: trunk/yake/common/media/samples/task/demo.lua ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/yake/common/media/samples/task/events.lua =================================================================== --- trunk/yake/common/media/samples/task/events.lua 2007-08-24 21:25:15 UTC (rev 1821) +++ trunk/yake/common/media/samples/task/events.lua 2007-08-27 13:45:58 UTC (rev 1822) @@ -1,26 +1,26 @@ --- boiler plate code: -print("lua: init task adapter code...") - ---@todo move this code out into 'entity.bind.lua' -function events(id) -- alias for: self:get(id) - if not id then - return self:events() - else - return self:events():get(id) - end -end - -function wait(delay) - if not delay then - return nil - end - schedule_revive(sched, delay, function() end) - print("lua: wait.yield...") - coroutine.yield() -end -task = { - add = function(fn,delayMs) - return sched:add(fn,delayMs) - end -} +-- boiler plate code: +print("lua: init task adapter code...") + +--@todo move this code out into 'entity.bind.lua' +function events(id) -- alias for: self:get(id) + if not id then + return self:events() + else + return self:events():get(id) + end +end + +function wait(delay) + if not delay then + return nil + end + schedule_revive(sched, delay, function() end) + print("lua: wait.yield...") + coroutine.yield() +end +task = { + add = function(fn,delayMs) + return sched:add(fn,delayMs) + end +} print("lua: task adapter code initialised") \ No newline at end of file Property changes on: trunk/yake/common/media/samples/task/events.lua ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/yake/common/media/scripts/raf1.lua =================================================================== --- trunk/yake/common/media/scripts/raf1.lua 2007-08-24 21:25:15 UTC (rev 1821) +++ trunk/yake/common/media/scripts/raf1.lua 2007-08-27 13:45:58 UTC (rev 1822) @@ -1,109 +1,109 @@ -local gworld = scene.gworld -local defaultCam = scene.activeCamera -local actionMap = app.actionMap -local input = yake.input - --------------------------------------- --- Configure graphics --------------------------------------- - --- configure basic scene properties -gworld:setShadowsEnabled(false) -gworld:setAmbientLight(yake.Color(0,0,0,1)) - --- create ninja -local sn = gworld:createSceneNode() -local e = gworld:createEntity("ninja.mesh") -sn:attach(e) - --- create directional light - -local light = gworld:createLight() -- create light - -local lightnode = gworld:createSceneNode() -- attach light to node -lightnode:attach(light) - -light.type = yake.graphics.Light.LT_DIRECTIONAL -- configure light -light:setDiffuseColour(yake.Color(1,1,1,1)) -light.direction = yake.Vector3(0,-1,1) - --- configure active (=default) camera - -local cam = scene.activeCamera -assert(cam) -cam.position = yake.Vector3(100,20,-200) -cam:setFixedYawAxis( yake.Vector3.UnitY ) -- keep upwards direction constant -cam:lookAt( yake.Vector3(0,100,0) ) -- look at our ninja! - --------------------------------------- --- Configure input --------------------------------------- - -local activeKeys = {} -- Store the keys that are active in current frame. - --- We demonstrate two ways to bind Lua callbacks to a keyboard action. --- #1 demonstrates the details --- #2 shows how to achieve the same thing fast and Lua-style - ------- #1: "The Long Way" - ---local idLeft = input.ActionId.fromName("left") -- look up ActionId by its name (useful for user-defined ones) -local idLeft = input.ACTIONID_LEFT -- using an ActionId constant - --- Connect key "Cursor Left" to action "left": -local acLeft = input.KeyboardActionCondition(app.keyboard, input.KC_LEFT, input.KAM_CONTINUOUS) -actionMap:reg(idLeft,acLeft) - --- Our Lua callback handler: -function onLeft() - activeKeys["left"] = true -end - -actionMap:connectToAction(idLeft,onLeft) -- by Action ID - ------- #2: "Shortcut" (using action names and anonymous Lua functions) - -actionMap:reg("right", input.KeyboardActionCondition(app.keyboard, input.KC_RIGHT, input.KAM_CONTINUOUS)) -actionMap:connectToAction("right", - function() - activeKeys["right"] = true - end) - -------- Let's define a few helper functions to make things easier: - -function createKeyAction(action, key, keymode) - return actionMap:reg(action, input.KeyboardActionCondition(app.keyboard, key, keymode )) -end -function bindAction(action, handler) - return actionMap:connectToAction(action, handler) -end - -------- Bind the rest of the keys to actions: - -createKeyAction("forward", input.KC_UP, input.KAM_CONTINUOUS) -bindAction("forward", function() - activeKeys["forward"] = true - end) - -createKeyAction("reverse", input.KC_DOWN, input.KAM_CONTINUOUS) -bindAction("reverse", function() - activeKeys["reverse"] = true - end) - ------------------------------------ -function onFrame(timeElapsed) - local distance = 25 * timeElapsed - for k,v in pairs(activeKeys) do - if k == "left" then - cam:translate( -1 * yake.Vector3.UnitX * distance ) - elseif k == "right" then - cam:translate( 1 * yake.Vector3.UnitX * distance ) - elseif k == "forward" then - cam:translate( -1 * yake.Vector3.UnitZ * distance ) - elseif k == "reverse" then - cam:translate( 1 * yake.Vector3.UnitZ * distance ) - end - end - -- prepare for next frame: - activeKeys = {} +local gworld = scene.gworld +local defaultCam = scene.activeCamera +local actionMap = app.actionMap +local input = yake.input + +-------------------------------------- +-- Configure graphics +-------------------------------------- + +-- configure basic scene properties +gworld:setShadowsEnabled(false) +gworld:setAmbientLight(yake.Color(0,0,0,1)) + +-- create ninja +local sn = gworld:createSceneNode() +local e = gworld:createEntity("ninja.mesh") +sn:attach(e) + +-- create directional light + +local light = gworld:createLight() -- create light + +local lightnode = gworld:createSceneNode() -- attach light to node +lightnode:attach(light) + +light.type = yake.graphics.Light.LT_DIRECTIONAL -- configure light +light:setDiffuseColour(yake.Color(1,1,1,1)) +light.direction = yake.Vector3(0,-1,1) + +-- configure active (=default) camera + +local cam = scene.activeCamera +assert(cam) +cam.position = yake.Vector3(100,20,-200) +cam:setFixedYawAxis( yake.Vector3.UnitY ) -- keep upwards direction constant +cam:lookAt( yake.Vector3(0,100,0) ) -- look at our ninja! + +-------------------------------------- +-- Configure input +-------------------------------------- + +local activeKeys = {} -- Store the keys that are active in current frame. + +-- We demonstrate two ways to bind Lua callbacks to a keyboard action. +-- #1 demonstrates the details +-- #2 shows how to achieve the same thing fast and Lua-style + +------ #1: "The Long Way" + +--local idLeft = input.ActionId.fromName("left") -- look up ActionId by its name (useful for user-defined ones) +local idLeft = input.ACTIONID_LEFT -- using an ActionId constant + +-- Connect key "Cursor Left" to action "left": +local acLeft = input.KeyboardActionCondition(app.keyboard, input.KC_LEFT, input.KAM_CONTINUOUS) +actionMap:reg(idLeft,acLeft) + +-- Our Lua callback handler: +function onLeft() + activeKeys["left"] = true +end + +actionMap:connectToAction(idLeft,onLeft) -- by Action ID + +------ #2: "Shortcut" (using action names and anonymous Lua functions) + +actionMap:reg("right", input.KeyboardActionCondition(app.keyboard, input.KC_RIGHT, input.KAM_CONTINUOUS)) +actionMap:connectToAction("right", + function() + activeKeys["right"] = true + end) + +------- Let's define a few helper functions to make things easier: + +function createKeyAction(action, key, keymode) + return actionMap:reg(action, input.KeyboardActionCondition(app.keyboard, key, keymode )) +end +function bindAction(action, handler) + return actionMap:connectToAction(action, handler) +end + +------- Bind the rest of the keys to actions: + +createKeyAction("forward", input.KC_UP, input.KAM_CONTINUOUS) +bindAction("forward", function() + activeKeys["forward"] = true + end) + +createKeyAction("reverse", input.KC_DOWN, input.KAM_CONTINUOUS) +bindAction("reverse", function() + activeKeys["reverse"] = true + end) + +----------------------------------- +function onFrame(timeElapsed) + local distance = 25 * timeElapsed + for k,v in pairs(activeKeys) do + if k == "left" then + cam:translate( -1 * yake.Vector3.UnitX * distance ) + elseif k == "right" then + cam:translate( 1 * yake.Vector3.UnitX * distance ) + elseif k == "forward" then + cam:translate( -1 * yake.Vector3.UnitZ * distance ) + elseif k == "reverse" then + cam:translate( 1 * yake.Vector3.UnitZ * distance ) + end + end + -- prepare for next frame: + activeKeys = {} end \ No newline at end of file Property changes on: trunk/yake/common/media/scripts/raf1.lua ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/yake/common/media/scripts/res1.lua =================================================================== --- trunk/yake/common/media/scripts/res1.lua 2007-08-24 21:25:15 UTC (rev 1821) +++ trunk/yake/common/media/scripts/res1.lua 2007-08-27 13:45:58 UTC (rev 1822) @@ -1,20 +1,20 @@ --- acquire global res::SourceManager -print("acquire SourceManager") -assert( yake.res ) -local res = yake.res -assert( res.global.sourceManager ) -local sourceManager = res.global.sourceManager - --- add some sources -print("add sources") -sourceManager:addSource("file","./") -sourceManager:addSource("file","../../../scripts/tools/luadocs/") - --- find resource using sourceManager: -print("locate project.txt...") -local find = sourceManager:find("project.txt") -if find.valid then - print("found project.txt at: "..find.location) -else - print("could not find project.txt") +-- acquire global res::SourceManager +print("acquire SourceManager") +assert( yake.res ) +local res = yake.res +assert( res.global.sourceManager ) +local sourceManager = res.global.sourceManager + +-- add some sources +print("add sources") +sourceManager:addSource("file","./") +sourceManager:addSource("file","../../../scripts/tools/luadocs/") + +-- find resource using sourceManager: +print("locate project.txt...") +local find = sourceManager:find("project.txt") +if find.valid then + print("found project.txt at: "..find.location) +else + print("could not find project.txt") end \ No newline at end of file Property changes on: trunk/yake/common/media/scripts/res1.lua ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/yake/src/base/templates/yakeSignals.cpp =================================================================== --- trunk/yake/src/base/templates/yakeSignals.cpp 2007-08-24 21:25:15 UTC (rev 1821) +++ trunk/yake/src/base/templates/yakeSignals.cpp 2007-08-27 13:45:58 UTC (rev 1822) @@ -1,53 +1,53 @@ -/* - ------------------------------------------------------------------------------------ - This file is part of YAKE - Copyright (c) 2004 - 2008 The YAKE Team - For the latest information visit http://www.yake.org - ------------------------------------------------------------------------------------ - This program is free software; you can redistribute it and/or modify it under - the terms of the GNU Lesser General Public License as published by the Free Software - Foundation; either version 2 of the License, or (at your option) any later - version. - - This program is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License along with - this program; if not, write to the Free Software Foundation, Inc., 59 Temple - Place - Suite 330, Boston, MA 02111-1307, USA, or go to - http://www.gnu.org/copyleft/lesser.txt. - ------------------------------------------------------------------------------------ - If you are interested in another license model contact the Yake Team via - E-Mail: te...@ya.... - For more information see the LICENSE file in the root directory of the - source code distribution. - ------------------------------------------------------------------------------------ -*/ -#include <yake/base/yakePCH.h> -#include <yake/base/templates/yakeSignals.h> - -namespace yake { - - //----------------------------------------------------- - SignalConnectionGroup::SignalConnectionGroup() - { - } - SignalConnectionGroup::~SignalConnectionGroup() - { - this->clearAndDisconnectAll(); - } - void SignalConnectionGroup::clearAndDisconnectAll() - { - for (SignalConnectionList::const_iterator it = connections_.begin(); - it != connections_.end(); ++it) - (*it).disconnect(); - connections_.clear(); - } - SignalConnectionGroup& SignalConnectionGroup::operator += (const SignalConnection& connection) - { - connections_.push_back( connection ); - return *this; - } - -} // yake +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#include <yake/base/yakePCH.h> +#include <yake/base/templates/yakeSignals.h> + +namespace yake { + + //----------------------------------------------------- + SignalConnectionGroup::SignalConnectionGroup() + { + } + SignalConnectionGroup::~SignalConnectionGroup() + { + this->clearAndDisconnectAll(); + } + void SignalConnectionGroup::clearAndDisconnectAll() + { + for (SignalConnectionList::const_iterator it = connections_.begin(); + it != connections_.end(); ++it) + (*it).disconnect(); + connections_.clear(); + } + SignalConnectionGroup& SignalConnectionGroup::operator += (const SignalConnection& connection) + { + connections_.push_back( connection ); + return *this; + } + +} // yake Property changes on: trunk/yake/src/base/templates/yakeSignals.cpp ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/yake/src/base/yakeConfigFile.cpp =================================================================== --- trunk/yake/src/base/yakeConfigFile.cpp 2007-08-24 21:25:15 UTC (rev 1821) +++ trunk/yake/src/base/yakeConfigFile.cpp 2007-08-27 13:45:58 UTC (rev 1822) @@ -1,279 +1,279 @@ -/* - ------------------------------------------------------------------------------------ - This file is part of YAKE - Copyright (c) 2004 - 2008 The YAKE Team - For the latest information visit http://www.yake.org - ------------------------------------------------------------------------------------ - This program is free software; you can redistribute it and/or modify it under - the terms of the GNU Lesser General Public License as published by the Free Software - Foundation; either version 2 of the License, or (at your option) any later - version. - - This program is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License along with - this program; if not, write to the Free Software Foundation, Inc., 59 Temple - Place - Suite 330, Boston, MA 02111-1307, USA, or go to - http://www.gnu.org/copyleft/lesser.txt. - ------------------------------------------------------------------------------------ - If you are interested in another license model contact the Yake Team via - E-Mail: te...@ya.... - For more information see the LICENSE file in the root directory of the - source code distribution. - ------------------------------------------------------------------------------------ -*/ - -#include <yake/base/yakePCH.h> -#include <yake/base/yakeConfigFile.h> - -namespace yake { - - namespace detail { - } // namespace detail - - Configuration::Configuration() : tree_( new tree_type() ) - { - } - Configuration::Configuration(const Configuration& other) : tree_(other.tree_), prefix_(other.prefix_) - { - } - const Configuration& Configuration::operator=(const Configuration& rhs) - { - if (this == &rhs) - return *this; - tree_ = rhs.tree_; - prefix_ = rhs.prefix_; - return *this; - } - Configuration::Configuration(const Configuration& cfg, const String& path) : tree_( cfg.tree_ ), prefix_(path) - { - if (!prefix_.empty()) - { - // make sure there's a trailing '/' - if (prefix_.at( prefix_.size() -1 ) != '/') - prefix_ += '/'; - } - } - void Configuration::copyFrom(const Configuration& other) - { - tree_.reset( new tree_type() ); - if (other.tree_) - *tree_ = *other.tree_; - prefix_ = other.prefix_; - } - Configuration::~Configuration() - { - } - Configuration::const_iterator Configuration::begin(const String& path) const - { - try { - return tree_->get_child('/',prefix_+path).begin(); - } - catch (boost::property_tree::ptree_error&) - { - return tree_->end(); - } - } - Configuration::const_iterator Configuration::end(const String& path) const - { - try { - return tree_->get_child('/',prefix_+path).end(); - } - catch (boost::property_tree::ptree_error&) - { - return tree_->end(); - } - } - bool Configuration::exists(const String& path) const - { - try { - tree_->get_child('/',prefix_+path); - return true; - } - catch (boost::property_tree::ptree_error&) - { - return false; - } - } - String Configuration::get(const String& pathToValue, const String& defaultValue) const - { - try { - return tree_->get<String>('/',prefix_+pathToValue); - } - catch (...) - { - return defaultValue; - } - } - void Configuration::readFromFile(const String& fn, const String& insertAt) - { - YAKE_ASSERT( insertAt.empty() && "not yet supported" ); - std::ifstream in(fn.c_str()); - if (!in.is_open()) - return; //@todo - boost::property_tree::read_info(in,*tree_); - } - void Configuration::readFromXML(const String& fn, const String& insertAt) - { - YAKE_ASSERT( insertAt.empty() && "not yet supported" ); - std::ifstream in(fn.c_str()); - if (!in.is_open()) - return; //@todo - boost::property_tree::read_xml(in,*tree_); - } - void Configuration::writeToFile(const String& fn, const String& startAt) - { - YAKE_ASSERT( startAt.empty() && "not yet supported" ); - //boost::property_tree::write_info(cout,*tree_); - - std::ofstream out(fn.c_str()); - if (!out.is_open()) - return; //@todo - boost::property_tree::write_info(out,*tree_); - } - void Configuration::writeToXML(const String& fn, const String& startAt) - { - YAKE_ASSERT( startAt.empty() && "not yet supported" ); - //boost::property_tree::write_xml(cout,*tree_); - - std::ofstream out(fn.c_str()); - if (!out.is_open()) - return; //@todo - boost::property_tree::write_xml(out,*tree_); - } - - //----------------------------------------------------- - - IniFile::IniFile() - { - } - /* - ini::const_key_iterator ini::begin(const String& section) const - { - Sections::const_iterator itSect = sections_.find(section); - if (itSect == sections_.end()) - return empty_.end(); - return itSect->second.begin(); - } - ini::const_key_iterator ini::end(const String& section) const - { - Sections::const_iterator itSect = sections_.find(section); - if (itSect == sections_.end()) - return empty_.end(); - return itSect->second.end(); - } - */ - StringVector IniFile::getKeys(const String& section) const - { - Sections::const_iterator itSect = sections_.find(section); - if (itSect == sections_.end()) - return StringVector(); - KeyValueMap::const_iterator it = itSect->second.begin(); - KeyValueMap::const_iterator itEnd = itSect->second.end(); - StringVector ret; - for (; it != itEnd; ++it) - ret.push_back( it->first ); - return ret; - } - StringPairVector IniFile::getKeysAndValues(const String& section) const - { - Sections::const_iterator itSect = sections_.find(section); - if (itSect == sections_.end()) - return StringPairVector(); - StringPairVector ret; - YAKE_FOR_EACH( KeyValueMap::const_iterator, itKey, itSect->second ) - { - const ValueList& values = itKey->second; - YAKE_FOR_EACH( ValueList::const_iterator, itValue, values ) - ret.push_back( StringPair( itKey->first, *itValue ) ); - } - return ret; - } - IniFile::KeyValueMap IniFile::getKeysAndValues2(const String& section) const - { - Sections::const_iterator itSect = sections_.find(section); - if (itSect == sections_.end()) - return IniFile::KeyValueMap(); - return itSect->second; - } - bool IniFile::hasSection(const String& section) const - { - Sections::const_iterator itSect = sections_.find(section); - return (itSect != sections_.end()); - } - IniFile::value IniFile::getFirstValue(const String& section, const String& key) const - { - Sections::const_iterator itSect = sections_.find(section); - if (itSect == sections_.end()) - return false; - KeyValueMap::const_iterator itKey = itSect->second.find(key); - if (itKey == itSect->second.end()) - return false; - const ValueList& values = itKey->second; - if (values.empty()) - return false; - return values.front(); - } - StringVector IniFile::getAllValues(const String& section, const String& key) const - { - Sections::const_iterator itSect = sections_.find(section); - if (itSect == sections_.end()) - return StringVector(); - KeyValueMap::const_iterator itKey = itSect->second.find(key); - if (itKey == itSect->second.end()) - return StringVector(); - const ValueList& values = itKey->second; - return values; - } - bool IniFile::load(const String& filename) - { - std::ifstream in(filename.c_str(), std::ios::in); - if (!in) - return false; - String currSection; - String line; - while (std::getline(in,line)) - { - StringUtil::trim( line, true, true ); // trim left and right - // skip comments (full line and trailing ones) - { - String::size_type commentStart = line.find("#"); - if (String::npos != commentStart) - { - line = line.substr(0,commentStart); - StringUtil::trim(line); - } - } - if (line.empty()) // skip empty lines - continue; - // - if (line[0] == '[') - { - String::size_type endMarker = line.find("]"); - YAKE_ASSERT( endMarker != String::npos ).debug("syntax error in section declaration: missing ']'."); - if (endMarker == String::npos) - continue; - currSection = line.substr(1,endMarker-1); - StringUtil::trim(currSection); - } - else - { - String key,value; - String::size_type splitAt = line.find("="); - if (splitAt != String::npos) - { - key = line.substr(0,splitAt); - value = line.substr(splitAt+1); - StringUtil::trim(key); - StringUtil::trim(value); - } - else - key = line; - sections_[currSection][key].push_back( value ); - } - } - return true; - } -} // yake +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ + +#include <yake/base/yakePCH.h> +#include <yake/base/yakeConfigFile.h> + +namespace yake { + + namespace detail { + } // namespace detail + + Configuration::Configuration() : tree_( new tree_type() ) + { + } + Configuration::Configuration(const Configuration& other) : tree_(other.tree_), prefix_(other.prefix_) + { + } + const Configuration& Configuration::operator=(const Configuration& rhs) + { + if (this == &rhs) + return *this; + tree_ = rhs.tree_; + prefix_ = rhs.prefix_; + return *this; + } + Configuration::Configuration(const Configuration& cfg, const String& path) : tree_( cfg.tree_ ), prefix_(path) + { + if (!prefix_.empty()) + { + // make sure there's a trailing '/' + if (prefix_.at( prefix_.size() -1 ) != '/') + prefix_ += '/'; + } + } + void Configuration::copyFrom(const Configuration& other) + { + tree_.reset( new tree_type() ); + if (other.tree_) + *tree_ = *other.tree_; + prefix_ = other.prefix_; + } + Configuration::~Configuration() + { + } + Configuration::const_iterator Configuration::begin(const String& path) const + { + try { + return tree_->get_child('/',prefix_+path).begin(); + } + catch (boost::property_tree::ptree_error&) + { + return tree_->end(); + } + } + Configuration::const_iterator Configuration::end(const String& path) const + { + try { + return tree_->get_child('/',prefix_+path).end(); + } + catch (boost::property_tree::ptree_error&) + { + return tree_->end(); + } + } + bool Configuration::exists(const String& path) const + { + try { + tree_->get_child('/',prefix_+path); + return true; + } + catch (boost::property_tree::ptree_error&) + { + return false; + } + } + String Configuration::get(const String& pathToValue, const String& defaultValue) const + { + try { + return tree_->get<String>('/',prefix_+pathToValue); + } + catch (...) + { + return defaultValue; + } + } + void Configuration::readFromFile(const String& fn, const String& insertAt) + { + YAKE_ASSERT( insertAt.empty() && "not yet supported" ); + std::ifstream in(fn.c_str()); + if (!in.is_open()) + return; //@todo + boost::property_tree::read_info(in,*tree_); + } + void Configuration::readFromXML(const String& fn, const String& insertAt) + { + YAKE_ASSERT( insertAt.empty() && "not yet supported" ); + std::ifstream in(fn.c_str()); + if (!in.is_open()) + return; //@todo + boost::property_tree::read_xml(in,*tree_); + } + void Configuration::writeToFile(const String& fn, const String& startAt) + { + YAKE_ASSERT( startAt.empty() && "not yet supported" ); + //boost::property_tree::write_info(cout,*tree_); + + std::ofstream out(fn.c_str()); + if (!out.is_open()) + return; //@todo + boost::property_tree::write_info(out,*tree_); + } + void Configuration::writeToXML(const String& fn, const String& startAt) + { + YAKE_ASSERT( startAt.empty() && "not yet supported" ); + //boost::property_tree::write_xml(cout,*tree_); + + std::ofstream out(fn.c_str()); + if (!out.is_open()) + return; //@todo + boost::property_tree::write_xml(out,*tree_); + } + + //----------------------------------------------------- + + IniFile::IniFile() + { + } + /* + ini::const_key_iterator ini::begin(const String& section) const + { + Sections::const_iterator itSect = sections_.find(section); + if (itSect == sections_.end()) + return empty_.end(); + return itSect->second.begin(); + } + ini::const_key_iterator ini::end(const String& section) const + { + Sections::const_iterator itSect = sections_.find(section); + if (itSect == sections_.end()) + return empty_.end(); + return itSect->second.end(); + } + */ + StringVector IniFile::getKeys(const String& section) const + { + Sections::const_iterator itSect = sections_.find(section); + if (itSect == sections_.end()) + return StringVector(); + KeyValueMap::const_iterator it = itSect->second.begin(); + KeyValueMap::const_iterator itEnd = itSect->second.end(); + StringVector ret; + for (; it != itEnd; ++it) + ret.push_back( it->first ); + return ret; + } + StringPairVector IniFile::getKeysAndValues(const String& section) const + { + Sections::const_iterator itSect = sections_.find(section); + if (itSect == sections_.end()) + return StringPairVector(); + StringPairVector ret; + YAKE_FOR_EACH( KeyValueMap::const_iterator, itKey, itSect->second ) + { + const ValueList& values = itKey->second; + YAKE_FOR_EACH( ValueList::const_iterator, itValue, values ) + ret.push_back( StringPair( itKey->first, *itValue ) ); + } + return ret; + } + IniFile::KeyValueMap IniFile::getKeysAndValues2(const String& section) const + { + Sections::const_iterator itSect = sections_.find(section); + if (itSect == sections_.end()) + return IniFile::KeyValueMap(); + return itSect->second; + } + bool IniFile::hasSection(const String& section) const + { + Sections::const_iterator itSect = sections_.find(section); + return (itSect != sections_.end()); + } + IniFile::value IniFile::getFirstValue(const String& section, const String& key) const + { + Sections::const_iterator itSect = sections_.find(section); + if (itSect == sections_.end()) + return false; + KeyValueMap::const_iterator itKey = itSect->second.find(key); + if (itKey == itSect->second.end()) + return false; + const ValueList& values = itKey->second; + if (values.empty()) + return false; + return values.front(); + } + StringVector IniFile::getAllValues(const String& section, const String& key) const + { + Sections::const_iterator itSect = sections_.find(section); + if (itSect == sections_.end()) + return StringVector(); + KeyValueMap::const_iterator itKey = itSect->second.find(key); + if (itKey == itSect->second.end()) + return StringVector(); + const ValueList& values = itKey->second; + return values; + } + bool IniFile::load(const String& filename) + { + std::ifstream in(filename.c_str(), std::ios::in); + if (!in) + return false; + String currSection; + String line; + while (std::getline(in,line)) + { + StringUtil::trim( line, true, true ); // trim left and right + // skip comments (full line and trailing ones) + { + String::size_type commentStart = line.find("#"); + if (String::npos != commentStart) + { + line = line.substr(0,commentStart); + StringUtil::trim(line); + } + } + if (line.empty()) // skip empty lines + continue; + // + if (line[0] == '[') + { + String::size_type endMarker = line.find("]"); + YAKE_ASSERT( endMarker != String::npos ).debug("syntax error in section declaration: missing ']'."); + if (endMarker == String::npos) + continue; + currSection = line.substr(1,endMarker-1); + StringUtil::trim(currSection); + } + else + { + String key,value; + String::size_type splitAt = line.find("="); + if (splitAt != String::npos) + { + key = line.substr(0,splitAt); + value = line.substr(splitAt+1); + StringUtil::trim(key); + StringUtil::trim(value); + } + else + key = line; + sections_[currSection][key].push_back( value ); + } + } + return true; + } +} // yake Property changes on: trunk/yake/src/base/yakeConfigFile.cpp ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/yake/src/base/yakeFileLog.cpp =================================================================== --- trunk/yake/src/base/yakeFileLog.cpp 2007-08-24 21:25:15 UTC (rev 1821) +++ trunk/yake/src/base/yakeFileLog.cpp 2007-08-27 13:45:58 UTC (rev 1822) @@ -1,59 +1,59 @@ -/* - ------------------------------------------------------------------------------------ - This file is part of YAKE - Copyright (c) 2004 - 2008 The YAKE Team - For the latest information visit http://www.yake.org - ------------------------------------------------------------------------------------ - This program is free software; you can redistribute it and/or modify it under - the terms of the GNU Lesser General Public License as published by the Free Software - Foundation; either version 2 of the License, or (at your option) any later - version. - - This program is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License along with - this program; if not, write to the Free Software Foundation, Inc., 59 Temple - Place - Suite 330, Boston, MA 02111-1307, USA, or go to - http://www.gnu.org/copyleft/lesser.txt. - ------------------------------------------------------------------------------------ - If you are interested in another license model contact the Yake Team via - E-Mail: te...@ya.... - For more information see the LICENSE file in the root directory of the - source code distribution. - ------------------------------------------------------------------------------------ -*/ -#include <yake/base/yakePCH.h> -#include <yake/base/yakeLog.h> -#include <yake/base/yakeFileLog.h> -#include <boost/lexical_cast.hpp> - -namespace yake { -namespace logging { - - file_listener::file_listener(const std::string& fileName) - { - fp_.open(fileName.c_str()); - fp_ << "// format:\n"; - fp_ << "// [processId][logId][threadId] [logLevel] message\n"; - fp_.flush(); - } - file_listener::~file_listener() - { - fp_.close(); - } - void file_listener::write(const severity_t sev, const char* msg, const char* logId, const char* procId, threadid_t threadId) - { - formatLogMessage(fp_, sev, msg, logId, procId, threadId ); - fp_.flush(); - } - log_listener_ptr file_listener::add(const std::string& fileName) - { - log_listener_ptr l( new file_listener(fileName) ); - addListener( l.get() ); - return l; - } - -} // logging -} // yake +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#include <yake/base/yakePCH.h> +#include <yake/base/yakeLog.h> +#include <yake/base/yakeFileLog.h> +#include <boost/lexical_cast.hpp> + +namespace yake { +namespace logging { + + file_listener::file_listener(const std::string& fileName) + { + fp_.open(fileName.c_str()); + fp_ << "// format:\n"; + fp_ << "// [processId][logId][threadId] [logLevel] message\n"; + fp_.flush(); + } + file_listener::~file_listener() + { + fp_.close(); + } + void file_listener::write(const severity_t sev, const char* msg, const char* logId, const char* procId, threadid_t threadId) + { + formatLogMessage(fp_, sev, msg, logId, procId, threadId ); + fp_.flush(); + } + log_listener_ptr file_listener::add(const std::string& fileName) + { + log_listener_ptr l( new file_listener(fileName) ); + addListener( l.get() ); + return l; + } + +} // logging +} // yake Property changes on: trunk/yake/src/base/yakeFileLog.cpp ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/yake/src/base/yakeStderrLog.cpp =================================================================== --- trunk/yake/src/base/yakeStderrLog.cpp 2007-08-24 21:25:15 UTC (rev 1821) +++ trunk/yake/src/base/yakeStderrLog.cpp 2007-08-27 13:45:58 UTC (rev 1822) @@ -1,60 +1,60 @@ -/* - ------------------------------------------------------------------------------------ - This file is part of YAKE - Copyright (c) 2004 - 2008 The YAKE Team - For the latest information visit http://www.yake.org - ------------------------------------------------------------------------------------ - This program is free software; you can redistribute it and/or modify it under - the terms of the GNU Lesser General Public License as published by the Free Software - Foundation; either version 2 of the License, or (at your option) any later - version. - - This program is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License along with - this program; if not, write to the Free Software Foundation, Inc., 59 Temple - Place - Suite 330, Boston, MA 02111-1307, USA, or go to - http://www.gnu.org/copyleft/lesser.txt. - ------------------------------------------------------------------------------------ - If you are interested in another license model contact the Yake Team via - E-Mail: te...@ya.... - For more information see the LICENSE file in the root directory of the - source code distribution. - ------------------------------------------------------------------------------------ -*/ -#include <yake/base/yakePCH.h> -#include <yake/base/yakeLog.h> -#include <yake/base/yakeStderrLog.h> -#include <yake/base/native/yakeNative.h> -#include <boost/lexical_cast.hpp> - -namespace yake { -namespace logging { - - stderr_listener::stderr_listener() - { - } - stderr_listener::~stderr_listener() - { - } - void stderr_listener::write(const severity_t sev, const char* msg, const char* logId, const char* procId, threadid_t threadId) - { - std::ostringstream ss; - formatLogMessage(ss, sev, msg, logId, procId, threadId ); - - if (native::debug_Log_available()) //@todo potential performance problem - native::debug_Log( ss.str(), sev ); - else - std::cerr << ss.str(); - } - log_listener_ptr stderr_listener::add() - { - log_listener_ptr l( new stderr_listener() ); - addListener( l.get() ); - return l; - } - -} // logging -} // yake +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#include <yake/base/yakePCH.h> +#include <yake/base/yakeLog.h> +#include <yake/base/yakeStderrLog.h> +#include <yake/base/native/yakeNative.h> +#include <boost/lexical_cast.hpp> + +namespace yake { +namespace logging { + + stderr_listener::stderr_listener() + { + } + stderr_listener::~stderr_listener() + { + } + void stderr_listener::write(const severity_t sev, const char* msg, const char* logId, const char* procId, threadid_t threadId) + { + std::ostringstream ss; + formatLogMessage(ss, sev, msg, logId, procId, threadId ); + + if (native::debug_Log_available()) //@todo potential performance problem + native::debug_Log( ss.str(), sev ); + else + std::cerr << ss.str(); + } + log_listener_ptr stderr_listener::add() + { + log_listener_ptr l( new stderr_listener() ); + addListener( l.get() ); + return l; + } + +} // logging +} // yake Property changes on: trunk/yake/src/base/yakeStderrLog.cpp ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/yake/src/bindings.lua/detail/graphics.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/graphics.lua.cpp 2007-08-24 21:25:15 UTC (rev 1821) +++ trunk/yake/src/bindings.lua/detail/graphics.lua.cpp 2007-08-27 13:45:58 UTC (rev 1822) @@ -1,182 +1,182 @@ -/* - ------------------------------------------------------------------------------------ - This file is part of YAKE - Copyright (c) 2004 - 2008 The YAKE Team - For the latest information visit http://www.yake.org - ------------------------------------------------------------------------------------ - This program is free software; you can redistribute it and/or modify it under - the terms of the GNU Lesser General Public License as published by the Free Software - Foundation; either version 2 of the License, or (at your option) any later - version. - - This program is distributed in the hope that it will be useful, but WITHOUT - ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public License along with - this program; if not, write to the Free Software Foundation, Inc., 59 Temple - Place - Suite 330, Boston, MA 02111-1307, USA, or go to - http://www.gnu.org/copyleft/lesser.txt. - ------------------------------------------------------------------------------------ - If you are interested in another license model contact the Yake Team via - E-Mail: te...@ya.... - For more information see the LICENSE file in the root directory of the - source code distribution. - ------------------------------------------------------------------------------------ -*/ -#include <yake/config.h> -#if YAKE_ENABLE_LUA_GRAPHICS == 1 - -// See task.lua.cpp -#include <yake/bindings.lua/common/yake.lua.shared_ptr.h> - -#include <yake/bindings.lua/bindings.lua.h> // Don't forget to include this for proper dllexport! - -#include <yake/base/templates/yakeSmartAssert.h> -#include <yake/base/yake.h> -#include <yake/graphics/yakeGraphics.h> - -#include <yake/bindings.lua/detail/private.h> -#include <yake/bindings.lua/common/yake.lua.any_converter.h> - -#include <luabind/discard_result_policy.hpp> -#include <luabind/iterator_policy.hpp> -#include <luabind/operator.hpp> - -namespace yake { -namespace graphics { - ISceneNode* ISceneNode_getChildByName_NameOnly(ISceneNode* n, const String& name) - { - return (n ? n->getChildByName(name,false) : 0); - } - ISceneNode* IWorld_createSceneNode_NoName(IWorld* w) - { - return (w ? w->createSceneNode() : 0); - } - - void bind( lua_State* L ) - { - YAKE_ASSERT( L ); - if (!L) - return; - - using namespace luabind; - -#define YAKE_GRAPHICS_MODULE L, "yake" - - module( YAKE_GRAPHICS_MODULE ) - [ - namespace_("graphics") - [ - class_<ISceneNode,Movable>("SceneNode") - .enum_("TransformSpace") - [ - value("TS_LOCAL",ISceneNode::TS_LOCAL), - value("TS_PARENT",ISceneNode::TS_PARENT), - value("TS_WORLD",ISceneNode::TS_WORLD) - ] - .property("name", &ISceneNode::getName, &ISceneNode::setName) - .property("scale", &ISceneNode::getScale, &ISceneNode::setScale) - .property("parent", &ISceneNode::getParent) - .def("setInheritScale", &ISceneNode::setInheritScale) - .def("addChild", &ISceneNode::addChildNode) - .def("createChildNode", &ISceneNode::createChildNode) - .def("attach", &ISceneNode::attachEntity) - .def("attach", &ISceneNode::attachCamera) - .def("attach", &ISceneNode::attachLight) - .def("attach", &ISceneNode::attachParticleSystem) - .def("detach", (void(ISceneNode::*)(IEntity*))&ISceneNode::detach) - .def("detach", (void(ISceneNode::*)(ILight*))&ISceneNode::detach) - .def("detach", (void(ISceneNode::*)(ICamera*))&ISceneNode::detach) - .def("detach", (void(ISceneNode::*)(IParticleSystem*))&ISceneNode::detach) - .def("getChildByName", &ISceneNode::getChildByName) - .def("getChildByName", &ISceneNode_getChildByName_NameOnly) - .def("translate", &ISceneNode::translate) - .def("rotate", &ISceneNode::rotate) - , - cl... [truncated message content] |
From: <psy...@us...> - 2007-08-27 17:13:48
|
Revision: 1823 http://yake.svn.sourceforge.net/yake/?rev=1823&view=rev Author: psyclonist Date: 2007-08-27 10:13:37 -0700 (Mon, 27 Aug 2007) Log Message: ----------- * [ent/bindings.lua] added Trigger Modified Paths: -------------- trunk/yake/samples/ent/sampleEntFsm/demo.cpp trunk/yake/scripts/premake/samples.lua trunk/yake/src/bindings.lua/detail/ent.lua.cpp trunk/yake/src/ent/entity.cpp trunk/yake/yake/ent/ent.h trunk/yake/yake/ent/object.h trunk/yake/yake/plugins/scriptingLua/ScriptingSystemLua.h Added Paths: ----------- trunk/yake/common/media/scripts/o_trigger.lua trunk/yake/src/yake/ trunk/yake/src/yake/ent/ trunk/yake/src/yake/ent/trigger.cpp trunk/yake/yake/ent/trigger.h Added: trunk/yake/common/media/scripts/o_trigger.lua =================================================================== --- trunk/yake/common/media/scripts/o_trigger.lua (rev 0) +++ trunk/yake/common/media/scripts/o_trigger.lua 2007-08-27 17:13:37 UTC (rev 1823) @@ -0,0 +1,99 @@ +print("> Starting object script..."); +function startup() + --this:fsm("main"):connectTo("alive",fn) -- connects to 'enter', 'tick', 'exit' + --this:fsm("main"):connectToEnter("dead",fn) -- connects to 'enter' only + --this:fsm("main"):connect("alive", fnEnter, fnTick, fnExit) + + this:events("spawn"):connect( + function() + + end + ) +end +event = { + on_spawn = function() + print(" script event.on_spawn") + end, + on_tick = function() + print(" script event.on_tick") + end, + on_die = function() + print(" script event.on_die") + end, + -- various: + onArrived = function() --triggered as a result of "go to" + end, + -- Trigger + on_toggle = function(a) + print("event.on_toggle") + end +} +fsm = { + main = { + states = { + awakening, + alive, + dead + }, + transitions = { + {awakening,"spawn",alive}, + {alive,"die",dead} + } + } +} +state = { + ticks = 0, + off = { + on_enter = function() + print("state.off.enter()") + + this:setCondition(function() return (state.ticks >= 1 and state.ticks <= 3) end) + this:events():get("onTriggered"):connect( function(a) print("TRIGGER:onTriggered:",a) end ) + end, + on_tick = function() + state.ticks = state.ticks + 1 + print("TRIGGER off.tick()",state.ticks) + -- + --if (state.off.ticks == 1) then + -- this:processFsmEvent("trigger") + --end + -- + end, + on_exit = function() + print("state.off.exit()") + end + } + , + on = { + on_enter = function() + print("state.on.enter()") + --this:processFsmEvent("trigger") + --this:events():get("onTriggered"):fire() + end, + on_tick = function() + state.ticks = state.ticks + 1 + print("TRIGGER on.tick()",state.ticks) + end, + on_exit = function() + print("state.on.exit()") + end + } + , + dead = { + on_enter = function() + print(" script state.dead.on_enter") + end, + on_tick = function() + print(" script state.dead.on_tick") + end, + on_exit = function() + print(" script state.dead.on_exit") + end + } +} +print("> Object script up."); + +function main() + print("main()") +end + Modified: trunk/yake/samples/ent/sampleEntFsm/demo.cpp =================================================================== --- trunk/yake/samples/ent/sampleEntFsm/demo.cpp 2007-08-27 13:45:58 UTC (rev 1822) +++ trunk/yake/samples/ent/sampleEntFsm/demo.cpp 2007-08-27 17:13:37 UTC (rev 1823) @@ -2,11 +2,13 @@ #include "yake/base/yake.h" #include "yake/ent/ent.h" #include "yake/scripting/scripting.h" +#include "yake/bindings.lua/common/yake.lua.common.h" +#include "yake/plugins/scriptingLua/ScriptingSystemLua.h" #include "yake/bindings.lua/bindings.lua.h" #include "yake/bindings.lua/bindings.lua.ent.h" +#include "yake/res/res.h" using namespace yake; - namespace exapp { // Commonly used states for this application's objects. const std::string ksAwakening = "awakening"; @@ -31,6 +33,11 @@ ent::Entity* ent = ent::Entity::cast(obj); YAKE_ASSERT( ent ); ent->attachVM(vm,"main"); + + if (ent::Trigger::cast(ent)) + luabind::globals( static_cast<scripting::LuaVM*>(vm.get())->getLuaState() )["this"] = ent::Trigger::cast(ent); + else + luabind::globals( static_cast<scripting::LuaVM*>(vm.get())->getLuaState() )["this"] = ent; } virtual void onDestroyObject(ent::Object* obj) { @@ -46,18 +53,7 @@ ent::Entity* ent = ent::Entity::cast(obj); YAKE_ASSERT( ent ); - // Add default FSM states and transitions: - - ent->addFsmState(ksAwakening); - ent->addFsmState(ksAlive); - ent->addFsmState(ksDead); - - ent->addFsmTransition(ksAwakening,"spawn",ksAlive); - ent->addFsmTransition(ksAlive,"die",ksDead); - - // Set initial state: - - ent->setFsmState(ksAwakening); + ent->processFsmEvent("spawn"); } private: scripting::IScriptingSystem& scriptingSys_; @@ -69,6 +65,7 @@ }; IMPL_CO_1(SimpleGraphicsCo,"Component") } // namespace exapp + #ifdef OOSTATE struct oostate { @@ -181,12 +178,19 @@ machine.processEvent("go"); } #endif -#include "yake/bindings.lua/common/yake.lua.common.h" -#include "yake/plugins/scriptingLua/ScriptingSystemLua.h" int main(int argc, char* argv[]) { try { + // create and attach log listeners + typedef SharedPtr<logging::log_listener> log_listener_ptr; + log_listener_ptr toStdErr( new yake::logging::stderr_listener() ); + logging::addListener( toStdErr.get() ); + + // Setup resources + res::SourceFactory::global().reg<res::FileSource>("file"); + res::SourceManager::global().addSource("file","../../common/media/scripts/"); + // Create the scripting system we want to use (Lua). SharedPtr<scripting::IScriptingSystem> luaSys = templates::create<scripting::IScriptingSystem>("lua"); YAKE_ASSERT( luaSys.get() ); @@ -203,33 +207,59 @@ SharedPtr<exapp::ExampleAppObjectMgrListener> exappObjInitializer( new exapp::ExampleAppObjectMgrListener(*luaSys) ); objMgr.attachListener( exappObjInitializer.get(), "exapp_listener", ent::ObjectManager::kKeepOwnership ); - // Register object class + // Register object class(es) ent::RegistrationResult ret = objMgr.registerClass<ent::Entity>("Entity"); YAKE_ASSERT( ret.first == object::RC_OK ); + ret = objMgr.registerClass<ent::Trigger>("Trigger"); + YAKE_ASSERT( ret.first == object::RC_OK ); + + // Create trigger + { + ent::Trigger* trigger = ent::Trigger::cast(objMgr.makeObject("Trigger")); + YAKE_ASSERT( trigger ); + } + + for (size_t i=0; i<10; ++i) + objMgr.tick(); + // Let's create an object. - //ent::Object* o = objMgr.makeObject(ret.second); // create by ClassId - ent::Object* o = objMgr.makeObject("Entity"); // create by class name - YAKE_ASSERT( o ); - ent::Entity* e = ent::Entity::cast(o); // cast to Entity* - YAKE_ASSERT( e ); - e->properties().add("location",property::makeValueProperty<String>("")); + if (false) + { + //ent::Object* o = objMgr.makeObject(ret.second); // create by ClassId + ent::Object* o = objMgr.makeObject("Entity"); // create by class name + YAKE_ASSERT( o ); + ent::Entity* e = ent::Entity::cast(o); // cast to Entity* + YAKE_ASSERT( e ); + e->properties().add("location",property::makeValueProperty<String>("")); - luabind::globals( static_cast<scripting::LuaVM*>(e->getFsmVM().get())->getLuaState() )["this"] = e; + // Add default FSM states and transitions: - // NB At this point the FSM has been set up by the exapp listener! - // Also the scripting VM has been initialized and is ready for use. + e->addFsmState(exapp::ksAwakening); + e->addFsmState(exapp::ksAlive); + e->addFsmState(exapp::ksDead); - // Do some message/event processing - objMgr.makeAndPostMessage( o, int(1) ); // to specific target - objMgr.makeAndBroadcastMessage( int(2) ); // to all objects + e->addFsmTransition(exapp::ksAwakening,"spawn",exapp::ksAlive); + e->addFsmTransition(exapp::ksAlive,"die",exapp::ksDead); - // Do some FSM event processing: - e->processFsmEvent("spawn"); - objMgr.tick(); // triggers o->tick(), also triggers message handling! - objMgr.tick(); - e->processFsmEvent("die"); + // Set initial state: + e->setFsmState(exapp::ksAwakening); + + // NB At this point the FSM has been set up by the exapp listener! + // Also the scripting VM has been initialized and is ready for use. + + // Do some message/event processing + objMgr.makeAndPostMessage( o, int(1) ); // to specific target + objMgr.makeAndBroadcastMessage( int(2) ); // to all objects + + // Do some FSM event processing: + e->processFsmEvent("spawn"); + objMgr.tick(); // triggers o->tick(), also triggers message handling! + objMgr.tick(); + e->processFsmEvent("die"); + } + //@todo use scheduler for yield/resume functionality. (code in prototype is in fsm2_lua.cpp) //e->getVM().resume(); Modified: trunk/yake/scripts/premake/samples.lua =================================================================== --- trunk/yake/scripts/premake/samples.lua 2007-08-27 13:45:58 UTC (rev 1822) +++ trunk/yake/scripts/premake/samples.lua 2007-08-27 17:13:37 UTC (rev 1823) @@ -47,6 +47,8 @@ useComponent("scripting") useComponent("ent") useComponent("bindings.lua") + useDep("lua") + useDep("luabind") end -------------------------------------- Modified: trunk/yake/src/bindings.lua/detail/ent.lua.cpp =================================================================== --- trunk/yake/src/bindings.lua/detail/ent.lua.cpp 2007-08-27 13:45:58 UTC (rev 1822) +++ trunk/yake/src/bindings.lua/detail/ent.lua.cpp 2007-08-27 17:13:37 UTC (rev 1823) @@ -108,6 +108,38 @@ Object::EventAccess& x = o.events(); return &x; } + struct TriggerConditionWrapper + { + luabind::object fn_; + typedef boost::shared_ptr<TriggerConditionWrapper> pointer; + bool execute() + { + try { + return luabind::call_function<bool>(fn_); + } + catch (luabind::cast_failed& ex) + { + YAKE_LOG_ERROR("ent.lua",String("TriggerConditionWrapper: cast_failed: ") + ex.what()); + return false; + } + } + }; + static void Trigger_setCondition(Trigger& trigger, luabind::object o) + { + if (!o || luabind::type(o) != LUA_TFUNCTION) + return; + TriggerConditionWrapper::pointer p( new TriggerConditionWrapper() ); + p->fn_ = o; + trigger.setCondition( boost::bind(&TriggerConditionWrapper::execute,p) ); + } + static bool Trigger_isOn(const Trigger& trigger) + { + return (trigger.getCurrentFsmState() == "on"); + } + static bool Trigger_isOff(const Trigger& trigger) + { + return (trigger.getCurrentFsmState() == "off"); + } //------------------------------------------------------------------------- // Helper struct so that we gain access to the private member // "properties_" in Object::PropertyAccess: @@ -242,6 +274,14 @@ module( YAKE_MODEL_MODULE ) [ + class_<Trigger,Entity>( "Trigger" ) + .def( "setCondition", &Trigger_setCondition) + .property( "on", &Trigger_isOn) + .property( "off", &Trigger_isOff) + ]; + + module( YAKE_MODEL_MODULE ) + [ class_<ObjectManager>( "ObjectManager" ) .def( "makeObject", (Object*(ObjectManager::*)(const String&))&ObjectManager::makeObject ) .def( "getObject", &ObjectManager::getObject ) @@ -280,6 +320,8 @@ YAKE_ASSERT( luabind::type(tbl2) == LUA_TTABLE ); luabind::object fnObj = tbl2[fn.c_str()]; + if (luabind::type(fnObj) == LUA_TNIL) + return; YAKE_ASSERT( luabind::type(fnObj) == LUA_TFUNCTION ); fnObj(); @@ -302,7 +344,7 @@ LuaFsmObjectListener::LuaFsmObjectListener(scripting::IScriptingSystem& scriptingSystem) : scriptingSystem_(scriptingSystem) { - startScript_ = scriptingSystem_.createScriptFromFile("../../common/media/scripts/o_fsm_test.lua"); + startScript_ = scriptingSystem_.createScriptFromFile("o_fsm_test.lua"); YAKE_ASSERT( startScript_.get() ); } void LuaFsmObjectListener::onInit(Object& obj) @@ -322,8 +364,10 @@ Entity* ent = Entity::cast(&obj); if (ent) { - ent->getFsmVM()->execute("event.on_tick()"); - ent->getFsmVM()->execute("state." + ent->getCurrentFsmState() + ".on_tick()"); + scripting::VMPtr vm = ent->getFsmVM(); + vm->execute("event.on_tick()"); + //vm->execute("state." + ent->getCurrentFsmState() + ".on_tick()"); + detail::executeOfTable_2(*vm,"state",ent->getCurrentFsmState(),"on_tick"); } } void LuaFsmObjectListener::onFsmEventHandled(Object& obj, const object_fsm&, const object_fsm::event_type& evt) Modified: trunk/yake/src/ent/entity.cpp =================================================================== --- trunk/yake/src/ent/entity.cpp 2007-08-27 13:45:58 UTC (rev 1822) +++ trunk/yake/src/ent/entity.cpp 2007-08-27 17:13:37 UTC (rev 1823) @@ -60,7 +60,9 @@ } void Entity::setFsmState(const fsm_state_type& state) { + //@todo exit previous state? m_.setState(state); + //onEnter(m_,state); } void Entity::onEnter(const object_fsm& fsm, const object_fsm::state_type& state) { Added: trunk/yake/src/yake/ent/trigger.cpp =================================================================== --- trunk/yake/src/yake/ent/trigger.cpp (rev 0) +++ trunk/yake/src/yake/ent/trigger.cpp 2007-08-27 17:13:37 UTC (rev 1823) @@ -0,0 +1,73 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#include "yake/ent/pch.h" +#include "yake/ent/ent.h" + +namespace yake { +namespace ent { + + IMPL_OBJECT(Trigger) + + void Trigger::setCondition(const ConditionFn& fn) + { + cond_ = fn; + } + Trigger::Trigger() + { + this->attachListener( this, "this", ObjectListenerManager::kKeepOwnership ); + + this->addFsmState("dead"); + this->addFsmState("off"); + this->addFsmState("on"); + this->addFsmTransition("dead","spawn","off"); + this->addFsmTransition("off","toggle","on"); + this->addFsmTransition("on","toggle","off"); + + this->setFsmState("dead"); + + this->events().createAndAdd("onTriggered"); + + //this->properties().add("condition",property::makePointerProperty<boost::function<bool(void)> >( &cond_ ) ); + //this->properties().add("condition",property::makePointerProperty<luabind::object>( &cond_ ) ); + } + void Trigger::onTick() + { + Entity::onTick(); + const bool condMet = cond_ ? cond_() : false; + if (condMet && getCurrentFsmState()=="off" || + !condMet && getCurrentFsmState()=="on") + { + this->processFsmEvent("toggle"); + } + } + void Trigger::onFsmEnterState(Object&,/*const String& fsmName, */const object_fsm&, const object_fsm::state_type& state) + { + this->events().get("onTriggered")->fire( (state=="on") ); + + } +} // namespace ent +} // namespace yake Modified: trunk/yake/yake/ent/ent.h =================================================================== --- trunk/yake/yake/ent/ent.h 2007-08-27 13:45:58 UTC (rev 1822) +++ trunk/yake/yake/ent/ent.h 2007-08-27 17:13:37 UTC (rev 1823) @@ -35,6 +35,7 @@ #include "yake/ent/object_mgr.h" #include "yake/ent/object_mgr_listener.h" #include "yake/ent/entity.h" +#include "yake/ent/trigger.h" #endif Modified: trunk/yake/yake/ent/object.h =================================================================== --- trunk/yake/yake/ent/object.h 2007-08-27 13:45:58 UTC (rev 1822) +++ trunk/yake/yake/ent/object.h 2007-08-27 17:13:37 UTC (rev 1823) @@ -57,9 +57,12 @@ IMPL_CLASS_RTTI(CLASS) \ CLASS* CLASS::cast(::yake::ent::Object* obj) \ { \ - return (obj ? ((obj->isA() == CLASS::cls()) ? dynamic_cast<CLASS*>(obj) : 0 ) : 0); \ + return dynamic_cast<CLASS*>(obj); \ } + // @todo This cast() implementaiton would have to use obj->isKondOf(CLASS::cls()) to be useful! + // return (obj ? ((obj->isA() == CLASS::cls()) ? dynamic_cast<CLASS*>(obj) : 0 ) : 0); \ + /** Base class for complex objects with unique ids, properties and default events. @note properties: id (ObjectId) */ Added: trunk/yake/yake/ent/trigger.h =================================================================== --- trunk/yake/yake/ent/trigger.h (rev 0) +++ trunk/yake/yake/ent/trigger.h 2007-08-27 17:13:37 UTC (rev 1823) @@ -0,0 +1,61 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 2004 - 2008 The YAKE Team + For the latest information visit http://www.yake.org + ------------------------------------------------------------------------------------ + This program is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License as published by the Free Software + Foundation; either version 2 of the License, or (at your option) any later + version. + + This program is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License along with + this program; if not, write to the Free Software Foundation, Inc., 59 Temple + Place - Suite 330, Boston, MA 02111-1307, USA, or go to + http://www.gnu.org/copyleft/lesser.txt. + ------------------------------------------------------------------------------------ + If you are interested in another license model contact the Yake Team via + E-Mail: te...@ya.... + For more information see the LICENSE file in the root directory of the + source code distribution. + ------------------------------------------------------------------------------------ +*/ +#ifndef YAKE_ENT_TRIGGER_H +#define YAKE_ENT_TRIGGER_H + +#include "yake/ent/prerequisites.h" +#include "yake/ent/entity.h" + +namespace yake { +namespace ent { + + struct YAKE_ENT_API Trigger : public Entity, public ObjectListener + { + DECL_OBJECT(Trigger,"Trigger") + + Trigger(); + //virtual ~Trigger() {} + + typedef boost::function<bool(void)> ConditionFn; + void setCondition(const ConditionFn&); + + private: + virtual void onTick(); + private: + virtual void onFsmEventHandled(Object&, const object_fsm&, const object_fsm::event_type&) {} + virtual void onFsmEnterState(Object&,/*const String& fsmName, */const object_fsm&, const object_fsm::state_type& state); + virtual void onFsmExitState(Object&,/*const String& fsmName, */const object_fsm&, const object_fsm::state_type& state) {} + + private: + ConditionFn cond_; + }; + +} // namespace ent +} // namespace yake + +#endif + Modified: trunk/yake/yake/plugins/scriptingLua/ScriptingSystemLua.h =================================================================== --- trunk/yake/yake/plugins/scriptingLua/ScriptingSystemLua.h 2007-08-27 13:45:58 UTC (rev 1822) +++ trunk/yake/yake/plugins/scriptingLua/ScriptingSystemLua.h 2007-08-27 17:13:37 UTC (rev 1823) @@ -31,6 +31,7 @@ #include <boost/enable_shared_from_this.hpp> #include <boost/shared_ptr.hpp> #include <boost/noncopyable.hpp> +#include <yake/scripting/yakeScriptingSystem.h> #include <yake/res/res.h> #if defined( YAKE_SCRIPTINGLUA_EXPORTS ) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |