Thread: [Yake-svn] SF.net SVN: yake: [1420] trunk/yake
Status: Beta
Brought to you by:
psyclonist
From: <psy...@us...> - 2006-08-07 23:31:32
|
Revision: 1420 Author: psyclonist Date: 2006-08-07 16:31:14 -0700 (Mon, 07 Aug 2006) ViewCVS: http://svn.sourceforge.net/yake/?rev=1420&view=rev Log Message: ----------- cumulative patch 0000007 by mj (Thanks!), small fixes by psy Modified Paths: -------------- trunk/yake/SConstruct trunk/yake/buildspec.xml trunk/yake/src/yake/samples/model/dotScene/demo.cpp trunk/yake/src/yapp/samples/misc/vehicle/yakeDemo.cpp Modified: trunk/yake/SConstruct =================================================================== --- trunk/yake/SConstruct 2006-08-07 22:29:16 UTC (rev 1419) +++ trunk/yake/SConstruct 2006-08-07 23:31:14 UTC (rev 1420) @@ -43,7 +43,7 @@ optimization_flags = ' -O3 ' # debug flag. -g[Level] -debug_flags = ' -g ' +debug_flags = ' -g2 -O0' # if you want to profile with GNU gprof profiler_flags = ' -pg ' @@ -63,6 +63,8 @@ BuildDir( build_dir, '.', duplicate = 0 ) +cc_flags += debug_flags + env = Environment( CCFLAGS = cc_flags ) ####################################################### Modified: trunk/yake/buildspec.xml =================================================================== --- trunk/yake/buildspec.xml 2006-08-07 22:29:16 UTC (rev 1419) +++ trunk/yake/buildspec.xml 2006-08-07 23:31:14 UTC (rev 1420) @@ -13,6 +13,7 @@ <include>dependencies/PLSM</include> <include>dependencies/ode/include</include> <include>dependencies/luabind</include> + <include>/usr/include/CEGUI</include> <include>/usr/local/include/CEGUI</include> </Common> @@ -104,22 +105,79 @@ </BuildSharedLibrary> <BuildSharedLibrary + name="yakeNet" + src="src/yake/net" + > + <libadd>yakeBase</libadd> + </BuildSharedLibrary> + + <BuildSharedLibrary + name="yakeLoader" + src="src/yake/loader" + > + <libadd>yakeBase</libadd> + </BuildSharedLibrary> + + + + <BuildSharedLibrary + name="yakeModel" + src="src/yake/model" + > + <libadd>yakeBase</libadd> + <libadd>yakeLoader</libadd> + </BuildSharedLibrary> + + + <!-- Uncomment if you want to use it :D + <BuildSharedLibrary name="yakeThread" src="src/yake/thread" > <libadd>yakeBase</libadd> <libadd>ZThread</libadd> </BuildSharedLibrary> + --> + <!-- doesn't contain any files <BuildSharedLibrary + name="yakeStatemachine" + src="src/yake/statemachine" + > + <libadd>yakeBase</libadd> + </BuildSharedLibrary> + --> + + <!-- doesn't contain any files + <BuildSharedLibrary name="yakeObject" src="src/yake/object" > <libadd>yakeBase</libadd> </BuildSharedLibrary> + --> + <BuildSharedLibrary + name="yakeEnt" + src="src/yake/ent" + > + <libadd>yakeBase</libadd> + <!--<libadd>yakeObject</libadd>--> + <!--<libadd>yakeStatemachine</libadd>--> + </BuildSharedLibrary> + <!-- <BuildSharedLibrary + name="yakeEntLua" + src="src/yake/plugins/entLua" + > + <libadd>yakeBase</libadd> + <libadd>yakeEnt</libadd> + <libadd>lua</libadd> + <libadd>luabind</libadd> + </BuildSharedLibrary> + + <BuildSharedLibrary name="yakeRx" src="src/yake/rx" > @@ -165,7 +223,6 @@ > <libadd>yakeBase</libadd> <libadd>luabind</libadd> - <libadd>lualib</libadd> <libadd>lua</libadd> </BuildSharedLibrary> @@ -176,7 +233,6 @@ > <libadd>yakeBase</libadd> <libadd>luabind</libadd> - <libadd>lualib</libadd> <libadd>lua</libadd> </BuildSharedLibrary> @@ -186,7 +242,6 @@ > <libadd>yakeBase</libadd> <libadd>luabind</libadd> - <libadd>lualib</libadd> <libadd>lua</libadd> </BuildSharedLibrary> @@ -196,7 +251,6 @@ > <libadd>yakeBase</libadd> <libadd>luabind</libadd> - <libadd>lualib</libadd> <libadd>lua</libadd> </BuildSharedLibrary> @@ -218,6 +272,7 @@ <libadd>yappEvents</libadd> </BuildSharedLibrary> +<!-- <BuildSharedLibrary name="yappLoader" src="src/yapp/loader" @@ -232,6 +287,7 @@ <libadd>yappBase</libadd> <libadd>yappLoader</libadd> </BuildSharedLibrary> + --> <BuildSharedLibrary name="yappMsg" @@ -246,8 +302,8 @@ > <libadd>yappBase</libadd> <libadd>yappMsg</libadd> - </BuildSharedLibrary>--> - + </BuildSharedLibrary> + --> <BuildSharedLibrary name="yappVehicle" src="src/yapp/vehicle" @@ -255,7 +311,7 @@ <libadd>yappBase</libadd> <libadd>yakephysicsODE</libadd> </BuildSharedLibrary> - + <BuildSharedLibrary name="yappraf" src="src/yapp/raf" @@ -279,15 +335,15 @@ src="src/yapp/plugins/entLua" > <libadd>yappEnt</libadd> - </BuildSharedLibrary>--> + </BuildSharedLibrary> <BuildSharedLibrary name="yappmodelLuaBindings" src="src/yapp/plugins/modelLuaBindings" > - <!--libadd>yappEnt</libadd--> <libadd>luabind</libadd> </BuildSharedLibrary> + --> <BuildSharedLibrary name="yappTerrainPhysicsManager" @@ -322,6 +378,7 @@ <libadd>common_libs</libadd> </BuildProgram> + <!-- <BuildProgram name="DotSceneGraphicsDemo" src="src/yapp/samples/graphics/dotScene" @@ -347,7 +404,24 @@ <libadd>yappModel</libadd> <libadd>yappLoader</libadd> </BuildProgram> + --> + <!-- + <BuildProgram + name="roserver" + src="src/yake/samples/net/roserver" + > + <libadd>common_libs</libadd> + </BuildProgram> + + <BuildProgram + name="roclient" + src="src/yake/samples/net/roclient" + > + <libadd>common_libs</libadd> + </BuildProgram> +--> +<!-- <BuildProgram name="VehicleDemo" src="src/yapp/samples/base/vehicle" @@ -358,8 +432,19 @@ <libadd>yappraf</libadd> </BuildProgram> - <!-- <BuildProgram + name="sampleEntFSM" + src="src/yake/samples/ent/sampleEntFsm" + > + <libadd>common_libs</libadd> + <libadd>yakeEnt</libadd> + <libadd>yakeEntLua</libadd> + <libadd>yakescriptingLua</libadd> + </BuildProgram> +--> + +<!-- + <BuildProgram name="TerrainDemo" src="src/yapp/samples/ode_terrain_demo" > @@ -372,7 +457,6 @@ <libadd>yappTerrainPhysicsManager</libadd> <libadd>dl</libadd> </BuildProgram> - --> <BuildProgram name="consoleDemo" @@ -381,10 +465,10 @@ <libadd>common_libs</libadd> <libadd>yakeCEGUIOgreAdapter</libadd> <libadd>lua</libadd> - <libadd>lualib</libadd> <libadd>luabind</libadd> <libadd>CEGUIOgreRenderer</libadd> </BuildProgram> + --> <!--<BuildProgram name="cmdrmayhem" src="src/yapp/samples/misc/cmdrmayhem" Modified: trunk/yake/src/yake/samples/model/dotScene/demo.cpp =================================================================== --- trunk/yake/src/yake/samples/model/dotScene/demo.cpp 2006-08-07 22:29:16 UTC (rev 1419) +++ trunk/yake/src/yake/samples/model/dotScene/demo.cpp 2006-08-07 23:31:14 UTC (rev 1420) @@ -95,6 +95,7 @@ // graphics mGWorld = getGraphicsSystem().createWorld(); YAKE_ASSERT( mGWorld ); + mGWorld->setAmbientLight(Color(0.5,0.5,0.5)); //NOTE: Make sure you create a camera before calling mGWorld->setShadowsEnabled(true) // when using "ogre3d" and the terrain scene manager with modulated texture shadows. @@ -196,7 +197,7 @@ if (!shutdownRequested()) { mPWorld->step( timeElapsed ); - triggerPhysicsUpdateSignal(0,timeElapsed); + triggerPhysicsUpdateSignal(timeElapsed); triggerGraphicsUpdateSignal(0,timeElapsed); mGWorld->render( timeElapsed ); Modified: trunk/yake/src/yapp/samples/misc/vehicle/yakeDemo.cpp =================================================================== --- trunk/yake/src/yapp/samples/misc/vehicle/yakeDemo.cpp 2006-08-07 22:29:16 UTC (rev 1419) +++ trunk/yake/src/yapp/samples/misc/vehicle/yakeDemo.cpp 2006-08-07 23:31:14 UTC (rev 1420) @@ -98,6 +98,7 @@ // getPhysicalWorld()->setGlobalGravity(Vector3(0,real(-9.81),0)); + getPhysicalWorld()->setCurrentSolverParam("stepsize",real(0.01)); // create ground mGround = new model::Model(); @@ -188,7 +189,7 @@ { mActionMap.update(); - mCentralController.triggerPhysicsUpdateSignal(0,timeElapsed); + mCentralController.triggerPhysicsUpdateSignal(timeElapsed); mCentralController.triggerGraphicsUpdateSignal(0,timeElapsed); if (mCar) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2006-09-03 12:10:12
|
Revision: 1432 http://svn.sourceforge.net/yake/?rev=1432&view=rev Author: psyclonist Date: 2006-09-03 05:09:38 -0700 (Sun, 03 Sep 2006) Log Message: ----------- - Collision feedback for actors reactivated. Includes basic collision cache for filtering jittering effects. - Made signal helper macros more consistent. Modified Paths: -------------- trunk/yake/src/yake/plugins/physicsODE/OdeActor.cpp trunk/yake/src/yake/plugins/physicsODE/OdeWorld.cpp trunk/yake/src/yake/samples/physics/demo/yakeDemo.cpp trunk/yake/src/yapp/vehicle/yakeNativeOde.cpp trunk/yake/yake/base/templates/yakeSignals.h trunk/yake/yake/physics/yakePhysicsWorld.h trunk/yake/yake/plugins/physicsODE/OdeActor.h trunk/yake/yake/plugins/physicsODE/OdeAvatar.h trunk/yake/yake/plugins/physicsODE/OdeWorld.h trunk/yake/yapp/vehicle/yakeNativeOde.h Modified: trunk/yake/src/yake/plugins/physicsODE/OdeActor.cpp =================================================================== --- trunk/yake/src/yake/plugins/physicsODE/OdeActor.cpp 2006-09-02 13:16:22 UTC (rev 1431) +++ trunk/yake/src/yake/plugins/physicsODE/OdeActor.cpp 2006-09-03 12:09:38 UTC (rev 1432) @@ -54,11 +54,14 @@ } this->setPosition( math::Vector3::kZero ); this->setOrientation( math::Quaternion::kIdentity ); + mPostStepConn = pWorld->subscribeToPostStep( boost::bind(&OdeActor::postStep,this,_1,_2) ); } //----------------------------------------------------- OdeActor::~OdeActor() { + mPostStepConn.disconnect(); + YAKE_SAFE_DELETE( mBody ); // destroy all shapes mShapes.clear(); @@ -292,30 +295,39 @@ } //----------------------------------------------------- - // void OdeActor::postStep( real timeElapsed ) - // { - // Vector< OdeActor* > its; - // for (CollisionList::iterator it = mCollisions.begin(); it != mCollisions.end(); ++it) - // { - // CollisionInfo& info = it->second; - // info.time += timeElapsed; - // if (info.time >= 0.1) - // { - // mLeaveCollisionSignal( this, it->first ); - // its.push_back( it->first ); - // } - // } - // VectorIterator< Vector< OdeActor* > > itErase( - // its.begin(), its.end() ); - // while (itErase.hasMoreElements()) - // { - // CollisionList::iterator itFind = mCollisions.find( itErase.getNext() ); - // if (itFind != mCollisions.end()) - // mCollisions.erase( itFind ); - // } - // its.clear(); - // } + void OdeActor::postStep( const real timeElapsed, const real simTime ) + { + Vector< OdeActor* > its; + //std::cout << "OdeActor::postStep() @ " << simTime << " cache " << int(mCollisions.size()) << "\n"; + for (CollisionCache::iterator it = mCollisions.begin(); it != mCollisions.end(); ++it) + { + CollisionInfo& info = it->second; + //std::cout << " " << info.timeSinceCollision_ << "\n"; + // If there's no update for this collision pair within a reasonable time, + // then report "collision exited" and delete the collision pair info. + if (info.timeSinceCollision_ >= 0.5) //@todo make dependent on step time + { + //YAKE_LOG("collision end"); + this->mSigCollisionExited( + ActorCollisionInfo( this, info.thisShape_, info.otherActor_, info.otherShape_ ) ); + its.push_back( it->first ); + continue; + } + + info.timeSinceCollision_ += timeElapsed; + } + VectorIterator< Vector< OdeActor* > > itErase( its.begin(), its.end() ); + while (itErase.hasMoreElements()) + { + CollisionCache::iterator itFind = mCollisions.find( itErase.getNext() ); + YAKE_ASSERT( itFind != mCollisions.end() ); + if (itFind != mCollisions.end()) + mCollisions.erase( itFind ); + } + its.clear(); + } + // #define DEBUG_COLLISIONS //----------------------------------------------------- @@ -349,44 +361,39 @@ return; } -#ifdef DEBUG_COLLISIONS - YAKE_LOG( "Firing collision signals" ); -#endif - // collisions are fired... - this->mSigCollisionEntered( ActorCollisionInfo( this, pShapeA, pOther, pShapeB ) ); - pOther->mSigCollisionEntered( ActorCollisionInfo( pOther, pShapeB, this, pShapeA ) ); - - const OdeMaterial* pMatA = pShapeA->getMaterial(); - const OdeMaterial* pMatB = pShapeB->getMaterial(); - // if materials are not supposed to produce any contact forces // This is the case if we just want some collision detection and without // any contact joints... + const OdeMaterial* pMatA = pShapeA->getMaterial(); + const OdeMaterial* pMatB = pShapeB->getMaterial(); + YAKE_ASSERT( pMatA && pMatB ).debug("cannot process collisions without proper materials"); if ( !pMatA || !pMatB ) { -#ifdef DEBUG_COLLISIONS - YAKE_LOG( "collision detection without materials..." ); -#endif return; } - //HACK FIXME implement collision cache!!! - // fire collision events - //CollisionCache::iterator itFind = mCollisions.find( pOther ); - // if ( itFind == mCollisions.end() ) - // { - // // new collision - // CollisionInfo info = 0; - // mCollisions.insert( CollisionCache::value_type( pOther, info ) ); - // - // //mEnterCollisionSignal( this, pOther ); - // } - // else - // { - // // still colliding, so reset timeout - // itFind->second = 0; - // } + // feed collision cache + // collision with pOther already in cache? + CollisionCache::iterator itFind = mCollisions.find( pOther ); + if ( itFind == mCollisions.end() ) + { + //std::cout << "new collision between " << this << " and " << pOther << "\n"; + // new collision + mCollisions.insert( + CollisionCache::value_type( pOther, CollisionInfo(pShapeA,pOther,pShapeB) ) ); + + //@todo move this out - or post the information into a message queue + this->mSigCollisionEntered( ActorCollisionInfo( this, pShapeA, pOther, pShapeB ) ); + pOther->mSigCollisionEntered( ActorCollisionInfo( pOther, pShapeB, this, pShapeA ) ); + } + else + { + //std::cout << "updated collision between " << this << " and " << pOther << "\n"; + // still colliding, so reset timeout + itFind->second.timeSinceCollision_ = 0; + } + // calculate soft cfm parameter[0..10^-6] from softness [0..1] float softness = ( pMatA->mSoftness + pMatB->mSoftness ) / 1000000.0f; Modified: trunk/yake/src/yake/plugins/physicsODE/OdeWorld.cpp =================================================================== --- trunk/yake/src/yake/plugins/physicsODE/OdeWorld.cpp 2006-09-02 13:16:22 UTC (rev 1431) +++ trunk/yake/src/yake/plugins/physicsODE/OdeWorld.cpp 2006-09-03 12:09:38 UTC (rev 1432) @@ -365,8 +365,10 @@ static real overflow = 0.; real t = overflow + timeElapsed; firePreStep(); + real steppedTime = 0.; while ( t > mStepSize ) { + steppedTime += mStepSize; mTime += mStepSize; t -= mStepSize; @@ -417,7 +419,7 @@ mSigPostStepInternal(mStepSize); } - firePostStep( mTime ); + firePostStep( steppedTime, mTime ); overflow = t; } Modified: trunk/yake/src/yake/samples/physics/demo/yakeDemo.cpp =================================================================== --- trunk/yake/src/yake/samples/physics/demo/yakeDemo.cpp 2006-09-02 13:16:22 UTC (rev 1431) +++ trunk/yake/src/yake/samples/physics/demo/yakeDemo.cpp 2006-09-03 12:09:38 UTC (rev 1432) @@ -196,7 +196,7 @@ } void onCollisionEntered() { - //YAKE_LOG("demo: collision!"); + YAKE_LOG("demo: collision!"); } void setupLights() { @@ -406,7 +406,7 @@ typedef Deque< SharedPtr<Simple> > ObjectList; ObjectList objs; - RandomNumberGeneratorMT randomiser; + RandomNumberGenerator randomiser; real lastTime = native::getTime(); while (!mShutdownRequested) @@ -436,18 +436,20 @@ #endif // spawn the object const Vector3 spawnOffset = bUseWorldOne ? Vector3(-5,0,0) : Vector3(5,0,0); - const Vector3 spawnPos = spawnOffset + Vector3(randomiser.randReal()*0.5,10,randomiser.randReal()*0.5); + const Vector3 spawnPos = spawnOffset + Vector3(randomiser.rand()*0.5,10,randomiser.rand()*0.5); objs.push_back( SharedPtr<Simple>( new Simple( pPWorld ) ) ); SharedPtr<Simple> last = objs.back(); - if (randomiser.randReal() < 0.5) + std::cout << randomiser.rand() << "\n"; + + if (randomiser.rand() < 0.5) createBox( pPWorld, *objs.back(), spawnPos, // position - Vector3(randomiser.randReal()*3,1,randomiser.randReal()*2) ); // dimensions + Vector3(randomiser.rand()*3,1,randomiser.rand()*2) ); // dimensions else createBall( pPWorld, *objs.back(), spawnPos, // position - randomiser.randReal()*2 ); //dimension/radius + randomiser.rand()*2 ); //dimension/radius // objs.push_back( SharedPtr<Simple>( new Simple( pPWorld ) ) ); Modified: trunk/yake/src/yapp/vehicle/yakeNativeOde.cpp =================================================================== --- trunk/yake/src/yapp/vehicle/yakeNativeOde.cpp 2006-09-02 13:16:22 UTC (rev 1431) +++ trunk/yake/src/yapp/vehicle/yakeNativeOde.cpp 2006-09-03 12:09:38 UTC (rev 1432) @@ -591,7 +591,7 @@ mPreStepSigConn = PWorld.subscribeToPreStepInternal( boost::bind(&OdeWheel::_onPreStepInternal,this,_1) ); - mPostStepSigConn = PWorld.subscribeToPostStep( boost::bind(&OdeWheel::_onPostStep,this,_1) ); + mPostStepSigConn = PWorld.subscribeToPostStep( boost::bind(&OdeWheel::_onPostStep,this,_1,_2) ); } OdeWheel::~OdeWheel() { @@ -629,7 +629,7 @@ const real maxSteer = 0.7; mpJoint->setLimits( 0, maxSteer * (mCurrSteer - 0.05), maxSteer * (mCurrSteer + 0.05) ); } - void OdeWheel::_onPostStep( const real dt ) + void OdeWheel::_onPostStep( const real dt, const real /*time*/ ) { YAKE_ASSERT( mpChassis ); YAKE_ASSERT( mpWheel ); @@ -689,7 +689,7 @@ if (mBrakeRatio > 0.01) _applyBrakeTq( math::Vector3::kUnitX * mBrakeRatio * 1.5 ); - const real targetVel = tq < 0. ? -40 : 40; + const real targetVel = tq < 0. ? -40. : 40.; _applyMotor( targetVel, - tq * 0.1/*@todo this is "dt" dependent*/ ); } void OdeWheel::_applyTq( const math::Vector3& torque ) Modified: trunk/yake/yake/base/templates/yakeSignals.h =================================================================== --- trunk/yake/yake/base/templates/yakeSignals.h 2006-09-02 13:16:22 UTC (rev 1431) +++ trunk/yake/yake/base/templates/yakeSignals.h 2006-09-03 12:09:38 UTC (rev 1432) @@ -144,10 +144,10 @@ void fire ## NAME() \ { mSig ## NAME(); } -#define YAKE_MEMBERSIGNAL_FIRE_FN1(ACCESS, NAME, PARAMS, PARAMSCALL) \ +#define YAKE_MEMBERSIGNAL_FIRE_FN1(ACCESS, NAME, PARAM0, PARAM0TYPE) \ ACCESS: \ - void fire ## NAME(PARAMS) \ - { mSig ## NAME(PARAMSCALL); } + void fire ## NAME(PARAM0TYPE PARAM0) \ + { mSig ## NAME(PARAM0); } #define YAKE_MEMBERSIGNAL_FIRE_FN2(ACCESS, NAME, PARAM0, PARAM0TYPE, PARAM1, PARAM1TYPE) \ ACCESS: \ Modified: trunk/yake/yake/physics/yakePhysicsWorld.h =================================================================== --- trunk/yake/yake/physics/yakePhysicsWorld.h 2006-09-02 13:16:22 UTC (rev 1431) +++ trunk/yake/yake/physics/yakePhysicsWorld.h 2006-09-03 12:09:38 UTC (rev 1432) @@ -86,7 +86,10 @@ virtual real getStepSize() const = 0; YAKE_MEMBERSIGNAL_PUREINTERFACE( public, void(void), PreStep ) - YAKE_MEMBERSIGNAL_PUREINTERFACE( public, void(real), PostStep ) + + //dt,time + YAKE_MEMBERSIGNAL_PUREINTERFACE( public, void(const real, const real), PostStep ) + YAKE_MEMBERSIGNAL_PUREINTERFACE( public, void(const real), PreStepInternal ) }; Modified: trunk/yake/yake/plugins/physicsODE/OdeActor.h =================================================================== --- trunk/yake/yake/plugins/physicsODE/OdeActor.h 2006-09-02 13:16:22 UTC (rev 1431) +++ trunk/yake/yake/plugins/physicsODE/OdeActor.h 2006-09-03 12:09:38 UTC (rev 1432) @@ -67,10 +67,10 @@ dSpaceID getSpaceID() { return this->actorSpaceID;}; YAKE_MEMBERSIGNAL_VIRTUALIMPL(public, void(const ActorCollisionInfo&), CollisionEntered); - YAKE_MEMBERSIGNAL_FIRE_FN1(public, CollisionEntered, const ActorCollisionInfo& info, info); + YAKE_MEMBERSIGNAL_FIRE_FN1(public, CollisionEntered, info, const ActorCollisionInfo&); YAKE_MEMBERSIGNAL_VIRTUALIMPL(public, void(const ActorCollisionInfo&), CollisionExited); - YAKE_MEMBERSIGNAL_FIRE_FN1(public, CollisionExited, const ActorCollisionInfo& info, info); + YAKE_MEMBERSIGNAL_FIRE_FN1(public, CollisionExited, info, const ActorCollisionInfo&); // Ode helpers void _collide( OdeActor* pOther, dGeomID geomA, dGeomID geomB, dJointGroup* pContactJointGroup ); @@ -85,12 +85,16 @@ void setupOdeSpace(); void addGeomToSpace( const OdeGeom * geom ); + + private: + void postStep(const real timeElapsed, const real simTime); protected: static const int MAX_CONTACTS = 40; + SignalConnection mPostStepConn; - math::Vector3 mPosition; - math::Quaternion mOrientation; + math::Vector3 mPosition; + math::Quaternion mOrientation; OdeBody* mBody; OdeWorld* mOdeWorld; @@ -98,9 +102,20 @@ typedef Deque<SharedPtr<OdeGeom> > ShapeList; ShapeList mShapes; - typedef real CollisionInfo; + struct CollisionInfo + { + IShape* thisShape_; + IActor* otherActor_; + IShape* otherShape_; + real timeSinceCollision_; + CollisionInfo(IShape* thisShape, IActor* otherActor, IShape* otherShape) : + thisShape_(thisShape), otherActor_(otherActor), otherShape_(otherShape), + timeSinceCollision_(0.) + {} + + }; typedef std::map< OdeActor*, CollisionInfo > CollisionCache; - CollisionCache mCollisions; + CollisionCache mCollisions; dSpaceID actorSpaceID; dSpace * actorSpace; Modified: trunk/yake/yake/plugins/physicsODE/OdeAvatar.h =================================================================== --- trunk/yake/yake/plugins/physicsODE/OdeAvatar.h 2006-09-02 13:16:22 UTC (rev 1431) +++ trunk/yake/yake/plugins/physicsODE/OdeAvatar.h 2006-09-03 12:09:38 UTC (rev 1432) @@ -64,10 +64,10 @@ virtual bool isDucking() const; YAKE_MEMBERSIGNAL_VIRTUALIMPL(public, void(bool), OnJump) - YAKE_MEMBERSIGNAL_FIRE_FN1(public, OnJump, bool jumping, jumping) + YAKE_MEMBERSIGNAL_FIRE_FN1(public, OnJump, jumping, bool) YAKE_MEMBERSIGNAL_VIRTUALIMPL(public, void(bool), OnDuck) - YAKE_MEMBERSIGNAL_FIRE_FN1(public, OnDuck, bool ducking, ducking) + YAKE_MEMBERSIGNAL_FIRE_FN1(public, OnDuck, ducking, bool) protected: private: Modified: trunk/yake/yake/plugins/physicsODE/OdeWorld.h =================================================================== --- trunk/yake/yake/plugins/physicsODE/OdeWorld.h 2006-09-02 13:16:22 UTC (rev 1431) +++ trunk/yake/yake/plugins/physicsODE/OdeWorld.h 2006-09-03 12:09:38 UTC (rev 1432) @@ -79,9 +79,9 @@ YAKE_MEMBERSIGNAL_VIRTUALIMPL( public, void, PreStep ); YAKE_MEMBERSIGNAL_FIRE_FN0( public, PreStep ); YAKE_MEMBERSIGNAL_VIRTUALIMPL( public, void, PostStep ); - YAKE_MEMBERSIGNAL_FIRE_FN1( public, PostStep, real t, t ); + YAKE_MEMBERSIGNAL_FIRE_FN2( public, PostStep, dt, const real , t, const real ); YAKE_MEMBERSIGNAL_VIRTUALIMPL( public, void, PreStepInternal ); - YAKE_MEMBERSIGNAL_FIRE_FN1( public, PreStepInternal, const real dt, dt ); + YAKE_MEMBERSIGNAL_FIRE_FN1( public, PreStepInternal, dt, const real ); YAKE_MEMBERSIGNAL( public, void(const real), PostStepInternal ); public: Modified: trunk/yake/yapp/vehicle/yakeNativeOde.h =================================================================== --- trunk/yake/yapp/vehicle/yakeNativeOde.h 2006-09-02 13:16:22 UTC (rev 1431) +++ trunk/yake/yapp/vehicle/yakeNativeOde.h 2006-09-03 12:09:38 UTC (rev 1432) @@ -231,7 +231,7 @@ void _applyMotor( real velocity, real fmax ); void _onPreStepInternal( const real dt ); - void _onPostStep( const real dt ); + void _onPostStep( const real dt, const real time ); private: physics::IActorPtr mpChassis; physics::IJointPtr mpJoint; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2006-09-03 20:49:50
|
Revision: 1437 http://svn.sourceforge.net/yake/?rev=1437&view=rev Author: psyclonist Date: 2006-09-03 13:49:18 -0700 (Sun, 03 Sep 2006) Log Message: ----------- added Force and Torque types Modified Paths: -------------- trunk/yake/src/yake/plugins/physicsODE/OdeActor.cpp trunk/yake/src/yake/plugins/physicsODE/OdeBody.cpp trunk/yake/src/yake/plugins/physicsODE/OdeWorld.cpp trunk/yake/src/yapp/vehicle/yakeNativeOde.cpp trunk/yake/yake/physics/yakePhysicsAffectors.h trunk/yake/yake/physics/yakePhysicsBody.h trunk/yake/yake/plugins/physicsODE/OdeBody.h trunk/yake/yake/plugins/physicsODE/OdeWorld.h Modified: trunk/yake/src/yake/plugins/physicsODE/OdeActor.cpp =================================================================== --- trunk/yake/src/yake/plugins/physicsODE/OdeActor.cpp 2006-09-03 14:11:18 UTC (rev 1436) +++ trunk/yake/src/yake/plugins/physicsODE/OdeActor.cpp 2006-09-03 20:49:18 UTC (rev 1437) @@ -427,14 +427,14 @@ contact[i].surface.mu2 = friction2; // 0 or 10 } - contact[i].surface.slip1 = 0.1; //FIXME need to set this right - contact[i].surface.slip2 = 0.1; //FIXME need to set this right + contact[i].surface.slip1 = dReal(.1); //FIXME need to set this right + contact[i].surface.slip2 = dReal(0.1); //FIXME need to set this right contact[i].surface.motion1 = 0; // contact[i].surface.motion2 = 0; //FIXME soft erp parameter should be correct - contact[i].surface.soft_erp = 0.2; - contact[i].surface.soft_cfm = 0.001; + contact[i].surface.soft_erp = dReal(0.2); + contact[i].surface.soft_cfm = dReal(0.001); real restitution = std::max( pMatA->mRestitution, pMatB->mRestitution ); contact[i].surface.bounce = restitution; @@ -444,7 +444,7 @@ #endif //FIXME bounce velocity needs to be tuned - contact[i].surface.bounce_vel = 0.01; + contact[i].surface.bounce_vel = dReal(0.01); dJointID contactJointID = dJointCreateContact( mOdeWorld->_getOdeID(), contactJointGroup->id(), Modified: trunk/yake/src/yake/plugins/physicsODE/OdeBody.cpp =================================================================== --- trunk/yake/src/yake/plugins/physicsODE/OdeBody.cpp 2006-09-03 14:11:18 UTC (rev 1436) +++ trunk/yake/src/yake/plugins/physicsODE/OdeBody.cpp 2006-09-03 20:49:18 UTC (rev 1437) @@ -51,7 +51,7 @@ mOdeBody->setAngularVel( 0, 0, 0 ); dMassSetSphere( &mMass, 1, 1 ); - dMassAdjust( &mMass, 0.0001 ); + dMassAdjust( &mMass, dReal(0.0001) ); mOdeBody->setMass( &mMass ); setPosition( math::Vector3(0,0,0) ); @@ -237,63 +237,16 @@ //--------------------------------------------------- void OdeBody::addForce( const Force& force ) { - //@todo apply force over several time steps according to duration. - const math::Vector3 totalForce = force.force * force.duration; - if (force.frameType == RF_GLOBAL) - mOdeBody->addForce( totalForce.x, totalForce.y, totalForce.z ); - else - mOdeBody->addRelForce( totalForce.x, totalForce.y, totalForce.z ); + mForces.push_back( std::make_pair(F_FORCE,force) ); } //--------------------------------------------------- - void OdeBody::addForce( math::Vector3 const& rForce ) + void OdeBody::addTorque( Torque const& torque ) { - mOdeBody->addForce( rForce.x, rForce.y, rForce.z ); + mForces.push_back( std::make_pair(F_TORQUE,torque) ); } //--------------------------------------------------- - void OdeBody::addForceAtPos( math::Vector3 const& rForce, math::Vector3 const& rPos ) - { - mOdeBody->addForceAtPos( rForce.x, rForce.y, rForce.z, rPos.x, rPos.y, rPos.z ); - } - - //--------------------------------------------------- - void OdeBody::addForceAtLocalPos( math::Vector3 const& rForce, math::Vector3 const& rPos ) - { - mOdeBody->addForceAtRelPos( rForce.x, rForce.y, rForce.z, rPos.x, rPos.y, rPos.z ); - } - - //--------------------------------------------------- - void OdeBody::addLocalForce( math::Vector3 const& rForce ) - { - mOdeBody->addRelForce( rForce.x, rForce.y, rForce.z ); - } - - //--------------------------------------------------- - void OdeBody::addLocalForceAtLocalPos( math::Vector3 const& rForce, math::Vector3 const& rPos ) - { - mOdeBody->addRelForceAtRelPos( rForce.x, rForce.y, rForce.z, rPos.x, rPos.y, rPos.z ); - } - - //--------------------------------------------------- - void OdeBody::addLocalForceAtPos( math::Vector3 const& rForce, math::Vector3 const& rPos ) - { - mOdeBody->addRelForceAtPos( rForce.x, rForce.y, rForce.z, rPos.x, rPos.y, rPos.z ); - } - - //--------------------------------------------------- - void OdeBody::addTorque( math::Vector3 const& rTorque ) - { - mOdeBody->addTorque( rTorque.x, rTorque.y, rTorque.z ); - } - - //--------------------------------------------------- - void OdeBody::addLocalTorque( math::Vector3 const& rTorque ) - { - mOdeBody->addRelTorque( rTorque.x, rTorque.y, rTorque.z ); - } - - //--------------------------------------------------- void OdeBody::setLinearVelocity( math::Vector3 const& rVelocity ) { mOdeBody->setLinearVel( rVelocity.x, rVelocity.y, rVelocity.z ); @@ -359,6 +312,79 @@ return mOdeBody; } + //----------------------------------------------------- + void OdeBody::_applyForce(const Force& f) + { + if (f.valueRef_ == RF_GLOBAL) + { + if (f.posRef_ == RF_GLOBAL) + mOdeBody->addForceAtPos( f.value_.x, f.value_.y, f.value_.z, f.pos_.x, f.pos_.y, f.pos_.z ); + else + mOdeBody->addForceAtRelPos( f.value_.x, f.value_.y, f.value_.z, f.pos_.x, f.pos_.y, f.pos_.z ); + } + else + { + if (f.posRef_ == RF_GLOBAL) + mOdeBody->addRelForceAtPos( f.value_.x, f.value_.y, f.value_.z, f.pos_.x, f.pos_.y, f.pos_.z ); + else + mOdeBody->addRelForceAtRelPos( f.value_.x, f.value_.y, f.value_.z, f.pos_.x, f.pos_.y, f.pos_.z ); + } + } + + //----------------------------------------------------- + void OdeBody::_applyTorque(const Force& f) + { + if (f.valueRef_ == RF_GLOBAL) + mOdeBody->addTorque( f.value_.x, f.value_.y, f.value_.z ); + else + mOdeBody->addRelTorque( f.value_.x, f.value_.y, f.value_.z ); + } + + //----------------------------------------------------- + void OdeBody::_preStep(const real stepSize) + { + typedef Forces::reverse_iterator reverse_force_iterator; + typedef Forces::iterator force_iterator; + + if (!mForces.empty()) + mOdeBody->enable(); + + force_iterator it=mForces.begin(); + while (it != mForces.end()) + { + if (it->second.singleStep_) + { + it->second.duration_ = stepSize; + } + else if (it->second.duration_ < stepSize) + { + it->second.value_ *= it->second.duration_ / stepSize; + } + // + if (it->first == F_FORCE) + this->_applyForce(it->second); + else + this->_applyTorque(it->second); + // + it->second.duration_ -= stepSize; + if (it->second.singleStep_ || it->second.duration_ <= 0.) + { + if (it != mForces.end()-1) + { + *it = mForces.back(); + mForces.pop_back(); + } + else + { + mForces.erase( it ); + it = mForces.end(); + } + } + else + ++it; + } + } + } // physics } // yake Modified: trunk/yake/src/yake/plugins/physicsODE/OdeWorld.cpp =================================================================== --- trunk/yake/src/yake/plugins/physicsODE/OdeWorld.cpp 2006-09-03 14:11:18 UTC (rev 1436) +++ trunk/yake/src/yake/plugins/physicsODE/OdeWorld.cpp 2006-09-03 20:49:18 UTC (rev 1437) @@ -41,11 +41,11 @@ namespace physics { //----------------------------------------------------- - OdeWorld::OdeWorld() : mNextMeshId( 0 ) + OdeWorld::OdeWorld() : mNextMeshId( 0 ), mTimeOverflow(0.) { //TODO make these settings configurable for user //simulation - mStepSize = real( 0.05 ); // default: 50Hz + mStepSize = real( 1./20. ); mOdeWorld = new dWorld(); YAKE_ASSERT( mOdeWorld ); @@ -56,8 +56,8 @@ mOdeContactGroup = new dJointGroup( 0 ); mOdeWorld->setAutoDisableFlag( 1 ); - mOdeWorld->setAutoDisableAngularThreshold( 0.01 ); // ODE default: 0.01 - mOdeWorld->setAutoDisableLinearThreshold( 0.01 ); // ODE default: 0.01 + mOdeWorld->setAutoDisableAngularThreshold( dReal(0.01) ); // ODE default: 0.01 + mOdeWorld->setAutoDisableLinearThreshold( dReal(0.01) ); // ODE default: 0.01 mOdeWorld->setAutoDisableSteps( 10 ); // ODE default: 10 mOdeWorld->setAutoDisableTime( 0 ); // ODE default: 0. (= ignore time) @@ -69,13 +69,13 @@ // Global ERP and CFM values should be configurable via some (properties?) interface // Individual values ( for joints and such ) should also be accessable // perhaps via direct_ode access. - mOdeWorld->setCFM( 0.001 ); - mOdeWorld->setERP( 0.95 ); + mOdeWorld->setCFM( dReal(0.001) ); + mOdeWorld->setERP( dReal(0.95) ); - dWorldSetQuickStepNumIterations( mOdeWorld->id(), 20 ); + dWorldSetQuickStepNumIterations( mOdeWorld->id(), 10 ); - dWorldSetContactMaxCorrectingVel( mOdeWorld->id(), .1 ); - dWorldSetContactSurfaceLayer( mOdeWorld->id(), 0.001 ); + dWorldSetContactMaxCorrectingVel( mOdeWorld->id(), dReal(2.) ); + dWorldSetContactSurfaceLayer( mOdeWorld->id(), dReal(0.01) ); mTime = real(0.); @@ -362,18 +362,26 @@ //----------------------------------------------------- void OdeWorld::step( const real timeElapsed ) { - static real overflow = 0.; - real t = overflow + timeElapsed; + real t = mTimeOverflow + timeElapsed; + + std::cout << "step dt=" << timeElapsed << " t=" << t << " step=" << mStepSize << "\n"; firePreStep(); real steppedTime = 0.; while ( t > mStepSize ) { + std::cout << " t=" << t << "\n"; + steppedTime += mStepSize; mTime += mStepSize; t -= mStepSize; + + // pre-step firePreStepInternal(mStepSize); + for (BodyList::iterator it=mBodies.begin(), itEnd=mBodies.end(); it != itEnd; ++it) + (*it)->_preStep(mStepSize); + #ifdef ADJUST_FPU_PRECISION _controlfp(_PC_64, _MCW_PC); #endif @@ -421,7 +429,7 @@ firePostStep( steppedTime, mTime ); - overflow = t; + mTimeOverflow = t; } //----------------------------------------------------- Modified: trunk/yake/src/yapp/vehicle/yakeNativeOde.cpp =================================================================== --- trunk/yake/src/yapp/vehicle/yakeNativeOde.cpp 2006-09-03 14:11:18 UTC (rev 1436) +++ trunk/yake/src/yapp/vehicle/yakeNativeOde.cpp 2006-09-03 20:49:18 UTC (rev 1437) @@ -690,7 +690,7 @@ _applyBrakeTq( math::Vector3::kUnitX * mBrakeRatio * 1.5 ); const real targetVel = tq < 0. ? -40. : 40.; - _applyMotor( targetVel, - tq * 0.1/*@todo this is "dt" dependent*/ ); + _applyMotor( targetVel, - tq * 0.01/*@todo this is "dt" dependent*/ ); } void OdeWheel::_applyTq( const math::Vector3& torque ) { @@ -808,7 +808,7 @@ { physics::IBody* pBody = itBody.getNext(); - pBody->addForceAtPos( f, pos ); + pBody->addForce( physics::Force(f, physics::RF_GLOBAL, pos, physics::RF_GLOBAL) ); } } } // namespace vehicle Modified: trunk/yake/yake/physics/yakePhysicsAffectors.h =================================================================== --- trunk/yake/yake/physics/yakePhysicsAffectors.h 2006-09-03 14:11:18 UTC (rev 1436) +++ trunk/yake/yake/physics/yakePhysicsAffectors.h 2006-09-03 20:49:18 UTC (rev 1437) @@ -79,7 +79,7 @@ public: virtual void applyTo( IBody & rBody, const real /*timeElapsed*/ ) { - rBody.addForce( mAcceleration * rBody.getMass() ); + rBody.addForce( Force( mAcceleration * rBody.getMass(), RF_GLOBAL ) ); } }; @@ -102,7 +102,7 @@ { math::Vector3 direction = rBody.getActor().getPosition() - mPoint; direction.normalise(); - rBody.addForce( direction * mAcceleration * rBody.getMass() ); + rBody.addForce( Force( direction * mAcceleration * rBody.getMass(), RF_GLOBAL ) ); } }; Modified: trunk/yake/yake/physics/yakePhysicsBody.h =================================================================== --- trunk/yake/yake/physics/yakePhysicsBody.h 2006-09-03 14:11:18 UTC (rev 1436) +++ trunk/yake/yake/physics/yakePhysicsBody.h 2006-09-03 20:49:18 UTC (rev 1437) @@ -31,52 +31,12 @@ # include <yake/physics/yakePhysicsPrerequisites.h> #endif #include <yake/base/yakeTaggedListenerManager.h> +#include <yake/physics/yakePhysicsCommon.h> namespace yake { using namespace ::yake::math; namespace physics { - enum ReferenceFrame { - RF_LOCAL, - RF_GLOBAL - }; - - struct YAKE_PHYSICS_API Force - { - math::Vector3 force; - real duration; - ReferenceFrame frameType; - - Force() : - duration(0) - {} - Force( const math::Vector3& f, const real t, const ReferenceFrame rf = RF_GLOBAL ) : - force(f), - duration(t), - frameType(rf) - {} - - Force& operator = (const Force& rhs) - { - if (&rhs == this) - return *this; - force = rhs.force; - duration = rhs.duration; - frameType = rhs.frameType; - return *this; - } - Force& operator += (const Force& rhs) - { - force += rhs.force; - duration += rhs.duration; - return *this; - } - bool operator == (const Force& rhs) - { - return (frameType == rhs.frameType && force == rhs.force && duration == rhs.duration); - } - }; - class YAKE_PHYSICS_API IBodyListener { public: @@ -278,8 +238,10 @@ /** Adds a force. The specifics are detailed in the Force object. */ - virtual void addForce( const Force& force ) = 0; + virtual void addForce( const Force& ) = 0; + virtual void addTorque( const Torque& ) = 0; +#if defined(YAKE_PHYSICS_OLD_FORCE_API) /** Adds a force defined in the global reference frame. */ virtual void addForce( const math::Vector3& rForce ) = 0; @@ -307,14 +269,13 @@ in the global reference frame. */ virtual void addLocalForceAtPos( const math::Vector3& rForce, const math::Vector3& rPos ) = 0; - /** Adds a torque defined in the global reference frame. */ virtual void addTorque( const math::Vector3& rTorque ) = 0; - /** Adds a torque defined in the local reference frame. */ virtual void addLocalTorque( const math::Vector3& rTorque ) = 0; +#endif }; YAKE_PHYSICS_COMMON_POINTERS( IBody ); Modified: trunk/yake/yake/plugins/physicsODE/OdeBody.h =================================================================== --- trunk/yake/yake/plugins/physicsODE/OdeBody.h 2006-09-03 14:11:18 UTC (rev 1436) +++ trunk/yake/yake/plugins/physicsODE/OdeBody.h 2006-09-03 20:49:18 UTC (rev 1437) @@ -56,7 +56,9 @@ virtual void setAngularVelocity( const math::Vector3& rVelocity); virtual math::Vector3 getAngularVelocity() const; - virtual void addForce( const Force& force ); + virtual void addForce( const Force& ); + virtual void addTorque( const Torque& ); +#if defined(YAKE_PHYSICS_OLD_FORCE_API) virtual void addForce( const math::Vector3& rForce ); virtual void addForceAtPos( const math::Vector3& rForce, const math::Vector3& rPos ); virtual void addForceAtLocalPos( const math::Vector3& rForce, const math::Vector3& rPos ); @@ -65,7 +67,7 @@ virtual void addLocalForceAtPos( const math::Vector3& rForce, const math::Vector3& rPos ); virtual void addTorque( const math::Vector3& rTorque ); virtual void addLocalTorque( const math::Vector3& rTorque ); - +#endif // helpers for OdeActor virtual void setPosition( const math::Vector3 & position ); virtual void setOrientation( const math::Quaternion & orientation ); @@ -93,13 +95,25 @@ //bool _isValid() const { return mValid; }*/ void _applyMassDescFromShapeDesc( const IShape::Desc& rShapeDesc, real massOrDensity, IBody::quantityType qType ); - protected: + void _preStep(const real stepSize); + private: + void _applyForce(const Force&); + void _applyTorque(const Force&); + private: OdeWorld* mOdeWorld; OdeActor& mOwner; dBody* mOdeBody; dMass mMass; // MassType mMassType; // bool mValid; + + enum FType + { + F_FORCE, + F_TORQUE + }; + typedef std::deque<std::pair<FType,Force> > Forces; + Forces mForces; }; } // physics Modified: trunk/yake/yake/plugins/physicsODE/OdeWorld.h =================================================================== --- trunk/yake/yake/plugins/physicsODE/OdeWorld.h 2006-09-03 14:11:18 UTC (rev 1436) +++ trunk/yake/yake/plugins/physicsODE/OdeWorld.h 2006-09-03 20:49:18 UTC (rev 1437) @@ -107,6 +107,7 @@ OdeTriMesh::MeshData getMeshDataById( TriangleMeshId id ) const; protected: + real mTimeOverflow; real mTime; real mStepSize; dWorld* mOdeWorld; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2006-09-05 22:35:37
|
Revision: 1439 http://svn.sourceforge.net/yake/?rev=1439&view=rev Author: psyclonist Date: 2006-09-05 15:35:16 -0700 (Tue, 05 Sep 2006) Log Message: ----------- fixed IAvatar behaviour, introduce Force and Torque Modified Paths: -------------- trunk/yake/src/yake/plugins/physicsODE/OdeAvatar.cpp trunk/yake/src/yake/plugins/physicsODE/OdeWorld.cpp trunk/yake/yake/plugins/physicsODE/OdeAvatar.h Added Paths: ----------- trunk/yake/src/yake/physics/yakePhysicsCommon.cpp trunk/yake/yake/physics/yakePhysicsCommon.h Added: trunk/yake/src/yake/physics/yakePhysicsCommon.cpp =================================================================== --- trunk/yake/src/yake/physics/yakePhysicsCommon.cpp (rev 0) +++ trunk/yake/src/yake/physics/yakePhysicsCommon.cpp 2006-09-05 22:35:16 UTC (rev 1439) @@ -0,0 +1,122 @@ +#include <yake/physics/yakePCH.h> +#include <yake/physics/yakePhysicsCommon.h> +#include <limits> + +namespace yake { +namespace physics { + + Force::Force() : + duration_(real(0.)), + singleStep_(true), + posRef_(RF_LOCAL), + valueRef_(RF_LOCAL) + { + } + Force::Force(const Vector3& value, const ReferenceFrame rfValue, const Point3& pos, const ReferenceFrame rfPos, const real duration) : + value_(value), + pos_(pos), + duration_(duration), + singleStep_(false), + posRef_(rfPos), + valueRef_(rfValue) + { + } + Force::Force(const Vector3& value, const ReferenceFrame rfValue, const Point3& pos, const ReferenceFrame rfPos) : + value_(value), + pos_(pos), + duration_(real(0.)), + singleStep_(true), + posRef_(rfPos), + valueRef_(rfValue) + { + } + Force::Force(const Vector3& value, const ReferenceFrame rfValue, const real duration) : + value_(value), + pos_(Point3::kZero), + duration_(duration), + singleStep_(false), + posRef_(RF_GLOBAL), + valueRef_(rfValue) + { + } + Force::Force(const Vector3& value, const ReferenceFrame rfValue) : + value_(value), + pos_(Point3::kZero), + duration_(real(0.)), + singleStep_(true), + posRef_(RF_GLOBAL), + valueRef_(rfValue) + { + } + Force::Force(const Force& other) : + value_(other.value_), + pos_(other.pos_), + duration_(other.duration_), + singleStep_(other.singleStep_), + posRef_(other.posRef_), + valueRef_(other.valueRef_) + { + } + Force& Force::operator = (const Force& rhs) + { + if (this == &rhs) + return *this; + value_ = rhs.value_; + pos_ = rhs.pos_; + duration_ = rhs.duration_; + singleStep_ = rhs.singleStep_; + posRef_ = rhs.posRef_; + valueRef_ = rhs.valueRef_; + return *this; + } + // comparison + bool Force::operator == (const Force& rhs) const + { + return (value_ == rhs.value_ && + pos_ == rhs.pos_ && + fabs(duration_ - rhs.duration_) < std::numeric_limits<real>::epsilon() && + singleStep_ == rhs.singleStep_ && + posRef_ == rhs.posRef_ && + valueRef_ == rhs.valueRef_); + } + bool Force::operator != (const Force& rhs) const + { + return !(*this == rhs); + } + // ... + Force& Force::operator *= (const real rhs) + { + value_ *= rhs; + return *this; + } + Force Force::operator * (const real rhs) + { + Force tmp(*this); + tmp *= rhs; + return (tmp); + } + Force& Force::operator += (const Force& rhs) + { + YAKE_ASSERT( valueRef_ == rhs.valueRef_ ).debug("incompatible frames of reference"); + YAKE_ASSERT( posRef_ == rhs.posRef_ ).debug("incompatible frames of reference"); + YAKE_ASSERT( singleStep_ == rhs.singleStep_ ).debug("incompatible step settings"); + + if (singleStep_) + value_ += rhs.value_; + else + { + YAKE_ASSERT( duration_ != 0. ); + YAKE_ASSERT( rhs.duration_ != 0. ); + value_ += rhs.value_ * (rhs.duration_ / duration_); + } + return *this; + } + Force Force::operator + (const Force& rhs) + { + Force tmp(*this); + tmp += rhs; + return tmp; + } + +} // namespace physics +} // namespace yake Modified: trunk/yake/src/yake/plugins/physicsODE/OdeAvatar.cpp =================================================================== --- trunk/yake/src/yake/plugins/physicsODE/OdeAvatar.cpp 2006-09-05 22:32:38 UTC (rev 1438) +++ trunk/yake/src/yake/plugins/physicsODE/OdeAvatar.cpp 2006-09-05 22:35:16 UTC (rev 1439) @@ -62,6 +62,7 @@ mPreStepConn.disconnect(); mPostStepConn.disconnect(); YAKE_SAFE_DELETE( mRay ); + YAKE_SAFE_DELETE( mTopRay ); mOdeWorld->destroyActor( mActor ); mActor = 0; mOdeWorld = 0; @@ -84,18 +85,34 @@ mSphereRadius = mDimensions.x * real(0.5); mSphereOffset = Vector3(0,mHeightAboveGround,0); mRayLength = 100.; // set to expected maximum height above ground... or better... + mTopRayLength = 100.; mActor = static_cast<OdeActor*>(static_cast<IWorld*>(mOdeWorld)->createActor( ACTOR_DYNAMIC )); YAKE_ASSERT( mActor ); OdeGeom* pShape = static_cast<OdeGeom*>(mActor->createShape( IShape::SphereDesc( real(mSphereRadius) ) )); mActor->setPosition( mPosition + mSphereOffset ); + mActor->getBody().setMass( 1 ); mRay = new OdeRay( mOdeWorld, real(mRayLength) ); mRay->setDirection( -Vector3::kUnitY ); mRay->ignore( pShape->_getOdeGeomID() ); + mTopRay = new OdeRay( mOdeWorld, real(mTopRayLength) ); + mTopRay->setDirection( Vector3::kUnitY ); + mTopRay->ignore( pShape->_getOdeGeomID() ); + mPreStepConn = mOdeWorld->subscribeToPreStepInternal( boost::bind(&OdeAvatar::onPreStepInternal,this,_1) ); mPostStepConn = mOdeWorld->subscribeToPostStepInternal( boost::bind(&OdeAvatar::onPostStepInternal,this,_1) ); + +#ifdef YAKE_DEBUG + std::cout << "ACTOR\n"; + std::cout << " dim = " << mDimensions << "\n"; + std::cout << " pos = " << mPosition << "\n"; + std::cout << " heightAboveGround = " << mHeightAboveGround << "\n"; + std::cout << " sphereOffset = " << mSphereOffset << "\n"; + std::cout << "\n"; +#endif + return true; } @@ -104,47 +121,44 @@ { if (dt <= 0) return; + + // dampen + + mActor->getBody().setAngularVelocity( Vector3(0,0,0) ); + mActor->setOrientation( Quaternion::kIdentity ); + // gather information mPosition = mActor->getPosition(); - mOrientation = mActor->getOrientation(); + mOrientation = mActor->getOrientation(); // is always Quaternion::kIdentity + //std::cout << "avatar: pos = " << mPosition << "\n"; + const real targetHeightAboveGround = mDucking ? mHeightAboveGroundDuck : mHeightAboveGround; const Vector3 currLinVel = mActor->getBody().getLinearVelocity(); const real currVel = currLinVel.y; - const Vector3 currPos = mActor->getPosition(); + const Vector3 currPos = mPosition; // let's do some real work: Vector3 targetVel = 2 * (mTargetVelocity - currLinVel) * dt; targetVel.y = 0.; // ! Vector3 f(0,0,0); + + if (mJumping) + targetVel *= 0.2; // player is less able to control direction during jump - so scale influence + if (mJumpStartInProgress) { - if (mJumpTime > 0.) - { - // "Starting phase" (we apply force) - mJumpTime -= dt; - - f += Vector3(0,100,0); - ++mJumpApplies; - } - else - { - // "Jumping phase" - const real minGlobalHeight = mRay->intersectionPoint().y + targetHeightAboveGround; - std::cout << "JUMPWAITING (applied=" << mJumpApplies << ")" << currPos.y << " > 0.1 + " << minGlobalHeight << "\n"; - if (currVel < -0.01 || currPos.y > (minGlobalHeight + 0.1)) - { - mJumpStartInProgress = false; // we're going downwards again. - } - } + mActor->getBody().addForce( Force(Vector3(0,40,0), RF_GLOBAL, mJumpTime) ); + mJumpStartInProgress = false; + return; } if (mRay->intersects()) { - if (mJumping && !mJumpStartInProgress) + if (mJumping && !mJumpStartInProgress && currVel < -0.01) // jumping & downwards movement { if (mRay->intersectionDepth() < targetHeightAboveGround) mJumping = false; @@ -154,20 +168,30 @@ const Vector3 targetPoint = mRay->intersectionPoint() + Vector3::kUnitY * targetHeightAboveGround; + // distToTarget < 0 if player is above ideal position + // distToTarget > 0 if player is beneath ideal position const real distToTarget = (targetPoint.y - currPos.y); - //@todo make all these spring and damping stuff configurable... - const real k = real(1.0); - const real f1 = k * real(20.) * distToTarget; - const real f2 = k * real(15.) * currVel; + if (distToTarget < 0.) // if above ideal position - do nothing + {} + else if (distToTarget > 0.) // if below ideal position - correct + { + //@todo make all this spring and damping stuff configurable... + const real k = real(1.1); + const real f1 = k * real(20.) * distToTarget; + const real f2 = k * real(10.) * currVel; - f = Vector3::kUnitY * (f1 - f2); + f = Vector3::kUnitY * (f1 - f2); + } } } + const Vector3 force = (dt == 0.) ? Vector3::kZero : (f + (mActor->getBody().getMass() * (targetVel / dt))); - mActor->getBody().addForce( 1./*mDynamicsInfluence?*/ * force ); + + if (force.length() > 0.01) + mActor->getBody().addForce( 1./*mDynamicsInfluence?*/ * force ); } //----------------------------------------------------- @@ -175,12 +199,14 @@ { _updateRayData(); mRay->_clearIntersection(); + mTopRay->_clearIntersection(); } //----------------------------------------------------- void OdeAvatar::_updateRayData() { mRay->setPosition( mPosition/*ball position*/ ); + mTopRay->setPosition( mPosition/*ball position*/ ); } //----------------------------------------------------- @@ -192,6 +218,7 @@ //----------------------------------------------------- void OdeAvatar::setInfluenceByDynamics( const real ratio ) { + YAKE_ASSERT( 0. <= ratio && ratio <= 1. ); mDynamicsInfluence = ratio; } @@ -208,7 +235,7 @@ return; mDucking = false; mJumpApplies = 0; - mJumpTime = real(0.08); + mJumpTime = real(0.2); mJumping = true; mJumpStartInProgress = true; } Modified: trunk/yake/src/yake/plugins/physicsODE/OdeWorld.cpp =================================================================== --- trunk/yake/src/yake/plugins/physicsODE/OdeWorld.cpp 2006-09-05 22:32:38 UTC (rev 1438) +++ trunk/yake/src/yake/plugins/physicsODE/OdeWorld.cpp 2006-09-05 22:35:16 UTC (rev 1439) @@ -364,12 +364,12 @@ { real t = mTimeOverflow + timeElapsed; - std::cout << "step dt=" << timeElapsed << " t=" << t << " step=" << mStepSize << "\n"; + //std::cout << "step dt=" << timeElapsed << " t=" << t << " step=" << mStepSize << "\n"; firePreStep(); real steppedTime = 0.; while ( t > mStepSize ) { - std::cout << " t=" << t << "\n"; + //std::cout << " t=" << t << "\n"; steppedTime += mStepSize; mTime += mStepSize; Added: trunk/yake/yake/physics/yakePhysicsCommon.h =================================================================== --- trunk/yake/yake/physics/yakePhysicsCommon.h (rev 0) +++ trunk/yake/yake/physics/yakePhysicsCommon.h 2006-09-05 22:35:16 UTC (rev 1439) @@ -0,0 +1,56 @@ +#ifndef YAKE_PHYSICS_COMMON_H +#define YAKE_PHYSICS_COMMON_H + +#include <yake/physics/yakePhysicsPrerequisites.h> + +namespace yake { +namespace physics { + /** Represents the type of a frame of reference. */ + enum ReferenceFrame { + RF_LOCAL, + RF_GLOBAL + }; + /** Represents a force (type: Force) or torque (type: Torque, via typedef). + @note For torque the optional position will be ignored! + */ + struct YAKE_PHYSICS_API Force + { + Force(); + /** e.g. Force(Vector3(0,0,1), RF_LOCAL, Point3(1,1,1), RF_GLOBAL) */ + Force(const Vector3&, const ReferenceFrame, const Point3&, const ReferenceFrame, const real); + + /** single step */ + Force(const Vector3&, const ReferenceFrame, const Point3&, const ReferenceFrame); + + /** global position */ + Force(const Vector3&, const ReferenceFrame, const real duration); + Force(const Vector3&, const ReferenceFrame refValue = RF_GLOBAL); + Force(const Force&); + Force& operator=(const Force&); + + bool operator == (const Force&) const; + bool operator != (const Force&) const; + + Force& operator *= (const real); + Force operator * (const real); + + /** @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&); + + //private: + Vector3 value_; + Point3 pos_; + real duration_; + bool singleStep_; + ReferenceFrame posRef_; + ReferenceFrame valueRef_; + }; + typedef Force Torque; + +} // namespace physics +} // namespace yake + +#endif Modified: trunk/yake/yake/plugins/physicsODE/OdeAvatar.h =================================================================== --- trunk/yake/yake/plugins/physicsODE/OdeAvatar.h 2006-09-05 22:32:38 UTC (rev 1438) +++ trunk/yake/yake/plugins/physicsODE/OdeAvatar.h 2006-09-05 22:35:16 UTC (rev 1439) @@ -93,6 +93,8 @@ OdeWorld* mOdeWorld; OdeRay* mRay; double mRayLength; + OdeRay* mTopRay; + double mTopRayLength; double mSphereRadius; math::Vector3 mSphereOffset; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2006-09-05 22:40:40
|
Revision: 1447 http://svn.sourceforge.net/yake/?rev=1447&view=rev Author: psyclonist Date: 2006-09-05 15:40:30 -0700 (Tue, 05 Sep 2006) Log Message: ----------- new sample layout Added Paths: ----------- trunk/yake/samples/ trunk/yake/samples/README.TXT Added: trunk/yake/samples/README.TXT =================================================================== --- trunk/yake/samples/README.TXT (rev 0) +++ trunk/yake/samples/README.TXT 2006-09-05 22:40:30 UTC (rev 1447) @@ -0,0 +1,30 @@ +Overview over the sampels + + +debug +scripted_entity +custom_entity +vehicle1 +sync1 +dotlink +fsm +audio3d +raf_simple +raf_most_systems +gui_console + + +sampleDebug - debug output + +sampleScriptedEntity - scripting entities (callbacks, states, events and more) +sampleCustomEntity - how to implement a new entity +sampleVehicle1 - different vehicles can be controlled (car,jet, uses RAF, entities and models) +sampleSync1 - decoupled, interpolated physics and graphics systems +sampleDotLink - how to tie .link, .scene and .xode together +sampleFSM - simple finite state machine demo +sampleAudio3d - how to use the audio system for playing 3D sounds + +sampleRafSimple - bare-bones RAF application +sampleRafMostSystems - initialisation of most systems (graphics, physics, scripting etc) + +sampleGuiConsole - a CEGUI-based console with history to script Yake applications using Lua This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2006-09-09 18:03:49
|
Revision: 1448 http://svn.sourceforge.net/yake/?rev=1448&view=rev Author: psyclonist Date: 2006-09-09 11:03:27 -0700 (Sat, 09 Sep 2006) Log Message: ----------- safe use of types (MouseButton), signal type is now Vector3 Modified Paths: -------------- trunk/yake/src/yake/input/yakeActionMap.cpp trunk/yake/src/yake/input/yakeInputEventGenerator.cpp trunk/yake/src/yake/plugins/inputOgre/InputSystemOgre.cpp trunk/yake/yake/input/yakeActionMap.h trunk/yake/yake/input/yakeInputSystem.h trunk/yake/yake/plugins/inputOgre/InputSystemOgre.h Modified: trunk/yake/src/yake/input/yakeActionMap.cpp =================================================================== --- trunk/yake/src/yake/input/yakeActionMap.cpp 2006-09-05 22:40:30 UTC (rev 1447) +++ trunk/yake/src/yake/input/yakeActionMap.cpp 2006-09-09 18:03:27 UTC (rev 1448) @@ -207,7 +207,7 @@ bool ActionMap::loadFromFile(ActionMap& amap, const String& fname, KeyboardDevice* pKeyboard, const ReceiveConditionConnectionFn fn) { - YAKE_ASSERT( pKeyboard ).warning("No keyboard device."); + YAKE_ASSERT( pKeyboard ).debug("No keyboard device."); std::ifstream in( fname.c_str() ); if (!in.is_open()) @@ -227,7 +227,7 @@ StringVector splitVector; splitVector = yake::split<String>(line, "="); - YAKE_ASSERT( splitVector.size() >= 2 )( line ).warning("Invalid syntax! Not enough parameters!"); + YAKE_ASSERT( splitVector.size() >= 2 )( line ).debug("Invalid syntax! Not enough parameters!"); if (splitVector.size() < 2) continue; @@ -240,7 +240,7 @@ // parse rest splitVector = yake::split<String>(splitVector.back(), ","); - YAKE_ASSERT( splitVector.size() >= 1 )( actionName ).warning("Invalid syntax! Need an input specifier!"); + YAKE_ASSERT( splitVector.size() >= 1 )( actionName ).debug("Invalid syntax! Need an input specifier!"); if (splitVector.size() < 1) continue; @@ -249,10 +249,10 @@ #ifdef YAKE_DEBUG if (splitVector.size() > 2) { - YAKE_ASSERT( splitVector.size() <= 2 )(line).warning("Too many parameters! Ignoring superfluous ones!"); + YAKE_ASSERT( splitVector.size() <= 2 )(line).debug("Too many parameters! Ignoring superfluous ones!"); } #endif - YAKE_ASSERT( mode == "pressed" || mode == "continuous" || mode == "released" || mode == "pressed_released" )(mode).warning("Invalid mode! Skipping!"); + YAKE_ASSERT( mode == "pressed" || mode == "continuous" || mode == "released" || mode == "pressed_released" )(mode).debug("Invalid mode! Skipping!"); if (mode != "pressed" && mode != "continuous" && mode != "released" && mode != "pressed_released") continue; @@ -370,14 +370,14 @@ // MouseButtonActionCondition //----------------------------------------------------- MouseButtonActionCondition::MouseButtonActionCondition( - MouseDevice * device, uint8 button, bool continuous) : + MouseDevice * device, MouseButton button, bool continuous) : MouseActionCondition(device), mButton(button), mContinuous(continuous) { } - void MouseButtonActionCondition::setButton(uint8 button) + void MouseButtonActionCondition::setButton(MouseButton button) { mButton = button; } @@ -402,12 +402,6 @@ mDirection(direction), mContinuous(continuous) { -#ifdef YAKE_DEBUG - if ((mAxis == MMA_X_AND_Y || mAxis == MMA_ALL) && mDirection == MMD_BOTH) - { - YAKE_LOG_INFORMATION("MouseMoveActionCondition: Direction = MMD_BOTH and Axis is either MMA_X_AND_Y or MMA_ALL. This may result in unexpected behavior!"); - } -#endif mPreviousPosition = mMouse->getPosition(); } @@ -435,46 +429,48 @@ const real maxMovementY = maxMovement.getWidth(); const real maxWheelmove = 120.0f; //@todo read this out via win32 api - const math::Vector3 pos = mMouse->getPosition() - mPreviousPosition; + const math::Vector3 deltaPos = mMouse->getPosition() - mPreviousPosition; mPreviousPosition = mMouse->getPosition(); + if (deltaPos.length() == 0.) + return kAC_FALSE; switch (mAxis) { case MMA_X: { - if (mDirection == MMD_POSITIVE && pos.x > 0) + if (mDirection == MMD_POSITIVE && deltaPos.x > 0) { - return Result(true, pos.x / maxMovementX); + return Result(true, Vector3(deltaPos.x / maxMovementX,0,0)); } - else if (mDirection == MMD_NEGATIVE && pos.x < 0) + else if (mDirection == MMD_NEGATIVE && deltaPos.x < 0) { // The user wants to know how much the mouse has moved, // in only 1 direction. This should never be negative. - return Result(true, -pos.x / maxMovementX); + return Result(true, Vector3(-deltaPos.x / maxMovementX,0,0)); } - else if (mDirection == MMD_BOTH && pos.x != 0) + else if (mDirection == MMD_BOTH && deltaPos.x != 0) { // This may be negative, because it represents the // direction the mouse was moved in. - return Result(true, pos.x / maxMovementX); + return Result(true, Vector3(deltaPos.x / maxMovementX,0,0)); } } break; case MMA_Y: { - if (mDirection == MMD_POSITIVE && pos.y > 0) + if (mDirection == MMD_POSITIVE && deltaPos.y > 0) { - return Result(true, pos.y / maxMovementY); + return Result(true, Vector3(0, deltaPos.y / maxMovementY, 0)); } - else if (mDirection == MMD_NEGATIVE && pos.y < 0) + else if (mDirection == MMD_NEGATIVE && deltaPos.y < 0) { // The user wants to know how much the mouse has moved, // in only 1 direction. This should never be negative. - return Result(true, -pos.y / maxMovementY); + return Result(true, Vector3(0, -deltaPos.y / maxMovementY, 0)); } - else if (mDirection == MMD_BOTH && pos.y != 0) + else if (mDirection == MMD_BOTH && deltaPos.y != 0) { - return Result(true, pos.y / maxMovementY); + return Result(true, Vector3(0, deltaPos.y / maxMovementY, 0)); } } break; @@ -482,57 +478,54 @@ { if (mDirection == MMD_POSITIVE) { - real ret = 0.f; - if (pos.x > 0.f) + Vector3 ret; + if (deltaPos.x > 0.f) { - ret += (pos.x / maxMovementX); + ret.x += (deltaPos.x / maxMovementX); } - if (pos.y > 0.f) + if (deltaPos.y > 0.f) { - ret += (pos.y / maxMovementY); + ret.y += (deltaPos.y / maxMovementY); } - return (ret > 0.f) ? Result(true,ret) : kAC_FALSE; + return (ret.x > 0.f || ret.y > 0.5) ? Result(true,ret) : kAC_FALSE; } else if (mDirection == MMD_NEGATIVE) { - real ret = 0.0f; - if (pos.x < 0.f) + Vector3 ret; + if (deltaPos.x < 0.f) { - ret += (pos.x / maxMovementX); + ret.x += (deltaPos.x / maxMovementX); } - if (pos.y < 0.f) + if (deltaPos.y < 0.f) { - ret += (pos.y / maxMovementY); + ret.y += (deltaPos.y / maxMovementY); } // The user wants to know how much the mouse has moved, // in only 1 direction. This should never be negative. - return (ret < 0.f) ? Result(true,-ret) : kAC_FALSE; + return (ret.x < 0.f || ret.y < 0.f) ? Result(true,-ret) : kAC_FALSE; } else if (mDirection == MMD_BOTH) { - // This may return awkward values, as it may be 0.0 when - // for example pos.x = 10 and pos.y = -10. It's probably - // better not to use this, but it's here in case someone - // finds a use for it. - return Result(true,(pos.x / maxMovementX) + (pos.y / maxMovementY)); + Vector3 ret(deltaPos.x / maxMovementX, deltaPos.y / maxMovementY, 0); + return Result(true,ret); } } break; case MMA_WHEEL: { - if (mDirection == MMD_POSITIVE && pos.z > 0) + if (mDirection == MMD_POSITIVE && deltaPos.z > 0) { - return Result(true,pos.z / maxWheelmove); + return Result(true,Vector3(0, 0, deltaPos.z / maxWheelmove)); } - else if (mDirection == MMD_NEGATIVE && pos.z < 0) + else if (mDirection == MMD_NEGATIVE && deltaPos.z < 0) { // The user wants to know how much the mouse has moved, // in only 1 direction. This should never be negative. - return Result(true,-pos.z / maxWheelmove); + return Result(true,Vector3(0, 0, -deltaPos.z / maxWheelmove)); } - else if (mDirection == MMD_BOTH && pos.z != 0) + else if (mDirection == MMD_BOTH && deltaPos.z != 0) { - return Result(true,pos.z / maxWheelmove); + return Result(true,Vector3(0, 0, deltaPos.z / maxWheelmove)); } } break; @@ -540,35 +533,35 @@ { if (mDirection == MMD_POSITIVE) { - real ret = 0.0f; - if (pos.x > 0) + Vector3 ret; + if (deltaPos.x > 0) { - ret += (pos.x / maxMovementX); + ret.x += (deltaPos.x / maxMovementX); } - if (pos.y > 0) + if (deltaPos.y > 0) { - ret += (pos.y / maxMovementY); + ret.y += (deltaPos.y / maxMovementY); } - if (pos.z > 0) + if (deltaPos.z > 0) { - ret += (pos.z / maxWheelmove); + ret.z += (deltaPos.z / maxWheelmove); } return Result(true,ret); } else if (mDirection == MMD_NEGATIVE) { - real ret = 0.0f; - if (pos.x < 0) + Vector3 ret; + if (deltaPos.x < 0) { - ret += (pos.x / maxMovementX); + ret.x += (deltaPos.x / maxMovementX); } - if (pos.y < 0) + if (deltaPos.y < 0) { - ret += (pos.y / maxMovementY); + ret.y += (deltaPos.y / maxMovementY); } - if (pos.z < 0) + if (deltaPos.z < 0) { - ret += (pos.z / maxWheelmove); + ret.z += (deltaPos.z / maxWheelmove); } // The user wants to know how much the mouse has moved, // in only 1 direction. This should never be negative. @@ -577,10 +570,10 @@ else if (mDirection == MMD_BOTH) { // This may return awkward values, as it may be 0.0 when - // for example pos.x = 10 and pos.y = -10 and pos.z = 0. + // for example deltaPos.x = 10 and deltaPos.y = -10 and deltaPos.z = 0. // It's probably better not to use this, but it's here // in case someone finds a use for it. - return Result(true,(pos.x / maxMovementX) + (pos.y / maxMovementY) + (pos.z / maxWheelmove)); + return Result(true,Vector3((deltaPos.x / maxMovementX), (deltaPos.y / maxMovementY), (deltaPos.z / maxWheelmove))); } } break; @@ -678,8 +671,8 @@ { ActionMapEntry* entry; ActionId id; - real signal; - TriggeredAction(ActionMapEntry* e, const ActionId i, const real s = real(1.)) : + Vector3 signal; + TriggeredAction(ActionMapEntry* e, const ActionId i, const Vector3 s = Vector3::kZero) : entry(e), id(i), signal(s) {} }; Modified: trunk/yake/src/yake/input/yakeInputEventGenerator.cpp =================================================================== --- trunk/yake/src/yake/input/yakeInputEventGenerator.cpp 2006-09-05 22:40:30 UTC (rev 1447) +++ trunk/yake/src/yake/input/yakeInputEventGenerator.cpp 2006-09-09 18:03:27 UTC (rev 1448) @@ -120,7 +120,7 @@ for (uint8 btn=0; btn<buttonCount; ++btn) { - bool state = mMouse->isButtonDown( btn ); + bool state = mMouse->isButtonDown( MouseButton(btn) ); if (state != mMouseButtons[btn]) { if (state) Modified: trunk/yake/src/yake/plugins/inputOgre/InputSystemOgre.cpp =================================================================== --- trunk/yake/src/yake/plugins/inputOgre/InputSystemOgre.cpp 2006-09-05 22:40:30 UTC (rev 1447) +++ trunk/yake/src/yake/plugins/inputOgre/InputSystemOgre.cpp 2006-09-09 18:03:27 UTC (rev 1448) @@ -46,6 +46,13 @@ 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 ); } //----------------------------------------------------------------------- @@ -60,9 +67,10 @@ } //----------------------------------------------------------------------- - bool MouseDeviceOgre::isButtonDown( int button ) const + bool MouseDeviceOgre::isButtonDown( MouseButton button ) const { - if (button > 2) return false; + YAKE_ASSERT( 0 <= button && button <= MB_LAST )(button)(MB_LAST); + if (button > MB_LAST) return false; if (button < 0) return false; return mButtons[ button ]; } Modified: trunk/yake/yake/input/yakeActionMap.h =================================================================== --- trunk/yake/yake/input/yakeActionMap.h 2006-09-05 22:40:30 UTC (rev 1447) +++ trunk/yake/yake/input/yakeActionMap.h 2006-09-09 18:03:27 UTC (rev 1448) @@ -31,6 +31,8 @@ #include <yake/input/yakePrerequisites.h> #endif +//#include <boost/tuple/tuple.hpp> + namespace yake { namespace input { @@ -116,7 +118,7 @@ public: virtual ~ActionCondition() {} - typedef std::pair<bool,real> Result; + typedef std::pair<bool,Vector3> Result; virtual Result operator()() = 0; }; @@ -165,13 +167,13 @@ class YAKE_INPUT_API MouseButtonActionCondition : public MouseActionCondition { public: - MouseButtonActionCondition( MouseDevice* device, uint8 button = 0, bool continous = false ); - void setButton( uint8 button ); + MouseButtonActionCondition( MouseDevice* device, MouseButton button = MB_LEFT, bool continous = false ); + void setButton( MouseButton button ); void setContinuous( bool continous = false ); virtual Result operator()(); private: - uint8 mButton; - bool mContinuous; + MouseButton mButton; + bool mContinuous; }; enum MouseMoveAxis @@ -235,9 +237,11 @@ struct ActionResult { ActionId id; - real signal; - ActionResult(const ActionId i, const real s = real(1.)) : id(i), signal(s) + Vector3 signal; + ActionResult(const ActionId i, const real s = real(1.)) : id(i), signal(s,0,0) {} + ActionResult(const ActionId i, const Vector3& s) : id(i), signal(s) + {} }; typedef Signal1< void(void) > VoidActionSignal; Modified: trunk/yake/yake/input/yakeInputSystem.h =================================================================== --- trunk/yake/yake/input/yakeInputSystem.h 2006-09-05 22:40:30 UTC (rev 1447) +++ trunk/yake/yake/input/yakeInputSystem.h 2006-09-09 18:03:27 UTC (rev 1448) @@ -220,6 +220,14 @@ virtual bool isKeyDown( KeyCode key ) const = 0; }; + enum MouseButton + { + MB_LEFT = 0, + MB_RIGHT, + MB_MIDDLE, + //MB_USER1, + MB_LAST + }; class YAKE_INPUT_API MouseDevice : public InputDevice { public: @@ -227,7 +235,7 @@ { return IDT_MOUSE; } virtual int getNumButtons() const = 0; - virtual bool isButtonDown( int button ) const = 0; + virtual bool isButtonDown( MouseButton button ) const = 0; virtual math::Vector3 getPosition() const = 0; virtual void setClip( const math::Rectangle & rect ) = 0; virtual void setScale( const math::Vector3 & scale ) = 0; Modified: trunk/yake/yake/plugins/inputOgre/InputSystemOgre.h =================================================================== --- trunk/yake/yake/plugins/inputOgre/InputSystemOgre.h 2006-09-05 22:40:30 UTC (rev 1447) +++ trunk/yake/yake/plugins/inputOgre/InputSystemOgre.h 2006-09-09 18:03:27 UTC (rev 1448) @@ -42,7 +42,7 @@ virtual ~MouseDeviceOgre(); virtual int getNumButtons() const; - virtual bool isButtonDown( int button ) const; + virtual bool isButtonDown( MouseButton button ) const; virtual math::Vector3 getPosition() const; virtual void setClip( const math::Rectangle & rect ) { mClip = rect; } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2006-09-09 18:05:15
|
Revision: 1449 http://svn.sourceforge.net/yake/?rev=1449&view=rev Author: psyclonist Date: 2006-09-09 11:04:56 -0700 (Sat, 09 Sep 2006) Log Message: ----------- fixed physics timing, added physics time to RAF application state Modified Paths: -------------- trunk/yake/src/yake/plugins/physicsODE/OdeWorld.cpp trunk/yake/src/yapp/raf/yakeRtApplicationState.cpp trunk/yake/src/yapp/samples/misc/cmdrmayhem/yakeDemo.cpp trunk/yake/yapp/raf/yakeRtApplicationState.h Modified: trunk/yake/src/yake/plugins/physicsODE/OdeWorld.cpp =================================================================== --- trunk/yake/src/yake/plugins/physicsODE/OdeWorld.cpp 2006-09-09 18:03:27 UTC (rev 1448) +++ trunk/yake/src/yake/plugins/physicsODE/OdeWorld.cpp 2006-09-09 18:04:56 UTC (rev 1449) @@ -362,18 +362,19 @@ //----------------------------------------------------- void OdeWorld::step( const real timeElapsed ) { - real t = mTimeOverflow + timeElapsed; + mTimeOverflow += timeElapsed; - //std::cout << "step dt=" << timeElapsed << " t=" << t << " step=" << mStepSize << "\n"; + std::cout << "physics.step() @ time=" << mTime << " overflow=" << mTimeOverflow << " dt=" << timeElapsed << " step=" << mStepSize << "\n"; + firePreStep(); real steppedTime = 0.; - while ( t > mStepSize ) + while ( mTimeOverflow > mStepSize ) { //std::cout << " t=" << t << "\n"; steppedTime += mStepSize; mTime += mStepSize; - t -= mStepSize; + mTimeOverflow -= mStepSize; // pre-step @@ -428,8 +429,6 @@ } firePostStep( steppedTime, mTime ); - - mTimeOverflow = t; } //----------------------------------------------------- Modified: trunk/yake/src/yapp/raf/yakeRtApplicationState.cpp =================================================================== --- trunk/yake/src/yapp/raf/yakeRtApplicationState.cpp 2006-09-09 18:03:27 UTC (rev 1448) +++ trunk/yake/src/yapp/raf/yakeRtApplicationState.cpp 2006-09-09 18:04:56 UTC (rev 1449) @@ -39,7 +39,8 @@ MainState(owner), mQuitRequested(false), mQuitKC(input::KC_ESCAPE), - mQuitByKeyEnabled(false) + mQuitByKeyEnabled(false), + mPhysicsTimeFactor(real(1.)) {} graphics::ICamera* RtMainState::onCreateDefaultCamera() { @@ -75,6 +76,16 @@ mQuitByKeyEnabled = true; mQuitKC = kc; } + void RtMainState::setPhysicsTimeFactor(const real factor) + { + YAKE_ASSERT( factor >= 0. )( factor ).debug("factors < 0 cannot be handled."); + if (factor >= 0.) + mPhysicsTimeFactor = factor; + } + real RtMainState::getPhysicsTimeFactor() const + { + return mPhysicsTimeFactor; + } void RtMainState::onEnter() { createScene(); @@ -84,7 +95,7 @@ real lastTime = native::getTime(); while (!quitRequested()) { - real now = native::getTime(); + const real now = native::getTime(); real elapsed = now - lastTime; if (elapsed < real(0.0001)) elapsed = real(0.01); @@ -103,10 +114,17 @@ onFrame(elapsed); if (mPWorld.get()) - mPWorld->step( elapsed ); + { + const real time_physics_elapsed = mPhysicsTimeFactor * elapsed; + mPWorld->step( time_physics_elapsed ); + this->triggerPhysicsUpdateSignal( time_physics_elapsed ); + } if (mGWorld.get()) + { mGWorld->render( elapsed ); + this->triggerGraphicsUpdateSignal( 0, elapsed ); //@todo fixme parameter sim time "si" + } lastTime = now; } Modified: trunk/yake/src/yapp/samples/misc/cmdrmayhem/yakeDemo.cpp =================================================================== --- trunk/yake/src/yapp/samples/misc/cmdrmayhem/yakeDemo.cpp 2006-09-09 18:03:27 UTC (rev 1448) +++ trunk/yake/src/yapp/samples/misc/cmdrmayhem/yakeDemo.cpp 2006-09-09 18:04:56 UTC (rev 1449) @@ -4,9 +4,19 @@ #include <yake/model/model.h> #include <yake/input/yakeInput.h> #include <yapp/common/yakeCameraControllers.h> +//#include <yapp/common/yakeCEGUIHelpers.h> +#include <CEGUI/CEGUISystem.h> +#include <CEGUI/CEGUISchemeManager.h> +#include <CEGUI/CEGUIWindowManager.h> +#include <CEGUI/CEGUIWindow.h> +#include <CEGUI/CEGUIExceptions.h> +#include <CEGUI/CEGUIString.h> using namespace yake; +const input::ActionId ACTIONID_ZOOM_INOUT( input::ACTIONID_USER + 1, "zoom_inout" ); +const input::ActionId ACTIONID_MOUSE_MOVE( input::ACTIONID_USER + 2, "mouse_move" ); + /** Configuration of the application */ struct TheConfiguration : public raf::ApplicationConfiguration { @@ -48,7 +58,7 @@ } /** Main application state */ -class TheMainState : public raf::RtMainState, public yake::model::CentralControllerBase +class TheMainState : public raf::RtMainState { public: TheMainState(raf::Application& owner) : @@ -64,6 +74,20 @@ { } private: + //@todo cleanup code! + void setupGUI() + { + using namespace CEGUI; + try { + WindowManager& wmgr = WindowManager::getSingleton(); + Window* sheet = wmgr.loadWindowLayout( "cmdr_main.layout" ); + System::getSingleton().setGUISheet(sheet); + } + catch (CEGUI::Exception& ex) + { + YAKE_EXCEPT(yake::String("CEGUI Exception:\n") + ex.getMessage().c_str() ); + } + } protected: virtual void onCreateScene() { @@ -184,18 +208,34 @@ mActionMap.reg( ACTIONID_DOWN, new input::KeyboardActionCondition( getApp().getKeyboard(), KC_C, KAM_PRESSED ) ); mActionMap.subscribeToActionIdV( ACTIONID_DOWN, boost::bind(&TheMainState::onCrouch,this) ); - mActionMap.reg( ACTIONID_PITCH_UP, new input::MouseMoveActionCondition( getApp().getMouse(), input::MMA_WHEEL, input::MMD_BOTH ) ); - mActionMap.subscribeToActionIdR( ACTIONID_PITCH_UP, Bind1(&TheMainState::onMouseWheel,this) ); + mActionMap.reg( ACTIONID_ZOOM_INOUT, new input::MouseMoveActionCondition( getApp().getMouse(), input::MMA_WHEEL, input::MMD_BOTH ) ); + mActionMap.subscribeToActionIdR( ACTIONID_ZOOM_INOUT, Bind1(&TheMainState::onMouseWheel,this) ); + mActionMap.reg( ACTIONID_MOUSE_MOVE, new input::MouseMoveActionCondition( getApp().getMouse(), input::MMA_X_AND_Y, input::MMD_BOTH ) ); + mActionMap.subscribeToActionIdR( ACTIONID_MOUSE_MOVE, Bind1(&TheMainState::onMouseMoveXY,this) ); + // for cursor getApp().enableMouseInputForCEGUI(true); + getApp().enableKeyboardInputForCEGUI(true); + + setupGUI(); } virtual void onExit() { + //@todo cleanupGUI(); + + getApp().enableKeyboardInputForCEGUI(false); getApp().enableMouseInputForCEGUI(false); } virtual void onFrame(const real timeElapsed) { + /* + static real time = 0.; + std::cout << "onFrame() @ " << time << "\n"; + time += timeElapsed; + */ + + // mActionMap.update(); math::Vector3 projViewDir = mTopDownCtrlr.getOffset(); @@ -231,12 +271,6 @@ playerTargetVel = projViewRot * playerTargetVel; mPlayerRep->setTargetVelocity( playerTargetVel.normalisedCopy() * maxVel ); - if (mComplex) - { - this->triggerGraphicsUpdateSignal(0,timeElapsed); - this->triggerPhysicsUpdateSignal(timeElapsed); - } - { // top-down controller const real dist = timeElapsed * 4.; math::Vector3 offset; @@ -253,20 +287,52 @@ } mTopDownCtrlr.setTarget( mPlayerRep->getPosition() ); + + if (this->getApp().getMouse()->isButtonDown( input::MB_RIGHT )) + { + std::cout << mMouseMovement << "\n"; + mTopDownCtrlr.setTargetOffset( mTopDownCtrlr.getTargetOffset() + mMouseMovement * 1000. * timeElapsed ); + //@todo mMouseMovement + } + + // mTopDownCtrlr.update( timeElapsed ); // prepare for next step mActiveActions.clear(); + mMouseMovement = Vector3::kZero; //std::cout << this->mPlayerRep->getPosition() << "\n"; + + if (this->getApp().getKeyboard()->isKeyDown(input::KC_ADD)) + { + real physicsTimeFactor = this->getPhysicsTimeFactor(); + physicsTimeFactor += 0.1 * timeElapsed; + this->setPhysicsTimeFactor( physicsTimeFactor ); + std::cout << "factor = " << this->getPhysicsTimeFactor() << "\n"; + } + if (this->getApp().getKeyboard()->isKeyDown(input::KC_SUBTRACT)) + { + real physicsTimeFactor = this->getPhysicsTimeFactor(); + physicsTimeFactor -= 0.1 * timeElapsed; + if (physicsTimeFactor < 0.) physicsTimeFactor = 0.; + this->setPhysicsTimeFactor( physicsTimeFactor ); + std::cout << "factor = " << this->getPhysicsTimeFactor() << "\n"; + } } protected: + void onMouseMoveXY(const input::ActionMap::ActionResult& ar) + { + mMouseMovement = ar.signal * 10.; + std::swap( mMouseMovement.y, mMouseMovement.z ); + mMouseMovement.y = 0.; + } void onMouseWheel(const input::ActionMap::ActionResult& ar) { - if (fabs(ar.signal) < std::numeric_limits<real>::epsilon()) + if (fabs(ar.signal.z) < std::numeric_limits<real>::epsilon()) return; - const real fac = (1.0 - 0.1 * ar.signal); // either 0.9 or 1.1 + const real fac = (1.0 - 0.1 * ar.signal.z); // either 0.9 or 1.1 // scale the target offset Vector3 targetOffset = mTopDownCtrlr.getTargetOffset() * fac; @@ -302,6 +368,7 @@ Env* mEnv; TopDownCameraController mTopDownCtrlr; + Vector3 mMouseMovement; }; /** The mighty application itself! */ Modified: trunk/yake/yapp/raf/yakeRtApplicationState.h =================================================================== --- trunk/yake/yapp/raf/yakeRtApplicationState.h 2006-09-09 18:03:27 UTC (rev 1448) +++ trunk/yake/yapp/raf/yakeRtApplicationState.h 2006-09-09 18:04:56 UTC (rev 1449) @@ -31,6 +31,7 @@ #include "yake/graphics/yakeGraphics.h" #include "yake/physics/yakePhysics.h" #include "yake/scripting/yakeScriptingSystem.h" +#include "yake/model/model.h" namespace yake { namespace raf { @@ -38,27 +39,25 @@ class MainState; /** Typical realtime application main state */ - class YAKE_RAF_API RtMainState : public MainState + class YAKE_RAF_API RtMainState : public MainState, public yake::model::CentralControllerBase { public: RtMainState(Application& owner); void requestQuit(); bool quitRequested() const; void enableInstantQuitByKey( input::KeyCode kc ); + + /** Factor is multiplied with delta time of real elapsed time. + @note The factor should be between [0.0 .. 1.0+]. 0 is pause, 1 is real-time, anything above is accelerated. + */ + void setPhysicsTimeFactor( const real ); + real getPhysicsTimeFactor() const; protected: // main message handlers to override - virtual void onEnter(); virtual void onStep(); virtual void onExit(); - private: - // setup functions - void createScene(); - void destroyScene(); - void createCameraViewportPair(); - - protected: // message handlers to override by derived classes virtual void onCreateScene() {} virtual graphics::ICamera* onGetDefaultCamera() { return 0; } @@ -77,6 +76,11 @@ graphics::ICamera* getDefaultCamera(); private: + // setup functions + void createScene(); + void destroyScene(); + void createCameraViewportPair(); + private: bool mQuitRequested; SharedPtr<graphics::IWorld> mGWorld; SharedPtr<audio::IWorld> mAWorld; @@ -88,6 +92,8 @@ input::KeyCode mQuitKC; bool mQuitByKeyEnabled; + + real mPhysicsTimeFactor; }; } // namespace raf This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2006-09-10 20:49:56
|
Revision: 1455 http://svn.sourceforge.net/yake/?rev=1455&view=rev Author: psyclonist Date: 2006-09-10 13:48:56 -0700 (Sun, 10 Sep 2006) Log Message: ----------- - msg is now parameterizable by source and target types - various documenation and code improvements Modified Paths: -------------- trunk/yake/scripts/msvc8/ent.vcproj trunk/yake/src/yake/ent/component_holder.cpp trunk/yake/src/yake/ent/object.cpp trunk/yake/src/yake/ent/vm_holder.cpp trunk/yake/src/yake/model/yakeModelManager.cpp trunk/yake/src/yake/model/yakeModelTemplateManager.cpp trunk/yake/src/yapp/samples/misc/vehicle/yakeDemo.cpp trunk/yake/yake/ent/component.h trunk/yake/yake/ent/component_holder.h trunk/yake/yake/ent/ent.h trunk/yake/yake/ent/object.h trunk/yake/yake/ent/object_listener.h trunk/yake/yake/ent/object_mgr.h trunk/yake/yake/ent/object_mgr_listener.h trunk/yake/yake/ent/prerequisites.h trunk/yake/yake/ent/vm_holder.h trunk/yake/yake/model/model.h trunk/yake/yake/model/model_component.h trunk/yake/yake/msg/listener.h trunk/yake/yake/msg/listener_mgr.h trunk/yake/yake/msg/message.h trunk/yake/yake/msg/prerequisites.h trunk/yake/yake/msg/processors.h trunk/yake/yake/msg/router.h trunk/yake/yake/msg/yakeMessage.h trunk/yake/yake/object/ObjectManager.h trunk/yake/yake/object/ObjectManager.inl Added Paths: ----------- trunk/yake/src/yake/ent/entity.cpp trunk/yake/yake/ent/entity.h Modified: trunk/yake/scripts/msvc8/ent.vcproj =================================================================== --- trunk/yake/scripts/msvc8/ent.vcproj 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/scripts/msvc8/ent.vcproj 2006-09-10 20:48:56 UTC (rev 1455) @@ -200,6 +200,10 @@ > </File> <File + RelativePath="..\..\src\yake\ent\entity.cpp" + > + </File> + <File RelativePath="..\..\src\yake\ent\object.cpp" > </File> @@ -258,6 +262,10 @@ > </File> <File + RelativePath="..\..\yake\ent\entity.h" + > + </File> + <File RelativePath="..\..\yake\ent\object.h" > </File> Modified: trunk/yake/src/yake/ent/component_holder.cpp =================================================================== --- trunk/yake/src/yake/ent/component_holder.cpp 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/src/yake/ent/component_holder.cpp 2006-09-10 20:48:56 UTC (rev 1455) @@ -33,7 +33,7 @@ void CoHolder::addComponent(const CoTag& tag, Component* co) { if (getComponent(tag)) - return; //@todo throw instead? + YAKE_EXCEPT("Component with this tag already exists in this CoHolder instance!"); components_.insert( std::make_pair(tag, co) ); } Component* CoHolder::getComponent(const CoTag& tag) const Added: trunk/yake/src/yake/ent/entity.cpp =================================================================== --- trunk/yake/src/yake/ent/entity.cpp (rev 0) +++ trunk/yake/src/yake/ent/entity.cpp 2006-09-10 20:48:56 UTC (rev 1455) @@ -0,0 +1,118 @@ +/* +------------------------------------------------------------------------------------ +This file is part of YAKE +Copyright (c) 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(Entity) + + 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). + // That's why we use the approach below. + //m_.processEventCb(evt,boost::bind(&Entity::onEnter,this,_1,_2),boost::bind(&Entity::onExit,this,_1,_2)); + + typedef boost::function<void(const object_fsm&, const object_fsm::state_type& state)> fn_t; + const fn_t fnEnter = boost::bind(&Entity::onEnter,boost::ref(this),_1,_2); + const fn_t fnExit = boost::bind(&Entity::onExit,boost::ref(this),_1,_2); + + m_.processEventCb(String(evt), fnEnter, fnExit); + + listeners_fsmEventHandled(*this,m_,evt); + } + void Entity::addFsmState(const fsm_state_type& state) + { + m_.addState(state); + } + void Entity::addFsmTransition(const fsm_state_type& from, const fsm_event_type& evt, const fsm_state_type& to) + { + m_.addTransition(from,evt,to); + } + void Entity::setFsmState(const fsm_state_type& state) + { + m_.setState(state); + } + void Entity::onEnter(const object_fsm& fsm, const object_fsm::state_type& state) + { + //std::cout << "Entity.state.enter '" << state << "'\n"; + listeners_fsmEnterState(*this,fsm,state); + } + void Entity::onExit(const object_fsm& fsm, const object_fsm::state_type& state) + { + //std::cout << "Entity.state.exit '" << state << "'\n"; + listeners_fsmExitState(*this,fsm,state); + } + SignalConnection Entity::subsribeToVmAttached(const VMHolder::VmAttachedSignal::slot_type& slot) + { + return vms_.subsribeToVmAttached(slot); + } + SignalConnection Entity::subscribeToVmDetached(const VMHolder::VmDetachedSignal::slot_type& slot) + { + return vms_.subscribeToVmDetached(slot); + } + bool Entity::attachVM(scripting::IVM* vm,const String& tag) + { + return vms_.attachVM(vm,tag); + } + scripting::IVM* Entity::detachVM(const String& tag) + { + return vms_.detachVM(tag); + } + scripting::IVM* Entity::getVM(const String& tag) const + { + return vms_.getVM(tag); + } + void Entity::setModel(ModelPtr modelPtr) + { + model_ = modelPtr; + } + ModelPtr Entity::getModel() const + { + return model_; + } +#if 0 //@todo fixme + void Entity::addComponent(const CoTag& tag, Component* co) + { + components_.addComponent( tag, co ); + } + Component* Entity::removeComponent(const Component* co) + { + return components_.removeComponent( co ); + } + Component* Entity::removeComponent(const CoTag& tag) + { + return components_.removeComponent( tag ); + } + Component* Entity::getComponent(const CoTag& tag) const + { + return components_.getComponent( tag ); + } +#endif +} // namespace ent +} // namespace yake Modified: trunk/yake/src/yake/ent/object.cpp =================================================================== --- trunk/yake/src/yake/ent/object.cpp 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/src/yake/ent/object.cpp 2006-09-10 20:48:56 UTC (rev 1455) @@ -41,65 +41,13 @@ return id_; } - IMPL_OBJECT(Entity) - - 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). - // That's why we use the approach below. - //m_.processEventCb(evt,boost::bind(&Entity::onEnter,this,_1,_2),boost::bind(&Entity::onExit,this,_1,_2)); - - typedef boost::function<void(const object_fsm&, const object_fsm::state_type& state)> fn_t; - const fn_t fnEnter = boost::bind(&Entity::onEnter,boost::ref(this),_1,_2); - const fn_t fnExit = boost::bind(&Entity::onExit,boost::ref(this),_1,_2); - - m_.processEventCb(std::string(evt), fnEnter, fnExit); - - listeners_fsmEventHandled(*this,m_,evt); - } - void Entity::addFsmState(const fsm_state_type& state) - { - m_.addState(state); - } - void Entity::addFsmTransition(const fsm_state_type& from, const fsm_event_type& evt, const fsm_state_type& to) - { - m_.addTransition(from,evt,to); - } - void Entity::setFsmState(const fsm_state_type& state) - { - m_.setState(state); - } - void Entity::onEnter(const object_fsm& fsm, const object_fsm::state_type& state) - { - //std::cout << "Entity.state.enter '" << state << "'\n"; - listeners_fsmEnterState(*this,fsm,state); - } - void Entity::onExit(const object_fsm& fsm, const object_fsm::state_type& state) - { - //std::cout << "Entity.state.exit '" << state << "'\n"; - listeners_fsmExitState(*this,fsm,state); - } - SignalConnection Entity::subsribeToVmAttached(const VMHolder::VmAttachedSignal::slot_type& slot) - { - return vms_.subsribeToVmAttached(slot); - } - SignalConnection Entity::subscribeToVmDetached(const VMHolder::VmDetachedSignal::slot_type& slot) - { - return vms_.subscribeToVmDetached(slot); - } - bool Entity::attachVM(scripting::IVM* vm,const std::string& tag) - { - return vms_.attachVM(vm,tag); - } - scripting::IVM* Entity::detachVM(const std::string& tag) - { - return vms_.detachVM(tag); - } - scripting::IVM* Entity::getVM(const std::string& tag) const - { - return vms_.getVM(tag); - } - } } +MSG_NAMESPACE_BEGIN +const traits<ent::ObjectId,ent::ObjectId>::Source traits<ent::ObjectId,ent::ObjectId>::kNoSource = ent::ObjectId(-1,0); +const traits<ent::ObjectId,ent::ObjectId>::Source traits<ent::ObjectId,ent::ObjectId>::kAnySource = ent::ObjectId(-1,1); +const traits<ent::ObjectId,ent::ObjectId>::Source traits<ent::ObjectId,ent::ObjectId>::kNoTarget = ent::ObjectId(-1,2); +const traits<ent::ObjectId,ent::ObjectId>::Source traits<ent::ObjectId,ent::ObjectId>::kBroadcastTarget = ent::ObjectId(-1,3); +const traits<ent::ObjectId,ent::ObjectId>::Source traits<ent::ObjectId,ent::ObjectId>::kAnyTarget = ent::ObjectId(-1,4); +MSG_NAMESPACE_END Modified: trunk/yake/src/yake/ent/vm_holder.cpp =================================================================== --- trunk/yake/src/yake/ent/vm_holder.cpp 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/src/yake/ent/vm_holder.cpp 2006-09-10 20:48:56 UTC (rev 1455) @@ -44,7 +44,7 @@ */ vms_.clear(); } - bool VMHolder::attachVM(scripting::IVM* vm,const std::string& tag) + bool VMHolder::attachVM(scripting::IVM* vm,const String& tag) { YAKE_ASSERT(vm)(tag).debug("null vm"); if (!vm) @@ -60,7 +60,7 @@ sigAttached_(tag,vm); return true; } - scripting::IVM* VMHolder::detachVM(const std::string &tag) + scripting::IVM* VMHolder::detachVM(const String &tag) { YAKE_ASSERT( !tag.empty() )(tag).debug("invalid tag"); if (tag.empty()) @@ -74,7 +74,7 @@ sigAttached_(tag,vm); return vm; } - scripting::IVM* VMHolder::getVM(const std::string &tag) const + scripting::IVM* VMHolder::getVM(const String &tag) const { YAKE_ASSERT( !tag.empty() )(tag).debug("invalid tag"); if (tag.empty()) Modified: trunk/yake/src/yake/model/yakeModelManager.cpp =================================================================== --- trunk/yake/src/yake/model/yakeModelManager.cpp 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/src/yake/model/yakeModelManager.cpp 2006-09-10 20:48:56 UTC (rev 1455) @@ -90,7 +90,7 @@ name=... ... */ - Model* ModelManager::createModel(const String& modelName, const ModelComponentDescList& compDescList) + ModelPtr ModelManager::createModel(const String& modelName, const ModelComponentDescList& compDescList) { YAKE_LOG_INFORMATION( "MODEL: Creating model with name: " + modelName ); @@ -98,13 +98,13 @@ YAKE_ASSERT( !modelName.empty() ); YAKE_ASSERT( models_.find(modelName) == models_.end() )(modelName).debug("Model with that name already exists."); if (models_.find(modelName) != models_.end()) - return 0; + return ModelPtr(); // Create model object - Model* m = new Model(); + ModelPtr m( new Model() ); m->setName( modelName ); - models_.insert( std::make_pair(modelName,SharedPtr<Model>(m)) ); //FIXME <-- data duplication. Model already has a name. - modelCtx_.model_ = m; + models_.insert( std::make_pair(modelName,m) ); //FIXME <-- data duplication. Model already has a name. + modelCtx_.model_ = m.get(); sigModelCreatedSignal_(*m,modelCtx_); @@ -141,13 +141,13 @@ return m; } /// graphics/dotScene:name=gfx;file=bla.scene|physics/dotXODE... - Model* ModelManager::createModel(const String& modelName, const String& def) + ModelPtr ModelManager::createModel(const String& modelName, const String& def) { // Validate name YAKE_ASSERT( !modelName.empty() ); YAKE_ASSERT( models_.find(modelName) == models_.end() )(modelName).debug("Model with that name already exists."); if (models_.find(modelName) != models_.end()) - return 0; + return ModelPtr(); // Split components string Vector<String> defComponents = split<String>(def, "|"); Modified: trunk/yake/src/yake/model/yakeModelTemplateManager.cpp =================================================================== --- trunk/yake/src/yake/model/yakeModelTemplateManager.cpp 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/src/yake/model/yakeModelTemplateManager.cpp 2006-09-10 20:48:56 UTC (rev 1455) @@ -113,7 +113,7 @@ return true; } - Model* ModelManager::createModelFromTemplate(const String& modelName, const String& tplName) + ModelPtr ModelManager::createModelFromTemplate(const String& modelName, const String& tplName) { YAKE_ASSERT( !modelName.empty() )(modelName)(tplName); YAKE_ASSERT( !tplName.empty() )(modelName)(tplName); @@ -124,7 +124,7 @@ // bail out if template could not be found if (it == this->modelTemplates_.end()) - return 0; + return ModelPtr(); // create model using template YAKE_ASSERT( it->second.get() )(modelName)(tplName); Modified: trunk/yake/src/yapp/samples/misc/vehicle/yakeDemo.cpp =================================================================== --- trunk/yake/src/yapp/samples/misc/vehicle/yakeDemo.cpp 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/src/yapp/samples/misc/vehicle/yakeDemo.cpp 2006-09-10 20:48:56 UTC (rev 1455) @@ -252,7 +252,7 @@ }; struct Car : public GoVehicleBase { - Car() : mModel(0), mVehicle(0) + Car() : mVehicle(0) {} ~Car() { @@ -311,7 +311,7 @@ void destroy() { //@todo - mModel = 0; + mModel.reset(); mVehicle = 0; } virtual void onEnter(input::ActionMap& actionMap, input::KeyboardDevice* keyboard) @@ -391,7 +391,7 @@ } private: vehicle::IVehicle* mVehicle; - model::Model* mModel; + model::ModelPtr mModel; typedef AssocVector<String,real> EmitterRealMap; EmitterRealMap mEmitterMinVel; EmitterRealMap mEmitterMaxVel; @@ -444,7 +444,7 @@ struct Jet : public GoVehicleBase { - Jet() : mModel(0), mVehicle(0) + Jet() : mModel(), mVehicle(0) {} ~Jet() { @@ -506,7 +506,7 @@ void destroy() { //@todo - mModel = 0; + mModel.reset(); mVehicle = 0; } virtual void onEnter(input::ActionMap& actionMap, input::KeyboardDevice* keyboard) @@ -589,7 +589,7 @@ } private: vehicle::IVehicle* mVehicle; - model::Model* mModel; + model::ModelPtr mModel; typedef AssocVector<String,real> EmitterRealMap; EmitterRealMap mEmitterMinVel; Modified: trunk/yake/yake/ent/component.h =================================================================== --- trunk/yake/yake/ent/component.h 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/yake/ent/component.h 2006-09-10 20:48:56 UTC (rev 1455) @@ -44,6 +44,10 @@ #define IMPL_CO_1(CLASS,PARENT1) \ IMPL_CLASS_RTTI_1(CLASS,PARENT1) + /** Represents the base class for object components. + @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> { virtual ~Component() {} Modified: trunk/yake/yake/ent/component_holder.h =================================================================== --- trunk/yake/yake/ent/component_holder.h 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/yake/ent/component_holder.h 2006-09-10 20:48:56 UTC (rev 1455) @@ -32,15 +32,35 @@ namespace yake { namespace ent { - typedef std::string CoTag; + /** Type that is used to tag components in component holders (CoHolder). */ + typedef String CoTag; + + /** Container of components. Components have to be tagged. + @note Tags have to be unique within a CoHolder object. + @note This class is not intended to be derived from! Therefore it doesn't have a virtual destructor! + */ struct YAKE_ENT_API CoHolder { - // operations + CoHolder() {} + + /** 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; private: + CoHolder(const CoHolder&); + CoHolder& operator=(const CoHolder&); + private: typedef std::map<CoTag,Component*> TagCoMap; TagCoMap components_; }; Modified: trunk/yake/yake/ent/ent.h =================================================================== --- trunk/yake/yake/ent/ent.h 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/yake/ent/ent.h 2006-09-10 20:48:56 UTC (rev 1455) @@ -34,6 +34,7 @@ #include "yake/ent/object.h" #include "yake/ent/object_mgr.h" #include "yake/ent/object_mgr_listener.h" +#include "yake/ent/entity.h" #endif Added: trunk/yake/yake/ent/entity.h =================================================================== --- trunk/yake/yake/ent/entity.h (rev 0) +++ trunk/yake/yake/ent/entity.h 2006-09-10 20:48:56 UTC (rev 1455) @@ -0,0 +1,114 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright (c) 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_ENTITY_H +#define YAKE_ENT_ENTITY_H + +#include "yake/ent/prerequisites.h" +#include "yake/ent/object.h" +#include "yake/model/model.h" //@todo reduce dependency ... + +namespace yake { +namespace ent { + + typedef model::ModelPtr ModelPtr; + /** Represents complex objects with components, unique ids, properties, state machines, scripting machines. + */ + struct YAKE_ENT_API Entity : public Object + { + DECL_OBJECT(Entity,"Entity") + Entity() {} + virtual ~Entity() {} + + typedef object_fsm::state_type fsm_state_type; + typedef object_fsm::event_type fsm_event_type; + + // FSM operations + + void addFsmState(const fsm_state_type&); + void addFsmTransition(const fsm_state_type&, const fsm_event_type&, const fsm_state_type&); + void setFsmState(const fsm_state_type&); + void processFsmEvent(const fsm_event_type& evt); + const fsm_state_type& getCurrentFsmState() const + { return m_.current(); } + + // VM operations + + SignalConnection subsribeToVmAttached(const VMHolder::VmAttachedSignal::slot_type&); + SignalConnection subscribeToVmDetached(const VMHolder::VmDetachedSignal::slot_type&); + + bool attachVM(scripting::IVM*,const String& tag); + scripting::IVM* detachVM(const String& tag); + scripting::IVM* getVM(const String& tag) const; + + scripting::IVM* getFsmVM() const + { + return this->getVM("main"); + } + + 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::IVM*)> VmInitializedSignal; + boost::signals::connection subscribeToVmInitialized(const VmInitializedSignal::slot_type&); + + private: + void onEnter(const object_fsm&, const object_fsm::state_type& state); + void onExit(const object_fsm&, const object_fsm::state_type& state); + private: + object_fsm m_; + VMHolder vms_; + CoHolder components_; + ModelPtr model_; + }; + +} // namespace ent +} // namespace yake + +#endif + Modified: trunk/yake/yake/ent/object.h =================================================================== --- trunk/yake/yake/ent/object.h 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/yake/ent/object.h 2006-09-10 20:48:56 UTC (rev 1455) @@ -53,6 +53,8 @@ return (obj ? ((obj->isA() == CLASS::cls()) ? dynamic_cast<CLASS*>(obj) : 0 ) : 0); \ } + /** Base class for complex objects with unique ids, properties and default events. + */ struct YAKE_ENT_API Object : public yake::PropHolder<Object>, public ObjectListenerManager { DECL_OBJECT(Object,"Object") @@ -83,57 +85,6 @@ ObjectId id_; }; - /** @todo Do not publicly inherit from CoHolder and VMHolder!? - */ - struct YAKE_ENT_API Entity : public Object, public CoHolder - { - DECL_OBJECT(Entity,"Entity") - Entity() {} - virtual ~Entity() {} - - typedef object_fsm::state_type fsm_state_type; - typedef object_fsm::event_type fsm_event_type; - - // id operations - - void setId(const ObjectId& id); - const ObjectId& getId() const; - - // FSM operations - - void addFsmState(const fsm_state_type&); - void addFsmTransition(const fsm_state_type&, const fsm_event_type&, const fsm_state_type&); - void setFsmState(const fsm_state_type&); - void processFsmEvent(const fsm_event_type& evt); - const fsm_state_type& getCurrentFsmState() const - { return m_.current(); } - - // VM operations - - SignalConnection subsribeToVmAttached(const VMHolder::VmAttachedSignal::slot_type&); - SignalConnection subscribeToVmDetached(const VMHolder::VmDetachedSignal::slot_type&); - - bool attachVM(scripting::IVM*,const std::string& tag); - scripting::IVM* detachVM(const std::string& tag); - scripting::IVM* getVM(const std::string& tag) const; - - scripting::IVM* getFsmVM() const - { - return this->getVM("main"); - } - - // signals - typedef boost::signal<void(const std::string&,scripting::IVM*)> VmInitializedSignal; - boost::signals::connection subscribeToVmInitialized(const VmInitializedSignal::slot_type&); - - private: - void onEnter(const object_fsm&, const object_fsm::state_type& state); - void onExit(const object_fsm&, const object_fsm::state_type& state); - private: - object_fsm m_; - VMHolder vms_; - }; - } // namespace ent } // namespace yake Modified: trunk/yake/yake/ent/object_listener.h =================================================================== --- trunk/yake/yake/ent/object_listener.h 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/yake/ent/object_listener.h 2006-09-10 20:48:56 UTC (rev 1455) @@ -33,14 +33,16 @@ namespace ent { struct Object; + /** Callback base class for typical per-Object events. + */ struct YAKE_ENT_API ObjectListener { virtual ~ObjectListener() {} virtual void onTick(Object&) {} virtual void onInit(Object&) {} virtual void onFsmEventHandled(Object&, const object_fsm&, const object_fsm::event_type&) {} - virtual void onFsmEnterState(Object&,/*const std::string& fsmName, */const object_fsm&, const object_fsm::state_type&) {} - virtual void onFsmExitState(Object&,/*const std::string& fsmName, */const object_fsm&, const object_fsm::state_type&) {} + virtual void onFsmEnterState(Object&,/*const String& fsmName, */const object_fsm&, const object_fsm::state_type&) {} + virtual void onFsmExitState(Object&,/*const String& fsmName, */const object_fsm&, const object_fsm::state_type&) {} }; struct YAKE_ENT_API ObjectListenerManager : public ListenerManager<ObjectListener> @@ -58,19 +60,19 @@ while (it.hasMoreElements()) it.getNext().first->onTick(obj); } - void listeners_fsmEventHandled(Object& obj,/*const std::string& fsmName, */const object_fsm& fsm, const object_fsm::event_type& evt) + void listeners_fsmEventHandled(Object& obj,/*const String& fsmName, */const object_fsm& fsm, const object_fsm::event_type& evt) { yake::ConstVectorIterator<listener_list> it(listeners_); while (it.hasMoreElements()) it.getNext().first->onFsmEventHandled(obj,fsm,evt); } - void listeners_fsmEnterState(Object& obj,/*const std::string& fsmName, */const object_fsm& fsm, const object_fsm::state_type& state) + void listeners_fsmEnterState(Object& obj,/*const String& fsmName, */const object_fsm& fsm, const object_fsm::state_type& state) { yake::ConstVectorIterator<listener_list> it(listeners_); while (it.hasMoreElements()) it.getNext().first->onFsmEnterState(obj,fsm,state); } - void listeners_fsmExitState(Object& obj,/*const std::string& fsmName, */const object_fsm& fsm, const object_fsm::state_type& state) + void listeners_fsmExitState(Object& obj,/*const String& fsmName, */const object_fsm& fsm, const object_fsm::state_type& state) { yake::ConstVectorIterator<listener_list> it(listeners_); while (it.hasMoreElements()) Modified: trunk/yake/yake/ent/object_mgr.h =================================================================== --- trunk/yake/yake/ent/object_mgr.h 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/yake/ent/object_mgr.h 2006-09-10 20:48:56 UTC (rev 1455) @@ -38,16 +38,40 @@ typedef object::ResultCode RegistrationResultCode; typedef std::pair<RegistrationResultCode,ClassId> RegistrationResult; + /** Manages class registration; creation, destruction and initialization of instances; + as well as messaging between Objects. + @note ObjectManager also provides callback management for common events. + */ struct YAKE_ENT_API ObjectManager : public ListenerManager<ObjectManagerListener> { // operations + + /** Creates an Object for the given clsId. + If the ClassId isn't known (i.e. unregistered) then 0 is returned. + */ Object* makeObject(const ClassId clsId); - Object* makeObject(const std::string strClsId); + + /** Creates an Object for the given clsId. + If the ClassId isn't known (i.e. unregistered) then 0 is returned. + */ + Object* makeObject(const String strClsId); + + /** Destroys the given Object. */ void destroyObject(Object*); + + /** @todo Replace with "tick" message? */ void tick(); + /** Register an Object class. + Optionally, parameters can be specified that are stored with the class registration information + and can be accessed during creation of class instances. + @note These meta classes do not necessarily have to map to C++ classes. That is, it's possible + to register one and the same C++ class under different names (optionally,with different options). + This may be especially be useful in situations where backward compatiblity with data files using + string identifiers has to be maintained and C++ classes have been replaced with different ones. + */ template<typename T> - inline RegistrationResult registerClass(const std::string& name, const StringMap& options = MakeStringMap() ) + inline RegistrationResult registerClass(const String& name, const StringMap& options = MakeStringMap() ) { RegistrationResult ret = objMgr_.registerClass(name,&T::create,&T::destroy); if (ret.first == object::RC_OK) @@ -62,32 +86,32 @@ @see msg::makeListener @see broadcastMessage */ - void postMessage(msg::detail::message_base*, const msg::Source source = msg::kNoSource); + void postMessage(ObjectMessage*, const MessageSource source = kNoSource); /** Post a global message which is broadcasted to every object! @see msg::makeMessage @see msg::makeListener */ - void broadcastMessage(msg::detail::message_base*, const msg::Source source = msg::kNoSource); + void broadcastMessage(ObjectMessage*, const MessageSource source = kNoSource); /** Post message to a specific object. @see msg::makeMessage @see msg::makeListener */ - void postMessage(Object*, msg::detail::message_base*, const msg::Source source = msg::kNoSource); + void postMessage(Object*, ObjectMessage*, const MessageSource source = kNoSource); - /** Post message to a specific object. + /** Post message to a specific object identified by its ObjectId. @see msg::makeMessage @see msg::makeListener */ - void postMessage(ObjectId, msg::detail::message_base*, const msg::Source source = msg::kNoSource); + void postMessage(ObjectId, ObjectMessage*, const MessageSource source = kNoSource); /** Post message to objects in a STL(-like) container with object pointers. @see msg::makeMessage @see msg::makeListener */ template<typename T_container> - void postMessage(const T_container& objCtr, msg::detail::message_base* msg, const msg::Source source = msg::kNoSource) + void postMessage(const T_container& objCtr, ObjectMessage* msg, const MessageSource source = kNoSource) { ConstVectorIterator<T_container> it(objCtr); while (it.hasMoreElements()) @@ -106,7 +130,7 @@ typedef object::ObjectManager<Object> obj_mgr_type; obj_mgr_type objMgr_; - typedef AssocVector<std::string,StringMap> class_option_map; + typedef AssocVector<String,StringMap> class_option_map; class_option_map objClsOptions_; }; Modified: trunk/yake/yake/ent/object_mgr_listener.h =================================================================== --- trunk/yake/yake/ent/object_mgr_listener.h 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/yake/ent/object_mgr_listener.h 2006-09-10 20:48:56 UTC (rev 1455) @@ -33,6 +33,12 @@ namespace yake { namespace ent { + /** Listener base class for reacting on certain important object events. + Users of this class can choose to overwrite certain callback methods. + @note The entLua plugin uses these events to manage Lua scripting + machines for objects. + @see ObjectManager + */ struct YAKE_ENT_API ObjectManagerListener { virtual ~ObjectManagerListener() {} Modified: trunk/yake/yake/ent/prerequisites.h =================================================================== --- trunk/yake/yake/ent/prerequisites.h 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/yake/ent/prerequisites.h 2006-09-10 20:48:56 UTC (rev 1455) @@ -42,7 +42,12 @@ namespace yake { namespace ent { - typedef fsm::machine<std::string,std::string> object_fsm; + // Finite State Machine specialization + + typedef fsm::machine<String,String> object_fsm; + + // ObjectId and ClassId management + typedef object::ObjectId<object::default_objectid_traits> ObjectId; typedef ObjectId::ClassId ClassId; @@ -55,4 +60,39 @@ } // namespace ent } // namespace yake +// Specializations for messaging + +#include <yake/msg/yakeMessage.h> + +MSG_NAMESPACE_BEGIN +template<> +struct traits<::yake::ent::ObjectId,::yake::ent::ObjectId> +{ + typedef ::yake::ent::ObjectId Source; + typedef ::yake::ent::ObjectId Target; + + YAKE_ENT_API static const Source kNoSource; + static const Source kAnySource; + + static const Target kNoTarget; + static const Target kBroadcastTarget; + static const Target kAnyTarget; +}; +MSG_NAMESPACE_END + +namespace yake { +namespace ent { + + // Pull in types + + typedef msg::traits<ObjectId,ObjectId> MessageTraits; + typedef msg::detail::message_base<ObjectId,ObjectId> ObjectMessage; + typedef MessageTraits::Source MessageSource; + typedef MessageTraits::Target MessageTarget; + + static const MessageSource kNoSource = MessageTraits::kNoSource; + +} // namespace ent +} // namespace yake + #endif Modified: trunk/yake/yake/ent/vm_holder.h =================================================================== --- trunk/yake/yake/ent/vm_holder.h 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/yake/ent/vm_holder.h 2006-09-10 20:48:56 UTC (rev 1455) @@ -37,27 +37,32 @@ } namespace ent { + /** Container for scripting machines with optional tags for identification. + @note Tags have to be unique within a single VMHolder instance. + @note This class is used in Entity, for example, to manage scripting machines. + @note This class is not intended to be derived from! Therefore it doesn't have a virtual destructor! + */ struct YAKE_ENT_API VMHolder { VMHolder() {} - virtual ~VMHolder(); + ~VMHolder(); // operations - /** Warning: Currently ownership is not transferred! */ - bool attachVM(scripting::IVM*,const std::string& tag); - scripting::IVM* detachVM(const std::string& tag); - scripting::IVM* getVM(const std::string& tag) const; + /** @note Currently ownership is not transferred! */ + bool attachVM(scripting::IVM*,const String& tag); + scripting::IVM* detachVM(const String& tag); + scripting::IVM* getVM(const String& tag) const; // signals - typedef SignalX<void(const std::string&,scripting::IVM*)> VmAttachedSignal; + typedef SignalX<void(const String&,scripting::IVM*)> VmAttachedSignal; SignalConnection subsribeToVmAttached(const VmAttachedSignal::slot_type&); - typedef SignalX<void(const std::string&,scripting::IVM*)> VmDetachedSignal; + typedef SignalX<void(const String&,scripting::IVM*)> VmDetachedSignal; SignalConnection subscribeToVmDetached(const VmDetachedSignal::slot_type&); private: VmAttachedSignal sigAttached_; VmDetachedSignal sigDetached_; - typedef std::map<std::string,scripting::IVM*> VmMap; + typedef std::map<String,scripting::IVM*> VmMap; VmMap vms_; }; Modified: trunk/yake/yake/model/model.h =================================================================== --- trunk/yake/yake/model/model.h 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/yake/model/model.h 2006-09-10 20:48:56 UTC (rev 1455) @@ -131,6 +131,8 @@ ModelLinkContainer links_; ModelComponentContainer components_; }; + typedef SharedPtr<Model> ModelPtr; + struct ModelTemplate; struct YAKE_MODEL_API ModelManager { @@ -140,10 +142,10 @@ bool loadTemplatesFromDotModel(const String& fn); - Model* createModelFromTemplate(const String& modelName, const String& tplName); + ModelPtr createModelFromTemplate(const String& modelName, const String& tplName); - Model* createModel(const String& modelName, const ModelComponentDescList&); - Model* createModel(const String& modelName, const String& def); + ModelPtr createModel(const String& modelName, const ModelComponentDescList&); + ModelPtr createModel(const String& modelName, const String& def); void clear(); @@ -181,7 +183,7 @@ ComponentCreatorManager creatorMgr_; ModelCreationContext modelCtx_; - typedef AssocVector<String,SharedPtr<Model> > ModelList; + typedef AssocVector<String,ModelPtr> ModelList; ModelList models_; ModelCreatedSignal sigModelCreatedSignal_; Modified: trunk/yake/yake/model/model_component.h =================================================================== --- trunk/yake/yake/model/model_component.h 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/yake/model/model_component.h 2006-09-10 20:48:56 UTC (rev 1455) @@ -150,7 +150,7 @@ typedef ModelComponent::DescList ModelComponentDescList; typedef SharedPtr<ModelComponent> ModelComponentSharedPtr; typedef std::deque<ModelComponentSharedPtr> ModelComponentList; - typedef std::string ComponentTag; + typedef String ComponentTag; struct YAKE_MODEL_API ModelComponentContainer { ModelComponentContainer(); Modified: trunk/yake/yake/msg/listener.h =================================================================== --- trunk/yake/yake/msg/listener.h 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/yake/msg/listener.h 2006-09-10 20:48:56 UTC (rev 1455) @@ -33,17 +33,20 @@ namespace detail { /** Internal base class for listeners providing the basic interface and functionality. */ + template<typename source_type,typename target_type> struct listener_base { private: listener_base(const listener_base&); listener_base& operator = (const listener_base&); public: - listener_base(const std::string& msgTypeName) : msgTypeName_(msgTypeName) {} + typedef message_base<source_type,target_type> message_type; + + listener_base(const String& msgTypeName) : msgTypeName_(msgTypeName) {} virtual ~listener_base() {} - void execute(const message_base& msg) + void execute(const message_type& msg) { doExecute(msg); } - const std::string& msgTypeName() const + const String& msgTypeName() const { return msgTypeName_; } void destroy() { @@ -51,9 +54,9 @@ delete this; } protected: - virtual void doExecute(const message_base&) = 0; + virtual void doExecute(const message_type&) = 0; private: - std::string msgTypeName_; + String msgTypeName_; }; } // namespace detail /* @@ -67,22 +70,24 @@ /** Represents a listener for a specific type; \ the listener object encapsulates a user provided message handling function object. */ - template<typename MsgType> - struct listener : public detail::listener_base + template<typename source_type,typename target_type,typename MsgType> + struct listener : public detail::listener_base<source_type,target_type> { private: listener(const listener&); listener& operator=(const listener&); public: typedef boost::function<void(const MsgType&)> HandlerFn; + typedef detail::message_base<source_type,target_type> message_type; /** Construct a listener object with a handler function. The handler function has to be valid (i.e. non-empty). */ - listener(const HandlerFn& fn) : detail::listener_base(typeid(MsgType).name()),fn_(fn) + listener(const HandlerFn& fn) : + detail::listener_base<source_type,target_type>(get_type_name<MsgType>()),fn_(fn) {} protected: /** Executes the message handler function object and provides the message 'msgbase' as a parameter. */ - virtual void doExecute(const detail::message_base& msgbase) + virtual void doExecute(const message_type& msgbase) { try { fn_( static_cast<const MsgType&>(boost::any_cast<MsgType>(msgbase.value())) ); @@ -101,9 +106,9 @@ }; /** Helper function to easily create listener objects for a given message type. */ - template<typename T> - listener<T>* makeListener(const boost::function<void(const T&)>& fn) - { return new listener<T>(fn); } + template<typename source_type,typename target_type,typename T> + listener<source_type,target_type,T>* makeListener(const boost::function<void(const T&)>& fn) + { return new listener<source_type,target_type,T>(fn); } MSG_NAMESPACE_END Modified: trunk/yake/yake/msg/listener_mgr.h =================================================================== --- trunk/yake/yake/msg/listener_mgr.h 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/yake/msg/listener_mgr.h 2006-09-10 20:48:56 UTC (rev 1455) @@ -31,22 +31,20 @@ MSG_NAMESPACE_BEGIN - namespace detail { - struct msg_listener_mgr; - } // namespace detail - /** Represents the connection between a listener and the router and can be disconnected via a member method. @see ScopedListenerConnection @todo Handle disconnect()'s when having more than one copy of the connection object. @Remarks STILL VERY MUCH EXPERIMENTAL! NOT SUPPORTED BY ALL ROUTERS! CAN EXPLODE WHEN USED WRONGLY! */ + template<typename source_type,typename target_type,typename msg_listener_mgr_type> struct ListenerConnection { private: ListenerConnection(); public: - ListenerConnection(detail::msg_listener_mgr* mgr, - detail::listener_base* listener, + typedef detail::listener_base<source_type,target_type> listener_base_type; + ListenerConnection( msg_listener_mgr_type* mgr, + listener_base_type* listener, source_type source, target_type target) : mgr_(mgr), @@ -74,13 +72,18 @@ } /** Disconnects the listener from the message router. */ - void disconnect(); + void disconnect() + { + if (mgr_ && listener_) + mgr_->remove( *this ); + listener_ = 0; + } bool empty() const { return (listener_ != 0); } - detail::listener_base* listener() const + listener_base_type* listener() const { return listener_; } @@ -93,39 +96,47 @@ return target_; } private: - detail::msg_listener_mgr* mgr_; - detail::listener_base* listener_; + msg_listener_mgr_type* mgr_; + listener_base_type* listener_; source_type source_; target_type target_; }; namespace detail { - typedef std::deque<boost::shared_ptr<detail::listener_base> > listener_list; - typedef std::map<std::string,listener_list> listener_map; - /** Internal base class providing listener management and a hook for derived routers/processors. */ + template<typename source_type,typename target_type> struct msg_listener_mgr { + typedef ListenerConnection<source_type,target_type,msg_listener_mgr<source_type,target_type> > connection_type; + typedef detail::listener_base<source_type,target_type> listener_base_type; + typedef detail::message_base<source_type,target_type> message_base_type; + protected: + typedef std::deque<boost::shared_ptr<listener_base_type> > listener_list; + typedef std::map<std::string,listener_list> listener_map; + public: + msg_listener_mgr() : isProcessing_(false) {} - void remove(const ListenerConnection& conn) + void remove(const connection_type& conn) { if (isProcessing()) connsToRemove_.push_back(conn); _doRemove(conn); } - ListenerConnection add(detail::listener_base* l, source_type source = kNoSource, target_type tgt = kNoTarget) + connection_type add(listener_base_type* l, + source_type source = traits<source_type,target_type>::kNoSource, + target_type tgt = traits<source_type,target_type>::kNoTarget) { YAKE_ASSERT(l); if (!l) - return ListenerConnection(this,0,source,tgt); + return connection_type(this,0,source,tgt); listener_map& listeners = sources_[source][tgt]; - listeners[l->msgTypeName()].push_back( boost::shared_ptr<detail::listener_base>(l) ); - return ListenerConnection(this,l,source,tgt); + listeners[l->msgTypeName()].push_back( boost::shared_ptr<listener_base_type>(l) ); + return connection_type(this,l,source,tgt); } - void process(detail::message_base* msg) + void process(message_base_type* msg) { YAKE_ASSERT( msg ); @@ -135,7 +146,7 @@ YAKE_ASSERT( target != kAnyTarget ); // should be kBroadcastTarget. // find 'kAnySource' source - source_map::const_iterator itSource = sources_.find(kAnySource); + source_map::const_iterator itSource = sources_.find(traits<source_type,target_type>::kAnySource); if (itSource != sources_.end()) { // find listeners for specified target @@ -144,7 +155,7 @@ _processListeners( msg, itTarget->second ); // find listeners for special 'kAnyTarget' - itTarget = itSource->second.find(kAnyTarget); + itTarget = itSource->second.find(traits<source_type,target_type>::kAnyTarget); if (itTarget != itSource->second.end()) _processListeners( msg, itTarget->second ); } @@ -157,18 +168,18 @@ const target_map& targets = itSource->second; // process listeners that have subscribed to all messages of this source - target_map::const_iterator itAnyTargetListeners = targets.find(kAnyTarget); + target_map::const_iterator itAnyTargetListeners = targets.find(traits<source_type,target_type>::kAnyTarget); if (itAnyTargetListeners != targets.end()) _processListeners( msg, itAnyTargetListeners->second ); - // broadcast or targetted message? - if (target == kBroadcastTarget) + // broadcast or targeted message? + if (target == traits<source_type,target_type>::kBroadcastTarget) { // broadcasting - iterate over all targets: target_map::const_iterator itEnd = targets.end(); for (target_map::const_iterator itTarget = targets.begin(); itTarget != itEnd; ++itTarget) { - if (itTarget->first == kAnyTarget) // We already have processed them above. + if (itTarget->first == traits<source_type,target_type>::kAnyTarget) // We already have processed them above. continue; _processListeners( msg, itTarget->second ); } @@ -197,11 +208,11 @@ _doRemove( it.getNext() ); connsToRemove_.clear(); } - void _doRemove(const ListenerConnection& conn) + void _doRemove(const connection_type& conn) { _doRemove(conn.listener(),conn.source(),conn.target()); } - void _doRemove(detail::listener_base* l, source_type source = kNoSource, target_type tgt = kNoTarget) + void _doRemove(listener_base_type* l, source_type source = kNoSource, target_type tgt = kNoTarget) { source_map::iterator itSource = sources_.find( source ); if (itSource == sources_.end()) @@ -215,7 +226,7 @@ if (itL != listeners.end()) listeners.erase( itL ); } - void _processListeners(detail::message_base* msg, const listener_map& listeners) + void _processListeners(message_base_type* msg, const listener_map& listeners) { // find message type listener_map::const_iterator itMsgType = listeners.find(msg->msgTypeName()); @@ -238,30 +249,22 @@ return isProcessing_; } private: - //typedef MSG_NAMESPACE::detail::listener_list listener_list; - //typedef MSG_NAMESPACE::detail::listener_map listener_map; typedef AssocVector<target_type,listener_map> target_map; typedef AssocVector<source_type,target_map> source_map; source_map sources_; //listener_map listeners_; bool isProcessing_; - typedef std::deque<ListenerConnection> conn_list; + typedef std::deque<connection_type> conn_list; conn_list connsToRemove_; }; } - inline void ListenerConnection::disconnect() - { - if (mgr_ && listener_) - mgr_->remove( *this ); - listener_ = 0; - } - /** Wraps a ListenerConnection in RAII fashion. @see ListenerConnection @Remarks STILL VERY MUCH EXPERIMENTAL! NOT SUPPORTED BY ALL ROUTERS! CAN EXPLODE WHEN USED WRONGLY! */ + template<typename source_type,typename target_type> struct ScopedListenerConnection { private: @@ -269,9 +272,11 @@ ScopedListenerConnection(const ScopedListenerConnection&); ScopedListenerConnection& operator=(const ScopedListenerConnection&); public: + typedef detail::msg_listener_mgr<source_type,target_type> msg_listener_mgr_type; + typedef ListenerConnection<source_type,target_type,msg_listener_mgr_type> connection_type; /** Constructs a scoped listener connection object from a listener connection. */ - ScopedListenerConnection(const ListenerConnection& conn) : conn_(conn) + ScopedListenerConnection(const connection_type& conn) : conn_(conn) {} /** Destroys the scoped listener and disconnects the listener connection @@ -282,7 +287,7 @@ conn_.disconnect(); } private: - ListenerConnection conn_; + connection_type conn_; }; MSG_NAMESPACE_END Modified: trunk/yake/yake/msg/message.h =================================================================== --- trunk/yake/yake/msg/message.h 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/yake/msg/message.h 2006-09-10 20:48:56 UTC (rev 1455) @@ -31,40 +31,29 @@ MSG_NAMESPACE_BEGIN - /** Represents the (optionally to be used) source of a message. - @todo Make this a trait. - */ - typedef const void* source_type; - - /** @copydoc source_type - @Remarks This is an alias for good looking client code. - */ - typedef source_type Source; - - const Source kNoSource = Source(0); - const Source kAnySource = Source(-2); - - typedef const void* target_type; - typedef target_type Target; - const Target kNoTarget = Target(0); - const Target kBroadcastTarget = Target(-1); - const Target kAnyTarget = Target(-2); - namespace detail { /** Internal base class for messages providing the very basic interface. */ + template<typename source_type,typename target_type> struct message_base { private: message_base(const message_base&); message_base& operator=(const message_base&); public: + /** Constructs a message for the given value type. + @note msgTypeName can be used to override the type name. Use with care! + */ template<typename T> - message_base(const T& value, source_type src = kNoSource, target_type tgt = kNoTarget) : - value_(value), msgTypeName_(typeid(T).name()), src_(src), tgt_(tgt) + message_base( const T& value, + source_type src = traits<source_type,target_type>::kNoSource, + target_type tgt = traits<source_type,target_type>::kNoTarget, + const std::string& msgTypeName = std::string()) : + value_(value), msgTypeName_(msgTypeName.empty() ? get_type_name<T>() : msgTypeName), src_(src), tgt_(tgt) {} const boost::any& value() const { return value_; } +<<<<<<< .mine /** Tries to cast the embedded message value to the specified target type. @@ -84,10 +73,35 @@ return false; } } + /** Returns the type name of the contained value. */ +======= + + /** Tries to cast the embedded message value to the specified + target type. + Returns true if cast and assignment were successful, + otherwise false. The latter usually indicates a type mismatch + between embedded value type and specified target type. + */ + template<typename TargetT> + bool valueAs(TargetT& out) + { + try { + out = boost::any_cast<TargetT>( out ); + return true; + } + catch (boost::bad_any_cast&) + { + return false; + } + } +>>>>>>> .r1454 const std::string& msgTypeName() const { return msgTypeName_; } + + /** Returns the source of the message. */ source_type source() const { return src_; } + /** Returns the target of the message. */ target_type target() const { return tgt_; } protected: @@ -98,34 +112,42 @@ target_type tgt_; }; } // namespace detail - /** Represents a concrete message for the type T. - Provides value assignment. + /** Represents a concrete message for a type T. + Source and target id types have to specified. */ - template<typename T> - struct message : public detail::message_base + template<typename source_type,typename target_type,typename T> + struct message : public detail::message_base<source_type,target_type> { - /** Construct a message with value and optional source (0 by default). - + /** Construct a message with value and optional source (kNoSource by default). + Optionally overrides the automatically determined type name! */ - message(const T& v, source_type src = kNoSource, target_type tgt = kNoTarget) : - detail::message_base(v,src,tgt) + message(const T& v, + source_type src = traits<source_type,target_type>::kNoSource, + target_type tgt = traits<source_type,target_type>::kNoTarget, + const std::string& msgTypeName = std::string()) : + detail::message_base<source_type,target_type>(v,src,tgt,msgTypeName) {} /** Construct a message with default value for type T and source 0. */ - message() : detail::message_base(T()) + message() : detail::message_base<source_type,target_type>(T()) {} - /** Set the value to v. */ + /** Sets the message value to v. + */ void setValue(const T& v) { value_ = v; } //@todo add type mismatch tests!? }; - /** As the name implies this allocator is used by default for message creation and destruction. */ + /** This allocator is used by default for message creation and destruction. + @note This allocator uses new and delete. + */ struct DefaultMessageAllocator { DefaultMessageAllocator& instance(); - template<typename T> - static message<T>* create(const T& v, source_type src = kNoSource, target_type tgt = kNoTarget) + template<typename source_type,typename target_type,typename T> + static message<T,source_type,target_type>* create(const T& v, + source_type src = traits<source_type,target_type>::kNoSource, + target_type tgt = traits<source_type,target_type>::kNoTarget) { - return new message<T>(v,src,tgt); + return new message<T,source_type,target_type>(v,src,tgt); } template<typename MsgType> static void destroy(const MsgType* msg) @@ -135,15 +157,17 @@ } }; - /** Helper function to easily create messages. + /** Helper function to create messages using the default allocator/deallocator. */ - template<typename T> - message<T>* makeMessage(const T& v, source_type src = kNoSource, target_type tgt = kNoTarget) + template<typename source_type,typename target_type,typename T> + message<source_type,target_type,T>* makeMessage(const T& v, + source_type src = traits<source_type,target_type>::kNoSource, + target_type tgt = traits<source_type,target_type>::kNoTarget) { - return DefaultMessageAllocator::create<T>(v,src,tgt); + return DefaultMessageAllocator::create<T,source_type,target_type>(v,src,tgt); } - /** Destroys the message. */ + /** Destroys the message using the default allocator/deallocator. */ template<typename T> void destroyMessage(T* msg) { Modified: trunk/yake/yake/msg/prerequisites.h =================================================================== --- trunk/yake/yake/msg/prerequisites.h 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/yake/msg/prerequisites.h 2006-09-10 20:48:56 UTC (rev 1455) @@ -48,4 +48,42 @@ #include <boost/pool/object_pool.hpp> */ +MSG_NAMESPACE_BEGIN + +template<typename source_type,typename target_type> +struct traits; + +/** Specialization for source and target id types being 'int'. */ +template<> +struct traits<int,int> +{ + typedef int Source; + typedef int Target; + + static const Source kNoSource = Source(0); + static const Source kAnySource = Source(-2); + + static const Target kNoTarget = Target(0); + static const Target kBroadcastTarget = Target(-1); + static const Target kAnyTarget = Target(-2); +}; + +/** Generic function to return the type name for any given type T. + @note It's possible to override the returned type name by specializing this function for certain types. + For example, it may be beneficial to override it for std::string as the type name is usually hard to read. + Of course, this is a feature that has to be used with care! +*/ +template<typename T> +inline std::string get_type_name() +{ + return typeid(T).name(); +} +template<> +inline std::string get_type_name<String>() +{ + return "String"; +} + +MSG_NAMESPACE_END + #endif Modified: trunk/yake/yake/msg/processors.h =================================================================== --- trunk/yake/yake/msg/processors.h 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/yake/msg/processors.h 2006-09-10 20:48:56 UTC (rev 1455) @@ -32,12 +32,15 @@ MSG_NAMESPACE_BEGIN /** Processes messages immediately when they are possed. */ - struct ImmediateProcessor : public detail::msg_listener_mgr + template<typename source_type,typename target_type> + struct ImmediateProcessor : public detail::msg_listener_mgr<source_type,target_type> { - typedef detail::listener_map listener_map; - typedef detail::listener_list listener_list; + typedef detail::message_base<source_type,target_type> message_base_type; + typedef detail::msg_listener_mgr<source_type,target_type> msg_listener_mgr_type; + typedef msg_listener_mgr_type::listener_map listener_map; + typedef msg_listener_mgr_type::listener_list listener_list; - void onPost(detail::message_base* msg) + void onPost(message_base_type* msg) { YAKE_ASSERT(msg); YAKE_ASSERT( !isProcessing() ); @@ -51,14 +54,17 @@ @see ImmediateProcessor @see DoubleQueuedProcessor */ - struct SingleQueuedProcessor : public detail::msg_listener_mgr + template<typename source_type,typename target_type> + struct SingleQueuedProcessor : public detail::msg_listener_mgr<source_type,target_type> { - typedef detail::listener_map listener_map; - typedef detail::listener_list listener_list; + typedef detail::message_base<source_type,target_type> message_base_type; + typedef detail::msg_listener_mgr<source_type,target_type> msg_listener_mgr_type; + typedef msg_listener_mgr_type::listener_map listener_map; + typedef msg_listener_mgr_type::listener_list listener_list; SingleQueuedProcessor() {} - void onPost(detail::message_base* msg) + void onPost(message_base_type* msg) { YAKE_ASSERT(!isProcessing()); YAKE_ASSERT(msg); @@ -84,7 +90,7 @@ setProcessing(true); for (msg_q::const_iterator it = q_.begin(); it != q_.end(); ++it) { - detail::message_base* msg = *it; + message_base_type* msg = *it; YAKE_ASSERT( msg ); this->process(msg); } @@ -93,7 +99,7 @@ #endif } private: - typedef std::deque<detail::message_base*> msg_q; + typedef std::deque<message_base_type*> msg_q; msg_q q_; bool isProcessing_; }; @@ -102,10 +108,13 @@ @see ImmediateProcessor @see SingleQueuedProcessor */ - struct DoubleQueuedProcessor : public detail::msg_listener_mgr + template<typename source_type,typename target_type> + struct DoubleQueuedProcessor : public detail::msg_listener_mgr<source_type,target_type> { - typedef detail::listener_map listener_map; - typedef detail::listener_list listener_list; + typedef detail::message_base<source_type,target_type> message_base_type; + typedef detail::msg_listener_mgr<source_type,target_type> msg_listener_mgr_type; + typedef msg_listener_mgr_type::listener_map listener_map; + typedef msg_listener_mgr_type::listener_list listener_list; DoubleQueuedProcessor() : q_(&q1_) {} void onPost(detail::message_base* msg) @@ -121,7 +130,7 @@ while (!procQ->empty()) { setProcessing(true); - detail::message_base* msg = procQ->front(); + message_base_type* msg = procQ->front(); procQ->pop_front(); YAKE_ASSERT( msg ); this->process(msg); @@ -129,7 +138,7 @@ } } private: - typedef std::deque<detail::message_base*> msg_q; + typedef std::deque<message_base_type*> msg_q; msg_q q1_,q2_; msg_q* q_; bool isProcessing_; Modified: trunk/yake/yake/msg/router.h =================================================================== --- trunk/yake/yake/msg/router.h 2006-09-09 18:21:04 UTC (rev 1454) +++ trunk/yake/yake/msg/router.h 2006-09-10 20:48:56 UTC (rev 1455) @@ -37,7 +37,7 @@ @code using namespace msg; - router< ImmediateProcessor > myrouter; + router< int, int, ImmediateProcessor<int> > myrouter; myrouter.post(makeMessage(1)); // int(1) is the message myrouter.postMessage(1); // the same - but using an alternative... [truncated message content] |
From: <psy...@us...> - 2006-09-12 21:23:11
|
Revision: 1459 http://svn.sourceforge.net/yake/?rev=1459&view=rev Author: psyclonist Date: 2006-09-12 14:22:45 -0700 (Tue, 12 Sep 2006) Log Message: ----------- - ent: Implemented basic object messaging for targetted and broadcasted messages. - msg: Fixed a number of issues. Modified Paths: -------------- trunk/yake/src/yake/ent/object.cpp trunk/yake/src/yake/ent/object_mgr.cpp trunk/yake/src/yake/samples/ent/sampleEntFsm/demo.cpp trunk/yake/yake/ent/object.h trunk/yake/yake/ent/object_mgr.h trunk/yake/yake/ent/prerequisites.h trunk/yake/yake/msg/listener_mgr.h trunk/yake/yake/msg/message.h trunk/yake/yake/msg/processors.h trunk/yake/yake/msg/router.h Modified: trunk/yake/src/yake/ent/object.cpp =================================================================== --- trunk/yake/src/yake/ent/object.cpp 2006-09-12 17:34:08 UTC (rev 1458) +++ trunk/yake/src/yake/ent/object.cpp 2006-09-12 21:22:45 UTC (rev 1459) @@ -34,20 +34,58 @@ void Object::setId(const ObjectId& id) { + YAKE_ASSERT( id != MessageTraits::kNoSource )(MessageTraits::kNoSource)(id); + YAKE_ASSERT( id != MessageTraits::kAnySource )(MessageTraits::kAnySource)(id); + YAKE_ASSERT( id != MessageTraits::kNoTarget )(MessageTraits::kNoTarget)(id); + YAKE_ASSERT( id != MessageTraits::kBroadcastTarget )(MessageTraits::kBroadcastTarget)(id); + YAKE_ASSERT( id != MessageTraits::kAnyTarget )(MessageTraits::kAnyTarget)(id); id_ = id; } const ObjectId& Object::getId() const { return id_; } + void Object::processMessage(const int& i) + { + std::cout << "Object::processMessage(" << i << ")\n"; + } + void Object::registerMessageListeners(detail::message_router_type& msgRouter) + { + YAKE_ASSERT( id_ != ObjectId::kNull ); + // let object listen to messages of type 'int' targetted to itself directly + listenerConnections_.push_back( + msgRouter.addListener( + msg::makeListener<ObjectId,ObjectId,int>(Bind1(&Object::processMessage,this)), + MessageTraits::kAnySource, + id_ ) + ); + + // let object listen to broadcasted messages of type 'int' + listenerConnections_.push_back( + msgRouter.addListener( + msg::makeListener<ObjectId,ObjectId,int>(Bind1(&Object::processMessage,this)), + MessageTraits::kAnySource, + MessageTraits::kBroadcastTarget ) + ); + } + void Object::destroy() + { + for (listenerconnetion_list::iterator it = listenerConnections_.begin(), itend = listenerConnections_.end(); + it != itend; ++it) + { + it->disconnect(); + } + listenerConnections_.clear(); + } + } } MSG_NAMESPACE_BEGIN -const traits<ent::ObjectId,ent::ObjectId>::Source traits<ent::ObjectId,ent::ObjectId>::kNoSource = ent::ObjectId(-1,0); -const traits<ent::ObjectId,ent::ObjectId>::Source traits<ent::ObjectId,ent::ObjectId>::kAnySource = ent::ObjectId(-1,1); -const traits<ent::ObjectId,ent::ObjectId>::Source traits<ent::ObjectId,ent::ObjectId>::kNoTarget = ent::ObjectId(-1,2); -const traits<ent::ObjectId,ent::ObjectId>::Source traits<ent::ObjectId,ent::ObjectId>::kBroadcastTarget = ent::ObjectId(-1,3); -const traits<ent::ObjectId,ent::ObjectId>::Source traits<ent::ObjectId,ent::ObjectId>::kAnyTarget = ent::ObjectId(-1,4); +const traits<ent::ObjectId,ent::ObjectId>::Source traits<ent::ObjectId,ent::ObjectId>::kNoSource = ent::ObjectId(ent::ObjectId::kNull-1,0); +const traits<ent::ObjectId,ent::ObjectId>::Source traits<ent::ObjectId,ent::ObjectId>::kAnySource = ent::ObjectId(ent::ObjectId::kNull-1,1); +const traits<ent::ObjectId,ent::ObjectId>::Target traits<ent::ObjectId,ent::ObjectId>::kNoTarget = ent::ObjectId(ent::ObjectId::kNull-1,2); +const traits<ent::ObjectId,ent::ObjectId>::Target traits<ent::ObjectId,ent::ObjectId>::kBroadcastTarget = ent::ObjectId(ent::ObjectId::kNull-1,3); +const traits<ent::ObjectId,ent::ObjectId>::Target traits<ent::ObjectId,ent::ObjectId>::kAnyTarget = ent::ObjectId(ent::ObjectId::kNull-1,4); MSG_NAMESPACE_END Modified: trunk/yake/src/yake/ent/object_mgr.cpp =================================================================== --- trunk/yake/src/yake/ent/object_mgr.cpp 2006-09-12 17:34:08 UTC (rev 1458) +++ trunk/yake/src/yake/ent/object_mgr.cpp 2006-09-12 21:22:45 UTC (rev 1459) @@ -43,6 +43,8 @@ YAKE_ASSERT( obj )(clsId); objs_.push_back( obj ); + obj->registerMessageListeners(msgRouter_); + listeners_onObjectCreated(obj); obj->init(); @@ -56,8 +58,9 @@ YAKE_ASSERT( obj ); listeners_onDestroyObject( obj ); - //obj->shutdown(); + obj->destroy(); + object_ptr_list::iterator it = std::find(objs_.begin(),objs_.end(),obj); if (it != objs_.end()) objs_.erase( it ); @@ -66,6 +69,7 @@ } void ObjectManager::tick() { + msgRouter_.processMessages(); yake::ConstVectorIterator<object_ptr_list> it(objs_); while (it.hasMoreElements()) it.getNext()->tick(); @@ -97,6 +101,19 @@ while (it.hasMoreElements()) it.getNext().first->onDestroyObject(obj); } + void ObjectManager::postMessage(Object* obj, ObjectMessageBase* msg, const MessageSource source) + { + YAKE_ASSERT( obj ); + YAKE_ASSERT( msg ); + msg->setTarget( obj->getId() ); + msgRouter_.post( msg ); + } + void ObjectManager::broadcastMessage(ObjectMessageBase* msg, const MessageSource source /* = MessageTraits::kNoSource */) + { + YAKE_ASSERT( msg ); + msg->setTarget( MessageTraits::kBroadcastTarget ); + msgRouter_.post( msg ); + } } } Modified: trunk/yake/src/yake/samples/ent/sampleEntFsm/demo.cpp =================================================================== --- trunk/yake/src/yake/samples/ent/sampleEntFsm/demo.cpp 2006-09-12 17:34:08 UTC (rev 1458) +++ trunk/yake/src/yake/samples/ent/sampleEntFsm/demo.cpp 2006-09-12 21:22:45 UTC (rev 1459) @@ -210,10 +210,15 @@ YAKE_ASSERT( e ); // 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() + objMgr.tick(); // triggers o->tick(), also triggers message handling! objMgr.tick(); e->processFsmEvent("die"); Modified: trunk/yake/yake/ent/object.h =================================================================== --- trunk/yake/yake/ent/object.h 2006-09-12 17:34:08 UTC (rev 1458) +++ trunk/yake/yake/ent/object.h 2006-09-12 21:22:45 UTC (rev 1459) @@ -78,11 +78,18 @@ listeners_tick(*this); onTick(); } + void destroy(); + + void processMessage(const int&); + + void registerMessageListeners(detail::message_router_type& msgRouter); protected: virtual void onInit() {} virtual void onTick() {} private: ObjectId id_; + typedef std::deque<detail::ListenerConnection> listenerconnetion_list; + listenerconnetion_list listenerConnections_; }; } // namespace ent Modified: trunk/yake/yake/ent/object_mgr.h =================================================================== --- trunk/yake/yake/ent/object_mgr.h 2006-09-12 17:34:08 UTC (rev 1458) +++ trunk/yake/yake/ent/object_mgr.h 2006-09-12 21:22:45 UTC (rev 1459) @@ -81,37 +81,50 @@ return ret; } + template<typename MessageValueType> + void makeAndPostMessage(Object* obj, const MessageValueType& value, const MessageSource source = MessageTraits::kNoSource) + { + YAKE_ASSERT( obj ); + //this->postMessage( obj, msg::makeMessage<ObjectId,ObjectId,MessageValueType>(value,source,obj->getId()), source ); + this->postMessage( obj, new msg::message<ObjectId,ObjectId,MessageValueType>(value,source,obj->getId()) ); + } + template<typename MessageValueType> + void makeAndBroadcastMessage(const MessageValueType& value, const MessageSource source = MessageTraits::kNoSource) + { + this->broadcastMessage( new msg::message<ObjectId,ObjectId,MessageValueType>(value,source,MessageTraits::kBroadcastTarget) ); + } + /** Post a global message. This message is *not* broadcasted to every object! @see msg::makeMessage @see msg::makeListener @see broadcastMessage */ - void postMessage(ObjectMessage*, const MessageSource source = kNoSource); + void postMessage(ObjectMessageBase*, const MessageSource source = MessageTraits::kNoSource); /** Post a global message which is broadcasted to every object! @see msg::makeMessage @see msg::makeListener */ - void broadcastMessage(ObjectMessage*, const MessageSource source = kNoSource); + void broadcastMessage(ObjectMessageBase*, const MessageSource source = MessageTraits::kNoSource); /** Post message to a specific object. @see msg::makeMessage @see msg::makeListener */ - void postMessage(Object*, ObjectMessage*, const MessageSource source = kNoSource); + void postMessage(Object*, ObjectMessageBase*, const MessageSource source = MessageTraits::kNoSource); /** Post message to a specific object identified by its ObjectId. @see msg::makeMessage @see msg::makeListener */ - void postMessage(ObjectId, ObjectMessage*, const MessageSource source = kNoSource); + void postMessage(ObjectId, ObjectMessageBase*, const MessageSource source = MessageTraits::kNoSource); /** Post message to objects in a STL(-like) container with object pointers. @see msg::makeMessage @see msg::makeListener */ template<typename T_container> - void postMessage(const T_container& objCtr, ObjectMessage* msg, const MessageSource source = kNoSource) + void postMessage(const T_container& objCtr, ObjectMessageBase* msg, const MessageSource source = MessageTraits::kNoSource) { ConstVectorIterator<T_container> it(objCtr); while (it.hasMoreElements()) @@ -132,6 +145,8 @@ typedef AssocVector<String,StringMap> class_option_map; class_option_map objClsOptions_; + + detail::message_router_type msgRouter_; }; } // namespace ent Modified: trunk/yake/yake/ent/prerequisites.h =================================================================== --- trunk/yake/yake/ent/prerequisites.h 2006-09-12 17:34:08 UTC (rev 1458) +++ trunk/yake/yake/ent/prerequisites.h 2006-09-12 21:22:45 UTC (rev 1459) @@ -51,12 +51,6 @@ typedef object::ObjectId<object::default_objectid_traits> ObjectId; typedef ObjectId::ClassId ClassId; - struct ClsEntry - { - RttiClass* cls; - }; - typedef object::ClassAndObjectIdManager<ClsEntry> ClassAndObjectIdManager; - } // namespace ent } // namespace yake @@ -72,10 +66,10 @@ typedef ::yake::ent::ObjectId Target; YAKE_ENT_API static const Source kNoSource; - static const Source kAnySource; + YAKE_ENT_API static const Source kAnySource; static const Target kNoTarget; - static const Target kBroadcastTarget; + YAKE_ENT_API static const Target kBroadcastTarget; static const Target kAnyTarget; }; MSG_NAMESPACE_END @@ -86,12 +80,20 @@ // Pull in types typedef msg::traits<ObjectId,ObjectId> MessageTraits; - typedef msg::detail::message_base<ObjectId,ObjectId> ObjectMessage; + typedef msg::detail::message_base<ObjectId,ObjectId> ObjectMessageBase; typedef MessageTraits::Source MessageSource; typedef MessageTraits::Target MessageTarget; - static const MessageSource kNoSource = MessageTraits::kNoSource; + namespace detail { + typedef msg::DoubleQueuedProcessor<ObjectId,ObjectId> message_processor_type; + typedef msg::router<ObjectId,ObjectId,message_processor_type> message_router_type; + typedef msg::ListenerConnection<ObjectId,ObjectId,msg::detail::msg_listener_mgr<ObjectId,ObjectId> > ListenerConnection; + } + //static const MessageSource kNoSource = MessageTraits::kNoSource; + //static const MessageSource kAnySource = MessageTraits::kAnySource; + //static const MessageTarget kBroadcastTarget = MessageTraits::kBroadcastTarget; + } // namespace ent } // namespace yake Modified: trunk/yake/yake/msg/listener_mgr.h =================================================================== --- trunk/yake/yake/msg/listener_mgr.h 2006-09-12 17:34:08 UTC (rev 1458) +++ trunk/yake/yake/msg/listener_mgr.h 2006-09-12 21:22:45 UTC (rev 1459) @@ -39,10 +39,12 @@ template<typename source_type,typename target_type,typename msg_listener_mgr_type> struct ListenerConnection { - private: - ListenerConnection(); public: typedef detail::listener_base<source_type,target_type> listener_base_type; + ListenerConnection() : + mgr_(0), + listener_(0) + {} ListenerConnection( msg_listener_mgr_type* mgr, listener_base_type* listener, source_type source, @@ -115,6 +117,7 @@ protected: typedef std::deque<boost::shared_ptr<listener_base_type> > listener_list; typedef std::map<std::string,listener_list> listener_map; + typedef traits<source_type,target_type> traits_type; public: msg_listener_mgr() : isProcessing_(false) @@ -142,8 +145,8 @@ const source_type source = msg->source(); const target_type target = msg->target(); - YAKE_ASSERT( source != kAnySource ); // should be kNoSource if there's no source. - YAKE_ASSERT( target != kAnyTarget ); // should be kBroadcastTarget. + YAKE_ASSERT( source != traits_type::kAnySource ); // should be kNoSource if there's no source. + YAKE_ASSERT( target != traits_type::kAnyTarget ); // should be kBroadcastTarget. // find 'kAnySource' source source_map::const_iterator itSource = sources_.find(traits<source_type,target_type>::kAnySource); Modified: trunk/yake/yake/msg/message.h =================================================================== --- trunk/yake/yake/msg/message.h 2006-09-12 17:34:08 UTC (rev 1458) +++ trunk/yake/yake/msg/message.h 2006-09-12 21:22:45 UTC (rev 1459) @@ -82,6 +82,8 @@ /** Returns the target of the message. */ target_type target() const { return tgt_; } + void setTarget(const target_type tgt) + { tgt_ = tgt; } protected: boost::any value_; private: Modified: trunk/yake/yake/msg/processors.h =================================================================== --- trunk/yake/yake/msg/processors.h 2006-09-12 17:34:08 UTC (rev 1458) +++ trunk/yake/yake/msg/processors.h 2006-09-12 21:22:45 UTC (rev 1459) @@ -117,7 +117,7 @@ typedef msg_listener_mgr_type::listener_list listener_list; DoubleQueuedProcessor() : q_(&q1_) {} - void onPost(detail::message_base* msg) + void onPost(message_base_type* msg) { YAKE_ASSERT(msg); q_->push_back(msg); //@todo sort by msg type!? Modified: trunk/yake/yake/msg/router.h =================================================================== --- trunk/yake/yake/msg/router.h 2006-09-12 17:34:08 UTC (rev 1458) +++ trunk/yake/yake/msg/router.h 2006-09-12 21:22:45 UTC (rev 1459) @@ -67,6 +67,7 @@ typedef detail::message_base<source_type,target_type> message_base_type; typedef detail::listener_base<source_type,target_type> listener_base_type; + typedef typename processor_type::connection_type listener_connection_type; /** Post a message. Processing is controlled by T_processor. @see postMessage() @@ -84,13 +85,21 @@ target_type target = traits<source_type,target_type>::kNoTarget) { this->onPost( MSG_NAMESPACE::makeMessage<T,source_type,target_type>(v,source,target) ); } + listener_connection_type addListener( + listener_base_type* l, + source_type source = traits<source_type,target_type>::kNoSource, + target_type target = traits<source_type,target_type>::kNoTarget) + { + YAKE_ASSERT(l); + if (!l) + return listener_connection_type(); + return this->add(l,source,target); + } + /** Operator for listener registration (with source identifier kNoSource). */ router& operator << (listener_base_type* l) { - YAKE_ASSERT(l); - if (!l) - return *this; - this->add(l); + this->addListener(l); return *this; } /** Operator for listener registration with user supplied source identifier. */ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2006-09-12 21:24:52
|
Revision: 1460 http://svn.sourceforge.net/yake/?rev=1460&view=rev Author: psyclonist Date: 2006-09-12 14:24:34 -0700 (Tue, 12 Sep 2006) Log Message: ----------- cleanup and removal of deprecated code Modified Paths: -------------- trunk/yake/scripts/msvc8/base.vcproj trunk/yake/src/yapp/samples/misc/cmdrmayhem/yakeDemo.cpp trunk/yake/src/yapp/samples/misc/vehicle/yakeDemo.cpp Removed Paths: ------------- trunk/yake/yake/base/templates/yakeProperties.h Modified: trunk/yake/scripts/msvc8/base.vcproj =================================================================== --- trunk/yake/scripts/msvc8/base.vcproj 2006-09-12 21:22:45 UTC (rev 1459) +++ trunk/yake/scripts/msvc8/base.vcproj 2006-09-12 21:24:34 UTC (rev 1460) @@ -533,18 +533,10 @@ > </File> <File - RelativePath="..\..\yake\base\templates\yakeNiftyContainer.h" - > - </File> - <File RelativePath="..\..\yake\base\templates\yakePointer.h" > </File> <File - RelativePath="..\..\yake\base\templates\yakeProperties.h" - > - </File> - <File RelativePath="..\..\yake\base\templates\yakeRegistry.h" > </File> Modified: trunk/yake/src/yapp/samples/misc/cmdrmayhem/yakeDemo.cpp =================================================================== --- trunk/yake/src/yapp/samples/misc/cmdrmayhem/yakeDemo.cpp 2006-09-12 21:22:45 UTC (rev 1459) +++ trunk/yake/src/yapp/samples/misc/cmdrmayhem/yakeDemo.cpp 2006-09-12 21:24:34 UTC (rev 1460) @@ -64,7 +64,7 @@ TheMainState(raf::Application& owner) : raf::RtMainState(owner), mGround(0), - mComplex(0), + mPlayerModel(0), mPlayerRep(0), mEnv(0) { @@ -153,9 +153,9 @@ ); YAKE_ASSERT( mPlayerRep ); { - mComplex = new model::Model(); + mPlayerModel = new model::Model(); model::Graphical* pG = new model::Graphical(); - mComplex->addComponent( pG ); + mPlayerModel->addComponent( pG ); graphics::ISceneNode* pSN = getGraphicalWorld()->createSceneNode(); pG->addSceneNode( pSN, "playerSN" ); graphics::IEntity* pE = getGraphicalWorld()->createEntity("sphere_d1.mesh"); @@ -163,7 +163,7 @@ pSN->setScale( 0.5 * math::Vector3::kUnitScale ); model::ModelMovableDirectLink* pLink = new model::ModelMovableDirectLink(); - mComplex->addLink( pLink ); + mPlayerModel->addLink( pLink ); pLink->setSource( mPlayerRep ); pLink->subscribeToPositionChanged( pSN ); pLink->subscribeToOrientationChanged( pSN ); @@ -178,7 +178,7 @@ virtual void onDestroyScene() { mTopDownCtrlr.setCamera( 0 ); - YAKE_SAFE_DELETE( mComplex ); + YAKE_SAFE_DELETE( mPlayerModel ); YAKE_SAFE_DELETE( mPlayerRep ); YAKE_SAFE_DELETE( mGround ); YAKE_SAFE_DELETE( mEnv ); @@ -370,8 +370,8 @@ { mActiveActions.insert( input::ACTIONID_DOWN ); } private: physics::IAvatarPtr mPlayerRep; - model::Model* mGround; - model::Model* mComplex; + model::Model* mGround; + model::Model* mPlayerModel; input::ActionMap mActionMap; typedef std::set<input::ActionId> ActionIdList; Modified: trunk/yake/src/yapp/samples/misc/vehicle/yakeDemo.cpp =================================================================== --- trunk/yake/src/yapp/samples/misc/vehicle/yakeDemo.cpp 2006-09-12 21:22:45 UTC (rev 1459) +++ trunk/yake/src/yapp/samples/misc/vehicle/yakeDemo.cpp 2006-09-12 21:24:34 UTC (rev 1460) @@ -513,10 +513,11 @@ { using namespace input; + // load key<->action bindings + ActionMap::loadFromFile( actionMap, "../../media/vehicles/demo.actionmap.txt", keyboard, boost::bind(&Jet::addInputConditionConnection,this,_1) ); + // front wheel controls - ActionMap::loadFromFile( actionMap, "../../media/vehicles/demo.actionmap.txt", keyboard, boost::bind(&Jet::addInputConditionConnection,this,_1) ); - this->addInputSignalConnection( actionMap.subscribeToActionIdV( ACTIONID_LEFT, boost::bind(&Jet::onFrontWheelLeft,this) ) ); this->addInputSignalConnection( Deleted: trunk/yake/yake/base/templates/yakeProperties.h =================================================================== --- trunk/yake/yake/base/templates/yakeProperties.h 2006-09-12 21:22:45 UTC (rev 1459) +++ trunk/yake/yake/base/templates/yakeProperties.h 2006-09-12 21:24:34 UTC (rev 1460) @@ -1,73 +0,0 @@ -/* - ------------------------------------------------------------------------------------ - This file is part of YAKE - Copyright \xA9 2004 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_BASE_TEMPLATES_PROPERTIES_H -#define YAKE_BASE_TEMPLATES_PROPERTIES_H - -//============================================================================ -// IMPLEMENTATION HEADERS -//============================================================================ -//============================================================================ -// INTERFACE STRUCTURES / UTILITY CLASSES -//============================================================================ -#define YAKE_DECLARE_PROPERTY_GET( type, getfunc, var ) \ -struct _dp_##getfunc \ -{ \ - inline operator type() \ - { \ - return ((THIS_CLASS *) ((char *) this - offsetof( THIS_CLASS, var )))->getfunc(); \ - } \ -}; \ -friend struct _dp_##getfunc; \ -_dp_##getfunc var - -#define YAKE_DECLARE_PROPERTY_PUT( type, putfunc, var ) \ -struct _dp_##putfunc \ -{ \ - inline type operator=(const type & value) \ - { \ - return ((THIS_CLASS *) ((char *) this - offsetof( THIS_CLASS, var )))->putfunc( value ); \ - } \ -}; \ -friend struct _dp_##putfunc; \ -_dp_##putfunc var - -#define YAKE_DECLARE_PROPERTY( type, getfunc, putfunc, var ) \ -struct _dp_##getfunc_##putfunc \ -{ \ - inline operator type() \ - { \ - return ((THIS_CLASS *) ((char *) this - offsetof( THIS_CLASS, var )))->getfunc(); \ - } \ - inline type operator=(const type & value) \ - { \ - return ((THIS_CLASS *) ((char *) this - offsetof( THIS_CLASS, var )))->putfunc( value ); \ - } \ -}; \ -friend struct _dp_##getfunc_##putfunc; \ - _dp_##getfunc##_##putfunc var - -#endif // YAKE_BASE_TEMPLATES_PROPERTIES_H This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2006-09-14 21:06:39
|
Revision: 1465 http://svn.sourceforge.net/yake/?rev=1465&view=rev Author: psyclonist Date: 2006-09-14 13:56:35 -0700 (Thu, 14 Sep 2006) Log Message: ----------- set svn line ending property to 'native' Modified Paths: -------------- trunk/yake/common/media/graphics.delorean/delorean.material trunk/yake/common/media/graphics.fx/thruster1.particle trunk/yake/common/media/graphics.fx/thruster_jet.particle trunk/yake/common/media/scripts/o_fsm_test.lua trunk/yake/common/media/vehicles/delorean.xml trunk/yake/common/media/vehicles/jet.xml trunk/yake/common/media/vehicles/jet2.xml trunk/yake/documentation/api/docMainPage.h trunk/yake/samples/README.TXT trunk/yake/scripts/msvc71/samples/misc/sampleCar.vcproj trunk/yake/scripts/msvc71/vehicle.vcproj trunk/yake/scripts/msvc8/audio.vcproj trunk/yake/scripts/msvc8/base.vcproj trunk/yake/scripts/msvc8/data.vcproj trunk/yake/scripts/msvc8/ent.vcproj trunk/yake/scripts/msvc8/graphics.vcproj trunk/yake/scripts/msvc8/gui.vcproj trunk/yake/scripts/msvc8/gui_adapter.vcproj trunk/yake/scripts/msvc8/input.vcproj trunk/yake/scripts/msvc8/loader.vcproj trunk/yake/scripts/msvc8/model.vcproj trunk/yake/scripts/msvc8/msg.vcproj trunk/yake/scripts/msvc8/msg2.vcproj trunk/yake/scripts/msvc8/net.vcproj trunk/yake/scripts/msvc8/object.vcproj trunk/yake/scripts/msvc8/physics.vcproj trunk/yake/scripts/msvc8/plugins/audio/audioOpenAL.vcproj trunk/yake/scripts/msvc8/plugins/ent/entCommon.vcproj trunk/yake/scripts/msvc8/plugins/ent/entLua.vcproj trunk/yake/scripts/msvc8/plugins/graphics/graphicsOgre.vcproj trunk/yake/scripts/msvc8/plugins/gui/ceguiOgreRendererAdapter.vcproj trunk/yake/scripts/msvc8/plugins/input/inputOgre.vcproj trunk/yake/scripts/msvc8/plugins/model/modelLua.vcproj trunk/yake/scripts/msvc8/plugins/physics/physicsNX.vcproj trunk/yake/scripts/msvc8/plugins/physics/physicsODE.vcproj trunk/yake/scripts/msvc8/plugins/physics/terrainPhysMgr.vcproj trunk/yake/scripts/msvc8/plugins/scripting/baseLuaBindings.vcproj trunk/yake/scripts/msvc8/plugins/scripting/graphicsLuaBindings.vcproj trunk/yake/scripts/msvc8/plugins/scripting/scriptingLua.vcproj trunk/yake/scripts/msvc8/plugins/scripting/scriptingLuaBindings.vcproj trunk/yake/scripts/msvc8/raf.vcproj trunk/yake/scripts/msvc8/reflection.vcproj trunk/yake/scripts/msvc8/samples/application/sample_application.vcproj trunk/yake/scripts/msvc8/samples/audio/sampleAudio1.vcproj trunk/yake/scripts/msvc8/samples/base/registryPluginConcrete.vcproj trunk/yake/scripts/msvc8/samples/base/registryPluginInterface.vcproj trunk/yake/scripts/msvc8/samples/base/sampleAbstractFactory.vcproj trunk/yake/scripts/msvc8/samples/base/sampleContainer.vcproj trunk/yake/scripts/msvc8/samples/base/sampleDebug.vcproj trunk/yake/scripts/msvc8/samples/base/sampleEvents.vcproj trunk/yake/scripts/msvc8/samples/base/sampleRegistry.vcproj trunk/yake/scripts/msvc8/samples/base/sampleRegistryPlugin.vcproj trunk/yake/scripts/msvc8/samples/base/sampleRegistryPluginManual.vcproj trunk/yake/scripts/msvc8/samples/data/sampleDataMisc.vcproj trunk/yake/scripts/msvc8/samples/ent/sampleEntFsm.vcproj trunk/yake/scripts/msvc8/samples/graphics/sampleGraphicsDemo.vcproj trunk/yake/scripts/msvc8/samples/misc/sampleCmdrMayhem.vcproj trunk/yake/scripts/msvc8/samples/misc/sampleGuiConsole.vcproj trunk/yake/scripts/msvc8/samples/misc/sampleScripted.vcproj trunk/yake/scripts/msvc8/samples/misc/sampleScriptedGraphics.vcproj trunk/yake/scripts/msvc8/samples/misc/sampleVehicle.vcproj trunk/yake/scripts/msvc8/samples/model/sampleDotLink.vcproj trunk/yake/scripts/msvc8/samples/model/sampleModel1.vcproj trunk/yake/scripts/msvc8/samples/model/sampleSync1.vcproj trunk/yake/scripts/msvc8/samples/msg/sampleMsg1.vcproj trunk/yake/scripts/msvc8/samples/net/sampleNetPacket.vcproj trunk/yake/scripts/msvc8/samples/net/sampleRoClient.vcproj trunk/yake/scripts/msvc8/samples/net/sampleRoServer.vcproj trunk/yake/scripts/msvc8/samples/physics/samplePhysicsDemo.vcproj trunk/yake/scripts/msvc8/samples/physics/samplePhysicsPagingTerrain.vcproj trunk/yake/scripts/msvc8/samples/raf/sampleRafDemo1.vcproj trunk/yake/scripts/msvc8/samples/raf/sampleRafMinimal.vcproj trunk/yake/scripts/msvc8/samples/scripting/sampleScriptingLua.vcproj trunk/yake/scripts/msvc8/samples/statemachine/sampleFsm1.vcproj trunk/yake/scripts/msvc8/samples/thread/sampleThread1.vcproj trunk/yake/scripts/msvc8/samples.sln trunk/yake/scripts/msvc8/scripting.vcproj trunk/yake/scripts/msvc8/thread.vcproj trunk/yake/scripts/msvc8/vehicle.vcproj trunk/yake/scripts/msvc8/yapp.vcproj trunk/yake/src/yake/ent/component.cpp trunk/yake/src/yake/ent/component_holder.cpp trunk/yake/src/yake/ent/entity.cpp trunk/yake/src/yake/ent/object.cpp trunk/yake/src/yake/ent/object_listener.cpp trunk/yake/src/yake/ent/object_mgr.cpp trunk/yake/src/yake/ent/object_mgr_listener.cpp trunk/yake/src/yake/ent/pch.cpp trunk/yake/src/yake/ent/vm_holder.cpp trunk/yake/src/yake/input/yakeActionIds.cpp trunk/yake/src/yake/loader/pch.cpp trunk/yake/src/yake/loader/yakeDotScene.cpp trunk/yake/src/yake/loader/yakeXODEParser.cpp trunk/yake/src/yake/model/pch.cpp trunk/yake/src/yake/model/yakeComponentCreatorManager.cpp trunk/yake/src/yake/model/yakeDotLinkLoader.cpp trunk/yake/src/yake/model/yakeDotModelParser.cpp trunk/yake/src/yake/model/yakeGraphical.cpp trunk/yake/src/yake/model/yakeGraphicalCreator.cpp trunk/yake/src/yake/model/yakeGraphicalDotSceneLoader.cpp trunk/yake/src/yake/model/yakeLinkCreator.cpp trunk/yake/src/yake/model/yakeModel.cpp trunk/yake/src/yake/model/yakeModelComponent.cpp trunk/yake/src/yake/model/yakeModelComponentContainer.cpp trunk/yake/src/yake/model/yakeModelLink.cpp trunk/yake/src/yake/model/yakeModelLinkContainer.cpp trunk/yake/src/yake/model/yakeModelManager.cpp trunk/yake/src/yake/model/yakeModelMovableLink.cpp trunk/yake/src/yake/model/yakeModelTemplate.cpp trunk/yake/src/yake/model/yakeModelTemplateManager.cpp trunk/yake/src/yake/model/yakePhysical.cpp trunk/yake/src/yake/model/yakePhysicalCreator.cpp trunk/yake/src/yake/model/yakeXODEListener.cpp trunk/yake/src/yake/net/detail/netCommon.cpp trunk/yake/src/yake/net/detail/netEnetClientPacketConnection.cpp trunk/yake/src/yake/net/detail/netEnetServerPacketConnection.cpp trunk/yake/src/yake/net/detail/netEventConnection.cpp trunk/yake/src/yake/net/detail/netInternal.cpp trunk/yake/src/yake/net/net.cpp trunk/yake/src/yake/net/pch.cpp trunk/yake/src/yake/physics/yakePhysicsCommon.cpp trunk/yake/src/yake/plugins/entLua/entLua.cpp trunk/yake/src/yake/plugins/physicsODE/OdeAvatar.cpp trunk/yake/src/yake/plugins/physicsODE/OdeRay.cpp trunk/yake/src/yake/samples/audio/demo1/demo.cpp trunk/yake/src/yake/samples/audio/demo1/pch.cpp trunk/yake/src/yake/samples/ent/sampleEntFsm/demo.cpp trunk/yake/src/yake/samples/model/dotScene/demo.cpp trunk/yake/src/yake/samples/model/dotScene/pch.cpp trunk/yake/src/yake/samples/msg/sampleMsg1/demo.cpp trunk/yake/src/yake/samples/net/packet/demo.cpp trunk/yake/src/yake/samples/net/packet/pch.cpp trunk/yake/src/yake/samples/net/roclient/ROClient.cpp trunk/yake/src/yake/samples/net/roclient/demo.cpp trunk/yake/src/yake/samples/net/roclient/pch.cpp trunk/yake/src/yake/samples/net/roserver/ROServer.cpp trunk/yake/src/yake/samples/net/roserver/demo.cpp trunk/yake/src/yake/samples/net/roserver/pch.cpp trunk/yake/src/yake/samples/statemachine/sampleFsm1/demo.cpp trunk/yake/src/yapp/plugins/terrainPhysMgr/TerrainOdeActor.cpp trunk/yake/src/yapp/plugins/terrainPhysMgr/TerrainPhysicsManager.cpp trunk/yake/src/yapp/samples/misc/cmdrmayhem/yakeDemo.cpp trunk/yake/src/yapp/samples/misc/vehicle/yakeDemo.cpp trunk/yake/src/yapp/samples/misc/vehicle/yakePCH.cpp trunk/yake/src/yapp/vehicle/yakeDotVehicle.cpp trunk/yake/src/yapp/vehicle/yakeMountPoint.cpp trunk/yake/src/yapp/vehicle/yakeNativeOde.cpp trunk/yake/src/yapp/vehicle/yakeOdeEngine.cpp trunk/yake/src/yapp/vehicle/yakePCH.cpp trunk/yake/src/yapp/vehicle/yakeVehicle.cpp trunk/yake/src/yapp/vehicle/yakeVehicleModelComponent.cpp trunk/yake/src/yapp/vehicle/yakeVehicleModelComponentCreator.cpp trunk/yake/yake/base/math/yakeAxisAlignedBox.h trunk/yake/yake/base/yakeTaggedListenerManager.h trunk/yake/yake/ent/component.h trunk/yake/yake/ent/component_holder.h trunk/yake/yake/ent/ent.h trunk/yake/yake/ent/entity.h trunk/yake/yake/ent/object.h trunk/yake/yake/ent/object_listener.h trunk/yake/yake/ent/object_mgr.h trunk/yake/yake/ent/object_mgr_listener.h trunk/yake/yake/ent/pch.h trunk/yake/yake/ent/prerequisites.h trunk/yake/yake/ent/vm_holder.h trunk/yake/yake/loader/loader.h trunk/yake/yake/loader/pch.h trunk/yake/yake/loader/prerequisites.h trunk/yake/yake/loader/yakeDotLinkLoader.h trunk/yake/yake/loader/yakeDotScene.h trunk/yake/yake/loader/yakeXODEParser.h trunk/yake/yake/model/model.h trunk/yake/yake/model/model_component.h trunk/yake/yake/model/model_dotmodel_parser.h trunk/yake/yake/model/model_graphical_dotscene_loader.h trunk/yake/yake/model/model_link.h trunk/yake/yake/model/model_link_dotlink_loader.h trunk/yake/yake/model/model_physical_xode_loader.h trunk/yake/yake/model/pch.h trunk/yake/yake/model/prerequisites.h trunk/yake/yake/msg/listener.h trunk/yake/yake/msg/prerequisites.h trunk/yake/yake/msg/processors.h trunk/yake/yake/msg/yakeMessage.h trunk/yake/yake/net/detail/netEnetClientPacketConnection.h trunk/yake/yake/net/detail/netEnetServerPacketConnection.h trunk/yake/yake/net/detail/netEventConnection.h trunk/yake/yake/net/detail/netInternal.h trunk/yake/yake/net/net.h trunk/yake/yake/net/netBitstream.h trunk/yake/yake/net/netBitstream.inl trunk/yake/yake/net/netBitstreamAdapters.h trunk/yake/yake/net/netCommon.h trunk/yake/yake/net/netEvent.h trunk/yake/yake/net/netPacket.h trunk/yake/yake/net/netPrerequisites.h trunk/yake/yake/net/netTypes.h trunk/yake/yake/net/pch.h trunk/yake/yake/object/ClassAndObjectIdManager.h trunk/yake/yake/object/ClassAndObjectIdManager.inl trunk/yake/yake/object/ObjectContainer.h trunk/yake/yake/object/ObjectId.h trunk/yake/yake/object/ObjectId.inl trunk/yake/yake/object/ObjectManager.h trunk/yake/yake/object/ObjectManager.inl trunk/yake/yake/object/common.h trunk/yake/yake/object/pch.h trunk/yake/yake/object/yakeObjects.h trunk/yake/yake/physics/yakePhysicsCommon.h trunk/yake/yake/plugins/entLua/entLua.h trunk/yake/yake/plugins/physicsODE/OdeAvatar.h trunk/yake/yake/plugins/physicsODE/OdeRay.h trunk/yake/yake/plugins/physicsODE/yakePrerequisites.h trunk/yake/yake/prop/prerequisites.h trunk/yake/yake/prop/prop.h trunk/yake/yake/prop/prop_def.h trunk/yake/yake/prop/prop_holder.h trunk/yake/yake/prop/rtti_class.h trunk/yake/yake/prop/yakeProperty.h trunk/yake/yake/samples/audio/demo1/pch.h trunk/yake/yake/samples/model/dotScene/pch.h trunk/yake/yake/samples/net/common/common.h trunk/yake/yake/samples/net/common/commonEvents.h trunk/yake/yake/samples/net/common/config.h trunk/yake/yake/samples/net/packet/pch.h trunk/yake/yake/samples/net/roclient/ROClient.h trunk/yake/yake/samples/net/roclient/pch.h trunk/yake/yake/samples/net/roserver/ROServer.h trunk/yake/yake/samples/net/roserver/pch.h trunk/yake/yake/statemachine/fsm_core.h trunk/yake/yake/statemachine/fsm_oo_machine.h trunk/yake/yapp/common/yakeCEGUIHelpers.h trunk/yake/yapp/common/yakeCameraControllers.h trunk/yake/yapp/plugins/terrainPhysMgr/TerrainOdeActor.h trunk/yake/yapp/plugins/terrainPhysMgr/TerrainOdeShape.h trunk/yake/yapp/plugins/terrainPhysMgr/TerrainPhysicsManager.h trunk/yake/yapp/samples/misc/vehicle/yakePCH.h trunk/yake/yapp/vehicle/yakeDotVehicle.h trunk/yake/yapp/vehicle/yakeInterfaces.h trunk/yake/yapp/vehicle/yakeMountPoint.h trunk/yake/yapp/vehicle/yakeNativeOde.h trunk/yake/yapp/vehicle/yakePCH.h trunk/yake/yapp/vehicle/yakePrerequisites.h trunk/yake/yapp/vehicle/yakeTemplates.h trunk/yake/yapp/vehicle/yakeVehicle.h trunk/yake/yapp/vehicle/yakeVehicleModelComponent.h trunk/yake/yapp/vehicle/yakeVehicleSystem.h Property Changed: ---------------- trunk/yake/common/media/graphics.delorean/delorean.material trunk/yake/common/media/graphics.fx/thruster1.particle trunk/yake/common/media/graphics.fx/thruster_jet.particle trunk/yake/common/media/scripts/o_fsm_test.lua trunk/yake/common/media/vehicles/delorean.xml trunk/yake/common/media/vehicles/jet.xml trunk/yake/common/media/vehicles/jet2.xml trunk/yake/documentation/api/docMainPage.h trunk/yake/samples/README.TXT trunk/yake/scripts/msvc71/samples/misc/sampleCar.vcproj trunk/yake/scripts/msvc71/vehicle.vcproj trunk/yake/scripts/msvc8/audio.vcproj trunk/yake/scripts/msvc8/base.vcproj trunk/yake/scripts/msvc8/data.vcproj trunk/yake/scripts/msvc8/ent.vcproj trunk/yake/scripts/msvc8/graphics.vcproj trunk/yake/scripts/msvc8/gui.vcproj trunk/yake/scripts/msvc8/gui_adapter.vcproj trunk/yake/scripts/msvc8/input.vcproj trunk/yake/scripts/msvc8/loader.vcproj trunk/yake/scripts/msvc8/model.vcproj trunk/yake/scripts/msvc8/msg.vcproj trunk/yake/scripts/msvc8/msg2.vcproj trunk/yake/scripts/msvc8/net.vcproj trunk/yake/scripts/msvc8/object.vcproj trunk/yake/scripts/msvc8/physics.vcproj trunk/yake/scripts/msvc8/plugins/audio/audioOpenAL.vcproj trunk/yake/scripts/msvc8/plugins/ent/entCommon.vcproj trunk/yake/scripts/msvc8/plugins/ent/entLua.vcproj trunk/yake/scripts/msvc8/plugins/graphics/graphicsOgre.vcproj trunk/yake/scripts/msvc8/plugins/gui/ceguiOgreRendererAdapter.vcproj trunk/yake/scripts/msvc8/plugins/input/inputOgre.vcproj trunk/yake/scripts/msvc8/plugins/model/modelLua.vcproj trunk/yake/scripts/msvc8/plugins/physics/physicsNX.vcproj trunk/yake/scripts/msvc8/plugins/physics/physicsODE.vcproj trunk/yake/scripts/msvc8/plugins/physics/terrainPhysMgr.vcproj trunk/yake/scripts/msvc8/plugins/scripting/baseLuaBindings.vcproj trunk/yake/scripts/msvc8/plugins/scripting/graphicsLuaBindings.vcproj trunk/yake/scripts/msvc8/plugins/scripting/scriptingLua.vcproj trunk/yake/scripts/msvc8/plugins/scripting/scriptingLuaBindings.vcproj trunk/yake/scripts/msvc8/raf.vcproj trunk/yake/scripts/msvc8/reflection.vcproj trunk/yake/scripts/msvc8/samples/application/sample_application.vcproj trunk/yake/scripts/msvc8/samples/audio/sampleAudio1.vcproj trunk/yake/scripts/msvc8/samples/base/registryPluginConcrete.vcproj trunk/yake/scripts/msvc8/samples/base/registryPluginInterface.vcproj trunk/yake/scripts/msvc8/samples/base/sampleAbstractFactory.vcproj trunk/yake/scripts/msvc8/samples/base/sampleContainer.vcproj trunk/yake/scripts/msvc8/samples/base/sampleDebug.vcproj trunk/yake/scripts/msvc8/samples/base/sampleEvents.vcproj trunk/yake/scripts/msvc8/samples/base/sampleRegistry.vcproj trunk/yake/scripts/msvc8/samples/base/sampleRegistryPlugin.vcproj trunk/yake/scripts/msvc8/samples/base/sampleRegistryPluginManual.vcproj trunk/yake/scripts/msvc8/samples/data/sampleDataMisc.vcproj trunk/yake/scripts/msvc8/samples/ent/sampleEntFsm.vcproj trunk/yake/scripts/msvc8/samples/graphics/sampleGraphicsDemo.vcproj trunk/yake/scripts/msvc8/samples/misc/sampleCmdrMayhem.vcproj trunk/yake/scripts/msvc8/samples/misc/sampleGuiConsole.vcproj trunk/yake/scripts/msvc8/samples/misc/sampleScripted.vcproj trunk/yake/scripts/msvc8/samples/misc/sampleScriptedGraphics.vcproj trunk/yake/scripts/msvc8/samples/misc/sampleVehicle.vcproj trunk/yake/scripts/msvc8/samples/model/sampleDotLink.vcproj trunk/yake/scripts/msvc8/samples/model/sampleModel1.vcproj trunk/yake/scripts/msvc8/samples/model/sampleSync1.vcproj trunk/yake/scripts/msvc8/samples/msg/sampleMsg1.vcproj trunk/yake/scripts/msvc8/samples/net/sampleNetPacket.vcproj trunk/yake/scripts/msvc8/samples/net/sampleRoClient.vcproj trunk/yake/scripts/msvc8/samples/net/sampleRoServer.vcproj trunk/yake/scripts/msvc8/samples/physics/samplePhysicsDemo.vcproj trunk/yake/scripts/msvc8/samples/physics/samplePhysicsPagingTerrain.vcproj trunk/yake/scripts/msvc8/samples/raf/sampleRafDemo1.vcproj trunk/yake/scripts/msvc8/samples/raf/sampleRafMinimal.vcproj trunk/yake/scripts/msvc8/samples/scripting/sampleScriptingLua.vcproj trunk/yake/scripts/msvc8/samples/statemachine/sampleFsm1.vcproj trunk/yake/scripts/msvc8/samples/thread/sampleThread1.vcproj trunk/yake/scripts/msvc8/samples.sln trunk/yake/scripts/msvc8/scripting.vcproj trunk/yake/scripts/msvc8/thread.vcproj trunk/yake/scripts/msvc8/vehicle.vcproj trunk/yake/scripts/msvc8/yapp.vcproj trunk/yake/src/yake/ent/component.cpp trunk/yake/src/yake/ent/component_holder.cpp trunk/yake/src/yake/ent/entity.cpp trunk/yake/src/yake/ent/object.cpp trunk/yake/src/yake/ent/object_listener.cpp trunk/yake/src/yake/ent/object_mgr.cpp trunk/yake/src/yake/ent/object_mgr_listener.cpp trunk/yake/src/yake/ent/pch.cpp trunk/yake/src/yake/ent/vm_holder.cpp trunk/yake/src/yake/input/yakeActionIds.cpp trunk/yake/src/yake/loader/pch.cpp trunk/yake/src/yake/loader/yakeDotScene.cpp trunk/yake/src/yake/loader/yakeXODEParser.cpp trunk/yake/src/yake/model/pch.cpp trunk/yake/src/yake/model/yakeComponentCreatorManager.cpp trunk/yake/src/yake/model/yakeDotLinkLoader.cpp trunk/yake/src/yake/model/yakeDotModelParser.cpp trunk/yake/src/yake/model/yakeGraphical.cpp trunk/yake/src/yake/model/yakeGraphicalCreator.cpp trunk/yake/src/yake/model/yakeGraphicalDotSceneLoader.cpp trunk/yake/src/yake/model/yakeLinkCreator.cpp trunk/yake/src/yake/model/yakeModel.cpp trunk/yake/src/yake/model/yakeModelComponent.cpp trunk/yake/src/yake/model/yakeModelComponentContainer.cpp trunk/yake/src/yake/model/yakeModelLink.cpp trunk/yake/src/yake/model/yakeModelLinkContainer.cpp trunk/yake/src/yake/model/yakeModelManager.cpp trunk/yake/src/yake/model/yakeModelMovableLink.cpp trunk/yake/src/yake/model/yakeModelTemplate.cpp trunk/yake/src/yake/model/yakeModelTemplateManager.cpp trunk/yake/src/yake/model/yakePhysical.cpp trunk/yake/src/yake/model/yakePhysicalCreator.cpp trunk/yake/src/yake/model/yakeXODEListener.cpp trunk/yake/src/yake/net/detail/netCommon.cpp trunk/yake/src/yake/net/detail/netEnetClientPacketConnection.cpp trunk/yake/src/yake/net/detail/netEnetServerPacketConnection.cpp trunk/yake/src/yake/net/detail/netEventConnection.cpp trunk/yake/src/yake/net/detail/netInternal.cpp trunk/yake/src/yake/net/net.cpp trunk/yake/src/yake/net/pch.cpp trunk/yake/src/yake/physics/yakePhysicsCommon.cpp trunk/yake/src/yake/plugins/entLua/entLua.cpp trunk/yake/src/yake/plugins/physicsODE/OdeAvatar.cpp trunk/yake/src/yake/plugins/physicsODE/OdeRay.cpp trunk/yake/src/yake/samples/audio/demo1/demo.cpp trunk/yake/src/yake/samples/audio/demo1/pch.cpp trunk/yake/src/yake/samples/ent/sampleEntFsm/demo.cpp trunk/yake/src/yake/samples/model/dotScene/demo.cpp trunk/yake/src/yake/samples/model/dotScene/pch.cpp trunk/yake/src/yake/samples/msg/sampleMsg1/demo.cpp trunk/yake/src/yake/samples/net/packet/demo.cpp trunk/yake/src/yake/samples/net/packet/pch.cpp trunk/yake/src/yake/samples/net/roclient/ROClient.cpp trunk/yake/src/yake/samples/net/roclient/demo.cpp trunk/yake/src/yake/samples/net/roclient/pch.cpp trunk/yake/src/yake/samples/net/roserver/ROServer.cpp trunk/yake/src/yake/samples/net/roserver/demo.cpp trunk/yake/src/yake/samples/net/roserver/pch.cpp trunk/yake/src/yake/samples/statemachine/sampleFsm1/demo.cpp trunk/yake/src/yapp/plugins/terrainPhysMgr/TerrainOdeActor.cpp trunk/yake/src/yapp/plugins/terrainPhysMgr/TerrainPhysicsManager.cpp trunk/yake/src/yapp/samples/misc/cmdrmayhem/yakeDemo.cpp trunk/yake/src/yapp/samples/misc/vehicle/yakeDemo.cpp trunk/yake/src/yapp/samples/misc/vehicle/yakePCH.cpp trunk/yake/src/yapp/samples/physics/paging_terrain/yakeDemo.cpp trunk/yake/src/yapp/samples/physics/paging_terrain/yakePCH.cpp trunk/yake/src/yapp/vehicle/yakeDotVehicle.cpp trunk/yake/src/yapp/vehicle/yakeMountPoint.cpp trunk/yake/src/yapp/vehicle/yakeNativeOde.cpp trunk/yake/src/yapp/vehicle/yakeOdeEngine.cpp trunk/yake/src/yapp/vehicle/yakePCH.cpp trunk/yake/src/yapp/vehicle/yakeVehicle.cpp trunk/yake/src/yapp/vehicle/yakeVehicleModelComponent.cpp trunk/yake/src/yapp/vehicle/yakeVehicleModelComponentCreator.cpp trunk/yake/yake/base/math/yakeAxisAlignedBox.h trunk/yake/yake/base/yakeTaggedListenerManager.h trunk/yake/yake/ent/component.h trunk/yake/yake/ent/component_holder.h trunk/yake/yake/ent/ent.h trunk/yake/yake/ent/entity.h trunk/yake/yake/ent/object.h trunk/yake/yake/ent/object_listener.h trunk/yake/yake/ent/object_mgr.h trunk/yake/yake/ent/object_mgr_listener.h trunk/yake/yake/ent/pch.h trunk/yake/yake/ent/prerequisites.h trunk/yake/yake/ent/vm_holder.h trunk/yake/yake/loader/loader.h trunk/yake/yake/loader/pch.h trunk/yake/yake/loader/prerequisites.h trunk/yake/yake/loader/yakeDotLinkLoader.h trunk/yake/yake/loader/yakeDotScene.h trunk/yake/yake/loader/yakeXODEParser.h trunk/yake/yake/model/model.h trunk/yake/yake/model/model_component.h trunk/yake/yake/model/model_dotmodel_parser.h trunk/yake/yake/model/model_graphical_dotscene_loader.h trunk/yake/yake/model/model_link.h trunk/yake/yake/model/model_link_dotlink_loader.h trunk/yake/yake/model/model_physical_xode_loader.h trunk/yake/yake/model/pch.h trunk/yake/yake/model/prerequisites.h trunk/yake/yake/msg/listener.h trunk/yake/yake/msg/prerequisites.h trunk/yake/yake/msg/processors.h trunk/yake/yake/msg/yakeMessage.h trunk/yake/yake/net/detail/netEnetClientPacketConnection.h trunk/yake/yake/net/detail/netEnetServerPacketConnection.h trunk/yake/yake/net/detail/netEventConnection.h trunk/yake/yake/net/detail/netInternal.h trunk/yake/yake/net/net.h trunk/yake/yake/net/netBitstream.h trunk/yake/yake/net/netBitstream.inl trunk/yake/yake/net/netBitstreamAdapters.h trunk/yake/yake/net/netCommon.h trunk/yake/yake/net/netEvent.h trunk/yake/yake/net/netPacket.h trunk/yake/yake/net/netPrerequisites.h trunk/yake/yake/net/netTypes.h trunk/yake/yake/net/pch.h trunk/yake/yake/object/ClassAndObjectIdManager.h trunk/yake/yake/object/ClassAndObjectIdManager.inl trunk/yake/yake/object/ObjectContainer.h trunk/yake/yake/object/ObjectId.h trunk/yake/yake/object/ObjectId.inl trunk/yake/yake/object/ObjectManager.h trunk/yake/yake/object/ObjectManager.inl trunk/yake/yake/object/common.h trunk/yake/yake/object/pch.h trunk/yake/yake/object/yakeObjects.h trunk/yake/yake/physics/yakePhysicsCommon.h trunk/yake/yake/plugins/entLua/entLua.h trunk/yake/yake/plugins/physicsODE/OdeAvatar.h trunk/yake/yake/plugins/physicsODE/OdeRay.h trunk/yake/yake/plugins/physicsODE/yakePrerequisites.h trunk/yake/yake/prop/prerequisites.h trunk/yake/yake/prop/prop.h trunk/yake/yake/prop/prop_def.h trunk/yake/yake/prop/prop_holder.h trunk/yake/yake/prop/rtti_class.h trunk/yake/yake/prop/yakeProperty.h trunk/yake/yake/samples/audio/demo1/pch.h trunk/yake/yake/samples/model/dotScene/pch.h trunk/yake/yake/samples/net/common/common.h trunk/yake/yake/samples/net/common/commonEvents.h trunk/yake/yake/samples/net/common/config.h trunk/yake/yake/samples/net/packet/pch.h trunk/yake/yake/samples/net/roclient/ROClient.h trunk/yake/yake/samples/net/roclient/pch.h trunk/yake/yake/samples/net/roserver/ROServer.h trunk/yake/yake/samples/net/roserver/pch.h trunk/yake/yake/statemachine/fsm_core.h trunk/yake/yake/statemachine/fsm_oo_machine.h trunk/yake/yapp/common/yakeCEGUIHelpers.h trunk/yake/yapp/common/yakeCameraControllers.h trunk/yake/yapp/plugins/terrainPhysMgr/TerrainOdeActor.h trunk/yake/yapp/plugins/terrainPhysMgr/TerrainOdePrerequisites.h trunk/yake/yapp/plugins/terrainPhysMgr/TerrainOdeShape.h trunk/yake/yapp/plugins/terrainPhysMgr/TerrainPhysicsManager.h trunk/yake/yapp/samples/misc/vehicle/yakePCH.h trunk/yake/yapp/vehicle/yakeDotVehicle.h trunk/yake/yapp/vehicle/yakeInterfaces.h trunk/yake/yapp/vehicle/yakeMountPoint.h trunk/yake/yapp/vehicle/yakeNativeOde.h trunk/yake/yapp/vehicle/yakePCH.h trunk/yake/yapp/vehicle/yakePrerequisites.h trunk/yake/yapp/vehicle/yakeTemplates.h trunk/yake/yapp/vehicle/yakeVehicle.h trunk/yake/yapp/vehicle/yakeVehicleModelComponent.h trunk/yake/yapp/vehicle/yakeVehicleSystem.h Modified: trunk/yake/common/media/graphics.delorean/delorean.material =================================================================== --- trunk/yake/common/media/graphics.delorean/delorean.material 2006-09-13 22:50:25 UTC (rev 1464) +++ trunk/yake/common/media/graphics.delorean/delorean.material 2006-09-14 20:56:35 UTC (rev 1465) @@ -1,13 +1,13 @@ -material delorean -{ - technique - { - pass - { - texture_unit - { - texture delorean.tga - } - } - } -} +material delorean +{ + technique + { + pass + { + texture_unit + { + texture delorean.tga + } + } + } +} Property changes on: trunk/yake/common/media/graphics.delorean/delorean.material ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/yake/common/media/graphics.fx/thruster1.particle =================================================================== --- trunk/yake/common/media/graphics.fx/thruster1.particle 2006-09-13 22:50:25 UTC (rev 1464) +++ trunk/yake/common/media/graphics.fx/thruster1.particle 2006-09-14 20:56:35 UTC (rev 1465) @@ -1,37 +1,37 @@ -// exhaust - fire (and smoke?) -// source: OGRE3D -thruster1 -{ - material Examples/Flare - particle_width 25 - particle_height 25 - cull_each false - quota 200 - billboard_type point - - // Area emitter - emitter Point - { - angle 5 - emission_rate 100 - time_to_live 0.5 - direction 0 0 1 - velocity_min 250 - velocity_max 300 - colour_range_start 1 1 0.5 - colour_range_end 1 0.8 0.3 - } - - affector ColourFader - { - red -0.25 - green -1 - blue -1 - } - - affector Scaler - { - rate 0.1 - } - -} +// exhaust - fire (and smoke?) +// source: OGRE3D +thruster1 +{ + material Examples/Flare + particle_width 25 + particle_height 25 + cull_each false + quota 200 + billboard_type point + + // Area emitter + emitter Point + { + angle 5 + emission_rate 100 + time_to_live 0.5 + direction 0 0 1 + velocity_min 250 + velocity_max 300 + colour_range_start 1 1 0.5 + colour_range_end 1 0.8 0.3 + } + + affector ColourFader + { + red -0.25 + green -1 + blue -1 + } + + affector Scaler + { + rate 0.1 + } + +} Property changes on: trunk/yake/common/media/graphics.fx/thruster1.particle ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/yake/common/media/graphics.fx/thruster_jet.particle =================================================================== --- trunk/yake/common/media/graphics.fx/thruster_jet.particle 2006-09-13 22:50:25 UTC (rev 1464) +++ trunk/yake/common/media/graphics.fx/thruster_jet.particle 2006-09-14 20:56:35 UTC (rev 1465) @@ -1,37 +1,37 @@ -// exhaust - fire (and smoke?) -// source: OGRE3D -thruster2 -{ - material Examples/Flare - particle_width 5 - particle_height 5 - cull_each false - quota 200 - billboard_type point - - // Area emitter - emitter Point - { - angle 0.5 - emission_rate 100 - time_to_live 0.2 - direction 0 0 1 - velocity_min 60 - velocity_max 70 - colour_range_start 1 1 0.5 - colour_range_end 1 0.8 0.3 - } - - affector ColourFader - { - red -0.25 - green -1 - blue -1 - } - - affector Scaler - { - rate 0.1 - } - -} +// exhaust - fire (and smoke?) +// source: OGRE3D +thruster2 +{ + material Examples/Flare + particle_width 5 + particle_height 5 + cull_each false + quota 200 + billboard_type point + + // Area emitter + emitter Point + { + angle 0.5 + emission_rate 100 + time_to_live 0.2 + direction 0 0 1 + velocity_min 60 + velocity_max 70 + colour_range_start 1 1 0.5 + colour_range_end 1 0.8 0.3 + } + + affector ColourFader + { + red -0.25 + green -1 + blue -1 + } + + affector Scaler + { + rate 0.1 + } + +} Property changes on: trunk/yake/common/media/graphics.fx/thruster_jet.particle ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/yake/common/media/scripts/o_fsm_test.lua =================================================================== --- trunk/yake/common/media/scripts/o_fsm_test.lua 2006-09-13 22:50:25 UTC (rev 1464) +++ trunk/yake/common/media/scripts/o_fsm_test.lua 2006-09-14 20:56:35 UTC (rev 1465) @@ -1,75 +1,75 @@ -print("> Starting object script..."); -event = { - on_spawn = function() - print(" script event.on_spawn") - --ent:postCmd("go to","jack's bar") - --OR: ev:postCmd(ent,"go to","jack's bar") - --ent:postCmd("die") - 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 -} -fsm = { - main = { - states = { - awakening, - alive, - dead - }, - transitions = { - {awakening,"spawn",alive}, - {alive,"die",dead} - } - } -} -state = { - alive = { - on_enter = function() - print(" script state.alive.on_enter") - end, - on_tick = function() - print(" script state.alive.on_tick") - end, - on_exit = function() - print(" script state.alive.on_exit") - end - }, - awakening = { - on_enter = function() - print(" script state.awakening.on_enter") - end, - on_tick = function() - print(" script state.awakening.on_tick") - end, - on_exit = function() - print(" script state.awakening.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() calling charGoTo()") - charGoTo("blah") - print("main() resuming from charGoTo()") -end - +print("> Starting object script..."); +event = { + on_spawn = function() + print(" script event.on_spawn") + --ent:postCmd("go to","jack's bar") + --OR: ev:postCmd(ent,"go to","jack's bar") + --ent:postCmd("die") + 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 +} +fsm = { + main = { + states = { + awakening, + alive, + dead + }, + transitions = { + {awakening,"spawn",alive}, + {alive,"die",dead} + } + } +} +state = { + alive = { + on_enter = function() + print(" script state.alive.on_enter") + end, + on_tick = function() + print(" script state.alive.on_tick") + end, + on_exit = function() + print(" script state.alive.on_exit") + end + }, + awakening = { + on_enter = function() + print(" script state.awakening.on_enter") + end, + on_tick = function() + print(" script state.awakening.on_tick") + end, + on_exit = function() + print(" script state.awakening.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() calling charGoTo()") + charGoTo("blah") + print("main() resuming from charGoTo()") +end + Property changes on: trunk/yake/common/media/scripts/o_fsm_test.lua ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/yake/common/media/vehicles/delorean.xml =================================================================== --- trunk/yake/common/media/vehicles/delorean.xml 2006-09-13 22:50:25 UTC (rev 1464) +++ trunk/yake/common/media/vehicles/delorean.xml 2006-09-14 20:56:35 UTC (rev 1465) @@ -1,52 +1,52 @@ -<dotvehicle> - <vehicleTemplate name="delorean"> - <!-- chassis --> - <chassis> - <body totalMass="1.5" /> - <shapeSet> - <box x="1.70" y="0.6" z="4" material="chassis"> - <!--<materialRef ref="chassis" />--> - <!--<material inheritsFrom="default" friction="0.07" />--> - <position x="0" y="0" z="0" /> - </box> - <box x="1.30" y="0.3" z="1.8" material="chassisTop"> - <position x="0" y="0.45" z="-0.4" /> - </box> - </shapeSet> - </chassis> - <!-- two axles --> - <axle name="front" /> - <axle name="rear" /> - <!-- engine --> - <engine name="main" type="CarEngine" axle="rear"> - <rpm min="300" max="6000" redline="5000" /> - <curves> - <curve name="max_torque"> - </curve> - </curves> - <gearBox> - <gear id="0" mode="reverse" ratio="-2.90" /> - <gear id="1" mode="neutral" /> - <gear id="2" mode="forward" ratio="2.66" /> - <gear id="3" mode="forward" ratio="1.78" /> - <gear id="4" mode="forward" ratio="1.30" /> - <gear id="5" mode="forward" ratio="0.74" /> - <gear id="6" mode="forward" ratio="0.50" /> - </gearBox> - </engine> - <!-- wheels --> - <steeringGroup index="0" /> - <wheel name="leftFrontWheel" material="wheel" axle="front" steeringGroup="0" radius="0.275" mass="0.018" massIsRelativeToChassis="yes" suspensionSpring="30" suspensionDamping="3"> - <position x="-0.78" y="-0.4" z="1.18" /> - </wheel> - <wheel name="rightFrontWheel" material="wheel" axle="front" steeringGroup="0" radius="0.275" mass="0.018" massIsRelativeToChassis="yes" suspensionSpring="30" suspensionDamping="3"> - <position x="0.78" y="-0.4" z="1.18" /> - </wheel> - <wheel name="leftRearWheel" material="wheel" axle="rear" radius="0.275" mass="0.018" massIsRelativeToChassis="yes" suspensionSpring="30" suspensionDamping="3"> - <position x="-0.78" y="-0.4" z="-1.1" /> - </wheel> - <wheel name="rightRearWheel" material="wheel" axle="rear" radius="0.275" mass="0.018" massIsRelativeToChassis="yes" suspensionSpring="30" suspensionDamping="3"> - <position x="0.78" y="-0.4" z="-1.1" /> - </wheel> - </vehicleTemplate> +<dotvehicle> + <vehicleTemplate name="delorean"> + <!-- chassis --> + <chassis> + <body totalMass="1.5" /> + <shapeSet> + <box x="1.70" y="0.6" z="4" material="chassis"> + <!--<materialRef ref="chassis" />--> + <!--<material inheritsFrom="default" friction="0.07" />--> + <position x="0" y="0" z="0" /> + </box> + <box x="1.30" y="0.3" z="1.8" material="chassisTop"> + <position x="0" y="0.45" z="-0.4" /> + </box> + </shapeSet> + </chassis> + <!-- two axles --> + <axle name="front" /> + <axle name="rear" /> + <!-- engine --> + <engine name="main" type="CarEngine" axle="rear"> + <rpm min="300" max="6000" redline="5000" /> + <curves> + <curve name="max_torque"> + </curve> + </curves> + <gearBox> + <gear id="0" mode="reverse" ratio="-2.90" /> + <gear id="1" mode="neutral" /> + <gear id="2" mode="forward" ratio="2.66" /> + <gear id="3" mode="forward" ratio="1.78" /> + <gear id="4" mode="forward" ratio="1.30" /> + <gear id="5" mode="forward" ratio="0.74" /> + <gear id="6" mode="forward" ratio="0.50" /> + </gearBox> + </engine> + <!-- wheels --> + <steeringGroup index="0" /> + <wheel name="leftFrontWheel" material="wheel" axle="front" steeringGroup="0" radius="0.275" mass="0.018" massIsRelativeToChassis="yes" suspensionSpring="30" suspensionDamping="3"> + <position x="-0.78" y="-0.4" z="1.18" /> + </wheel> + <wheel name="rightFrontWheel" material="wheel" axle="front" steeringGroup="0" radius="0.275" mass="0.018" massIsRelativeToChassis="yes" suspensionSpring="30" suspensionDamping="3"> + <position x="0.78" y="-0.4" z="1.18" /> + </wheel> + <wheel name="leftRearWheel" material="wheel" axle="rear" radius="0.275" mass="0.018" massIsRelativeToChassis="yes" suspensionSpring="30" suspensionDamping="3"> + <position x="-0.78" y="-0.4" z="-1.1" /> + </wheel> + <wheel name="rightRearWheel" material="wheel" axle="rear" radius="0.275" mass="0.018" massIsRelativeToChassis="yes" suspensionSpring="30" suspensionDamping="3"> + <position x="0.78" y="-0.4" z="-1.1" /> + </wheel> + </vehicleTemplate> </dotvehicle> \ No newline at end of file Property changes on: trunk/yake/common/media/vehicles/delorean.xml ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/yake/common/media/vehicles/jet.xml =================================================================== --- trunk/yake/common/media/vehicles/jet.xml 2006-09-13 22:50:25 UTC (rev 1464) +++ trunk/yake/common/media/vehicles/jet.xml 2006-09-14 20:56:35 UTC (rev 1465) @@ -1,75 +1,75 @@ -<dotvehicle> - <vehicleTemplate name="jet"> - <!-- chassis --> - <chassis> - <body totalMass="10" /> - <shapeSet> - <box x="3" y="1" z="10"> - <position x="0" y="0" z="0" /> - </box> - </shapeSet> - </chassis> - <!-- left thruster --> - <mountPoint name="left"> - <position x="7" y="0" z="0" /> - <direction x="1" y="0" z="0" /> - </mountPoint> - <engine name="left" type="MountedThruster" mountPoint="left"> - <forces min="0." max="10." dieOff="4" rise="8" /> - </engine> - <!-- right thruster --> - <mountPoint name="right"> - <position x="-7" y="0" z="0" /> - <direction x="-1" y="0" z="0" /> - </mountPoint> - <engine name="right" type="MountedThruster" mountPoint="right"> - <forces min="0." max="10." dieOff="4" rise="8" /> - </engine> - <!-- front thruster --> - <mountPoint name="front"> - <position x="0" y="0" z="7" /> - <direction x="0" y="0" z="1" /> - </mountPoint> - <engine name="backward" type="MountedThruster" mountPoint="front"> - <forces min="0." max="20." dieOff="4" rise="8" /> - </engine> - <!-- rear thruster --> - <mountPoint name="rear"> - <position x="0" y="0" z="-7" /> - <direction x="0" y="0" z="-1" /> - </mountPoint> - <engine name="forward" type="MountedThruster" mountPoint="rear"> - <forces min="0." max="80." dieOff="10" rise="20" /> - </engine> - <!-- bottom (upward) thruster --> - <mountPoint name="bottom"> - <position x="0" y="0" z="0" /> - <direction x="0" y="-1" z="0" /> - </mountPoint> - <engine name="upward" type="MountedThruster" mountPoint="bottom"> - <forces min="0." max="500." dieOff="10" rise="20" /> - </engine> - <!-- bottom (downward) thruster --> - <mountPoint name="top"> - <position x="0" y="0" z="0" /> - <direction x="0" y="1" z="0" /> - </mountPoint> - <engine name="downward" type="MountedThruster" mountPoint="top"> - <forces min="0." max="250." dieOff="10" rise="20" /> - </engine> - <!-- two axles --> - <axle name="front" /> - <axle name="rear" /> - <!-- wheels - one in front for steering, two at the rear end --> - <steeringGroup index="0" /> - <wheel name="frontWheel" axle="front" steeringGroup="0" radius="1.0" mass="0.05" massIsRelativeToChassis="yes" suspensionSpring="100" suspensionDamping="20"> - <position x="0" y="-3" z="5.5" /> - </wheel> - <wheel name="leftRearWheel" axle="rear" radius="1.0" mass="0.05" massIsRelativeToChassis="yes" suspensionSpring="150" suspensionDamping="20"> - <position x="-3" y="-3" z="-3" /> - </wheel> - <wheel name="rightRearWheel" axle="rear" radius="1.0" mass="0.05" massIsRelativeToChassis="yes" suspensionSpring="150" suspensionDamping="20"> - <position x="3" y="-3" z="-3" /> - </wheel> - </vehicleTemplate> -</dotvehicle> +<dotvehicle> + <vehicleTemplate name="jet"> + <!-- chassis --> + <chassis> + <body totalMass="10" /> + <shapeSet> + <box x="3" y="1" z="10"> + <position x="0" y="0" z="0" /> + </box> + </shapeSet> + </chassis> + <!-- left thruster --> + <mountPoint name="left"> + <position x="7" y="0" z="0" /> + <direction x="1" y="0" z="0" /> + </mountPoint> + <engine name="left" type="MountedThruster" mountPoint="left"> + <forces min="0." max="10." dieOff="4" rise="8" /> + </engine> + <!-- right thruster --> + <mountPoint name="right"> + <position x="-7" y="0" z="0" /> + <direction x="-1" y="0" z="0" /> + </mountPoint> + <engine name="right" type="MountedThruster" mountPoint="right"> + <forces min="0." max="10." dieOff="4" rise="8" /> + </engine> + <!-- front thruster --> + <mountPoint name="front"> + <position x="0" y="0" z="7" /> + <direction x="0" y="0" z="1" /> + </mountPoint> + <engine name="backward" type="MountedThruster" mountPoint="front"> + <forces min="0." max="20." dieOff="4" rise="8" /> + </engine> + <!-- rear thruster --> + <mountPoint name="rear"> + <position x="0" y="0" z="-7" /> + <direction x="0" y="0" z="-1" /> + </mountPoint> + <engine name="forward" type="MountedThruster" mountPoint="rear"> + <forces min="0." max="80." dieOff="10" rise="20" /> + </engine> + <!-- bottom (upward) thruster --> + <mountPoint name="bottom"> + <position x="0" y="0" z="0" /> + <direction x="0" y="-1" z="0" /> + </mountPoint> + <engine name="upward" type="MountedThruster" mountPoint="bottom"> + <forces min="0." max="500." dieOff="10" rise="20" /> + </engine> + <!-- bottom (downward) thruster --> + <mountPoint name="top"> + <position x="0" y="0" z="0" /> + <direction x="0" y="1" z="0" /> + </mountPoint> + <engine name="downward" type="MountedThruster" mountPoint="top"> + <forces min="0." max="250." dieOff="10" rise="20" /> + </engine> + <!-- two axles --> + <axle name="front" /> + <axle name="rear" /> + <!-- wheels - one in front for steering, two at the rear end --> + <steeringGroup index="0" /> + <wheel name="frontWheel" axle="front" steeringGroup="0" radius="1.0" mass="0.05" massIsRelativeToChassis="yes" suspensionSpring="100" suspensionDamping="20"> + <position x="0" y="-3" z="5.5" /> + </wheel> + <wheel name="leftRearWheel" axle="rear" radius="1.0" mass="0.05" massIsRelativeToChassis="yes" suspensionSpring="150" suspensionDamping="20"> + <position x="-3" y="-3" z="-3" /> + </wheel> + <wheel name="rightRearWheel" axle="rear" radius="1.0" mass="0.05" massIsRelativeToChassis="yes" suspensionSpring="150" suspensionDamping="20"> + <position x="3" y="-3" z="-3" /> + </wheel> + </vehicleTemplate> +</dotvehicle> Property changes on: trunk/yake/common/media/vehicles/jet.xml ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/yake/common/media/vehicles/jet2.xml =================================================================== --- trunk/yake/common/media/vehicles/jet2.xml 2006-09-13 22:50:25 UTC (rev 1464) +++ trunk/yake/common/media/vehicles/jet2.xml 2006-09-14 20:56:35 UTC (rev 1465) @@ -1,97 +1,97 @@ -<dotvehicle> - <import type="dotVehicle" src="common_vehicle_components.vehicle.xml" /> - - <!-- declare "Jet" templates --> - <wheelTemplate name="jet_rear_wheel" axle="rear" radius="0.5" totalMass="1" /> - <engineTemplate name="jet_ground_engine" type="CarEngine"> - <gearbox numGears="2"> - <gear idx=0 type="backward" rpm="1000" /> - <gear idx=1 type="forward" rpm="blah" /> - </gearbox> - </engineTemplate> - <vehicleTemplate name="jet"> - <!-- chassis --> - <chassis> - <body totalMass="10"> - </body> - <shapeset> - <box x="1.5" y="1" z="2"> - <position x="0" y="0" z="0" /> - </box> - </shapeset> - </chassis> - <!-- front thruster --> - <mountPoint name="front_reverse"> - <position x="-2" y="0" z="1" /> - <direction x="0" y="0" z="-1" /> - </mountPoint> - <engine name="front_reverse" type="MountedThruster" mountPoint="front_reverse"> - <forces min="0." max="10." dieOff="4" rise="8" /> - </engine> - <!-- two main thrusters at the back - both are controlled by a single mount point --> - <mountPoint name="main_accel"> - <position x="0" y="0" z="-1" /> - <direction x="0" y="0" z="1" /> - <mountPoint name="main_accel_left"> - <position x="-0.8" y="0" z="0" /> - </mountPoint> - <mountPoint name="main_accel_right"> - <position x="0.8" y="0" z="0" /> - </mountPoint> - </mountPoint> - <engine name="main_left" type="MountedThruster" mountPoint="main_accel_left"> - <forces min="0." max="80." dieOff="40." rise="60." /> - </engine> - <engine name="main_right" type="MountedThruster" mountPoint="main_accel_right"> - <forces min="0." max="80." dieOff="40." rise="60." /> - </engine> - <!-- 3 wheels (one in front, two at the back) - Therefore we need two axles (front,back). - We also use a single engine to power the rear wheels. - The front wheel is used for steering. - --> - <axle name="front" /> - <axle name="rear" /> - <engine tpl="jet_ground_engine" axle="rear" /> <!-- NOTE: We create the engine from a template! --> - <steeringGroup name="front" /> - <!-- Explicitely define wheel: --> - <wheel name="front" axle="front" radius="0.3" totalMass="1" steeringGroup="front" > - <position x="0" y="-0.5" z="0.9" /> - <orientation /> - </wheel> - <!-- Define rear wheels by using the wheel template "jet_rear_wheel": --> - <wheel tpl="jet_rear_wheel"> - <position x="-0.5" y="-0.5" z="-0.2" /> - <orientation /> - </wheel> - <wheel tpl="jet_rear_wheel"> - <position x="0.5" y="-0.5" z="-0.2" /> - <orientation /> - </wheel> - </vehicleTemplate> - - <!-- visual vehicle representation --> - <vehicleVisuals name="jet_default_visuals" tpl="jet"> - <graphical name="small_wheel" src="blah.scene" /> - <graphical name="rear_wheel"> - <scenenode name="wheel_sn"> - <entity meshFile="rear_wheel.mesh" /> - </scenenode> - </graphical> - <link type="movable"> - <source type="wheel" name="front" /> - <target type="graphical" name="small_wheel" /> - </link> - <link type="movable"> - <source type="wheel" name="rear_left" /> - <target type="graphical" name="rear_wheel" /> - </link> - <link type="movable"> - <source type="wheel" name="rear_left" /> - <target type="graphical" name="rear_wheel" /> - </link> - </vehicleVisuals> - - <!-- instantiate vehicle --> - <vehicleInstance tpl="jet" /> +<dotvehicle> + <import type="dotVehicle" src="common_vehicle_components.vehicle.xml" /> + + <!-- declare "Jet" templates --> + <wheelTemplate name="jet_rear_wheel" axle="rear" radius="0.5" totalMass="1" /> + <engineTemplate name="jet_ground_engine" type="CarEngine"> + <gearbox numGears="2"> + <gear idx=0 type="backward" rpm="1000" /> + <gear idx=1 type="forward" rpm="blah" /> + </gearbox> + </engineTemplate> + <vehicleTemplate name="jet"> + <!-- chassis --> + <chassis> + <body totalMass="10"> + </body> + <shapeset> + <box x="1.5" y="1" z="2"> + <position x="0" y="0" z="0" /> + </box> + </shapeset> + </chassis> + <!-- front thruster --> + <mountPoint name="front_reverse"> + <position x="-2" y="0" z="1" /> + <direction x="0" y="0" z="-1" /> + </mountPoint> + <engine name="front_reverse" type="MountedThruster" mountPoint="front_reverse"> + <forces min="0." max="10." dieOff="4" rise="8" /> + </engine> + <!-- two main thrusters at the back - both are controlled by a single mount point --> + <mountPoint name="main_accel"> + <position x="0" y="0" z="-1" /> + <direction x="0" y="0" z="1" /> + <mountPoint name="main_accel_left"> + <position x="-0.8" y="0" z="0" /> + </mountPoint> + <mountPoint name="main_accel_right"> + <position x="0.8" y="0" z="0" /> + </mountPoint> + </mountPoint> + <engine name="main_left" type="MountedThruster" mountPoint="main_accel_left"> + <forces min="0." max="80." dieOff="40." rise="60." /> + </engine> + <engine name="main_right" type="MountedThruster" mountPoint="main_accel_right"> + <forces min="0." max="80." dieOff="40." rise="60." /> + </engine> + <!-- 3 wheels (one in front, two at the back) + Therefore we need two axles (front,back). + We also use a single engine to power the rear wheels. + The front wheel is used for steering. + --> + <axle name="front" /> + <axle name="rear" /> + <engine tpl="jet_ground_engine" axle="rear" /> <!-- NOTE: We create the engine from a template! --> + <steeringGroup name="front" /> + <!-- Explicitely define wheel: --> + <wheel name="front" axle="front" radius="0.3" totalMass="1" steeringGroup="front" > + <position x="0" y="-0.5" z="0.9" /> + <orientation /> + </wheel> + <!-- Define rear wheels by using the wheel template "jet_rear_wheel": --> + <wheel tpl="jet_rear_wheel"> + <position x="-0.5" y="-0.5" z="-0.2" /> + <orientation /> + </wheel> + <wheel tpl="jet_rear_wheel"> + <position x="0.5" y="-0.5" z="-0.2" /> + <orientation /> + </wheel> + </vehicleTemplate> + + <!-- visual vehicle representation --> + <vehicleVisuals name="jet_default_visuals" tpl="jet"> + <graphical name="small_wheel" src="blah.scene" /> + <graphical name="rear_wheel"> + <scenenode name="wheel_sn"> + <entity meshFile="rear_wheel.mesh" /> + </scenenode> + </graphical> + <link type="movable"> + <source type="wheel" name="front" /> + <target type="graphical" name="small_wheel" /> + </link> + <link type="movable"> + <source type="wheel" name="rear_left" /> + <target type="graphical" name="rear_wheel" /> + </link> + <link type="movable"> + <source type="wheel" name="rear_left" /> + <target type="graphical" name="rear_wheel" /> + </link> + </vehicleVisuals> + + <!-- instantiate vehicle --> + <vehicleInstance tpl="jet" /> </dotvehicle> \ No newline at end of file Property changes on: trunk/yake/common/media/vehicles/jet2.xml ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/yake/documentation/api/docMainPage.h =================================================================== --- trunk/yake/documentation/api/docMainPage.h 2006-09-13 22:50:25 UTC (rev 1464) +++ trunk/yake/documentation/api/docMainPage.h 2006-09-14 20:56:35 UTC (rev 1465) @@ -1,27 +1,27 @@ -/** \mainpage "YAKE 0.5.0dev API" - -!!! YAKE 0.5.0dev API Documentation - - -!! What is this? - -This is the API documentation for YAKE. It contains specifications for each class, method and variable which can be used in code you write. - -!! Where do I start? - -The API documentation is most useful as a reference to YAKE. It is not intended to be a guide which introduces you to developing software with YAKE. -If you know your way around YAKE the reference documentation will become handy and you will want to make use of it. - -To get started with the concepts and basics of YAKE you should refer to the more discussive material in the manual and tutorials. -You find these in the Wiki (http://www.yake.org/wiki). If you don't find what you search either in the Wiki or the API reference then -you may want to try out the community features and get in contact with YAKE's developers and users. Information on forums, IRC and other ways of contact can be found at the YAKE website (http://www.yake.org). - - - - - -Copyright (C) The YAKE Team - -Permission is granted to make and distribute verbatim copies of this API documentation provided the copyright notice and this permission notice are preserved on all copies. - -*/ +/** \mainpage "YAKE 0.5.0dev API" + +!!! YAKE 0.5.0dev API Documentation + + +!! What is this? + +This is the API documentation for YAKE. It contains specifications for each class, method and variable which can be used in code you write. + +!! Where do I start? + +The API documentation is most useful as a reference to YAKE. It is not intended to be a guide which introduces you to developing software with YAKE. +If you know your way around YAKE the reference documentation will become handy and you will want to make use of it. + +To get started with the concepts and basics of YAKE you should refer to the more discussive material in the manual and tutorials. +You find these in the Wiki (http://www.yake.org/wiki). If you don't find what you search either in the Wiki or the API reference then +you may want to try out the community features and get in contact with YAKE's developers and users. Information on forums, IRC and other ways of contact can be found at the YAKE website (http://www.yake.org). + + + + + +Copyright (C) The YAKE Team + +Permission is granted to make and distribute verbatim copies of this API documentation provided the copyright notice and this permission notice are preserved on all copies. + +*/ Property changes on: trunk/yake/documentation/api/docMainPage.h ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/yake/samples/README.TXT =================================================================== --- trunk/yake/samples/README.TXT 2006-09-13 22:50:25 UTC (rev 1464) +++ trunk/yake/samples/README.TXT 2006-09-14 20:56:35 UTC (rev 1465) @@ -1,30 +1,30 @@ -Overview over the sampels - - -debug -scripted_entity -custom_entity -vehicle1 -sync1 -dotlink -fsm -audio3d -raf_simple -raf_most_systems -gui_console - - -sampleDebug - debug output - -sampleScriptedEntity - scripting entities (callbacks, states, events and more) -sampleCustomEntity - how to implement a new entity -sampleVehicle1 - different vehicles can be controlled (car,jet, uses RAF, entities and models) -sampleSync1 - decoupled, interpolated physics and graphics systems -sampleDotLink - how to tie .link, .scene and .xode together -sampleFSM - simple finite state machine demo -sampleAudio3d - how to use the audio system for playing 3D sounds - -sampleRafSimple - bare-bones RAF application -sampleRafMostSystems - initialisation of most systems (graphics, physics, scripting etc) - -sampleGuiConsole - a CEGUI-based console with history to script Yake applications using Lua +Overview over the sampels + + +debug +scripted_entity +custom_entity +vehicle1 +sync1 +dotlink +fsm +audio3d +raf_simple +raf_most_systems +gui_console + + +sampleDebug - debug output + +sampleScriptedEntity - scripting entities (callbacks, states, events and more) +sampleCustomEntity - how to implement a new entity +sampleVehicle1 - different vehicles can be controlled (car,jet, uses RAF, entities and models) +sampleSync1 - decoupled, interpolated physics and graphics systems +sampleDotLink - how to tie .link, .scene and .xode together +sampleFSM - simple finite state machine demo +sampleAudio3d - how to use the audio system for playing 3D sounds + +sampleRafSimple - bare-bones RAF application +sampleRafMostSystems - initialisation of most systems (graphics, physics, scripting etc) + +sampleGuiConsole - a CEGUI-based console with history to script Yake applications using Lua Property changes on: trunk/yake/samples/README.TXT ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/yake/scripts/msvc71/samples/misc/sampleCar.vcproj =================================================================== --- trunk/yake/scripts/msvc71/samples/misc/sampleCar.vcproj 2006-09-13 22:50:25 UTC (rev 1464) +++ trunk/yake/scripts/msvc71/samples/misc/sampleCar.vcproj 2006-09-14 20:56:35 UTC (rev 1465) @@ -1,156 +1,156 @@ -<?xml version="1.0" encoding="Windows-1252"?> -<VisualStudioProject - ProjectType="Visual C++" - Version="7.10" - Name="sampleCar" - ProjectGUID="{EE77E955-42BD-47A4-BDC6-D92759F45D01}" - Keyword="Win32Proj"> - <Platforms> - <Platform - Name="Win32"/> - </Platforms> - <Configurations> - <Configuration - Name="Debug|Win32" - OutputDirectory="../../../../common/bin/debug" - IntermediateDirectory="../../../../common/obj/debug/$(ProjectName)" - ConfigurationType="1" - CharacterSet="2"> - <Tool - Name="VCCLCompilerTool" - Optimization="0" - AdditionalIncludeDirectories="../../../../;../../../../dependencies/boost/;../../../../dependencies/ttl/" - PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE" - MinimalRebuild="TRUE" - BasicRuntimeChecks="3" - RuntimeLibrary="3" - RuntimeTypeInfo="TRUE" - UsePrecompiledHeader="3" - PrecompiledHeaderThrough="yapp/samples/misc/car/yakePCH.h" - WarningLevel="3" - Detect64BitPortabilityProblems="TRUE" - DebugInformationFormat="4"/> - <Tool - Name="VCCustomBuildTool"/> - <Tool - Name="VCLinkerTool" - AdditionalDependencies="base.lib graphics.lib physics.lib audio.lib data.lib input.lib yapp.lib scripting.lib vehicle.lib" - OutputFile="$(OutDir)/$(ProjectName).exe" - LinkIncremental="2" - AdditionalLibraryDirectories="../../../../common/lib/debug;../../../../dependencies/lib" - GenerateDebugInformation="TRUE" - ProgramDatabaseFile="$(OutDir)/$(ProjectName).pdb" - SubSystem="1" - TargetMachine="1"/> - <Tool - Name="VCMIDLTool"/> - <Tool - Name="VCPostBuildEventTool"/> - <Tool - Name="VCPreBuildEventTool"/> - <Tool - Name="VCPreLinkEventTool"/> - <Tool - Name="VCResourceCompilerTool"/> - <Tool - Name="VCWebServiceProxyGeneratorTool"/> - <Tool - Name="VCXMLDataGeneratorTool"/> - <Tool - Name="VCWebDeploymentTool"/> - <Tool - Name="VCManagedWrapperGeneratorTool"/> - <Tool - Name="VCAuxiliaryManagedWrapperGeneratorTool"/> - </Configuration> - <Configuration - Name="Release|Win32" - OutputDirectory="../../../../common/bin/release" - IntermediateDirectory="../../../../common/obj/release/$(ProjectName)" - ConfigurationType="1" - CharacterSet="2"> - <Tool - Name="VCCLCompilerTool" - AdditionalIncludeDirectories="../../../../;../../../../dependencies/boost/;../../../../dependencies/ttl/" - PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE" - RuntimeLibrary="2" - RuntimeTypeInfo="TRUE" - UsePrecompiledHeader="3" - PrecompiledHeaderThrough="yapp/samples/misc/car/yakePCH.h" - WarningLevel="3" - Detect64BitPortabilityProblems="TRUE" - DebugInformationFormat="3"/> - <Tool - Name="VCCustomBuildTool"/> - <Tool - Name="VCLinkerTool" - AdditionalDependencies="base.lib graphics.lib physics.lib audio.lib data.lib input.lib yapp.lib scripting.lib vehicle.lib" - OutputFile="$(OutDir)/$(ProjectName).exe" - LinkIncremental="1" - AdditionalLibraryDirectories="../../../../common/lib/release;../../../../dependencies/lib" - GenerateDebugInformation="FALSE" - SubSystem="1" - OptimizeReferences="2" - EnableCOMDATFolding="2" - TargetMachine="1"/> - <Tool - Name="VCMIDLTool"/> - <Tool - Name="VCPostBuildEventTool"/> - <Tool - Name="VCPreBuildEventTool"/> - <Tool - Name="VCPreLinkEventTool"/> - <Tool - Name="VCResourceCompilerTool"/> - <Tool - Name="VCWebServiceProxyGeneratorTool"/> - <Tool - Name="VCXMLDataGeneratorTool"/> - <Tool - Name="VCWebDeploymentTool"/> - <Tool - Name="VCManagedWrapperGeneratorTool"/> - <Tool - Name="VCAuxiliaryManagedWrapperGeneratorTool"/> - </Configuration> - </Configurations> - <References> - </References> - <Files> - <Filter - Name="inc" ... [truncated message content] |
From: <psy...@us...> - 2006-09-14 21:46:06
|
Revision: 1466 http://svn.sourceforge.net/yake/?rev=1466&view=rev Author: psyclonist Date: 2006-09-14 14:45:38 -0700 (Thu, 14 Sep 2006) Log Message: ----------- reverted to original custom random number generator instead of boost's as the latter seems to be unmaintained. Modified Paths: -------------- trunk/yake/scripts/msvc8/base.vcproj trunk/yake/src/yake/plugins/baseLuaBindings/yakeLuaBinder.cpp trunk/yake/src/yake/samples/physics/demo/yakeDemo.cpp trunk/yake/yake/base/math/yakeRand.h Added Paths: ----------- trunk/yake/src/yake/base/math/yakeRand.cpp trunk/yake/yake/base/math/yakeMersenneTwister.h Modified: trunk/yake/scripts/msvc8/base.vcproj =================================================================== --- trunk/yake/scripts/msvc8/base.vcproj 2006-09-14 20:56:35 UTC (rev 1465) +++ trunk/yake/scripts/msvc8/base.vcproj 2006-09-14 21:45:38 UTC (rev 1466) @@ -365,6 +365,10 @@ > </File> <File + RelativePath="..\..\src\yake\base\math\yakeRand.cpp" + > + </File> + <File RelativePath="..\..\src\yake\base\math\yakeRay.cpp" > </File> Added: trunk/yake/src/yake/base/math/yakeRand.cpp =================================================================== --- trunk/yake/src/yake/base/math/yakeRand.cpp (rev 0) +++ trunk/yake/src/yake/base/math/yakeRand.cpp 2006-09-14 21:45:38 UTC (rev 1466) @@ -0,0 +1,78 @@ +/* + ------------------------------------------------------------------------------------ + This file is part of YAKE + Copyright \xA9 2004 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/math/yakeRand.h> +#include <yake/base/math/yakeMersenneTwister.h> + +namespace yake { +namespace math { + + //--------------------------------------------------- + RandomNumberGeneratorMT::RandomNumberGeneratorMT() + { + mRand = new MTRand(); + setSeed( 54738 ); + } + + //--------------------------------------------------- + RandomNumberGeneratorMT::~RandomNumberGeneratorMT() + { + YAKE_SAFE_DELETE( mRand ); + } + + //--------------------------------------------------- + real RandomNumberGeneratorMT::operator()() + { + return (real) mRand->rand(); + } + + //--------------------------------------------------- + uint32 RandomNumberGeneratorMT::randInt() + { + return mRand->randInt(); + } + + //--------------------------------------------------- + real RandomNumberGeneratorMT::randReal() + { + return (real) mRand->rand(); + } + + //--------------------------------------------------- + void RandomNumberGeneratorMT::setSeed( uint32 seed ) + { + mSeed = seed; + mRand->seed( mSeed ); + } + + //--------------------------------------------------- + uint32 RandomNumberGeneratorMT::getSeed() const + { + return mSeed; + } +} +} Modified: trunk/yake/src/yake/plugins/baseLuaBindings/yakeLuaBinder.cpp =================================================================== --- trunk/yake/src/yake/plugins/baseLuaBindings/yakeLuaBinder.cpp 2006-09-14 20:56:35 UTC (rev 1465) +++ trunk/yake/src/yake/plugins/baseLuaBindings/yakeLuaBinder.cpp 2006-09-14 21:45:38 UTC (rev 1466) @@ -129,14 +129,15 @@ ]; // RandomNumberGenerator - typedef RandomNumberGeneratorMT<real> rng_type; + typedef RandomNumberGenerator rng_type; module( YAKE_MATH_MODULE ) [ class_< rng_type >( "RandomNumberGenerator" ) .def( constructor<>() ) .def( "setSeed", &rng_type::setSeed ) .def( "getSeed", &rng_type::getSeed ) - .def( "rand", &rng_type::rand ) + .def( "randInt", &rng_type::randInt ) + .def( "randReal", &rng_type::randReal ) ]; } Modified: trunk/yake/src/yake/samples/physics/demo/yakeDemo.cpp =================================================================== --- trunk/yake/src/yake/samples/physics/demo/yakeDemo.cpp 2006-09-14 20:56:35 UTC (rev 1465) +++ trunk/yake/src/yake/samples/physics/demo/yakeDemo.cpp 2006-09-14 21:45:38 UTC (rev 1466) @@ -436,20 +436,20 @@ #endif // spawn the object const Vector3 spawnOffset = bUseWorldOne ? Vector3(-5,0,0) : Vector3(5,0,0); - const Vector3 spawnPos = spawnOffset + Vector3(randomiser.rand()*0.5,10,randomiser.rand()*0.5); + const Vector3 spawnPos = spawnOffset + Vector3(randomiser.randReal()*0.5,10,randomiser.randReal()*0.5); objs.push_back( SharedPtr<Simple>( new Simple( pPWorld ) ) ); SharedPtr<Simple> last = objs.back(); - std::cout << randomiser.rand() << "\n"; + std::cout << randomiser.randReal() << "\n"; - if (randomiser.rand() < 0.5) + if (randomiser.randReal() < 0.5) createBox( pPWorld, *objs.back(), spawnPos, // position - Vector3(randomiser.rand()*3,1,randomiser.rand()*2) ); // dimensions + Vector3(randomiser.randReal()*3,1,randomiser.randReal()*2) ); // dimensions else createBall( pPWorld, *objs.back(), spawnPos, // position - randomiser.rand()*2 ); //dimension/radius + randomiser.randReal()*2 ); //dimension/radius // objs.push_back( SharedPtr<Simple>( new Simple( pPWorld ) ) ); Added: trunk/yake/yake/base/math/yakeMersenneTwister.h =================================================================== --- trunk/yake/yake/base/math/yakeMersenneTwister.h (rev 0) +++ trunk/yake/yake/base/math/yakeMersenneTwister.h 2006-09-14 21:45:38 UTC (rev 1466) @@ -0,0 +1,434 @@ +// MersenneTwister.h +// Mersenne Twister random number generator -- a C++ class MTRand +// Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus +// Richard J. Wagner v1.0 15 May 2003 rjw...@wr... + +// The Mersenne Twister is an algorithm for generating random numbers. It +// was designed with consideration of the flaws in various other generators. +// The period, 2^19937-1, and the order of equidistribution, 623 dimensions, +// are far greater. The generator is also fast; it avoids multiplication and +// division, and it benefits from caches and pipelines. For more information +// see the inventors' web page at http://www.math.keio.ac.jp/~matumoto/emt.html + +// Reference +// M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-Dimensionally +// Equidistributed Uniform Pseudo-Random Number Generator", ACM Transactions on +// Modeling and Computer Simulation, Vol. 8, No. 1, January 1998, pp 3-30. + +// Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, +// Copyright (C) 2000 - 2003, Richard J. Wagner +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// +// 3. The names of its contributors may not be used to endorse or promote +// products derived from this software without specific prior written +// permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// The original code included the following notice: +// +// When you use this, send an email to: mat...@ma... +// with an appropriate reference to your work. +// +// It would be nice to CC: rjw...@wr... and Co...@ma... +// when you write. + +#ifndef YAKE_BASE_MATH_MERSENNETWISTER_H +#define YAKE_BASE_MATH_MERSENNETWISTER_H + +// Not thread safe (unless auto-initialization is avoided and each thread has +// its own MTRand object) + +//============================================================================ +// IMPLEMENTATION HEADERS +//============================================================================ +// Standard headers +#ifndef YAKE_BASE_PREREQUISITES_H +# include "yakePrerequisites.h" +#endif + +//============================================================================ +// INTERFACE STRUCTURES / UTILITY CLASSES +//============================================================================ +namespace yake { +namespace math { + +class MTRand { +// Data +public: + typedef unsigned long uint32; // unsigned integer type, at least 32 bits + + enum { N = 624 }; // length of state vector + enum { SAVE = N + 1 }; // length of array for save() + +protected: + enum { M = 397 }; // period parameter + + uint32 state[N]; // internal state + uint32 *pNext; // next value to get from state + int left; // number of values left before reload needed + + +//Methods +public: + MTRand( const uint32& oneSeed ); // initialize with a simple uint32 + MTRand( uint32 *const bigSeed, uint32 const seedLength = N ); // or an array + MTRand(); // auto-initialize with /dev/urandom or time() and clock() + + // Do NOT use for CRYPTOGRAPHY without securely hashing several returned + // values together, otherwise the generator state can be learned after + // reading 624 consecutive values. + + // Access to 32-bit random numbers + double rand(); // real number in [0,1] + double rand( const double& n ); // real number in [0,n] + double randExc(); // real number in [0,1) + double randExc( const double& n ); // real number in [0,n) + double randDblExc(); // real number in (0,1) + double randDblExc( const double& n ); // real number in (0,n) + uint32 randInt(); // integer in [0,2^32-1] + uint32 randInt( const uint32& n ); // integer in [0,n] for n < 2^32 + double operator()() { return rand(); } // same as rand() + + // Access to 53-bit random numbers (capacity of IEEE double precision) + double rand53(); // real number in [0,1) + + // Access to nonuniform random number distributions + double randNorm( const double& mean = 0.0, const double& variance = 0.0 ); + + // Re-seeding functions with same behavior as initializers + void seed( const uint32 oneSeed ); + void seed( uint32 *const bigSeed, const uint32 seedLength = N ); + void seed(); + + // Saving and loading generator state + void save( uint32* saveArray ) const; // to array of size SAVE + void load( uint32 *const loadArray ); // from such array + friend std::ostream& operator<<( std::ostream& os, const MTRand& mtrand ); + friend std::istream& operator>>( std::istream& is, MTRand& mtrand ); + +protected: + void initialize( const uint32 oneSeed ); + void reload(); + uint32 hiBit( const uint32& u ) const { return u & 0x80000000UL; } + uint32 loBit( const uint32& u ) const { return u & 0x00000001UL; } + uint32 loBits( const uint32& u ) const { return u & 0x7fffffffUL; } + uint32 mixBits( const uint32& u, const uint32& v ) const + { return hiBit(u) | loBits(v); } + uint32 twist( const uint32& m, const uint32& s0, const uint32& s1 ) const + { return m ^ (mixBits(s0,s1)>>1) ^ (/*-*/loBit(s1) & 0x9908b0dfUL); } // todo ok? + static uint32 hash( time_t t, clock_t c ); +}; + + +inline MTRand::MTRand( const uint32& oneSeed ) + { seed(oneSeed); } + +inline MTRand::MTRand( uint32 *const bigSeed, const uint32 seedLength ) + { seed(bigSeed,seedLength); } + +inline MTRand::MTRand() + { seed(); } + +inline double MTRand::rand() + { return double(randInt()) * (1.0/4294967295.0); } + +inline double MTRand::rand( const double& n ) + { return rand() * n; } + +inline double MTRand::randExc() + { return double(randInt()) * (1.0/4294967296.0); } + +inline double MTRand::randExc( const double& n ) + { return randExc() * n; } + +inline double MTRand::randDblExc() + { return ( double(randInt()) + 0.5 ) * (1.0/4294967296.0); } + +inline double MTRand::randDblExc( const double& n ) + { return randDblExc() * n; } + +inline double MTRand::rand53() +{ + uint32 a = randInt() >> 5, b = randInt() >> 6; + return ( a * 67108864.0 + b ) * (1.0/9007199254740992.0); // by Isaku Wada +} + +inline double MTRand::randNorm( const double& mean, const double& variance ) +{ + // Return a real number from a normal (Gaussian) distribution with given + // mean and variance by Box-Muller method + double r = sqrt( -2.0 * log( 1.0-randDblExc()) ) * variance; + double phi = 2.0 * 3.14159265358979323846264338328 * randExc(); + return mean + r * cos(phi); +} + +inline MTRand::uint32 MTRand::randInt() +{ + // Pull a 32-bit integer from the generator state + // Every other access function simply transforms the numbers extracted here + + if( left == 0 ) reload(); + --left; + + register uint32 s1; + s1 = *pNext++; + s1 ^= (s1 >> 11); + s1 ^= (s1 << 7) & 0x9d2c5680UL; + s1 ^= (s1 << 15) & 0xefc60000UL; + return ( s1 ^ (s1 >> 18) ); +} + +inline MTRand::uint32 MTRand::randInt( const uint32& n ) +{ + // Find which bits are used in n + // Optimized by Magnus Jonsson (ma...@sm...) + uint32 used = n; + used |= used >> 1; + used |= used >> 2; + used |= used >> 4; + used |= used >> 8; + used |= used >> 16; + + // Draw numbers until one is found in [0,n] + uint32 i; + do + i = randInt() & used; // toss unused bits to shorten search + while( i > n ); + return i; +} + + +inline void MTRand::seed( const uint32 oneSeed ) +{ + // Seed the generator with a simple uint32 + initialize(oneSeed); + reload(); +} + + +inline void MTRand::seed( uint32 *const bigSeed, const uint32 seedLength ) +{ + // Seed the generator with an array of uint32's + // There are 2^19937-1 possible initial states. This function allows + // all of those to be accessed by providing at least 19937 bits (with a + // default seed length of N = 624 uint32's). Any bits above the lower 32 + // in each element are discarded. + // Just call seed() if you want to get array from /dev/urandom + initialize(19650218UL); + register int i = 1; + register uint32 j = 0; + register int k = ( N > seedLength ? N : seedLength ); + for( ; k; --k ) + { + state[i] = + state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1664525UL ); + state[i] += ( bigSeed[j] & 0xffffffffUL ) + j; + state[i] &= 0xffffffffUL; + ++i; ++j; + if( i >= N ) { state[0] = state[N-1]; i = 1; } + if( j >= seedLength ) j = 0; + } + for( k = N - 1; k; --k ) + { + state[i] = + state[i] ^ ( (state[i-1] ^ (state[i-1] >> 30)) * 1566083941UL ); + state[i] -= i; + state[i] &= 0xffffffffUL; + ++i; + if( i >= N ) { state[0] = state[N-1]; i = 1; } + } + state[0] = 0x80000000UL; // MSB is 1, assuring non-zero initial array + reload(); +} + + +inline void MTRand::seed() +{ + // Seed the generator with an array from /dev/urandom if available + // Otherwise use a hash of time() and clock() values + + // First try getting an array from /dev/urandom + FILE* urandom = fopen( "/dev/urandom", "rb" ); + if( urandom ) + { + uint32 bigSeed[N]; + register uint32 *s = bigSeed; + register int i = N; + register bool success = true; + while( success && i-- ) + success = !!fread( s++, sizeof(uint32), 1, urandom ); // /SGB !! eliminates bool-to-int performance warning + fclose(urandom); + if( success ) { seed( bigSeed, N ); return; } + } + + // Was not successful, so use time() and clock() instead + seed( hash( time(NULL), clock() ) ); +} + + +inline void MTRand::initialize( const uint32 seed ) +{ + // Initialize generator state with seed + // See Knuth TAOCP Vol 2, 3rd Ed, p.106 for multiplier. + // In previous versions, most significant bits (MSBs) of the seed affect + // only MSBs of the state array. Modified 9 Jan 2002 by Makoto Matsumoto. + register uint32 *s = state; + register uint32 *r = state; + register int i = 1; + *s++ = seed & 0xffffffffUL; + for( ; i < N; ++i ) + { + *s++ = ( 1812433253UL * ( *r ^ (*r >> 30) ) + i ) & 0xffffffffUL; + r++; + } +} + + +inline void MTRand::reload() +{ + // Generate N new values in state + // Made clearer and faster by Matthew Bellew (mat...@ho...) + register uint32 *p = state; + register int i; + for( i = N - M; i--; ++p ) + *p = twist( p[M], p[0], p[1] ); + for( i = M; --i; ++p ) + *p = twist( p[M-N], p[0], p[1] ); + *p = twist( p[M-N], p[0], state[0] ); + + left = N, pNext = state; +} + + +inline MTRand::uint32 MTRand::hash( time_t t, clock_t c ) +{ + // Get a uint32 from t and c + // Better than uint32(x) in case x is floating point in [0,1] + // Based on code by Lawrence Kirby (fr...@ge...) + + static uint32 differ = 0; // guarantee time-based seeds will change + + uint32 h1 = 0; + unsigned char *p = (unsigned char *) &t; + for( size_t i = 0; i < sizeof(t); ++i ) + { + h1 *= UCHAR_MAX + 2U; + h1 += p[i]; + } + uint32 h2 = 0; + p = (unsigned char *) &c; + for( size_t j = 0; j < sizeof(c); ++j ) + { + h2 *= UCHAR_MAX + 2U; + h2 += p[j]; + } + return ( h1 + differ++ ) ^ h2; +} + + +inline void MTRand::save( uint32* saveArray ) const +{ + register uint32 *sa = saveArray; + register const uint32 *s = state; + register int i = N; + for( ; i--; *sa++ = *s++ ) {} + *sa = left; +} + + +inline void MTRand::load( uint32 *const loadArray ) +{ + register uint32 *s = state; + register uint32 *la = loadArray; + register int i = N; + for( ; i--; *s++ = *la++ ) {} + left = *la; + pNext = &state[N-left]; +} + + +inline std::ostream& operator<<( std::ostream& os, const MTRand& mtrand ) +{ + register const MTRand::uint32 *s = mtrand.state; + register int i = mtrand.N; + for( ; i--; os << *s++ << "\t" ) {} + return os << mtrand.left; +} + + +inline std::istream& operator>>( std::istream& is, MTRand& mtrand ) +{ + register MTRand::uint32 *s = mtrand.state; + register int i = mtrand.N; + for( ; i--; is >> *s++ ) {} + is >> mtrand.left; + mtrand.pNext = &mtrand.state[mtrand.N-mtrand.left]; + return is; +} + +} // math +} // yake + +#endif // YAKE_BASE_MATH_MERSENNETWISTER_H + +// Change log: +// +// v0.1 - First release on 15 May 2000 +// - Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus +// - Translated from C to C++ +// - Made completely ANSI compliant +// - Designed convenient interface for initialization, seeding, and +// obtaining numbers in default or user-defined ranges +// - Added automatic seeding from /dev/urandom or time() and clock() +// - Provided functions for saving and loading generator state +// +// v0.2 - Fixed bug which reloaded generator one step too late +// +// v0.3 - Switched to clearer, faster reload() code from Matthew Bellew +// +// v0.4 - Removed trailing newline in saved generator format to be consistent +// with output format of built-in types +// +// v0.5 - Improved portability by replacing static const int's with enum's and +// clarifying return values in seed(); suggested by Eric Heimburg +// - Removed MAXINT constant; use 0xffffffffUL instead +// +// v0.6 - Eliminated seed overflow when uint32 is larger than 32 bits +// - Changed integer [0,n] generator to give better uniformity +// +// v0.7 - Fixed operator precedence ambiguity in reload() +// - Added access for real numbers in (0,1) and (0,n) +// +// v0.8 - Included time.h header to properly support time_t and clock_t +// +// v1.0 - Revised seeding to match 26 Jan 2002 update of Nishimura and Matsumoto +// - Allowed for seeding with arrays of any length +// - Added access for real numbers in [0,1) with 53-bit resolution +// - Added access for real numbers from normal (Gaussian) distributions +// - Increased overall speed by optimizing twist() +// - Doubled speed of integer [0,n] generation +// - Fixed out-of-range number generation on 64-bit machines +// - Improved portability by substituting literal constants for long enum's +// - Changed license from GNU LGPL to BSD Modified: trunk/yake/yake/base/math/yakeRand.h =================================================================== --- trunk/yake/yake/base/math/yakeRand.h 2006-09-14 20:56:35 UTC (rev 1465) +++ trunk/yake/yake/base/math/yakeRand.h 2006-09-14 21:45:38 UTC (rev 1466) @@ -35,76 +35,55 @@ # include "../yakePrerequisites.h" #endif -#include <boost/random.hpp> - //============================================================================ // INTERFACE STRUCTURES / UTILITY CLASSES //============================================================================ namespace yake { namespace math { - /** A random number generator (using boost::random's mersenne twister). + class MTRand; + /** Random number generator interface. + \see RandomNumberGeneratorMT + */ + template < typename IntType, typename RealType > + class YAKE_BASE_API RandomNumberGeneratorT + { + public: + virtual ~RandomNumberGeneratorT() {} + + virtual void setSeed( IntType seed ) = 0; + virtual IntType getSeed() const = 0; + + virtual RealType operator()() = 0; + virtual IntType randInt() = 0; + virtual RealType randReal() = 0; + }; + + /** A random number generator. + In fact, it's a thin wrapper for a MersenneTwister implementation ( + see yakeRand.cpp and yakeMersenneTwister.h for more information ). \see RandomNumberGenerator */ - template<typename value_type> - class RandomNumberGeneratorMT + class YAKE_BASE_API RandomNumberGeneratorMT : public RandomNumberGeneratorT< uint32, real > { public: RandomNumberGeneratorMT(); + virtual ~RandomNumberGeneratorMT(); - void setSeed( uint32 seed ); - uint32 getSeed() const; + virtual void setSeed( uint32 seed ); + virtual uint32 getSeed() const; - value_type operator()(); - value_type rand(); + virtual real operator()(); + virtual uint32 randInt(); + virtual real randReal(); protected: - //typedef boost::mt11213b generator_type; //@todo find out why this doesn't seem to work for us. - typedef boost::minstd_rand generator_type; - generator_type rand_; - typedef boost::uniform_real<real> dist_type; - typedef boost::variate_generator<generator_type&,dist_type> gen_type; - dist_type dist_; - gen_type gen_; - uint32 seed_; + MTRand * mRand; + uint32 mSeed; }; - template<typename value_type> - RandomNumberGeneratorMT<value_type>::RandomNumberGeneratorMT() : - seed_(54783), - dist_(0,1), - gen_(rand_,dist_) - { - setSeed( seed_ ); - } - template<typename value_type> - value_type RandomNumberGeneratorMT<value_type>::operator()() - { - return gen_(); - } - template<typename value_type> - value_type RandomNumberGeneratorMT<value_type>::rand() - { - return gen_(); - } - template<typename value_type> - void RandomNumberGeneratorMT<value_type>::setSeed( uint32 seed ) - { - //const std::vector<int> v(9999u, 0x41); - const std::vector<int> v(9999u, seed); - seed_ = seed; - rand_.seed( v.begin(), v.end() ); - } - template<typename value_type> - uint32 RandomNumberGeneratorMT<value_type>::getSeed() const - { - return seed_; - } } // math - - // pull into namespace yake - typedef math::RandomNumberGeneratorMT<real> RandomNumberGenerator; - + typedef math::RandomNumberGeneratorMT RandomNumberGenerator; } // yake #endif // YAKE_BASE_MATH_RAND_H This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2006-09-18 21:32:06
|
Revision: 1470 http://svn.sourceforge.net/yake/?rev=1470&view=rev Author: psyclonist Date: 2006-09-18 14:31:49 -0700 (Mon, 18 Sep 2006) Log Message: ----------- Re-enabled and improved Win32 "Assertion Failed" dialog Modified Paths: -------------- trunk/yake/src/yake/base/native/win32/yakeDebug.cpp trunk/yake/yake/base/native/win32/win32.rc Modified: trunk/yake/src/yake/base/native/win32/yakeDebug.cpp =================================================================== --- trunk/yake/src/yake/base/native/win32/yakeDebug.cpp 2006-09-16 19:40:12 UTC (rev 1469) +++ trunk/yake/src/yake/base/native/win32/yakeDebug.cpp 2006-09-18 21:31:49 UTC (rev 1470) @@ -70,7 +70,7 @@ { char szBuffer[ 1024 ]; sprintf( szBuffer, - "An ASSERT() failed under the following circumstances:\n\nMessage:\t%s\nCondition:\t%s\nFile:\t\t%s\nLine:\t\t%i", + "An assertion failed under the following circumstances:\n\nMessage:\t%s\nCondition:\t%s\nFile:\t\t%s\nLine:\t\t%i", g_pszMessage, g_pszCondition, g_pszFile, Modified: trunk/yake/yake/base/native/win32/win32.rc =================================================================== --- trunk/yake/yake/base/native/win32/win32.rc 2006-09-16 19:40:12 UTC (rev 1469) +++ trunk/yake/yake/base/native/win32/win32.rc 2006-09-18 21:31:49 UTC (rev 1470) @@ -13,7 +13,7 @@ #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// -// Englisch (USA) resources +// English (U.S.) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) #ifdef _WIN32 @@ -52,17 +52,16 @@ // Dialog // -IDD_ASSERT_FAILED DIALOGEX 0, 0, 274, 93 +IDD_ASSERT_FAILED DIALOGEX 0, 0, 274, 142 STYLE DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU -CAPTION "Debugging Error - ASSERT() failed" +CAPTION "Assertion Failed" FONT 8, "MS Sans Serif", 0, 0, 0x0 BEGIN - DEFPUSHBUTTON "E&xit",IDC_EXIT,177,73,50,14 - PUSHBUTTON "&Debug",IDC_DEBUG,111,73,50,14 - PUSHBUTTON "&Continue",IDC_CONTINUE,45,73,50,14 - LTEXT "Static",IDC_ERROR_TEXT,7,7,263,48 - CONTROL "&Ignore always",IDC_IGNORE_ALWAYS,"Button", - BS_AUTOCHECKBOX | WS_TABSTOP,7,57,84,10 + DEFPUSHBUTTON "E&xit",IDC_EXIT,212,123,50,14 + PUSHBUTTON "&Debug",IDC_DEBUG,146,123,50,14 + PUSHBUTTON "&Continue",IDC_CONTINUE,80,123,50,14 + LTEXT "Static",IDC_ERROR_TEXT,7,7,263,111 + CONTROL "&Ignore always",IDC_IGNORE_ALWAYS,"Button",BS_AUTOCHECKBOX | WS_TABSTOP,7,125,67,10 END @@ -76,12 +75,12 @@ BEGIN IDD_ASSERT_FAILED, DIALOG BEGIN - RIGHTMARGIN, 213 + RIGHTMARGIN, 270 END END #endif // APSTUDIO_INVOKED -#endif // Englisch (USA) resources +#endif // English (U.S.) resources ///////////////////////////////////////////////////////////////////////////// This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2006-09-18 21:36:29
|
Revision: 1474 http://svn.sourceforge.net/yake/?rev=1474&view=rev Author: psyclonist Date: 2006-09-18 14:36:13 -0700 (Mon, 18 Sep 2006) Log Message: ----------- added IAvatar::getCreator() and implemented IWorld::destroyAvatar() Modified Paths: -------------- trunk/yake/src/yake/plugins/physicsODE/OdeAvatar.cpp trunk/yake/src/yake/plugins/physicsODE/OdeWorld.cpp trunk/yake/yake/physics/yakePhysicsAvatar.h trunk/yake/yake/plugins/physicsODE/OdeAvatar.h Modified: trunk/yake/src/yake/plugins/physicsODE/OdeAvatar.cpp =================================================================== --- trunk/yake/src/yake/plugins/physicsODE/OdeAvatar.cpp 2006-09-18 21:34:23 UTC (rev 1473) +++ trunk/yake/src/yake/plugins/physicsODE/OdeAvatar.cpp 2006-09-18 21:36:13 UTC (rev 1474) @@ -63,6 +63,8 @@ mPostStepConn.disconnect(); YAKE_SAFE_DELETE( mRay ); YAKE_SAFE_DELETE( mTopRay ); + YAKE_ASSERT( mOdeWorld ); + YAKE_ASSERT( mActor ); mOdeWorld->destroyActor( mActor ); mActor = 0; mOdeWorld = 0; @@ -210,6 +212,13 @@ } //----------------------------------------------------- + IWorld& OdeAvatar::getCreator() const + { + YAKE_ASSERT( this->mOdeWorld ); + return *this->mOdeWorld; + } + + //----------------------------------------------------- void OdeAvatar::setDimensions( const Vector3& dim ) { mDimensions = dim; Modified: trunk/yake/src/yake/plugins/physicsODE/OdeWorld.cpp =================================================================== --- trunk/yake/src/yake/plugins/physicsODE/OdeWorld.cpp 2006-09-18 21:34:23 UTC (rev 1473) +++ trunk/yake/src/yake/plugins/physicsODE/OdeWorld.cpp 2006-09-18 21:36:13 UTC (rev 1474) @@ -354,9 +354,15 @@ mActors.erase( std::find(mActors.begin(), mActors.end(), checked_cast<OdeActor*>((IActorPtr)pActor) ) ); } //----------------------------------------------------- + bool operator==(const SharedPtr<OdeAvatar>& lhs, const OdeAvatar* rhs) + { + return (lhs.get() == rhs); + } + //----------------------------------------------------- void OdeWorld::destroyAvatar( IAvatarPtr pAvatar ) { - YAKE_ASSERT( 0 && "NOT IMPLEMENTED" ); + YAKE_ASSERT( pAvatar ); + mAvatars.erase( std::find(mAvatars.begin(), mAvatars.end(), checked_cast<OdeAvatar*>((IAvatarPtr)pAvatar) ) ); } //----------------------------------------------------- Modified: trunk/yake/yake/physics/yakePhysicsAvatar.h =================================================================== --- trunk/yake/yake/physics/yakePhysicsAvatar.h 2006-09-18 21:34:23 UTC (rev 1473) +++ trunk/yake/yake/physics/yakePhysicsAvatar.h 2006-09-18 21:36:13 UTC (rev 1474) @@ -35,6 +35,8 @@ using namespace ::yake::math; namespace physics { + class IWorld; + /** @deprecated Use the signals instead that IAvatar provides. */ class YAKE_PHYSICS_API IAvatarListener @@ -75,6 +77,8 @@ virtual void duck(const bool yes) = 0; virtual bool isDucking() const = 0; + virtual IWorld& getCreator() const = 0; + YAKE_MEMBERSIGNAL_PUREINTERFACE( public, void(bool), OnJump ) YAKE_MEMBERSIGNAL_PUREINTERFACE( public, void(bool), OnDuck ) }; Modified: trunk/yake/yake/plugins/physicsODE/OdeAvatar.h =================================================================== --- trunk/yake/yake/plugins/physicsODE/OdeAvatar.h 2006-09-18 21:34:23 UTC (rev 1473) +++ trunk/yake/yake/plugins/physicsODE/OdeAvatar.h 2006-09-18 21:36:13 UTC (rev 1474) @@ -63,6 +63,8 @@ virtual void duck(const bool yes); virtual bool isDucking() const; + virtual IWorld& getCreator() const; + YAKE_MEMBERSIGNAL_VIRTUALIMPL(public, void(bool), OnJump) YAKE_MEMBERSIGNAL_FIRE_FN1(public, OnJump, jumping, bool) This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2006-09-18 21:39:23
|
Revision: 1477 http://svn.sourceforge.net/yake/?rev=1477&view=rev Author: psyclonist Date: 2006-09-18 14:39:05 -0700 (Mon, 18 Sep 2006) Log Message: ----------- demo now uses data-driven action maps for input binding, cleaned up demo by separating application code from character control code Modified Paths: -------------- trunk/yake/scripts/msvc8/samples/misc/sampleCmdrMayhem.vcproj trunk/yake/src/yake/input/yakeActionMap.cpp trunk/yake/src/yapp/samples/misc/cmdrmayhem/yakeDemo.cpp Modified: trunk/yake/scripts/msvc8/samples/misc/sampleCmdrMayhem.vcproj =================================================================== --- trunk/yake/scripts/msvc8/samples/misc/sampleCmdrMayhem.vcproj 2006-09-18 21:37:44 UTC (rev 1476) +++ trunk/yake/scripts/msvc8/samples/misc/sampleCmdrMayhem.vcproj 2006-09-18 21:39:05 UTC (rev 1477) @@ -238,6 +238,10 @@ Name="entity scripts" > </Filter> + <File + RelativePath="..\..\..\..\common\media\samples\character\demo.actionmap.txt" + > + </File> </Files> <Globals> </Globals> Modified: trunk/yake/src/yake/input/yakeActionMap.cpp =================================================================== --- trunk/yake/src/yake/input/yakeActionMap.cpp 2006-09-18 21:37:44 UTC (rev 1476) +++ trunk/yake/src/yake/input/yakeActionMap.cpp 2006-09-18 21:39:05 UTC (rev 1477) @@ -272,7 +272,7 @@ } else { - YAKE_ASSERT( 0 ).debug("Batman, help!"); + YAKE_ASSERT( 0 ).debug("Batman, help! Unknown type!"); } YAKE_ASSERT( pCond )(line).debug("Could not create condition!"); Modified: trunk/yake/src/yapp/samples/misc/cmdrmayhem/yakeDemo.cpp =================================================================== --- trunk/yake/src/yapp/samples/misc/cmdrmayhem/yakeDemo.cpp 2006-09-18 21:37:44 UTC (rev 1476) +++ trunk/yake/src/yapp/samples/misc/cmdrmayhem/yakeDemo.cpp 2006-09-18 21:39:05 UTC (rev 1477) @@ -57,6 +57,182 @@ YAKE_ASSERT( 0 ); } +// struct AvatarPhysicsComponent : public ModelComponent +// struct HumanAvatarController : public ModelComponent +// struct AvatarGraphicsComponent : public ModelComponent + +struct ControllableCharacter +{ +public: + ControllableCharacter(model::CentralControllerBase&, graphics::IWorld&, physics::IWorld&); + ~ControllableCharacter(); + void bindInput(input::ActionMap&, input::KeyboardDevice*, input::MouseDevice*); + void unbindInput(); + void update(const real dt); + void setDirection(const Vector3&); + Vector3 getPosition() const; +private: + ControllableCharacter(const ControllableCharacter&); + ControllableCharacter& operator=(const ControllableCharacter&); +private: + void addInputSignalConnection(const SignalConnection&); + void addInputConditionConnection(const input::ConditionConnection&); +private: + void onForward() + { mActiveActions.insert( input::ACTIONID_FORWARD ); } + void onReverse() + { mActiveActions.insert( input::ACTIONID_REVERSE ); } + void onUp() + { mActiveActions.insert( input::ACTIONID_UP ); } + void onLeft() + { mActiveActions.insert( input::ACTIONID_LEFT ); } + void onRight() + { mActiveActions.insert( input::ACTIONID_RIGHT ); } + void onCrouch() + { mActiveActions.insert( input::ACTIONID_DOWN ); } +private: + physics::IAvatarPtr mPlayerRep; + model::Model* mPlayerModel; + + typedef std::deque<SignalConnection> SignalConnectionList; + SignalConnectionList mInputSignalConnections; + + typedef std::deque<input::ConditionConnection> ConditionConnectionList; + ConditionConnectionList mInputConditionConnections; + + typedef std::set<input::ActionId> ActionIdList; + ActionIdList mActiveActions; + Vector3 mMouseMovement; + Quaternion mProjViewRot; +}; +ControllableCharacter::ControllableCharacter( + model::CentralControllerBase& centralCtrlr, + yake::graphics::IWorld & gworld, + yake::physics::IWorld & pworld) +{ + mPlayerRep = pworld.createAvatar( + physics::IAvatar::Desc( + math::Vector3(0.5,2,0), // dimensions + math::Vector3(0,real(0.1),0) // initial position (relative to stable position) + ) + ); + YAKE_ASSERT( mPlayerRep ); + { + mPlayerModel = new model::Model(); + model::Graphical* pG = new model::Graphical(); + mPlayerModel->addComponent( pG ); + graphics::ISceneNode* pSN = gworld.createSceneNode(); + pG->addSceneNode( pSN, "playerSN" ); + graphics::IEntity* pE = gworld.createEntity("sphere_d1.mesh"); + pSN->attachEntity( pE ); + pSN->setScale( 0.5 * math::Vector3::kUnitScale ); + + model::ModelMovableDirectLink* pLink = new model::ModelMovableDirectLink(); + mPlayerModel->addLink( pLink ); + pLink->setSource( mPlayerRep ); + pLink->subscribeToPositionChanged( pSN ); + pLink->subscribeToOrientationChanged( pSN ); + centralCtrlr.subscribeToGraphicsUpdate( Bind2(&model::ModelMovableDirectLink::update,pLink) ); + } +} +ControllableCharacter::~ControllableCharacter() +{ + unbindInput(); + if (mPlayerRep) + { + mPlayerRep->getCreator().destroyAvatar( mPlayerRep ); + mPlayerRep = 0; + } + YAKE_SAFE_DELETE( mPlayerModel ); +} +void ControllableCharacter::bindInput(input::ActionMap& actionMap, + input::KeyboardDevice* keyboard, + input::MouseDevice* mouse) +{ + YAKE_ASSERT( keyboard ); + YAKE_ASSERT( mouse ); + + using namespace input; + + // load key<->action bindings + ActionMap::loadFromFile( actionMap, "../../media/samples/character/demo.actionmap.txt", keyboard, + boost::bind(&ControllableCharacter::addInputConditionConnection,this,_1) ); + + // bind functions/callbacks to input actions + this->addInputSignalConnection( + actionMap.subscribeToActionIdV( ACTIONID_LEFT, boost::bind(&ControllableCharacter::onLeft,this) ) ); + this->addInputSignalConnection( + actionMap.subscribeToActionIdV( ACTIONID_RIGHT, boost::bind(&ControllableCharacter::onRight,this) ) ); + this->addInputSignalConnection( + actionMap.subscribeToActionIdV( ACTIONID_FORWARD, boost::bind(&ControllableCharacter::onForward,this) ) ); + this->addInputSignalConnection( + actionMap.subscribeToActionIdV( ACTIONID_REVERSE, boost::bind(&ControllableCharacter::onReverse,this) ) ); + this->addInputSignalConnection( + actionMap.subscribeToActionIdV( ACTIONID_UP, boost::bind(&ControllableCharacter::onUp,this) ) ); + this->addInputSignalConnection( + actionMap.subscribeToActionIdV( ACTIONID_DOWN, boost::bind(&ControllableCharacter::onCrouch,this) ) ); +} +void ControllableCharacter::unbindInput() +{ + for( SignalConnectionList::iterator it = mInputSignalConnections.begin(); it != mInputSignalConnections.end(); ++it ) + it->disconnect(); + mInputSignalConnections.clear(); + + for( ConditionConnectionList::iterator it = mInputConditionConnections.begin(); it != mInputConditionConnections.end(); ++it ) + it->disconnect(); + mInputConditionConnections.clear(); +} +void ControllableCharacter::addInputSignalConnection(const SignalConnection& conn) +{ + mInputSignalConnections.push_back( conn ); +} +void ControllableCharacter::addInputConditionConnection(const input::ConditionConnection& conn) +{ + mInputConditionConnections.push_back( conn ); +} +void ControllableCharacter::setDirection(const Vector3& dir) +{ + const Vector3 normalisedDir = dir.normalisedCopy(); + mProjViewRot.FromAxes( normalisedDir.crossProduct( math::Vector3::kUnitY ), math::Vector3::kUnitY, -normalisedDir ); +} +void ControllableCharacter::update(const real dt) +{ + // + const real maxVel = real(3.0); + math::Vector3 playerTargetVel; + ConstDequeIterator< ActionIdList > itAction( mActiveActions ); + while (itAction.hasMoreElements()) + { + const input::ActionId activeId = itAction.getNext(); + if (activeId == input::ACTIONID_FORWARD) + playerTargetVel += math::Vector3(0,0,+1); + else if (activeId == input::ACTIONID_REVERSE) + playerTargetVel += math::Vector3(0,0,-1); + else if (activeId == input::ACTIONID_LEFT) + playerTargetVel += math::Vector3(+1,0,0); + else if (activeId == input::ACTIONID_RIGHT) + playerTargetVel += math::Vector3(-1,0,0); + else if (activeId == input::ACTIONID_UP) + mPlayerRep->jump(); + else if (activeId == input::ACTIONID_DOWN) + { + mPlayerRep->duck( !mPlayerRep->isDucking() ); + } + } + playerTargetVel.normalise(); + playerTargetVel = mProjViewRot * playerTargetVel; + mPlayerRep->setTargetVelocity( playerTargetVel.normalisedCopy() * maxVel ); + + // prepare for next step + mActiveActions.clear(); + mMouseMovement = Vector3::kZero; +} +Vector3 ControllableCharacter::getPosition() const +{ + YAKE_ASSERT( mPlayerRep ); + return mPlayerRep->getPosition(); +} + /** Main application state */ class TheMainState : public raf::RtMainState { @@ -64,8 +240,6 @@ TheMainState(raf::Application& owner) : raf::RtMainState(owner), mGround(0), - mPlayerModel(0), - mPlayerRep(0), mEnv(0) { enableInstantQuitByKey( input::KC_ESCAPE ); @@ -93,7 +267,7 @@ { YAKE_LOG_INFORMATION("Creating scene"); - getPhysicalWorld()->setGlobalGravity(Vector3(0,-9.8,0)); + getPhysicalWorld()->setGlobalGravity(Vector3(0,real(-9.8),0)); // create a light graphics::ILight* pLight = getGraphicalWorld()->createLight(); @@ -145,31 +319,8 @@ // dirMediaRoot+sceneBaseName+".scene", dirMediaRoot+sceneBaseName+".xode", dirMediaRoot+sceneBaseName+".link" ); // create player/avatar - mPlayerRep = getPhysicalWorld()->createAvatar( - physics::IAvatar::Desc( - math::Vector3(0.5,2,0), // dimensions - math::Vector3(0,0.1,0) // initial position (relative to stable position) - ) - ); - YAKE_ASSERT( mPlayerRep ); - { - mPlayerModel = new model::Model(); - model::Graphical* pG = new model::Graphical(); - mPlayerModel->addComponent( pG ); - graphics::ISceneNode* pSN = getGraphicalWorld()->createSceneNode(); - pG->addSceneNode( pSN, "playerSN" ); - graphics::IEntity* pE = getGraphicalWorld()->createEntity("sphere_d1.mesh"); - pSN->attachEntity( pE ); - pSN->setScale( 0.5 * math::Vector3::kUnitScale ); + mPlayer.reset( new ControllableCharacter(*this,*getGraphicalWorld(),*getPhysicalWorld()) ); - model::ModelMovableDirectLink* pLink = new model::ModelMovableDirectLink(); - mPlayerModel->addLink( pLink ); - pLink->setSource( mPlayerRep ); - pLink->subscribeToPositionChanged( pSN ); - pLink->subscribeToOrientationChanged( pSN ); - this->subscribeToGraphicsUpdate( Bind2(&model::ModelMovableDirectLink::update,pLink) ); - } - // top-down camera controller mTopDownCtrlr.setOffset( math::Vector3(10,10,-10) ); mTopDownCtrlr.setTargetOffset( math::Vector3(10,10,-10) ); @@ -178,8 +329,7 @@ virtual void onDestroyScene() { mTopDownCtrlr.setCamera( 0 ); - YAKE_SAFE_DELETE( mPlayerModel ); - YAKE_SAFE_DELETE( mPlayerRep ); + mPlayer.reset(); YAKE_SAFE_DELETE( mGround ); YAKE_SAFE_DELETE( mEnv ); } @@ -189,29 +339,15 @@ using namespace input; // controls + if (mPlayer) + mPlayer->bindInput( mActionMap, getApp().getKeyboard(), getApp().getMouse() ); - mActionMap.reg( ACTIONID_LEFT, new input::KeyboardActionCondition( getApp().getKeyboard(), KC_A, KAM_CONTINUOUS ) ); - mActionMap.subscribeToActionIdV( ACTIONID_LEFT, boost::bind(&TheMainState::onLeft,this) ); - - mActionMap.reg( ACTIONID_RIGHT, new input::KeyboardActionCondition( getApp().getKeyboard(), KC_D, KAM_CONTINUOUS ) ); - mActionMap.subscribeToActionIdV( ACTIONID_RIGHT, boost::bind(&TheMainState::onRight,this) ); - - mActionMap.reg( ACTIONID_FORWARD, new input::KeyboardActionCondition( getApp().getKeyboard(), KC_W, KAM_CONTINUOUS ) ); - mActionMap.subscribeToActionIdV( ACTIONID_FORWARD, boost::bind(&TheMainState::onForward,this) ); - - mActionMap.reg( ACTIONID_REVERSE, new input::KeyboardActionCondition( getApp().getKeyboard(), KC_S, KAM_CONTINUOUS ) ); - mActionMap.subscribeToActionIdV( ACTIONID_REVERSE, boost::bind(&TheMainState::onReverse,this) ); - - mActionMap.reg( ACTIONID_UP, new input::KeyboardActionCondition( getApp().getKeyboard(), KC_SPACE, KAM_PRESSED ) ); - mActionMap.subscribeToActionIdV( ACTIONID_UP, boost::bind(&TheMainState::onUp,this) ); - - mActionMap.reg( ACTIONID_DOWN, new input::KeyboardActionCondition( getApp().getKeyboard(), KC_C, KAM_PRESSED ) ); - mActionMap.subscribeToActionIdV( ACTIONID_DOWN, boost::bind(&TheMainState::onCrouch,this) ); - - mActionMap.reg( ACTIONID_ZOOM_INOUT, new input::MouseMoveActionCondition( getApp().getMouse(), input::MMA_WHEEL, input::MMD_BOTH ) ); + // top-down controller + // @todo unsubscribe + mActionMap.reg( ACTIONID_ZOOM_INOUT, new MouseMoveActionCondition( getApp().getMouse(), input::MMA_WHEEL, input::MMD_BOTH ) ); mActionMap.subscribeToActionIdR( ACTIONID_ZOOM_INOUT, Bind1(&TheMainState::onMouseWheel,this) ); - mActionMap.reg( ACTIONID_MOUSE_MOVE, new input::MouseMoveActionCondition( getApp().getMouse(), input::MMA_X_AND_Y, input::MMD_BOTH ) ); + mActionMap.reg( ACTIONID_MOUSE_MOVE, new MouseMoveActionCondition( getApp().getMouse(), input::MMA_X_AND_Y, input::MMD_BOTH ) ); mActionMap.subscribeToActionIdR( ACTIONID_MOUSE_MOVE, Bind1(&TheMainState::onMouseMoveXY,this) ); // for cursor @@ -222,57 +358,34 @@ } virtual void onExit() { - //@todo cleanupGUI(); + if (mPlayer) + mPlayer->unbindInput(); getApp().enableKeyboardInputForCEGUI(false); getApp().enableMouseInputForCEGUI(false); + + RtMainState::onExit(); } virtual void onFrame(const real timeElapsed) { - /* - static real time = 0.; - std::cout << "onFrame() @ " << time << "\n"; - time += timeElapsed; - */ - // mActionMap.update(); - math::Vector3 projViewDir = mTopDownCtrlr.getOffset(); - projViewDir.y = 0.; - if (projViewDir.length() <= 0.01) - projViewDir = math::Vector3::kUnitZ; - projViewDir.normalise(); - math::Quaternion projViewRot; - projViewRot.FromAxes( projViewDir.crossProduct( math::Vector3::kUnitY ), math::Vector3::kUnitY, -projViewDir ); + // + if (mPlayer) + { + Vector3 projViewDir = mTopDownCtrlr.getOffset(); + projViewDir.y = 0.; + if (projViewDir.length() <= 0.01) + projViewDir = math::Vector3::kUnitZ; + projViewDir.normalise(); + mPlayer->setDirection( projViewDir ); - const real maxVel = real(3.0); - math::Vector3 playerTargetVel; - ConstDequeIterator< ActionIdList > itAction( mActiveActions ); - while (itAction.hasMoreElements()) - { - const input::ActionId activeId = itAction.getNext(); - if (activeId == input::ACTIONID_FORWARD) - playerTargetVel += math::Vector3(0,0,+1); - else if (activeId == input::ACTIONID_REVERSE) - playerTargetVel += math::Vector3(0,0,-1); - else if (activeId == input::ACTIONID_LEFT) - playerTargetVel += math::Vector3(+1,0,0); - else if (activeId == input::ACTIONID_RIGHT) - playerTargetVel += math::Vector3(-1,0,0); - else if (activeId == input::ACTIONID_UP) - mPlayerRep->jump(); - else if (activeId == input::ACTIONID_DOWN) - { - mPlayerRep->duck( !mPlayerRep->isDucking() ); - } + mPlayer->update( timeElapsed ); } - playerTargetVel.normalise(); - playerTargetVel = projViewRot * playerTargetVel; - mPlayerRep->setTargetVelocity( playerTargetVel.normalisedCopy() * maxVel ); { // top-down controller - const real dist = timeElapsed * 4.; + const real dist = timeElapsed * real(4.); math::Vector3 offset; if (this->getApp().getKeyboard()->isKeyDown(input::KC_I)) offset += dist * math::Vector3::kUnitZ; @@ -286,14 +399,14 @@ mTopDownCtrlr.setTargetOffset( mTopDownCtrlr.getTargetOffset() + offset ); } - mTopDownCtrlr.setTarget( mPlayerRep->getPosition() ); + mTopDownCtrlr.setTarget( mPlayer->getPosition() ); // Rotate camera around camera's 'up' axis // when user presses RMB and moves the mouse. if (this->getApp().getMouse()->isButtonDown( input::MB_RIGHT )) { // @todo adjust rotation over several frames for smoother rotation. - const double angle = mMouseMovement.x * 100. * timeElapsed; + const real angle = mMouseMovement.x * real(100.) * timeElapsed; Matrix3 rot; rot.FromAxisAngle( Vector3::kUnitY, angle ); @@ -319,20 +432,20 @@ if (this->getApp().getKeyboard()->isKeyDown(input::KC_ADD)) { real physicsTimeFactor = this->getPhysicsTimeFactor(); - physicsTimeFactor += 0.1 * timeElapsed; + physicsTimeFactor += real(0.1) * timeElapsed; this->setPhysicsTimeFactor( physicsTimeFactor ); std::cout << "factor = " << this->getPhysicsTimeFactor() << "\n"; } if (this->getApp().getKeyboard()->isKeyDown(input::KC_SUBTRACT)) { real physicsTimeFactor = this->getPhysicsTimeFactor(); - physicsTimeFactor -= 0.1 * timeElapsed; + physicsTimeFactor -= real(0.1) * timeElapsed; if (physicsTimeFactor < 0.) physicsTimeFactor = 0.; this->setPhysicsTimeFactor( physicsTimeFactor ); std::cout << "factor = " << this->getPhysicsTimeFactor() << "\n"; } } -protected: +private: void onMouseMoveXY(const input::ActionMap::ActionResult& ar) { mMouseMovement = ar.signal * 10.; @@ -344,7 +457,7 @@ if (fabs(ar.signal.z) < std::numeric_limits<real>::epsilon()) return; - const real fac = (1.0 - 0.1 * ar.signal.z); // either 0.9 or 1.1 + const real fac = real(1.0 - 0.1 * ar.signal.z); // either 0.9 or 1.1 // scale the target offset Vector3 targetOffset = mTopDownCtrlr.getTargetOffset() * fac; @@ -356,22 +469,8 @@ // apply mTopDownCtrlr.setTargetOffset( targetOffset ); } - void onForward() - { mActiveActions.insert( input::ACTIONID_FORWARD ); } - void onReverse() - { mActiveActions.insert( input::ACTIONID_REVERSE ); } - void onUp() - { mActiveActions.insert( input::ACTIONID_UP ); } - void onLeft() - { mActiveActions.insert( input::ACTIONID_LEFT ); } - void onRight() - { mActiveActions.insert( input::ACTIONID_RIGHT ); } - void onCrouch() - { mActiveActions.insert( input::ACTIONID_DOWN ); } private: - physics::IAvatarPtr mPlayerRep; model::Model* mGround; - model::Model* mPlayerModel; input::ActionMap mActionMap; typedef std::set<input::ActionId> ActionIdList; @@ -381,6 +480,8 @@ TopDownCameraController mTopDownCtrlr; Vector3 mMouseMovement; + + SharedPtr<ControllableCharacter> mPlayer; }; /** The mighty application itself! */ This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2006-09-24 22:05:57
|
Revision: 1479 http://svn.sourceforge.net/yake/?rev=1479&view=rev Author: psyclonist Date: 2006-09-24 15:05:27 -0700 (Sun, 24 Sep 2006) Log Message: ----------- Condition processing of ActionMaps can be stopped and restarted. Added documentation. Modified Paths: -------------- trunk/yake/src/yake/input/yakeActionMap.cpp trunk/yake/src/yapp/samples/misc/cmdrmayhem/yakeDemo.cpp trunk/yake/yake/input/yakeActionMap.h Modified: trunk/yake/src/yake/input/yakeActionMap.cpp =================================================================== --- trunk/yake/src/yake/input/yakeActionMap.cpp 2006-09-21 21:59:47 UTC (rev 1478) +++ trunk/yake/src/yake/input/yakeActionMap.cpp 2006-09-24 22:05:27 UTC (rev 1479) @@ -336,7 +336,7 @@ return (mKeyb->isKeyDown( mKey ) ? kAC_TRUE1 : kAC_FALSE); else { - bool state = mKeyb->isKeyDown( mKey ); + const bool state = mKeyb->isKeyDown( mKey ); if (state != mLastState) { mLastState = state; @@ -359,6 +359,19 @@ } //----------------------------------------------------- + void KeyboardActionCondition::onStopConditionProcessing() + { + } + + //----------------------------------------------------- + void KeyboardActionCondition::onStartConditionProcessing() + { + if (mMode == KAM_CONTINUOUS) + return; + mLastState = mKeyb->isKeyDown( mKey ); + } + + //----------------------------------------------------- // MouseActionCondition //----------------------------------------------------- MouseActionCondition::MouseActionCondition(yake::input::MouseDevice *device) : mMouse(device) @@ -370,29 +383,70 @@ // MouseButtonActionCondition //----------------------------------------------------- MouseButtonActionCondition::MouseButtonActionCondition( - MouseDevice * device, MouseButton button, bool continuous) : + MouseDevice * device, MouseButton button, MouseButtonActionMode mode) : MouseActionCondition(device), mButton(button), - mContinuous(continuous) + mMode(mode) { } + //----------------------------------------------------- void MouseButtonActionCondition::setButton(MouseButton button) { mButton = button; } + //----------------------------------------------------- void MouseButtonActionCondition::setContinuous(bool continuous) { mContinuous = continuous; } + //----------------------------------------------------- ActionCondition::Result MouseButtonActionCondition::operator()() { - return (mMouse->isButtonDown( mButton )) ? kAC_TRUE1 : kAC_FALSE; + if (!mMouse) + return kAC_FALSE; + if (mMode == KAM_CONTINUOUS) + return (mMouse->isButtonDown( mButton ) ? kAC_TRUE1 : kAC_FALSE); + else + { + const bool state = mMouse->isButtonDown( mButton ); + if (state != mLastState) + { + mLastState = state; + if (mMode == KAM_PRESSED_AND_RELEASED) + return kAC_TRUE1; + else + { + // fire only if key is 'pressed' + if (mLastState && mMode == KAM_PRESSED) + return kAC_TRUE1; + else if (!mLastState && mMode == KAM_RELEASED) + return kAC_TRUE1; + else + return kAC_FALSE; + } + } + else + return kAC_FALSE; + } } //----------------------------------------------------- + void MouseButtonActionCondition::onStopConditionProcessing() + { + } + + //----------------------------------------------------- + void MouseButtonActionCondition::onStartConditionProcessing() + { + if (mMode == KAM_CONTINUOUS) + return; + mLastState = mMouse->isButtonDown( mButton ); + } + + //----------------------------------------------------- // MouseMoveActionCondition //----------------------------------------------------- MouseMoveActionCondition::MouseMoveActionCondition( @@ -582,19 +636,34 @@ // not yet caught? -> no movement return kAC_FALSE; } + void MouseMoveActionCondition::onStopConditionProcessing() + { + } + void MouseMoveActionCondition::onStartConditionProcessing() + { + mPreviousPosition = mMouse->getPosition(); + } //----------------------------------------------------- // ActionMap //----------------------------------------------------- //----------------------------------------------------- - ActionMap::ActionMap() + ActionMap::ActionMap() : + mProcessingInProgress( false ) { } //----------------------------------------------------- ActionMap::~ActionMap() { + this->stop(); + this->clear(); + } + + //----------------------------------------------------- + void ActionMap::clear() + { mEntries.clear(); } @@ -613,6 +682,9 @@ else it->second->conditions.push_back( SharedPtr<ActionCondition>(condition)); + if (mProcessingInProgress) + condition->onStartConditionProcessing(); + return ConditionConnection(this,actionId,condition); } @@ -631,6 +703,8 @@ ActionCondition* cond = reinterpret_cast<ActionCondition*>(p); YAKE_ASSERT( cond ); + if (mProcessingInProgress) + cond->onStopConditionProcessing(); ConditionList& condList = it->second->conditions; ConditionList::iterator itC = std::find(condList.begin(), condList.end(), cond); @@ -665,6 +739,8 @@ //----------------------------------------------------- void ActionMap::update() { + YAKE_ASSERT( mProcessingInProgress ).debug("Processing has not been started via start()! Will not update action conditions!"); + // the update loop ActionList dead; std::deque<TriggeredAction> triggered; @@ -713,6 +789,38 @@ } //----------------------------------------------------- + void ActionMap::start() + { + for (ActionList::const_iterator it = mEntries.begin(); it != mEntries.end(); ++it) + { + ActionMapEntry* pEntry = it->second.get(); + YAKE_ASSERT( pEntry ); + const ConditionList& condList = pEntry->conditions; + for (ConditionList::const_iterator itC = condList.begin(); itC != condList.end(); ++itC) + { + (*itC)->onStartConditionProcessing(); + } + } + mProcessingInProgress = true; + } + + //----------------------------------------------------- + void ActionMap::stop() + { + for (ActionList::const_iterator it = mEntries.begin(); it != mEntries.end(); ++it) + { + ActionMapEntry* pEntry = it->second.get(); + YAKE_ASSERT( pEntry ); + const ConditionList& condList = pEntry->conditions; + for (ConditionList::const_iterator itC = condList.begin(); itC != condList.end(); ++itC) + { + (*itC)->onStopConditionProcessing(); + } + } + mProcessingInProgress = false; + } + + //----------------------------------------------------- // class: ConditionConnection //----------------------------------------------------- ConditionConnection::ConditionConnection(ActionMap* m,const ActionId& id,void* p) : map_(m), data_(p), id_(id) Modified: trunk/yake/src/yapp/samples/misc/cmdrmayhem/yakeDemo.cpp =================================================================== --- trunk/yake/src/yapp/samples/misc/cmdrmayhem/yakeDemo.cpp 2006-09-21 21:59:47 UTC (rev 1478) +++ trunk/yake/src/yapp/samples/misc/cmdrmayhem/yakeDemo.cpp 2006-09-24 22:05:27 UTC (rev 1479) @@ -355,9 +355,13 @@ getApp().enableKeyboardInputForCEGUI(true); setupGUI(); + + mActionMap.start(); } virtual void onExit() { + mActionMap.stop(); + if (mPlayer) mPlayer->unbindInput(); Modified: trunk/yake/yake/input/yakeActionMap.h =================================================================== --- trunk/yake/yake/input/yakeActionMap.h 2006-09-21 21:59:47 UTC (rev 1478) +++ trunk/yake/yake/input/yakeActionMap.h 2006-09-24 22:05:27 UTC (rev 1479) @@ -121,6 +121,8 @@ typedef std::pair<bool,Vector3> Result; virtual Result operator()() = 0; + virtual void onStopConditionProcessing() = 0; + virtual void onStartConditionProcessing() = 0; }; enum KeyboardActionMode { @@ -147,10 +149,11 @@ void setMode( KeyboardActionMode mode ); virtual Result operator()(); + virtual void onStopConditionProcessing(); + virtual void onStartConditionProcessing(); private: KeyboardDevice* mKeyb; KeyCode mKey; - bool mContinuous; bool mLastState; KeyboardActionMode mMode; }; @@ -164,16 +167,21 @@ MouseDevice* mMouse; }; + typedef KeyboardActionMode MouseButtonActionMode; class YAKE_INPUT_API MouseButtonActionCondition : public MouseActionCondition { public: - MouseButtonActionCondition( MouseDevice* device, MouseButton button = MB_LEFT, bool continous = false ); + MouseButtonActionCondition( MouseDevice* device, MouseButton button = MB_LEFT, MouseButtonActionMode mode = KAM_CONTINUOUS ); void setButton( MouseButton button ); void setContinuous( bool continous = false ); virtual Result operator()(); + virtual void onStopConditionProcessing(); + virtual void onStartConditionProcessing(); private: - MouseButton mButton; - bool mContinuous; + MouseButton mButton; + bool mContinuous; + bool mLastState; + MouseButtonActionMode mMode; }; enum MouseMoveAxis @@ -199,6 +207,8 @@ void setDirection( MouseMoveDirection direction ); void setContinuous( bool continuous = false ); virtual Result operator()(); + virtual void onStopConditionProcessing(); + virtual void onStartConditionProcessing(); private: MouseMoveAxis mAxis; MouseMoveDirection mDirection; @@ -207,6 +217,11 @@ }; class ActionMap; + /** Represents a connection of a condition with an ActionMap. + If the condition is disconnected the condition object + is available again for being registered with new ActionMap + objects or it can be destroyed. + */ struct YAKE_INPUT_API ConditionConnection { ~ConditionConnection(); @@ -223,17 +238,35 @@ }; typedef std::deque<ConditionConnection> ConditionConnectionList; - /** An ActionMap object can handly any number of ActionCondition/ActionId pairs. - The update() method has to be regularly called. - If an action should be run an ActionSignal is fired which will inform all - subscribers of the action. + /** An ActionMap object can handle any number of ActionConditions per ActionId. + @note The update() method has to be regularly called to trigger action handlers. + If an action is triggered an ActionSignal is fired which will inform all + subscribers of the action. + @note start() has to be called prior to calling update(). + @note The processing of an ActionMap can be stopped for longer intervals + by calling stop() and, later, start() again. It proves to be useful + to notify conditions that processing has stopped and later restarted, + so that they can adjust internal data in order to avoid reporting, + for example, large movements after pausing the action map for some time. + @note At the moment, an action is reported as 'being triggered' by reporting to all its subscribers + exactly once during one run of update(). This means, that even if several + conditions are met for a single action the action will be reported just once! + @note At the moment, the result of the first triggered condition + of an ActionId will be returned. + @todo Add support to subscribe to specific ActionId/Condition pairs instead of just ActionIds? */ class YAKE_INPUT_API ActionMap { public: ActionMap(); + + /** Destructs the ActionMap object and clears all contents (i.e. + all registered conditions are destroyed and signal connections are disconnected). + */ ~ActionMap(); + /** Represents the result for a given triggered action. + */ struct ActionResult { ActionId id; @@ -244,16 +277,75 @@ {} }; - typedef Signal1< void(void) > VoidActionSignal; + typedef Signal0< void(void) > VoidActionSignal; typedef Signal1< void(const ActionResult&) > ActionResultSignal; + /** Add a condition for an action id. + @note Any number of conditions can be registered for a single ActionId. + */ ConditionConnection reg( const ActionId & actionId, ActionCondition* condition ); + /*@todo + typedef ConditionConnection ConditionConnectionPtr; + ConditionConnectionPtr addActionCondition( const ActionId & actionId, ActionCondition* condition ); + ConditionConnectionPtr removeCondition(ConditionConnectionPtr); + void destroyCondition(ConditionConnectionPtr); + */ + /** Subscribe a callback to an ActionId. The callback will be run + whenever the action is triggered by its conditions. + @note This version of callback subscription only reports triggering + of the action without additional information. See subscribeToActionIdR() + for this functionality. + @see subscribeToActionIdR + */ SignalConnection subscribeToActionIdV( const ActionId & actionId, const VoidActionSignal::slot_type & slot ); + + /** Subscribe a callback to an ActionId. The callback will be run + whenever the action is triggered by its conditions. + @note This version of callback subscription allows to receive + additional information in the signal signature. + @see ActionResultSignal + @see subscribeToActionIdV + */ SignalConnection subscribeToActionIdR( const ActionId & actionId, const ActionResultSignal::slot_type & slot ); + /*@todo + void subscribeToActionIdV_managed( const ActionId & actionId, const VoidActionSignal::slot_type & slot ); + void subscribeToActionIdR_managed( const ActionId & actionId, const ActionResultSignal::slot_type & slot ); + */ + /** Process conditions and report actions if conditions are ment. + @note ActionMap::start() has to be called once prior to calling update(). + @note Processing can be interrupted by not calling update(). For longer + times without calls to update() it is often useful to notify + the conditions that processing has been suspended. This is done + by a call to stop(). In this case, before continuing to process + conditions by calling update(), it is necessary to inform the conditions + that processing continues by calling start() once. + See ActionMap for more information. + @see ActionMap + @see start() + @see stop() + */ void update(); + /** Notifies conditions that processing will be interrupted for some time. + @note The processing can be restarted by calling start() once and, regularly, update(). + */ + void stop(); + + /** Notifies conditions that processing will continue by calls to update() + */ + void start(); + + /** Clears the ActionMap by removing all ActionIds, and destroying all their + condition objects as well as signals. + @note Any connections to signals or conditions by clients external + to the ActionMap object are invalid after a call to clear()! + */ + void clear(); + + //void addManagedConditionConnection(const ConditionConnection&); + typedef boost::function<void(const ConditionConnection&)> ReceiveConditionConnectionFn; static bool loadFromFile(ActionMap& amap, const String& fname, KeyboardDevice* pKeyboard, const ReceiveConditionConnectionFn fn); static bool saveToFile(ActionMap& amap, const String& fname); @@ -284,6 +376,7 @@ entry(e), id(i), signal(s) {} }; + bool mProcessingInProgress; }; // utility, often needed for configuration files. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2006-10-24 20:30:38
|
Revision: 1483 http://svn.sourceforge.net/yake/?rev=1483&view=rev Author: psyclonist Date: 2006-10-24 13:30:19 -0700 (Tue, 24 Oct 2006) Log Message: ----------- - adjusted to interface changes in PLMS2 - fixed API declaration Modified Paths: -------------- trunk/yake/src/yapp/plugins/terrainPhysMgr/TerrainOdeActor.cpp trunk/yake/src/yapp/plugins/terrainPhysMgr/TerrainPhysicsManager.cpp trunk/yake/yapp/plugins/terrainPhysMgr/TerrainOdeActor.h trunk/yake/yapp/plugins/terrainPhysMgr/TerrainOdeShape.h trunk/yake/yapp/plugins/terrainPhysMgr/TerrainPhysicsManager.h Modified: trunk/yake/src/yapp/plugins/terrainPhysMgr/TerrainOdeActor.cpp =================================================================== --- trunk/yake/src/yapp/plugins/terrainPhysMgr/TerrainOdeActor.cpp 2006-10-22 21:05:38 UTC (rev 1482) +++ trunk/yake/src/yapp/plugins/terrainPhysMgr/TerrainOdeActor.cpp 2006-10-24 20:30:19 UTC (rev 1483) @@ -128,8 +128,8 @@ YAKE_LOG( String("Tile collision TRIMESH creation:")); Ogre::PagingLandScapeTile * pTile = pBox->getAttachedTile(); - std::cerr << "Page ( " << pTile->getInfo()->mPageX << ", " << pTile->getInfo()->mPageZ << ")" << std::endl; - std::cerr << "Tile ( " << pTile->getInfo()->mTileX << ", " << pTile->getInfo()->mTileZ << ")" << std::endl; + std::cerr << "Page ( " << pTile->getInfo()->pageX << ", " << pTile->getInfo()->pageZ << ")" << std::endl; + std::cerr << "Tile ( " << pTile->getInfo()->tileX << ", " << pTile->getInfo()->tileZ << ")" << std::endl; #endif if( pBox->getMeshID() == kTriangleMeshIdNone) { @@ -264,8 +264,8 @@ Ogre::PagingLandScapeTile * pTile = pBox->getAttachedTile(); - std::cerr << "Page ( " << pTile->getInfo()->mPageX << ", " << pTile->getInfo()->mPageZ << ")" << std::endl; - std::cerr << "Tile ( " << pTile->getInfo()->mTileX << ", " << pTile->getInfo()->mTileZ << ")" << std::endl; + std::cerr << "Page ( " << pTile->getInfo()->pageX << ", " << pTile->getInfo()->pageZ << ")" << std::endl; + std::cerr << "Tile ( " << pTile->getInfo()->tileX << ", " << pTile->getInfo()->tileZ << ")" << std::endl; cerr<<"BOX ID = "<<pBox->getCollisionBoxID()<<endl; #endif Modified: trunk/yake/src/yapp/plugins/terrainPhysMgr/TerrainPhysicsManager.cpp =================================================================== --- trunk/yake/src/yapp/plugins/terrainPhysMgr/TerrainPhysicsManager.cpp 2006-10-22 21:05:38 UTC (rev 1482) +++ trunk/yake/src/yapp/plugins/terrainPhysMgr/TerrainPhysicsManager.cpp 2006-10-24 20:30:19 UTC (rev 1483) @@ -226,10 +226,10 @@ vector< void*> params; - params.push_back( &tileInfo->mPageX ); - params.push_back( &tileInfo->mPageZ ); - params.push_back( &tileInfo->mTileX ); - params.push_back( &tileInfo->mTileZ ); + params.push_back( &tileInfo->pageX ); + params.push_back( &tileInfo->pageZ ); + params.push_back( &tileInfo->tileX ); + params.push_back( &tileInfo->tileZ ); params.push_back( &detailLevel ); sceneManager->getOption( "PageGetTileVertexData_2", ¶ms ); Modified: trunk/yake/yapp/plugins/terrainPhysMgr/TerrainOdeActor.h =================================================================== --- trunk/yake/yapp/plugins/terrainPhysMgr/TerrainOdeActor.h 2006-10-22 21:05:38 UTC (rev 1482) +++ trunk/yake/yapp/plugins/terrainPhysMgr/TerrainOdeActor.h 2006-10-24 20:30:19 UTC (rev 1483) @@ -41,6 +41,7 @@ #include "TerrainPhysicsManager.h" +#include <yapp/plugins/terrainPhysMgr/TerrainOdePrerequisites.h> #include <yapp/plugins/terrainPhysMgr/TerrainOdeShape.h> namespace yake @@ -52,7 +53,7 @@ class OdeTerrainCollisionBox; class Ogre::PagingLandScapeTileInfo; - class YAKE_PHYSICSODE_API TerrainCollisionDetectionActor : public OdeActor + class YAKE_PHYSICSPLSM_API TerrainCollisionDetectionActor : public OdeActor { protected: struct comparator Modified: trunk/yake/yapp/plugins/terrainPhysMgr/TerrainOdeShape.h =================================================================== --- trunk/yake/yapp/plugins/terrainPhysMgr/TerrainOdeShape.h 2006-10-22 21:05:38 UTC (rev 1482) +++ trunk/yake/yapp/plugins/terrainPhysMgr/TerrainOdeShape.h 2006-10-24 20:30:19 UTC (rev 1483) @@ -27,6 +27,7 @@ #ifndef YAKE_TERRAIN_ODESHAPES_H #define YAKE_TERRAIN_ODESHAPES_H +#include <yapp/plugins/terrainPhysMgr/TerrainOdePrerequisites.h> #include <yake/plugins/physicsODE/OdeShapes.h> #include "OgreRenderQueue.h" @@ -42,7 +43,7 @@ namespace yake { namespace physics { - class YAKE_PHYSICSODE_API OdeTerrainCollisionBox : public OdeBox + class YAKE_PHYSICSPLSM_API OdeTerrainCollisionBox : public OdeBox { public: OdeTerrainCollisionBox( dSpace* pSpace, OdeActor* pOwner, real sizex, real sizey, real sizez, Modified: trunk/yake/yapp/plugins/terrainPhysMgr/TerrainPhysicsManager.h =================================================================== --- trunk/yake/yapp/plugins/terrainPhysMgr/TerrainPhysicsManager.h 2006-10-22 21:05:38 UTC (rev 1482) +++ trunk/yake/yapp/plugins/terrainPhysMgr/TerrainPhysicsManager.h 2006-10-24 20:30:19 UTC (rev 1483) @@ -37,6 +37,7 @@ #include <OgreDefaultHardwareBufferManager.h> #include <OgrePagingLandScapePageManager.h> +#include <yapp/plugins/terrainPhysMgr/TerrainOdePrerequisites.h> #include <yapp/plugins/terrainPhysMgr/TerrainOdeActor.h> #include <yake/plugins/graphicsOgre/yakeGraphicsSystem.h> @@ -118,8 +119,8 @@ CollisionBoxList alreadyLoadedCollisionDetectionBoxes; }; - typedef yake::base::templates::SingletonHolder< PLSMTerrainPhysicsManager, - yake::base::templates::CreateUsingNew> TerrainPhysicsManager; + typedef yake::templates::SingletonHolder< PLSMTerrainPhysicsManager, + yake::templates::CreateUsingNew> TerrainPhysicsManager; } } #endif // __TERRAIN_PHYS_MANAGER This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2006-11-01 15:15:30
|
Revision: 1487 http://svn.sourceforge.net/yake/?rev=1487&view=rev Author: psyclonist Date: 2006-11-01 07:15:05 -0800 (Wed, 01 Nov 2006) Log Message: ----------- refactored avatar into full 3D, fixed various bugs Modified Paths: -------------- trunk/yake/src/yake/physics/yakePhysicsCommon.cpp trunk/yake/src/yake/plugins/physicsODE/OdeAvatar.cpp trunk/yake/src/yapp/samples/misc/cmdrmayhem/yakeDemo.cpp trunk/yake/yake/physics/yakePhysicsAvatar.h trunk/yake/yake/physics/yakePhysicsCommon.h trunk/yake/yake/plugins/physicsODE/OdeAvatar.h Modified: trunk/yake/src/yake/physics/yakePhysicsCommon.cpp =================================================================== --- trunk/yake/src/yake/physics/yakePhysicsCommon.cpp 2006-11-01 15:11:59 UTC (rev 1486) +++ trunk/yake/src/yake/physics/yakePhysicsCommon.cpp 2006-11-01 15:15:05 UTC (rev 1487) @@ -35,7 +35,7 @@ pos_(Point3::kZero), duration_(duration), singleStep_(false), - posRef_(RF_GLOBAL), + posRef_(RF_LOCAL), valueRef_(rfValue) { } @@ -44,7 +44,7 @@ pos_(Point3::kZero), duration_(real(0.)), singleStep_(true), - posRef_(RF_GLOBAL), + posRef_(RF_LOCAL), valueRef_(rfValue) { } Modified: trunk/yake/src/yake/plugins/physicsODE/OdeAvatar.cpp =================================================================== --- trunk/yake/src/yake/plugins/physicsODE/OdeAvatar.cpp 2006-11-01 15:11:59 UTC (rev 1486) +++ trunk/yake/src/yake/plugins/physicsODE/OdeAvatar.cpp 2006-11-01 15:15:05 UTC (rev 1487) @@ -52,7 +52,9 @@ mJumpStartInProgress(false), mDucking(false), mJumpApplies(0), - mJumpTime(real(0.)) + mJumpTime(real(0.)), + mCurrDirection(Vector3::kUnitZ), + mUp(Vector3::kUnitY) { } @@ -93,14 +95,15 @@ YAKE_ASSERT( mActor ); OdeGeom* pShape = static_cast<OdeGeom*>(mActor->createShape( IShape::SphereDesc( real(mSphereRadius) ) )); mActor->setPosition( mPosition + mSphereOffset ); + mActor->setOrientation( mOrientation ); mActor->getBody().setMass( 1 ); mRay = new OdeRay( mOdeWorld, real(mRayLength) ); - mRay->setDirection( -Vector3::kUnitY ); + mRay->setDirection( -mUp ); mRay->ignore( pShape->_getOdeGeomID() ); mTopRay = new OdeRay( mOdeWorld, real(mTopRayLength) ); - mTopRay->setDirection( Vector3::kUnitY ); + mTopRay->setDirection( mUp ); mTopRay->ignore( pShape->_getOdeGeomID() ); mPreStepConn = mOdeWorld->subscribeToPreStepInternal( boost::bind(&OdeAvatar::onPreStepInternal,this,_1) ); @@ -115,6 +118,8 @@ std::cout << "\n"; #endif + this->_updateOrientation(); + return true; } @@ -124,55 +129,56 @@ if (dt <= 0) return; - // dampen + // dampen @todo use motor mActor->getBody().setAngularVelocity( Vector3(0,0,0) ); - mActor->setOrientation( Quaternion::kIdentity ); // gather information mPosition = mActor->getPosition(); - mOrientation = mActor->getOrientation(); // is always Quaternion::kIdentity - //std::cout << "avatar: pos = " << mPosition << "\n"; - - const real targetHeightAboveGround = mDucking ? - mHeightAboveGroundDuck : mHeightAboveGround; - - const Vector3 currLinVel = mActor->getBody().getLinearVelocity(); - const real currVel = currLinVel.y; - const Vector3 currPos = mPosition; - // let's do some real work: - Vector3 targetVel = 2 * (mTargetVelocity - currLinVel) * dt; - targetVel.y = 0.; // ! - Vector3 f(0,0,0); - - if (mJumping) - targetVel *= 0.2; // player is less able to control direction during jump - so scale influence - if (mJumpStartInProgress) { - mActor->getBody().addForce( Force(Vector3(0,40,0), RF_GLOBAL, mJumpTime) ); + mActor->getBody().addForce( Force( mUp * 40, RF_GLOBAL, mJumpTime) ); mJumpStartInProgress = false; return; } + + YAKE_ASSERT( dt > 0. ); + if (dt < 0.) + return; + + // determine local linear velocity vector and 'upwards' scalar velocity value. + const Vector3 currLinVel = mActor->getBody().getLinearVelocity(); + const Vector3 localCurrLinVel = mOrientation.Inverse() * currLinVel; + const real currUpVel = localCurrLinVel.y; + + // + const real targetHeightAboveGround = mDucking ? mHeightAboveGroundDuck : mHeightAboveGround; if (mRay->intersects()) { - if (mJumping && !mJumpStartInProgress && currVel < -0.01) // jumping & downwards movement + if (mJumping && !mJumpStartInProgress && currUpVel < -0.01) // jumping & downwards movement { if (mRay->intersectionDepth() < targetHeightAboveGround) mJumping = false; } if (!mJumping) { - const Vector3 targetPoint = mRay->intersectionPoint() - + Vector3::kUnitY * targetHeightAboveGround; + const Point3 intPoint = mRay->intersectionPoint(); + // this is the 'ideal position' + const Point3 targetPoint = intPoint + mUp * targetHeightAboveGround; + + // determine current height above ground/object + const Vector3 vCurrHeightAboveGround = (mPosition - intPoint); + const real currHeightAboveGround = + fabs((mOrientation.Inverse() * vCurrHeightAboveGround).y); + // distToTarget < 0 if player is above ideal position // distToTarget > 0 if player is beneath ideal position - const real distToTarget = (targetPoint.y - currPos.y); + const real distToTarget = targetHeightAboveGround - currHeightAboveGround; if (distToTarget < 0.) // if above ideal position - do nothing {} @@ -181,34 +187,68 @@ //@todo make all this spring and damping stuff configurable... const real k = real(1.1); const real f1 = k * real(20.) * distToTarget; - const real f2 = k * real(10.) * currVel; + const real f2 = k * real(10.) * currUpVel; - f = Vector3::kUnitY * (f1 - f2); + // upwards force to keep the avatar floating + real f = (f1 - f2); + if (f > 0.001) + { + mActor->getBody().addForce( Force(mUp * f, RF_GLOBAL) ); + } } } } - const Vector3 force = - (dt == 0.) ? Vector3::kZero : - (f + (mActor->getBody().getMass() * (targetVel / dt))); + // velocity/forces in avatar's movement plane: + Vector3 localTargetVel = mCurrMoveInPlane * 15./*maxVel*/; //@todo make configurable + localTargetVel = (localTargetVel - localCurrLinVel); + localTargetVel.y = 0.; + if (mJumping) + localTargetVel *= 0.2; // player is less able to control direction during jump - so scale influence + if (localTargetVel.length() > 0.001) + { + Vector3 forceInLocalPlane = mActor->getBody().getMass() * (localTargetVel); + forceInLocalPlane = mOrientation * forceInLocalPlane; + mActor->getBody().addForce( Force(forceInLocalPlane, RF_GLOBAL) ); + } - if (force.length() > 0.01) - mActor->getBody().addForce( 1./*mDynamicsInfluence?*/ * force ); + // + this->_updateOrientation(); } //----------------------------------------------------- + void OdeAvatar::_updateOrientation() + { + YAKE_ASSERT(mActor); + const Vector3 linVel = mActor->getBody().getLinearVelocity(); + { + const Vector3 right = mUp.crossProduct( mCurrDirection ).normalisedCopy(); + mCurrDirection = right.crossProduct( mUp ).normalisedCopy(); + mOrientation.FromAxes( right.normalisedCopy(), mUp.normalisedCopy(), mCurrDirection.normalisedCopy() ); + } + } + + //----------------------------------------------------- void OdeAvatar::onPreStepInternal(const real dt) { - _updateRayData(); + this->_updateRayData(); mRay->_clearIntersection(); mTopRay->_clearIntersection(); + + //@todo fix gravity + mActor->getBody().addForce( Force(-mUp*9.81, RF_GLOBAL) ); + //mActor->getBody().addForce( Force(-mUp*4, RF_GLOBAL) ); } //----------------------------------------------------- void OdeAvatar::_updateRayData() { - mRay->setPosition( mPosition/*ball position*/ ); - mTopRay->setPosition( mPosition/*ball position*/ ); + // downwards ray sensor + mRay->setPosition( mPosition ); + mRay->setDirection( -mUp ); + // upwards ray sensor + mTopRay->setPosition( mPosition ); + mTopRay->setDirection( mUp ); } //----------------------------------------------------- @@ -232,10 +272,19 @@ } //----------------------------------------------------- + void OdeAvatar::move( const Vector3& vel ) + { + YAKE_ASSERT( vel.length() < 1.01 ); + mCurrMoveInPlane = vel.normalisedCopy(); + mCurrMoveInPlane.y = 0; // up is ignored + } + //----------------------------------------------------- + /* void OdeAvatar::setTargetVelocity( const Vector3& vel ) { mTargetVelocity = vel; } + */ //----------------------------------------------------- void OdeAvatar::jump() @@ -270,17 +319,18 @@ //----------------------------------------------------- void OdeAvatar::setPosition( const Vector3& rPosition ) { + YAKE_ASSERT( mActor ); mPosition = rPosition; - if (mActor) - mActor->setPosition( mPosition ); + mActor->setPosition( mPosition ); } //----------------------------------------------------- void OdeAvatar::setOrientation( const Quaternion& rOrientation ) { + YAKE_ASSERT( mActor ); mOrientation = rOrientation; - if (mActor) - mActor->setOrientation( mOrientation ); + mActor->setOrientation( mOrientation ); + mCurrDirection = mOrientation * Vector3::kUnitZ; } //----------------------------------------------------- @@ -294,10 +344,14 @@ //----------------------------------------------------- Quaternion OdeAvatar::getOrientation() const { - if (mActor) - mOrientation = mActor->getOrientation(); return mOrientation; } + //----------------------------------------------------- + void OdeAvatar::setGravityDirection( const Vector3& rkGravityDirection ) + { + mUp = -rkGravityDirection.normalisedCopy(); + } + } // physics } // yake Modified: trunk/yake/src/yapp/samples/misc/cmdrmayhem/yakeDemo.cpp =================================================================== --- trunk/yake/src/yapp/samples/misc/cmdrmayhem/yakeDemo.cpp 2006-11-01 15:11:59 UTC (rev 1486) +++ trunk/yake/src/yapp/samples/misc/cmdrmayhem/yakeDemo.cpp 2006-11-01 15:15:05 UTC (rev 1487) @@ -12,11 +12,83 @@ #include <CEGUI/CEGUIExceptions.h> #include <CEGUI/CEGUIString.h> +#define DEMO_USES_SPHERE + using namespace yake; const input::ActionId ACTIONID_ZOOM_INOUT( input::ACTIONID_USER + 1, "zoom_inout" ); const input::ActionId ACTIONID_MOUSE_MOVE( input::ACTIONID_USER + 2, "mouse_move" ); +const input::ActionId ACTIONID_NEXT_CAMERA( input::ACTIONID_USER + 3, "next_camera" ); +struct CoordSys : public Movable +{ +private: + CoordSys(const CoordSys&); + CoordSys& operator=(const CoordSys&); +public: + CoordSys(graphics::IWorld& w) + { + sn_.reset( w.createSceneNode() ); + for (size_t i=0; i<3; ++i) + { + graphics::ISceneNode* sn = sn_->createChildNode(); + graphics::IEntity* ent = w.createEntity("pyramid_1x1x1.mesh"); + sn->attachEntity( ent ); + Quaternion q; + if (i==0) // x + { + q.FromAngleAxis( 0.5*3.14, Vector3::kUnitY ); + ent->setMaterial( "pyramid_red" ); + } + else if (i==1) // y + { + q.FromAngleAxis( -0.5*3.14, Vector3::kUnitX ); + ent->setMaterial( "pyramid_green" ); + } + else // z + { + q.FromAngleAxis( 0, Vector3::kUnitY ); + ent->setMaterial( "pyramid_blue" ); + } + sn->setOrientation( q ); + sn->setScale(Vector3(1,1,5)); + } + } + ~CoordSys() + { + sn_.reset(); + } + virtual void setPosition( const Vector3& rPosition ) + { + sn_->setPosition( rPosition ); + } + virtual void setOrientation( const Quaternion& rOrientation ) + { + std::cout << "cs.x=" << rOrientation * Vector3::kUnitX << " "; + std::cout << "cs.y=" << rOrientation * Vector3::kUnitY << " "; + std::cout << "cs.z=" << rOrientation * Vector3::kUnitZ << "\n"; + sn_->setOrientation( rOrientation ); + } + virtual Vector3 getPosition() const + { + return sn_->getPosition(); + } + virtual Quaternion getOrientation() const + { + return sn_->getOrientation(); + } + virtual Vector3 getDerivedPosition() const + { + return sn_->getDerivedPosition(); + } + virtual Quaternion getDerivedOrientation() const + { + return sn_->getDerivedOrientation(); + } +private: + SharedPtr<graphics::ISceneNode> sn_; +}; + /** Configuration of the application */ struct TheConfiguration : public raf::ApplicationConfiguration { @@ -70,7 +142,9 @@ void unbindInput(); void update(const real dt); void setDirection(const Vector3&); - Vector3 getPosition() const; + Point3 getPosition() const; + void setPosition(const Point3&); + Quaternion getOrientation() const; private: ControllableCharacter(const ControllableCharacter&); ControllableCharacter& operator=(const ControllableCharacter&); @@ -90,6 +164,10 @@ { mActiveActions.insert( input::ACTIONID_RIGHT ); } void onCrouch() { mActiveActions.insert( input::ACTIONID_DOWN ); } + void onRotateLeft() + { mActiveActions.insert( input::ACTIONID_ROTATE_LEFT ); } + void onRotateRight() + { mActiveActions.insert( input::ACTIONID_ROTATE_RIGHT ); } private: physics::IAvatarPtr mPlayerRep; model::Model* mPlayerModel; @@ -104,6 +182,8 @@ ActionIdList mActiveActions; Vector3 mMouseMovement; Quaternion mProjViewRot; + + SharedPtr<CoordSys> mCoordSys; }; ControllableCharacter::ControllableCharacter( model::CentralControllerBase& centralCtrlr, @@ -112,8 +192,8 @@ { mPlayerRep = pworld.createAvatar( physics::IAvatar::Desc( - math::Vector3(0.5,2,0), // dimensions - math::Vector3(0,real(0.1),0) // initial position (relative to stable position) + Vector3(0.5,2,0), // dimensions + Vector3(0,real(0.1),0) // initial position (relative to stable position) ) ); YAKE_ASSERT( mPlayerRep ); @@ -125,7 +205,7 @@ pG->addSceneNode( pSN, "playerSN" ); graphics::IEntity* pE = gworld.createEntity("sphere_d1.mesh"); pSN->attachEntity( pE ); - pSN->setScale( 0.5 * math::Vector3::kUnitScale ); + pSN->setScale( 0.5 * Vector3::kUnitScale ); model::ModelMovableDirectLink* pLink = new model::ModelMovableDirectLink(); mPlayerModel->addLink( pLink ); @@ -134,6 +214,7 @@ pLink->subscribeToOrientationChanged( pSN ); centralCtrlr.subscribeToGraphicsUpdate( Bind2(&model::ModelMovableDirectLink::update,pLink) ); } + mCoordSys.reset( new CoordSys(gworld) ); } ControllableCharacter::~ControllableCharacter() { @@ -145,6 +226,11 @@ } YAKE_SAFE_DELETE( mPlayerModel ); } +void ControllableCharacter::setPosition(const Point3& pos) +{ + YAKE_ASSERT( mPlayerRep ); + mPlayerRep->setPosition( pos ); +} void ControllableCharacter::bindInput(input::ActionMap& actionMap, input::KeyboardDevice* keyboard, input::MouseDevice* mouse) @@ -164,6 +250,10 @@ this->addInputSignalConnection( actionMap.subscribeToActionIdV( ACTIONID_RIGHT, boost::bind(&ControllableCharacter::onRight,this) ) ); this->addInputSignalConnection( + actionMap.subscribeToActionIdV( ACTIONID_ROTATE_LEFT, boost::bind(&ControllableCharacter::onRotateLeft,this) ) ); + this->addInputSignalConnection( + actionMap.subscribeToActionIdV( ACTIONID_ROTATE_RIGHT, boost::bind(&ControllableCharacter::onRotateRight,this) ) ); + this->addInputSignalConnection( actionMap.subscribeToActionIdV( ACTIONID_FORWARD, boost::bind(&ControllableCharacter::onForward,this) ) ); this->addInputSignalConnection( actionMap.subscribeToActionIdV( ACTIONID_REVERSE, boost::bind(&ControllableCharacter::onReverse,this) ) ); @@ -193,45 +283,77 @@ void ControllableCharacter::setDirection(const Vector3& dir) { const Vector3 normalisedDir = dir.normalisedCopy(); - mProjViewRot.FromAxes( normalisedDir.crossProduct( math::Vector3::kUnitY ), math::Vector3::kUnitY, -normalisedDir ); + mProjViewRot.FromAxes( normalisedDir.crossProduct( Vector3::kUnitY ), Vector3::kUnitY, -normalisedDir ); } void ControllableCharacter::update(const real dt) { // - const real maxVel = real(3.0); - math::Vector3 playerTargetVel; + const real maxAng = 3.14; + real ang = 0.; + Vector3 playerTargetVel; ConstDequeIterator< ActionIdList > itAction( mActiveActions ); while (itAction.hasMoreElements()) { const input::ActionId activeId = itAction.getNext(); if (activeId == input::ACTIONID_FORWARD) - playerTargetVel += math::Vector3(0,0,+1); + playerTargetVel += Vector3(0,0,+1); else if (activeId == input::ACTIONID_REVERSE) - playerTargetVel += math::Vector3(0,0,-1); + playerTargetVel += Vector3(0,0,-1); else if (activeId == input::ACTIONID_LEFT) - playerTargetVel += math::Vector3(+1,0,0); + playerTargetVel += Vector3(+1,0,0); //x=1 is left vector! else if (activeId == input::ACTIONID_RIGHT) - playerTargetVel += math::Vector3(-1,0,0); + playerTargetVel += Vector3(-1,0,0); else if (activeId == input::ACTIONID_UP) mPlayerRep->jump(); + else if (activeId == input::ACTIONID_ROTATE_LEFT) + ang += maxAng; + else if (activeId == input::ACTIONID_ROTATE_RIGHT) + ang -= maxAng; else if (activeId == input::ACTIONID_DOWN) { mPlayerRep->duck( !mPlayerRep->isDucking() ); } } - playerTargetVel.normalise(); - playerTargetVel = mProjViewRot * playerTargetVel; - mPlayerRep->setTargetVelocity( playerTargetVel.normalisedCopy() * maxVel ); + if (playerTargetVel.length() > 0.001) + { + playerTargetVel.normalise(); + mPlayerRep->move( playerTargetVel ); // velocity relative to player's orientation + } + else + mPlayerRep->move( Vector3::kZero ); + // newUp = gravity_source to position +#ifdef DEMO_USES_SPHERE + const Vector3 newGravityVector = (Vector3::kZero/*source of gravity*/ - mPlayerRep->getPosition()).normalisedCopy(); + mPlayerRep->setGravityDirection( newGravityVector ); +#else + mPlayerRep->setGravityDirection( Vector3(0,1,0) ); +#endif + if (fabs(ang) > 0.001) + { + Quaternion rot( ang * dt, mPlayerRep->getOrientation() * Vector3::kUnitY ); + rot = rot * mPlayerRep->getOrientation(); + mPlayerRep->setOrientation( rot ); + } + // prepare for next step mActiveActions.clear(); mMouseMovement = Vector3::kZero; + + // + mCoordSys->setPosition( mPlayerRep->getPosition() ); + mCoordSys->setOrientation( mPlayerRep->getOrientation() ); } Vector3 ControllableCharacter::getPosition() const { YAKE_ASSERT( mPlayerRep ); return mPlayerRep->getPosition(); } +Quaternion ControllableCharacter::getOrientation() const +{ + YAKE_ASSERT( mPlayerRep ); + return mPlayerRep->getOrientation(); +} /** Main application state */ class TheMainState : public raf::RtMainState @@ -267,46 +389,56 @@ { YAKE_LOG_INFORMATION("Creating scene"); - getPhysicalWorld()->setGlobalGravity(Vector3(0,real(-9.8),0)); + //getPhysicalWorld()->setGlobalGravity(Vector3(0,real(-9.8),0)); // create a light graphics::ILight* pLight = getGraphicalWorld()->createLight(); pLight->setType( graphics::ILight::LT_DIRECTIONAL ); - pLight->setDirection( math::Vector3(0,-1,1) ); + pLight->setDirection( Vector3(0,-1,1) ); getGraphicalWorld()->createSceneNode("lightnode0")->attachLight( pLight ); getGraphicalWorld()->setShadowsEnabled( true ); // position camera and look at the ninja getDefaultCamera()->setNearClipDistance( 1 ); - getDefaultCamera()->setFixedYawAxis(math::Vector3::kUnitY); - getDefaultCamera()->setPosition(math::Vector3(7,4,-7)); + getDefaultCamera()->setFixedYawAxis(Vector3::kUnitY); + getDefaultCamera()->setPosition(Vector3(7,4,-7)); // create ground mGround = new model::Model(); { - const real groundHeight = 0; + const real groundHeight = 50; // visual +#ifndef DEMO_USES_SPHERE graphics::ISceneNode* pGroundSN = getGraphicalWorld()->createSceneNode(); graphics::IEntity* pGroundE = getGraphicalWorld()->createEntity("plane_1x1.mesh"); pGroundE->setMaterial("box"); pGroundE->setCastsShadow( false ); pGroundSN->attachEntity( pGroundE ); - pGroundSN->setScale( math::Vector3(100,1,100) ); - pGroundSN->setPosition( math::Vector3(0,groundHeight,0) ); + pGroundSN->setScale( Vector3(100,1,100) ); + pGroundSN->setPosition( Vector3(0,-groundHeight,0) ); model::Graphical* pG = new model::Graphical(); pG->addSceneNode( pGroundSN, "ground", true ); mGround->addComponent( pG, "p" ); +#endif // physical physics::IActorPtr pGroundPlane = getPhysicalWorld()->createActor( physics::ACTOR_STATIC ); - pGroundPlane->createShape( physics::IShape::PlaneDesc( math::Vector3(0,1,0), groundHeight ) ); +#ifdef DEMO_USES_SPHERE + pGroundPlane->createShape( physics::IShape::SphereDesc( real(groundHeight) ) ); +#else + pGroundPlane->createShape( physics::IShape::PlaneDesc( Vector3(0,-1,0), groundHeight ) ); +#endif model::Physical* pP = new model::Physical(); pP->addActor( pGroundPlane, "groundPlane" ); mGround->addComponent( pP, "g" ); } + // +#ifdef DEMO_USES_SPHERE + getGraphicalWorld()->load("osm","C:/Programme/Autodesk/3dsMax8/OSM/geo1.osm"); +#endif // sky box getGraphicalWorld()->setSkyBox("Examples/SpaceSkyBox"); @@ -320,15 +452,36 @@ // create player/avatar mPlayer.reset( new ControllableCharacter(*this,*getGraphicalWorld(),*getPhysicalWorld()) ); + //mPlayer->setPosition( Point3(0,-52,0) ); // 2 meters above the 50 m radius sphere + mPlayer->setPosition( Point3(-25.967,44.376,0.9326) ); - // top-down camera controller - mTopDownCtrlr.setOffset( math::Vector3(10,10,-10) ); - mTopDownCtrlr.setTargetOffset( math::Vector3(10,10,-10) ); - mTopDownCtrlr.setCamera( getDefaultCamera() ); + // camera controllers + { // top-down camera controller + TopDownCameraController* ctrlr = new TopDownCameraController(); + ctrlr->setCamera( getDefaultCamera() ); + ctrlr->setOffset( Vector3(40,0,0) ); + ctrlr->setTargetOffset( Vector3(40,0,0) ); + mCamControllers.push_back( CameraControllerPtr(ctrlr) ); + } + { // 3rd person camera controller + ThirdPersonCameraController* ctrlr = new ThirdPersonCameraController(); + ctrlr->setCamera( getDefaultCamera() ); + + ctrlr->setOffsetFromTarget( Vector3(0,1.5,2) ); + ctrlr->setCurrentOffsetFromTarget( ctrlr->getOffsetFromTarget() ); + + // slightly downwards + ctrlr->setOffsetOrientation( Quaternion( -0.5, Vector3::kUnitX ) ); + ctrlr->setCurrentOffsetOrientation( ctrlr->getOffsetOrientation() ); + + mCamControllers.push_back( CameraControllerPtr(ctrlr) ); + } + mCurrentCamController = 0; + } virtual void onDestroyScene() { - mTopDownCtrlr.setCamera( 0 ); + mCamControllers.clear(); mPlayer.reset(); YAKE_SAFE_DELETE( mGround ); YAKE_SAFE_DELETE( mEnv ); @@ -342,8 +495,14 @@ if (mPlayer) mPlayer->bindInput( mActionMap, getApp().getKeyboard(), getApp().getMouse() ); + YAKE_ASSERT( !mCamControllers.empty() ); + + // + mActionMap.reg( ACTIONID_NEXT_CAMERA, new KeyboardActionCondition( getApp().getKeyboard(), input::KC_1, input::KAM_RELEASED ) ); + mActionMap.subscribeToActionIdV( ACTIONID_NEXT_CAMERA, BindX(&TheMainState::onNextCamera,this) ); + // top-down controller - // @todo unsubscribe + // @todo unsubscribe; move out into top down controller's bindInput() mActionMap.reg( ACTIONID_ZOOM_INOUT, new MouseMoveActionCondition( getApp().getMouse(), input::MMA_WHEEL, input::MMD_BOTH ) ); mActionMap.subscribeToActionIdR( ACTIONID_ZOOM_INOUT, Bind1(&TheMainState::onMouseWheel,this) ); @@ -378,54 +537,69 @@ // if (mPlayer) { + /* Vector3 projViewDir = mTopDownCtrlr.getOffset(); projViewDir.y = 0.; if (projViewDir.length() <= 0.01) - projViewDir = math::Vector3::kUnitZ; + projViewDir = Vector3::kUnitZ; projViewDir.normalise(); mPlayer->setDirection( projViewDir ); - + */ mPlayer->update( timeElapsed ); } + CameraControllerPtr currCamCtrlr = mCamControllers.at(mCurrentCamController); + YAKE_ASSERT( currCamCtrlr.get() ); + + //@todo hide properly + if (TopDownCameraController* topdownCtrlr = dynamic_cast<TopDownCameraController*>(currCamCtrlr.get())) { // top-down controller const real dist = timeElapsed * real(4.); - math::Vector3 offset; + Vector3 offset; if (this->getApp().getKeyboard()->isKeyDown(input::KC_I)) - offset += dist * math::Vector3::kUnitZ; + offset += dist * Vector3::kUnitZ; if (this->getApp().getKeyboard()->isKeyDown(input::KC_K)) - offset += - dist * math::Vector3::kUnitZ; + offset += - dist * Vector3::kUnitZ; if (this->getApp().getKeyboard()->isKeyDown(input::KC_J)) - offset += dist * math::Vector3::kUnitX; + offset += dist * Vector3::kUnitX; if (this->getApp().getKeyboard()->isKeyDown(input::KC_L)) - offset += - dist * math::Vector3::kUnitX; - mTopDownCtrlr.setOffset( mTopDownCtrlr.getOffset() + offset ); - mTopDownCtrlr.setTargetOffset( mTopDownCtrlr.getTargetOffset() + offset ); - } + offset += - dist * Vector3::kUnitX; + if (this->getApp().getKeyboard()->isKeyDown(input::KC_R)) + offset += dist * Vector3::kUnitY; + if (this->getApp().getKeyboard()->isKeyDown(input::KC_F)) + offset += - dist * Vector3::kUnitY; + topdownCtrlr->setOffset( topdownCtrlr->getOffset() + offset ); + topdownCtrlr->setTargetOffset( topdownCtrlr->getTargetOffset() + offset ); - mTopDownCtrlr.setTarget( mPlayer->getPosition() ); + topdownCtrlr->setTarget( mPlayer->getPosition() ); - // Rotate camera around camera's 'up' axis - // when user presses RMB and moves the mouse. - if (this->getApp().getMouse()->isButtonDown( input::MB_RIGHT )) - { - // @todo adjust rotation over several frames for smoother rotation. - const real angle = mMouseMovement.x * real(100.) * timeElapsed; - Matrix3 rot; - rot.FromAxisAngle( Vector3::kUnitY, angle ); + // Rotate camera around camera's 'up' axis + // when user presses RMB and moves the mouse. + if (this->getApp().getMouse()->isButtonDown( input::MB_RIGHT )) + { + // @todo adjust rotation over several frames for smoother rotation. + const real angle = mMouseMovement.x * real(100.) * timeElapsed; + Matrix3 rot; + rot.FromAxisAngle( Vector3::kUnitY, angle ); - // NB rotate both 'target offset' and 'current offset' so that - // relative to each other they stay the same. + // NB rotate both 'target offset' and 'current offset' so that + // relative to each other they stay the same. - Vector3 offset = rot * mTopDownCtrlr.getTargetOffset(); - mTopDownCtrlr.setTargetOffset( offset ); + Vector3 offset = rot * topdownCtrlr->getTargetOffset(); + topdownCtrlr->setTargetOffset( offset ); - offset = rot * mTopDownCtrlr.getOffset(); - mTopDownCtrlr.setOffset( offset ); + offset = rot * topdownCtrlr->getOffset(); + topdownCtrlr->setOffset( offset ); + } } + else if (ThirdPersonCameraController* ctrlr = dynamic_cast<ThirdPersonCameraController*>(currCamCtrlr.get())) + { + ctrlr->setTargetPosition( mPlayer->getPosition() ); + ctrlr->setTargetOrientation( mPlayer->getOrientation() ); + } // - mTopDownCtrlr.update( timeElapsed ); + currCamCtrlr->update( timeElapsed ); // prepare for next step mActiveActions.clear(); @@ -450,6 +624,12 @@ } } private: + void onNextCamera() + { + ++mCurrentCamController; + if (mCurrentCamController >= mCamControllers.size()) + mCurrentCamController = 0; + } void onMouseMoveXY(const input::ActionMap::ActionResult& ar) { mMouseMovement = ar.signal * 10.; @@ -457,7 +637,8 @@ mMouseMovement.y = 0.; } void onMouseWheel(const input::ActionMap::ActionResult& ar) - { + { + /** @todo move out into CameraControllerBase::init() ... if (fabs(ar.signal.z) < std::numeric_limits<real>::epsilon()) return; @@ -472,6 +653,7 @@ // apply mTopDownCtrlr.setTargetOffset( targetOffset ); + */ } private: model::Model* mGround; @@ -482,7 +664,11 @@ Env* mEnv; - TopDownCameraController mTopDownCtrlr; + typedef SharedPtr<CameraControllerBase> CameraControllerPtr; + typedef std::deque<CameraControllerPtr> CameraControllerList; + CameraControllerList mCamControllers; + int mCurrentCamController; + Vector3 mMouseMovement; SharedPtr<ControllableCharacter> mPlayer; @@ -500,8 +686,15 @@ } }; +#define WIN32_LEAN_AND_MEAN +#include <windows.h> + int main( int argc, char** argv ) { + // @todo fixme: Workaround on windows because of different timers on different cores... + ::SetProcessAffinityMask( ::GetCurrentProcess(), 0x01 ); + ::SetThreadAffinityMask( ::GetCurrentThread(), 0x01 ); + // Use default executor for convenience. // It's always possible to manually execute TheApp::initialise() etc. TheApp theApp; Modified: trunk/yake/yake/physics/yakePhysicsAvatar.h =================================================================== --- trunk/yake/yake/physics/yakePhysicsAvatar.h 2006-11-01 15:11:59 UTC (rev 1486) +++ trunk/yake/yake/physics/yakePhysicsAvatar.h 2006-11-01 15:15:05 UTC (rev 1487) @@ -55,23 +55,27 @@ public: struct Desc { - Desc( const math::Vector3 & rkDimensions = math::Vector3(0,2,0), - const math::Vector3 & rkPosition = math::Vector3::kZero, - const math::Quaternion & rkOrientation = math::Quaternion::kIdentity) : + Desc( const Vector3 & rkDimensions = Vector3(0,2,0), + const Vector3 & rkPosition = Vector3::kZero, + const Quaternion & rkOrientation = Quaternion::kIdentity) : position( rkPosition ), orientation( rkOrientation ), dimensions( rkDimensions ) {} - math::Vector3 position; - math::Quaternion orientation; - math::Vector3 dimensions; + Vector3 position; + Quaternion orientation; + Vector3 dimensions; }; public: - virtual void setDimensions( const math::Vector3 & rkDimensions ) = 0; + virtual void setDimensions( const Vector3 & rkDimensions ) = 0; virtual void setInfluenceByDynamics( const real ratio ) = 0; - virtual void setTargetVelocity( const math::Vector3 & rkTargetVelocity ) = 0; + virtual void setGravityDirection( const Vector3& rkGravityDirection ) = 0; + //virtual void setTargetVelocity( const Vector3 & rkTargetVelocity ) = 0; + + //@todo should actually be a Vector2! in plane of current player. y ("up") is ignored. + virtual void move( const Vector3& ) = 0; // max values [-1,+1] virtual void jump() = 0; virtual bool isJumping() const = 0; virtual void duck(const bool yes) = 0; Modified: trunk/yake/yake/physics/yakePhysicsCommon.h =================================================================== --- trunk/yake/yake/physics/yakePhysicsCommon.h 2006-11-01 15:11:59 UTC (rev 1486) +++ trunk/yake/yake/physics/yakePhysicsCommon.h 2006-11-01 15:15:05 UTC (rev 1487) @@ -22,7 +22,7 @@ /** single step */ Force(const Vector3&, const ReferenceFrame, const Point3&, const ReferenceFrame); - /** global position */ + /** relative to local position (0,0,0) */ Force(const Vector3&, const ReferenceFrame, const real duration); Force(const Vector3&, const ReferenceFrame refValue = RF_GLOBAL); Force(const Force&); Modified: trunk/yake/yake/plugins/physicsODE/OdeAvatar.h =================================================================== --- trunk/yake/yake/plugins/physicsODE/OdeAvatar.h 2006-11-01 15:11:59 UTC (rev 1486) +++ trunk/yake/yake/plugins/physicsODE/OdeAvatar.h 2006-11-01 15:15:05 UTC (rev 1487) @@ -47,17 +47,20 @@ bool init(const IAvatar::Desc&); - virtual void setPosition( const math::Vector3& rPosition ); - virtual void setOrientation( const math::Quaternion& rOrientation ); - virtual math::Vector3 getPosition() const; - virtual math::Vector3 getDerivedPosition() const { return getPosition(); }//FIXME is this enough? - virtual math::Quaternion getOrientation() const; - virtual math::Quaternion getDerivedOrientation() const { return getOrientation(); }//FIXME is this enough? + virtual void setPosition( const Vector3& rPosition ); + virtual void setOrientation( const Quaternion& rOrientation ); + virtual Vector3 getPosition() const; + virtual Vector3 getDerivedPosition() const { return getPosition(); }//FIXME is this enough? + virtual Quaternion getOrientation() const; + virtual Quaternion getDerivedOrientation() const { return getOrientation(); }//FIXME is this enough? - virtual void setDimensions( const math::Vector3& rkDimensions ); + virtual void setDimensions( const Vector3& rkDimensions ); virtual void setInfluenceByDynamics( const real ratio ); - virtual void setTargetVelocity( const math::Vector3& rkTargetVelocity ); + virtual void setGravityDirection( const Vector3& rkGravityDirection ); + //virtual void setTargetVelocity( const Vector3& rkTargetVelocity ); + virtual void move( const Vector3& ); + virtual void jump(); virtual bool isJumping() const; virtual void duck(const bool yes); @@ -76,13 +79,17 @@ void onPreStepInternal(const real dt); void onPostStepInternal(const real dt); void _updateRayData(); + void _updateOrientation(); private: - mutable math::Vector3 mPosition; - mutable math::Quaternion mOrientation; + mutable Vector3 mPosition; + mutable Quaternion mOrientation; + Vector3 mCurrDirection; + Vector3 mUp; + Vector3 mCurrMoveInPlane; - math::Vector3 mDimensions; + Vector3 mDimensions; real mDynamicsInfluence; - math::Vector3 mTargetVelocity; + //Vector3 mTargetVelocity; bool mJumping; bool mJumpStartInProgress; @@ -99,7 +106,7 @@ double mTopRayLength; double mSphereRadius; - math::Vector3 mSphereOffset; + Vector3 mSphereOffset; real mHeightAboveGround; real mHeightAboveGroundDuck; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2006-11-01 15:20:33
|
Revision: 1492 http://svn.sourceforge.net/yake/?rev=1492&view=rev Author: psyclonist Date: 2006-11-01 07:19:39 -0800 (Wed, 01 Nov 2006) Log Message: ----------- refactored yake::net Modified Paths: -------------- trunk/yake/src/yake/net/detail/netEnetClientPacketConnection.cpp trunk/yake/src/yake/net/detail/netEnetServerPacketConnection.cpp trunk/yake/src/yake/net/detail/netEventConnection.cpp trunk/yake/src/yake/net/detail/netInternal.cpp trunk/yake/src/yake/samples/net/packet/demo.cpp trunk/yake/src/yake/samples/net/roclient/ROClient.cpp trunk/yake/src/yake/samples/net/roclient/demo.cpp trunk/yake/src/yake/samples/net/roserver/ROServer.cpp trunk/yake/yake/net/netEvent.h trunk/yake/yake/net/netPacket.h trunk/yake/yake/samples/net/common/commonEvents.h trunk/yake/yake/samples/net/roclient/ROClient.h trunk/yake/yake/samples/net/roserver/ROServer.h Modified: trunk/yake/src/yake/net/detail/netEnetClientPacketConnection.cpp =================================================================== --- trunk/yake/src/yake/net/detail/netEnetClientPacketConnection.cpp 2006-11-01 15:18:35 UTC (rev 1491) +++ trunk/yake/src/yake/net/detail/netEnetClientPacketConnection.cpp 2006-11-01 15:19:39 UTC (rev 1492) @@ -113,10 +113,9 @@ if (m_host) { if (m_serverPeer) - { - //boost::mutex::scoped_lock enetLock(getEnetMtx()); enet_peer_disconnect( m_serverPeer, 0 /*@todo data*/ ); - } + + /*@todo handle graceful disconnects... Timer timer; timer.start(); while (timer.getTime() < 1) @@ -124,17 +123,14 @@ net::update(); net::native::sleep(10); } - { - //boost::mutex::scoped_lock enetLock(getEnetMtx()); - enet_peer_reset( m_peer ); - enet_host_destroy( m_host ); - m_host = 0; - } + */ + + enet_peer_reset( m_peer ); + enet_host_destroy( m_host ); + m_host = 0; } - { - m_ready = false; - m_serverIp = ""; - } + m_ready = false; + m_serverIp = ""; m_serverPeer = 0; } void EnetClientPacketConnection::update() Modified: trunk/yake/src/yake/net/detail/netEnetServerPacketConnection.cpp =================================================================== --- trunk/yake/src/yake/net/detail/netEnetServerPacketConnection.cpp 2006-11-01 15:18:35 UTC (rev 1491) +++ trunk/yake/src/yake/net/detail/netEnetServerPacketConnection.cpp 2006-11-01 15:19:39 UTC (rev 1492) @@ -124,12 +124,11 @@ { if (m_host->peerCount > 0) { - { - //boost::mutex::scoped_lock enetLock(getEnetMtx()); - // try to gracefully disconnect clients - for (size_t i=0; i<m_host->peerCount; ++i) - enet_peer_disconnect( &m_host->peers[i], 0 /*@todo data*/ ); - } + // try to gracefully disconnect clients + for (size_t i=0; i<m_host->peerCount; ++i) + enet_peer_disconnect( &m_host->peers[i], 0 /*@todo data*/ ); + + /** @todo handle graceful disconnects... Timer timer; timer.start(); while (timer.getTime() < 2) // wait 2 seconds for acknowledgement @@ -137,6 +136,8 @@ net::update(); net::native::sleep(10); } + */ + // forcefully disconnect remaining clients if (m_host->peerCount > 0) { @@ -145,11 +146,8 @@ enet_peer_reset( &m_host->peers[i] ); } } - { - //boost::mutex::scoped_lock enetLock(getEnetMtx()); - enet_host_destroy( m_host ); - m_host = 0; - } + enet_host_destroy( m_host ); + m_host = 0; } } m_ip2string.clear(); @@ -214,7 +212,8 @@ const double deltaT = max(currT - m_timeOfLastUpdate, 0.0001); NET_ASSERT( deltaT > 0. )(deltaT); PeerToClientMap::iterator itEnd = m_clients.end(); - for (PeerToClientMap::iterator it = m_clients.begin(); it != itEnd; ++it) + PeerToClientMap::iterator it = m_clients.begin(); + while (it != itEnd) { Client* c = it->second; NET_ASSERT(c); @@ -227,6 +226,27 @@ this->disconnect( c->id ); } } + else if (c->state == CS_DISCONNECTING) // graceful disconnections + { + c->timeLeft_ -= deltaT; + if (c->timeLeft_ < 0.) + { + NET_LOG("net_packet_server: client could not be gracefully disconnected. => killed."); + enet_peer_reset( c->peer ); + c->state = CS_DEAD; + PeerToClientMap::iterator itnext = it; + ++itnext; + m_id2client.erase( m_id2client.find( c->id ) ); + m_clients.erase( it ); + it = itnext; + fireCallback_ClientDisconnected( c->id ); + delete c; + c = 0; + continue; + } + } + // next + ++it; } m_timeOfLastUpdate = currT; } Modified: trunk/yake/src/yake/net/detail/netEventConnection.cpp =================================================================== --- trunk/yake/src/yake/net/detail/netEventConnection.cpp 2006-11-01 15:18:35 UTC (rev 1491) +++ trunk/yake/src/yake/net/detail/netEventConnection.cpp 2006-11-01 15:19:39 UTC (rev 1492) @@ -145,18 +145,24 @@ out.write( evt.id(), sizeof(NetEvent::id_type)*8 ) ; if (!evt.pack( out )) + { + NET_LOG("EvtConn: failed to pack event with id '" << int(evt.id()) << "'."); return; //@FIXME: inform user + } out.flush(); + NET_LOG("EvtConn: sending " << int(data.size()) << " bytes to '" << int(opt.getPeerId()) << "'."); conn_->send( &data.front(), data.size(), opt ); } void EventConnection::onReceivePacket(const PeerId peerId, const void* dataPtr, const size_t dataLen, const ChannelId channel) { + NET_LOG("EvtConn: received " << int(dataLen) << " bytes from '" << int(peerId) << "'."); NET_ASSERT( dataPtr && dataLen > 0 ); NET_ASSERT( dataLen >= sizeof(event_id) ); if (dataLen < sizeof(event_id)) { ++stats_.numInvalidPackets; + NET_LOG("EvtConn: invalid packet"); return; //@FIXME increase error count !? } @@ -171,18 +177,20 @@ ibitstream in(&dataSource); // extract event id - event_id evtId = NetEvent::EVTID_NONE; + event_id evtId = 0; in.read( evtId, sizeof(NetEvent::id_type)*8 ); // check event id EventIdMap::const_iterator it = eventIds_.find( evtId ); if (it == eventIds_.end()) { + NET_LOG("EvtConn: received unregistered event id '" << int(evtId) << "'."); ++stats_.numUnregisteredEventIds; return; } if (evtId == NetEvent::EVTID_NONE) { + NET_LOG("EvtConn: received invalid event id '" << int(evtId) << "'."); ++stats_.numInvalidEventIds; return; } @@ -192,6 +200,7 @@ { if (!contains(allowedEventIds_,evtId)) { + NET_LOG("EvtConn: blocked event id '" << int(evtId) << "'."); ++stats_.numBlockedEventIds; return; } @@ -204,6 +213,7 @@ { if (dir_ == evtDir) { + NET_LOG("EvtConn: wrong direction for event id '" << int(evtId) << "'."); ++stats_.numWrongEventDirection; return; } @@ -220,6 +230,7 @@ if (!evt->unpack(in)) { fnDestroy(evt); + NET_LOG("EvtConn: failed to unpack event with id '" << int(evtId) << "'."); ++stats_.numInvalidEvents; return; } Modified: trunk/yake/src/yake/net/detail/netInternal.cpp =================================================================== --- trunk/yake/src/yake/net/detail/netInternal.cpp 2006-11-01 15:18:35 UTC (rev 1491) +++ trunk/yake/src/yake/net/detail/netInternal.cpp 2006-11-01 15:19:39 UTC (rev 1492) @@ -80,7 +80,7 @@ it->second(); } } - native::sleep(10); + native::sleep(0); } } uint32 UpdateThread::add( const UpdateFn& fn ) Modified: trunk/yake/src/yake/samples/net/packet/demo.cpp =================================================================== --- trunk/yake/src/yake/samples/net/packet/demo.cpp 2006-11-01 15:18:35 UTC (rev 1491) +++ trunk/yake/src/yake/samples/net/packet/demo.cpp 2006-11-01 15:19:39 UTC (rev 1492) @@ -24,8 +24,12 @@ } private: void onStarted(); + bool started() const + { + return started_; + } private: - safe_var<bool> started_; + bool started_; net::Address addr_; net::uint32 maxClients_; net::IServerPacketConnection* conn_; @@ -48,7 +52,7 @@ } bool server::start() { - YAKE_ASSERT( !started_.getCopy() ); + YAKE_ASSERT( !started_ ); YAKE_ASSERT( !conn_ ); YAKE_LOG("creating server...\n"); @@ -67,7 +71,7 @@ YAKE_SAFE_DELETE( conn_ ); return false; } - while (!started_.getCopy()) + while (!started_) { net::native::sleep(10); net::update(); @@ -86,7 +90,7 @@ void server::broadcastHello() { YAKE_ASSERT( conn_ ); - YAKE_ASSERT( started_.getCopy() ); + YAKE_ASSERT( started_ ); std::string hello("hello!"); conn_->send( hello.c_str(), hello.size(), net::SendOptions().reliability(net::R_RELIABLE) ); COUTLN("server:broadcastHello() " << conn_->getNumConnectedClients() << " client(s)"); @@ -114,9 +118,9 @@ { net::IClientPacketConnection* client = net::createClientPacketConnection(); YAKE_ASSERT( client ); - client->connect(net::Address(4000), false /*true=block until connection established or timeout.*/); client->addPacketReceivedCallback( client_onPacketReceived ); clients.push_back( yake::SharedPtr<net::IClientPacketConnection>(client) ); + client->connect(net::Address(4000), false /*true=block until connection established or timeout.*/); } //net::native::sleep(500); // unfortunately, this is still necessary... @@ -128,7 +132,9 @@ { net::native::sleep(10); net::update(); - if (!sentHello && theServer.numConnectedClients() > 0) + + // send hello when at least 3 clients have connected... + if (!sentHello && theServer.numConnectedClients() >= 3) { theServer.broadcastHello(); sentHello = true; Modified: trunk/yake/src/yake/samples/net/roclient/ROClient.cpp =================================================================== --- trunk/yake/src/yake/samples/net/roclient/ROClient.cpp 2006-11-01 15:18:35 UTC (rev 1491) +++ trunk/yake/src/yake/samples/net/roclient/ROClient.cpp 2006-11-01 15:19:39 UTC (rev 1492) @@ -7,175 +7,169 @@ namespace ro { -client::client() : timedOut_(false), conn_(false), running_(false), evtConn_(0), stage_(CS_JOINING) -{ -} -client::~client() -{ - stop(); -} -bool client::running() const -{ - boost::mutex::scoped_lock lck(runningMtx_); - return running_; -} -bool client::start(const net::Address& serverAddr) -{ - try { - // create connection & register callbacks - conn_ = net::createClientPacketConnection(); - assert( conn_ ); + client::client() : + timedOut_(false), running_(false), stage_(CS_JOINING) + { + } + client::~client() + { + stop(); + } + bool client::running() const + { + boost::mutex::scoped_lock lck(runningMtx_); + return running_; + } + bool client::start(const net::Address& serverAddr) + { + try { + // create connection & register callbacks + conn_.reset( net::createClientPacketConnection() ); + assert( conn_ ); - conn_->addTimeOutCallback( boost::bind(&client::onTimeOut,this) ); - conn_->addStartedCallback( boost::bind(&client::onClientStarted,this) ); + conn_->addTimeOutCallback( boost::bind(&client::onTimeOut,this) ); + conn_->addStartedCallback( boost::bind(&client::onClientStarted,this) ); - // attempt to connect to server - conn_->connect( serverAddr ); + // attempt to connect to server + conn_->connect( serverAddr ); - return true; - } - catch (const net::Exception& e) - { - COUTLN("Caught net exception: " << e.what()); - if (conn_) + return true; + } + catch (const net::Exception& e) { - delete conn_; - conn_ = 0; + COUTLN("Caught net exception: " << e.what()); + conn_.reset(); } + return false; } - return false; -} -void client::waitForStart() -{ - while (!timedOut_.getCopy() && !running()) + void client::waitForStart() { - net::native::sleep(10); - net::update(); - } - if (timedOut_.getCopy()) - return; - // set up event connection - assert( conn_ ); - assert( !evtConn_ ); - evtConn_ = net::createEventConnection(); - assert( evtConn_ ); + while (!timedOut_.getCopy() && !running()) + { + net::native::sleep(10); + net::update(); + } + if (timedOut_.getCopy()) + return; + // set up event connection + assert( conn_ ); + assert( !evtConn_ ); + evtConn_.reset( net::createEventConnection() ); + assert( evtConn_ ); - evtConn_->setPolling( true ); + evtConn_->setPolling( true ); - evtConn_->registerEvent( c2sEvtJoinReq::ID, net::NetEvent::DIR_ANY, - c2sEvtJoinReq::create, c2sEvtJoinReq::destroy ); - evtConn_->registerEvent( s2cEvtJoinReqReply::ID, net::NetEvent::DIR_ANY, - s2cEvtJoinReqReply::create, s2cEvtJoinReqReply::destroy ); - evtConn_->registerEvent( s2cEvtClassTable::ID, net::NetEvent::DIR_ANY, - s2cEvtClassTable::create, s2cEvtClassTable::destroy ); + evtConn_->registerEvent( c2sEvtJoinReq::ID, net::NetEvent::DIR_ANY, + c2sEvtJoinReq::create, c2sEvtJoinReq::destroy ); + evtConn_->registerEvent( s2cEvtJoinReqReply::ID, net::NetEvent::DIR_ANY, + s2cEvtJoinReqReply::create, s2cEvtJoinReqReply::destroy ); + evtConn_->registerEvent( s2cEvtClassTable::ID, net::NetEvent::DIR_ANY, + s2cEvtClassTable::create, s2cEvtClassTable::destroy ); - evtConn_->setProcessEventCallback( boost::bind(&client::init_onProcessEvent,this,_1,_2,_3) ); - evtConn_->setPacketConnection( conn_, net::NetEvent::DIR_ANY ); + evtConn_->setProcessEventCallback( boost::bind(&client::init_onProcessEvent,this,_1,_2,_3) ); + evtConn_->setPacketConnection( conn_.get(), net::NetEvent::DIR_ANY ); - evtConn_->start(); + evtConn_->start(); - // initiate "join" sequence - this->stage_ = CS_JOINING; + // initiate "join" sequence + this->stage_ = CS_JOINING; - c2sEvtJoinReq evt; - evtConn_->sendEvent( evt, net::SendOptions().channel(CHANNELID_CONTROL) ); - -#if NET_STRESS_TEST_LEVEL >= 1 - // send a second time to test our server logic :) - for (size_t i=0; i<3; ++i) + c2sEvtJoinReq evt; evtConn_->sendEvent( evt, net::SendOptions().channel(CHANNELID_CONTROL) ); -#endif - evt.setId( 23 ); // invalid id! - evtConn_->sendEvent( evt, net::SendOptions().channel(CHANNELID_CONTROL) ); + #if NET_STRESS_TEST_LEVEL >= 1 + // send a second time to test our server logic :) + for (size_t i=0; i<3; ++i) + evtConn_->sendEvent( evt, net::SendOptions().channel(CHANNELID_CONTROL) ); + #endif - while (stage_ == CS_JOINING) + evt.setId( 23 ); // invalid id! + evtConn_->sendEvent( evt, net::SendOptions().channel(CHANNELID_CONTROL) ); + + while (stage_ == CS_JOINING) + { + evtConn_->poll(); + net::update(); + net::native::sleep(0); + } + } + void client::step() { + if (!running()) + return; + evtConn_->poll(); - net::update(); - net::native::sleep(1); - } -} -void client::step() -{ - if (!running()) - return; - evtConn_->poll(); - - if (stage_ == CS_RUNNING) - { + if (stage_ == CS_RUNNING) + { + } } -} -void client::stop() -{ + void client::stop() { - boost::mutex::scoped_lock lck(runningMtx_); - running_ = false; + { + boost::mutex::scoped_lock lck(runningMtx_); + running_ = false; + } + // clean up + if (evtConn_) + { + evtConn_->stop(); + evtConn_.reset(); + } + if (conn_) + { + conn_->disconnect(); + conn_.reset(); + } } - // clean up - if (evtConn_) + void client::onClientStarted() { - evtConn_->stop(); - delete evtConn_; - evtConn_ = 0; + COUTLN("client started."); + + { + boost::mutex::scoped_lock lck(runningMtx_); + running_ = true; + } } - if (conn_) + void client::onTimeOut() { - conn_->disconnect(); - delete conn_; - conn_ = 0; - } -} -void client::onClientStarted() -{ - COUTLN("client started."); + COUTLN("client could not connect to server. destroying connection object."); - { - boost::mutex::scoped_lock lck(runningMtx_); - running_ = true; + // Do NOT destroy the connection object here! It may still be inside the callback loop! + // We can call disconnect(), though. + timedOut_ = true; + //conn->disconnect(); } -} -void client::onTimeOut() -{ - COUTLN("client could not connect to server. destroying connection object."); - - // Do NOT destroy the connection object here! It may still be inside the callback loop! - // We can call disconnect(), though. - timedOut_ = true; - //conn->disconnect(); -} -void client::running_onProcessEvent(const net::PeerId, const net::NetEvent& evt, const net::ChannelId) -{ - COUTLN("client (running) received event (" << (int)evt.id() << ")."); - if (evt.id() == s2cEvtClassTable::ID) + void client::running_onProcessEvent(const net::PeerId, const net::NetEvent& evt, const net::ChannelId) { - COUTLN("starting sim " << evt.id()); + COUTLN("client (running) received event (" << (int)evt.id() << ")."); + if (evt.id() == s2cEvtClassTable::ID) + { + COUTLN("starting sim " << evt.id()); + } } -} -void client::init_onProcessEvent(const net::PeerId, const net::NetEvent& evt, const net::ChannelId) -{ - COUTLN("client (init) received event (" << (int)evt.id() << ")."); - if (stage_ == CS_JOINING) + void client::init_onProcessEvent(const net::PeerId, const net::NetEvent& evt, const net::ChannelId) { - if (evt.id() == s2cEvtJoinReqReply::ID) + COUTLN("client (init) received event (" << (int)evt.id() << ")."); + if (stage_ == CS_JOINING) { - const s2cEvtJoinReqReply& reply = static_cast<const s2cEvtJoinReqReply&>( evt ); - if (reply.accepted) + if (evt.id() == s2cEvtJoinReqReply::ID) { - COUTLN("CONNECTED TO SERVER."); - stage_ = CS_RUNNING; + const s2cEvtJoinReqReply& reply = static_cast<const s2cEvtJoinReqReply&>( evt ); + if (reply.accepted) + { + COUTLN("CONNECTED TO SERVER."); + stage_ = CS_RUNNING; + } + else + { + COUTLN("SERVER DENIED ACCESS!"); + stage_ = CS_DEAD; + evtConn_->setProcessEventCallback( boost::bind(&client::init_onProcessEvent,this,_1,_2,_3) ); + } } - else - { - COUTLN("SERVER DENIED ACCESS!"); - stage_ = CS_DEAD; - evtConn_->setProcessEventCallback( boost::bind(&client::init_onProcessEvent,this,_1,_2,_3) ); - } } } -} - } // namespace ro Modified: trunk/yake/src/yake/samples/net/roclient/demo.cpp =================================================================== --- trunk/yake/src/yake/samples/net/roclient/demo.cpp 2006-11-01 15:18:35 UTC (rev 1491) +++ trunk/yake/src/yake/samples/net/roclient/demo.cpp 2006-11-01 15:19:39 UTC (rev 1492) @@ -30,4 +30,3 @@ net::shutdown(); return 0; } - Modified: trunk/yake/src/yake/samples/net/roserver/ROServer.cpp =================================================================== --- trunk/yake/src/yake/samples/net/roserver/ROServer.cpp 2006-11-01 15:18:35 UTC (rev 1491) +++ trunk/yake/src/yake/samples/net/roserver/ROServer.cpp 2006-11-01 15:19:39 UTC (rev 1492) @@ -13,7 +13,6 @@ enum stage_t { CS_WAIT_FOR_REQ = 1, // waiting for "req join" - CS_JOINED, // server acknowledged "join" request & sent ... CS_RUNNING, CS_DEAD }; @@ -75,6 +74,7 @@ while (!running()) { + //conn_->update(); ->@todo net::update(); net::native::sleep(10); } @@ -87,6 +87,7 @@ boost::mutex::scoped_lock lck(runningMtx_); running_ = false; } + clients_.clear(); if (conn_) { conn_->stop(); @@ -119,6 +120,7 @@ boost::mutex::scoped_lock lck(runningMtx_); running_ = true; } + COUTLN("server: starting event connection..."); YAKE_ASSERT( !evtConn_ ); evtConn_ = net::createEventConnection(); YAKE_ASSERT( evtConn_ ); @@ -134,6 +136,7 @@ evtConn_->setPacketConnection( conn_, net::NetEvent::DIR_ANY ); evtConn_->start(); + COUTLN("server: event connection started."); } void server::onReceivePacket(const net::PeerId peerId, const void* data, const size_t len, const net::ChannelId channel) { @@ -146,14 +149,17 @@ try { COUTLN("server received event (" << (int)evt.id() << ")."); + // Let client object handle the event. If no client object exists + // for this peer, create it. + // get client object - client* c = 0; + ClientPtr c; ClientPtrMap::iterator it = clients_.find( peerId ); if (it == clients_.end()) { - c = new client(); + c.reset( new Client() ); c->id = peerId; - c->stage = client::CS_WAIT_FOR_REQ; + c->stage = Client::CS_WAIT_FOR_REQ; c->evtConn = evtConn_; clients_.insert(std::make_pair(peerId,c)); } @@ -165,6 +171,7 @@ } catch (...) { + COUTLN("server: CAUGHT UNHANDLED EXCEPTION!\n"); } } //----------------------------------------------------------------------------- @@ -189,8 +196,13 @@ for (size_t i=0; i<3; ++i) evtConn->sendEvent( this->id, joinReply, net::SendOptions().channel(CHANNELID_CONTROL) ); #endif - this->stage = CS_JOINED; + // + s2cEvtClassTable clsTbl; + clsTbl.globalClassIds_["test"] = 42; + clsTbl.globalClassIds_["player"] = 56; + evtConn->sendEvent( this->id, clsTbl, net::SendOptions().channel(CHANNELID_CONTROL) ); + // use different event callback for the CS_RUNNING stage: COUTLN(" => RUNNING"); processEventFn_ = boost::bind(&client::running_onProcessEvent,this,_1,_2); @@ -203,7 +215,6 @@ YAKE_ASSERT( stage == CS_RUNNING ); if (stage != CS_RUNNING) return; - //@todo put events in a queue - it is then processed in the main simulation thread! //// send class table & start sim //s2cEvtClassTable evtClassTbl; //evtConn->sendEvent( this->id, evtClassTbl, net::SendOptions().channel(CHANNELID_SIMCTRL) ); Modified: trunk/yake/yake/net/netEvent.h =================================================================== --- trunk/yake/yake/net/netEvent.h 2006-11-01 15:18:35 UTC (rev 1491) +++ trunk/yake/yake/net/netEvent.h 2006-11-01 15:19:39 UTC (rev 1492) @@ -155,7 +155,6 @@ typedef boost::function<NetEvent*(const NetEvent::id_type)> CreateEventFn; typedef boost::function<void(NetEvent*)> DestroyEventFn; - /** NB fnCreate and fnDestroy have to be threadsafe when manual polling is used! */ virtual void registerEvent(const NetEvent::id_type, const NetEvent::Direction, const CreateEventFn& fnCreate, const DestroyEventFn& fnDestroy) = 0; virtual void sendEvent(const NetEvent&, const SendOptions& opt = SendOptions()) = 0; Modified: trunk/yake/yake/net/netPacket.h =================================================================== --- trunk/yake/yake/net/netPacket.h 2006-11-01 15:18:35 UTC (rev 1491) +++ trunk/yake/yake/net/netPacket.h 2006-11-01 15:19:39 UTC (rev 1492) @@ -7,7 +7,7 @@ /** Interface for packet sending objects. */ - class NET_API IPacketSender + class NET_API IPacketSender : public boost::noncopyable { public: virtual ~IPacketSender() {} @@ -35,13 +35,22 @@ /** Interface for packet receiving objects. */ - class NET_API IPacketReceiver + class NET_API IPacketReceiver : public boost::noncopyable { public: virtual ~IPacketReceiver() {} typedef boost::function<void(const PeerId, const void*, const size_t, const ChannelId)> OnPacketReceivedFn; - virtual CallbackConnection addPacketReceivedCallback( const OnPacketReceivedFn&) = 0; + // catch-all + virtual CallbackConnection addPacketReceivedCallback( const OnPacketReceivedFn& ) = 0; + /* + // catch for a channel + virtual CallbackConnection addPacketReceivedCallback( const OnPacketReceivedFn&, const ChannelId ) = 0; + // catch for a peer + virtual CallbackConnection addPacketReceivedCallback( const PeerId, const OnPacketReceivedFn& ) = 0; + // catch for peer and channel + virtual CallbackConnection addPacketReceivedCallback( const PeerId, const OnPacketReceivedFn&, const ChannelId ) = 0; + */ }; /** Interface for packet sending and receiving objects (connections). Modified: trunk/yake/yake/samples/net/common/commonEvents.h =================================================================== --- trunk/yake/yake/samples/net/common/commonEvents.h 2006-11-01 15:18:35 UTC (rev 1491) +++ trunk/yake/yake/samples/net/common/commonEvents.h 2006-11-01 15:19:39 UTC (rev 1492) @@ -61,11 +61,58 @@ CLASS() : net::NetEvent(ID) \ {} +inline net::ibitstream& operator >> (net::ibitstream& in, net::uint8& rhs) +{ + in.read( rhs ); + return in; +} +inline net::obitstream& operator << (net::obitstream& out, const net::uint8 rhs) +{ + out.write( rhs ); + return out; +} +inline net::ibitstream& operator >> (net::ibitstream& in, net::uint16& rhs) +{ + in.read( rhs ); + return in; +} +inline net::obitstream& operator << (net::obitstream& out, const net::uint16 rhs) +{ + out.write( rhs ); + return out; +} +inline net::ibitstream& operator >> (net::ibitstream& in, net::uint32& rhs) +{ + in.read( rhs ); + return in; +} +inline net::obitstream& operator << (net::obitstream& out, const net::uint32 rhs) +{ + out.write( rhs ); + return out; +} +inline net::ibitstream& operator >> (net::ibitstream& in, int& rhs) +{ + in.read( rhs ); + return in; +} +inline net::obitstream& operator << (net::obitstream& out, const int rhs) +{ + out.write( rhs ); + return out; +} + struct version_t { net::uint8 ver[3]; - version_t(const net::uint8 maj = 0, const net::uint8 min = 0, const net::uint8 b = 0) + version_t() { + ver[0] = 0; + ver[1] = 0; + ver[2] = 0; + } + version_t(const net::uint8 maj, const net::uint8 min, const net::uint8 b) + { ver[0] = maj; ver[1] = min; ver[2] = b; @@ -101,26 +148,77 @@ } version_t version; }; +inline net::obitstream& operator << (net::obitstream& out, const std::string& rhs) +{ + out.write(int(rhs.length())); + if (!rhs.empty()) + out.write( rhs.c_str(), (rhs.size()*sizeof(std::string::value_type)*8) ); + return out; +} +inline net::ibitstream& operator >> (net::ibitstream& in, std::string& rhs) +{ + int len = 0; + in.read(len); + assert(len < 10000); // enforce upper limit + rhs.clear(); + rhs.reserve(len); + while (len>0) + { + char c = 0; + in.read(c); + rhs += c; + len--; + } + return in; +} +#define YAKE_FOR_EACH(ITER_TYPE,ITER_NAME,CTR) \ + for (ITER_TYPE ITER_NAME = CTR.begin(); ITER_NAME != CTR.end(); ++ITER_NAME) + +template<typename _Ty, typename _Pr, typename _Alloc> +inline net::obitstream& operator << (net::obitstream& out, const std::map<_Ty,_Pr,_Alloc>& ctr) +{ + out.write(net::uint32(ctr.size())); + typedef std::map<_Ty,_Pr,_Alloc> map_type; + typedef typename map_type::const_iterator iter_type; + YAKE_FOR_EACH(iter_type,it,ctr) + out << it->first << it->second; + return out; +} +template<typename _Ty, typename _Pr, typename _Alloc> +inline net::ibitstream& operator >> (net::ibitstream& in, std::map<_Ty,_Pr,_Alloc>& ctr) +{ + ctr.clear(); + net::uint32 count = 0; + in.read(count); + //@todo safe-guard count + typedef std::map<_Ty,_Pr,_Alloc> map_type; + typedef typename map_type::const_iterator iter_type; + for (size_t i=0; i<count; ++i) + { + std::pair<_Ty,_Pr> data; + in >> data.first; + in >> data.second; + ctr.insert( data ); + } + return in; +} struct s2cEvtJoinReqReply : public net::NetEvent { DECLARE_EVENT( s2cEvtJoinReqReply, 2 ); virtual bool pack(net::obitstream& out) const { out.write( accepted ); - std::string msg("blah burp!"); - out.write( msg.c_str(), msg.size()+1 ); + std::string msg("i wanna join!"); + out << msg; return true; } virtual bool unpack(net::ibitstream& in) { in.read( accepted ); + std::string msg; - net::uint8 c = 0; - while (in.read(c,8)) - { - msg += c; - } - COUTLN("MSG " << msg.c_str()); + in >> msg; + COUTLN("MSG: " << msg.c_str()); return true; } bool accepted; @@ -130,12 +228,18 @@ DECLARE_EVENT( s2cEvtClassTable, 10 ); virtual bool pack(net::obitstream& out) const { - //out << globalClassIds_; + std::map<int,int> c; + c[1] = 2; + c[3] = 46; + out << c; + out << globalClassIds_; return true; } virtual bool unpack(net::ibitstream& in) { - //in >> globalClassIds_; + std::map<int,int> c; + in >> c; + in >> globalClassIds_; return true; } //uint8 numClassIdBits_; Modified: trunk/yake/yake/samples/net/roclient/ROClient.h =================================================================== --- trunk/yake/yake/samples/net/roclient/ROClient.h 2006-11-01 15:18:35 UTC (rev 1491) +++ trunk/yake/yake/samples/net/roclient/ROClient.h 2006-11-01 15:19:39 UTC (rev 1492) @@ -14,12 +14,12 @@ bool running() const; void step(); private: - net::IClientPacketConnection* conn_; - safe_var<bool> timedOut_; - net::INetEventConnection* evtConn_; + yake::SharedPtr<net::IClientPacketConnection> conn_; + safe_var<bool> timedOut_; + yake::SharedPtr<net::INetEventConnection> evtConn_; bool running_; - mutable boost::mutex runningMtx_; + mutable boost::mutex runningMtx_; enum stage_t { CS_DEAD = 1, @@ -37,42 +37,3 @@ } // namespace ro #endif -#ifndef RO_CLIENT_H -#define RO_CLIENT_H - -namespace ro { - - struct client - { - public: - client(); - ~client(); - bool start( const net::Address& ); - void waitForStart(); - void stop(); - bool running() const; - void step(); - private: - net::IClientPacketConnection* conn_; - safe_var<bool> timedOut_; - net::INetEventConnection* evtConn_; - - bool running_; - mutable boost::mutex runningMtx_; - - enum stage_t { - CS_DEAD = 1, - CS_JOINING, - CS_RUNNING - }; - stage_t stage_; - private: - void onClientStarted(); - void onTimeOut(); - void running_onProcessEvent(const net::PeerId, const net::NetEvent& , const net::ChannelId); - void init_onProcessEvent(const net::PeerId, const net::NetEvent& , const net::ChannelId); - }; - -} // namespace ro - -#endif Modified: trunk/yake/yake/samples/net/roserver/ROServer.h =================================================================== --- trunk/yake/yake/samples/net/roserver/ROServer.h 2006-11-01 15:18:35 UTC (rev 1491) +++ trunk/yake/yake/samples/net/roserver/ROServer.h 2006-11-01 15:19:39 UTC (rev 1492) @@ -17,11 +17,14 @@ void queueEvent(const net::PeerId, net::NetEvent*, const net::ChannelId); void queueEventBroadcast(net::NetEvent*, const net::ChannelId); private: + server(const server&); + server& operator=(const server&); + private: void onServerStarted(); void onReceivePacket(const net::PeerId, const void*, const size_t, const net::ChannelId); void onProcessEvent(const net::PeerId, const net::NetEvent&, const net::ChannelId); private: - bool running_; + volatile bool running_; mutable boost::mutex runningMtx_; bool running() const; @@ -30,9 +33,10 @@ net::IServerPacketConnection* conn_; net::INetEventConnection* evtConn_; - typedef server_impl::client client; + typedef server_impl::client Client; + typedef yake::SharedPtr<Client> ClientPtr; - typedef std::map<net::PeerId,client*> ClientPtrMap; + typedef std::map<net::PeerId,ClientPtr> ClientPtrMap; ClientPtrMap clients_; //@todo put into specialized object "NetEventQueue" This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2006-11-18 21:03:58
|
Revision: 1495 http://svn.sourceforge.net/yake/?rev=1495&view=rev Author: psyclonist Date: 2006-11-18 13:03:56 -0800 (Sat, 18 Nov 2006) Log Message: ----------- new demo for demonstrating remoting objects, improved net component (interface, functionality, docs) Modified Paths: -------------- trunk/yake/common/bin/debug/yake.graphics.ogre_resources.cfg trunk/yake/scripts/msvc8/net.vcproj trunk/yake/src/yake/ent/object_mgr.cpp trunk/yake/src/yake/net/detail/netCommon.cpp trunk/yake/src/yake/net/detail/netEnetClientPacketConnection.cpp trunk/yake/src/yake/net/detail/netEnetServerPacketConnection.cpp trunk/yake/src/yake/net/detail/netEventConnection.cpp trunk/yake/src/yake/net/detail/netInternal.cpp trunk/yake/src/yake/net/net.cpp trunk/yake/src/yake/samples/net/packet/demo.cpp trunk/yake/src/yake/samples/net/roclient/ROClient.cpp trunk/yake/src/yake/samples/net/roserver/ROServer.cpp trunk/yake/yake/net/detail/netEnetClientPacketConnection.h trunk/yake/yake/net/detail/netEnetServerPacketConnection.h trunk/yake/yake/net/detail/netEventConnection.h trunk/yake/yake/net/detail/netInternal.h trunk/yake/yake/net/net.h trunk/yake/yake/net/netBitstream.h trunk/yake/yake/net/netBitstream.inl trunk/yake/yake/net/netBitstreamAdapters.h trunk/yake/yake/net/netCommon.h trunk/yake/yake/net/netEvent.h trunk/yake/yake/net/netPacket.h trunk/yake/yake/net/netPrerequisites.h trunk/yake/yake/net/netTypes.h trunk/yake/yake/samples/net/common/commonEvents.h trunk/yake/yake/samples/net/common/config.h trunk/yake/yake/samples/net/roclient/ROClient.h trunk/yake/yake/samples/net/roserver/ROServer.h Added Paths: ----------- trunk/yake/common/bin/debug/rodemo.cfg trunk/yake/common/bin/debug/rodemo_client.cfg trunk/yake/common/bin/debug/rodemo_server.cfg trunk/yake/common/bin/debug/rodemo_serverclient.cfg trunk/yake/common/bin/release/rodemo.cfg trunk/yake/common/bin/release/rodemo_client.cfg trunk/yake/common/bin/release/rodemo_server.cfg trunk/yake/common/bin/release/rodemo_serverclient.cfg trunk/yake/scripts/msvc8/samples/net/sampleRoInprocess.vcproj trunk/yake/src/yake/net/detail/netDataChunk.cpp trunk/yake/src/yake/net/detail/netPacket.cpp trunk/yake/src/yake/samples/net/roinprocess/ trunk/yake/src/yake/samples/net/roinprocess/pch.cpp trunk/yake/yake/samples/net/common/roCommon.h Added: trunk/yake/common/bin/debug/rodemo.cfg =================================================================== --- trunk/yake/common/bin/debug/rodemo.cfg (rev 0) +++ trunk/yake/common/bin/debug/rodemo.cfg 2006-11-18 21:03:56 UTC (rev 1495) @@ -0,0 +1,11 @@ +rodemo +{ + server + { + start 1 + } + client + { + count 0 + } +} Added: trunk/yake/common/bin/debug/rodemo_client.cfg =================================================================== --- trunk/yake/common/bin/debug/rodemo_client.cfg (rev 0) +++ trunk/yake/common/bin/debug/rodemo_client.cfg 2006-11-18 21:03:56 UTC (rev 1495) @@ -0,0 +1,11 @@ +rodemo +{ + server + { + start 0 + } + client + { + count 1 + } +} Added: trunk/yake/common/bin/debug/rodemo_server.cfg =================================================================== --- trunk/yake/common/bin/debug/rodemo_server.cfg (rev 0) +++ trunk/yake/common/bin/debug/rodemo_server.cfg 2006-11-18 21:03:56 UTC (rev 1495) @@ -0,0 +1,11 @@ +rodemo +{ + server + { + start 1 + } + client + { + count 0 + } +} Added: trunk/yake/common/bin/debug/rodemo_serverclient.cfg =================================================================== --- trunk/yake/common/bin/debug/rodemo_serverclient.cfg (rev 0) +++ trunk/yake/common/bin/debug/rodemo_serverclient.cfg 2006-11-18 21:03:56 UTC (rev 1495) @@ -0,0 +1,11 @@ +rodemo +{ + server + { + start 1 + } + client + { + count 1 + } +} Modified: trunk/yake/common/bin/debug/yake.graphics.ogre_resources.cfg =================================================================== --- trunk/yake/common/bin/debug/yake.graphics.ogre_resources.cfg 2006-11-01 15:25:54 UTC (rev 1494) +++ trunk/yake/common/bin/debug/yake.graphics.ogre_resources.cfg 2006-11-18 21:03:56 UTC (rev 1495) @@ -22,3 +22,4 @@ FileSystem=../../media/gui.cegui.fonts/ FileSystem=../../media/gui.cegui.layouts/ Zip=../../media/skybox.zip +FileSystem=C:/Programme/Autodesk/3dsMax8/OSM/ Added: trunk/yake/common/bin/release/rodemo.cfg =================================================================== --- trunk/yake/common/bin/release/rodemo.cfg (rev 0) +++ trunk/yake/common/bin/release/rodemo.cfg 2006-11-18 21:03:56 UTC (rev 1495) @@ -0,0 +1,11 @@ +rodemo +{ + server + { + start 1 + } + client + { + count 0 + } +} Added: trunk/yake/common/bin/release/rodemo_client.cfg =================================================================== --- trunk/yake/common/bin/release/rodemo_client.cfg (rev 0) +++ trunk/yake/common/bin/release/rodemo_client.cfg 2006-11-18 21:03:56 UTC (rev 1495) @@ -0,0 +1,11 @@ +rodemo +{ + server + { + start 0 + } + client + { + count 1 + } +} Added: trunk/yake/common/bin/release/rodemo_server.cfg =================================================================== --- trunk/yake/common/bin/release/rodemo_server.cfg (rev 0) +++ trunk/yake/common/bin/release/rodemo_server.cfg 2006-11-18 21:03:56 UTC (rev 1495) @@ -0,0 +1,11 @@ +rodemo +{ + server + { + start 1 + } + client + { + count 0 + } +} Added: trunk/yake/common/bin/release/rodemo_serverclient.cfg =================================================================== --- trunk/yake/common/bin/release/rodemo_serverclient.cfg (rev 0) +++ trunk/yake/common/bin/release/rodemo_serverclient.cfg 2006-11-18 21:03:56 UTC (rev 1495) @@ -0,0 +1,11 @@ +rodemo +{ + server + { + start 1 + } + client + { + count 1 + } +} Modified: trunk/yake/scripts/msvc8/net.vcproj =================================================================== --- trunk/yake/scripts/msvc8/net.vcproj 2006-11-01 15:25:54 UTC (rev 1494) +++ trunk/yake/scripts/msvc8/net.vcproj 2006-11-18 21:03:56 UTC (rev 1495) @@ -222,6 +222,10 @@ > </File> <File + RelativePath="..\..\src\yake\net\detail\netDataChunk.cpp" + > + </File> + <File RelativePath="..\..\src\yake\net\detail\netEnetClientPacketConnection.cpp" > </File> @@ -237,6 +241,10 @@ RelativePath="..\..\src\yake\net\detail\netInternal.cpp" > </File> + <File + RelativePath="..\..\src\yake\net\detail\netPacket.cpp" + > + </File> </Filter> <Filter Name="enet" Added: trunk/yake/scripts/msvc8/samples/net/sampleRoInprocess.vcproj =================================================================== --- trunk/yake/scripts/msvc8/samples/net/sampleRoInprocess.vcproj (rev 0) +++ trunk/yake/scripts/msvc8/samples/net/sampleRoInprocess.vcproj 2006-11-18 21:03:56 UTC (rev 1495) @@ -0,0 +1,244 @@ +<?xml version="1.0" encoding="Windows-1252"?> +<VisualStudioProject + ProjectType="Visual C++" + Version="8,00" + Name="sampleRoInprocess" + ProjectGUID="{8CB64BC3-7D11-484F-8D10-17DC105701F6}" + Keyword="Win32Proj" + > + <Platforms> + <Platform + Name="Win32" + /> + </Platforms> + <ToolFiles> + </ToolFiles> + <Configurations> + <Configuration + Name="Debug|Win32" + OutputDirectory="../../../../common/bin/debug" + IntermediateDirectory="../../../../common/obj/debug/$(ProjectName)" + ConfigurationType="1" + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + > + <Tool + Name="VCPreBuildEventTool" + /> + <Tool + Name="VCCustomBuildTool" + /> + <Tool + Name="VCXMLDataGeneratorTool" + /> + <Tool + Name="VCWebServiceProxyGeneratorTool" + /> + <Tool + Name="VCMIDLTool" + /> + <Tool + Name="VCCLCompilerTool" + Optimization="0" + AdditionalIncludeDirectories="../../../../;../../../../dependencies/boost/;../../../../dependencies/ttl/" + PreprocessorDefinitions="_STLP_DEBUG;WIN32;_DEBUG;_CONSOLE" + MinimalRebuild="true" + BasicRuntimeChecks="3" + RuntimeLibrary="3" + RuntimeTypeInfo="true" + UsePrecompiledHeader="2" + PrecompiledHeaderThrough="yake/samples/net/roinprocess/pch.h" + WarningLevel="3" + Detect64BitPortabilityProblems="true" + DebugInformationFormat="4" + /> + <Tool + Name="VCManagedResourceCompilerTool" + /> + <Tool + Name="VCResourceCompilerTool" + /> + <Tool + Name="VCPreLinkEventTool" + /> + <Tool + Name="VCLinkerTool" + AdditionalDependencies="base.lib graphics.lib physics.lib audio.lib data.lib input.lib yapp.lib scripting.lib ent.lib" + OutputFile="$(OutDir)/$(ProjectName).exe" + LinkIncremental="2" + AdditionalLibraryDirectories="../../../../common/lib;../../../../common/lib/debug;../../../../dependencies/lib" + GenerateDebugInformation="true" + ProgramDatabaseFile="$(OutDir)/$(ProjectName).pdb" + SubSystem="1" + TargetMachine="1" + /> + <Tool + Name="VCALinkTool" + /> + <Tool + Name="VCManifestTool" + /> + <Tool + Name="VCXDCMakeTool" + /> + <Tool + Name="VCBscMakeTool" + /> + <Tool + Name="VCFxCopTool" + /> + <Tool + Name="VCAppVerifierTool" + /> + <Tool + Name="VCWebDeploymentTool" + /> + <Tool + Name="VCPostBuildEventTool" + /> + </Configuration> + <Configuration + Name="Release|Win32" + OutputDirectory="../../../../common/bin/release" + IntermediateDirectory="../../../../common/obj/release/$(ProjectName)" + ConfigurationType="1" + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + > + <Tool + Name="VCPreBuildEventTool" + /> + <Tool + Name="VCCustomBuildTool" + /> + <Tool + Name="VCXMLDataGeneratorTool" + /> + <Tool + Name="VCWebServiceProxyGeneratorTool" + /> + <Tool + Name="VCMIDLTool" + /> + <Tool + Name="VCCLCompilerTool" + AdditionalIncludeDirectories="../../../../;../../../../dependencies/boost/;../../../../dependencies/ttl/" + PreprocessorDefinitions="WIN32;NDEBUG;_CONSOLE" + RuntimeLibrary="2" + RuntimeTypeInfo="true" + UsePrecompiledHeader="2" + PrecompiledHeaderThrough="yake/samples/net/roinprocess/pch.h" + WarningLevel="3" + Detect64BitPortabilityProblems="true" + DebugInformationFormat="3" + /> + <Tool + Name="VCManagedResourceCompilerTool" + /> + <Tool + Name="VCResourceCompilerTool" + /> + <Tool + Name="VCPreLinkEventTool" + /> + <Tool + Name="VCLinkerTool" + AdditionalDependencies="base.lib graphics.lib physics.lib audio.lib data.lib input.lib yapp.lib scripting.lib ent.lib" + OutputFile="$(OutDir)/$(ProjectName).exe" + LinkIncremental="1" + AdditionalLibraryDirectories="../../../../common/lib;../../../../common/lib/release;../../../../dependencies/lib" + GenerateDebugInformation="false" + SubSystem="1" + OptimizeReferences="2" + EnableCOMDATFolding="2" + TargetMachine="1" + /> + <Tool + Name="VCALinkTool" + /> + <Tool + Name="VCManifestTool" + /> + <Tool + Name="VCXDCMakeTool" + /> + <Tool + Name="VCBscMakeTool" + /> + <Tool + Name="VCFxCopTool" + /> + <Tool + Name="VCAppVerifierTool" + /> + <Tool + Name="VCWebDeploymentTool" + /> + <Tool + Name="VCPostBuildEventTool" + /> + </Configuration> + </Configurations> + <References> + </References> + <Files> + <Filter + Name="inc" + > + <File + RelativePath="..\..\..\..\yake\samples\net\roinprocess\pch.h" + > + </File> + <File + RelativePath="..\..\..\..\yake\samples\net\roclient\ROClient.h" + > + </File> + <File + RelativePath="..\..\..\..\yake\samples\net\common\roCommon.h" + > + </File> + <File + RelativePath="..\..\..\..\yake\samples\net\roserver\ROServer.h" + > + </File> + </Filter> + <Filter + Name="src" + > + <File + RelativePath="..\..\..\..\src\yake\samples\net\roinprocess\demo.cpp" + > + </File> + <File + RelativePath="..\..\..\..\src\yake\samples\net\roinprocess\pch.cpp" + > + <FileConfiguration + Name="Debug|Win32" + > + <Tool + Name="VCCLCompilerTool" + UsePrecompiledHeader="1" + /> + </FileConfiguration> + <FileConfiguration + Name="Release|Win32" + > + <Tool + Name="VCCLCompilerTool" + UsePrecompiledHeader="1" + /> + </FileConfiguration> + </File> + <File + RelativePath="..\..\..\..\src\yake\samples\net\roclient\ROClient.cpp" + > + </File> + <File + RelativePath="..\..\..\..\src\yake\samples\net\roserver\ROServer.cpp" + > + </File> + </Filter> + </Files> + <Globals> + </Globals> +</VisualStudioProject> Modified: trunk/yake/src/yake/ent/object_mgr.cpp =================================================================== --- trunk/yake/src/yake/ent/object_mgr.cpp 2006-11-01 15:25:54 UTC (rev 1494) +++ trunk/yake/src/yake/ent/object_mgr.cpp 2006-11-18 21:03:56 UTC (rev 1495) @@ -37,11 +37,9 @@ YAKE_ASSERT( ret.first == object::RC_OK )(ret.first)(ret.second); return makeObject( ret.second ); } - Object* ObjectManager::makeObject(const ClassId clsId) + void ObjectManager::setupObjectPostCreate(Object* obj) { - Object* obj = objMgr_.createObject(clsId); - YAKE_ASSERT( obj )(clsId); - objs_.push_back( obj ); + YAKE_ASSERT( obj ); obj->registerMessageListeners(msgRouter_); @@ -50,9 +48,27 @@ obj->init(); listeners_onObjectInitialized(obj); + } + Object* ObjectManager::makeObject(const ObjectId objId) + { + Object* obj = objMgr_.createObject(objId.classId(),objId); + YAKE_ASSERT( obj )(objId); + objs_.push_back( obj ); + this->setupObjectPostCreate(obj); + return obj; } + Object* ObjectManager::makeObject(const ClassId clsId) + { + Object* obj = objMgr_.createObject(clsId); + YAKE_ASSERT( obj )(clsId); + objs_.push_back( obj ); + + this->setupObjectPostCreate(obj); + + return obj; + } void ObjectManager::destroyObject(Object* obj) { YAKE_ASSERT( obj ); @@ -114,7 +130,24 @@ msg->setTarget( MessageTraits::kBroadcastTarget ); msgRouter_.post( msg ); } + void ObjectManager::setClassIdGenerationRange(const ClassId min, const ClassId max) + { + objMgr_.setClassIdGenerationRange( min, max ); + } + bool ObjectManager::registerClassAlias(const String& aliasName, const ClassId targetClsId) + { + object::ResultCode ret = objMgr_.registerClassAlias( aliasName, targetClsId ); + return (ret == object::RC_OK); + } + bool ObjectManager::registerClassAlias(const ClassId aliasClsId, const ClassId targetClsId) + { + object::ResultCode ret = objMgr_.registerClassAlias( aliasClsId, targetClsId ); + return (ret == object::RC_OK); + } + Object* ObjectManager::getObject(const ObjectId objId) const + { + return objMgr_.getObject( objId ); + } } } - Modified: trunk/yake/src/yake/net/detail/netCommon.cpp =================================================================== --- trunk/yake/src/yake/net/detail/netCommon.cpp 2006-11-01 15:25:54 UTC (rev 1494) +++ trunk/yake/src/yake/net/detail/netCommon.cpp 2006-11-18 21:03:56 UTC (rev 1495) @@ -25,6 +25,7 @@ // Windows Header Files: #include <windows.h> +namespace yake { namespace net { //------------------------------------------------------------------------- @@ -89,7 +90,7 @@ {} Address::~Address() {} - Address& Address::operator =(const net::Address& rhs) + Address& Address::operator =(const Address& rhs) { if (this == &rhs) return *this; @@ -167,11 +168,31 @@ reliability_ = rel; return *this; } + SendOptions& SendOptions::reliable() + { + reliability_ = R_RELIABLE; + return *this; + } + SendOptions& SendOptions::unreliable() + { + reliability_ = R_UNRELIABLE; + return *this; + } SendOptions& SendOptions::ordering(const Ordering ord) { ordering_ = ord; return *this; } + SendOptions& SendOptions::ordered() + { + ordering_ = O_ORDERED; + return *this; + } + SendOptions& SendOptions::unordered() + { + ordering_ = O_UNORDERED; + return *this; + } SendOptions& SendOptions::channel(const ChannelId id) { channelId_ = id; @@ -237,3 +258,4 @@ } } // namespace net +} // namespace yake Added: trunk/yake/src/yake/net/detail/netDataChunk.cpp =================================================================== --- trunk/yake/src/yake/net/detail/netDataChunk.cpp (rev 0) +++ trunk/yake/src/yake/net/detail/netDataChunk.cpp 2006-11-18 21:03:56 UTC (rev 1495) @@ -0,0 +1,85 @@ +#include <yake/net/pch.h> +#include <yake/net/netCommon.h> + +namespace yake { +namespace net { + + DataChunk::DataChunk(const void* data, const size_t len) : buf_(0), bufSize_(0), dataSize_(0) + { + if (data && len) + this->reset( data, len ); + } + DataChunk::~DataChunk() + { + this->clear(); + } + const void* DataChunk::data() const + { + return buf_; + } + void* DataChunk::data() + { + return buf_; + } + size_t DataChunk::size() const + { + return dataSize_; + } + size_t DataChunk::capacity() const + { + return bufSize_; + } + void DataChunk::reset(const void* dataPtr, const size_t dataSize) + { + this->resize(dataSize,kThrowAwayData); + if (dataSize_) + { + assert( dataSize_ == dataSize ); + assert( bufSize_ >= dataSize ); + memcpy( buf_, dataPtr, dataSize_ ); + } + } + void DataChunk::resize(size_t newDataSize, ResizeMode keepData) + { + if (newDataSize <= bufSize_) + { + dataSize_ = newDataSize; + return; + } + if (keepData == kThrowAwayData || !buf_) + { + if (buf_) + delete [] buf_; + buf_ = new byte[newDataSize]; + bufSize_ = newDataSize; + dataSize_ = newDataSize; + return; + } + else if (keepData == kKeepData) + { + byte_ptr newBuf = new byte[newDataSize]; + assert( buf_ ); + memcpy( newBuf, buf_, std::min(newDataSize,dataSize_) ); + delete [] buf_; + buf_ = newBuf; + bufSize_ = newDataSize; + dataSize_ = newDataSize; + return; + } + else + throw std::runtime_error("DataChunk::resize(): unhandled ResizeMode"); + } + void DataChunk::shrink() + { + if (buf_ && (bufSize_ > dataSize_)) + { + byte_ptr newBuf = new byte[dataSize_]; + memcpy( newBuf, buf_, dataSize_ ); + delete [] buf_; + buf_ = newBuf; + bufSize_ = dataSize_; + } + } + +} // namespace net +} // namespace yake Modified: trunk/yake/src/yake/net/detail/netEnetClientPacketConnection.cpp =================================================================== --- trunk/yake/src/yake/net/detail/netEnetClientPacketConnection.cpp 2006-11-01 15:25:54 UTC (rev 1494) +++ trunk/yake/src/yake/net/detail/netEnetClientPacketConnection.cpp 2006-11-18 21:03:56 UTC (rev 1495) @@ -4,6 +4,7 @@ #include <yake/net/detail/netInternal.h> #include <yake/net/detail/netEnetClientPacketConnection.h> +namespace yake { namespace net { IClientPacketConnection* createClientPacketConnection() { @@ -76,7 +77,7 @@ } m_address.port = addr.port(); - m_peer = enet_host_connect( m_host, &m_address, 2 /*channel count*/ ); + m_peer = enet_host_connect( m_host, &m_address, 4 /*channel count*/ ); if (!m_peer) { NET_ERROR("Could not connect to server!"); @@ -115,16 +116,18 @@ if (m_serverPeer) enet_peer_disconnect( m_serverPeer, 0 /*@todo data*/ ); - /*@todo handle graceful disconnects... + // handle graceful disconnects... Timer timer; timer.start(); - while (timer.getTime() < 1) + // now wait until either disconnected or we time out. + while (m_serverPeer && timer.getTime() < 1) { net::update(); - net::native::sleep(10); + this->update(); + net::native::sleep(0); } - */ + // hard disconnect enet_peer_reset( m_peer ); enet_host_destroy( m_host ); m_host = 0; @@ -170,7 +173,7 @@ m_serverIp = ipToString( host ); const uint8 tmp = 0x7F; - this->send(&tmp,1,SendOptions().reliability(R_RELIABLE)); + this->send(PacketPtr(new Packet(&tmp,1)),SendOptions().reliability(R_RELIABLE)); } break; case ENET_EVENT_TYPE_RECEIVE: @@ -186,7 +189,8 @@ } else if (event.packet) { - this->fireCallback_PacketReceived(0,event.packet->data,event.packet->dataLength,ChannelId(event.channelID)); + this->fireCallback_PacketReceived( + 0,PacketPtr(new Packet(event.packet->data,event.packet->dataLength)),ChannelId(event.channelID)); } { //boost::mutex::scoped_lock enetLock(getEnetMtx()); @@ -203,18 +207,38 @@ break; }; } + // Send queued packets: + this->sendOutgoingPacketQ(); } - void EnetClientPacketConnection::send( const void* dataPtr, const size_t dataSize, const net::SendOptions& opt ) + void EnetClientPacketConnection::sendOutgoingPacketQ() { - this->sendBroadcast( dataPtr, dataSize, opt.getReliability(), opt.getOrdering(), opt.getChannel() ); + for (OutgoingPacketQ::const_iterator it = m_outgoingPacketQ.begin(); it != m_outgoingPacketQ.end(); ++it) + { + const SendOptions& opt = it->opt_; + const PacketPtr& pckt = it->pckt_; + YAKE_ASSERT( pckt.get() ); + this->sendBroadcast( pckt->payload().data(), pckt->payload().size(), + opt.getReliability(), opt.getOrdering(), opt.getChannel() ); + } + m_outgoingPacketQ.clear(); } - void EnetClientPacketConnection::send(const PeerId, const void* dataPtr, const size_t dataSize, const SendOptions& opt ) + void EnetClientPacketConnection::send( const PacketPtr& pckt, const SendOptions& opt ) { - this->sendBroadcast( dataPtr, dataSize, opt.getReliability(), opt.getOrdering(), opt.getChannel() ); + YAKE_ASSERT( pckt ); + if (!pckt) + return; + OutgoingPacket pcktEntry; + pcktEntry.opt_ = opt; + pcktEntry.pckt_ = pckt; + m_outgoingPacketQ.push_back( pcktEntry ); } + void EnetClientPacketConnection::send(const PeerId, const PacketPtr& pckt, const SendOptions& opt ) + { + this->send( pckt, opt ); + } void EnetClientPacketConnection::sendTo(const PeerId clientId, const void* dataPtr, const size_t dataSize, const Reliability rel, const Ordering ord, const ChannelId channel) { - sendBroadcast(dataPtr,dataSize,rel,ord,channel); + this->sendBroadcast(dataPtr,dataSize,rel,ord,channel); } void EnetClientPacketConnection::sendBroadcast(const void* dataPtr, const size_t dataSize, const Reliability rel, const Ordering, const ChannelId channel) { @@ -237,3 +261,4 @@ } // namespace impl } // namespace net +} // namespace yake Modified: trunk/yake/src/yake/net/detail/netEnetServerPacketConnection.cpp =================================================================== --- trunk/yake/src/yake/net/detail/netEnetServerPacketConnection.cpp 2006-11-01 15:25:54 UTC (rev 1494) +++ trunk/yake/src/yake/net/detail/netEnetServerPacketConnection.cpp 2006-11-18 21:03:56 UTC (rev 1495) @@ -4,6 +4,7 @@ #include <yake/net/detail/netInternal.h> #include <yake/net/detail/netEnetServerPacketConnection.h> +namespace yake { namespace net { IServerPacketConnection* createServerPacketConnection() { @@ -122,21 +123,35 @@ NET_ASSERT( m_host ); if (m_host) { - if (m_host->peerCount > 0) + if (!m_clients.empty()) { + for (PeerToClientMap::iterator itClient = m_clients.begin(); + itClient != m_clients.end(); ++itClient) + { + if (itClient->second->state != CS_DEAD && + itClient->second->state != CS_CONNECTED) + { + itClient->second->state = CS_DISCONNECTING; + } + } + // try to gracefully disconnect clients for (size_t i=0; i<m_host->peerCount; ++i) + { enet_peer_disconnect( &m_host->peers[i], 0 /*@todo data*/ ); + } - /** @todo handle graceful disconnects... + // handle graceful disconnects... Timer timer; timer.start(); - while (timer.getTime() < 2) // wait 2 seconds for acknowledgement + // wait max 2 seconds for disconnect acknowledgement from client. + // or stop waiting when client count reaches 0. + while (!m_clients.empty() && timer.getTime() < 2) { net::update(); - net::native::sleep(10); + this->update(); + net::native::sleep(0); } - */ // forcefully disconnect remaining clients if (m_host->peerCount > 0) @@ -173,6 +188,7 @@ return; // set client state itFindClient->second->state = CS_DISCONNECTING; + itFindClient->second->timeLeft_ = 2.; // 2 seconds for graceful disconnect // disconnect enet client { //boost::mutex::scoped_lock enetLock(getEnetMtx()); @@ -300,13 +316,14 @@ } const uint8 tmp = 0x7F; - this->send(peerId,&tmp,1,SendOptions().reliability(R_RELIABLE)); + this->send(peerId,PacketPtr(new Packet(&tmp,1)),SendOptions().reliability(R_RELIABLE)); } break; case ENET_EVENT_TYPE_RECEIVE: NET_ASSERT( event.packet ); NET_ASSERT( event.peer ); - NET_ASSERT( event.peer->data ); + //NET_ASSERT( event.peer->data ); + if (event.peer->data) { const ClientState cs = getClientState( event.peer ); if (cs == CS_CONNECTING) @@ -335,7 +352,9 @@ peerId = (reinterpret_cast<Client*>(event.peer->data))->id; } - fireCallback_PacketReceived(peerId,event.packet->data,event.packet->dataLength,event.channelID); + // This copies the packet data, at the moment. @todo optimize copy away + fireCallback_PacketReceived(peerId, + PacketPtr(new Packet(event.packet->data,event.packet->dataLength)),event.channelID); } { // destroy enet packet @@ -374,21 +393,49 @@ break; }; } + // Send any queued packets. + this->sendOutgoingPacketQ(); } - void EnetServerPacketConnection::send( const void* dataPtr, const size_t dataSize, const net::SendOptions& opt ) + void EnetServerPacketConnection::sendOutgoingPacketQ() { - const PeerId peerId = opt.getPeerId(); - if (peerId != PEERID_BROADCAST) - this->sendTo( peerId, dataPtr, dataSize, opt.getReliability(), opt.getOrdering(), opt.getChannel() ); - else - this->sendBroadcast( dataPtr, dataSize, opt.getReliability(), opt.getOrdering(), opt.getChannel() ); + for (OutgoingPacketQ::const_iterator it = m_outgoingPacketQ.begin(); it != m_outgoingPacketQ.end(); ++it) + //YAKE_FOR_EACH(OutgoingPacketQ::const_iterator,it,m_outgoingPacketQ) + { + const SendOptions& opt = it->opt_; + const PacketPtr& pckt = it->pckt_; + YAKE_ASSERT( pckt.get() ); + if (it->target_ == PEERID_BROADCAST) + this->sendBroadcast( pckt->payload().data(), pckt->payload().size(), + opt.getReliability(), opt.getOrdering(), opt.getChannel() ); + else + this->sendTo( it->target_, pckt->payload().data(), pckt->payload().size(), + opt.getReliability(), opt.getOrdering(), opt.getChannel() ); + } + m_outgoingPacketQ.clear(); } - void EnetServerPacketConnection::send(const PeerId peerId, const void* dataPtr, const size_t dataSize, const SendOptions& opt ) + void EnetServerPacketConnection::send( const PacketPtr& pckt, const SendOptions& opt ) { - SendOptions options = opt; - options.peerId( peerId ); - send( dataPtr, dataSize, options ); + YAKE_ASSERT( pckt ); + if (!pckt) + return; + OutgoingPacket pcktEntry; + pcktEntry.opt_ = opt; + pcktEntry.pckt_ = pckt; + pcktEntry.target_ = opt.getPeerId(); + m_outgoingPacketQ.push_back( pcktEntry ); } + void EnetServerPacketConnection::send(const PeerId peerId, const PacketPtr& pckt, const SendOptions& opt ) + { + YAKE_ASSERT( pckt ); + if (!pckt) + return; + OutgoingPacket pcktEntry; + pcktEntry.opt_ = opt; + pcktEntry.opt_.peerId( peerId ); + pcktEntry.pckt_ = pckt; + pcktEntry.target_ = opt.getPeerId(); + m_outgoingPacketQ.push_back( pcktEntry ); + } void EnetServerPacketConnection::sendTo(const PeerId clientId, const void* dataPtr, const size_t dataSize, const Reliability rel, const Ordering, const ChannelId channel) { NET_ASSERT( dataSize > 0 ); @@ -406,8 +453,9 @@ // send //boost::mutex::scoped_lock clientsLock(m_clientsMtx); IdToClientMap::const_iterator it = m_id2client.find( clientId ); - NET_ASSERT( it != m_id2client.end() ); - enet_peer_send( it->second->peer, channel, packet ); + NET_ASSERT( it != m_id2client.end() )( clientId ).warning("unknown client id"); + if (it != m_id2client.end()) + enet_peer_send( it->second->peer, channel, packet ); } } void EnetServerPacketConnection::sendBroadcast(const void* dataPtr, const size_t dataSize, const Reliability rel, const Ordering, const ChannelId channel) @@ -430,3 +478,4 @@ } // namespace impl } // namespace net +} // namespace yake Modified: trunk/yake/src/yake/net/detail/netEventConnection.cpp =================================================================== --- trunk/yake/src/yake/net/detail/netEventConnection.cpp 2006-11-01 15:25:54 UTC (rev 1494) +++ trunk/yake/src/yake/net/detail/netEventConnection.cpp 2006-11-18 21:03:56 UTC (rev 1495) @@ -5,6 +5,7 @@ #include <yake/net/detail/netInternal.h> #include <yake/net/detail/netEventConnection.h> +namespace yake { namespace net { const NetEvent::id_type NetEvent::EVTID_NONE = 0xff; NetEvent::NetEvent(const id_type id) : id_(id) @@ -97,7 +98,7 @@ } if (conn_) { - conn_->addPacketReceivedCallback( boost::bind(&EventConnection::onReceivePacket,this,_1,_2,_3,_4) ); + conn_->addPacketReceivedCallback( boost::bind(&EventConnection::onReceivePacket,this,_1,_2,_3) ); started_ = true; } return started_; @@ -152,10 +153,18 @@ out.flush(); NET_LOG("EvtConn: sending " << int(data.size()) << " bytes to '" << int(opt.getPeerId()) << "'."); - conn_->send( &data.front(), data.size(), opt ); + conn_->send( PacketPtr(new Packet(&data.front(), data.size() )), opt ); //@todo optimize copy out! } - void EventConnection::onReceivePacket(const PeerId peerId, const void* dataPtr, const size_t dataLen, const ChannelId channel) + void EventConnection::onReceivePacket(const PeerId peerId, const PacketPtr& pckt, const ChannelId channel) { + NET_ASSERT( pckt ); + if (!pckt) + { + NET_LOG("EvtConn: handling invalid packet object from '" << int(peerId) << "'."); + return; + } + const void* dataPtr = pckt->payload().data(); + const size_t dataLen = pckt->payload().size(); NET_LOG("EvtConn: received " << int(dataLen) << " bytes from '" << int(peerId) << "'."); NET_ASSERT( dataPtr && dataLen > 0 ); NET_ASSERT( dataLen >= sizeof(event_id) ); @@ -275,7 +284,9 @@ if (!processEventFn_.empty()) processEventFn_( it->peerId_, *it->evt_, it->channel_ ); it->fnDestroy_( it->evt_ ); + ++stats_.numEventsProcessed; } } } // namespace impl } // namespace net +} // namespace yake Modified: trunk/yake/src/yake/net/detail/netInternal.cpp =================================================================== --- trunk/yake/src/yake/net/detail/netInternal.cpp 2006-11-01 15:25:54 UTC (rev 1494) +++ trunk/yake/src/yake/net/detail/netInternal.cpp 2006-11-18 21:03:56 UTC (rev 1495) @@ -2,9 +2,13 @@ #include <yake/net/net.h> #include <yake/net/detail/netInternal.h> +#include <boost/thread/mutex.hpp> +namespace yake { namespace net { void update() { + static boost::mutex s_mtx; + boost::mutex::scoped_lock lck(s_mtx); impl::UpdateThread::instance().__update__(); } namespace impl { @@ -121,3 +125,4 @@ } // namespace impl } // namespace net +} // namespace yake Added: trunk/yake/src/yake/net/detail/netPacket.cpp =================================================================== --- trunk/yake/src/yake/net/detail/netPacket.cpp (rev 0) +++ trunk/yake/src/yake/net/detail/netPacket.cpp 2006-11-18 21:03:56 UTC (rev 1495) @@ -0,0 +1,16 @@ +#include <yake/net/pch.h> +#include <yake/net/netCommon.h> + +namespace yake { +namespace net { + + Packet::Packet(const void* dataPtr, const size_t dataSize) : payload_(dataPtr,dataSize) + { + } + const DataChunk& Packet::payload() const + { + return payload_; + } + +} // namespace net +} // namespace yake Modified: trunk/yake/src/yake/net/net.cpp =================================================================== --- trunk/yake/src/yake/net/net.cpp 2006-11-01 15:25:54 UTC (rev 1494) +++ trunk/yake/src/yake/net/net.cpp 2006-11-18 21:03:56 UTC (rev 1495) @@ -31,6 +31,7 @@ #endif // PLATFORM_WIN32 +namespace yake { namespace net { bool initialize() @@ -50,4 +51,4 @@ } } // namespace net - +} // namespace yake Modified: trunk/yake/src/yake/samples/net/packet/demo.cpp =================================================================== --- trunk/yake/src/yake/samples/net/packet/demo.cpp 2006-11-01 15:25:54 UTC (rev 1494) +++ trunk/yake/src/yake/samples/net/packet/demo.cpp 2006-11-18 21:03:56 UTC (rev 1495) @@ -92,13 +92,13 @@ YAKE_ASSERT( conn_ ); YAKE_ASSERT( started_ ); std::string hello("hello!"); - conn_->send( hello.c_str(), hello.size(), net::SendOptions().reliability(net::R_RELIABLE) ); + conn_->send( hello.c_str(), hello.size(), net::SendOptions().reliable() ); COUTLN("server:broadcastHello() " << conn_->getNumConnectedClients() << " client(s)"); } void client_onPacketReceived(const net::PeerId peerId, const void* data, const size_t len, const net::ChannelId channel) { - COUTLN(" client " << peerId << " packet(size=" << len << ") on channel " << channel << "\n"); + COUTLN(" client " << peerId << " packet(size=" << len << ") on channel " << int(channel) << "\n"); } int main(int argc, char* argv[]) Modified: trunk/yake/src/yake/samples/net/roclient/ROClient.cpp =================================================================== --- trunk/yake/src/yake/samples/net/roclient/ROClient.cpp 2006-11-01 15:25:54 UTC (rev 1494) +++ trunk/yake/src/yake/samples/net/roclient/ROClient.cpp 2006-11-18 21:03:56 UTC (rev 1495) @@ -1,29 +1,32 @@ -#include <yake/samples/net/roclient/pch.h> +#include <yake/samples/net/roinprocess/pch.h> #include <yake/base/yake.h> +#include <yake/object/yakeObjects.h> +#include <yake/ent/ent.h> #include <yake/net/net.h> #include <yake/samples/net/common/common.h> #include <yake/samples/net/common/commonEvents.h> #include <yake/samples/net/roclient/ROClient.h> +namespace yake { namespace ro { - client::client() : - timedOut_(false), running_(false), stage_(CS_JOINING) + client::client(const net::Address& serverAddr) : + timedOut_(false), stage_(CS_JOINING), objMgr_(0), serverAddr_(serverAddr), packetConnStarted_(false) { } client::~client() { stop(); } - bool client::running() const + void client::setObjectManager(ent::ObjectManager* objMgr) { - boost::mutex::scoped_lock lck(runningMtx_); - return running_; + objMgr_ = objMgr; } - bool client::start(const net::Address& serverAddr) + bool client::onStart() { try { // create connection & register callbacks + packetConnStarted_ = false; conn_.reset( net::createClientPacketConnection() ); assert( conn_ ); @@ -31,8 +34,15 @@ conn_->addStartedCallback( boost::bind(&client::onClientStarted,this) ); // attempt to connect to server - conn_->connect( serverAddr ); + /* + conn_->connect( serverAddr_, true, 2000 ); + */ + conn_->connect( serverAddr_ ); + this->waitForStart(); + if (timedOut_.getCopy()) + return false; + return true; } catch (const net::Exception& e) @@ -44,9 +54,9 @@ } void client::waitForStart() { - while (!timedOut_.getCopy() && !running()) + while (!timedOut_.getCopy() && !packetConnStarted_) { - net::native::sleep(10); + net::native::sleep(0); net::update(); } if (timedOut_.getCopy()) @@ -64,9 +74,11 @@ evtConn_->registerEvent( s2cEvtJoinReqReply::ID, net::NetEvent::DIR_ANY, s2cEvtJoinReqReply::create, s2cEvtJoinReqReply::destroy ); evtConn_->registerEvent( s2cEvtClassTable::ID, net::NetEvent::DIR_ANY, - s2cEvtClassTable::create, s2cEvtClassTable::destroy ); + s2cEvtClassTable::create, s2cEvtClassTable::destroy ); + evtConn_->registerEvent( s2cEvtCreateObject::ID, net::NetEvent::DIR_ANY, + s2cEvtCreateObject::create, s2cEvtCreateObject::destroy ); - evtConn_->setProcessEventCallback( boost::bind(&client::init_onProcessEvent,this,_1,_2,_3) ); + evtConn_->setProcessEventCallback( boost::bind(&client::onProcessEvent,this,_1,_2,_3) ); evtConn_->setPacketConnection( conn_.get(), net::NetEvent::DIR_ANY ); evtConn_->start(); @@ -86,30 +98,32 @@ evt.setId( 23 ); // invalid id! evtConn_->sendEvent( evt, net::SendOptions().channel(CHANNELID_CONTROL) ); + + currEvtProcessFn_ = boost::bind(&client::init_onProcessEvent,this,_1,_2,_3); + /* while (stage_ == CS_JOINING) { evtConn_->poll(); net::update(); net::native::sleep(0); } + */ } void client::step() { if (!running()) return; - evtConn_->poll(); + assert( evtConn_.get() ); + if (evtConn_.get()) + evtConn_->poll(); if (stage_ == CS_RUNNING) { } } - void client::stop() + void client::onStop() { - { - boost::mutex::scoped_lock lck(runningMtx_); - running_ = false; - } // clean up if (evtConn_) { @@ -120,16 +134,13 @@ { conn_->disconnect(); conn_.reset(); + packetConnStarted_ = false; } } void client::onClientStarted() { COUTLN("client started."); - - { - boost::mutex::scoped_lock lck(runningMtx_); - running_ = true; - } + packetConnStarted_ = true; } void client::onTimeOut() { @@ -145,8 +156,68 @@ COUTLN("client (running) received event (" << (int)evt.id() << ")."); if (evt.id() == s2cEvtClassTable::ID) { - COUTLN("starting sim " << evt.id()); + COUTLN("client: starting sim " << int(evt.id())); + const s2cEvtClassTable& reply = static_cast<const s2cEvtClassTable&>( evt ); + COUTLN(" " << int(reply.globalClassIds_.size()) << " class(es)"); + for (std::map<std::string,ent::ClassId>::const_iterator it = reply.globalClassIds_.begin(); + it != reply.globalClassIds_.end(); ++it) + { + const std::string& clsName = it->first; + const ent::ClassId globalClsId = it->second; + COUTLN(" ['" << clsName << "'] = " << int(globalClsId)); + if (!objMgr_) + { + COUTLN(" -> no object manager"); + } + else + { + ent::ObjectManager::ClassIdLookupResult ret = objMgr_->getClassId( clsName ); + if (ret.first) + { + const ent::ClassId localClsId = ret.second; + if (localClsId != it->second) + { + if (objMgr_->registerClassAlias( globalClsId, localClsId )) + { + COUTLN(" -> successfully registered alias"); + } + else + { + COUTLN(" -> failed to register alias"); + } + } + else + { + COUTLN(" -> no need to register an alias (global id = local id; and names match)"); + } + } + else + { + COUTLN(" -> class with this name not registered locally!"); + } + } + } } + else if (evt.id() == s2cEvtCreateObject::ID) + { + COUTLN("client: creating object"); + const s2cEvtCreateObject& reply = static_cast<const s2cEvtCreateObject&>( evt ); + COUTLN(" object class='" << int(reply.objId_.classId()) << "' serNo='" << int(reply.objId_.serialNo()) << "'"); + if (objMgr_) + { + ent::Object* o = objMgr_->makeObject( reply.objId_ ); + if (o) + { + COUTLN(" successfully created! (class='" << o->isA()->name() << "')"); + objMgr_->destroyObject( o ); + } + else + COUTLN(" failed to create!"); + } + } + //else if (evt.id() == s2cUpdateObject::ID) + { + } } void client::init_onProcessEvent(const net::PeerId, const net::NetEvent& evt, const net::ChannelId) { @@ -158,18 +229,26 @@ const s2cEvtJoinReqReply& reply = static_cast<const s2cEvtJoinReqReply&>( evt ); if (reply.accepted) { - COUTLN("CONNECTED TO SERVER."); + COUTLN("client: CONNECTED TO SERVER."); stage_ = CS_RUNNING; + currEvtProcessFn_ = boost::bind(&client::running_onProcessEvent,this,_1,_2,_3); } else { - COUTLN("SERVER DENIED ACCESS!"); + COUTLN("client: SERVER DENIED ACCESS!"); stage_ = CS_DEAD; - evtConn_->setProcessEventCallback( boost::bind(&client::init_onProcessEvent,this,_1,_2,_3) ); + currEvtProcessFn_ = boost::bind(&client::init_onProcessEvent,this,_1,_2,_3); } } } } + void client::onProcessEvent(const net::PeerId pId, const net::NetEvent& evt, const net::ChannelId cId) + { + COUTLN("client (dispatcher) received event (" << (int)evt.id() << ")."); + if (!currEvtProcessFn_.empty()) + currEvtProcessFn_(pId,evt,cId); + this->dispatchNetEvent(pId,evt,cId); + } } // namespace ro - +} // namespace yake Added: trunk/yake/src/yake/samples/net/roinprocess/pch.cpp =================================================================== --- trunk/yake/src/yake/samples/net/roinprocess/pch.cpp (rev 0) +++ trunk/yake/src/yake/samples/net/roinprocess/pch.cpp 2006-11-18 21:03:56 UTC (rev 1495) @@ -0,0 +1 @@ +#include <yake/samples/net/roinprocess/pch.h> Modified: trunk/yake/src/yake/samples/net/roserver/ROServer.cpp =================================================================== --- trunk/yake/src/yake/samples/net/roserver/ROServer.cpp 2006-11-01 15:25:54 UTC (rev 1494) +++ trunk/yake/src/yake/samples/net/roserver/ROServer.cpp 2006-11-18 21:03:56 UTC (rev 1495) @@ -1,15 +1,201 @@ -#include <yake/samples/net/roserver/pch.h> +#include <yake/samples/net/roinprocess/pch.h> +#include <yake/object/yakeObjects.h> +#include <yake/ent/ent.h> #include <yake/net/net.h> #include <yake/samples/net/common/common.h> #include <yake/samples/net/common/commonEvents.h> #include <yake/samples/net/roserver/ROServer.h> +namespace yake { namespace ro { //----------------------------------------------------------------------------- + IServiceHost::IServiceHost() : running_(false) + { + } + bool IServiceHost::running() const + { + boost::mutex::scoped_lock lck(runningMtx_); + return running_; + } + bool IServiceHost::start() + { + bool succ = this->onStart(); + if (!succ) + return false; + + { + boost::mutex::scoped_lock lck(runningMtx_); + running_ = true; + } + + // start services + YAKE_FOR_EACH(detail::ServiceManager::const_service_iterator,it,serviceMgr_) + { + (*it)->onStart(*this); + } + + return true; + } + void IServiceHost::stop() + { + { + boost::mutex::scoped_lock lck(runningMtx_); + running_ = false; + } + + // stop services + YAKE_FOR_EACH(detail::ServiceManager::const_service_iterator,it,serviceMgr_) + { + (*it)->onStop(*this); + } + + // stop the rest + this->onStop(); + } + void IServiceHost::addService(IServicePtr service, const std::string& tag) + { + serviceMgr_.addService( service, tag ); + if (this->running()) + service->onStart(*this); + } + void IServiceHost::removeAllServices() + { + serviceMgr_.removeAllServices(); + } + IServicePtr IServiceHost::removeService(const std::string & tag) + { + IServicePtr service = serviceMgr_.removeService( tag ); + if (service && this->running()) + service->onStop(*this); + return service; + } + IServicePtr IServiceHost::removeService(IServicePtr service) + { + serviceMgr_.removeService( service ); + if (service && this->running()) + service->onStop(*this); + return service; + } + IServicePtr IServiceHost::getService(const std::string& tag) const + { + return serviceMgr_.getService( tag ); + } + void IServiceHost::dispatchNetEvent(const net::PeerId pId, const net::NetEvent& evt, const net::ChannelId cId) + { + // find catch-all for this channel (ignore event id) + { + SigMap::const_iterator it = sigMap_.find( ChannelEventIdPair(cId,net::NetEvent::EVTID_NONE) ); + if (it != sigMap_.end()) + (*it->second)(pId,evt,cId); + } + + // find signal for this channel and event id: + SigMap::const_iterator it = sigMap_.find( ChannelEventIdPair(cId,evt.id()) ); + if (it == sigMap_.end()) + return; + (*it->second)(pId,evt,cId); + } + SignalConnection IServiceHost::subscribeToNetEvent( + const net::NetEvent::id_type eId, const net::ChannelId cId, const EvtProcessEventFn& fn) + { + const ChannelEventIdPair idPair(cId,eId); + + SigMap::iterator it = sigMap_.find( idPair ); + if (it == sigMap_.end()) + { + ProcessEventSigPtr sig( new ProcessEventSig() ); + sigMap_[ idPair ] = sig; + return sig->connect( fn ); + } + return it->second->connect(fn); + } + SignalConnection IServiceHost::subscribeToNetEventChannel( + const net::ChannelId cId, const EvtProcessEventFn& fn) + { + const ChannelEventIdPair idPair(cId,net::NetEvent::EVTID_NONE); + + SigMap::iterator it = sigMap_.find( idPair ); + if (it == sigMap_.end()) + { + ProcessEventSigPtr sig( new ProcessEventSig() ); + sigMap_[ idPair ] = sig; + return sig->connect( fn ); + } + return it->second->connect(fn); + } + + //----------------------------------------------------------------------------- + namespace detail { + + void ServiceManager::addService(IServicePtr service, const std::string& tag) + { + YAKE_ASSERT( service ); + if (!service) + return; + + services_.insert( service ); + if (!tag.empty()) + { + YAKE_ASSERT( tag2service_.find(tag) == tag2service_.end() ).debug("duplicate tag!"); + tag2service_[ tag ] = service; + } + } + IServicePtr ServiceManager::getService(const std::string& tag) const + { + TagMap::const_iterator itFind = tag2service_.find(tag); + return (itFind == tag2service_.end() ? IServicePtr() : itFind->second); + } + IServicePtr ServiceManager::removeService(const std::string& tag) + { + TagMap::iterator itFind = tag2service_.find(tag); + if (itFind == tag2service_.end()) + return IServicePtr(); + IServicePtr service = itFind->second; + tag2service_.erase( itFind ); + services_.erase( service ); + return service; + } + IServicePtr ServiceManager::removeService(const IServicePtr service) + { + YAKE_FOR_EACH(TagMap::iterator,itFind,tag2service_) + { + if (itFind->second == service) + { + tag2service_.erase( itFind ); + break; + } + } + services_.erase( service ); + return service; + } + void ServiceManager::removeAllServices() + { + tag2service_.clear(); + services_.clear(); + } + ServiceManager::const_service_iterator ServiceManager::begin() const + { + return services_.begin(); + } + ServiceManager::const_service_iterator ServiceManager::end() const + { + return services_.end(); + } + + } // namespace detail + //----------------------------------------------------------------------------- namespace server_impl { - class client + class client : public server::iclient { public: + + virtual void sendEvent(const net::NetEvent& evt, + const net::SendOptions& opt = net::SendOptions().channel(CHANNELID_CONTROL)) + { + YAKE_ASSERT( evtConn ); + evtConn->sendEvent( evt, opt ); + } + enum stage_t { CS_WAIT_FOR_REQ = 1, // waiting for "req join" @@ -22,15 +208,24 @@ AM_REGULAR, AM_SPECTATOR }; - net::PeerId id; - stage_t stage; - access_mode_t accessMode; - net::INetEventConnection* evtConn; + net::PeerId id; + stage_t stage; + access_mode_t accessMode; + SharedPtr<net::INetEventConnection> evtConn; + server& svr; - client() : id(net::NetEvent::EVTID_NONE), stage(CS_DEAD), accessMode(AM_REGULAR), evtConn(0) + client(server& svrObj) : + id(net::NetEvent::EVTID_NONE), + stage(CS_DEAD), + accessMode(AM_REGULAR), + svr(svrObj) { processEventFn_ = boost::bind(&client::init_onProcessEvent,this,_1,_2); } + virtual net::PeerId getPeerId() const + { + return this->id; + } void onProcessEvent(const net::NetEvent& evt, const net::ChannelId channel) { YAKE_ASSERT( !processEventFn_.empty() ); @@ -48,58 +243,86 @@ //----------------------------------------------------------------------------- - server::server() : conn_(0), running_(false), evtConn_(0) + server::server() : packetConnStarted_(false) { } server::~server() { stop(); } - bool server::start() + /* + void server::queueEvent(const net::PeerId id, net::NetEvent* evt, const net::ChannelId cId) { + SOF_ASSERT( evt ); + if (!evt) + return; + outEvtQ_.push_back( EventQEntry(id,evt,cId) ); + } + */ + SignalConnection server::subscribeToClientSimulationStarted(const ClientSimulationStartedSignal::slot_type& slot) + { + return sigClientSimulationStarted_.connect(slot); + } + SignalConnection server::subscribeToClientDisconnected(const ClientDisconnectedSignal::slot_type& slot) + { + return sigClientDisconnected_.connect(slot); + } + const s2cEvtClassTable& server::getClassTableMessage() const + { + return evtClassTbl_; + } + void server::onClientSimStarted(iclient&c) + { + sigClientSimulationStarted_(c); + } + void server::setClassTableMessage(const s2cEvtClassTable& msg) + { + msg.copyTo( evtClassTbl_ ); + } + bool server::onStart() + { if (conn_) return true; - const net::uint16 port = 40000; + const uint16 port = 40000; const size_t maxClients = 32; - conn_ = net::createServerPacketConnection(); + conn_.reset( net::createServerPacketConnection() ); YAKE_ASSERT( conn_ ); conn_->addStartedCallback( boost::bind(&server::onServerStarted,this) ); - conn_->addPacketReceivedCallback( boost::bind(&server::onReceivePacket,this,_1,_2,_3,_4) ); + conn_->addPacketReceivedCallback( boost::bind(&server::onReceivePacket,this,_1,_2,_3) ); + conn_->addClientDisconnectedCallback( boost::bind(&server::onClientDisconnected,this,_1) ); COUTLN("starting server at port " << port << " with max. " << maxClients << " clients..."); conn_->start( net::Address(port), maxClients ); - while (!running()) + // wait until net object is up + while (!packetConnStarted_) { //conn_->update(); ->@todo net::update(); - net::native::sleep(10); + net::native::sleep(0); } - return true; } - void server::stop() + void server::onStop() { + // shutdown net resources + if (evtConn_) { - boost::mutex::scoped_lock lck(runningMtx_); - running_ = false; + evtConn_->stop(); + evtConn_.reset(); } - clients_.clear(); if (conn_) { conn_->stop(); - delete conn_; - conn_ = 0; + conn_.reset(); + packetConnStarted_ = false; } - if (evtConn_) - { - evtConn_->stop(); - delete evtConn_; - evtConn_ = 0; - } + + // disconnect/destroy remaining clients + clients_.clear(); } void server::step() { @@ -108,21 +331,12 @@ if (evtConn_) evtConn_->poll(); } - bool server::running() const - { - boost::mutex::scoped_lock lck(runningMtx_); - return running_; - } void server::onServerStarted() { - COUTLN("server started."); - { - boost::mutex::scoped_lock lck(runningMtx_); - running_ = true; - } + COUTLN("server packet connection started."); COUTLN("server: starting event connection..."); YAKE_ASSERT( !evtConn_ ); - evtConn_ = net::createEventConnection(); + evtConn_.reset( net::createEventConnection() ); YAKE_ASSERT( evtConn_ ); evtConn_->setPolling(true); @@ -131,14 +345,17 @@ evtConn_->registerEvent( s2cEvtJoinReqReply::ID, net::NetEvent::DIR_ANY, s2cEvtJoinReqReply::create, s2cEvtJoinReqReply::destroy ); evtConn_->registerEvent( s2cEvtClassTable::ID, net::NetEvent::DIR_ANY, s2cEvtClassTable::create, s2cEvtClassTable::destroy ); evtConn_->registerEvent( c2sEvtSimOk::ID, net::NetEvent::DIR_ANY, c2sEvtSimOk::create, c2sEvtSimOk::destroy ); + evtConn_->registerEvent( s2cEvtCreateObject::ID, net::NetEvent::DIR_ANY, s2cEvtCreateObject::create, s2cEvtCreateObject::destroy ); evtConn_->setProcessEventCallback( boost::bind(&server::onProcessEvent,this,_1,_2,_3) ); - evtConn_->setPacketConnection( conn_, net::NetEvent::DIR_ANY ); + evtConn_->setPacketConnection( conn_.get(), net::NetEvent::DIR_ANY ); evtConn_->start(); COUTLN("server: event connection started."); + + packetConnStarted_ = true; } - void server::onReceivePacket(const net::PeerId peerId, const void* data, const size_t len, const net::ChannelId channel) + void server::onReceivePacket(const net::PeerId peerId, const net::PacketPtr&, const net::ChannelId channel) { COUTLN("server received packet."); //echoing... @@ -149,7 +366,7 @@ try { COUTLN("server received event (" << (int)evt.id() << ")."); - // Let client object handle the event. If no client object exists + // 1. Let client object handle the event. If no client object exists // for this peer, create it. // get client object @@ -157,7 +374,7 @@ ClientPtrMap::iterator it = clients_.find( peerId ); if (it == clients_.end()) { - c.reset( new Client() ); + c.reset( new Client(*this) ); c->id = peerId; c->stage = Client::CS_WAIT_FOR_REQ; c->evtConn = evtConn_; @@ -168,12 +385,25 @@ // handle event c->onProcessEvent( evt, channel ); + + // 2. Let services handle event + this->dispatchNetEvent( peerId, evt, channel ); } catch (...) { COUTLN("server: CAUGHT UNHANDLED EXCEPTION!\n"); } } + void server::onClientDisconnected(const net::PeerId pId) + { + COUTLN("ro::server: client '" << pId << "' disconnected."); + ClientPtrMap::iterator it = this->clients_.find( pId ); + YAKE_ASSERT(it != this->clients_.end())(pId).warning("unknown client disconnected. lookup failed."); + if (it == this->clients_.end()) + return; + this->sigClientDisconnected_( *it->second ); + this->clients_.erase( it ); + } //----------------------------------------------------------------------------- namespace server_impl { @@ -185,28 +415,29 @@ if (evt.id() == c2sEvtJoinReq::ID) { const c2sEvtJoinReq& evtJoinReq = static_cast<const c2sEvtJoinReq&>(evt); - COUTLN(" evt: Join Request"); + COUTLN("server: evt: Join Request"); // send reply: OK - COUTLN(" => accepted"); + COUTLN("server: accepted join request by client"); s2cEvtJoinReqReply joinReply; joinReply.accepted = true; - evtConn->sendEvent( this->id, joinReply, net::SendOptions().channel(CHANNELID_CONTROL) ); + evtConn->sendEvent( this->id, joinReply, net::SendOptions().channel(CHANNELID_CONTROL).ordered().reliable() ); #if NET_STRESS_TEST_LEVEL >= 1 for (size_t i=0; i<3; ++i) evtConn->sendEvent( this->id, joinReply, net::SendOptions().channel(CHANNELID_CONTROL) ); #endif - // - s2cEvtClassTable clsTbl; - clsTbl.globalClassIds_["test"] = 42; - clsTbl.globalClassIds_["player"] = 56; - evtConn->sendEvent( this->id, clsTbl, net::SendOptions().channel(CHANNELID_CONTROL) ); + // replicate class table + evtConn->sendEvent( this->id, this->svr.getClassTableMessage(), + net::SendOptions().channel(CHANNELID_CONTROL).ordered().reliable() ); // use different event callback for the CS_RUNNING stage: - COUTLN(" => RUNNING"); + COUTLN("server: => CLIENT: RUNNING"); processEventFn_ = boost::bind(&client::running_onProcessEvent,this,_1,_2); this->stage = CS_RUNNING; + + // replicate objects + this->svr.onClientSimStarted( *this ); } } void client::running_onProcessEvent(const net::NetEvent& evt, const net::ChannelId channel) @@ -215,9 +446,7 @@ YAKE_ASSERT( stage == CS_RUNNING ); if (stage != CS_RUNNING) return; - //// send class table & start sim - //s2cEvtClassTable evtClassTbl; - //evtConn->sendEvent( this->id, evtClassTbl, net::SendOptions().channel(CHANNELID_SIMCTRL) ); } } // namespace server_impl } // namespace ro +} // namespace yake Modified: trunk/yake/yake/net/detail/netEnetClientPacketConnection.h =================================================================== --- trunk/yake/yake/net/detail/netEnetClientPacketConnection.h 2006-11-01 15:25:54 UTC (rev 1494) +++ trunk/yake/yake/net/detail/netEnetClientPacketConnection.h 2006-11-18 21:03:56 UTC (rev 1495) @@ -1,11 +1,12 @@ -#ifndef NET_ENETCLIENTPACKETCONNECTION_H -#define NET_ENETCLIENTPACKETCONNECTION_H +#ifndef YAKE_NET_ENETCLIENTPACKETCONNECTION_H +#define YAKE_NET_ENETCLIENTPACKETCONNECTION_H +namespace yake { namespace net { namespace impl { //-------------------------------------------------------------------------- - class EnetClientPacketConnection : public ::net::IClientPacketConnection + class EnetClientPacketConnection : public IClientPacketConnection { public: EnetClientPacketConnection(); @@ -14,8 +15,8 @@ virtual void connect( const Address&, const bool doBlock, const uint32 timeOut ); virtual void disconnect(); - virtual void send(const void*, const size_t, const SendOptions& opt = SendOptions()); - virtual void send(const PeerId, const void*, const size_t, const SendOptions& opt = SendOptions()); + virtual void send(const PacketPtr& pckt, const SendOptions& opt = SendOptions()); + virtual void send(const PeerId, const PacketPtr& pckt, const SendOptions& opt = SendOptions()); virtual void addStartedCallback(const OnStartedFn&); virtual CallbackConnection addPacketReceivedCallback( const OnPacketReceivedFn&); @@ -40,17 +41,18 @@ for (OnStartedFnList::const_iterator it = startedFnList_.begin(); it != startedFnList_.end(); ++it) (*it)(); } - void fireCallback_PacketReceived(const PeerId peerId, const void* data, const size_t dataLen, const ChannelId channel) + void fireCallback_PacketReceived(const PeerId peerId, const PacketPtr& pckt, const ChannelId channel) { //boost::mutex::scoped_lock lck(packetReceivedFnListMtx_); for (OnPacketReceivedFnList::const_iterator it = packetReceivedFnList_.begin(); it != packetReceivedFnList_.end(); ++it) - (it->second)(peerId,data,dataLen,channel); + (it->second)(peerId,pckt,channel); } void fireCallback_TimeOut() { for (OnTimeOutFnList::const_iterator it = timeOutFnList_.begin(); it != timeOutFnList_.end(); ++it) (*it)(); } + void sendOutgoingPacketQ(); private: typedef std::deque<OnStartedFn> OnStartedFnList; typedef std::map<CallbackHandle,OnPacketReceivedFn> OnPacketReceivedFnList; @@ -71,9 +73,19 @@ bool m_waitingForConnect; std::string m_serverIp; Timer m_connTimer; + + struct OutgoingPacket + { + //PeerId target_; + PacketPtr pckt_; + SendOptions opt_; + }; + typedef std::deque<OutgoingPacket> OutgoingPacketQ; + OutgoingPacketQ m_outgoingPacketQ; }; } // namespace impl } // namespace net +} // namespace yake #endif Modified: trunk/yake/yake/net/detail/netEnetServerPacketConnection.h =================================================================== --- trunk/yake/yake/net/detail/netEnetServerPacketConnection.h 2006-11-01 15:25:54 UTC (rev 1494) +++ trunk/yake/yake/net/detail/netEnetServerPacketConnection.h 2006-11-18 21:03:56 UTC (rev 1495) @@ -1,11 +1,12 @@ -#ifndef NET_ENETSERVERPACKETCONNECTION_H -#define NET_ENETSERVERPACKETCONNECTION_H +#ifndef YAKE_NET_ENETSERVERPACKETCONNECTION_H +#define YAKE_NET_ENETSERVERPACKETCONNECTION_H +namespace yake { namespace net { namespace impl { //-------------------------------------------------------------------------- - class EnetServerPacketConnection : public ::net::IServerPacketConnection + class EnetServerPacketConnection : public IServerPacketConnection { public: EnetServerPacketConnection(); @@ -30,8 +31,8 @@ virtual void disconnect( const PeerId client ); - virtual void send(const void*, const size_t, const SendOptions& opt = SendOptions()); - virtual void send(const PeerId, const void*, const size_t, const SendOptions& opt = SendOptions()); + virtual void send(const PacketPtr&, const SendOptions& opt = SendOptions()); + virtual void send(const PeerId, const PacketPtr&, const SendOptions& opt = SendOptions()); virtual void addStartedCallback(const OnStartedFn&); virtual void addClientConnectedCallback(const OnClientConnectedFn&); @@ -55,6 +56,7 @@ size_t numMaxLiveClients_; }; private: + // send via enet void sendTo(const PeerId clientId, const void* dataPtr, const size_t dataSize, const Reliability rel, const Ordering, const ChannelId channel); void sendBroadcast(const void* dataPtr, const size_t dataSize, const Reliability rel, const Ordering, const Cha... [truncated message content] |
From: <psy...@us...> - 2006-11-18 22:21:58
|
Revision: 1499 http://svn.sourceforge.net/yake/?rev=1499&view=rev Author: psyclonist Date: 2006-11-18 14:21:57 -0800 (Sat, 18 Nov 2006) Log Message: ----------- added net::scoped_lock, added documentation Modified Paths: -------------- trunk/yake/src/yake/net/detail/netInternal.cpp trunk/yake/src/yake/net/net.cpp trunk/yake/yake/net/net.h trunk/yake/yake/net/netEvent.h trunk/yake/yake/net/netPacket.h Modified: trunk/yake/src/yake/net/detail/netInternal.cpp =================================================================== --- trunk/yake/src/yake/net/detail/netInternal.cpp 2006-11-18 21:07:23 UTC (rev 1498) +++ trunk/yake/src/yake/net/detail/netInternal.cpp 2006-11-18 22:21:57 UTC (rev 1499) @@ -5,10 +5,29 @@ #include <boost/thread/mutex.hpp> namespace yake { namespace net { + namespace detail { + struct scoped_lock_impl : public boost::noncopyable + { + scoped_lock_impl() + { + lck_.reset( new boost::mutex::scoped_lock(s_mtx_) ); + } + private: + SharedPtr<boost::mutex::scoped_lock> lck_; + static boost::mutex s_mtx_; + }; + boost::mutex scoped_lock_impl::s_mtx_; + } // namespace impl + scoped_lock::scoped_lock() + { + impl_.reset( new detail::scoped_lock_impl() ); + } + scoped_lock::~scoped_lock() + { + } void update() { - static boost::mutex s_mtx; - boost::mutex::scoped_lock lck(s_mtx); + scoped_lock lck; impl::UpdateThread::instance().__update__(); } namespace impl { @@ -79,7 +98,10 @@ return; } - for (UpdateFnMap::iterator it = fns_.begin(); it != fns_.end(); ++it) + // Create a copy of the registered functions in case that + // callbacks modify fns_ (which could/would invalidate the iterator). + UpdateFnMap tmpFns = fns_; + for (UpdateFnMap::iterator it = tmpFns.begin(); it != tmpFns.end(); ++it) { it->second(); } Modified: trunk/yake/src/yake/net/net.cpp =================================================================== --- trunk/yake/src/yake/net/net.cpp 2006-11-18 21:07:23 UTC (rev 1498) +++ trunk/yake/src/yake/net/net.cpp 2006-11-18 22:21:57 UTC (rev 1499) @@ -36,7 +36,8 @@ bool initialize() { - if (enet_initialize() < 0) + scoped_lock lck; + if (::enet_initialize() < 0) { fprintf(stderr, "An error occurred while initializing ENet.\n"); return false; @@ -46,8 +47,9 @@ } void shutdown() { + scoped_lock lck; impl::UpdateThread::destroy(); - enet_deinitialize(); + ::enet_deinitialize(); } } // namespace net Modified: trunk/yake/yake/net/net.h =================================================================== --- trunk/yake/yake/net/net.h 2006-11-18 21:07:23 UTC (rev 1498) +++ trunk/yake/yake/net/net.h 2006-11-18 22:21:57 UTC (rev 1499) @@ -9,10 +9,60 @@ namespace yake { namespace net { + /** One-time initialization function. + @remarks Call it once per application prior to accessing anything else + in yake::net. + @note If called, the corresponding shutdown() function has to be called, too. + @note This function is thread-safe. + @note NEVER call this function when a net::scoped_lock exists / is active! + @see update() + @see shutdown() + @see scoped_lock + */ NET_API bool initialize(); + + /** Service network processing. + Should be called regularly to service the networking objects (receiving, sending, callbacks). + @note This function is thread-safe. + @note NEVER call this function when a net::scoped_lock exists / is active! + @see initialize() + @see shutdown() + @see scoped_lock + */ NET_API void update(); + + /** Cleanup yake::net. + @note This function is thread-safe. + @note NEVER call this function when a net::scoped_lock exists / is active! + @see scoped_lock + @see initialize() + @see update() + */ NET_API void shutdown(); +#pragma warning(push) +#pragma warning(disable: 4275) // 'T' used as base for dll-interface class 'X' + namespace detail { + struct scoped_lock_impl; + } // namespace detail + /** This objects allows to acquire a lock to the global mutex used + by the networking library. + @note By default, only initialize(), update() and shutdown() are synchronized and thread-safe. + Other objects are not! + You may need to make other parts of your application thread-safe with regards to + accessing yake::net objects. In this case, you can use scoped_lock to acquire the lock. + @note NEVER call initialize(), update() or shutdown() if a scoped_lock is active/exists! + At a minimum, this will cause the calling thread to hang as initialize(), update() or + shutdown() wait indefinitely for the mutex to be unlocked! + */ + struct NET_API scoped_lock : public boost::noncopyable + { + scoped_lock(); + ~scoped_lock(); + private: + SharedPtr<detail::scoped_lock_impl> impl_; + }; +#pragma warning(pop) } // namespace net } // namespace yake Modified: trunk/yake/yake/net/netEvent.h =================================================================== --- trunk/yake/yake/net/netEvent.h 2006-11-18 21:07:23 UTC (rev 1498) +++ trunk/yake/yake/net/netEvent.h 2006-11-18 22:21:57 UTC (rev 1499) @@ -23,14 +23,15 @@ static const id_type EVTID_NONE; enum Direction { DIR_ANY, - DIR_CLIENT_TO_SERVER, - DIR_SERVER_TO_CLIENT + DIR_CLIENT_TO_SERVER, //@todo make DIR_OUTGOING + DIR_SERVER_TO_CLIENT //@todo make DIR_INCOMING }; - private: + private: // no default c'tor (so hide it) NetEvent(); + private: // non-copyable: NetEvent(const NetEvent&); NetEvent& operator=(const NetEvent&); - protected: + protected: // c'tor callable by derived types: NetEvent(const id_type); public: @@ -142,36 +143,73 @@ impl::EventConnection* owner_; }; + /** + @note Only registered events can be sent or received. Use registerEvent() before + receiving or sending events of the specified type. + @note Use createEventConnection(). + */ class NET_API INetEventConnection { public: virtual ~INetEventConnection(); + /** Sets the packet connection to be used for sending and receiving events. + @note The packet connection has to be set prior to calling start(). + */ virtual void setPacketConnection(IPacketConnection*,const NetEvent::Direction) = 0; + + /** @todo */ virtual void setMaxEventErrors(const size_t) = 0; + /** Start the event processing. */ virtual bool start() = 0; + /** Stop event processing. */ virtual void stop() = 0; typedef boost::function<NetEvent*(const NetEvent::id_type)> CreateEventFn; typedef boost::function<void(NetEvent*)> DestroyEventFn; + /** Registers an event for use with this event connection object. + @todo Only registered events can be sent or received. + */ virtual void registerEvent(const NetEvent::id_type, const NetEvent::Direction, const CreateEventFn& fnCreate, const DestroyEventFn& fnDestroy) = 0; + /** Broadcasts the event (if its id has been registered!). */ virtual void sendEvent(const NetEvent&, const SendOptions& opt = SendOptions()) = 0; + /** Sends the event (if its id has been registered!). */ virtual void sendEvent(const PeerId, const NetEvent&, const SendOptions& opt = SendOptions()) = 0; + /** @deprecated */ virtual void setAllowedIncomingEventIds(const std::vector<NetEvent::id_type>&) = 0; + /** Activates/Deactivates manual polling. + If activated, poll() should be called regularly to process pending events. + If not activated, every call to net::update() will automatically process events. + */ virtual void setPolling(const bool manualPolling = false) = 0; + + /** Processes pending events and forwards them to registered handlers. + @todo Should only be called when manual polling is used! + @see setPolling(bool) + */ virtual void poll() = 0; typedef boost::function<void(const PeerId, const NetEvent&, const ChannelId)> EvtProcessEventFn; typedef boost::function<void(void)> EvtDisconnectFn; - /** Pass 0 to disable. */ + /** Sets the event callback function. + @todo Pass 0 to disable. + */ virtual void setProcessEventCallback(const EvtProcessEventFn&) = 0; + /** Sets the disconnect callback function. + @todo pass 0 to disable. + */ virtual void setDisconnectCallback(const EvtDisconnectFn&) = 0; }; + /** Creates an event connection. + The caller takes over ownership and has to make sure + the connection object is destroyed prior to calling net::shutdown(). + @todo Move into INetEventConnection::create() ? + */ NET_API INetEventConnection* createEventConnection(); } // namespace net Modified: trunk/yake/yake/net/netPacket.h =================================================================== --- trunk/yake/yake/net/netPacket.h 2006-11-18 21:07:23 UTC (rev 1498) +++ trunk/yake/yake/net/netPacket.h 2006-11-18 22:21:57 UTC (rev 1499) @@ -17,7 +17,15 @@ { public: virtual ~IPacketSender() {} + /** Sends a packet to all registered peers. + @note On client connections there is only one registered peer: the server. + In this case both send() methods work identical. + */ virtual void send(const PacketPtr&, const SendOptions& opt = SendOptions()) = 0; + /** Sends a packet to the specified, registered peer. + @note On client connections there is only one registered peer: the server. + In this case both send() methods work identical. + */ virtual void send(const PeerId, const PacketPtr&, const SendOptions& opt = SendOptions()) = 0; }; @@ -66,6 +74,7 @@ public: typedef boost::function<void(void)> OnStartedFn; typedef boost::function<void(void)> OnTimeOutFn; + /** Set the callback that will be called as soon as the connection is up. */ virtual void addStartedCallback(const OnStartedFn&) = 0; }; @@ -77,8 +86,10 @@ { public: - /*** @Remarks May throw exception. */ - virtual void start( const Address&, const size_t ) = 0; + /** @Remarks May throw exception. + @param maxClients The maximum number of clients that may be connected at one time. + */ + virtual void start( const Address&, const size_t maxClients ) = 0; /** Disconnects all clients and shuts down the packet connection. @Remarks This function blocks for a short time in order to allow @@ -87,9 +98,17 @@ */ virtual void stop() = 0; + /** Set whitelist of allowed ips. + Clients with ips not in the list will not be allowed to connect. + If the list is empty (which is also the default when this function + does not get called) all client ips are allowed. + */ virtual void setAllowedClientIps(const std::vector<std::string>&) = 0; //virtual void setAllowedClientIps(const std::vector<uint32>&) = 0; + /** Returns the number of clients that are connected. + @todo Clients that are currently connecting or disconnecting are not included! + */ virtual size_t getNumConnectedClients() const = 0; /** Disconnects the client. @@ -101,10 +120,12 @@ typedef boost::function<void(const PeerId, const Address&)> OnClientConnectedFn; typedef boost::function<void(const PeerId)> OnClientDisconnectedFn; - /** Not thread-safe! Call only before calling start()! */ + /** Set callback to be called when a client successfully connected. */ virtual void addClientConnectedCallback(const OnClientConnectedFn&) = 0; + /** Set callback to be called when a client disconnected. */ virtual void addClientDisconnectedCallback(const OnClientDisconnectedFn&) = 0; }; + /** A packet connection interface specific to packet clients. Packet clients manage a single connection to a packet server. @see IClientPacketConnection @@ -112,14 +133,26 @@ class NET_API IClientPacketConnection : public IPacketConnection { public: + /** Connect to the given server. + If doBlock is false, the call returns immediately, otherwise it waits + until the connection attempt succeeded or the timeout of 'timeOut' milliseconds + is reached. + The 'started' and 'timeout' callbacks should be used to handle error cases. + @note Use disconnect() to close the connection. + */ virtual void connect( const Address&, const bool doBlock = false, const uint32 timeOut = 2000 ) = 0; + /** Disconnect from the server. + @note As the connection tries to gracefully disconnect from the server, this function + may block for short time (up to 1 second). + */ virtual void disconnect() = 0; + /** Set the callback to be called when a connection attempt times out. */ virtual void addTimeOutCallback(const OnTimeOutFn&) = 0; }; - /** @Remarks User code is responsible for destroying the connection objects!*/ + /** @Remarks User code is responsible for destroying connection objects!*/ NET_API IServerPacketConnection* createServerPacketConnection(); - /** @Remarks User code is responsible for destroying the connection objects!*/ + /** @Remarks User code is responsible for destroying connection objects!*/ NET_API IClientPacketConnection* createClientPacketConnection(); } // namespace net This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2006-11-28 22:41:30
|
Revision: 1501 http://svn.sourceforge.net/yake/?rev=1501&view=rev Author: psyclonist Date: 2006-11-28 14:41:28 -0800 (Tue, 28 Nov 2006) Log Message: ----------- added documentation, added net::Timer::set(), added common PING/PONG events Modified Paths: -------------- trunk/yake/src/yake/net/detail/netCommon.cpp trunk/yake/yake/net/netCommon.h trunk/yake/yake/net/netEvent.h trunk/yake/yake/samples/net/common/commonEvents.h trunk/yake/yake/samples/net/common/roCommon.h Modified: trunk/yake/src/yake/net/detail/netCommon.cpp =================================================================== --- trunk/yake/src/yake/net/detail/netCommon.cpp 2006-11-23 22:10:30 UTC (rev 1500) +++ trunk/yake/src/yake/net/detail/netCommon.cpp 2006-11-28 22:41:28 UTC (rev 1501) @@ -225,6 +225,10 @@ Timer::~Timer() { } + void Timer::set(const double time) + { + YAKE_ASSERT(0); + } void Timer::start() { start_ = ::yake::native::getTime(); Modified: trunk/yake/yake/net/netCommon.h =================================================================== --- trunk/yake/yake/net/netCommon.h 2006-11-23 22:10:30 UTC (rev 1500) +++ trunk/yake/yake/net/netCommon.h 2006-11-28 22:41:28 UTC (rev 1501) @@ -14,25 +14,26 @@ /** Used to identify network peers. */ typedef uint32 PeerId; + /** Special ID reserved to indicate the 'broadcast target'. */ const PeerId PEERID_BROADCAST = 0xffffffff; - /** Specifies the reliability method a packet will be transferred with. */ + /** Specifies the reliability method a packet can be transferred with. */ enum Reliability { R_RELIABLE = 0, R_UNRELIABLE }; - /** Specifies the ordering method a packet will be transferred with. */ + + /** Specifies the ordering method a packet can be transferred with. */ enum Ordering { O_ORDERED = 0, O_UNORDERED }; - /** Represents a specifically configured set of options. - It used for specifying additional information and hints - when sending data/packets. - Usage example: conn.send(buf.data(),buf.size(), SendOptions().setOrdering(O_ORDERED).setReliability(R_RELIABLED)); + /** Represents a specifically configured set of options and hints used for + sending one or more packets. + Usage example: conn.send(buf.data(),buf.size(), SendOptions().ordered().reliable()); */ struct NET_API SendOptions { @@ -45,17 +46,28 @@ @Remarks This setting is ignored by broadcast functions! */ SendOptions& peerId(const PeerId); + /** Set reliability method. */ SendOptions& reliability(const Reliability); + /** Set reliability method to R_RELIABLE. */ SendOptions& reliable(); + /** Set reliability method to R_UNRELIABLE. */ SendOptions& unreliable(); + /** Set ordering method. */ SendOptions& ordering(const Ordering); + /** Set ordering method to O_ORDERED. */ SendOptions& ordered(); + /** Set ordering method to O_UNORDERED. */ SendOptions& unordered(); + /** Set the channel to use. */ SendOptions& channel(const ChannelId); + /** Returns the target peer id (can also be special value like PEERID_BROADCAST). */ PeerId getPeerId() const; + /** Returns reliability method to be used for sending. */ Reliability getReliability() const; + /** Returns Ordering method to be used for sending. */ Ordering getOrdering() const; + /** Returns the channel to be used for sending. */ ChannelId getChannel() const; private: PeerId peerId_; @@ -64,20 +76,29 @@ ChannelId channelId_; }; - /** Represents a network address (IP + port pair). + /** Represents a network address (IP/host name and port pair). + IP/host name is represented as a string. */ struct NET_API Address { /** Initializes the IP with "127.0.0.1". */ Address(const uint16 port); + + /** Initialize IP. */ Address(const std::string& ip = std::string("127.0.0.1"), const uint16 port = 0); + /** Initializes with data from another address. */ Address(const Address&); ~Address(); + /** Assigns data from another address to this one. */ Address& operator=(const Address&); + /** Sets the IP or host name. */ void setIp(const std::string& ip); + /** Returns the IP or host name. */ const std::string& ip() const; + /** Sets the port number. */ void setPort(const uint16 port); + /** Returns the port number. */ const uint16 port() const; private: std::string ip_; @@ -92,7 +113,7 @@ namespace native { /** Sleeps the active thread for a certain number of milliseconds. This also yields the thread! (For example, a Win32 implementation - may use ::Sleep().) + may use ::Sleep() internally.) */ NET_API void sleep(const uint32 ms); } // namespace native @@ -102,6 +123,7 @@ { Exception(const std::string& msg, const char* file = 0, const int line = 0); virtual ~Exception() throw() {} + /** Return a descriptive string with details on the exception. */ virtual const char* what() const throw(); private: std::string msg_; @@ -114,12 +136,19 @@ public: Timer(); ~Timer(); + /** Starts timing. */ void start(); + /** Stops timing. Use start() to restart. */ void stop(); + /** Pauses timing. Use resume() to continue. */ void pause(); + /** Resumes timing after pause() has been called. */ void resume(); + /** Reset time to 0. */ void reset(); + /** Returns the total elapsed time in seconds. */ double getTime() const; + void set(const double); private: double start_; mutable double time_; @@ -128,6 +157,8 @@ typedef uint8 byte; typedef byte* byte_ptr; + /** Represents a chunk of data with functionality for resizing. + */ struct NET_API DataChunk { public: @@ -206,16 +237,22 @@ size_t dataSize_; }; + /** Represents a packet for sending and receiving. + */ struct NET_API Packet : boost::noncopyable { + /** Construct packet, optionally copying existing data. */ Packet(const void* dataPtr = 0, const size_t dataSize = 0); //SendOptions& options(); //const SendOptions& options() const; + + /** Access packet payload (the contained information). */ const DataChunk& payload() const; private: DataChunk payload_; //SendOptions opt_; }; + /** Shared pointer for packets is used for flexible lifetime control. */ typedef yake::SharedPtr<Packet> PacketPtr; } // namespace net Modified: trunk/yake/yake/net/netEvent.h =================================================================== --- trunk/yake/yake/net/netEvent.h 2006-11-23 22:10:30 UTC (rev 1500) +++ trunk/yake/yake/net/netEvent.h 2006-11-28 22:41:28 UTC (rev 1501) @@ -14,13 +14,25 @@ typedef ByteVectorSink bitstream_sink; typedef ByteVectorSource bitstream_source; + /** Base class for event objects that can be sent and received via + INetEventConnections. + @see INetEventConnection + */ class NET_API NetEvent { public: virtual ~NetEvent() {} + /** Type to identify events. */ typedef uint8 id_type; + /** Special value used in certain circumstances. + It is defined as 0xff. + */ static const id_type EVTID_NONE; + /** Direction events can travel. + @todo replace with DIR_OUTGOING and DIR_INCOMING instead of + DIR_CLIENT_TO_SERVER and DIR_SERVER_TO_CLIENT. + */ enum Direction { DIR_ANY, DIR_CLIENT_TO_SERVER, //@todo make DIR_OUTGOING @@ -35,10 +47,17 @@ NetEvent(const id_type); public: + /** Returns the ID of this event. */ id_type id() const; void setId(const id_type id); //@really needed? + /** Serialize event information into the bitstream. + @note It is not necessary to serialize the event id. + */ virtual bool pack(obitstream&) const = 0; + /** Deserialize event information. + @note Format has to match the one used in pack() obviously. + */ virtual bool unpack(ibitstream&) = 0; //NetEvent* clone(); Modified: trunk/yake/yake/samples/net/common/commonEvents.h =================================================================== --- trunk/yake/yake/samples/net/common/commonEvents.h 2006-11-23 22:10:30 UTC (rev 1500) +++ trunk/yake/yake/samples/net/common/commonEvents.h 2006-11-28 22:41:28 UTC (rev 1501) @@ -340,4 +340,61 @@ } std::string cId_; }; +struct s2cEvtPing : public yake::net::NetEvent +{ + DECLARE_EVENT( s2cEvtPing, 40 ); + s2cEvtPing(const yake::uint32 serverTime) : + yake::net::NetEvent(ID), serverTime_(serverTime) + {} + virtual bool pack(yake::net::obitstream& out) const + { + out << serverTime_; + return true; + } + virtual bool unpack(yake::net::ibitstream& in) + { + in >> serverTime_; + return true; + } + yake::uint32 serverTime_; +}; +struct c2sEvtPong : public yake::net::NetEvent +{ + DECLARE_EVENT( c2sEvtPong, 41 ); + c2sEvtPong(const yake::uint32 clientTime, const yake::uint32 serverTime) : + yake::net::NetEvent(ID), clientTime_(clientTime), serverTime_(serverTime) + {} + virtual bool pack(yake::net::obitstream& out) const + { + out << serverTime_ << clientTime_; + return true; + } + virtual bool unpack(yake::net::ibitstream& in) + { + in >> serverTime_ >> clientTime_; + return true; + } + yake::uint32 serverTime_; + yake::uint32 clientTime_; +}; +struct s2cEvtPong : public yake::net::NetEvent +{ + DECLARE_EVENT( s2cEvtPong, 42 ); + s2cEvtPong(const yake::uint32 serverTime2_, const yake::uint32 clientTime, const yake::uint32 serverTime) : + yake::net::NetEvent(ID), clientTime_(clientTime), serverTime_(serverTime), serverTime2_(serverTime_) + {} + virtual bool pack(yake::net::obitstream& out) const + { + out << serverTime_ << clientTime_ << serverTime2_; + return true; + } + virtual bool unpack(yake::net::ibitstream& in) + { + in >> serverTime_ >> clientTime_ >> serverTime2_; + return true; + } + yake::uint32 serverTime_; + yake::uint32 serverTime2_; + yake::uint32 clientTime_; +}; #endif Modified: trunk/yake/yake/samples/net/common/roCommon.h =================================================================== --- trunk/yake/yake/samples/net/common/roCommon.h 2006-11-23 22:10:30 UTC (rev 1500) +++ trunk/yake/yake/samples/net/common/roCommon.h 2006-11-28 22:41:28 UTC (rev 1501) @@ -7,17 +7,33 @@ namespace yake { namespace ro { struct IServiceHost; + /** Represents a service that can be plugged added to and managed by an IServiceHost. + */ struct IService : public boost::noncopyable { virtual ~IService() {} + /** Callback is triggered when the service should start and + has to be overridden by derived classes. + @note An IServiceHost may decide to start and stop services + under various circumstances. + */ virtual void onStart(IServiceHost&) = 0; + /** Callback is triggered when the service should stop and + has to be overridden by derived classes. + @note An IServiceHost may decide to start and stop services + under various circumstances. + */ virtual void onStop(IServiceHost&) = 0; }; + /** Shared pointer managing an IService pointer. */ typedef SharedPtr<IService> IServicePtr; namespace detail { - //@todo private/impl + /** Implementation specific object managing + a number of services. + @todo Move into private area (i.e. where library users cannot see it). + */ struct ServiceManager : public boost::noncopyable { void addService(IServicePtr, const std::string& tag = ""); @@ -38,6 +54,9 @@ }; } // namespace detail typedef SharedPtr<net::INetEventConnection> NetEventConnectionPtr; + /** Base class for objects that have control over packet and event connections + and manage a number of attachable services. + */ struct IServiceHost : public boost::noncopyable { protected: @@ -45,7 +64,12 @@ public: virtual ~IServiceHost() {} + /** Start the IServiceHost and all registered services. + @note Services can be added after the IServiceHost has been started. + */ bool start(); + /** Stop the IServiceHost and all registered services. + */ void stop(); virtual NetEventConnectionPtr getEventConnection() const = 0; @@ -54,22 +78,54 @@ //virtual net::IServerPacketConnection* getServerPacketConnection() const = 0; // mirror detail::ServiceManager interface (internally forwarded) + + /** Adds a service to the host. The host takes control over + starting and stopping the service. + @note The service should not have been started when it is passed to addService()! + @remarks Services can be added before or after starting the IServiceHost. + If an IService is added before start() has been called, then its onStart() + callback will be called when start() is finally called. + If an IService is added after start() has been called, then its onStart() + callback will be immediately called from within the addService() method. + */ void addService(IServicePtr, const std::string& tag = ""); + /** Removes the given service. + @note The service is stopped if it's running. + */ IServicePtr removeService(IServicePtr); + /** Removes the service identified by the given tag. + @note The service is stopped if it's running. + */ IServicePtr removeService(const std::string&); + /** Removes all services. + @note Services are stopped if they're running. + */ void removeAllServices(); + /** Returns a pointer to the service identified by the given tag. + */ IServicePtr getService(const std::string& tag) const; typedef net::INetEventConnection::EvtProcessEventFn EvtProcessEventFn; + /** Use this method to subscribe to certain net events on a specific channel. + */ SignalConnection subscribeToNetEvent( const net::NetEvent::id_type, const net::ChannelId, const EvtProcessEventFn& fn); + + /** Use this method to subscribe to all net events on a specific channel. + */ SignalConnection subscribeToNetEventChannel( const net::ChannelId, const EvtProcessEventFn& fn); private: virtual bool onStart() = 0; virtual void onStop() = 0; protected: + /** Returns true if the IServiceHost has been started, otherwise false. + */ bool running() const; + /** Dispatches received net events to registered listeners. + @see subscribeToNetEvent + @see subscribeToNetEventChannel + */ void dispatchNetEvent(const net::PeerId, const net::NetEvent&, const net::ChannelId); private: detail::ServiceManager serviceMgr_; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2006-12-03 00:18:46
|
Revision: 1508 http://svn.sourceforge.net/yake/?rev=1508&view=rev Author: psyclonist Date: 2006-12-02 16:18:45 -0800 (Sat, 02 Dec 2006) Log Message: ----------- added ro::server::setInterface(), added debug output Modified Paths: -------------- trunk/yake/src/yake/samples/net/roclient/ROClient.cpp trunk/yake/src/yake/samples/net/roserver/ROServer.cpp trunk/yake/yake/samples/net/roserver/ROServer.h Modified: trunk/yake/src/yake/samples/net/roclient/ROClient.cpp =================================================================== --- trunk/yake/src/yake/samples/net/roclient/ROClient.cpp 2006-12-03 00:17:33 UTC (rev 1507) +++ trunk/yake/src/yake/samples/net/roclient/ROClient.cpp 2006-12-03 00:18:45 UTC (rev 1508) @@ -34,6 +34,7 @@ conn_->addStartedCallback( boost::bind(&client::onClientStarted,this) ); // attempt to connect to server + COUTLN("trying to connect to '" << serverAddr_.ip() << ":" << serverAddr_.port() << "' ..."); /* conn_->connect( serverAddr_, true, 2000 ); */ Modified: trunk/yake/src/yake/samples/net/roserver/ROServer.cpp =================================================================== --- trunk/yake/src/yake/samples/net/roserver/ROServer.cpp 2006-12-03 00:17:33 UTC (rev 1507) +++ trunk/yake/src/yake/samples/net/roserver/ROServer.cpp 2006-12-03 00:18:45 UTC (rev 1508) @@ -243,13 +243,17 @@ //----------------------------------------------------------------------------- - server::server() : packetConnStarted_(false) + server::server() : packetConnStarted_(false), bindInterface_("127.0.0.1:40000") { } server::~server() { stop(); } + void server::setInterface(const net::Address& bindInterface) + { + bindInterface_ = bindInterface; + } /* void server::queueEvent(const net::PeerId id, net::NetEvent* evt, const net::ChannelId cId) { @@ -284,7 +288,6 @@ if (conn_) return true; - const uint16 port = 40000; const size_t maxClients = 32; conn_.reset( net::createServerPacketConnection() ); @@ -294,8 +297,8 @@ conn_->addPacketReceivedCallback( boost::bind(&server::onReceivePacket,this,_1,_2,_3) ); conn_->addClientDisconnectedCallback( boost::bind(&server::onClientDisconnected,this,_1) ); - COUTLN("starting server at port " << port << " with max. " << maxClients << " clients..."); - conn_->start( net::Address(port), maxClients ); + COUTLN("starting server at '" << bindInterface_.ip() << ":" << bindInterface_.port() << "' with max. " << maxClients << " clients..."); + conn_->start( bindInterface_, maxClients ); // wait until net object is up while (!packetConnStarted_) Modified: trunk/yake/yake/samples/net/roserver/ROServer.h =================================================================== --- trunk/yake/yake/samples/net/roserver/ROServer.h 2006-12-03 00:17:33 UTC (rev 1507) +++ trunk/yake/yake/samples/net/roserver/ROServer.h 2006-12-03 00:18:45 UTC (rev 1508) @@ -17,6 +17,9 @@ server(); ~server(); + // Call before start() + void setInterface(const net::Address&); + // implement IServiceHost interface virtual NetEventConnectionPtr getEventConnection() const { return this->evtConn_; } @@ -69,6 +72,7 @@ private: // internal callback void onClientSimStarted(iclient&); private: + net::Address bindInterface_; // volatile bool packetConnStarted_; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2006-12-03 00:45:15
|
Revision: 1510 http://svn.sourceforge.net/yake/?rev=1510&view=rev Author: psyclonist Date: 2006-12-02 16:45:15 -0800 (Sat, 02 Dec 2006) Log Message: ----------- added netsvc component Added Paths: ----------- trunk/yake/scripts/msvc8/netSvc.vcproj trunk/yake/src/yake/netsvc/ trunk/yake/src/yake/netsvc/netService.cpp trunk/yake/src/yake/netsvc/netServiceHost.cpp trunk/yake/src/yake/netsvc/netSvc.cpp trunk/yake/src/yake/netsvc/pch.cpp trunk/yake/yake/netsvc/ trunk/yake/yake/netsvc/netPrerequisites.h trunk/yake/yake/netsvc/netService.h trunk/yake/yake/netsvc/netServiceHost.h trunk/yake/yake/netsvc/netSvc.h trunk/yake/yake/netsvc/pch.h Added: trunk/yake/scripts/msvc8/netSvc.vcproj =================================================================== --- trunk/yake/scripts/msvc8/netSvc.vcproj (rev 0) +++ trunk/yake/scripts/msvc8/netSvc.vcproj 2006-12-03 00:45:15 UTC (rev 1510) @@ -0,0 +1,255 @@ +<?xml version="1.0" encoding="Windows-1252"?> +<VisualStudioProject + ProjectType="Visual C++" + Version="8,00" + Name="netSvc" + ProjectGUID="{E50171E1-18D3-495B-9942-D99DF08E1040}" + RootNamespace="netSvc" + Keyword="Win32Proj" + > + <Platforms> + <Platform + Name="Win32" + /> + </Platforms> + <ToolFiles> + </ToolFiles> + <Configurations> + <Configuration + Name="Debug|Win32" + OutputDirectory="../../common/bin/debug" + IntermediateDirectory="../../common/obj/debug/$(ProjectName)" + ConfigurationType="2" + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + > + <Tool + Name="VCPreBuildEventTool" + /> + <Tool + Name="VCCustomBuildTool" + /> + <Tool + Name="VCXMLDataGeneratorTool" + /> + <Tool + Name="VCWebServiceProxyGeneratorTool" + /> + <Tool + Name="VCMIDLTool" + /> + <Tool + Name="VCCLCompilerTool" + Optimization="0" + AdditionalIncludeDirectories="../../;../../dependencies/boost/;../../dependencies/ttl/;..dependencies/tinyxml" + PreprocessorDefinitions="_STLP_DEBUG;WIN32;_DEBUG;_WINDOWS;_USRDLL;YAKE_NETSVC_EXPORTS" + MinimalRebuild="true" + BasicRuntimeChecks="3" + RuntimeLibrary="3" + RuntimeTypeInfo="true" + UsePrecompiledHeader="2" + PrecompiledHeaderThrough="yake/netsvc/pch.h" + WarningLevel="3" + Detect64BitPortabilityProblems="true" + DebugInformationFormat="4" + /> + <Tool + Name="VCManagedResourceCompilerTool" + /> + <Tool + Name="VCResourceCompilerTool" + /> + <Tool + Name="VCPreLinkEventTool" + /> + <Tool + Name="VCLinkerTool" + AdditionalDependencies="base.lib" + OutputFile="$(OutDir)/yake_$(ProjectName)-vc80-d.dll" + LinkIncremental="2" + AdditionalLibraryDirectories="../../common/lib;../../common/lib/debug;../../dependencies/lib" + GenerateDebugInformation="true" + ProgramDatabaseFile="$(OutDir)/$(ProjectName).pdb" + SubSystem="2" + ImportLibrary="../../common/lib/$(TargetName).lib" + TargetMachine="1" + /> + <Tool + Name="VCALinkTool" + /> + <Tool + Name="VCManifestTool" + /> + <Tool + Name="VCXDCMakeTool" + /> + <Tool + Name="VCBscMakeTool" + /> + <Tool + Name="VCFxCopTool" + /> + <Tool + Name="VCAppVerifierTool" + /> + <Tool + Name="VCWebDeploymentTool" + /> + <Tool + Name="VCPostBuildEventTool" + /> + </Configuration> + <Configuration + Name="Release|Win32" + OutputDirectory="../../common/bin/release" + IntermediateDirectory="../../common/obj/release/$(ProjectName)" + ConfigurationType="2" + InheritedPropertySheets="$(VCInstallDir)VCProjectDefaults\UpgradeFromVC71.vsprops" + CharacterSet="2" + > + <Tool + Name="VCPreBuildEventTool" + /> + <Tool + Name="VCCustomBuildTool" + /> + <Tool + Name="VCXMLDataGeneratorTool" + /> + <Tool + Name="VCWebServiceProxyGeneratorTool" + /> + <Tool + Name="VCMIDLTool" + /> + <Tool + Name="VCCLCompilerTool" + AdditionalIncludeDirectories="../../;../../dependencies/boost/;../../dependencies/ttl/;..dependencies/tinyxml" + PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USRDLL;YAKE_NETSVC_EXPORTS" + RuntimeLibrary="2" + RuntimeTypeInfo="true" + UsePrecompiledHeader="2" + PrecompiledHeaderThrough="yake/netsvc/pch.h" + WarningLevel="3" + Detect64BitPortabilityProblems="true" + DebugInformationFormat="3" + /> + <Tool + Name="VCManagedResourceCompilerTool" + /> + <Tool + Name="VCResourceCompilerTool" + /> + <Tool + Name="VCPreLinkEventTool" + /> + <Tool + Name="VCLinkerTool" + AdditionalDependencies="base.lib" + OutputFile="$(OutDir)/yake_$(ProjectName)-vc80.dll" + LinkIncremental="1" + AdditionalLibraryDirectories="../../common/lib;../../common/lib/release;../../dependencies/lib" + GenerateDebugInformation="false" + SubSystem="1" + OptimizeReferences="2" + EnableCOMDATFolding="2" + ImportLibrary="../../common/lib/release/$(TargetName).lib" + TargetMachine="1" + /> + <Tool + Name="VCALinkTool" + /> + <Tool + Name="VCManifestTool" + /> + <Tool + Name="VCXDCMakeTool" + /> + <Tool + Name="VCBscMakeTool" + /> + <Tool + Name="VCFxCopTool" + /> + <Tool + Name="VCAppVerifierTool" + /> + <Tool + Name="VCWebDeploymentTool" + /> + <Tool + Name="VCPostBuildEventTool" + /> + </Configuration> + </Configurations> + <References> + </References> + <Files> + <Filter + Name="src" + Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx" + UniqueIdentifier="{1441AE57-C6D0-4c49-BE0F-31522C92DE6C}" + > + <File + RelativePath="..\..\src\yake\netsvc\netService.cpp" + > + </File> + <File + RelativePath="..\..\src\yake\netsvc\netServiceHost.cpp" + > + </File> + <File + RelativePath="..\..\src\yake\netsvc\netSvc.cpp" + > + </File> + <File + RelativePath="..\..\src\yake\netsvc\pch.cpp" + > + <FileConfiguration + Name="Debug|Win32" + > + <Tool + Name="VCCLCompilerTool" + UsePrecompiledHeader="1" + /> + </FileConfiguration> + <FileConfiguration + Name="Release|Win32" + > + <Tool + Name="VCCLCompilerTool" + UsePrecompiledHeader="1" + /> + </FileConfiguration> + </File> + </Filter> + <Filter + Name="inc" + Filter="h;hpp;hxx;hm;inl;inc;xsd" + UniqueIdentifier="{EAA8A4D1-68D3-40d3-8FA1-8ABB03609AF8}" + > + <File + RelativePath="..\..\yake\netsvc\netPrerequisites.h" + > + </File> + <File + RelativePath="..\..\yake\netsvc\netService.h" + > + </File> + <File + RelativePath="..\..\yake\netsvc\netServiceHost.h" + > + </File> + <File + RelativePath="..\..\yake\netsvc\netSvc.h" + > + </File> + <File + RelativePath="..\..\yake\netsvc\pch.h" + > + </File> + </Filter> + </Files> + <Globals> + </Globals> +</VisualStudioProject> Added: trunk/yake/src/yake/netsvc/netService.cpp =================================================================== --- trunk/yake/src/yake/netsvc/netService.cpp (rev 0) +++ trunk/yake/src/yake/netsvc/netService.cpp 2006-12-03 00:45:15 UTC (rev 1510) @@ -0,0 +1,9 @@ +#include <yake/netsvc/pch.h> +#include <yake/netsvc/netService.h> +#include <yake/netsvc/netServiceHost.h> + +namespace yake { +namespace net { + +} // namespace net +} // namespace yake Added: trunk/yake/src/yake/netsvc/netServiceHost.cpp =================================================================== --- trunk/yake/src/yake/netsvc/netServiceHost.cpp (rev 0) +++ trunk/yake/src/yake/netsvc/netServiceHost.cpp 2006-12-03 00:45:15 UTC (rev 1510) @@ -0,0 +1,185 @@ +#include <yake/netsvc/pch.h> +#include <yake/netsvc/netService.h> +#include <yake/netsvc/netServiceHost.h> + +namespace yake { +namespace net { + + //----------------------------------------------------------------------------- + IServiceHost::IServiceHost() : running_(false) + { + } + bool IServiceHost::running() const + { + boost::mutex::scoped_lock lck(runningMtx_); + return running_; + } + bool IServiceHost::start() + { + bool succ = this->onStart(); + if (!succ) + return false; + + { + boost::mutex::scoped_lock lck(runningMtx_); + running_ = true; + } + + // start services + YAKE_FOR_EACH(detail::ServiceManager::const_service_iterator,it,serviceMgr_) + { + (*it)->onStart(*this); + } + + return true; + } + void IServiceHost::stop() + { + { + boost::mutex::scoped_lock lck(runningMtx_); + running_ = false; + } + + // stop services + YAKE_FOR_EACH(detail::ServiceManager::const_service_iterator,it,serviceMgr_) + { + (*it)->onStop(*this); + } + + // stop the rest + this->onStop(); + } + void IServiceHost::addService(IServicePtr service, const std::string& tag) + { + serviceMgr_.addService( service, tag ); + if (this->running()) + service->onStart(*this); + } + void IServiceHost::removeAllServices() + { + serviceMgr_.removeAllServices(); + } + IServicePtr IServiceHost::removeService(const std::string & tag) + { + IServicePtr service = serviceMgr_.removeService( tag ); + if (service && this->running()) + service->onStop(*this); + return service; + } + IServicePtr IServiceHost::removeService(IServicePtr service) + { + serviceMgr_.removeService( service ); + if (service && this->running()) + service->onStop(*this); + return service; + } + IServicePtr IServiceHost::getService(const std::string& tag) const + { + return serviceMgr_.getService( tag ); + } + void IServiceHost::dispatchNetEvent(const net::PeerId pId, const net::NetEvent& evt, const net::ChannelId cId) + { + // find catch-all for this channel (ignore event id) + { + SigMap::const_iterator it = sigMap_.find( ChannelEventIdPair(cId,net::NetEvent::EVTID_NONE) ); + if (it != sigMap_.end()) + (*it->second)(pId,evt,cId); + } + + // find signal for this channel and event id: + SigMap::const_iterator it = sigMap_.find( ChannelEventIdPair(cId,evt.id()) ); + if (it == sigMap_.end()) + return; + (*it->second)(pId,evt,cId); + } + SignalConnection IServiceHost::subscribeToNetEvent( + const net::NetEvent::id_type eId, const net::ChannelId cId, const EvtProcessEventFn& fn) + { + const ChannelEventIdPair idPair(cId,eId); + + SigMap::iterator it = sigMap_.find( idPair ); + if (it == sigMap_.end()) + { + ProcessEventSigPtr sig( new ProcessEventSig() ); + sigMap_[ idPair ] = sig; + return sig->connect( fn ); + } + return it->second->connect(fn); + } + SignalConnection IServiceHost::subscribeToNetEventChannel( + const net::ChannelId cId, const EvtProcessEventFn& fn) + { + const ChannelEventIdPair idPair(cId,net::NetEvent::EVTID_NONE); + + SigMap::iterator it = sigMap_.find( idPair ); + if (it == sigMap_.end()) + { + ProcessEventSigPtr sig( new ProcessEventSig() ); + sigMap_[ idPair ] = sig; + return sig->connect( fn ); + } + return it->second->connect(fn); + } + +//----------------------------------------------------------------------------- +namespace detail { + + void ServiceManager::addService(IServicePtr service, const std::string& tag) + { + YAKE_ASSERT( service ); + if (!service) + return; + + services_.insert( service ); + if (!tag.empty()) + { + YAKE_ASSERT( tag2service_.find(tag) == tag2service_.end() ).debug("duplicate tag!"); + tag2service_[ tag ] = service; + } + } + IServicePtr ServiceManager::getService(const std::string& tag) const + { + TagMap::const_iterator itFind = tag2service_.find(tag); + return (itFind == tag2service_.end() ? IServicePtr() : itFind->second); + } + IServicePtr ServiceManager::removeService(const std::string& tag) + { + TagMap::iterator itFind = tag2service_.find(tag); + if (itFind == tag2service_.end()) + return IServicePtr(); + IServicePtr service = itFind->second; + tag2service_.erase( itFind ); + services_.erase( service ); + return service; + } + IServicePtr ServiceManager::removeService(const IServicePtr service) + { + YAKE_FOR_EACH(TagMap::iterator,itFind,tag2service_) + { + if (itFind->second == service) + { + tag2service_.erase( itFind ); + break; + } + } + services_.erase( service ); + return service; + } + void ServiceManager::removeAllServices() + { + tag2service_.clear(); + services_.clear(); + } + ServiceManager::const_service_iterator ServiceManager::begin() const + { + return services_.begin(); + } + ServiceManager::const_service_iterator ServiceManager::end() const + { + return services_.end(); + } + +} // namespace detail + +} // namespace net +} // namespace yake Added: trunk/yake/src/yake/netsvc/netSvc.cpp =================================================================== --- trunk/yake/src/yake/netsvc/netSvc.cpp (rev 0) +++ trunk/yake/src/yake/netsvc/netSvc.cpp 2006-12-03 00:45:15 UTC (rev 1510) @@ -0,0 +1,9 @@ +#include <yake/netsvc/pch.h> +#include <yake/netsvc/netService.h> +#include <yake/netsvc/netServiceHost.h> + +namespace yake { +namespace net { + +} // namespace net +} // namespace yake Added: trunk/yake/src/yake/netsvc/pch.cpp =================================================================== --- trunk/yake/src/yake/netsvc/pch.cpp (rev 0) +++ trunk/yake/src/yake/netsvc/pch.cpp 2006-12-03 00:45:15 UTC (rev 1510) @@ -0,0 +1 @@ +#include <yake/netsvc/pch.h> Added: trunk/yake/yake/netsvc/netPrerequisites.h =================================================================== --- trunk/yake/yake/netsvc/netPrerequisites.h (rev 0) +++ trunk/yake/yake/netsvc/netPrerequisites.h 2006-12-03 00:45:15 UTC (rev 1510) @@ -0,0 +1,30 @@ +#ifndef YAKE_NETSVC_PREREQUISITES_H +#define YAKE_NETSVC_PREREQUISITES_H + +#include <yake/base/yakePrerequisites.h> +#include <yake/base/yake.h> +#include <yake/net/net.h> + +#define YAKE_NETSVC_DLL + +#ifdef YAKE_NETSVC_EXPORTS +# ifdef YAKE_NETSVC_DLL +# define NETSVC_API DLLEXPORT +# else +# define NETSVC_API +# endif +#else +# ifdef YAKE_NETSVC_DLL +# define NETSVC_API DLLIMPORT +# else +# define NETSVC_API +# endif +# if defined( _DEBUG ) +# pragma comment(lib,"yake_netsvc-vc80-d.lib") +# else +# pragma comment(lib,"yake_netsvc-vc80.lib") +# endif +#endif + +#endif + Added: trunk/yake/yake/netsvc/netService.h =================================================================== --- trunk/yake/yake/netsvc/netService.h (rev 0) +++ trunk/yake/yake/netsvc/netService.h 2006-12-03 00:45:15 UTC (rev 1510) @@ -0,0 +1,41 @@ +#ifndef YAKE_NETSVC_SERVICE_H +#define YAKE_NETSVC_SERVICE_H + +#include "netPrerequisites.h" +//#include "netCommon.h" + +#pragma warning(push) +#pragma warning(disable: 4275) // C4275: non dll-interface class 'X' used as base for dll-interface 'Y' + +namespace yake { +namespace net { + + struct IServiceHost; + /** Represents a service that can be plugged added to and managed by an IServiceHost. + */ + struct NETSVC_API IService : public boost::noncopyable + { + virtual ~IService() {} + + /** Callback is triggered when the service should start and + has to be overridden by derived classes. + @note An IServiceHost may decide to start and stop services + under various circumstances. + */ + virtual void onStart(IServiceHost&) = 0; + /** Callback is triggered when the service should stop and + has to be overridden by derived classes. + @note An IServiceHost may decide to start and stop services + under various circumstances. + */ + virtual void onStop(IServiceHost&) = 0; + }; + /** Shared pointer managing an IService pointer. */ + typedef SharedPtr<IService> IServicePtr; + +} // namespace net +} // namespace yake + +#pragma warning(pop) + +#endif Added: trunk/yake/yake/netsvc/netServiceHost.h =================================================================== --- trunk/yake/yake/netsvc/netServiceHost.h (rev 0) +++ trunk/yake/yake/netsvc/netServiceHost.h 2006-12-03 00:45:15 UTC (rev 1510) @@ -0,0 +1,135 @@ +#ifndef YAKE_NETSVC_SERVICEHOST_H +#define YAKE_NETSVC_SERVICEHOST_H + +#include <boost/thread/mutex.hpp> +#include "netPrerequisites.h" +#include "netService.h" + +#pragma warning(push) +#pragma warning(disable: 4275) // C4275: non dll-interface class 'X' used as base for dll-interface 'Y' + +namespace yake { +namespace net { + + namespace detail { + /** Implementation specific object managing + a number of services. + @todo Move into private area (i.e. where library users cannot see it). + */ + struct NETSVC_API ServiceManager : public boost::noncopyable + { + void addService(IServicePtr, const std::string& tag = ""); + IServicePtr removeService(IServicePtr); + IServicePtr removeService(const std::string&); + void removeAllServices(); + IServicePtr getService(const std::string& tag) const; + private: + typedef std::set<IServicePtr> ServiceList; + public: + typedef ServiceList::const_iterator const_service_iterator; + const_service_iterator begin() const; + const_service_iterator end() const; + private: + typedef std::map<std::string,IServicePtr> TagMap; + TagMap tag2service_; + ServiceList services_; + }; + } // namespace detail + typedef SharedPtr<net::INetEventConnection> NetEventConnectionPtr; + /** Base class for objects that have control over packet and event connections + and manage a number of attachable services. + */ + struct NETSVC_API IServiceHost : public boost::noncopyable + { + protected: + IServiceHost(); + public: + virtual ~IServiceHost() {} + + /** Start the IServiceHost and all registered services. + @note Services can be added after the IServiceHost has been started. + */ + bool start(); + /** Stop the IServiceHost and all registered services. + */ + void stop(); + + virtual NetEventConnectionPtr getEventConnection() const = 0; + //virtual net::IPacketConnection* getPacketConnection() const = 0; + //virtual net::IClientPacketConnection* getClientPacketConnection() const = 0; + //virtual net::IServerPacketConnection* getServerPacketConnection() const = 0; + + // mirror detail::ServiceManager interface (internally forwarded) + + /** Adds a service to the host. The host takes control over + starting and stopping the service. + @note The service should not have been started when it is passed to addService()! + @remarks Services can be added before or after starting the IServiceHost. + If an IService is added before start() has been called, then its onStart() + callback will be called when start() is finally called. + If an IService is added after start() has been called, then its onStart() + callback will be immediately called from within the addService() method. + */ + void addService(IServicePtr, const std::string& tag = ""); + /** Removes the given service. + @note The service is stopped if it's running. + */ + IServicePtr removeService(IServicePtr); + /** Removes the service identified by the given tag. + @note The service is stopped if it's running. + */ + IServicePtr removeService(const std::string&); + /** Removes all services. + @note Services are stopped if they're running. + */ + void removeAllServices(); + /** Returns a pointer to the service identified by the given tag. + */ + IServicePtr getService(const std::string& tag) const; + + typedef net::INetEventConnection::EvtProcessEventFn EvtProcessEventFn; + /** Use this method to subscribe to certain net events on a specific channel. + */ + SignalConnection subscribeToNetEvent( + const net::NetEvent::id_type, const net::ChannelId, const EvtProcessEventFn& fn); + + /** Use this method to subscribe to all net events on a specific channel. + */ + SignalConnection subscribeToNetEventChannel( + const net::ChannelId, const EvtProcessEventFn& fn); + private: + virtual bool onStart() = 0; + virtual void onStop() = 0; + protected: + /** Returns true if the IServiceHost has been started, otherwise false. + */ + bool running() const; + /** Dispatches received net events to registered listeners. + @see subscribeToNetEvent + @see subscribeToNetEventChannel + */ + void dispatchNetEvent(const net::PeerId, const net::NetEvent&, const net::ChannelId); + private: + detail::ServiceManager serviceMgr_; + volatile bool running_; + mutable boost::mutex runningMtx_; + + typedef SignalX<void(const net::PeerId, const net::NetEvent&, const net::ChannelId)> ProcessEventSig; + typedef SharedPtr<ProcessEventSig> ProcessEventSigPtr; + + typedef std::pair<net::ChannelId,net::NetEvent::id_type> ChannelEventIdPair; + typedef std::map<ChannelEventIdPair,ProcessEventSigPtr> SigMap; + + struct EventIdEntry + { + ProcessEventSigPtr sig_; + }; + SigMap sigMap_; + }; + +} // namespace net +} // namespace yake + +#pragma warning(pop) + +#endif Added: trunk/yake/yake/netsvc/netSvc.h =================================================================== --- trunk/yake/yake/netsvc/netSvc.h (rev 0) +++ trunk/yake/yake/netsvc/netSvc.h 2006-12-03 00:45:15 UTC (rev 1510) @@ -0,0 +1,152 @@ +#ifndef YAKE_NETSVC_H +#define YAKE_NETSVC_H + +#include "netPrerequisites.h" +//#include "netCommon.h" + +namespace yake { +namespace net { + + struct IServiceHost; + /** Represents a service that can be plugged added to and managed by an IServiceHost. + */ + struct IService : public boost::noncopyable + { + virtual ~IService() {} + + /** Callback is triggered when the service should start and + has to be overridden by derived classes. + @note An IServiceHost may decide to start and stop services + under various circumstances. + */ + virtual void onStart(IServiceHost&) = 0; + /** Callback is triggered when the service should stop and + has to be overridden by derived classes. + @note An IServiceHost may decide to start and stop services + under various circumstances. + */ + virtual void onStop(IServiceHost&) = 0; + }; + /** Shared pointer managing an IService pointer. */ + typedef SharedPtr<IService> IServicePtr; + + namespace detail { + /** Implementation specific object managing + a number of services. + @todo Move into private area (i.e. where library users cannot see it). + */ + struct ServiceManager : public boost::noncopyable + { + void addService(IServicePtr, const std::string& tag = ""); + IServicePtr removeService(IServicePtr); + IServicePtr removeService(const std::string&); + void removeAllServices(); + IServicePtr getService(const std::string& tag) const; + private: + typedef std::set<IServicePtr> ServiceList; + public: + typedef ServiceList::const_iterator const_service_iterator; + const_service_iterator begin() const; + const_service_iterator end() const; + private: + typedef std::map<std::string,IServicePtr> TagMap; + TagMap tag2service_; + ServiceList services_; + }; + } // namespace detail + typedef SharedPtr<net::INetEventConnection> NetEventConnectionPtr; + /** Base class for objects that have control over packet and event connections + and manage a number of attachable services. + */ + struct IServiceHost : public boost::noncopyable + { + protected: + IServiceHost(); + public: + virtual ~IServiceHost() {} + + /** Start the IServiceHost and all registered services. + @note Services can be added after the IServiceHost has been started. + */ + bool start(); + /** Stop the IServiceHost and all registered services. + */ + void stop(); + + virtual NetEventConnectionPtr getEventConnection() const = 0; + //virtual net::IPacketConnection* getPacketConnection() const = 0; + //virtual net::IClientPacketConnection* getClientPacketConnection() const = 0; + //virtual net::IServerPacketConnection* getServerPacketConnection() const = 0; + + // mirror detail::ServiceManager interface (internally forwarded) + + /** Adds a service to the host. The host takes control over + starting and stopping the service. + @note The service should not have been started when it is passed to addService()! + @remarks Services can be added before or after starting the IServiceHost. + If an IService is added before start() has been called, then its onStart() + callback will be called when start() is finally called. + If an IService is added after start() has been called, then its onStart() + callback will be immediately called from within the addService() method. + */ + void addService(IServicePtr, const std::string& tag = ""); + /** Removes the given service. + @note The service is stopped if it's running. + */ + IServicePtr removeService(IServicePtr); + /** Removes the service identified by the given tag. + @note The service is stopped if it's running. + */ + IServicePtr removeService(const std::string&); + /** Removes all services. + @note Services are stopped if they're running. + */ + void removeAllServices(); + /** Returns a pointer to the service identified by the given tag. + */ + IServicePtr getService(const std::string& tag) const; + + typedef net::INetEventConnection::EvtProcessEventFn EvtProcessEventFn; + /** Use this method to subscribe to certain net events on a specific channel. + */ + SignalConnection subscribeToNetEvent( + const net::NetEvent::id_type, const net::ChannelId, const EvtProcessEventFn& fn); + + /** Use this method to subscribe to all net events on a specific channel. + */ + SignalConnection subscribeToNetEventChannel( + const net::ChannelId, const EvtProcessEventFn& fn); + private: + virtual bool onStart() = 0; + virtual void onStop() = 0; + protected: + /** Returns true if the IServiceHost has been started, otherwise false. + */ + bool running() const; + /** Dispatches received net events to registered listeners. + @see subscribeToNetEvent + @see subscribeToNetEventChannel + */ + void dispatchNetEvent(const net::PeerId, const net::NetEvent&, const net::ChannelId); + private: + detail::ServiceManager serviceMgr_; + volatile bool running_; + mutable boost::mutex runningMtx_; + + typedef SignalX<void(const net::PeerId, const net::NetEvent&, const net::ChannelId)> ProcessEventSig; + typedef SharedPtr<ProcessEventSig> ProcessEventSigPtr; + + typedef std::pair<net::ChannelId,net::NetEvent::id_type> ChannelEventIdPair; + typedef std::map<ChannelEventIdPair,ProcessEventSigPtr> SigMap; + + struct EventIdEntry + { + ProcessEventSigPtr sig_; + }; + SigMap sigMap_; + }; + +} // namespace net +} // namespace yake + +#endif Added: trunk/yake/yake/netsvc/pch.h =================================================================== --- trunk/yake/yake/netsvc/pch.h (rev 0) +++ trunk/yake/yake/netsvc/pch.h 2006-12-03 00:45:15 UTC (rev 1510) @@ -0,0 +1,7 @@ +#ifndef YAKE_NET_PCH_H +#define YAKE_NET_PCH_H + +#include <yake/base/yake.h> + +#endif + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <psy...@us...> - 2006-12-03 23:51:16
|
Revision: 1513 http://svn.sourceforge.net/yake/?rev=1513&view=rev Author: psyclonist Date: 2006-12-03 15:51:16 -0800 (Sun, 03 Dec 2006) Log Message: ----------- moved 'time' and 'comm' services (client and server sides) into 'netsvc' component, minor interface tweaks Modified Paths: -------------- trunk/yake/scripts/msvc8/netSvc.vcproj trunk/yake/src/yake/samples/net/roclient/ROClient.cpp trunk/yake/src/yake/samples/net/roserver/ROServer.cpp trunk/yake/yake/netsvc/netPrerequisites.h trunk/yake/yake/netsvc/netService.h trunk/yake/yake/netsvc/netServiceHost.h trunk/yake/yake/netsvc/netSvc.h trunk/yake/yake/samples/net/common/commonEvents.h trunk/yake/yake/samples/net/roserver/ROServer.h Added Paths: ----------- trunk/yake/src/yake/netsvc/detail/ trunk/yake/src/yake/netsvc/detail/netPeerRttCalculator.cpp trunk/yake/src/yake/netsvc/service/ trunk/yake/src/yake/netsvc/service/netClientCommService.cpp trunk/yake/src/yake/netsvc/service/netClientTimeService.cpp trunk/yake/src/yake/netsvc/service/netServerCommService.cpp trunk/yake/src/yake/netsvc/service/netServerTimeService.cpp trunk/yake/yake/netsvc/detail/ trunk/yake/yake/netsvc/detail/netPeerRttCalculator.h trunk/yake/yake/netsvc/service/ trunk/yake/yake/netsvc/service/netClientCommService.h trunk/yake/yake/netsvc/service/netClientTimeService.h trunk/yake/yake/netsvc/service/netCommServiceMessages.h trunk/yake/yake/netsvc/service/netServerCommService.h trunk/yake/yake/netsvc/service/netServerTimeService.h trunk/yake/yake/netsvc/service/netTimeServiceMessages.h Modified: trunk/yake/scripts/msvc8/netSvc.vcproj =================================================================== --- trunk/yake/scripts/msvc8/netSvc.vcproj 2006-12-03 00:46:45 UTC (rev 1512) +++ trunk/yake/scripts/msvc8/netSvc.vcproj 2006-12-03 23:51:16 UTC (rev 1513) @@ -222,6 +222,34 @@ /> </FileConfiguration> </File> + <Filter + Name="services" + > + <File + RelativePath="..\..\src\yake\netsvc\service\netClientCommService.cpp" + > + </File> + <File + RelativePath="..\..\src\yake\netsvc\service\netClientTimeService.cpp" + > + </File> + <File + RelativePath="..\..\src\yake\netsvc\service\netServerCommService.cpp" + > + </File> + <File + RelativePath="..\..\src\yake\netsvc\service\netServerTimeService.cpp" + > + </File> + </Filter> + <Filter + Name="detail" + > + <File + RelativePath="..\..\src\yake\netsvc\detail\netPeerRttCalculator.cpp" + > + </File> + </Filter> </Filter> <Filter Name="inc" @@ -248,6 +276,42 @@ RelativePath="..\..\yake\netsvc\pch.h" > </File> + <Filter + Name="services" + > + <File + RelativePath="..\..\yake\netsvc\service\netClientCommService.h" + > + </File> + <File + RelativePath="..\..\yake\netsvc\service\netClientTimeService.h" + > + </File> + <File + RelativePath="..\..\yake\netsvc\service\netCommServiceMessages.h" + > + </File> + <File + RelativePath="..\..\yake\netsvc\service\netServerCommService.h" + > + </File> + <File + RelativePath="..\..\yake\netsvc\service\netServerTimeService.h" + > + </File> + <File + RelativePath="..\..\yake\netsvc\service\netTimeServiceMessages.h" + > + </File> + </Filter> + <Filter + Name="detail" + > + <File + RelativePath="..\..\yake\netsvc\detail\netPeerRttCalculator.h" + > + </File> + </Filter> </Filter> </Files> <Globals> Added: trunk/yake/src/yake/netsvc/detail/netPeerRttCalculator.cpp =================================================================== --- trunk/yake/src/yake/netsvc/detail/netPeerRttCalculator.cpp (rev 0) +++ trunk/yake/src/yake/netsvc/detail/netPeerRttCalculator.cpp 2006-12-03 23:51:16 UTC (rev 1513) @@ -0,0 +1,133 @@ +#include <yake/netsvc/pch.h> +#include <yake/netsvc/detail/netPeerRttCalculator.h> + +namespace yake { +namespace net { +namespace detail { + + static bool SortPingsByRttAscending(const PingInfo& lhs, const PingInfo& rhs) + { + return lhs.rtt_ < rhs.rtt_; + } + PeerRttCalculator::const_pinginfo_iterator PeerRttCalculator::beginReceivedPings() const + { + return receivedPings_.begin(); + } + PeerRttCalculator::const_pinginfo_iterator PeerRttCalculator::endReceivedPings() const + { + return receivedPings_.end(); + } + PeerRttCalculator::const_pinginfo_iterator PeerRttCalculator::beginSentPings() const + { + return sentPings_.begin(); + } + PeerRttCalculator::const_pinginfo_iterator PeerRttCalculator::endSentPings() const + { + return sentPings_.end(); + } + size_t PeerRttCalculator::sizeReceivedPings() const + { + return receivedPings_.size(); + } + size_t PeerRttCalculator::sizeSentPings() const + { + return sentPings_.size(); + } + void PeerRttCalculator::clearSentPings() + { + sentPings_.clear(); + } + double PeerRttCalculator::getMeanRtt() const + { + return meanRtt_; + } + void PeerRttCalculator::addSentPing(const PingInfo& info) + { + this->sentPings_.push_back( info ); + } + void PeerRttCalculator::addReceivedPing(const PingInfo& info) + { + this->receivedPings_.push_back( info ); + } + bool PeerRttCalculator::processPong(const yake::uint32 currTimeMs, + const yake::uint32 origTime) + { + // find & update ping info record in list + PingInfoList::iterator itPing = std::find_if(sentPings_.begin(),sentPings_.end(), + is_time_sent(origTime)); + if (itPing == sentPings_.end()) + { + COUTLN("(cannot find ping for time " << origTime << ")"); + return false; + } + + // store received information (i.e. move from 'sent' list to 'received' list) + receivedPings_.push_back( *itPing ); + sentPings_.erase( itPing ); + { + PingInfo& pingInfo = receivedPings_.back(); + pingInfo.timeRecvd_ = currTimeMs; + pingInfo.rtt_ = (double(pingInfo.timeRecvd_) - double(pingInfo.timeSent_)); + COUTLN(pingInfo.rtt_); + if (pingInfo.rtt_ < 0.) + { + COUTLN("(ignoring rtt < 0; rtt=" << pingInfo.rtt_ << ")\n"); + receivedPings_.pop_back(); + return false; + } + } + + // keep only last 10 records + while (receivedPings_.size() > 10) + receivedPings_.pop_front(); // remove oldest + + // recalculate mean RTT + if (receivedPings_.size() > 1) + { + // remove spikes +#if 0 + if (peerInfo.meanRtt_ >= 0.) // it's < 0. at the very beginning + { + for(PingInfoList::iterator itPing = pings.begin(); itPing != pings.end(); ) + { + if (itPing->timeRecvd_ == 0) // ignore unanswered ones + { + ++itPing; + continue; + } + // + const double rtt = itPing->rtt_; + if (rtt > (peerInfo.meanRtt_ * 2.) || + rtt < 0. || + rtt > 1000./*1 sec*/) + { + PingInfoList::iterator itNext = itPing; + if (itNext != pings.end()) + ++itNext; + pings.erase( itPing ); + itPing = itNext; + //does this work?: itNext = pings.erase(itPing); + continue; + } + ++itPing; + } + } +#endif + + // recalc mean + //if (!receivedPings.empty()) + { + double sum = 0; + YAKE_FOR_EACH(PingInfoList::const_iterator,itPing,receivedPings_) + { + sum += itPing->rtt_; + } + this->meanRtt_ = sum / double(receivedPings_.size()); + } + } + return true; + } + +} // namespace detail +} // namespace net +} // namespace yake Added: trunk/yake/src/yake/netsvc/service/netClientCommService.cpp =================================================================== --- trunk/yake/src/yake/netsvc/service/netClientCommService.cpp (rev 0) +++ trunk/yake/src/yake/netsvc/service/netClientCommService.cpp 2006-12-03 23:51:16 UTC (rev 1513) @@ -0,0 +1,74 @@ +#include <yake/netsvc/pch.h> +#include <yake/netsvc/netService.h> +#include <yake/netsvc/netServiceHost.h> +#include <yake/netsvc/service/netClientCommService.h> +#include <yake/netsvc/service/netCommServiceMessages.h> + +namespace yake { +namespace net { + + ClientCommService::ClientCommService(const ChannelId cId) : commChannelId_(cId) + { + } + void ClientCommService::onStart(IServiceHost& host) + { + COUTLN("client: starting comm service"); + evtConn_ = host.getEventConnection(); + evtConn_->registerEvent( s2cEvtCommMsg::ID, NetEvent::DIR_ANY, s2cEvtCommMsg::create, s2cEvtCommMsg::destroy ); + host.subscribeToNetEvent( s2cEvtCommMsg::ID, commChannelId_, + boost::bind(&ClientCommService::onProcessMsg,this,_1,_2,_3)); + + //this->joinChannel("#server"); // always subscribe to this channel... well, subscription isn't really necessary. + } + void ClientCommService::onStop(IServiceHost&) + { + COUTLN("client: stopping comm service"); + } + void ClientCommService::joinChannel(const String& cId) + { + c2sEvtCommJoinChannel joinChannel(cId); + evtConn_->sendEvent(joinChannel, SendOptions().channel(commChannelId_)); + } + void ClientCommService::sendMessageToChannel(const String& cId, const String& msg) + { + //@todo check whether we are a member of this channel? Server informs us, anyway. + s2cEvtCommMsg sendMsg(cId,"me",cId,msg); + evtConn_->sendEvent(sendMsg, SendOptions().channel(commChannelId_)); + } + void ClientCommService::onProcessMsg(const PeerId pId, const NetEvent& evt, const ChannelId) + { + const s2cEvtCommMsg& msg = static_cast<const s2cEvtCommMsg&>(evt); + COUTLN("client-comm: received message: cid=" << msg.cId_ << " from=" << msg.from_ << " to=" << msg.to_ << " text=" << msg.msg_); + + activeChannels_[ msg.cId_ ].outstandingMessages_.push_back(MsgEntry(msg.from_,msg.msg_)); + } + bool ClientCommService::hasMessages(const String& cId) const + { + ChannelList::const_iterator it = activeChannels_.find(cId); + if (it == activeChannels_.end()) + return false; + return !(it->second.outstandingMessages_.empty()); + } + void ClientCommService::clearMessages(const String& cId) + { + ChannelList::iterator it = activeChannels_.find(cId); + if (it != activeChannels_.end()) + it->second.outstandingMessages_.clear(); + } + ClientCommService::const_message_iterator ClientCommService::beginMessages(const String& cId) const + { + ChannelList::const_iterator it = activeChannels_.find(cId); + if (it == activeChannels_.end()) + YAKE_EXCEPT("unknown channel"); + return it->second.outstandingMessages_.begin(); + } + ClientCommService::const_message_iterator ClientCommService::endMessages(const String& cId) const + { + ChannelList::const_iterator it = activeChannels_.find(cId); + if (it == activeChannels_.end()) + YAKE_EXCEPT("unknown channel"); + return it->second.outstandingMessages_.end(); + } + +} // namespace net +} // namespace yake Added: trunk/yake/src/yake/netsvc/service/netClientTimeService.cpp =================================================================== --- trunk/yake/src/yake/netsvc/service/netClientTimeService.cpp (rev 0) +++ trunk/yake/src/yake/netsvc/service/netClientTimeService.cpp 2006-12-03 23:51:16 UTC (rev 1513) @@ -0,0 +1,104 @@ +#include <yake/netsvc/pch.h> +#include <yake/netsvc/netService.h> +#include <yake/netsvc/netServiceHost.h> +#include <yake/netsvc/service/netClientTimeService.h> +#include <yake/netsvc/service/netTimeServiceMessages.h> + +namespace yake { +namespace net { + + ClientTimeService::ClientTimeService(const ChannelId cId) : timeChannelId_(cId) + { + } + void ClientTimeService::onStart(IServiceHost& host) + { + COUTLN("starting time service"); + evtConn_ = host.getEventConnection(); + + evtConn_->registerEvent( s2cEvtPing::ID, NetEvent::DIR_ANY, s2cEvtPing::create, s2cEvtPing::destroy ); + evtConn_->registerEvent( c2sEvtPong::ID, NetEvent::DIR_ANY, c2sEvtPong::create, c2sEvtPong::destroy ); + evtConn_->registerEvent( s2cEvtPong::ID, NetEvent::DIR_ANY, s2cEvtPong::create, s2cEvtPong::destroy ); + + host.subscribeToNetEvent( s2cEvtPing::ID, timeChannelId_, + boost::bind(&ClientTimeService::onPing,this,_1,_2,_3)); + host.subscribeToNetEvent( s2cEvtPong::ID, timeChannelId_, + boost::bind(&ClientTimeService::onPong,this,_1,_2,_3)); + + firstTime_ = true; + COUTLN("time service is up"); + } + void ClientTimeService::onStop(IServiceHost&) + { + COUTLN("stopping time service"); + timer_.stop(); + + firstTime_ = false; + clockDelta_ = 0.; + } + void ClientTimeService::onPing(const PeerId pId, const NetEvent& evt, const ChannelId cId) + { + COUTLN("client-time: received PING with cId='" << int(cId) << "'"); + + const s2cEvtPing& ping = static_cast<const s2cEvtPing&>(evt); + + // this should get our clock at least into the right ballpark + if (firstTime_) + { + timer_.start(); + } + double currTime = timer_.getTime(); + if (firstTime_) + { + //clockDelta_ = 0.; + clockDelta_ = 0.001 * double(ping.serverTime_) - currTime; + COUTLN("initial clock delta = " << clockDelta_); + firstTime_ = false; + } + currTime += clockDelta_; + + // reply + c2sEvtPong msg; + msg.serverTime_ = ping.serverTime_; + msg.clientTime_ = uint32(1000. * currTime); + evtConn_->sendEvent( msg, SendOptions().channel(cId).unreliable().unordered() ); + + // store ping info for RTT calculation + rttCalc_.addSentPing( detail::PingInfo(msg.clientTime_) ); + } + void ClientTimeService::onPong(const PeerId pId, const NetEvent& evt, const ChannelId cId) + { + COUTLN("client-time: received PONG with cId='" << int(cId) << "'"); + + const s2cEvtPong& msg = static_cast<const s2cEvtPong&>(evt); + + // aka getClientTime() + const double timerVal = timer_.getTime(); + const double currTime = timerVal + clockDelta_; + + const uint32 currTimeMs = uint32(1000. * currTime); + + // recalc RTT + rttCalc_.processPong( currTimeMs, msg.clientTime_ ); + COUTLN("client-time: RTT=" << rttCalc_.getMeanRtt() << " over " << int(rttCalc_.sizeReceivedPings()) << " samples"); + + // adjust clock + if (rttCalc_.getMeanRtt() > 0.) + { + //COUTLN("current clock=" << (timerVal+clockDelta_) << " clockdelta=" << clockDelta_); + const double halfLatency = 0.001 * .5 * rttCalc_.getMeanRtt(); + const double serverTime = 0.001 * double(msg.serverTime2_); // in sec + const double deltaToServer = serverTime - currTime + halfLatency; + clockDelta_ += deltaToServer; // @todo use a factor? (e.g. 0.6) + COUTLN("server t1=" << msg.serverTime_ << " t2=" << msg.serverTime2_); + //COUTLN("client sent=" << msg.clientTime_ << " curr(ms)=" << currTimeMs); + COUTLN("current clock=" << (timerVal+clockDelta_) << " clockdelta=" << clockDelta_); + COUTLN("deltaToServer=" << deltaToServer); + } + } + double ClientTimeService::getClientTime() const + { + return (timer_.getTime() + clockDelta_); + } + +} // namespace net +} // namespace yake Added: trunk/yake/src/yake/netsvc/service/netServerCommService.cpp =================================================================== --- trunk/yake/src/yake/netsvc/service/netServerCommService.cpp (rev 0) +++ trunk/yake/src/yake/netsvc/service/netServerCommService.cpp 2006-12-03 23:51:16 UTC (rev 1513) @@ -0,0 +1,145 @@ +#include <yake/netsvc/pch.h> +#include <boost/lexical_cast.hpp> +#include <yake/netsvc/netService.h> +#include <yake/netsvc/netServiceHost.h> +#include <yake/netsvc/service/netServerCommService.h> +#include <yake/netsvc/service/netCommServiceMessages.h> + +namespace yake { +namespace net { + + ServerCommService::ServerCommService(const ChannelId cId) : commChannelId_(cId) + { + } + void ServerCommService::onStart(IServiceHost& host) + { + COUTLN("starting comm service"); + 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)); + } + void ServerCommService::onStop(IServiceHost&) + { + COUTLN("stopping comm service"); + } + void ServerCommService::onClientConnected(const PeerId pId) + { + s2cEvtCommMsg msg("#server","server","you","client joined"); + evtConn_->sendEvent(msg, SendOptions().channel(commChannelId_)); + } + void ServerCommService::onClientDisconnected(const PeerId pId) + { + COUTLN("server-comm: user '" << pId << "' disconnected."); + + // remove user from all channels + YAKE_FOR_EACH(ChannelList::iterator,itChannel,channels_) + { + itChannel->second.users_.erase( pId ); + } + } + void ServerCommService::createChannel(const String& name, const String& description) + { + if (channels_.find( name ) != channels_.end()) + YAKE_EXCEPT("channel with this name already exists"); + channels_[ name ].description_ = description; + COUTLN("server-comm: channel '" << name << "' created."); + } + void ServerCommService::destroyChannel(const String& name) + { + ChannelList::iterator it = channels_.find( name ); + if (it != channels_.end()) + { + YAKE_FOR_EACH(UserList::const_iterator,itUser,it->second.users_) + { + s2cEvtCommLeaveChannel msg(it->first,"Channel destroyed."); + evtConn_->sendEvent(*itUser, msg, SendOptions().channel(commChannelId_)); + } + channels_.erase( it ); + } + } + void ServerCommService::onProcessJoinRequest(const PeerId pId, const NetEvent& evt, const ChannelId) + { + const c2sEvtCommJoinChannel& msg = static_cast<const c2sEvtCommJoinChannel&>(evt); + COUTLN("server-comm: user " << int(pId) << " likes to join '" << msg.cId_ << "'"); + + ChannelList::iterator itC = channels_.find( msg.cId_ ); + if (itC == channels_.end()) + { + //@todo reply + s2cEvtCommMsg reply("#server","server","user", + "Channel '" + msg.cId_ + "' does not exist.\n"); + evtConn_->sendEvent(pId, reply, SendOptions().channel(commChannelId_)); + } + else + { + // + itC->second.users_.insert( pId ); + + // + s2cEvtCommMsg reply(msg.cId_,"server","user", + "Welcome to channel '" + msg.cId_ + "'.\n" + itC->second.description_+"\n"); + evtConn_->sendEvent(pId, reply, SendOptions().channel(commChannelId_)); + } + } + void ServerCommService::onProcessMsg(const PeerId pId, const NetEvent& evt, const ChannelId) + { + const s2cEvtCommMsg& msg = static_cast<const s2cEvtCommMsg&>(evt); + COUTLN("server-comm: received: pId=" << int(pId) + << " cId=" << msg.cId_ << " from=" << msg.from_ << " to=" << msg.to_ << " text=" << msg.msg_); + + // special command channel: + + if (msg.cId_ == "$svc:comm") + { + Vector<String> cmd = split<String>(msg.msg_," "); + YAKE_ASSERT( !cmd.empty() ).warning("can't do much with an empty command."); + if (cmd.empty()) + return; + if (cmd.at(0) == "createchannel") + { + YAKE_ASSERT( cmd.size() == 2 || cmd.size() == 3 )(cmd).warning("malformed command."); + if (cmd.size() >= 2) + { + this->createChannel( cmd.at(1), (cmd.size()>2) ? cmd.at(2) : "" ); + } + } + return; + } + + + // normal channel: + + ChannelList::iterator itC = channels_.find( msg.cId_ ); + if (itC == channels_.end()) + { + //@todo reply + s2cEvtCommMsg reply("#server","server","user", + "Channel '" + msg.cId_ + "' does not exist.\n"); + evtConn_->sendEvent(pId, reply, SendOptions().channel(commChannelId_)); + } + else + { + // forward to clients except pId: + // NB @todo It may be beneficial to send the message to the originating user, too. + // This can improve the order of the messages client-side. + s2cEvtCommMsg fwdMsg( msg.cId_, msg.from_, msg.to_, msg.msg_ ); + fwdMsg.from_ = boost::lexical_cast<String>( pId ); + YAKE_FOR_EACH(UserList::const_iterator,itUser,itC->second.users_) + { + if (*itUser != pId) + { + evtConn_->sendEvent( *itUser, fwdMsg, SendOptions().channel(commChannelId_)); + } + } + } + } + +} // namespace net +} // namespace yake Added: trunk/yake/src/yake/netsvc/service/netServerTimeService.cpp =================================================================== --- trunk/yake/src/yake/netsvc/service/netServerTimeService.cpp (rev 0) +++ trunk/yake/src/yake/netsvc/service/netServerTimeService.cpp 2006-12-03 23:51:16 UTC (rev 1513) @@ -0,0 +1,130 @@ +#include <yake/netsvc/pch.h> +#include <yake/netsvc/netService.h> +#include <yake/netsvc/netServiceHost.h> +#include <yake/netsvc/service/netServerTimeService.h> +#include <yake/netsvc/service/netTimeServiceMessages.h> + +namespace yake { +namespace net { + + ServerTimeService::ServerTimeService(const ChannelId cId) : timeChannelId_(cId) + { + } + void ServerTimeService::onStart(IServiceHost& host) + { + COUTLN("starting time service"); + evtConn_ = host.getEventConnection(); + + evtConn_->registerEvent( s2cEvtPing::ID, NetEvent::DIR_ANY, s2cEvtPing::create, s2cEvtPing::destroy ); + evtConn_->registerEvent( c2sEvtPong::ID, NetEvent::DIR_ANY, c2sEvtPong::create, c2sEvtPong::destroy ); + evtConn_->registerEvent( s2cEvtPong::ID, NetEvent::DIR_ANY, s2cEvtPong::create, s2cEvtPong::destroy ); + + host.subscribeToNetEvent( c2sEvtPong::ID, timeChannelId_, + boost::bind(&ServerTimeService::onPong,this,_1,_2,_3)); + + timer_.start(); + } + void ServerTimeService::onStop(IServiceHost&) + { + COUTLN("stopping time service"); + timer_.stop(); + timer_.reset(); + } + void ServerTimeService::onClientConnected(const PeerId pId) + { + s2cEvtPing msg; + msg.serverTime_ = uint32( timer_.getTime() * 1000. ); // send ms + evtConn_->sendEvent(msg, SendOptions().channel(timeChannelId_).unreliable().unordered()); + + users_[pId].addSentPing( detail::PingInfo(msg.serverTime_) ); + } + void ServerTimeService::onClientDisconnected(const PeerId pId) + { + COUTLN("server-time: user '" << pId << "' disconnected."); + + users_.erase( pId ); + } + void ServerTimeService::update() + { + const double time = timer_.getTime(); + const double elapsed = time - lastTime_; + if (elapsed >= 1.) + { + lastTime_ = time; + + if (users_.empty()) + return; + + const uint32 timeMs = uint32(1000. * time); + + // for each user/client + YAKE_FOR_EACH(UserList::iterator,itUser,users_) + { + // for each sent ping: check whether pings timed out + for(detail::PeerRttCalculator::const_pinginfo_iterator itPing = itUser->second.beginSentPings(); + itPing != itUser->second.endSentPings(); ++itPing) + { + // last ping not answered yet within the last 0.9 seconds? + const double timeSinceSent = (timeMs - itPing->timeSent_); // in ms + if (timeSinceSent > 950) + { + //@todo force recalc of RTT + COUTLN("server-time: client timed out?"); + //itUser->second.processPong( timeMs, + // itPing->timeSent_ - itUser->second.meanRtt_ * 2 ); + //COUTLN("server-time: new RTT = " << itUser->second.meanRtt_); + } + } + // clear list and add new ping info + itUser->second.clearSentPings(); + itUser->second.addSentPing( detail::PingInfo(timeMs) ); + } + + // just broadcast + s2cEvtPing msg; + msg.serverTime_ = timeMs; + evtConn_->sendEvent(msg, SendOptions().channel(timeChannelId_).unreliable().unordered()); + } + } + void ServerTimeService::onPong(const PeerId pId, const NetEvent& evt, const ChannelId) + { + //@todo handle bad cast! + const c2sEvtPong& msg = static_cast<const c2sEvtPong&>(evt); + COUTLN("server-time: user " << int(pId) << " pong'd with '" << msg.serverTime_ << "'"); + + const uint32 timeMs = uint32(1000. * timer_.getTime()); + + // answer with another pong: let's the client to time sync'ing, too. + { + s2cEvtPong pong; + pong.serverTime_ = msg.serverTime_; + pong.clientTime_ = msg.clientTime_; + pong.serverTime2_ = timeMs; + evtConn_->sendEvent(pId, pong, SendOptions().channel(timeChannelId_).unreliable().unordered()); + } + + // find user + UserList::iterator itUser = users_.find(pId); + YAKE_ASSERT( itUser != users_.end() ).warning("recv'd PONG from unknown peer."); + if (itUser == users_.end()) + return; + detail::PeerRttCalculator& peerInfo = itUser->second; + + // + if (!peerInfo.processPong(timeMs,msg.serverTime_)) + { + COUTLN("server-time: could not handle PONG.\n"); + return; + } + COUTLN("server-time: client '" << pId << "' RTT=" << peerInfo.getMeanRtt() + << " over " << int(peerInfo.sizeReceivedPings()) << " samples"); + for(detail::PeerRttCalculator::const_pinginfo_iterator pi = peerInfo.beginReceivedPings(); + pi != peerInfo.endReceivedPings(); ++pi) + { + std::cout << pi->rtt_ << " "; + } + std::cout << "\n"; + } + +} // namespace net +} // namespace yake Modified: trunk/yake/src/yake/samples/net/roclient/ROClient.cpp =================================================================== --- trunk/yake/src/yake/samples/net/roclient/ROClient.cpp 2006-12-03 00:46:45 UTC (rev 1512) +++ trunk/yake/src/yake/samples/net/roclient/ROClient.cpp 2006-12-03 23:51:16 UTC (rev 1513) @@ -4,7 +4,6 @@ #include <yake/ent/ent.h> #include <yake/net/net.h> #include <yake/samples/net/common/common.h> -#include <yake/samples/net/common/commonEvents.h> #include <yake/samples/net/roclient/ROClient.h> namespace yake { Modified: trunk/yake/src/yake/samples/net/roserver/ROServer.cpp =================================================================== --- trunk/yake/src/yake/samples/net/roserver/ROServer.cpp 2006-12-03 00:46:45 UTC (rev 1512) +++ trunk/yake/src/yake/samples/net/roserver/ROServer.cpp 2006-12-03 23:51:16 UTC (rev 1513) @@ -3,187 +3,11 @@ #include <yake/ent/ent.h> #include <yake/net/net.h> #include <yake/samples/net/common/common.h> -#include <yake/samples/net/common/commonEvents.h> #include <yake/samples/net/roserver/ROServer.h> namespace yake { namespace ro { //----------------------------------------------------------------------------- - IServiceHost::IServiceHost() : running_(false) - { - } - bool IServiceHost::running() const - { - boost::mutex::scoped_lock lck(runningMtx_); - return running_; - } - bool IServiceHost::start() - { - bool succ = this->onStart(); - if (!succ) - return false; - - { - boost::mutex::scoped_lock lck(runningMtx_); - running_ = true; - } - - // start services - YAKE_FOR_EACH(detail::ServiceManager::const_service_iterator,it,serviceMgr_) - { - (*it)->onStart(*this); - } - - return true; - } - void IServiceHost::stop() - { - { - boost::mutex::scoped_lock lck(runningMtx_); - running_ = false; - } - - // stop services - YAKE_FOR_EACH(detail::ServiceManager::const_service_iterator,it,serviceMgr_) - { - (*it)->onStop(*this); - } - - // stop the rest - this->onStop(); - } - void IServiceHost::addService(IServicePtr service, const std::string& tag) - { - serviceMgr_.addService( service, tag ); - if (this->running()) - service->onStart(*this); - } - void IServiceHost::removeAllServices() - { - serviceMgr_.removeAllServices(); - } - IServicePtr IServiceHost::removeService(const std::string & tag) - { - IServicePtr service = serviceMgr_.removeService( tag ); - if (service && this->running()) - service->onStop(*this); - return service; - } - IServicePtr IServiceHost::removeService(IServicePtr service) - { - serviceMgr_.removeService( service ); - if (service && this->running()) - service->onStop(*this); - return service; - } - IServicePtr IServiceHost::getService(const std::string& tag) const - { - return serviceMgr_.getService( tag ); - } - void IServiceHost::dispatchNetEvent(const net::PeerId pId, const net::NetEvent& evt, const net::ChannelId cId) - { - // find catch-all for this channel (ignore event id) - { - SigMap::const_iterator it = sigMap_.find( ChannelEventIdPair(cId,net::NetEvent::EVTID_NONE) ); - if (it != sigMap_.end()) - (*it->second)(pId,evt,cId); - } - - // find signal for this channel and event id: - SigMap::const_iterator it = sigMap_.find( ChannelEventIdPair(cId,evt.id()) ); - if (it == sigMap_.end()) - return; - (*it->second)(pId,evt,cId); - } - SignalConnection IServiceHost::subscribeToNetEvent( - const net::NetEvent::id_type eId, const net::ChannelId cId, const EvtProcessEventFn& fn) - { - const ChannelEventIdPair idPair(cId,eId); - - SigMap::iterator it = sigMap_.find( idPair ); - if (it == sigMap_.end()) - { - ProcessEventSigPtr sig( new ProcessEventSig() ); - sigMap_[ idPair ] = sig; - return sig->connect( fn ); - } - return it->second->connect(fn); - } - SignalConnection IServiceHost::subscribeToNetEventChannel( - const net::ChannelId cId, const EvtProcessEventFn& fn) - { - const ChannelEventIdPair idPair(cId,net::NetEvent::EVTID_NONE); - - SigMap::iterator it = sigMap_.find( idPair ); - if (it == sigMap_.end()) - { - ProcessEventSigPtr sig( new ProcessEventSig() ); - sigMap_[ idPair ] = sig; - return sig->connect( fn ); - } - return it->second->connect(fn); - } - - //----------------------------------------------------------------------------- - namespace detail { - - void ServiceManager::addService(IServicePtr service, const std::string& tag) - { - YAKE_ASSERT( service ); - if (!service) - return; - - services_.insert( service ); - if (!tag.empty()) - { - YAKE_ASSERT( tag2service_.find(tag) == tag2service_.end() ).debug("duplicate tag!"); - tag2service_[ tag ] = service; - } - } - IServicePtr ServiceManager::getService(const std::string& tag) const - { - TagMap::const_iterator itFind = tag2service_.find(tag); - return (itFind == tag2service_.end() ? IServicePtr() : itFind->second); - } - IServicePtr ServiceManager::removeService(const std::string& tag) - { - TagMap::iterator itFind = tag2service_.find(tag); - if (itFind == tag2service_.end()) - return IServicePtr(); - IServicePtr service = itFind->second; - tag2service_.erase( itFind ); - services_.erase( service ); - return service; - } - IServicePtr ServiceManager::removeService(const IServicePtr service) - { - YAKE_FOR_EACH(TagMap::iterator,itFind,tag2service_) - { - if (itFind->second == service) - { - tag2service_.erase( itFind ); - break; - } - } - services_.erase( service ); - return service; - } - void ServiceManager::removeAllServices() - { - tag2service_.clear(); - services_.clear(); - } - ServiceManager::const_service_iterator ServiceManager::begin() const - { - return services_.begin(); - } - ServiceManager::const_service_iterator ServiceManager::end() const - { - return services_.end(); - } - - } // namespace detail - //----------------------------------------------------------------------------- namespace server_impl { class client : public server::iclient { @@ -277,7 +101,7 @@ } void server::onClientSimStarted(iclient&c) { - sigClientSimulationStarted_(c); + sigClientSimulationStarted_(c.getPeerId()); } void server::setClassTableMessage(const s2cEvtClassTable& msg) { @@ -404,7 +228,7 @@ YAKE_ASSERT(it != this->clients_.end())(pId).warning("unknown client disconnected. lookup failed."); if (it == this->clients_.end()) return; - this->sigClientDisconnected_( *it->second ); + this->sigClientDisconnected_( (*it->second).getPeerId() ); this->clients_.erase( it ); } //----------------------------------------------------------------------------- Added: trunk/yake/yake/netsvc/detail/netPeerRttCalculator.h =================================================================== --- trunk/yake/yake/netsvc/detail/netPeerRttCalculator.h (rev 0) +++ trunk/yake/yake/netsvc/detail/netPeerRttCalculator.h 2006-12-03 23:51:16 UTC (rev 1513) @@ -0,0 +1,66 @@ +#ifndef YAKE_NETSVC_PEERRTTCALCULATOR_H +#define YAKE_NETSVC_PEERRTTCALCULATOR_H + +#include <yake/netsvc/netPrerequisites.h> + +#pragma warning(push) +#pragma warning(disable: 4275) // C4275: non dll-interface class 'X' used as base for dll-interface 'Y' + +namespace yake { +namespace net { +namespace detail { + + struct NETSVC_API PingInfo + { + uint32 timeSent_; // in ms + uint32 timeRecvd_; // in ms + double rtt_; // in ms + PingInfo(const uint32 timeSent = 0): timeSent_(timeSent), timeRecvd_(0), rtt_(0) + {} + bool operator < (const PingInfo& rhs) const + { + return (timeSent_ < rhs.timeSent_); + } + }; + struct NETSVC_API is_time_sent : public std::unary_function<const PingInfo&,bool> + { + is_time_sent(const uint32 x) : x_(x) {} + bool operator()(const PingInfo& lhs) const + { + return (lhs.timeSent_ == x_); + } + uint32 x_; + }; + typedef std::list<PingInfo> PingInfoList;; + struct PeerRttCalculator + { + PeerRttCalculator() : meanRtt_(-1.) + {} + /** Also recalculates mean RTT. */ + bool processPong(const uint32 currTimeMs, const yake::uint32 origTime); + void addSentPing(const PingInfo&); + void addReceivedPing(const PingInfo&); + + typedef PingInfoList::const_iterator const_pinginfo_iterator; + const_pinginfo_iterator beginReceivedPings() const; + const_pinginfo_iterator endReceivedPings() const; + const_pinginfo_iterator beginSentPings() const; + const_pinginfo_iterator endSentPings() const; + size_t sizeReceivedPings() const; + size_t sizeSentPings() const; + void clearSentPings(); + + double getMeanRtt() const; + private: + PingInfoList receivedPings_; + PingInfoList sentPings_; + double meanRtt_; + }; + +} // namespace detail +} // namespace net +} // namespace yake + +#pragma warning(pop) + +#endif Modified: trunk/yake/yake/netsvc/netPrerequisites.h =================================================================== --- trunk/yake/yake/netsvc/netPrerequisites.h 2006-12-03 00:46:45 UTC (rev 1512) +++ trunk/yake/yake/netsvc/netPrerequisites.h 2006-12-03 23:51:16 UTC (rev 1513) @@ -26,5 +26,123 @@ # endif #endif +/** @todo move out */ +#define DECLARE_EVENT(CLASS,IDVALUE) \ +public: \ +static ::yake::net::NetEvent* create(::yake::net::NetEvent::id_type id) \ +{ CLASS* p = new CLASS(); p->setId(id); return p; } \ +static void destroy(::yake::net::NetEvent* p) { delete p; } \ +static const ::yake::net::NetEvent::id_type ID = IDVALUE; \ +CLASS() : ::yake::net::NetEvent(ID) \ +{} + +/** @todo replace with real logging */ +#define COUTLN(X) \ +{ \ + std::stringstream ss; \ + ss << X << "\n"; \ + std::cout << ss.str(); \ +} + +/** @todo move the streaming operators */ +namespace yake { +namespace net { + + inline yake::net::ibitstream& operator >> (yake::net::ibitstream& in, yake::uint8& rhs) + { + in.read( rhs ); + return in; + } + inline yake::net::obitstream& operator << (yake::net::obitstream& out, const yake::uint8 rhs) + { + out.write( rhs ); + return out; + } + inline yake::net::ibitstream& operator >> (yake::net::ibitstream& in, yake::uint16& rhs) + { + in.read( rhs ); + return in; + } + inline yake::net::obitstream& operator << (yake::net::obitstream& out, const yake::uint16 rhs) + { + out.write( rhs ); + return out; + } + inline yake::net::ibitstream& operator >> (yake::net::ibitstream& in, yake::uint32& rhs) + { + in.read( rhs ); + return in; + } + inline yake::net::obitstream& operator << (yake::net::obitstream& out, const yake::uint32 rhs) + { + out.write( rhs ); + return out; + } + inline yake::net::ibitstream& operator >> (yake::net::ibitstream& in, int& rhs) + { + in.read( rhs ); + return in; + } + inline yake::net::obitstream& operator << (yake::net::obitstream& out, const int rhs) + { + out.write( rhs ); + return out; + } + + inline yake::net::obitstream& operator << (yake::net::obitstream& out, const std::string& rhs) + { + out.write(int(rhs.length())); + if (!rhs.empty()) + out.write( rhs.c_str(), (rhs.size()*sizeof(std::string::value_type)*8) ); + return out; + } + inline yake::net::ibitstream& operator >> (yake::net::ibitstream& in, std::string& rhs) + { + int len = 0; + in.read(len); + assert(len < 10000); // enforce upper limit + rhs.clear(); + rhs.reserve(len); + while (len>0) + { + char c = 0; + in.read(c); + rhs += c; + len--; + } + return in; + } + + template<typename _Ty, typename _Pr, typename _Alloc> + inline yake::net::obitstream& operator << (yake::net::obitstream& out, const std::map<_Ty,_Pr,_Alloc>& ctr) + { + out.write(yake::uint32(ctr.size())); + typedef std::map<_Ty,_Pr,_Alloc> map_type; + typedef typename map_type::const_iterator iter_type; + YAKE_FOR_EACH(iter_type,it,ctr) + out << it->first << it->second; + return out; + } + template<typename _Ty, typename _Pr, typename _Alloc> + inline yake::net::ibitstream& operator >> (yake::net::ibitstream& in, std::map<_Ty,_Pr,_Alloc>& ctr) + { + ctr.clear(); + yake::uint32 count = 0; + in.read(count); + //@todo safe-guard count + typedef std::map<_Ty,_Pr,_Alloc> map_type; + typedef typename map_type::const_iterator iter_type; + for (size_t i=0; i<count; ++i) + { + std::pair<_Ty,_Pr> data; + in >> data.first; + in >> data.second; + ctr.insert( data ); + } + return in; + } +} // namespace net +} // namespace yake + #endif Modified: trunk/yake/yake/netsvc/netService.h =================================================================== --- trunk/yake/yake/netsvc/netService.h 2006-12-03 00:46:45 UTC (rev 1512) +++ trunk/yake/yake/netsvc/netService.h 2006-12-03 23:51:16 UTC (rev 1513) @@ -1,8 +1,7 @@ #ifndef YAKE_NETSVC_SERVICE_H #define YAKE_NETSVC_SERVICE_H -#include "netPrerequisites.h" -//#include "netCommon.h" +#include <yake/netsvc/netPrerequisites.h> #pragma warning(push) #pragma warning(disable: 4275) // C4275: non dll-interface class 'X' used as base for dll-interface 'Y' Modified: trunk/yake/yake/netsvc/netServiceHost.h =================================================================== --- trunk/yake/yake/netsvc/netServiceHost.h 2006-12-03 00:46:45 UTC (rev 1512) +++ trunk/yake/yake/netsvc/netServiceHost.h 2006-12-03 23:51:16 UTC (rev 1513) @@ -2,8 +2,8 @@ #define YAKE_NETSVC_SERVICEHOST_H #include <boost/thread/mutex.hpp> -#include "netPrerequisites.h" -#include "netService.h" +#include <yake/netsvc/netPrerequisites.h> +#include <yake/netsvc/netService.h> #pragma warning(push) #pragma warning(disable: 4275) // C4275: non dll-interface class 'X' used as base for dll-interface 'Y' Modified: trunk/yake/yake/netsvc/netSvc.h =================================================================== --- trunk/yake/yake/netsvc/netSvc.h 2006-12-03 00:46:45 UTC (rev 1512) +++ trunk/yake/yake/netsvc/netSvc.h 2006-12-03 23:51:16 UTC (rev 1513) @@ -1,151 +1,14 @@ #ifndef YAKE_NETSVC_H #define YAKE_NETSVC_H -#include "netPrerequisites.h" -//#include "netCommon.h" +#include <yake/netsvc/netPrerequisites.h> +#include <yake/netsvc/netService.h> +#include <yake/netsvc/netServiceHost.h> namespace yake { namespace net { - struct IServiceHost; - /** Represents a service that can be plugged added to and managed by an IServiceHost. - */ - struct IService : public boost::noncopyable - { - virtual ~IService() {} - /** Callback is triggered when the service should start and - has to be overridden by derived classes. - @note An IServiceHost may decide to start and stop services - under various circumstances. - */ - virtual void onStart(IServiceHost&) = 0; - /** Callback is triggered when the service should stop and - has to be overridden by derived classes. - @note An IServiceHost may decide to start and stop services - under various circumstances. - */ - virtual void onStop(IServiceHost&) = 0; - }; - /** Shared pointer managing an IService pointer. */ - typedef SharedPtr<IService> IServicePtr; - - namespace detail { - /** Implementation specific object managing - a number of services. - @todo Move into private area (i.e. where library users cannot see it). - */ - struct ServiceManager : public boost::noncopyable - { - void addService(IServicePtr, const std::string& tag = ""); - IServicePtr removeService(IServicePtr); - IServicePtr removeService(const std::string&); - void removeAllServices(); - IServicePtr getService(const std::string& tag) const; - private: - typedef std::set<IServicePtr> ServiceList; - public: - typedef ServiceList::const_iterator const_service_iterator; - const_service_iterator begin() const; - const_service_iterator end() const; - private: - typedef std::map<std::string,IServicePtr> TagMap; - TagMap tag2service_; - ServiceList services_; - }; - } // namespace detail - typedef SharedPtr<net::INetEventConnection> NetEventConnectionPtr; - /** Base class for objects that have control over packet and event connections - and manage a number of attachable services. - */ - struct IServiceHost : public boost::noncopyable - { - protected: - IServiceHost(); - public: - virtual ~IServiceHost() {} - - /** Start the IServiceHost and all registered services. - @note Services can be added after the IServiceHost has been started. - */ - bool start(); - /** Stop the IServiceHost and all registered services. - */ - void stop(); - - virtual NetEventConnectionPtr getEventConnection() const = 0; - //virtual net::IPacketConnection* getPacketConnection() const = 0; - //virtual net::IClientPacketConnection* getClientPacketConnection() const = 0; - //virtual net::IServerPacketConnection* getServerPacketConnection() const = 0; - - // mirror detail::ServiceManager interface (internally forwarded) - - /** Adds a service to the host. The host takes control over - starting and stopping the service. - @note The service should not have been started when it is passed to addService()! - @remarks Services can be added before or after starting the IServiceHost. - If an IService is added before start() has been called, then its onStart() - callback will be called when start() is finally called. - If an IService is added after start() has been called, then its onStart() - callback will be immediately called from within the addService() method. - */ - void addService(IServicePtr, const std::string& tag = ""); - /** Removes the given service. - @note The service is stopped if it's running. - */ - IServicePtr removeService(IServicePtr); - /** Removes the service identified by the given tag. - @note The service is stopped if it's running. - */ - IServicePtr removeService(const std::string&); - /** Removes all services. - @note Services are stopped if they're running. - */ - void removeAllServices(); - /** Returns a pointer to the service identified by the given tag. - */ - IServicePtr getService(const std::string& tag) const; - - typedef net::INetEventConnection::EvtProcessEventFn EvtProcessEventFn; - /** Use this method to subscribe to certain net events on a specific channel. - */ - SignalConnection subscribeToNetEvent( - const net::NetEvent::id_type, const net::ChannelId, const EvtProcessEventFn& fn); - - /** Use this method to subscribe to all net events on a specific channel. - */ - SignalConnection subscribeToNetEventChannel( - const net::ChannelId, const EvtProcessEventFn& fn); - private: - virtual bool onStart() = 0; - virtual void onStop() = 0; - protected: - /** Returns true if the IServiceHost has been started, otherwise false. - */ - bool running() const; - /** Dispatches received net events to registered listeners. - @see subscribeToNetEvent - @see subscribeToNetEventChannel - */ - void dispatchNetEvent(const net::PeerId, const net::NetEvent&, const net::ChannelId); - private: - detail::ServiceManager serviceMgr_; - volatile bool running_; - mutable boost::mutex runningMtx_; - - typedef SignalX<void(const net::PeerId, const net::NetEvent&, const net::ChannelId)> ProcessEventSig; - typedef SharedPtr<ProcessEventSig> ProcessEventSigPtr; - - typedef std::pair<net::ChannelId,net::NetEvent::id_type> ChannelEventIdPair; - typedef std::map<ChannelEventIdPair,ProcessEventSigPtr> SigMap; - - struct EventIdEntry - { - ProcessEventSigPtr sig_; - }; - SigMap sigMap_; - }; - } // namespace net } // namespace yake Added: trunk/yake/yake/netsvc/service/netClientCommService.h =================================================================== --- trunk/yake/yake/netsvc/service/netClientCommService.h (rev 0) +++ trunk/yake/yake/netsvc/service/netClientCommService.h 2006-12-03 23:51:16 UTC (rev 1513) @@ -0,0 +1,60 @@ +#ifndef YAKE_NETSVC_CLIENTCOMMSERVICE_H +#define YAKE_NETSVC_CLIENTCOMMSERVICE_H + +#include <yake/netsvc/netPrerequisites.h> +#include <yake/netsvc/netService.h> + +#pragma warning(push) +#pragma warning(disable: 4275) // C4275: non dll-interface class 'X' used as base for dll-interface 'Y' + +namespace yake { +namespace net { + + struct NETSVC_API ClientCommService : public IService + { + ClientCommService(const ChannelId); + virtual void onStart(IServiceHost&); + virtual void onStop(IServiceHost&); + /** Sends message to server with the request to join the channel specified by cId. + @note This function just queues the message. It does not wait for the response. + Neither does it make sure the message is really sent (use net::update()). + */ + void joinChannel(const String& cId); + void sendMessageToChannel(const String& cId, const String& msg); + private: + struct MsgEntry + { + String from_; + String msg_; + MsgEntry(const String& from = "", const String& msg = "") : from_(from), msg_(msg) + {} + }; + typedef std::deque<MsgEntry> MsgList; + public: + typedef MsgList::const_iterator const_message_iterator; + public: + bool hasMessages(const String& cId) const; + void clearMessages(const String& cId); + /** May throw if cId does not exist! */ + const_message_iterator beginMessages(const String& cId) const; + /** May throw if cId does not exist! */ + const_message_iterator endMessages(const String& cId) const; + private: + void onProcessMsg(const PeerId pId, const NetEvent& evt, const ChannelId); + private: + NetEventConnectionPtr evtConn_; + struct ChannelEntry + { + MsgList outstandingMessages_; + }; + typedef std::map<String,ChannelEntry> ChannelList; + ChannelList activeChannels_; + ChannelId commChannelId_; + }; + +} // namespace net +} // namespace yake + +#pragma warning(pop) + +#endif Added: trunk/yake/yake/netsvc/service/netClientTimeService.h =================================================================== --- trunk/yake/yake/netsvc/service/netClientTimeService.h (rev 0) +++ trunk/yake/yake/netsvc/service/netClientTimeService.h 2006-12-03 23:51:16 UTC (rev 1513) @@ -0,0 +1,37 @@ +#ifndef YAKE_NETSVC_CLIENTTIMESERVICE_H +#define YAKE_NETSVC_CLIENTTIMESERVICE_H + +#include <yake/netsvc/netPrerequisites.h> +#include <yake/netsvc/netService.h> +#include <yake/netsvc/detail/netPeerRttCalculator.h> + +#pragma warning(push) +#pragma warning(disable: 4275) // C4275: non dll-interface class 'X' used as base for dll-interface 'Y' + +namespace yake { +namespace net { + + struct NETSVC_API ClientTimeService : public IService + { + ClientTimeService(const ChannelId); + virtual void onStart(IServiceHost&); + virtual void onStop(IServiceHost&); + private: + void onPing(const PeerId pId, const NetEvent& evt, const ChannelId cId); + void onPong(const PeerId pId, const NetEvent& evt, const ChannelId cId); + double getClientTime() const; + private: + ChannelId timeChannelId_; + NetEventConnectionPtr evtConn_; + Timer timer_; //@todo replace + bool firstTime_; + detail::PeerRttCalculator rttCalc_; + double clockDelta_; + }; + +} // namespace net +} // namespace yake + +#pragma warning(pop) + +#endif Added: trunk/yake/yake/netsvc/service/netCommServiceMessages.h =================================================================== --- trunk/yake/yake/netsvc/service/netCommServiceMessages.h (rev 0) +++ trunk/yake/yake/netsvc/service/netCommServiceMessages.h 2006-12-03 23:51:16 UTC (rev 1513) @@ -0,0 +1,78 @@ +#ifndef YAKE_NETSVC_COMMSERVICEMESSAGES_H +#define YAKE_NETSVC_COMMSERVICEMESSAGES_H + +#include <yake/netsvc/netPrerequisites.h> + +#pragma warning(push) +#pragma warning(disable: 4275) // C4275: non dll-interface class 'X' used as base for dll-interface 'Y' + +namespace yake { +namespace net { +//namespace svc { +//namespace comm { + + struct s2cEvtCommMsg : public yake::net::NetEvent + { + DECLARE_EVENT( s2cEvtCommMsg, 30 ); + s2cEvtCommMsg(const std::string& cId, const std::string& from, const std::string& to, const std::string& msg) : + yake::net::NetEvent(ID), cId_(cId), msg_(msg), from_(from), to_(to) + {} + virtual bool pack(yake::net::obitstream& out) const + { + out << cId_ << from_ << to_ << msg_; + return true; + } + virtual bool unpack(yake::net::ibitstream& in) + { + in >> cId_ >> from_ >> to_ >> msg_; + return true; + } + std::string cId_; + std::string msg_; + std::string from_; + std::string to_; + }; + struct s2cEvtCommLeaveChannel : public yake::net::NetEvent + { + DECLARE_EVENT( s2cEvtCommLeaveChannel, 31 ); + s2cEvtCommLeaveChannel(const std::string& cId, const std::string& reason) : yake::net::NetEvent(ID), cId_(cId), reason_(reason) + {} + virtual bool pack(yake::net::obitstream& out) const + { + out << cId_ << reason_; + return true; + } + virtual bool unpack(yake::net::ibitstream& in) + { + in >> cId_ >> reason_; + return true; + } + std::string cId_; + std::string reason_; + }; + struct c2sEvtCommJoinChannel : public yake::net::NetEvent + { + DECLARE_EVENT( c2sEvtCommJoinChannel, 32 ); + c2sEvtCommJoinChannel(const std::string& cId) : yake::net::NetEvent(ID), cId_(cId) + {} + virtual bool pack(yake::net::obitstream& out) const + { + out << cId_; + return true; + } + virtual bool unpack(yake::net::ibitstream& in) + { + in >> cId_; + return true; + } + std::string cId_; + }; + +//} // namespace comm +//} // namespace svc +} // namespace net +} // namespace yake + +#pragma warning(pop) + +#endif Added: trunk/yake/yake/netsvc/service/netServerCommService.h =================================================================== --- trunk/yake/yake/netsvc/service/netServerCommService.h (rev 0) +++ trunk/yake/yake/netsvc/service/netServerCommService.h 2006-12-03 23:51:16 UTC (rev 1513) @@ -0,0 +1,44 @@ +#ifndef YAKE_NETSVC_SERVERCOMMSERVICE_H +#define YAKE_NETSVC_SERVERCOMMSERVICE_H + +#include <yake/netsvc/netPrerequisites.h> +#include <yake/netsvc/netService.h> + +#pragma warning(push) +#pragma warning(disable: 4275) // C4275: non dll-interface class 'X' used as base for dll-interface 'Y' + +namespace yake { +namespace net { + + struct NETSVC_API ServerCommService : public IService + { + ServerCommService(const ChannelId); + virtual void onStart(IServiceHost&); + virtual void onStop(IServiceHost&); + void onClientConnected(const PeerId); + void onClientDisconnected(const PeerId); + void createChannel(const String& name, const String& description); + void destroyChannel(const String& name); + private: + void onProcessJoinRequest(const PeerId pId, const NetEvent& evt, const ChannelId); + void onProcessMsg(const PeerId pId, const NetEvent& evt, const ChannelId); + private: + ChannelId commChannelId_; + NetEventConnectionPtr evtConn_; + + typedef std::set<PeerId> UserList; + struct ChannelEntry + { + String description_; + UserList users_; + }; + typedef std::map<String,ChannelEntry> ChannelList; + ChannelList channels_; + }; + +} // namespace net +} // namespace yake + +#pragma warning(pop) + +#endif Added: trunk/yake/yake/netsvc/service/netServerTimeService.h =================================================================== --- trunk/yake/yake/netsvc/service/netServerTimeService.h (rev 0) +++ trunk/yake/yake/netsvc/service/netServerTimeService.h 2006-12-03 23:51:16 UTC (rev 1513) @@ -0,0 +1,40 @@ +#ifndef YAKE_NETSVC_SERVERTIMESERVICE_H +#define YAKE_NETSVC_SERVERTIMESERVICE_H + +#include <yake/netsvc/netPrerequisites.h> +#include <yake/netsvc/netService.h> +#include <yake/netsvc/detail/netPeerRttCalculator.h> + +#pragma warning(push) +#pragma warning(disable: 4275) // C4275: non dll-interface class 'X' used as base for dll-interface 'Y' + +namespace yake { +namespace net { + + struct NETSVC_API ServerTimeService : public IService + { + ServerTimeService(const ChannelId); + virtual void onStart(IServiceHost&); + virtual void onStop(IServiceHost&); + void onClientConnected(const PeerId pId); + void onClientDisconnected(const PeerId pId); + void update(); + private: + void onPong(const PeerId pId, const NetEvent& evt, const ChannelId); + private: + ChannelId timeChannelId_; + NetEventConnectionPtr evtConn_; + double lastTime_; + + typedef std::map<PeerId,detail::PeerRttCalculator> UserList; + UserList users_; + + Timer timer_; //@todo replace + }; + +} // namespace net +} // namespace yake + +#pragma warning(pop) + +#endif Added: trunk/yake/yake/netsvc/service/netTimeServiceMessages.h =================================================================== --- trunk/yake/yake/netsvc/service/netTimeServiceMessages.h (rev 0) +++ trunk/yake/yake/netsvc/service/netTimeServiceMessages.h 2006-12-03 23:51:16 UTC (rev 1513) @@ -0,0 +1,79 @@ +#ifndef YAKE_NETSVC_TIMESERVICEMESSAGES_H +#define YAKE_NETSVC_TIMESERVICEMESSAGES_H + +#include <yake/netsvc/netPrerequisites.h> + +#pragma warning(push) +#pragma warning(disable: 4275) // C4275: non dll-interface class 'X' used as base for dll-interface 'Y' + +namespace yake { +namespace net { +//namespace svc { +//namespace comm { + + struct s2cEvtPing : public yake::net::NetEvent + { + DECLARE_EVENT( s2cEvtPing, 40 ); + s2cEvtPing(const yake::uint32 serverTime) : + yake::net::NetEvent(ID), serverTime_(serverTime) + {} + virtual bool pack(yake::net::obitstream& out) const + { + out << serverTime_; + return true; + } + virtual bool unpack(yake::net::ibitstream& in) + { + in >> serverTime_; + return true; + } + yake::uint32 serverTime_; + }; + struct c2sEvtPong : public yake::net::NetEvent + { + DECLARE_EVENT( c2sEvtPong, 41 ); + c2sEvtPong(const yake::uint32 clientTime, const yake::uint32 serverTime) : + yake::net::NetEvent(ID), clientTime_(clientTime), serverTime_(serverTime) + {} + virtual bool pack(yake::net::obitstream& out) const + { + out << serverTime_ << clientTime_; + return true; + } + virtual bool unpack(yake::net::ibitstream& in) + { + in >> serverTime_ >> clientTime_; + return true; + } + yake::uint32 serverTime_; + yake::uint32 clientTime_; + }; + struct s2cEvtPong : public yake::net::NetEvent + { + DECLARE_EVENT( s2cEvtPong, 42 ); + s2cEvtPong(const yake::uint32 serverTime2_, const yake::uint32 clientTime, const yake::uint32 serverTime) : + yake::net::NetEvent(ID), clientTime_(clientTime), serverTime_(serverTime), serverTime2_(serverTime_) + {} + virtual bool pack(yake::net::obitstream& out) const + { + out << serverTime_ << clientTime_ << serverTime2_; + return true; + } + virtual bool unpack(yake::net::ibitstream& in) + { + in >> serverTime_ >> clientTime_ >> serverTime2_; + return true; + } + yake::uint32 serverTime_; + yake::uint32 serverTime2_; + yake::uint32 clientTime_; + }; + +//} // namespace comm +//} // namespace svc +} // namespace net +} // namespace yake + +#pragma warning(pop) + +#endif Modified: trunk/yake/yake/samples/net/common/commonEvents.h =================================================================== --- trunk/yake/yake/samples/net/common/commonEvents.h 2006-12-03 00:46:45 UTC (rev 1512) +++ trunk/yake/yake/samples/net/common/commonEvents.h 2006-12-03 23:51:16 UTC (rev 1513) @@ -55,56 +55,6 @@ */ //--- -#define DECLARE_EVENT(CLASS,IDVALUE) \ -public: \ -static yake::net::NetEvent* create(yake::net::NetEvent::id_type id) \ -{ CLASS* p = new CLASS(); p->setId(id); return p; } \ -static void destroy(yake::net::NetEvent* p) { delete p; } \ -static const yake::net::NetEvent::id_type ID = IDVALUE; \ -CLASS() : yake::net::NetEvent(ID) \ -{} - -inline yake::net::ibitstream& operator >> (yake::net::ibitstream& in, yake::uint8& rhs) -{ - in.read( rhs ); - return in; -} -inline yake::net::obitstream& operator << (yake::net::obitstream& out, const yake::uint8 rhs) -{ - out.write( rhs ); - return out; -} -inline yake::net::ibitstream& operator >> (yake::net::ibitstream& in, yake::uint16& rhs) -{ - in.read( rhs ); - return in; -} -inline yake::net::obitstream& operator << (yake::net::obitstream& out, const yake::uint16 rhs) -{ - out.write( rhs ); - return out; -} -inline yake::net::ibitstream& operator >> (yake::net::ibitstream& in, yake::uint32& rhs) -{ - in.read( rhs ); - return in; -} -inline yake::net::obitstream& operator << (yake::net::obitstream& out, const yake::uint32 rhs) -{ - out.write( rhs ); - return out; -} -inline yake::net::ibitstream& operator >> (yake::net::ibitstream& in, int& rhs) -{ - in.read( rhs ); - return in; -} -inline yake::net::obitstream& operator << (yake::net::obitstream& out, const int rhs) -{ - out.write( rhs ); - return out; -} - struct version_t { yake::uint8 ver[3]; @@ -151,58 +101,7 @@ } version_t version; }; -inline yake::net::obitstream& operator << (yake::net::obitstream& out, const std::string& rhs) -{ - out.write(int(rhs.length())); - if (!rhs.empty()) - out.write( rhs.c_str(), (rhs.size()*sizeof(std::string::value_type)*8) ); - return out; -} -inline yake::net::ibitstream& operator >> (yake::net::ibitstream& in, std::string& rhs) -{ - int len = 0; - in.read(len); - assert(len < 10000); // enforce upper limit - rhs.clear(); - rhs.reserve(len); - while (len>0) - { - char c = 0; - in.read(c); - rhs += c; - len--; - } - return in; -} -template<typename _Ty, typename _Pr, typename _Alloc> -inline yake::net::obitstream& operator << (yake::net::obitstream& out, const std::map<_Ty,_Pr,_Alloc>& ctr) -{ - out.write(yake::uint32(ctr.size())); - typedef std::map<_Ty,_Pr,_Alloc> map_type; - typedef typename map_type::const_iterator iter_type; - YAKE_FOR_EACH(iter_type,it,ctr) - out << it->first << it->second; - return out; -} -template<typename _Ty, typename _Pr, typename _Alloc> -inline yake::net::ibitstream& operator >> (yake::net::ibitstream& in, std::map<_Ty,_Pr,_Alloc>& ctr) -{ - ctr.clear(); - yake::uint32 count = 0; - in.read(count); - //@todo safe-guard count - typedef std::map<_Ty,_Pr,_Alloc> map_type; - typedef typename map_type::const_iterator iter_type; - for (size_t i=0; i<count; ++i) - { - std::pair<_Ty,_Pr> data; - in >> data.first; - in >> data.second; - ctr.insert( data ); - } - return in; -} struct s2cEvtJoinReqReply : public yake::net::NetEvent { DECLARE_EVENT( s2cEvtJoinReqReply, 2 ); @@ -281,118 +180,4 @@ } yake::ent::ObjectId objId_; }; - -struct s2cEvtCommMsg : public yake::net::NetEvent -{ - DECLARE_EVENT( s2cEvtCommMsg, 30 ); - s2cEvtCommMsg(const std::string& cId, const std::string& from, const std::string& to, const std::string& msg) : - yake::net::NetEvent(ID), cId_(cId), msg_(msg), from_(from), to_(to) - {} - virtual bool pack(yake::net::obitstream& out) const - { - out << cId_ << from_ << to_ << msg_; - return true; - } - virtual bool unpack(yake::net::ibitstream& in) - { - in >> cId_ >> from_ >> to_ >> msg_; - return true; - } - std::string cId_; - std::string msg_; - std::string from_; - std::string to_; -}; -struct s2cEvtCommLeaveChannel : public yake::net::NetEvent -{ - DECLARE_EVENT( s2cEvtCommLeaveChannel, 31 ); - s2cEvtCommLeaveChannel(const std::string& cId, const std::string& reason) : yake::net::NetEvent(ID), cId_(cId), reason_(reason) - {} - virtual bool pack(yake::net::obitstream& out) const - { - out << cId_ << reason_; - return true; - } - virtual bool unpack(yake::net::ibitstream& in) - { - in >> cId_ >> reason_; - return true; - } - std::string cId_; - std::string reason_; -}; -struct c2sEvtCommJoinChannel : public yake::net::NetEvent -{ - DECLARE_EVENT( c2sEvtCommJoinChannel, 32 ); - c2sEvtCommJoinChannel(const std::string& cId) : yake::net::NetEvent(ID), cId_(cId) - {} - virtual bool pack(yake::net::obitstream& out) const - { - out << cId_; - return true; - } - virtual bool unpack(yake::net::ibitstream& in) - { - in >> cId_; - return true; - } - std::string cId_; -}; -struct s2cEvtPing : public yake::net::NetEvent -{ - DECLARE_EVENT( s2cEvtPing, 40 ); - s2cEvtPing(const yake::uint32 serverTime) : - yake::net::NetEvent(ID), serverTime_(serverTime) - {} - virtual bool pack(yake::net::obitstream& out) const - { - out << serverTime_; - return true; - } - virtual bool unpack(yake::net::ibitstream& in) - { - in >> serverTime_; - return true; - } - yake... [truncated message content] |