2007-04-16

This commit is contained in:
Anonymous Maarten committed 2015-12-03 01:37:37 +01:00
1 parent 78c27f03c8
commit e20673c2cd
120 files changed
+9578 -1036

No files matched your search

+30
View File
@@ -0,0 +1,30 @@
OpenSteer -- Steering Behaviors for Autonomous Characters
Copyright (c) 2002-2005, Sony Computer Entertainment America
Original author: Craig Reynolds <craig_reynolds@playstation.sony.com>
OpenSteer is open source software distributed in accordance with the MIT
License (http://www.opensource.org/licenses/mit-license.php) which says:
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
+205
View File
@@ -0,0 +1,205 @@
// ----------------------------------------------------------------------------
//
//
// OpenSteer -- Steering Behaviors for Autonomous Characters
//
// Copyright (c) 2002-2005, Sony Computer Entertainment America
// Original author: Craig Reynolds <craig_reynolds@playstation.sony.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//
// ----------------------------------------------------------------------------
//
//
// discrete time simulation clock for OpenSteerDemo
//
// Keeps track of real clock time and simulation time. Encapsulates the time
// API of the underlying operating system. Can be put in either "as fast as
// possible" variable time step mode (where simulation time steps are based on
// real time elapsed between updates), or in fixed "target FPS" mode where the
// simulation steps are constrained to start on 1/FPS boundaries (e.g. on a 60
// hertz video game console). Also handles the notion of "pausing" simulation
// time.
//
// Usage: allocate a clock, set its "paused" or "targetFPS" parameters, then
// call updateGlobalSimulationClock before each simulation step.
//
// 10-04-04 bk: put everything into the OpenSteer namespace
// 11-11-03 cwr: another overhaul: support aniamtion mode, switch to
// functional API, move smoothed stats inside this class
// 09-24-02 cwr: major overhaul
// 06-26-02 cwr: created
//
//
// ----------------------------------------------------------------------------
#ifndef OPENSTEER_CLOCK_H
#define OPENSTEER_CLOCK_H
#include "OpenSteer/Utilities.h"
#if defined (_XBOX)
#include <xtl.h>
#elif defined (_WIN32)
#include <windows.h>
#endif
namespace OpenSteer {
class Clock
{
public:
// constructor
Clock ();
// update this clock, called exactly once per simulation step ("frame")
void update (void);
// returns the number of seconds of real time (represented as a float)
// since the clock was first updated.
float realTimeSinceFirstClockUpdate (void);
// force simulation time ahead, ignoring passage of real time.
// Used for OpenSteerDemo's "single step forward" and animation mode
float advanceSimulationTimeOneFrame (void);
void advanceSimulationTime (const float seconds);
// "wait" until next frame time
void frameRateSync (void);
// main clock modes: variable or fixed frame rate, real-time or animation
// mode, running or paused.
private:
// run as fast as possible, simulation time is based on real time
bool variableFrameRateMode;
// fixed frame rate (ignored when in variable frame rate mode) in
// real-time mode this is a "target", in animation mode it is absolute
int fixedFrameRate;
// used for offline, non-real-time applications
bool animationMode;
// is simulation running or paused?
bool paused;
public:
int getFixedFrameRate (void) {return fixedFrameRate;}
int setFixedFrameRate (int ffr) {return fixedFrameRate = ffr;}
bool getAnimationMode (void) {return animationMode;}
bool setAnimationMode (bool am) {return animationMode = am;}
bool getVariableFrameRateMode (void) {return variableFrameRateMode;}
bool setVariableFrameRateMode (bool vfrm)
{return variableFrameRateMode = vfrm;}
bool togglePausedState (void) {return (paused = !paused);};
bool getPausedState (void) {return paused;};
bool setPausedState (bool newPS) {return paused = newPS;};
// clock keeps track of "smoothed" running average of recent frame rates.
// When a fixed frame rate is used, a running average of "CPU load" is
// kept (aka "non-wait time", the percentage of each frame time (time
// step) that the CPU is busy).
private:
float smoothedFPS;
float smoothedUsage;
void updateSmoothedRegisters (void)
{
const float rate = getSmoothingRate ();
if (elapsedRealTime > 0)
blendIntoAccumulator (rate, 1 / elapsedRealTime, smoothedFPS);
if (! getVariableFrameRateMode ())
blendIntoAccumulator (rate, getUsage (), smoothedUsage);
}
public:
float getSmoothedFPS (void) const {return smoothedFPS;}
float getSmoothedUsage (void) const {return smoothedUsage;}
float getSmoothingRate (void) const
{
if (smoothedFPS == 0) return 1; else return elapsedRealTime * 1.5f;
}
float getUsage (void)
{
// run time per frame over target frame time (as a percentage)
return ((100 * elapsedNonWaitRealTime) / (1.0f / fixedFrameRate));
}
// clock state member variables and public accessors for them
private:
// real "wall clock" time since launch
float totalRealTime;
// total time simulation has run
float totalSimulationTime;
// total time spent paused
float totalPausedTime;
// sum of (non-realtime driven) advances to simulation time
float totalAdvanceTime;
// interval since last simulation time
// (xxx does this need to be stored in the instance? xxx)
float elapsedSimulationTime;
// interval since last clock update time
// (xxx does this need to be stored in the instance? xxx)
float elapsedRealTime;
// interval since last clock update,
// exclusive of time spent waiting for frame boundary when targetFPS>0
float elapsedNonWaitRealTime;
public:
float getTotalRealTime (void) {return totalRealTime;}
float getTotalSimulationTime (void) {return totalSimulationTime;}
float getTotalPausedTime (void) {return totalPausedTime;}
float getTotalAdvanceTime (void) {return totalAdvanceTime;}
float getElapsedSimulationTime (void) {return elapsedSimulationTime;}
float getElapsedRealTime (void) {return elapsedRealTime;}
float getElapsedNonWaitRealTime (void) {return elapsedNonWaitRealTime;}
private:
// "manually" advance clock by this amount on next update
float newAdvanceTime;
// "Calendar time" when this clock was first updated
#ifdef _WIN32
// from QueryPerformanceCounter on Windows
LONGLONG basePerformanceCounter;
#else
// from gettimeofday on Linux and Mac OS X
int baseRealTimeSec;
int baseRealTimeUsec;
#endif
};
} // namespace OpenSteer
// ----------------------------------------------------------------------------
#endif // OPENSTEER_CLOCK_H
+337
View File
@@ -0,0 +1,337 @@
// ----------------------------------------------------------------------------
//
//
// OpenSteer -- Steering Behaviors for Autonomous Characters
//
// Copyright (c) 2002-2005, Sony Computer Entertainment America
// Original author: Craig Reynolds <craig_reynolds@playstation.sony.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//
// ----------------------------------------------------------------------------
//
//
// Proximity
//
// Data structures for accelerating proximity/locality/neighborhood queries
//
// 10-04-04 bk: put everything into the OpenSteer namespace
// 06-20-01 cwr: created
//
//
// ----------------------------------------------------------------------------
#ifndef OPENSTEER_PROXIMITY_H
#define OPENSTEER_PROXIMITY_H
#include <algorithm>
#include <vector>
#include "OpenSteer/Vec3.h"
#include "OpenSteer/lq.h" // XXX temp?
namespace OpenSteer {
// ----------------------------------------------------------------------------
// "tokens" are the objects manipulated by the spatial database
template <class ContentType>
class AbstractTokenForProximityDatabase
{
public:
virtual ~AbstractTokenForProximityDatabase () {}
// the client object calls this each time its position changes
virtual void updateForNewPosition (const Vec3& position) = 0;
// find all neighbors within the given sphere (as center and radius)
virtual void findNeighbors (const Vec3& center,
const float radius,
std::vector<ContentType>& results) = 0;
#ifndef NO_LQ_BIN_STATS
// only meaningful for LQProximityDatabase, provide dummy default
virtual void getBinPopulationStats (int& min, int& max, float& average)
{min=max=0; average=0.0;}
#endif // NO_LQ_BIN_STATS
};
// ----------------------------------------------------------------------------
// abstract type for all kinds of proximity databases
template <class ContentType>
class AbstractProximityDatabase
{
public:
// type for the "tokens" manipulated by this spatial database
typedef AbstractTokenForProximityDatabase<ContentType> tokenType;
virtual ~AbstractProximityDatabase() { /* Nothing to do? */ }
// allocate a token to represent a given client object in this database
virtual tokenType* allocateToken (ContentType parentObject) = 0;
// insert
// XXX maybe this should return an iterator?
// XXX see http://www.sgi.com/tech/stl/set.html
// virtual void insert (const ContentType& x) = 0;
// XXX name?
// returns the number of tokens in the proximity database
virtual int getPopulation (void) = 0;
};
// ----------------------------------------------------------------------------
// This is the "brute force" O(n^2) approach implemented in terms of the
// AbstractProximityDatabase protocol so it can be compared directly to other
// approaches. (e.g. the Boids plugin allows switching at runtime.)
template <class ContentType>
class BruteForceProximityDatabase
: public AbstractProximityDatabase<ContentType>
{
public:
// constructor
BruteForceProximityDatabase (void)
{
}
// destructor
virtual ~BruteForceProximityDatabase ()
{
}
// "token" to represent objects stored in the database
class tokenType : public AbstractTokenForProximityDatabase<ContentType>
{
public:
// constructor
tokenType (ContentType parentObject, BruteForceProximityDatabase& pd)
{
// store pointer to our associated database and the object this
// token represents, and store this token on the database's vector
bfpd = &pd;
object = parentObject;
bfpd->group.push_back (this);
}
// destructor
virtual ~tokenType ()
{
// remove this token from the database's vector
bfpd->group.erase (std::find (bfpd->group.begin(),
bfpd->group.end(),
this));
}
// the client object calls this each time its position changes
void updateForNewPosition (const Vec3& newPosition)
{
position = newPosition;
}
// find all neighbors within the given sphere (as center and radius)
void findNeighbors (const Vec3& center,
const float radius,
std::vector<ContentType>& results)
{
// loop over all tokens
const float r2 = radius * radius;
for (tokenIterator i = bfpd->group.begin();
i != bfpd->group.end();
i++)
{
const Vec3 offset = center - (**i).position;
const float d2 = offset.lengthSquared();
// push onto result vector when within given radius
if (d2 < r2) results.push_back ((**i).object);
}
}
private:
BruteForceProximityDatabase* bfpd;
ContentType object;
Vec3 position;
};
typedef std::vector<tokenType*> tokenVector;
typedef typename tokenVector::const_iterator tokenIterator;
// allocate a token to represent a given client object in this database
tokenType* allocateToken (ContentType parentObject)
{
return new tokenType (parentObject, *this);
}
// return the number of tokens currently in the database
int getPopulation (void)
{
return (int) group.size();
}
private:
// STL vector containing all tokens in database
tokenVector group;
};
// ----------------------------------------------------------------------------
// A AbstractProximityDatabase-style wrapper for the LQ bin lattice system
template <class ContentType>
class LQProximityDatabase : public AbstractProximityDatabase<ContentType>
{
public:
// constructor
LQProximityDatabase (const Vec3& center,
const Vec3& dimensions,
const Vec3& divisions)
{
const Vec3 halfsize (dimensions * 0.5f);
const Vec3 origin (center - halfsize);
lq = lqCreateDatabase (origin.x, origin.y, origin.z,
dimensions.x, dimensions.y, dimensions.z,
(int) round (divisions.x),
(int) round (divisions.y),
(int) round (divisions.z));
}
// destructor
virtual ~LQProximityDatabase ()
{
lqDeleteDatabase (lq);
lq = NULL;
}
// "token" to represent objects stored in the database
class tokenType : public AbstractTokenForProximityDatabase<ContentType>
{
public:
// constructor
tokenType (ContentType parentObject, LQProximityDatabase& lqsd)
{
lqInitClientProxy (&proxy, parentObject);
lq = lqsd.lq;
}
// destructor
virtual ~tokenType (void)
{
lqRemoveFromBin (&proxy);
}
// the client object calls this each time its position changes
void updateForNewPosition (const Vec3& p)
{
lqUpdateForNewLocation (lq, &proxy, p.x, p.y, p.z);
}
// find all neighbors within the given sphere (as center and radius)
void findNeighbors (const Vec3& center,
const float radius,
std::vector<ContentType>& results)
{
lqMapOverAllObjectsInLocality (lq,
center.x, center.y, center.z,
radius,
perNeighborCallBackFunction,
(void*)&results);
}
// called by LQ for each clientObject in the specified neighborhood:
// push that clientObject onto the ContentType vector in void*
// clientQueryState
// (parameter names commented out to prevent compiler warning from "-W")
static void perNeighborCallBackFunction (void* clientObject,
float /*distanceSquared*/,
void* clientQueryState)
{
typedef std::vector<ContentType> ctv;
ctv& results = *((ctv*) clientQueryState);
results.push_back ((ContentType) clientObject);
}
#ifndef NO_LQ_BIN_STATS
// Get statistics about bin populations: min, max and
// average of non-empty bins.
void getBinPopulationStats (int& min, int& max, float& average)
{
lqGetBinPopulationStats (lq, &min, &max, &average);
}
#endif // NO_LQ_BIN_STATS
private:
lqClientProxy proxy;
lqDB* lq;
};
// allocate a token to represent a given client object in this database
tokenType* allocateToken (ContentType parentObject)
{
return new tokenType (parentObject, *this);
}
// count the number of tokens currently in the database
int getPopulation (void)
{
int count = 0;
lqMapOverAllObjects (lq, counterCallBackFunction, &count);
return count;
}
// (parameter names commented out to prevent compiler warning from "-W")
static void counterCallBackFunction (void* /*clientObject*/,
float /*distanceSquared*/,
void* clientQueryState)
{
int& counter = *(int*)clientQueryState;
counter++;
}
private:
lqDB* lq;
};
} // namespace OpenSteer
// ----------------------------------------------------------------------------
#endif // OPENSTEER_PROXIMITY_H
+514
View File
@@ -0,0 +1,514 @@
// ----------------------------------------------------------------------------
//
//
// OpenSteer -- Steering Behaviors for Autonomous Characters
//
// Copyright (c) 2002-2005, Sony Computer Entertainment America
// Original author: Craig Reynolds <craig_reynolds@playstation.sony.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//
// ----------------------------------------------------------------------------
//
//
// Utilities for OpenSteering
//
// 08-06-05 bk: added functions to clamp values to a certain value range, to
// compare values using a tolerance, and so on.
// 10-04-04 bk: put everything into the OpenSteer namespace
// 07-09-02 cwr: created
//
//
// ----------------------------------------------------------------------------
#ifndef OPENSTEER_UTILITIES_H
#define OPENSTEER_UTILITIES_H
#include <iostream> // for ostream, <<, etc.
#include <cstdlib> // for rand, etc.
#include <cfloat> // for FLT_MAX, etc.
#include <cmath> // for sqrt, etc.
#include <vector> // for std::vector
#include <cassert> // for assert
#include <limits> // for numeric_limits
// ----------------------------------------------------------------------------
// For the sake of Windows, apparently this is a "Linux/Unix thing"
#ifndef OPENSTEER_M_PI
#define OPENSTEER_M_PI 3.14159265358979323846f
#endif
#ifdef _MSC_VER
#undef min
#undef max
#endif
namespace OpenSteer {
// ----------------------------------------------------------------------------
// Generic interpolation
template<class T> inline T interpolate (float alpha, const T& x0, const T& x1)
{
return x0 + ((x1 - x0) * alpha);
}
// ----------------------------------------------------------------------------
// Random number utilities
// Returns a float randomly distributed between 0 and 1
inline float frandom01 (void)
{
return (((float) rand ()) / ((float) RAND_MAX));
}
// Returns a float randomly distributed between lowerBound and upperBound
inline float frandom2 (float lowerBound, float upperBound)
{
return lowerBound + (frandom01 () * (upperBound - lowerBound));
}
// ----------------------------------------------------------------------------
// Constrain a given value (x) to be between two (ordered) bounds: min
// and max. Returns x if it is between the bounds, otherwise returns
// the nearer bound.
inline float clip (const float x, const float min, const float max)
{
if (x < min) return min;
if (x > max) return max;
return x;
}
// ----------------------------------------------------------------------------
// remap a value specified relative to a pair of bounding values
// to the corresponding value relative to another pair of bounds.
// Inspired by (dyna:remap-interval y y0 y1 z0 z1)
inline float remapInterval (float x,
float in0, float in1,
float out0, float out1)
{
// uninterpolate: what is x relative to the interval in0:in1?
float relative = (x - in0) / (in1 - in0);
// now interpolate between output interval based on relative x
return interpolate (relative, out0, out1);
}
// Like remapInterval but the result is clipped to remain between
// out0 and out1
inline float remapIntervalClip (float x,
float in0, float in1,
float out0, float out1)
{
// uninterpolate: what is x relative to the interval in0:in1?
float relative = (x - in0) / (in1 - in0);
// now interpolate between output interval based on relative x
return interpolate (clip (relative, 0, 1), out0, out1);
}
// ----------------------------------------------------------------------------
// classify a value relative to the interval between two bounds:
// returns -1 when below the lower bound
// returns 0 when between the bounds (inside the interval)
// returns +1 when above the upper bound
inline int intervalComparison (float x, float lowerBound, float upperBound)
{
if (x < lowerBound) return -1;
if (x > upperBound) return +1;
return 0;
}
// ----------------------------------------------------------------------------
inline float scalarRandomWalk (const float initial,
const float walkspeed,
const float min,
const float max)
{
const float next = initial + (((frandom01() * 2) - 1) * walkspeed);
if (next < min) return min;
if (next > max) return max;
return next;
}
// ----------------------------------------------------------------------------
inline float square (float x)
{
return x * x;
}
// ----------------------------------------------------------------------------
// for debugging: prints one line with a given C expression, an equals sign,
// and the value of the expression. For example "angle = 35.6"
#define debugPrint(e) (std::cout << #e" = " << (e) << std::endl << std::flush)
// ----------------------------------------------------------------------------
// blends new values into an accumulator to produce a smoothed time series
//
// Modifies its third argument, a reference to the float accumulator holding
// the "smoothed time series."
//
// The first argument (smoothRate) is typically made proportional to "dt" the
// simulation time step. If smoothRate is 0 the accumulator will not change,
// if smoothRate is 1 the accumulator will be set to the new value with no
// smoothing. Useful values are "near zero".
//
// Usage:
// blendIntoAccumulator (dt * 0.4f, currentFPS, smoothedFPS);
template<class T>
inline void blendIntoAccumulator (const float smoothRate,
const T& newValue,
T& smoothedAccumulator)
{
smoothedAccumulator = interpolate (clip (smoothRate, 0, 1),
smoothedAccumulator,
newValue);
}
// ----------------------------------------------------------------------------
// given a new Angle and an old angle, adjust the new for angle wraparound (the
// 0->360 flip), returning a value equivalent to newAngle, but closest in
// absolute value to oldAngle. For radians fullCircle = OPENSTEER_M_PI*2, for degrees
// fullCircle = 360. Based on code in stuart/bird/fish demo's camera.cc
//
// (not currently used)
/*
inline float distance1D (const float a, const float b)
{
const float d = a - b;
return (d > 0) ? d : -d;
}
float adjustForAngleWraparound (float newAngle,
float oldAngle,
float fullCircle)
{
// adjust newAngle for angle wraparound: consider its current value (a)
// as well as the angle 2pi larger (b) and 2pi smaller (c). Select the
// one closer (magnitude of difference) to the current value of oldAngle.
const float a = newAngle;
const float b = newAngle + fullCircle;
const float c = newAngle - fullCircle;
const float ad = distance1D (a, oldAngle);
const float bd = distance1D (b, oldAngle);
const float cd = distance1D (c, oldAngle);
if ((bd < ad) && (bd < cd)) return b;
if ((cd < ad) && (cd < bd)) return c;
return a;
}
*/
// ----------------------------------------------------------------------------
// Functions to encapsulate cross-platform differences for several <cmath>
// functions. Specifically, the C++ standard says that these functions are
// in the std namespace (std::sqrt, etc.) Apparently the MS VC6 compiler (or
// its header files) do not implement this correctly and the function names
// are in the global namespace. We hope these -XXX versions are a temporary
// expedient, to be removed later.
#ifdef _WIN32
inline float floorXXX (float x) {return ::floor (x);}
inline float sqrtXXX (float x) {return ::sqrt (x);}
inline float sinXXX (float x) {return ::sin (x);}
inline float cosXXX (float x) {return ::cos (x);}
inline float absXXX (float x) {return ::abs (x);}
inline int absXXX (int x) {return ::abs (x);}
inline float maxXXX (float x, float y) {if (x > y) return x; else return y;}
inline float minXXX (float x, float y) {if (x < y) return x; else return y;}
#else
inline float floorXXX (float x) {return std::floor (x);}
inline float sqrtXXX (float x) {return std::sqrt (x);}
inline float sinXXX (float x) {return std::sin (x);}
inline float cosXXX (float x) {return std::cos (x);}
inline float absXXX (float x) {return std::abs (x);}
inline int absXXX (int x) {return std::abs (x);}
inline float maxXXX (float x, float y) {return std::max (x, y);}
inline float minXXX (float x, float y) {return std::min (x, y);}
#endif
// ----------------------------------------------------------------------------
// round (x) "round off" x to the nearest integer (as a float value)
//
// This is a Gnu-sanctioned(?) post-ANSI-Standard(?) extension (as in
// http://www.opengroup.org/onlinepubs/007904975/basedefs/math.h.html)
// which may not be present in all C++ environments. It is defined in
// math.h headers in Linux and Mac OS X, but apparently not in Win32:
#ifdef _WIN32
inline float round (float x)
{
if (x < 0)
return -floorXXX (0.5f - x);
else
return floorXXX (0.5f + x);
}
#else
inline float round( float x )
{
return ::round( x );
}
#endif
/**
* Returns @a valueToClamp clamped to the range @a minValue - @a maxValue.
*/
template< typename T >
T
clamp( T const& valueToClamp, T const& minValue, T const& maxValue) {
assert( minValue <= maxValue && "minValue must be lesser or equal to maxValue." );
if ( valueToClamp < minValue ) {
return minValue;
} else if ( valueToClamp > maxValue ) {
return maxValue;
}
return valueToClamp;
}
/**
* Returns the floating point remainder of the division of @a x by @a y.
* If @a y is @c 0 the behavior is undefined.
*/
inline float modulo( float x, float y ) {
assert( 0.0f != y && "Division by zero." );
return std::fmod( x, y );
}
/**
* Returns the floating point remainder of the division of @a x by @a y.
* If @a y is @c 0 the behavior is undefined.
*/
inline double modulo( double x, double y ) {
assert( 0.0 != y && "Division by zero." );
return std::fmod( x, y );
}
/**
* Returns the floating point remainder of the division of @a x by @a y.
* If @a y is @c 0 the behavior is undefined.
*/
inline long double modulo( long double x, long double y ) {
assert( 0.0 != y && "Division by zero." );
return std::fmod( x, y );
}
/**
* Returns the floating point remainder of the division of @a x by @a y.
* If @a y is @c 0 the behavior is undefined.
*/
inline short modulo( short x, short y ) {
assert( 0 != y && "Division by zero." );
return x % y;
}
/**
* Returns the floating point remainder of the division of @a x by @a y.
* If @a y is @c 0 the behavior is undefined.
*/
inline int modulo( int x, int y ) {
assert( 0 != y && "Division by zero." );
return x % y;
}
/**
* Returns the floating point remainder of the division of @a x by @a y.
* If @a y is @c 0 the behavior is undefined.
*/
inline long modulo( long x, long y ) {
assert( 0 != y && "Division by zero." );
return x % y;
}
/**
* Returns <code>value</code> if <code>value >= 0 </code>, otherwise
* <code>-value</code>.
*/
template< typename T >
T abs( T const& value ) {
return absXXX( value );
}
/**
* Returns the maximum of the three values @a v0, @a v1, and @a v2.
*
* @todo Write a unit test.
*/
template< typename T >
T
max( T const& v0, T const& v1, T const& v2 ) {
return maxXXX( v0, maxXXX( v1, v2 ) );
}
/**
* Returns the minimum of the three values @a v0, @a v1, and @a v2.
*
* @todo Write a unit test.
*/
template< typename T >
T
min( T const& v0, T const& v1, T const& v2 ) {
return minXXX( v0, minXXX( v1, v2 ) );
}
/**
* Compares the absolute value of @a v with @a tolerance.
*
* See Christer Ericson, Real-Time Collision Detection, Morgan Kaufmann,
* 2005, pp. 441--443.
*
* @todo Write a unit test.
*/
template< typename T >
bool
isZero( T const& v, T const& tolerance = std::numeric_limits< T >::epsilon() ) {
return abs( v ) <= tolerance;
}
/**
* Compares @a lhs with @a rhs given a specific @a tolerance.
*
* @attention Adapt @a tolerance to the range of values of @a lhs and
* @a rhs.
* See Christer Ericson, Real-Time Collision Detection, Morgan Kaufmann,
* 2005, pp. 441--443.
*
* @return <code>abs( lhs - rhs ) <= tolerance</code>
*
* @todo Write a unit test.
*/
template< typename T >
bool
equalsAbsolute( T const& lhs, T const& rhs, T const& tolerance = std::numeric_limits< T >::epsilon() ) {
return isZero( lhs - rhs, tolerance );
}
/**
* Compares @a lhs with @a rhs given a specific @a tolerance taking the
* range of values into account.
*
* See Christer Ericson, Real-Time Collision Detection, Morgan Kaufmann,
* 2005, pp. 441--443.
*
* @return <code>abs( lhs - rhs ) <= tolerance * max( abs( lhs ), abs( rhs ), 1 )</code>
*
* @todo Write a unit test.
*/
template< typename T >
bool
equalsRelative( T const& lhs, T const& rhs, T const& tolerance = std::numeric_limits< T >::epsilon() ) {
return isZero( lhs - rhs, tolerance * max( abs( lhs ), abs( rhs ), T( 1 ) ) );
}
/**
* Approximately compares @a lhs with @a rhs given a specific @a tolerance
* taking the range of values into account.
*
* See Christer Ericson, Real-Time Collision Detection, Morgan Kaufmann,
* 2005, pp. 441--443.
*
* @return <code>abs( lhs - rhs ) <= tolerance * ( abs( lhs ) + abs( rhs ) + 1 )</code>
*
* @todo Write a unit test.
*/
template< typename T >
bool
equalsRelativeApproximately( T const& lhs, T const& rhs, T const& tolerance = std::numeric_limits< T >::epsilon() ) {
return isZero( lhs - rhs, tolerance * ( abs( lhs ) + abs( rhs ) + T( 1 ) ) );
}
/**
* Shrinks the capacity of a std::vector to fit its content.
*
* See Scott Meyer, Effective STL, Addison-Wesley, 2001, pp. 77--79.
*/
template< typename T >
void shrinkToFit( std::vector< T >& v ) {
std::vector< T >( v ).swap( v );
}
} // namespace OpenSteer
// ----------------------------------------------------------------------------
#endif // OPENSTEER_UTILITIES_H
+382
View File
@@ -0,0 +1,382 @@
// ----------------------------------------------------------------------------
//
//
// OpenSteer -- Steering Behaviors for Autonomous Characters
//
// Copyright (c) 2002-2005, Sony Computer Entertainment America
// Original author: Craig Reynolds <craig_reynolds@playstation.sony.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//
// ----------------------------------------------------------------------------
//
// Vec3: OpenSteer's generic type for 3d vectors
//
// This file defines the class Vec3, which is used throughout OpenSteer to
// manipulate 3d geometric data. It includes standard vector operations (like
// vector addition, subtraction, scale, dot, cross...) and more idiosyncratic
// utility functions.
//
// When integrating OpenSteer into a preexisting 3d application, it may be
// important to use the 3d vector type of that application. In that case Vec3
// can be changed to inherit from the preexisting application' vector type and
// to match the interface used by OpenSteer to the interface provided by the
// preexisting 3d vector type.
//
// 10-04-04 bk: put everything into the OpenSteer namespace
// 03-26-03 cwr: created to replace for Hiranabe-san's execellent but larger
// vecmath package (http://objectclub.esm.co.jp/vecmath/)
//
// ----------------------------------------------------------------------------
#ifndef OPENSTEER_VEC3_H
#define OPENSTEER_VEC3_H
#include "OpenSteer/Utilities.h" // for interpolate, etc.
namespace OpenSteer {
// ----------------------------------------------------------------------------
class Vec3
{
public:
// ----------------------------------------- generic 3d vector operations
// three-dimensional Cartesian coordinates
float x, y, z;
// constructors
Vec3 (void): x( 0.0f ), y( 0.0f ), z( 0.0f ) {}
Vec3 (float X, float Y, float Z) : x( X ), y( Y ), z( Z ) {}
// vector addition
Vec3 operator+ (const Vec3& v) const {return Vec3 (x+v.x, y+v.y, z+v.z);}
// vector subtraction
Vec3 operator- (const Vec3& v) const {return Vec3 (x-v.x, y-v.y, z-v.z);}
// unary minus
Vec3 operator- (void) const {return Vec3 (-x, -y, -z);}
// vector times scalar product (scale length of vector times argument)
Vec3 operator* (const float s) const {return Vec3 (x * s, y * s, z * s);}
// vector divided by a scalar (divide length of vector by argument)
Vec3 operator/ (const float s) const {return Vec3 (x / s, y / s, z / s);}
// dot product
float dot (const Vec3& v) const {return (x * v.x) + (y * v.y) + (z * v.z);}
// length
float length (void) const {return sqrtXXX (lengthSquared ());}
// length squared
float lengthSquared (void) const {return this->dot (*this);}
// normalize: returns normalized version (parallel to this, length = 1)
Vec3 normalize (void) const
{
// skip divide if length is zero
const float len = length ();
return (len>0) ? (*this)/len : (*this);
}
// cross product (modify "*this" to be A x B)
// [XXX side effecting -- deprecate this function? XXX]
void cross(const Vec3& a, const Vec3& b)
{
*this = Vec3 ((a.y * b.z) - (a.z * b.y),
(a.z * b.x) - (a.x * b.z),
(a.x * b.y) - (a.y * b.x));
}
// assignment
Vec3 operator= (const Vec3& v) {x=v.x; y=v.y; z=v.z; return *this;}
// set XYZ coordinates to given three floats
Vec3 set (const float _x, const float _y, const float _z)
{x = _x; y = _y; z = _z; return *this;}
// +=
Vec3 operator+= (const Vec3& v) {return *this = (*this + v);}
// -=
Vec3 operator-= (const Vec3& v) {return *this = (*this - v);}
// *=
Vec3 operator*= (const float& s) {return *this = (*this * s);}
Vec3 operator/=( float d ) { return *this = (*this / d); }
// equality/inequality
bool operator== (const Vec3& v) const {return x==v.x && y==v.y && z==v.z;}
bool operator!= (const Vec3& v) const {return !(*this == v);}
// @todo Remove - use @c distance from the Vec3Utilitites header instead.
// XXX experimental (4-1-03 cwr): is this the right approach? defining
// XXX "Vec3 distance (vec3, Vec3)" collided with STL's distance template.
static float distance (const Vec3& a, const Vec3& b){ return(a-b).length();}
// --------------------------- utility member functions used in OpenSteer
// return component of vector parallel to a unit basis vector
// (IMPORTANT NOTE: assumes "basis" has unit magnitude (length==1))
inline Vec3 parallelComponent (const Vec3& unitBasis) const
{
const float projection = this->dot (unitBasis);
return unitBasis * projection;
}
// return component of vector perpendicular to a unit basis vector
// (IMPORTANT NOTE: assumes "basis" has unit magnitude (length==1))
inline Vec3 perpendicularComponent (const Vec3& unitBasis) const
{
return (*this) - parallelComponent (unitBasis);
}
// clamps the length of a given vector to maxLength. If the vector is
// shorter its value is returned unaltered, if the vector is longer
// the value returned has length of maxLength and is paralle to the
// original input.
Vec3 truncateLength (const float maxLength) const
{
const float maxLengthSquared = maxLength * maxLength;
const float vecLengthSquared = this->lengthSquared ();
if (vecLengthSquared <= maxLengthSquared)
return *this;
else
return (*this) * (maxLength / sqrtXXX (vecLengthSquared));
}
// forces a 3d position onto the XZ (aka y=0) plane
Vec3 setYtoZero (void) const {return Vec3 (this->x, 0, this->z);}
// rotate this vector about the global Y (up) axis by the given angle
Vec3 rotateAboutGlobalY (float angle) const
{
const float s = sinXXX (angle);
const float c = cosXXX (angle);
return Vec3 ((this->x * c) + (this->z * s),
(this->y),
(this->z * c) - (this->x * s));
}
// version for caching sin/cos computation
Vec3 rotateAboutGlobalY (float angle, float& sin, float& cos) const
{
// is both are zero, they have not be initialized yet
if (sin==0 && cos==0)
{
sin = sinXXX (angle);
cos = cosXXX (angle);
}
return Vec3 ((this->x * cos) + (this->z * sin),
(this->y),
(this->z * cos) - (this->x * sin));
}
// if this position is outside sphere, push it back in by one diameter
Vec3 sphericalWrapAround (const Vec3& center, float radius)
{
const Vec3 offset = *this - center;
const float r = offset.length();
if (r > radius)
return *this + ((offset/r) * radius * -2);
else
return *this;
}
// names for frequently used vector constants
static const Vec3 zero;
static const Vec3 side;
static const Vec3 up;
static const Vec3 forward;
};
// ----------------------------------------------------------------------------
// scalar times vector product ("float * Vec3")
inline Vec3 operator* (float s, const Vec3& v) {return v*s;}
// return cross product a x b
inline Vec3 crossProduct(const Vec3& a, const Vec3& b)
{
Vec3 result((a.y * b.z) - (a.z * b.y),
(a.z * b.x) - (a.x * b.z),
(a.x * b.y) - (a.y * b.x));
return result;
}
// ----------------------------------------------------------------------------
// default character stream output method
#ifndef NOT_OPENSTEERDEMO // only when building OpenSteerDemo
inline std::ostream& operator<< (std::ostream& o, const Vec3& v)
{
return o << "(" << v.x << "," << v.y << "," << v.z << ")";
}
#endif // NOT_OPENSTEERDEMO
// ----------------------------------------------------------------------------
// Returns a position randomly distributed inside a sphere of unit radius
// centered at the origin. Orientation will be random and length will range
// between 0 and 1
Vec3 RandomVectorInUnitRadiusSphere (void);
// ----------------------------------------------------------------------------
// Returns a position randomly distributed on a disk of unit radius
// on the XZ (Y=0) plane, centered at the origin. Orientation will be
// random and length will range between 0 and 1
Vec3 randomVectorOnUnitRadiusXZDisk (void);
// ----------------------------------------------------------------------------
// Returns a position randomly distributed on the surface of a sphere
// of unit radius centered at the origin. Orientation will be random
// and length will be 1
inline Vec3 RandomUnitVector (void)
{
return RandomVectorInUnitRadiusSphere().normalize();
}
// ----------------------------------------------------------------------------
// Returns a position randomly distributed on a circle of unit radius
// on the XZ (Y=0) plane, centered at the origin. Orientation will be
// random and length will be 1
inline Vec3 RandomUnitVectorOnXZPlane (void)
{
return RandomVectorInUnitRadiusSphere().setYtoZero().normalize();
}
// ----------------------------------------------------------------------------
// used by limitMaxDeviationAngle / limitMinDeviationAngle below
Vec3 vecLimitDeviationAngleUtility (const bool insideOrOutside,
const Vec3& source,
const float cosineOfConeAngle,
const Vec3& basis);
// ----------------------------------------------------------------------------
// Enforce an upper bound on the angle by which a given arbitrary vector
// diviates from a given reference direction (specified by a unit basis
// vector). The effect is to clip the "source" vector to be inside a cone
// defined by the basis and an angle.
inline Vec3 limitMaxDeviationAngle (const Vec3& source,
const float cosineOfConeAngle,
const Vec3& basis)
{
return vecLimitDeviationAngleUtility (true, // force source INSIDE cone
source,
cosineOfConeAngle,
basis);
}
// ----------------------------------------------------------------------------
// Enforce a lower bound on the angle by which a given arbitrary vector
// diviates from a given reference direction (specified by a unit basis
// vector). The effect is to clip the "source" vector to be outside a cone
// defined by the basis and an angle.
inline Vec3 limitMinDeviationAngle (const Vec3& source,
const float cosineOfConeAngle,
const Vec3& basis)
{
return vecLimitDeviationAngleUtility (false, // force source OUTSIDE cone
source,
cosineOfConeAngle,
basis);
}
// ----------------------------------------------------------------------------
// Returns the distance between a point and a line. The line is defined in
// terms of a point on the line ("lineOrigin") and a UNIT vector parallel to
// the line ("lineUnitTangent")
inline float distanceFromLine (const Vec3& point,
const Vec3& lineOrigin,
const Vec3& lineUnitTangent)
{
const Vec3 offset = point - lineOrigin;
const Vec3 perp = offset.perpendicularComponent (lineUnitTangent);
return perp.length();
}
// ----------------------------------------------------------------------------
// given a vector, return a vector perpendicular to it (note that this
// arbitrarily selects one of the infinitude of perpendicular vectors)
Vec3 findPerpendicularIn3d (const Vec3& direction);
// ----------------------------------------------------------------------------
// candidates for global utility functions
//
// dot
// cross
// length
// distance
// normalized
} // namespace OpenSteer
// ----------------------------------------------------------------------------
#endif // OPENSTEER_VEC3_H
@@ -0,0 +1,96 @@
// ----------------------------------------------------------------------------
//
//
// OpenSteer -- Steering Behaviors for Autonomous Characters
//
// Copyright (c) 2002-2005, Sony Computer Entertainment America
// Original author: Craig Reynolds <craig_reynolds@playstation.sony.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//
// ----------------------------------------------------------------------------
//
// Utilities to work with Vec3.
//
// 05-12-05 bk: Created based on code of PolylinePathway.
//
// ----------------------------------------------------------------------------
#ifndef OPENSTEER_VEC3UTILITIES_H
#define OPENSTEER_VEC3UTILITIES_H
// Include OpenSteer::Vec3
#include "OpenSteer/Vec3.h"
// Include OpenSteer::size_t
#include "OpenSteer/StandardTypes.h"
// Include OpenSteer::equalsRelative
#include "OpenSteer/Utilities.h"
namespace OpenSteer {
/**
* Returns the nearest point on the segment @a segmentPoint0 to
* @a segmentPoint1 from @a point.
*/
OpenSteer::Vec3 nearestPointOnSegment( const Vec3& point,
const Vec3& segmentPoint0,
const Vec3& segmentPoint1 );
/**
* Computes minimum distance from @a point to the line segment defined by
* @a segmentPoint0 and @a segmentPoint1.
*/
float pointToSegmentDistance( const Vec3& point,
const Vec3& segmentPoint0,
const Vec3& segmentPoint1);
/**
* Retuns distance between @a a and @a b.
*/
inline float distance (const Vec3& a, const Vec3& b) {
return (a-b).length();
}
/**
* Elementwise relative tolerance comparison of @a lhs and @a rhs taking
* the range of the elements into account.
*
* See Christer Ericson, Real-Time Collision Detection, Morgan Kaufmann,
* 2005, pp. 441--443.
*
* @todo Rewrite using the stl or providing an own range based function.
*/
inline
bool
equalsRelative( Vec3 const& lhs,
Vec3 const& rhs,
float const& tolerance = std::numeric_limits< float >::epsilon() ) {
return equalsRelative( lhs.x, rhs.x, tolerance ) && equalsRelative( lhs.y, rhs.y ) && equalsRelative( lhs.z, rhs.z );
}
} // namespace OpenSteer
#endif // OPENSTEER_VEC3UTILITIES_H
+323
View File
@@ -0,0 +1,323 @@
/*
// ----------------------------------------------------------------------------
//
//
// OpenSteer -- Steering Behaviors for Autonomous Characters
//
// Copyright (c) 2002-2005, Sony Computer Entertainment America
// Original author: Craig Reynolds <craig_reynolds@playstation.sony.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// ----------------------------------------------------------------------------
*/
/* ------------------------------------------------------------------ */
/* */
/* Locality Query (LQ) Facility */
/* */
/* ------------------------------------------------------------------ */
/*
This utility is a spatial database which stores objects each of
which is associated with a 3d point (a location in a 3d space).
The points serve as the "search key" for the associated object.
It is intended to efficiently answer "sphere inclusion" queries,
also known as range queries: basically questions like:
Which objects are within a radius R of the location L?
In this context, "efficiently" means significantly faster than the
naive, brute force O(n) testing of all known points. Additionally
it is assumed that the objects move along unpredictable paths, so
that extensive preprocessing (for example, constructing a Delaunay
triangulation of the point set) may not be practical.
The implementation is a "bin lattice": a 3d rectangular array of
brick-shaped (rectangular parallelepipeds) regions of space. Each
region is represented by a pointer to a (possibly empty) doubly-
linked list of objects. All of these sub-bricks are the same
size. All bricks are aligned with the global coordinate axes.
Terminology used here: the region of space associated with a bin
is called a sub-brick. The collection of all sub-bricks is called
the super-brick. The super-brick should be specified to surround
the region of space in which (almost) all the key-points will
exist. If key-points move outside the super-brick everything will
continue to work, but without the speed advantage provided by the
spatial subdivision. For more details about how to specify the
super-brick's position, size and subdivisions see lqCreateDatabase
below.
Overview of usage: an application using this facility would first
create a database with lqCreateDatabase. For each client object
the application wants to put in the database it creates a
lqClientProxy and initializes it with lqInitClientProxy. When a
client object moves, the application calls lqUpdateForNewLocation.
To perform a query lqMapOverAllObjectsInLocality is passed an
application-supplied call-back function to be applied to all
client objects in the locality. See lqCallBackFunction below for
more detail. The lqFindNearestNeighborWithinRadius function can
be used to find a single nearest neighbor using the database.
Note that "locality query" is also known as neighborhood query,
neighborhood search, near neighbor search, and range query. For
additional information on this and related topics see:
http://www.red3d.com/cwr/boids/ips.html
For some description and illustrations of this database in use,
see this paper: http://www.red3d.com/cwr/papers/2000/pip.html
*/
#ifndef _lq_h
#define _lq_h
#ifdef __cplusplus
extern "C"
{
#endif
/* ------------------------------------------------------------------ */
/* */
/* Data types use by LQ */
/* */
/* ------------------------------------------------------------------ */
/* This structure represents the spatial database. Typically one of
these would be created (by a call to lqCreateDatabase) for a given
application. */
typedef struct lqInternalDB lqDB;
/* ------------------------------------------------------------------ */
/* This structure is a proxy for (and contains a pointer to) a client
(application) object in the spatial database. One of these exists
for each client object. This might be included within the
structure of a client object, or could be allocated separately. */
typedef struct lqClientProxy
{
/* previous object in this bin, or NULL */
struct lqClientProxy* prev;
/* next object in this bin, or NULL */
struct lqClientProxy* next;
/* bin ID (pointer to pointer to bin contents list) */
struct lqClientProxy** bin;
/* pointer to client object */
void* object;
/* the object's location ("key point") used for spatial sorting */
float x;
float y;
float z;
} lqClientProxy;
/* ------------------------------------------------------------------ */
/* */
/* Basic API */
/* */
/* ------------------------------------------------------------------ */
/* Allocate and initialize an LQ database, returns a pointer to it.
The application needs to call this before using the LQ facility.
The nine parameters define the properties of the "super-brick":
(1) origin: coordinates of one corner of the super-brick, its
minimum x, y and z extent.
(2) size: the width, height and depth of the super-brick.
(3) the number of subdivisions (sub-bricks) along each axis.
This routine also allocates the bin array, and initialize its
contents. */
lqDB* lqCreateDatabase (float originx, float originy, float originz,
float sizex, float sizey, float sizez,
int divx, int divy, int divz);
/* ------------------------------------------------------------------ */
/* Deallocates the LQ database */
void lqDeleteDatabase (lqDB*);
/* ------------------------------------------------------------------ */
/* The application needs to call this once on each lqClientProxy at
setup time to initialize its list pointers and associate the proxy
with its client object. */
void lqInitClientProxy (lqClientProxy* proxy, void* clientObject);
/* ------------------------------------------------------------------ */
/* Call for each client object every time its location changes. For
example, in an animation application, this would be called each
frame for every moving object. */
void lqUpdateForNewLocation (lqDB* lq,
lqClientProxy* object,
float x, float y, float z);
/* ------------------------------------------------------------------ */
/* Apply an application-specific function to all objects in a certain
locality. The locality is specified as a sphere with a given
center and radius. All objects whose location (key-point) is
within this sphere are identified and the function is applied to
them. The application-supplied function takes three arguments:
(1) a void* pointer to an lqClientProxy's "object".
(2) the square of the distance from the center of the search
locality sphere (x,y,z) to object's key-point.
(3) a void* pointer to the caller-supplied "client query state"
object -- typically NULL, but can be used to store state
between calls to the lqCallBackFunction.
This routine uses the LQ database to quickly reject any objects in
bins which do not overlap with the sphere of interest. Incremental
calculation of index values is used to efficiently traverse the
bins of interest. */
/* type for a pointer to a function used to map over client objects */
typedef void (* lqCallBackFunction) (void* clientObject,
float distanceSquared,
void* clientQueryState);
void lqMapOverAllObjectsInLocality (lqDB* lq,
float x, float y, float z,
float radius,
lqCallBackFunction func,
void* clientQueryState);
/* ------------------------------------------------------------------ */
/* */
/* Other API */
/* */
/* ------------------------------------------------------------------ */
/* Search the database to find the object whose key-point is nearest
to a given location yet within a given radius. That is, it finds
the object (if any) within a given search sphere which is nearest
to the sphere's center. The ignoreObject argument can be used to
exclude an object from consideration (or it can be NULL). This is
useful when looking for the nearest neighbor of an object in the
database, since otherwise it would be its own nearest neighbor.
The function returns a void* pointer to the nearest object, or
NULL if none is found. */
void* lqFindNearestNeighborWithinRadius (lqDB* lq,
float x, float y, float z,
float radius,
void* ignoreObject);
/* ------------------------------------------------------------------ */
/* Adds a given client object to a given bin, linking it into the bin
contents list. */
void lqAddToBin (lqClientProxy* object, lqClientProxy** bin);
/* ------------------------------------------------------------------ */
/* Removes a given client object from its current bin, unlinking it
from the bin contents list. */
void lqRemoveFromBin (lqClientProxy* object);
/* ------------------------------------------------------------------ */
/* Given an LQ database object and the nine basic parameters: fill in
the object's slots, allocate the bin array, and initialize its
contents. Normally the application does NOT call this directly, it
is called by lqCreateDatabase. */
void lqInitDatabase (lqDB* lq,
float originx, float originy, float originz,
float sizex, float sizey, float sizez,
int divx, int divy, int divz);
/* ------------------------------------------------------------------ */
/* Find the bin ID for a location in space. The location is given in
terms of its XYZ coordinates. The bin ID is a pointer to a pointer
to the bin contents list. */
lqClientProxy** lqBinForLocation (lqDB* lq, float x, float y, float z);
/* ------------------------------------------------------------------ */
/* Apply a user-supplied function to all objects in the database,
regardless of locality (cf lqMapOverAllObjectsInLocality) */
void lqMapOverAllObjects (lqDB* lq,
lqCallBackFunction func,
void* clientQueryState);
/* ------------------------------------------------------------------ */
/* Removes (all proxies for) all objects from all bins */
void lqRemoveAllObjects (lqDB* lq);
/* ------------------------------------------------------------------ */
/* Get statistics about bin populations: min, max and average of
non-empty bins. */
#ifndef NO_LQ_BIN_STATS
void lqGetBinPopulationStats (lqDB* lq,
int* min,
int* max,
float* average);
#endif /* NO_LQ_BIN_STATS */
/* ------------------------------------------------------------------ */
#ifndef NULL
#define NULL 0
#endif
/* ------------------------------------------------------------------ */
#ifdef __cplusplus
}
#endif
#endif /* _lq_h */
+5
View File
@@ -0,0 +1,5 @@
OpenSteer_0_8_2_source.zip
This is only a subset of OpenSteer; didn't want to add code that I don't use.
The docs are gone as well.
+310
View File
@@ -0,0 +1,310 @@
// ----------------------------------------------------------------------------
//
//
// OpenSteer -- Steering Behaviors for Autonomous Characters
//
// Copyright (c) 2002-2005, Sony Computer Entertainment America
// Original author: Craig Reynolds <craig_reynolds@playstation.sony.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//
// ----------------------------------------------------------------------------
//
//
// discrete time simulation clock for OpenSteerDemo
//
// Keeps track of real clock time and simulation time. Encapsulates OS's
// time API. Can be put in either "as fast as possible" variable time step
// mode (where simulation time steps are based on real time elapsed between
// updates), or in fixed "target FPS" mode where the simulation steps are
// constrained to start on 1/FPS boundaries (e.g. on a 60 hertz video game
// console). Also handles the notion of "pausing" simulation time.
//
// Usage: allocate a clock, set its "paused" or "targetFPS" parameters,
// then call updateGlobalSimulationClock before each simulation step.
//
// 10-04-04 bk: put everything into the OpenSteer namespace
// 09-24-02 cwr: major overhaul
// 06-26-02 cwr: created
//
//
// ----------------------------------------------------------------------------
#include "OpenSteer/Clock.h"
// ----------------------------------------------------------------------------
// XXX This is a bit ad hoc. Need to revisit conditionalization on operating
// XXX system. As of 5-5-03, this module knows about Win32 (code thanks to
// XXX Leaf Garland and Bruce Mitchener) and Linux/Unix (Craig's original
// XXX version). It tests for Xbox and Win32 and assumes Linux/Unix
// XXX otherwise.
#if defined (_XBOX)
#include <xtl.h>
#elif defined (_WIN32)
#include <windows.h>
#else
#include <sys/time.h>
#endif
// ----------------------------------------------------------------------------
// Constructor
OpenSteer::Clock::Clock (void)
{
// default is "real time, variable frame rate" and not paused
setFixedFrameRate (0);
setPausedState (false);
setAnimationMode (false);
setVariableFrameRateMode (true);
// real "wall clock" time since launch
totalRealTime = 0;
// time simulation has run
totalSimulationTime = 0;
// time spent paused
totalPausedTime = 0;
// sum of (non-realtime driven) advances to simulation time
totalAdvanceTime = 0;
// interval since last simulation time
elapsedSimulationTime = 0;
// interval since last clock update time
elapsedRealTime = 0;
// interval since last clock update,
// exclusive of time spent waiting for frame boundary when targetFPS>0
elapsedNonWaitRealTime = 0;
// "manually" advance clock by this amount on next update
newAdvanceTime = 0;
// "Calendar time" when this clock was first updated
#ifdef _WIN32
basePerformanceCounter = 0; // from QueryPerformanceCounter on Windows
#else
baseRealTimeSec = 0; // from gettimeofday on Linux and Mac OS X
baseRealTimeUsec = 0;
#endif
// clock keeps track of "smoothed" running average of recent frame rates.
// When a fixed frame rate is used, a running average of "CPU load" is
// kept (aka "non-wait time", the percentage of each frame time (time
// step) that the CPU is busy).
smoothedFPS = 0;
smoothedUsage = 0;
}
// ----------------------------------------------------------------------------
// update this clock, called once per simulation step ("frame") to:
//
// track passage of real time
// manage passage of simulation time (modified by Paused state)
// measure time elapsed between time updates ("frame rate")
// optionally: "wait" for next realtime frame boundary
void
OpenSteer::Clock::update (void)
{
// keep track of average frame rate and average usage percentage
updateSmoothedRegisters ();
// wait for next frame time (when targetFPS>0)
// XXX should this be at the end of the update function?
frameRateSync ();
// save previous real time to measure elapsed time
const float previousRealTime = totalRealTime;
// real "wall clock" time since this application was launched
totalRealTime = realTimeSinceFirstClockUpdate ();
// time since last clock update
elapsedRealTime = totalRealTime - previousRealTime;
// accumulate paused time
if (paused) totalPausedTime += elapsedRealTime;
// save previous simulation time to measure elapsed time
const float previousSimulationTime = totalSimulationTime;
// update total simulation time
if (getAnimationMode ())
{
// for "animation mode" use fixed frame time, ignore real time
const float frameDuration = 1.0f / getFixedFrameRate ();
totalSimulationTime += paused ? newAdvanceTime : frameDuration;
if (!paused) newAdvanceTime += frameDuration - elapsedRealTime;
}
else
{
// new simulation time is total run time minus time spent paused
totalSimulationTime = (totalRealTime
+ totalAdvanceTime
- totalPausedTime);
}
// update total "manual advance" time
totalAdvanceTime += newAdvanceTime;
// how much time has elapsed since the last simulation step?
elapsedSimulationTime = (paused ?
newAdvanceTime :
(totalSimulationTime - previousSimulationTime));
// reset advance amount
newAdvanceTime = 0;
}
// ----------------------------------------------------------------------------
// "wait" until next frame time (actually spin around this tight loop)
//
//
// (xxx there are probably a smarter ways to do this (using events or
// thread waits (eg usleep)) but they are likely to be unportable. xxx)
void
OpenSteer::Clock::frameRateSync (void)
{
// when in real time fixed frame rate mode
// (not animation mode and not variable frame rate mode)
if ((! getAnimationMode ()) && (! getVariableFrameRateMode ()))
{
// find next (real time) frame start time
const float targetStepSize = 1.0f / getFixedFrameRate ();
const float now = realTimeSinceFirstClockUpdate ();
const int lastFrameCount = (int) (now / targetStepSize);
const float nextFrameTime = (lastFrameCount + 1) * targetStepSize;
// record usage ("busy time", "non-wait time") for OpenSteerDemo app
elapsedNonWaitRealTime = now - totalRealTime;
// wait until next frame time
do {} while (realTimeSinceFirstClockUpdate () < nextFrameTime);
}
}
// ----------------------------------------------------------------------------
// force simulation time ahead, ignoring passage of real time.
// Used for OpenSteerDemo's "single step forward" and animation mode
float
OpenSteer::Clock::advanceSimulationTimeOneFrame (void)
{
// decide on what frame time is (use fixed rate, average for variable rate)
const float fps = (getVariableFrameRateMode () ?
getSmoothedFPS () :
getFixedFrameRate ());
const float frameTime = 1 / fps;
// bump advance time
advanceSimulationTime (frameTime);
// return the time value used (for OpenSteerDemo)
return frameTime;
}
void
OpenSteer::Clock::advanceSimulationTime (const float seconds)
{
if (seconds < 0) {
/// @todo - throw? how to handle error conditions? Not by crashing an app!
std::cerr << "negative arg to advanceSimulationTime - results will not be valid";
}
else
newAdvanceTime += seconds;
}
namespace {
// ----------------------------------------------------------------------------
// Returns the number of seconds of real time (represented as a float) since
// the clock was first updated.
//
// XXX Need to revisit conditionalization on operating system.
float
clockErrorExit (void)
{
/// @todo - throw? how to handle error conditions? Not by crashing an app!
std::cerr << "Problem reading system clock - results will not be valid";
return 0.0f;
}
} // anonymous namespace
float
OpenSteer::Clock::realTimeSinceFirstClockUpdate (void)
#ifdef _WIN32
{
// get time from Windows
LONGLONG counter, frequency;
bool clockOK = (QueryPerformanceCounter ((LARGE_INTEGER *)&counter) &&
QueryPerformanceFrequency ((LARGE_INTEGER *)&frequency));
if (!clockOK) return clockErrorExit ();
// ensure the base counter is recorded once after launch
if (basePerformanceCounter == 0) basePerformanceCounter = counter;
// real "wall clock" time since launch
const LONGLONG counterDifference = counter - basePerformanceCounter;
return ((float) counterDifference) / ((float)frequency);
}
#else
{
// get time from Linux (Unix, Mac OS X, ...)
timeval t;
if (gettimeofday (&t, 0) != 0) return clockErrorExit ();
// ensure the base time is recorded once after launch
if (baseRealTimeSec == 0)
{
baseRealTimeSec = t.tv_sec;
baseRealTimeUsec = t.tv_usec;
}
// real "wall clock" time since launch
return (( t.tv_sec - baseRealTimeSec) +
((t.tv_usec - baseRealTimeUsec) / 1000000.0f));
}
#endif
// ----------------------------------------------------------------------------
+213
View File
@@ -0,0 +1,213 @@
// ----------------------------------------------------------------------------
//
//
// OpenSteer -- Steering Behaviors for Autonomous Characters
//
// Copyright (c) 2002-2005, Sony Computer Entertainment America
// Original author: Craig Reynolds <craig_reynolds@playstation.sony.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//
// ----------------------------------------------------------------------------
//
//
// Vec3: OpenSteer's generic type for 3d vectors
//
// This file defines the class Vec3, which is used throughout OpenSteer to
// manipulate 3d geometric data. It includes standard vector operations (like
// vector addition, subtraction, scale, dot, cross...) and more idiosyncratic
// utility functions.
//
// When integrating OpenSteer into a preexisting 3d application, it may be
// important to use the 3d vector type of that application. In that case Vec3
// can be changed to inherit from the preexisting application' vector type and
// to match the interface used by OpenSteer to the interface provided by the
// preexisting 3d vector type.
//
// 10-04-04 bk: put everything into the OpenSteer namespace
// 03-26-03 cwr: created to replace for Hiranabe-san's execellent but larger
// vecmath package (http://objectclub.esm.co.jp/vecmath/)
//
//
// ----------------------------------------------------------------------------
#include "OpenSteer/Vec3.h"
// ----------------------------------------------------------------------------
// names for frequently used vector constants
const OpenSteer::Vec3 OpenSteer::Vec3::zero (0, 0, 0);
const OpenSteer::Vec3 OpenSteer::Vec3::up (0, 1, 0);
const OpenSteer::Vec3 OpenSteer::Vec3::forward (0, 0, 1);
// XXX This should be unified with LocalSpace::rightHanded, but I don't want
// XXX Vec3 to be based on LocalSpace which is based on Vec3. Perhaps there
// XXX should be a tiny chirality.h header to define a const? That could
// XXX then be included by both Vec3.h and LocalSpace.h
const OpenSteer::Vec3 OpenSteer::Vec3::side (-1, 0, 0);
// ----------------------------------------------------------------------------
// Returns a position randomly distributed inside a sphere of unit radius
// centered at the origin. Orientation will be random and length will range
// between 0 and 1
OpenSteer::Vec3
OpenSteer::RandomVectorInUnitRadiusSphere (void)
{
Vec3 v;
do
{
v.set ((frandom01()*2) - 1,
(frandom01()*2) - 1,
(frandom01()*2) - 1);
}
while (v.length() >= 1);
return v;
}
// ----------------------------------------------------------------------------
// Returns a position randomly distributed on a disk of unit radius
// on the XZ (Y=0) plane, centered at the origin. Orientation will be
// random and length will range between 0 and 1
OpenSteer::Vec3
OpenSteer::randomVectorOnUnitRadiusXZDisk (void)
{
Vec3 v;
do
{
v.set ((frandom01()*2) - 1,
0,
(frandom01()*2) - 1);
}
while (v.length() >= 1);
return v;
}
// ----------------------------------------------------------------------------
// Does a "ceiling" or "floor" operation on the angle by which a given vector
// deviates from a given reference basis vector. Consider a cone with "basis"
// as its axis and slope of "cosineOfConeAngle". The first argument controls
// whether the "source" vector is forced to remain inside or outside of this
// cone. Called by vecLimitMaxDeviationAngle and vecLimitMinDeviationAngle.
OpenSteer::Vec3
OpenSteer::vecLimitDeviationAngleUtility (const bool insideOrOutside,
const Vec3& source,
const float cosineOfConeAngle,
const Vec3& basis)
{
// immediately return zero length input vectors
float sourceLength = source.length();
if (sourceLength == 0) return source;
// measure the angular diviation of "source" from "basis"
const Vec3 direction = source / sourceLength;
float cosineOfSourceAngle = direction.dot (basis);
// Simply return "source" if it already meets the angle criteria.
// (note: we hope this top "if" gets compiled out since the flag
// is a constant when the function is inlined into its caller)
if (insideOrOutside)
{
// source vector is already inside the cone, just return it
if (cosineOfSourceAngle >= cosineOfConeAngle) return source;
}
else
{
// source vector is already outside the cone, just return it
if (cosineOfSourceAngle <= cosineOfConeAngle) return source;
}
// find the portion of "source" that is perpendicular to "basis"
const Vec3 perp = source.perpendicularComponent (basis);
// normalize that perpendicular
const Vec3 unitPerp = perp.normalize ();
// construct a new vector whose length equals the source vector,
// and lies on the intersection of a plane (formed the source and
// basis vectors) and a cone (whose axis is "basis" and whose
// angle corresponds to cosineOfConeAngle)
float perpDist = sqrtXXX (1 - (cosineOfConeAngle * cosineOfConeAngle));
const Vec3 c0 = basis * cosineOfConeAngle;
const Vec3 c1 = unitPerp * perpDist;
return (c0 + c1) * sourceLength;
}
// ----------------------------------------------------------------------------
// given a vector, return a vector perpendicular to it. arbitrarily selects
// one of the infinitely many perpendicular vectors. a zero vector maps to
// itself, otherwise length is irrelevant (empirically, output length seems to
// remain within 20% of input length).
OpenSteer::Vec3
OpenSteer::findPerpendicularIn3d (const Vec3& direction)
{
// to be filled in:
Vec3 quasiPerp; // a direction which is "almost perpendicular"
Vec3 result; // the computed perpendicular to be returned
// three mutually perpendicular basis vectors
const Vec3 i (1, 0, 0);
const Vec3 j (0, 1, 0);
const Vec3 k (0, 0, 1);
// measure the projection of "direction" onto each of the axes
const float id = i.dot (direction);
const float jd = j.dot (direction);
const float kd = k.dot (direction);
// set quasiPerp to the basis which is least parallel to "direction"
if ((id <= jd) && (id <= kd))
{
quasiPerp = i; // projection onto i was the smallest
}
else
{
if ((jd <= id) && (jd <= kd))
quasiPerp = j; // projection onto j was the smallest
else
quasiPerp = k; // projection onto k was the smallest
}
// return the cross product (direction x quasiPerp)
// which is guaranteed to be perpendicular to both of them
result.cross (direction, quasiPerp);
return result;
}
// ----------------------------------------------------------------------------
+88
View File
@@ -0,0 +1,88 @@
/**
* OpenSteer -- Steering Behaviors for Autonomous Characters
*
* Copyright (c) 2002-2005, Sony Computer Entertainment America
* Original author: Craig Reynolds <craig_reynolds@playstation.sony.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*
* @author Bjoern Knafla <bknafla@uni-kassel.de>
*/
#include "OpenSteer/Vec3Utilities.h"
// Include assert
#include <cassert>
// Include OpenSteer::clamp
#include "OpenSteer/Utilities.h"
/**
* @todo Is this useful?
std::pair< Vec3, Vec3 >
OpenSteer::convertPointAndSegmentToVectors( const Vec3& point,
const Vec3& segmentPoint0,
const Vec3& segmentPoint1 )
{
}
*/
OpenSteer::Vec3
OpenSteer::nearestPointOnSegment( const Vec3& point,
const Vec3& segmentPoint0,
const Vec3& segmentPoint1 )
{
// convert the test point to be "local" to ep0
Vec3 const local( point - segmentPoint0 );
// find the projection of "local" onto "segmentNormal"
Vec3 const segment( segmentPoint1 - segmentPoint0 );
float const segmentLength( segment.length() );
assert( 0 != segmentLength && "Segment mustn't be of length zero." );
Vec3 const segmentNormalized( segment / segmentLength );
float segmentProjection = segmentNormalized.dot (local);
segmentProjection = clamp( segmentProjection, 0.0f, segmentLength );
Vec3 result( segmentNormalized * segmentProjection );
result += segmentPoint0;
return result;
}
float
OpenSteer::pointToSegmentDistance ( const Vec3& point,
const Vec3& segmentPoint0,
const Vec3& segmentPoint1)
{
return distance( point, nearestPointOnSegment( point, segmentPoint0, segmentPoint1 ) );
}
+712
View File
@@ -0,0 +1,712 @@
/*
// ----------------------------------------------------------------------------
//
//
// OpenSteer -- Steering Behaviors for Autonomous Characters
//
// Copyright (c) 2002-2005, Sony Computer Entertainment America
// Original author: Craig Reynolds <craig_reynolds@playstation.sony.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// ----------------------------------------------------------------------------
*/
/* ------------------------------------------------------------------ */
/* */
/* Locality Query facility */
/* */
/* (by Craig Reynolds, see lq.h file for documentation) */
/* */
/* 5-17-99: created */
/* 5-20-99: found elusive "allocate 0 bins" bug */
/* 5-28-99: lqMapOverAllObjectsInLocality: clipped, incremental */
/* 6- 7-99: clean up, split off annotation stuff into debuglq.c */
/* 6- 8-99: tried screening by sum of coords ("first mean"?) but */
/* it was slightly slower, moved unused code to debuglq */
/* 10-19-99: Change lqClientObject, lqObject from: "struct x {};" to */
/* "typedef struct x {} x;" for EE compiler. */
/* 12- 2-00: Make lqObject "private" using lqInternalDB. */
/* 12- 5-00: Rename lqObject to lqDB, lqClientObject to lqClientProxy */
/* 12- 6-00: Change lqCallBackFunction from arglist of (void*) to: */
/* (void* clientObject, float distanceSquared, void* */
/* clientQueryState). Add void* clientQueryState arg to */
/* lqMapOverAllObjectsInLocality and its helper functions */
/* lqMapOverAllObjectsInLocalityClipped and */
/* lqMapOverAllOutsideObjects. Change macro */
/* lqTraverseBinClientObjectList to invoke callback */
/* function with three arguments, add "state" to its */
/* arglist. Remove extern lqDistanceSquared. */
/* 12- 7-00: Rename lqInitClientObject to lqInitClientProxy, make */
/* "func" be an argument to lqTraverseBinClientObjectList, */
/* add comments. */
/* 12- 8-00: Add lqFindNearestNeighborWithinRadius and related */
/* definitions: lqFindNearestHelper lqFindNearestState */
/* Add lqMapOverAllObjects and lqRemoveAllObjects (plus: */
/* lqMapOverAllObjectsInBin and lqRemoveAllObjectsInBin) */
/* */
/* ------------------------------------------------------------------ */
#include <stdlib.h>
#include <float.h>
#include <limits.h> /* for INT_MAX */
#include "OpenSteer/lq.h"
/* for debugging and graphical annotation (normally unused) */
#ifdef BOIDS_LQ_DEBUG
#include "OpenSteer/debuglq.c"
#endif
#ifndef WIN32
#define USUSED_PARAM __attribute__ ((unused))
#else
#define USUSED_PARAM
#endif
/* ------------------------------------------------------------------ */
/* This structure represents the spatial database. Typically one of
these would be created, by a call to lqCreateDatabase, for a given
application. */
typedef struct lqInternalDB
{
/* the origin is the super-brick corner minimum coordinates */
float originx, originy, originz;
/* length of the edges of the super-brick */
float sizex, sizey, sizez;
/* number of sub-brick divisions in each direction */
int divx, divy, divz;
/* pointer to an array of pointers, one for each bin */
lqClientProxy** bins;
/* extra bin for "everything else" (points outside super-brick) */
lqClientProxy* other;
} lqInternalDB;
/* ------------------------------------------------------------------ */
/* Allocate and initialize an LQ database, return a pointer to it.
The application needs to call this before using the LQ facility.
The nine parameters define the properties of the "super-brick":
(1) origin: coordinates of one corner of the super-brick, its
minimum x, y and z extent.
(2) size: the width, height and depth of the super-brick.
(3) the number of subdivisions (sub-bricks) along each axis.
This routine also allocates the bin array, and initialize its
contents. */
lqInternalDB* lqCreateDatabase (float originx, float originy, float originz,
float sizex, float sizey, float sizez,
int divx, int divy, int divz)
{
lqInternalDB* lq = ((lqInternalDB*) malloc (sizeof (lqInternalDB)));
lqInitDatabase (lq,
originx, originy, originz,
sizex, sizey, sizez,
divx, divy, divz);
return lq;
}
/* ------------------------------------------------------------------ */
/* Deallocate the memory used by the LQ database */
void lqDeleteDatabase(lqDB* lq)
{
free (lq->bins);
free (lq);
}
/* ------------------------------------------------------------------ */
/* Given an LQ database object and the nine basic parameters: fill in
the object's slots, allocate the bin array, and initialize its
contents. */
void lqInitDatabase (lqInternalDB* lq,
float originx, float originy, float originz,
float sizex, float sizey, float sizez,
int divx, int divy, int divz)
{
lq->originx = originx;
lq->originy = originy;
lq->originz = originz;
lq->sizex = sizex;
lq->sizey = sizey;
lq->sizez = sizez;
lq->divx = divx;
lq->divy = divy;
lq->divz = divz;
{
int i;
int bincount = divx * divy * divz;
int arraysize = sizeof (lqClientProxy*) * bincount;
lq->bins = (lqClientProxy**) malloc (arraysize);
for (i=0; i<bincount; i++) lq->bins[i] = NULL;
}
lq->other = NULL;
}
/* ------------------------------------------------------------------ */
/* Determine index into linear bin array given 3D bin indices */
#define lqBinCoordsToBinIndex(lq, ix, iy, iz) \
((ix * (lq)->divy * (lq)->divz) + (iy * (lq)->divz) + iz)
/* ------------------------------------------------------------------ */
/* Find the bin ID for a location in space. The location is given in
terms of its XYZ coordinates. The bin ID is a pointer to a pointer
to the bin contents list. */
lqClientProxy** lqBinForLocation (lqInternalDB* lq,
float x, float y, float z)
{
int i, ix, iy, iz;
/* if point outside super-brick, return the "other" bin */
if (x < lq->originx) return &(lq->other);
if (y < lq->originy) return &(lq->other);
if (z < lq->originz) return &(lq->other);
if (x >= lq->originx + lq->sizex) return &(lq->other);
if (y >= lq->originy + lq->sizey) return &(lq->other);
if (z >= lq->originz + lq->sizez) return &(lq->other);
/* if point inside super-brick, compute the bin coordinates */
ix = (int) (((x - lq->originx) / lq->sizex) * lq->divx);
iy = (int) (((y - lq->originy) / lq->sizey) * lq->divy);
iz = (int) (((z - lq->originz) / lq->sizez) * lq->divz);
/* convert to linear bin number */
i = lqBinCoordsToBinIndex (lq, ix, iy, iz);
/* return pointer to that bin */
return &(lq->bins[i]);
}
/* ------------------------------------------------------------------ */
/* The application needs to call this once on each lqClientProxy at
setup time to initialize its list pointers and associate the proxy
with its client object. */
void lqInitClientProxy (lqClientProxy* proxy, void* clientObject)
{
proxy->prev = NULL;
proxy->next = NULL;
proxy->bin = NULL;
proxy->object = clientObject;
}
/* ------------------------------------------------------------------ */
/* Adds a given client object to a given bin, linking it into the bin
contents list. */
void lqAddToBin (lqClientProxy* object, lqClientProxy** bin)
{
/* if bin is currently empty */
if (*bin == NULL)
{
object->prev = NULL;
object->next = NULL;
*bin = object;
}
else
{
object->prev = NULL;
object->next = *bin;
(*bin)->prev = object;
*bin = object;
}
/* record bin ID in proxy object */
object->bin = bin;
}
/* ------------------------------------------------------------------ */
/* Removes a given client object from its current bin, unlinking it
from the bin contents list. */
void lqRemoveFromBin (lqClientProxy* object)
{
/* adjust pointers if object is currently in a bin */
if (object->bin != NULL)
{
/* If this object is at the head of the list, move the bin
pointer to the next item in the list (might be NULL). */
if (*(object->bin) == object) *(object->bin) = object->next;
/* If there is a prev object, link its "next" pointer to the
object after this one. */
if (object->prev != NULL) object->prev->next = object->next;
/* If there is a next object, link its "prev" pointer to the
object before this one. */
if (object->next != NULL) object->next->prev = object->prev;
}
/* Null out prev, next and bin pointers of this object. */
object->prev = NULL;
object->next = NULL;
object->bin = NULL;
}
/* ------------------------------------------------------------------ */
/* Call for each client object every time its location changes. For
example, in an animation application, this would be called each
frame for every moving object. */
void lqUpdateForNewLocation (lqInternalDB* lq,
lqClientProxy* object,
float x, float y, float z)
{
/* find bin for new location */
lqClientProxy** newBin = lqBinForLocation (lq, x, y, z);
/* store location in client object, for future reference */
object->x = x;
object->y = y;
object->z = z;
/* has object moved into a new bin? */
if (newBin != object->bin)
{
lqRemoveFromBin (object);
lqAddToBin (object, newBin);
}
}
/* ------------------------------------------------------------------ */
/* Given a bin's list of client proxies, traverse the list and invoke
the given lqCallBackFunction on each object that falls within the
search radius. */
#define lqTraverseBinClientObjectList(co, radiusSquared, func, state) \
while (co != NULL) \
{ \
/* compute distance (squared) from this client */ \
/* object to given locality sphere's centerpoint */ \
float dx = x - co->x; \
float dy = y - co->y; \
float dz = z - co->z; \
float distanceSquared = (dx * dx) + (dy * dy) + (dz * dz); \
\
/* apply function if client object within sphere */ \
if (distanceSquared < radiusSquared) \
(*func) (co->object, distanceSquared, state); \
\
/* consider next client object in bin list */ \
co = co->next; \
}
/* ------------------------------------------------------------------ */
/* This subroutine of lqMapOverAllObjectsInLocality efficiently
traverses of subset of bins specified by max and min bin
coordinates. */
void lqMapOverAllObjectsInLocalityClipped (lqInternalDB* lq,
float x, float y, float z,
float radius,
lqCallBackFunction func,
void* clientQueryState,
int minBinX,
int minBinY,
int minBinZ,
int maxBinX,
int maxBinY,
int maxBinZ);
void lqMapOverAllObjectsInLocalityClipped (lqInternalDB* lq,
float x, float y, float z,
float radius,
lqCallBackFunction func,
void* clientQueryState,
int minBinX,
int minBinY,
int minBinZ,
int maxBinX,
int maxBinY,
int maxBinZ)
{
int i, j, k;
int iindex, jindex, kindex;
int slab = lq->divy * lq->divz;
int row = lq->divz;
int istart = minBinX * slab;
int jstart = minBinY * row;
int kstart = minBinZ;
lqClientProxy* co;
lqClientProxy** bin;
float radiusSquared = radius * radius;
#ifdef BOIDS_LQ_DEBUG
if (lqAnnoteEnable) drawBallGL (x, y, z, radius);
#endif
/* loop for x bins across diameter of sphere */
iindex = istart;
for (i = minBinX; i <= maxBinX; i++)
{
/* loop for y bins across diameter of sphere */
jindex = jstart;
for (j = minBinY; j <= maxBinY; j++)
{
/* loop for z bins across diameter of sphere */
kindex = kstart;
for (k = minBinZ; k <= maxBinZ; k++)
{
/* get current bin's client object list */
bin = &lq->bins[iindex + jindex + kindex];
co = *bin;
#ifdef BOIDS_LQ_DEBUG
if (lqAnnoteEnable) drawBin (lq, bin);
#endif
/* traverse current bin's client object list */
lqTraverseBinClientObjectList (co,
radiusSquared,
func,
clientQueryState);
kindex += 1;
}
jindex += row;
}
iindex += slab;
}
}
/* ------------------------------------------------------------------ */
/* If the query region (sphere) extends outside of the "super-brick"
we need to check for objects in the catch-all "other" bin which
holds any object which are not inside the regular sub-bricks */
void lqMapOverAllOutsideObjects (lqInternalDB* lq,
float x, float y, float z,
float radius,
lqCallBackFunction func,
void* clientQueryState);
void lqMapOverAllOutsideObjects (lqInternalDB* lq,
float x, float y, float z,
float radius,
lqCallBackFunction func,
void* clientQueryState)
{
lqClientProxy* co = lq->other;
float radiusSquared = radius * radius;
/* traverse the "other" bin's client object list */
lqTraverseBinClientObjectList (co,
radiusSquared,
func,
clientQueryState);
}
/* ------------------------------------------------------------------ */
/* Apply an application-specific function to all objects in a certain
locality. The locality is specified as a sphere with a given
center and radius. All objects whose location (key-point) is
within this sphere are identified and the function is applied to
them. The application-supplied function takes three arguments:
(1) a void* pointer to an lqClientProxy's "object".
(2) the square of the distance from the center of the search
locality sphere (x,y,z) to object's key-point.
(3) a void* pointer to the caller-supplied "client query state"
object -- typically NULL, but can be used to store state
between calls to the lqCallBackFunction.
This routine uses the LQ database to quickly reject any objects in
bins which do not overlap with the sphere of interest. Incremental
calculation of index values is used to efficiently traverse the
bins of interest. */
void lqMapOverAllObjectsInLocality (lqInternalDB* lq,
float x, float y, float z,
float radius,
lqCallBackFunction func,
void* clientQueryState)
{
int partlyOut = 0;
int completelyOutside =
(((x + radius) < lq->originx) ||
((y + radius) < lq->originy) ||
((z + radius) < lq->originz) ||
((x - radius) >= lq->originx + lq->sizex) ||
((y - radius) >= lq->originy + lq->sizey) ||
((z - radius) >= lq->originz + lq->sizez));
int minBinX, minBinY, minBinZ, maxBinX, maxBinY, maxBinZ;
/* is the sphere completely outside the "super brick"? */
if (completelyOutside)
{
lqMapOverAllOutsideObjects (lq, x, y, z, radius, func,
clientQueryState);
return;
}
/* compute min and max bin coordinates for each dimension */
minBinX = (int) ((((x - radius) - lq->originx) / lq->sizex) * lq->divx);
minBinY = (int) ((((y - radius) - lq->originy) / lq->sizey) * lq->divy);
minBinZ = (int) ((((z - radius) - lq->originz) / lq->sizez) * lq->divz);
maxBinX = (int) ((((x + radius) - lq->originx) / lq->sizex) * lq->divx);
maxBinY = (int) ((((y + radius) - lq->originy) / lq->sizey) * lq->divy);
maxBinZ = (int) ((((z + radius) - lq->originz) / lq->sizez) * lq->divz);
/* clip bin coordinates */
if (minBinX < 0) {partlyOut = 1; minBinX = 0;}
if (minBinY < 0) {partlyOut = 1; minBinY = 0;}
if (minBinZ < 0) {partlyOut = 1; minBinZ = 0;}
if (maxBinX >= lq->divx) {partlyOut = 1; maxBinX = lq->divx - 1;}
if (maxBinY >= lq->divy) {partlyOut = 1; maxBinY = lq->divy - 1;}
if (maxBinZ >= lq->divz) {partlyOut = 1; maxBinZ = lq->divz - 1;}
/* map function over outside objects if necessary (if clipped) */
if (partlyOut)
lqMapOverAllOutsideObjects (lq, x, y, z, radius, func,
clientQueryState);
/* map function over objects in bins */
lqMapOverAllObjectsInLocalityClipped (lq,
x, y, z,
radius,
func,
clientQueryState,
minBinX, minBinY, minBinZ,
maxBinX, maxBinY, maxBinZ);
}
/* ------------------------------------------------------------------ */
/* internal helper function */
typedef struct lqFindNearestState
{
void* ignoreObject;
void* nearestObject;
float minDistanceSquared;
} lqFindNearestState;
void lqFindNearestHelper (void* clientObject,
float distanceSquared,
void* clientQueryState);
void lqFindNearestHelper (void* clientObject,
float distanceSquared,
void* clientQueryState)
{
lqFindNearestState* fns = (lqFindNearestState*) clientQueryState;
/* do nothing if this is the "ignoreObject" */
if (fns->ignoreObject != clientObject)
{
/* record this object if it is the nearest one so far */
if (fns->minDistanceSquared > distanceSquared)
{
fns->nearestObject = clientObject;
fns->minDistanceSquared = distanceSquared;
}
}
}
/* ------------------------------------------------------------------ */
/* Search the database to find the object whose key-point is nearest
to a given location yet within a given radius. That is, it finds
the object (if any) within a given search sphere which is nearest
to the sphere's center. The ignoreObject argument can be used to
exclude an object from consideration (or it can be NULL). This is
useful when looking for the nearest neighbor of an object in the
database, since otherwise it would be its own nearest neighbor.
The function returns a void* pointer to the nearest object, or
NULL if none is found. */
void* lqFindNearestNeighborWithinRadius (lqInternalDB* lq,
float x, float y, float z,
float radius,
void* ignoreObject)
{
/* initialize search state */
lqFindNearestState lqFNS;
lqFNS.nearestObject = NULL;
lqFNS.ignoreObject = ignoreObject;
lqFNS.minDistanceSquared = FLT_MAX;
/* map search helper function over all objects within radius */
lqMapOverAllObjectsInLocality (lq,
x, y, z,
radius,
lqFindNearestHelper,
&lqFNS);
/* return nearest object found, if any */
return lqFNS.nearestObject;
}
/* ------------------------------------------------------------------ */
/* internal helper function */
void lqMapOverAllObjectsInBin (lqClientProxy* binProxyList,
lqCallBackFunction func,
void* clientQueryState);
void lqMapOverAllObjectsInBin (lqClientProxy* binProxyList,
lqCallBackFunction func,
void* clientQueryState)
{
/* walk down proxy list, applying call-back function to each one */
while (binProxyList != NULL)
{
(*func) (binProxyList->object, 0, clientQueryState);
binProxyList = binProxyList->next;
}
}
/* ------------------------------------------------------------------ */
/* Apply a user-supplied function to all objects in the database,
regardless of locality (cf lqMapOverAllObjectsInLocality) */
void lqMapOverAllObjects (lqInternalDB* lq,
lqCallBackFunction func,
void* clientQueryState)
{
int i;
int bincount = lq->divx * lq->divy * lq->divz;
for (i=0; i<bincount; i++)
{
lqMapOverAllObjectsInBin (lq->bins[i], func, clientQueryState);
}
lqMapOverAllObjectsInBin (lq->other, func, clientQueryState);
}
/* ------------------------------------------------------------------ */
/* looks at all bins (except "other") finding the min and max bin
populations and the average of NON-EMPTY bin populations. (The
average over all bins is a constant (population/bincount)) */
#ifndef NO_LQ_BIN_STATS
void lqgbpsCounter (void* clientObject USUSED_PARAM,
float distanceSquared USUSED_PARAM,
void* clientQueryState);
void lqgbpsCounter (void* clientObject USUSED_PARAM,
float distanceSquared USUSED_PARAM,
void* clientQueryState)
{
(*(int*)clientQueryState)++;
}
void lqGetBinPopulationStats (lqInternalDB* lq,
int* min,
int* max,
float* average)
{
int minPop = INT_MAX;
int maxPop = 0;
int totalCount = 0;
int nonEmptyBinCount = 0;
int bincount = lq->divx * lq->divy * lq->divz;
int i;
for (i=0; i<bincount; i++)
{
/* clear the counter */
int objectCount = 0;
/* apply counting function to each object in bin[i] */
lqMapOverAllObjectsInBin (lq->bins[i], lqgbpsCounter, &objectCount);
/* collect data: max and min population, count objects and non-empty bins */
if (objectCount > 0)
{
nonEmptyBinCount++;
if (maxPop < objectCount) maxPop = objectCount;
if (minPop > objectCount) minPop = objectCount;
totalCount += objectCount;
}
}
/* set return values */
*min = minPop;
*max = maxPop;
*average = ((float) totalCount) / ((float) nonEmptyBinCount);
}
#endif /* NO_LQ_BIN_STATS */
/* ------------------------------------------------------------------ */
/* internal helper function */
#define lqRemoveAllObjectsInBin(bin) \
while ((bin) != NULL) lqRemoveFromBin ((bin));
/* ------------------------------------------------------------------ */
/* Removes (all proxies for) all objects from all bins */
void lqRemoveAllObjects (lqInternalDB* lq)
{
int i;
int bincount = lq->divx * lq->divy * lq->divz;
for (i=0; i<bincount; i++)
{
lqRemoveAllObjectsInBin (lq->bins[i]);
}
lqRemoveAllObjectsInBin (lq->other);
}
/* ------------------------------------------------------------------ */