This commit is contained in:
romkazvo
2023-08-07 19:29:24 +08:00
commit 34d6c5d489
4832 changed files with 1389451 additions and 0 deletions

257
CryCommon/AABBSV.h Normal file
View File

@@ -0,0 +1,257 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek CryENGINE Source code
//
// File:AABBSV.h
// Description: shadow volume AABB functionality for overlap testings
//
// History:
// -Feb 15,2004:Created by Michael Glueck, code provided by Ivo Herzeg
//
//////////////////////////////////////////////////////////////////////
#ifndef AABBSV_H
#define AABBSV_H
#if _MSC_VER > 1000
# pragma once
#endif
#include "Cry_Geo.h"
struct Shadowvolume
{
uint32 sideamount;
uint32 nplanes;
Plane oplanes[10];
};
namespace NAABB_SV
{
//***************************************************************************************
//***************************************************************************************
//*** Calculate a ShadowVolume using an AABB and a point-light ***
//***************************************************************************************
//*** The planes of the AABB facing away from the point-light are the far-planes ***
//*** of the ShadowVolume. There can be 3-6 far-planes. ***
//***************************************************************************************
void AABB_ReceiverShadowVolume(const Vec3& PointLight, const AABB& Occluder, Shadowvolume &sv);
//***************************************************************************************
//***************************************************************************************
//*** Calculate a ShadowVolume using an AABB and a point-light ***
//***************************************************************************************
//*** The planes of the AABB facing the point-light are the near-planes of the ***
//*** the ShadowVolume. There can be 1-3 near-planes. ***
//*** The far-plane is defined by lightrange. ***
//***************************************************************************************
void AABB_ShadowVolume(const Vec3& PointLight, const AABB& Occluder, Shadowvolume &sv, f32 lightrange);
//***************************************************************************************
//*** this is the "fast" version to check if an AABB is overlapping a shadowvolume ***
//***************************************************************************************
bool Is_AABB_In_ShadowVolume( const Shadowvolume &sv, const AABB& Receiver );
//***************************************************************************************
//*** this is the "hierarchical" check ***
//***************************************************************************************
char Is_AABB_In_ShadowVolume_hierarchical( const Shadowvolume &sv, const AABB& Receiver );
}
inline void NAABB_SV::AABB_ReceiverShadowVolume(const Vec3& PointLight, const AABB& Occluder, Shadowvolume &sv)
{
sv.sideamount=0;
sv.nplanes=0;
//------------------------------------------------------------------------------
//-- check if PointLight is in front of any occluder plane or inside occluder --
//------------------------------------------------------------------------------
uint32 front=0;
if (PointLight.x<Occluder.min.x) front|=0x01;
if (PointLight.x>Occluder.max.x) front|=0x02;
if (PointLight.y<Occluder.min.y) front|=0x04;
if (PointLight.y>Occluder.max.y) front|=0x08;
if (PointLight.z<Occluder.min.z) front|=0x10;
if (PointLight.z>Occluder.max.z) front|=0x20;
sv.sideamount = BoxSides[(front<<3)+7];
uint32 back = front^0x3f;
if (back&0x01) { sv.oplanes[sv.nplanes].SetPlane(Vec3(-1,+0,+0),Occluder.min); sv.nplanes++; }
if (back&0x02) { sv.oplanes[sv.nplanes].SetPlane(Vec3(+1,+0,+0),Occluder.max); sv.nplanes++; }
if (back&0x04) { sv.oplanes[sv.nplanes].SetPlane(Vec3(+0,-1,+0),Occluder.min); sv.nplanes++; }
if (back&0x08) { sv.oplanes[sv.nplanes].SetPlane(Vec3(+0,+1,+0),Occluder.max); sv.nplanes++; }
if (back&0x10) { sv.oplanes[sv.nplanes].SetPlane(Vec3(+0,+0,-1),Occluder.min); sv.nplanes++; }
if (back&0x20) { sv.oplanes[sv.nplanes].SetPlane(Vec3(+0,+0,+1),Occluder.max); sv.nplanes++; }
if (front==0) return; //light is inside occluder
//all 8 vertices of a AABB
Vec3 o[8] =
{
Vec3(Occluder.min.x,Occluder.min.y,Occluder.min.z),
Vec3(Occluder.max.x,Occluder.min.y,Occluder.min.z),
Vec3(Occluder.min.x,Occluder.max.y,Occluder.min.z),
Vec3(Occluder.max.x,Occluder.max.y,Occluder.min.z),
Vec3(Occluder.min.x,Occluder.min.y,Occluder.max.z),
Vec3(Occluder.max.x,Occluder.min.y,Occluder.max.z),
Vec3(Occluder.min.x,Occluder.max.y,Occluder.max.z),
Vec3(Occluder.max.x,Occluder.max.y,Occluder.max.z)
};
//---------------------------------------------------------------------
//--- find the silhouette-vertices of the occluder-AABB ---
//---------------------------------------------------------------------
uint32 p0 = BoxSides[(front<<3)+0];
uint32 p1 = BoxSides[(front<<3)+1];
uint32 p2 = BoxSides[(front<<3)+2];
uint32 p3 = BoxSides[(front<<3)+3];
uint32 p4 = BoxSides[(front<<3)+4];
uint32 p5 = BoxSides[(front<<3)+5];
if(sv.sideamount==4)
{
sv.oplanes[sv.nplanes+0] = GetPlane( o[p1],o[p0], PointLight );
sv.oplanes[sv.nplanes+1] = GetPlane( o[p2],o[p1], PointLight );
sv.oplanes[sv.nplanes+2] = GetPlane( o[p3],o[p2], PointLight );
sv.oplanes[sv.nplanes+3] = GetPlane( o[p0],o[p3], PointLight );
}
if(sv.sideamount==6)
{
sv.oplanes[sv.nplanes+0] = GetPlane( o[p1],o[p0], PointLight );
sv.oplanes[sv.nplanes+1] = GetPlane( o[p2],o[p1], PointLight );
sv.oplanes[sv.nplanes+2] = GetPlane( o[p3],o[p2], PointLight );
sv.oplanes[sv.nplanes+3] = GetPlane( o[p4],o[p3], PointLight );
sv.oplanes[sv.nplanes+4] = GetPlane( o[p5],o[p4], PointLight );
sv.oplanes[sv.nplanes+5] = GetPlane( o[p0],o[p5], PointLight );
}
}
inline void NAABB_SV::AABB_ShadowVolume(const Vec3& PointLight, const AABB& Occluder, Shadowvolume &sv, f32 lightrange)
{
sv.sideamount=0;
sv.nplanes=0;
//------------------------------------------------------------------------------
//-- check if PointLight is in front of any occluder plane or inside occluder --
//------------------------------------------------------------------------------
uint32 front=0;
if (PointLight.x<Occluder.min.x) front|=0x01;
if (PointLight.x>Occluder.max.x) front|=0x02;
if (PointLight.y<Occluder.min.y) front|=0x04;
if (PointLight.y>Occluder.max.y) front|=0x08;
if (PointLight.z<Occluder.min.z) front|=0x10;
if (PointLight.z>Occluder.max.z) front|=0x20;
if (front==0) return; //light is inside occluder
sv.sideamount = BoxSides[(front<<3)+7];
if (front&0x01) { sv.oplanes[sv.nplanes].SetPlane(Vec3(-1,+0,+0),Occluder.min); sv.nplanes++; }
if (front&0x02) { sv.oplanes[sv.nplanes].SetPlane(Vec3(+1,+0,+0),Occluder.max); sv.nplanes++; }
if (front&0x04) { sv.oplanes[sv.nplanes].SetPlane(Vec3(+0,-1,+0),Occluder.min); sv.nplanes++; }
if (front&0x08) { sv.oplanes[sv.nplanes].SetPlane(Vec3(+0,+1,+0),Occluder.max); sv.nplanes++; }
if (front&0x10) { sv.oplanes[sv.nplanes].SetPlane(Vec3(+0,+0,-1),Occluder.min); sv.nplanes++; }
if (front&0x20) { sv.oplanes[sv.nplanes].SetPlane(Vec3(+0,+0,+1),Occluder.max); sv.nplanes++; }
//all 8 vertices of a AABB
Vec3 o[8] =
{
Vec3(Occluder.min.x,Occluder.min.y,Occluder.min.z),
Vec3(Occluder.max.x,Occluder.min.y,Occluder.min.z),
Vec3(Occluder.min.x,Occluder.max.y,Occluder.min.z),
Vec3(Occluder.max.x,Occluder.max.y,Occluder.min.z),
Vec3(Occluder.min.x,Occluder.min.y,Occluder.max.z),
Vec3(Occluder.max.x,Occluder.min.y,Occluder.max.z),
Vec3(Occluder.min.x,Occluder.max.y,Occluder.max.z),
Vec3(Occluder.max.x,Occluder.max.y,Occluder.max.z)
};
//---------------------------------------------------------------------
//--- find the silhouette-vertices of the occluder-AABB ---
//---------------------------------------------------------------------
uint32 p0 = BoxSides[(front<<3)+0];
uint32 p1 = BoxSides[(front<<3)+1];
uint32 p2 = BoxSides[(front<<3)+2];
uint32 p3 = BoxSides[(front<<3)+3];
uint32 p4 = BoxSides[(front<<3)+4];
uint32 p5 = BoxSides[(front<<3)+5];
//the new center-position in world-space
Vec3 MiddleOfOccluder = (Occluder.max+Occluder.min)*0.5f;
sv.oplanes[sv.nplanes] = GetPlane( GetNormalized(MiddleOfOccluder-PointLight),GetNormalized(MiddleOfOccluder-PointLight)*lightrange+PointLight );
sv.nplanes++;
if(sv.sideamount==4)
{
sv.oplanes[sv.nplanes+0] = GetPlane( o[p1],o[p0], PointLight );
sv.oplanes[sv.nplanes+1] = GetPlane( o[p2],o[p1], PointLight );
sv.oplanes[sv.nplanes+2] = GetPlane( o[p3],o[p2], PointLight );
sv.oplanes[sv.nplanes+3] = GetPlane( o[p0],o[p3], PointLight );
}
if(sv.sideamount==6)
{
sv.oplanes[sv.nplanes+0] = GetPlane( o[p1],o[p0], PointLight );
sv.oplanes[sv.nplanes+1] = GetPlane( o[p2],o[p1], PointLight );
sv.oplanes[sv.nplanes+2] = GetPlane( o[p3],o[p2], PointLight );
sv.oplanes[sv.nplanes+3] = GetPlane( o[p4],o[p3], PointLight );
sv.oplanes[sv.nplanes+4] = GetPlane( o[p5],o[p4], PointLight );
sv.oplanes[sv.nplanes+5] = GetPlane( o[p0],o[p5], PointLight );
}
}
inline bool NAABB_SV::Is_AABB_In_ShadowVolume( const Shadowvolume &sv, const AABB& Receiver )
{
uint32 pa=sv.sideamount+sv.nplanes;
f32 d;
const Vec3* pAABB=&Receiver.min;
//------------------------------------------------------------------------------
//---- check if receiver-AABB is in front of any of these planes ------
//------------------------------------------------------------------------------
for (uint32 x=0; x<pa; x++)
{
d=sv.oplanes[x].d;
d += sv.oplanes[x].n.x * pAABB[(*((uint32*)&sv.oplanes[x].n.x)>>31)].x;
d += sv.oplanes[x].n.y * pAABB[(*((uint32*)&sv.oplanes[x].n.y)>>31)].y;
d += sv.oplanes[x].n.z * pAABB[(*((uint32*)&sv.oplanes[x].n.z)>>31)].z;
if (d>0) return CULL_EXCLUSION;
}
return CULL_OVERLAP;
}
inline char NAABB_SV::Is_AABB_In_ShadowVolume_hierarchical( const Shadowvolume &sv, const AABB& Receiver )
{
uint32 pa=sv.sideamount+sv.nplanes;
const Vec3* pAABB=&Receiver.min;
f32 dot1,dot2;
uint32 notOverlap = 0x80000000; // will be reset to 0 if there's at least one overlapping
//------------------------------------------------------------------------------
//---- check if receiver-AABB is in front of any of these planes ------
//------------------------------------------------------------------------------
for (uint32 x=0; x<pa; x++)
{
dot1=dot2=sv.oplanes[x].d;
dot1 += sv.oplanes[x].n.x * pAABB[0+(*((uint32*)&sv.oplanes[x].n.x)>>31)].x;
dot2 += sv.oplanes[x].n.x * pAABB[1-(*((uint32*)&sv.oplanes[x].n.x)>>31)].x;
dot1 += sv.oplanes[x].n.y * pAABB[0+(*((uint32*)&sv.oplanes[x].n.y)>>31)].y;
dot2 += sv.oplanes[x].n.y * pAABB[1-(*((uint32*)&sv.oplanes[x].n.y)>>31)].y;
dot1 += sv.oplanes[x].n.z * pAABB[0+(*((uint32*)&sv.oplanes[x].n.z)>>31)].z;
dot2 += sv.oplanes[x].n.z * pAABB[1-(*((uint32*)&sv.oplanes[x].n.z)>>31)].z;
if ( !(((int32&)dot1)&0x80000000) ) return CULL_EXCLUSION;
notOverlap &= (int32&)dot2;
}
if (notOverlap) return CULL_INCLUSION;
return CULL_OVERLAP;
}
#endif

94
CryCommon/AgentParams.h Normal file
View File

@@ -0,0 +1,94 @@
#ifndef _AGENTPARAMS_H_
#define _AGENTPARAMS_H_
typedef struct AgentParameters
{
//-------------
// ranges
//----------------
// sensors:
// sight
float m_fSightRange; // how far can the agent see
float m_fHorizontalFov;
float m_fGravityMultiplier;
float m_fAccuracy;
float m_fOriginalAccuracy;
float m_fResponsiveness;
float m_fMaxHealth;
// sound
float m_fSoundRange; // how far can agent hear
// behaviour
float m_fAttackRange;
float m_fCommRange;
//-----------
// indices
//-------------
float m_fAggression;
float m_fOriginalAggression;
float m_fCohesion;
float m_fPersistence;
//-----------
// hostility data
//------------
float m_fSpeciesHostility;
float m_fGroupHostility;
float m_fMeleeDistance;
//-------------
// grouping data
//--------------
int m_nSpecies;
int m_nGroup;
bool m_bIgnoreTargets;
bool m_bPerceivePlayer;
bool m_bAwareOfPlayerTargeting;
bool m_bSpecial;
bool m_bSmartMelee;
AgentParameters()
{
m_bSmartMelee = true;
m_bSpecial = false;
m_fSightRange=0;
m_fHorizontalFov=0;
m_fGravityMultiplier=1.f;
m_fAccuracy=0;
m_fResponsiveness=0;
m_fMaxHealth=0;
m_fSoundRange=0;
m_fAttackRange=0;
m_fCommRange=0;
m_fAggression=0;
m_fCohesion=0;
m_fPersistence=0;
m_fSpeciesHostility=0;
m_fGroupHostility=0;
m_nSpecies=0;
m_nGroup=0;
m_fMeleeDistance = 2.f;
m_bIgnoreTargets=false;
m_bPerceivePlayer=true;
m_bAwareOfPlayerTargeting=false;
}
} AgentParameters;
#endif _AGENTPARAMS_H_

222
CryCommon/AnimKey.h Normal file
View File

@@ -0,0 +1,222 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2001.
// -------------------------------------------------------------------------
// File name: animkey.cpp
// Version: v1.00
// Created: 22/4/2002 by Timur.
// Compilers: Visual C++ 7.0
// Description:
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#ifndef __animkey_h__
#define __animkey_h__
#if _MSC_VER > 1000
#pragma once
#endif
struct ISound;
enum EAnimKeyFlags
{
//! This key is selected in track view.
AKEY_SELECTED = 0x01,
};
//! Interface to animation key.
//! Not real interface though...
//! No virtuals for optimization reason.
struct IKey
{
float time;
int flags;
// compare keys.
bool operator<( const IKey &key ) const { return time < key.time; }
bool operator==( const IKey &key ) const { return time == key.time; }
bool operator>( const IKey &key ) const { return time > key.time; }
bool operator<=( const IKey &key ) const { return time <= key.time; }
bool operator>=( const IKey &key ) const { return time >= key.time; }
bool operator!=( const IKey &key ) const { return time != key.time; }
protected:
//! Protect from direct instantiation of this class.
//! Only derived classes can be created,
IKey() :time(0),flags(0) {};
};
/** ITcbKey used in all TCB tracks.
*/
struct ITcbKey : public IKey
{
// Values.
float fval[4];
// Key controls.
float tens; //!< Key tension value.
float cont; //!< Key continuity value.
float bias; //!< Key bias value.
float easeto; //!< Key ease to value.
float easefrom; //!< Key ease from value.
//! Protect from direct instantiation of this class.
//! Only derived classes can be created,
ITcbKey() {
fval[0] = 0; fval[1] = 0; fval[2] = 0; fval[3] = 0;
tens = 0, cont = 0, bias = 0, easeto = 0, easefrom = 0;
};
template <class T>
void SetValue( const T& val ) { *((T*)fval) = val; };
template <class T>
void GetValue( T& val ) { val = *((T*)fval); };
void SetFloat( float val ) { SetValue(val); };
void SetVec3( const Vec3 &val ) { SetValue(val); };
void SetQuat( const Quat &val ) { SetValue(val); };
float GetFloat() const { return *((float*)fval); };
const Vec3& GetVec3() const { return *((Vec3*)fval); };
const Quat& GetQuat() const { return *((Quat*)fval); };
};
/** IEntityKey used in Entity track.
*/
struct IEventKey : public IKey
{
char event[64];
char animation[64];
float duration;
IEventKey()
{
event[0] = '\0'; // empty string.
animation[0] = '\0'; // empty string.
duration = 0;
}
};
/** ISelectKey used in Camera selection track or Scene node.
*/
struct ISelectKey : public IKey
{
char szSelection[128]; //!< Node name.
float fDuration;
ISelectKey()
{
fDuration = 0;
szSelection[0] = '\0'; // empty string.
}
};
/** ISoundKey used in sound track.
*/
struct ISoundKey : public IKey
{
char pszFilename[128];
unsigned char nVolume;
unsigned char nPan;
float inRadius;
float outRadius;
bool bStream; //!< Stream sound from disk.
bool b3DSound; //!< 3D or Stereo sound.
bool bLoop; //!< Loop sound.
float fDuration;
char description[32];
ISoundKey()
{
b3DSound = false;
inRadius = 10;
outRadius = 100;
bStream = false;
bLoop = false;
pszFilename[0]=0;
nVolume=255;
nPan=127;
fDuration=0.0f;
description[0] = 0;
}
};
/** ICharacterKey used in Character animation track.
*/
struct ICharacterKey : public IKey
{
char animation[64]; //!< Name of character animation.
float duration; //!< Duration in seconds of this animation.
float startTime; //!< Start time of this animtion (Offset from begining of animation).
float blendTime; //!< Blending time for this animation.
float speed; //!< Speed multiplier for this key.
bool bLoop; //!< True if animation must be looped.
bool bUnload; //!< Unload after sequence is finished
ICharacterKey() {
animation[0] = '\0'; duration = 0; blendTime = 0; startTime = 0; speed = 1;
bLoop = false;
bUnload = false;
}
};
/** IExprKey used in expression animation track.
*/
struct IExprKey : public IKey
{
IExprKey()
{
pszName[0]=0;
fAmp=1.0f;
fBlendIn=0.5f;
fHold=1.0f;
fBlendOut=0.5f;
}
char pszName[128]; //!< Name of morph-target
float fAmp;
float fBlendIn;
float fHold;
float fBlendOut;
};
/** IConsoleKey used in Console track, triggers console commands and variables.
*/
struct IConsoleKey : public IKey
{
char command[64];
IConsoleKey()
{
command[0] = '\0';
}
};
enum EMusicKeyType
{
eMusicKeyType_SetMood=0,
eMusicKeyType_VolumeRamp
};
/** IMusicKey used in music track.
*/
struct IMusicKey : public IKey
{
EMusicKeyType eType;
char szMood[64];
float fTime;
float fDuration;
char description[32];
IMusicKey()
{
eType=eMusicKeyType_SetMood;
szMood[0]=0;
fTime=0.0f;
fDuration=0.0f;
description[0]=0;
}
};
#endif // __animkey_h__

30
CryCommon/CRE2DQuad.h Normal file
View File

@@ -0,0 +1,30 @@
#ifndef _CRE2DQuad_H_
#define _CRE2DQuad_H_
#include "vertexformats.h"
class CRE2DQuad: public CRendElement
{
friend class CRender3D;
public:
CRE2DQuad()
{
mfSetType(eDATA_2DQuad);
mfUpdateFlags(FCEF_TRANSFORM);
}
virtual ~CRE2DQuad()
{
}
virtual void mfPrepare();
virtual bool mfDraw(SShader *ef, SShaderPass *sfm);
virtual void *mfGetPointer(ESrcPointer ePT, int *Stride, int Type, ESrcPointer Dst, int Flags);
struct_VERTEX_FORMAT_P3F_TEX2F m_arrVerts[4];
};
#endif _CRE2DQuad_H_

27
CryCommon/CREDummy.h Normal file
View File

@@ -0,0 +1,27 @@
#ifndef __CREDUMMY_H__
#define __CREDUMMY_H__
//=============================================================
class CREDummy : public CRendElement
{
friend class CRender3D;
public:
CREDummy()
{
mfSetType(eDATA_Dummy);
mfUpdateFlags(FCEF_TRANSFORM);
}
virtual ~CREDummy()
{
}
virtual void mfPrepare();
virtual bool mfDraw(SShader *ef, SShaderPass *sfm);
};
#endif // __CREMotionBlur_H__

92
CryCommon/CREFlashBang.h Normal file
View File

@@ -0,0 +1,92 @@
/*
=====================================================================
FILE : CREFlashBang.h
DESC : render element, simple fx
PROJ : Crytek Engine
CODER: Tiago Sousa
Last Update: 15/04/2003
=====================================================================
*/
#ifndef __CREFLASHBANG_H__
#define __CREFLASHBANG_H__
class CREFlashBang : public CRendElement
{
public:
CREFlashBang():m_fTimeScale(1.0f), m_bIsActive(0), m_fPosX(200), m_fPosY(100), m_fSizeX(400), m_fSizeY(400), m_fFlashTimeOut(1.0f)
{
mfSetType(eDATA_FlashBang);
mfUpdateFlags(FCEF_TRANSFORM);
};
virtual ~CREFlashBang()
{
};
virtual void mfPrepare();
virtual bool mfDraw(SShader *ef, SShaderPass *sfm);
// set/get methods
// activate flashbang
void SetIsActive(bool bActive)
{
m_bIsActive=bActive;
// reset flash time out
if(m_bIsActive)
m_fFlashTimeOut=1.0f;
};
bool GetIsActive(void)
{
return m_bIsActive;
};
// set speed of flashbang fade out
void SetTimeScale(float fTimeScale)
{
m_fTimeScale=fTimeScale;
};
float GetTimeScale(void)
{
return m_fTimeScale;
};
// set flashbangflash properties, fPosX/fPosY - position in screen space, sizeX/sizeY flash size
void SetProperties(float fPosX, float fPosY, float fSizeX, float fSizeY)
{
m_fPosX=fPosX;
m_fPosY=fPosY;
m_fSizeX=fSizeX;
m_fSizeY=fSizeY;
};
void GetProperties(float &fPosX, float &fPosY, float &fSizeX, float &fSizeY)
{
fPosX=m_fPosX;
fPosY=m_fPosY;
fSizeX=m_fSizeX;
fSizeY=m_fSizeY;
};
float GetFlashTimeOut(void)
{
return m_fFlashTimeOut;
};
private:
// active flag
bool m_bIsActive;
// time scale
float m_fTimeScale, m_fFlashTimeOut;
// flashbang flash properties
float m_fPosX, m_fPosY, m_fSizeX, m_fSizeY;
};
#endif

40
CryCommon/CREGlare.h Normal file
View File

@@ -0,0 +1,40 @@
#ifndef __CREGLARE_H__
#define __CREGLARE_H__
//=============================================================
struct SByteColor
{
byte r,g,b,a;
};
struct SLongColor
{
unsigned int r,g,b,a;
};
class CREGlare : public CRendElement
{
public:
int m_GlareWidth;
int m_GlareHeight;
float m_fGlareAmount;
public:
CREGlare()
{
mfInit();
}
void mfInit();
virtual ~CREGlare()
{
}
virtual void mfPrepare();
virtual bool mfDraw(SShader *ef, SShaderPass *sfm);
};
#endif // __CREGLARE_H__

144
CryCommon/CREOcLeaf.h Normal file
View File

@@ -0,0 +1,144 @@
#ifndef __CREOCLEAF_H__
#define __CREOCLEAF_H__
//=============================================================
struct SLightIndicies
{
CDLight m_AssociatedLight;
TArray<ushort> m_pIndicies;
TArray<ushort> m_pIndiciesAttenFrustr;
SVertexStream m_IndexBuffer; // used for DirectX only
unsigned short *GetIndices(int& nInds)
{
if (m_AssociatedLight.m_NumCM & 2)
{
nInds = m_pIndiciesAttenFrustr.Num();
if (nInds)
return &m_pIndiciesAttenFrustr[0];
return NULL;
}
else
{
nInds = m_pIndicies.Num();
if (nInds)
return &m_pIndicies[0];
return NULL;
}
}
SVertexStream *GetIndexBuffer()
{
return &m_IndexBuffer;
}
};
struct SMeshFace
{
Vec3 m_Normal;
Vec3 m_Middle;
};
#define FCEF_CALCCENTER 0x10000
#define FCEF_DYNAMIC 0x20000
class CREOcLeaf : public CRendElement
{
friend class CRenderer;
int mFrameCalcLight;
int mFrameCalcLightNoAtt;
int mFrameCalcAtten;
int mFrameCalcRefract;
int mFrameCalcHalfAngle;
int mFrameCalcHalfAngleNoAtt;
int mFrameCalcProject;
int mFrameCalcLAttenSpec0;
int mFrameCalcLAttenSpec1;
int mMaskLight0; // Light Vectors
int mMaskLight1; // HalfAngle Vectors
int mMaskLight2; // Light Attenuation ( LightVector/(brightness*2.0)+0.5 )
int mMaskLight3; // Light Attenuation ( (LightVector*0.5)+0.5 )
int mMaskLight4; // Attenuation
int mMaskLight5;
Vec3 m_Center;
public:
static CREOcLeaf *m_pLastRE;
struct CMatInfo *m_pChunk;
struct CLeafBuffer * m_pBuffer;
TArray<SMeshFace> *m_Faces;
TArray<SLightIndicies *> *m_LIndicies;
CREOcLeaf()
{
mfSetType(eDATA_OcLeaf);
mfUpdateFlags(FCEF_TRANSFORM);
m_Faces = NULL;
m_LIndicies = NULL;
m_pChunk = NULL;
m_pBuffer = NULL;
mFrameCalcLight = -1;
mFrameCalcAtten = -1;
mFrameCalcRefract = -1;
mFrameCalcHalfAngle = -1;
mMaskLight0 = 0;
mMaskLight1 = 0;
mMaskLight2 = 0;
m_Center.Set(0,0,0);
}
SLightIndicies *mfGetIndiciesForLight(CDLight *pDLight);
void mfGenerateIndicesInsideFrustrum(SLightIndicies *li, CDLight *pDLight);
void mfGenerateIndicesForAttenuation(SLightIndicies *li, CDLight *pDLight);
void mfFillRB(CCObject *pObj);
virtual ~CREOcLeaf()
{
SAFE_DELETE(m_Faces);
if (m_LIndicies)
{
for (int i=0; i<m_LIndicies->Num(); i++)
{
SLightIndicies *li = m_LIndicies->Get(i);
SAFE_DELETE(li);
}
SAFE_DELETE(m_LIndicies);
}
}
virtual struct CMatInfo *mfGetMatInfo();
virtual list2<struct CMatInfo> *mfGetMatInfoList();
virtual int mfGetMatId();
virtual bool mfPreDraw(SShaderPass *sl);
virtual void mfGetPlane(Plane& pl);
virtual void mfPrepare();
virtual bool mfCullByClipPlane(CCObject *pObj);
virtual void mfCenter(Vec3& Pos, CCObject*pObj);
virtual bool mfDraw(SShader *ef, SShaderPass *sfm);
virtual void *mfGetPointer(ESrcPointer ePT, int *Stride, int Type, ESrcPointer Dst, int Flags);
virtual void mfEndFlush();
virtual float mfMinDistanceToCamera(CCObject *pObj);
virtual float mfDistanceToCameraSquared(const CCObject & thisObject);
virtual bool mfCheckUpdate(int nVertFormat, int Flags);
virtual void mfGetBBox(Vec3& vMins, Vec3& vMaxs);
virtual int Size()
{
int nSize = sizeof(*this);
if (m_Faces)
nSize += m_Faces->GetMemoryUsage();
if (m_LIndicies)
{
nSize += m_LIndicies->GetMemoryUsage();
for (int i=0; i<m_LIndicies->Num(); i++)
{
SLightIndicies *li = m_LIndicies->Get(i);
nSize += sizeof(*li);
nSize += li->m_pIndicies.GetMemoryUsage();
nSize += li->m_pIndiciesAttenFrustr.GetMemoryUsage();
}
}
return nSize;
}
};
#endif // __CREOCLEAF_H__

View File

@@ -0,0 +1,47 @@
#ifndef __CREOCCLUSIONQUERY_H__
#define __CREOCCLUSIONQUERY_H__
//=============================================================
class CREOcclusionQuery : public CRendElement
{
friend class CRender3D;
public:
int m_nVisSamples;
int m_nCheckFrame;
int m_nDrawFrame;
Vec3 m_vBoxMin;
Vec3 m_vBoxMax;
#ifdef OPENGL
uint m_nOcclusionID;
#if defined(WIN64) || defined(LINUX64)
uint m_nOcclusionID2; // this is the safety dummy value to make the occlusion id extendable to 64-bit
#endif
#else
UINT_PTR m_nOcclusionID; // this will carry a pointer LPDIRECT3DQUERY9, so it needs to be 64-bit on WIN64
#endif
CREOcclusionQuery()
{
m_nOcclusionID = 0;
m_nVisSamples = 800*600;
m_nCheckFrame = 0;
m_nDrawFrame = 0;
m_vBoxMin=Vec3(0,0,0);
m_vBoxMax=Vec3(0,0,0);
mfSetType(eDATA_OcclusionQuery);
mfUpdateFlags(FCEF_TRANSFORM);
}
virtual ~CREOcclusionQuery();
virtual void mfPrepare();
virtual bool mfDraw(SShader *ef, SShaderPass *sfm);
virtual void mfReset();
};
#endif // __CREOCCLUSIONQUERY_H__

69
CryCommon/CREPolyMesh.h Normal file
View File

@@ -0,0 +1,69 @@
#ifndef __CREPOLYMESH_H__
#define __CREPOLYMESH_H__
//=============================================================
struct SPolyStat
{
int NumOccPolys;
int NumRendPolys;
int NumDetails;
int NumRendDetails;
int NumVerts;
int NumIndices;
};
class CREFlareGeom;
struct SMTriVert
{
Vec3d vert;
float dTC[2];
float lmTC[2];
UCol color;
};
class CREPolyMesh : public CRendElement
{
private:
public:
Plane m_Plane;
void *Srf;
int NumVerts;
int NumIndices;
SMTriVert *TriVerts;
bool *bNoDeform;
ushort *Indices;
int NumLightRE;
int mFrameBr;
static SPolyStat mRS;
static void mfPrintStat();
public:
CREPolyMesh()
{
mfSetType(eDATA_Poly);
mfSetFlags(FCEF_TRANSFORM | FCEF_NEEDFILLBUF);
NumLightRE = 0;
bNoDeform = NULL;
TriVerts = NULL;
Indices = NULL;
}
virtual ~CREPolyMesh();
void mfCheckSun(SShader *ef);
bool mfCullFace(ECull cl);
virtual CRendElement *mfCopyConstruct(void);
virtual void mfCenter(Vec3d& centr, CCObject*pObj);
virtual int mfTransform(Matrix44& ViewMatr, Matrix44& ProjMatr, vec4_t *verts, vec4_t *vertsp, int Num);
virtual void mfPrepare(void);
virtual void mfGetPlane(Plane& pl);
};
#endif // __CREPOLYMESH_H__

View File

@@ -0,0 +1,54 @@
/*
=====================================================================
FILE : CREScreenProcess.h
DESC : Screen processing render element
PROJ : Crytek Engine
CODER: Tiago Sousa
Last Update: 13/06/2003
=====================================================================
*/
#ifndef __CRESCREENPROCESS_H__
#define __CRESCREENPROCESS_H__
// screen processing vars class
class CScreenVars;
// screen processing render element
class CREScreenProcess : public CRendElement
{
friend class CD3D9Renderer;
friend class CGLRenderer;
public:
// constructor/destructor
CREScreenProcess();
virtual ~CREScreenProcess();
// prepare screen processing
virtual void mfPrepare();
// render screen processing
virtual bool mfDraw(SShader *ef, SShaderPass *sfm);
// begin screen processing
virtual void mfActivate(int iProcess);
// reset
virtual void mfReset(void);
// set/get methods
virtual int mfSetParameter(int iProcess, int iParams, void *dwValue);
virtual void *mfGetParameter(int iProcess, int iParams);
CScreenVars *GetVars() { return m_pVars; }
private:
virtual bool mfDrawLowSpec(SShader *ef, SShaderPass *sfm);
// screen processing vars class
CScreenVars *m_pVars;
};
#endif

55
CryCommon/CREShadowMap.h Normal file
View File

@@ -0,0 +1,55 @@
#ifndef __CRESHADOWMAP_H__
#define __CRESHADOWMAP_H__
//=============================================================
//struct CLeafBuffer;
//struct IEntity;
/*
class CREShadowMap : public CRendElement
{
friend class CRender3D;
public:
void * m_pShadowFrustum; // will define projection of shadow from this object
float m_fAlpha;
CREShadowMap()
{
mfSetType(eDATA_ShadowMap);
mfUpdateFlags(FCEF_TRANSFORM);
m_pShadowFrustum=0;
m_fAlpha=1.f;
}
virtual ~CREShadowMap();
virtual void mfPrepare();
virtual bool mfDraw(SShader *ef, SShaderPass *sfm);
};*/
/*
class CREShadowMapCaster : public CRendElement
{
friend class CRender3D;
public:
CLeafBuffer * m_pBuffer;
CREShadowMapCaster()
{
mfSetType(eDATA_ShadowMap);
mfUpdateFlags(FCEF_TRANSFORM);
}
virtual ~CREShadowMapCaster()
{
}
virtual void mfPrepare();
virtual bool mfDraw(SShader *ef, SShaderPass *sfm);
};
*/
#endif // __CRESHADOWMAP_H__

46
CryCommon/CRESky.h Normal file
View File

@@ -0,0 +1,46 @@
#ifndef __CRESKY_H__
#define __CRESKY_H__
//=============================================================
#include "VertexFormats.h"
class CRESky : public CRendElement
{
friend class CRender3D;
public:
float m_fTerrainWaterLevel;
float m_fSkyBoxStretching;
float m_fAlpha;
int m_nSphereListId;
list2<struct_VERTEX_FORMAT_P3F_COL4UB> * m_parrFogLayer;
list2<struct_VERTEX_FORMAT_P3F_COL4UB> * m_parrFogLayer2;
#define MAX_SKY_OCCLAREAS_NUM 8
struct_VERTEX_FORMAT_P3F_COL4UB m_arrvPortalVerts[MAX_SKY_OCCLAREAS_NUM][4];
CRESky()
{
mfSetType(eDATA_Sky);
mfUpdateFlags(FCEF_TRANSFORM);
m_fTerrainWaterLevel = 0;
m_fAlpha = 1;
m_nSphereListId = 0;
m_parrFogLayer = m_parrFogLayer2 = NULL;
m_fSkyBoxStretching=1.f;
memset(m_arrvPortalVerts,0,sizeof(m_arrvPortalVerts));
}
virtual ~CRESky();
virtual void mfPrepare();
virtual bool mfDraw(SShader *ef, SShaderPass *sfm);
void DrawSkySphere(float fHeight);
bool DrawFogLayer();
bool DrawBlackPortal();
};
#endif // __CRESKY_H__

View File

@@ -0,0 +1,86 @@
#ifndef __CRECommon_H__
#define __CRECommon_H__
//=============================================================
//class CTerrain;
class CRECommon : public CRendElement
{
friend class CRender3D;
public:
CRECommon()
{
mfSetType(eDATA_TerrainSector);
mfUpdateFlags(FCEF_TRANSFORM);
}
virtual ~CRECommon()
{
}
virtual void mfPrepare();
virtual bool mfDraw(SShader *ef, SShaderPass *sfm) { return true; }
};
class CREFarTreeSprites : public CRECommon
{
public:
CREFarTreeSprites()
{
mfSetType(eDATA_FarTreeSprites);
mfUpdateFlags(FCEF_TRANSFORM);
}
virtual bool mfDraw(SShader *ef, SShaderPass *sfm);
};
class CRETerrainDetailTextureLayers: public CRECommon
{
public:
CRETerrainDetailTextureLayers()
{
mfSetType(eDATA_TerrainDetailTextureLayers);
mfUpdateFlags(FCEF_TRANSFORM);
}
virtual bool mfDraw(SShader *ef, SShaderPass *sfm);
};
class CRETerrainParticles: public CRECommon
{
public:
CRETerrainParticles()
{
mfSetType(eDATA_TerrainParticles);
mfUpdateFlags(FCEF_TRANSFORM);
}
virtual bool mfDraw(SShader *ef, SShaderPass *sfm);
};
class CREClearStencil : public CRECommon
{
public:
CREClearStencil()
{
mfSetType(eDATA_ClearStencil);
mfUpdateFlags(FCEF_TRANSFORM);
}
virtual bool mfDraw(SShader *ef, SShaderPass *sfm);
};
class CREShadowMapGen: public CRECommon
{
public:
CREShadowMapGen()
{
mfSetType(eDATA_ShadowMapGen);
mfUpdateFlags(FCEF_TRANSFORM);
}
virtual bool mfDraw(SShader *ef, SShaderPass *sfm) { return true; }
};
#endif // __CRECommon_H__

View File

@@ -0,0 +1,47 @@
/*
#ifndef __CRETRIMESHADDITIONALSHADOW_H__
#define __CRETRIMESHADDITIONALSHADOW_H__
class CShadowVolEdge;
//////////////////////////////////////////////////////////////////////
class CRETriMeshAdditionalShadow : public CRendElement
{
public:
CRETriMeshAdditionalShadow()
{
mfSetType(eDATA_TriMeshAdditionalShadow);
mfUpdateFlags(FCEF_TRANSFORM | FCEF_NODEL);
m_vOrigin(0,0,0);
m_nNumEdges=m_nNumFaces=0;
m_pShadowVolEdgesList=NULL;
m_pFacesList=NULL;
m_pTexture=NULL;
}
virtual ~CRETriMeshAdditionalShadow()
{
}
virtual void mfPrepare();
virtual bool mfDraw(SShader *ef, SShaderPass *sfm);
Vec3d m_vOrigin;
int m_nNumEdges;
CShadowVolEdge *m_pShadowVolEdgesList;
int m_nNumFaces;
CObjFace *m_pFacesList;
ITexPic *m_pTexture;
private:
friend class CRender3D;
};
#endif // __CRETRIMESHADDITIONALSHADOW_H__
*/

View File

@@ -0,0 +1,68 @@
#ifndef __CRETRIMESHSHADOW_H__
#define __CRETRIMESHSHADOW_H__
//=============================================================
#define MAX_SV_INSTANCES 32
//=============================================================
struct ItShadowVolume;
class CDLight;
class CRETriMeshShadow : public CRendElement
{
public:
CRETriMeshShadow()
{
mfSetType(eDATA_TriMeshShadow);
mfUpdateFlags(FCEF_TRANSFORM | FCEF_NODEL);
memset(m_arrLBuffers,0,sizeof(m_arrLBuffers));
m_pSvObj=NULL;
m_nCurrInst=0;
m_nRendIndices = 0;
m_bAnimatedObject = false;
}
virtual ~CRETriMeshShadow();
virtual void mfPrepare();
virtual bool mfDraw(SShader *ef, SShaderPass *sfm);
virtual void * mfGetPointer(ESrcPointer ePT, int *Stride, int Type, ESrcPointer Dst, int Flags);
virtual bool mfCheckUpdate(int nVertFormat, int Flags);
virtual bool mfCheckUnload();
//! shadow volume info
struct ShadVolInstanceInfo
{
ShadVolInstanceInfo() { memset(this,0,sizeof(*this)); }
CLeafBuffer * pVB;
int nFrameId;
Vec3 vObjSpaceLightPos;
IEntityRender * pLightOwner;
IEntityRender * pShadowCaster;
};
//! array of ready shadow volumes
ShadVolInstanceInfo m_arrLBuffers[MAX_SV_INSTANCES]; // stores shadow volumes
int m_nCurrInst; // used to pass selected slot from mfCheckUpdate to mfDraw
int m_nRendIndices;
bool m_bAnimatedObject;
//! vertex buffer data set by shadowvolobject
ItShadowVolume *m_pSvObj;
static int GetAndResetRebuildsPerFrrameCounter();
static int GetAndResetShadowVolumesPerFrrameCounter();
static int GetShadowVolumesAllocatedCounter();
static void PrintStats();
private:
static int m_nCRETriMeshShadowRebuildsPerFrrame;
static int m_nCRETriMeshShadowShadowsPerFrrame;
static int m_nCRETriMeshShadowAloocatedShadows;
};
#endif // __CRETRIMESHSHADOW_H__

366
CryCommon/ColorDefs.h Normal file
View File

@@ -0,0 +1,366 @@
/*=============================================================================
ColorDefs.h : Colors declarations.
Copyright (c) 2001 Crytek Studios. All Rights Reserved.
Revision history:
* Created by Khonich Andrey
=============================================================================*/
#ifndef __COLORDEFS_H__
#define __COLORDEFS_H__
//#pragma warning(disable:4018) // signed/unsigned mismatch
//#pragma warning(disable:4244) // int to float loose of data.
//=========================================================
///#include "CryHeaders.h"
_inline float FClamp( float X, float Min, float Max )
{
return X<Min ? Min : X<Max ? X : Max;
}
class CFColor
{
public:
float r, g, b, a;
public:
CFColor() {}
CFColor(const Vec3 & vVec)
{
r = vVec.x;
g = vVec.y;
b = vVec.z;
a = 1.f;
}
CFColor(float lr, float lg, float lb, float la = 1.0f)
{
r = lr;
g = lg;
b = lb;
a = la;
}
CFColor(float *cols)
{
r = cols[0];
g = cols[1];
b = cols[2];
a = cols[3];
}
CFColor(unsigned int c)
{
r = (c & 0xff) / 255.0f;
g = ((c>>8) & 0xff) / 255.0f;
b = ((c>>16) & 0xff) / 255.0f;
a = ((c>>24) & 0xff) / 255.0f;
}
CFColor(unsigned char c[4])
{
r = c[0] / 255.0f;
g = c[1] / 255.0f;
b = c[2] / 255.0f;
a = c[3] / 255.0f;
}
/* CFColor(CryIRGB *c)
{
r = c->r / 255.0f;
g = c->g / 255.0f;
b = c->b / 255.0f;
a = 1.0f;
}*/
CFColor(float c)
{
r = g = b = a = c;
}
void Set(float fR,float fG,float fB,float fA=1.0f)
{
r=fR;g=fG;b=fB;a=fA;
}
// Binary math operators.
friend CFColor operator*( float Scale, const CFColor& C )
{
return CFColor( C.r * Scale, C.g * Scale, C.b * Scale, C.a * Scale );
}
CFColor operator+( const CFColor& C ) const
{
return CFColor( r + C.r, g + C.g, b + C.b, a + C.a );
}
CFColor operator-( const CFColor& C ) const
{
return CFColor( r - C.r, g - C.g, b - C.b, a - C.a );
}
CFColor operator*( float Scale ) const
{
return CFColor( r * Scale, g * Scale, b * Scale, a * Scale );
}
CFColor operator/( float Scale ) const
{
float IScale = 1.0f/Scale;
return CFColor( r * IScale, g * IScale, b * IScale, a * IScale );
}
CFColor operator*( const CFColor& C ) const
{
return CFColor( r * C.r, g * C.g, b * C.b, a * C.a );
}
// Binary comparison operators.
bool operator==( const CFColor& C ) const
{
return r==C.r && g==C.g && b==C.b && a==C.a;
}
bool operator!=( const CFColor& C ) const
{
return r!=C.r || g!=C.g || b!=C.b || a!=C.a;
}
// Assignment operators.
CFColor operator=( const float c )
{
r = g = b = a = c;
return *this;
}
CFColor operator=( const CFColor& C )
{
r = C.r;
g = C.g;
b = C.b;
a = C.a;
return *this;
}
CFColor operator+=( const CFColor& C )
{
r += C.r; g += C.g; b += C.b; a += C.a;
return *this;
}
CFColor operator-=( const CFColor& C )
{
r -= C.r; g -= C.g; b -= C.b; a -= C.a;
return *this;
}
CFColor operator*=( float Scale )
{
r *= Scale; g *= Scale; b *= Scale; a *= Scale;
return *this;
}
CFColor operator/=( float V )
{
float IV = 1.0f/V;
r *= IV; g *= IV; b *= IV; a *= IV;
return *this;
}
CFColor operator*=( const CFColor& C )
{
r *= C.r; g *= C.g; b *= C.b; a *= C.a;
return *this;
}
CFColor operator/=( const CFColor& C )
{
r /= C.r; g /= C.g; b /= C.b; a /= C.a;
return *this;
}
_inline const float& operator[](int i) const { return (&r)[i]; }
_inline float& operator[](int i) { return (&r)[i]; }
float* operator * () { return (&r); }
unsigned int GetTrue()
{
union
{
struct
{
unsigned char R, G, B, A;
};
unsigned int D;
}C;
C.R = uchar(r * 255.0f);
C.G = uchar(g * 255.0f);
C.B = uchar(b * 255.0f);
C.A = uchar(a * 255.0f);
return C.D;
}
unsigned int GetTrueInv()
{
union
{
struct
{
unsigned char R, G, B, A;
};
unsigned int D;
}C;
C.R = uchar(255.0f-r*255.0f);
C.G = uchar(255.0f-g*255.0f);
C.B = uchar(255.0f-b*255.0f);
C.A = uchar(255.0f-a*255.0f);
return C.D;
}
unsigned int GetTrueCol()
{
union
{
struct
{
unsigned char R, G, B, A;
};
unsigned int D;
}C;
// C.R = r * 255.0f; C.G = g * 255.0f; C.B = b * 255.0f; C.A = 255;
C.R = uchar(r * 255.0f);
C.G = uchar(g * 255.0f);
C.B = uchar(b * 255.0f);
C.A = uchar(255.0f);
return C.D;
}
void ScaleCol (float f)
{
r *= f; g *= f; b *= f;
}
float NormalizeCol (CFColor& out)
{
float max;
max = r;
if (g > max)
max = g;
if (b > max)
max = b;
if (max == 0)
return 0;
out = *this / max;
return max;
}
float Normalize (CFColor& out)
{
float max;
max = r;
if (g > max)
max = g;
if (b > max)
max = b;
if (a > max)
max = a;
if (max == 0)
return 0;
out = *this / max;
return max;
}
void Clamp(float Min = 0, float Max = 1.0f)
{
r = ::FClamp(r, Min, Max);
g = ::FClamp(g, Min, Max);
b = ::FClamp(b, Min, Max);
a = ::FClamp(a, Min, Max);
}
void ClampCol(float Min = 0, float Max = 1.0f)
{
r = ::FClamp(r, Min, Max);
g = ::FClamp(g, Min, Max);
b = ::FClamp(b, Min, Max);
}
void ClampAlpha(float Min = 0, float Max = 1.0f)
{
a = ::FClamp(a, Min, Max);
}
};
#define Col_Aquamarine CFColor (0.439216f, 0.858824f, 0.576471f)
#define Col_Black CFColor (0.0f, 0.0f, 0.0f)
#define Col_Blue CFColor (0.0f, 0.0f, 1.0f)
#define Col_BlueViolet CFColor (0.623529f, 0.372549f, 0.623529f)
#define Col_Brown CFColor (0.647059f, 0.164706f, 0.164706f)
#define Col_CadetBlue CFColor (0.372549f, 0.623529f, 0.623529f)
#define Col_Coral CFColor (1.0f, 0.498039f, 0.0f)
#define Col_CornflowerBlue CFColor (0.258824f, 0.258824f, 0.435294f)
#define Col_Cyan CFColor (0.0f, 1.0f, 1.0f)
#define Col_DarkGreen CFColor (0.184314f, 0.309804f, 0.184314f)
#define Col_DarkOliveGreen CFColor (0.309804f, 0.309804f, 0.184314f)
#define Col_DarkOrchild CFColor (0.6f, 0.196078f, 0.8f)
#define Col_DarkSlateBlue CFColor (0.419608f, 0.137255f, 0.556863f)
#define Col_DarkSlateGray CFColor (0.184314f, 0.309804f, 0.309804f)
#define Col_DarkSlateGrey CFColor (0.184314f, 0.309804f, 0.309804f)
#define Col_DarkTurquoise CFColor (0.439216f, 0.576471f, 0.858824f)
#define Col_DarkWood CFColor (0.05f, 0.01f, 0.005f)
#define Col_DimGray CFColor (0.329412f, 0.329412f, 0.329412f)
#define Col_DimGrey CFColor (0.329412f, 0.329412f, 0.329412f)
#define Col_FireBrick CFColor (0.9f, 0.4f, 0.3f)
#define Col_ForestGreen CFColor (0.137255f, 0.556863f, 0.137255f)
#define Col_Gold CFColor (0.8f, 0.498039f, 0.196078f)
#define Col_Goldenrod CFColor (0.858824f, 0.858824f, 0.439216f)
#define Col_Gray CFColor (0.752941f, 0.752941f, 0.752941f)
#define Col_Green CFColor (0.0f, 1.0f, 0.0f)
#define Col_GreenYellow CFColor (0.576471f, 0.858824f, 0.439216f)
#define Col_Grey CFColor (0.752941f, 0.752941f, 0.752941f)
#define Col_IndianRed CFColor (0.309804f, 0.184314f, 0.184314f)
#define Col_Khaki CFColor (0.623529f, 0.623529f, 0.372549f)
#define Col_LightBlue CFColor (0.74902f, 0.847059f, 0.847059f)
#define Col_LightGray CFColor (0.658824f, 0.658824f, 0.658824f)
#define Col_LightGrey CFColor (0.658824f, 0.658824f, 0.658824f)
#define Col_LightSteelBlue CFColor (0.560784f, 0.560784f, 0.737255f)
#define Col_LightWood CFColor (0.6f, 0.24f, 0.1f)
#define Col_LimeGreen CFColor (0.196078f, 0.8f, 0.196078f)
#define Col_Magenta CFColor (1.0f, 0.0f, 1.0f)
#define Col_Maroon CFColor (0.556863f, 0.137255f, 0.419608f)
#define Col_MedianWood CFColor (0.3f, 0.12f, 0.03f)
#define Col_MediumAquamarine CFColor (0.196078f, 0.8f, 0.6f)
#define Col_MediumBlue CFColor (0.196078f, 0.196078f, 0.8f)
#define Col_MediumForestGreen CFColor (0.419608f, 0.556863f, 0.137255f)
#define Col_MediumGoldenrod CFColor (0.917647f, 0.917647f, 0.678431f)
#define Col_MediumOrchid CFColor (0.576471f, 0.439216f, 0.858824f)
#define Col_MediumSeaGreen CFColor (0.258824f, 0.435294f, 0.258824f)
#define Col_MediumSlateBlue CFColor (0.498039f, 0.0f, 1.0f)
#define Col_MediumSpringGreen CFColor (0.498039f, 1.0f, 0.0f)
#define Col_MediumTurquoise CFColor (0.439216f, 0.858824f, 0.858824f)
#define Col_MediumVioletRed CFColor (0.858824f, 0.439216f, 0.576471f)
#define Col_MidnightBlue CFColor (0.184314f, 0.184314f, 0.309804f)
#define Col_Navy CFColor (0.137255f, 0.137255f, 0.556863f)
#define Col_NavyBlue CFColor (0.137255f, 0.137255f, 0.556863f)
#define Col_Orange CFColor (0.8f, 0.196078f, 0.196078f)
#define Col_OrangeRed CFColor (0.0f, 0.0f, 0.498039f)
#define Col_Orchid CFColor (0.858824f, 0.439216f, 0.858824f)
#define Col_PaleGreen CFColor (0.560784f, 0.737255f, 0.560784f)
#define Col_Pink CFColor (0.737255f, 0.560784f, 0.560784f)
#define Col_Plum CFColor (0.917647f, 0.678431f, 0.917647f)
#define Col_Red CFColor (1.0f, 0.0f, 0.0f)
#define Col_Salmon CFColor (0.435294f, 0.258824f, 0.258824f)
#define Col_SeaGreen CFColor (0.137255f, 0.556863f, 0.419608f)
#define Col_Sienna CFColor (0.556863f, 0.419608f, 0.137255f)
#define Col_SkyBlue CFColor (0.196078f, 0.6f, 0.8f)
#define Col_SlateBlue CFColor (0.0f, 0.498039f, 1.0f)
#define Col_SpringGreen CFColor (0.0f, 1.0f, 0.498039f)
#define Col_SteelBlue CFColor (0.137255f, 0.419608f, 0.556863f)
#define Col_Tan CFColor (0.858824f, 0.576471f, 0.439216f)
#define Col_Thistle CFColor (0.847059f, 0.74902f, 0.847059f)
#define Col_Turquoise CFColor (0.678431f, 0.917647f, 0.917647f)
#define Col_Violet CFColor (0.309804f, 0.184314f, 0.309804f)
#define Col_VioletRed CFColor (0.8f, 0.196078f, 0.6f)
#define Col_Wheat CFColor (0.847059f, 0.847059f, 0.74902f)
#define Col_White CFColor (1.0f, 1.0f, 1.0f)
#define Col_Yellow CFColor (1.0f, 1.0f, 0.0f)
#define Col_YellowGreen CFColor (0.6f, 0.8f, 0.196078f)
//=========================================================
#endif

139
CryCommon/CrtDebugStats.h Normal file
View File

@@ -0,0 +1,139 @@
// support for leak dumping and statistics gathering using vs Crt Debug
// should be included in every DLL below DllMain()
#ifdef WIN32
#ifdef _DEBUG
#include <ILog.h>
#include <crtdbg.h>
#include <algorithm>
#include <vector>
// copied from DBGINT.H (not a public header!)
#define nNoMansLandSize 4
typedef struct _CrtMemBlockHeader
{
struct _CrtMemBlockHeader * pBlockHeaderNext;
struct _CrtMemBlockHeader * pBlockHeaderPrev;
char * szFileName;
int nLine;
size_t nDataSize;
int nBlockUse;
long lRequest;
unsigned char gap[nNoMansLandSize];
/* followed by:
* unsigned char data[nDataSize];
* unsigned char anotherGap[nNoMansLandSize];
*/
} _CrtMemBlockHeader;
struct SFileInfo
{
int blocks; INT_PTR bytes; //AMD Port
SFileInfo(INT_PTR b) { blocks = 1; bytes = b; }; //AMD Port
};
_CrtMemState lastcheckpoint;
bool checkpointset = false;
extern "C" void __declspec(dllexport) CheckPoint()
{
_CrtMemCheckpoint(&lastcheckpoint);
checkpointset = true;
};
bool pairgreater( const std::pair<string, SFileInfo> &elem1, const std::pair<string, SFileInfo> &elem2)
{
return elem1.second.bytes > elem2.second.bytes;
}
extern "C" void __declspec(dllexport) UsageSummary(ILog *log, char *modulename, int *extras)
{
_CrtMemState state;
if(checkpointset)
{
_CrtMemState recent;
_CrtMemCheckpoint(&recent);
_CrtMemDifference(&state, &lastcheckpoint, &recent);
}
else
{
_CrtMemCheckpoint(&state);
};
INT_PTR numblocks = state.lCounts[_NORMAL_BLOCK]; //AMD Port
INT_PTR totalalloc = state.lSizes[_NORMAL_BLOCK]; //AMD Port
extras[0] = totalalloc;
extras[1] = numblocks;
log->Log("\001$5---------------------------------------------------------------------------------------------------");
if(!numblocks)
{
log->Log("\001$3Module %s has no memory in use", modulename);
return;
};
log->Log("\001$5Usage summary for module %s", modulename);
log->Log("\001%d kbytes (peak %d) in %d objects of %d average bytes\n",
totalalloc/1024, state.lHighWaterCount/1024, numblocks, numblocks ? totalalloc/numblocks : 0);
log->Log("\001%d kbytes allocated over time\n", state.lTotalCount/1024);
typedef std::map<string, SFileInfo> FileMap;
FileMap fm;
for(_CrtMemBlockHeader *h = state.pBlockHeader; h; h = h->pBlockHeaderNext)
{
if(_BLOCK_TYPE(h->nBlockUse)!=_NORMAL_BLOCK) continue;
string s = h->szFileName ? h->szFileName : "NO_SOURCE";
if (h->nLine > 0)
{
char buf[16];
sprintf(buf, "_%d", h->nLine);
s += buf;
}
FileMap::iterator it = fm.find(s);
if(it!=fm.end())
{
(*it).second.blocks++;
(*it).second.bytes += h->nDataSize;
}
else
{
fm.insert(FileMap::value_type(s, SFileInfo(h->nDataSize)));
};
};
typedef std::vector< std::pair<string, SFileInfo> > FileVector;
FileVector fv;
for(FileMap::iterator it = fm.begin(); it!=fm.end(); ++it) fv.push_back((*it));
std::sort(fv.begin(), fv.end(), pairgreater);
for(FileVector::iterator it = fv.begin(); it!=fv.end(); ++it)
{
log->Log("\001%6d kbytes / %6d blocks allocated from %s\n",
(*it).second.bytes/1024, (*it).second.blocks, (*it).first.c_str());
};
if(extras[2])
{
OutputDebugString("---------------------------------------------------------------------------------------------------\n");
OutputDebugString(modulename);
OutputDebugString("\n\n");
_CrtDumpMemoryLeaks();
OutputDebugString("\n\n");
};
};
#endif
#if !defined(_RELEASE) && !defined(_DLL)
extern "C" HANDLE _crtheap;
extern "C" HANDLE __declspec(dllexport) GetDLLHeap() { return _crtheap; };
#endif
#endif //WIN32

View File

@@ -0,0 +1,70 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2002.
// -------------------------------------------------------------------------
// File name: CryAnimationScriptCommands.h
// Version: v1.00
// Created: 1/15/2003 by Sergiy Migdalskiy
// Compilers: Visual Studio.NET
// Description: Declarations necessary for scripting extensions to the
// Cry Character Animation subsyste.
// -------------------------------------------------------------------------
// Notes:
// This file is separated from the ICryAnimation.h for the sake of fast
// compilation: it's only used in the game code once, and in the animation
// system once. When some additional extension is added to the animation
// scripting interface, only this file is changed, and no need to recompile
// the whole project
//
// History:
//
////////////////////////////////////////////////////////////////////////////
#ifndef __CRY_ANIMATION_SCRIPT_COMMANDS_HDR__
#define __CRY_ANIMATION_SCRIPT_COMMANDS_HDR__
enum CryAnimationScriptCommandEnum
{
// Start emitting particles from all characters, for test
CASCMD_TEST_PARTICLES = 0,
// Stop emitting all particles on all characters
CASCMD_STOP_PARTICLES = 1,
// Dump animation memory usage
CASCMD_DUMP_ANIMATIONS = 2,
// Dump all loaded models
CASCMD_DUMP_MODELS = 3,
// Unload all animations that haven't been touched for the *(int*)pParams number of frames
// if pParam == NULL, default number of frames should be used
CASCMD_TRASH_ANIMATIONS = 4,
// Unload the given animation (by the file name, may be without the path and extension)
// (char*)pParams is the 0-terminated string with the animation file name
CASCMD_UNLOAD_ANIMATION = 5,
// cleans up the decals on all characters
CASCMD_CLEAR_DECALS = 6,
// dumps the decals for all characters
CASCMD_DUMP_DECALS = 7,
//starts many animations simultaneously; uses (CASCmdStartMultiAnims*)pParams param block
CASCMD_START_MANY_ANIMS = 8,
// draws (one-time) all the bones of all the characters in the system
CASCMD_DEBUG_DRAW = 9,
// dumps the ModelState info, used to hunt down the invisible guy bug
CASCMD_DUMP_STATES = 10,
// dumps all models into the special ASCII file
CASCMD_EXPORT_MODELS_ASCII = 11
};
struct CASCmdStartAnim
{
const char* szAnimName;
int nLayer;
};
struct CASCmdStartMultiAnims
{
const CASCmdStartAnim* pAnims;
int numAnims;
float fBlendTime;
};
#endif

View File

@@ -0,0 +1,55 @@
#ifndef _CRY_COMMON_CRY_CHAR_ANIMATION_PARAMS_HDR_
#define _CRY_COMMON_CRY_CHAR_ANIMATION_PARAMS_HDR_
//////////////////////////////////////////////////////////////////////////
// This structure describes the parameters used to start an animation
// on a character.
struct CryCharAnimationParams
{
CryCharAnimationParams(
float _fBlendInTime = 0.125f,
float _fBlendOutTime = 0.125f,
int _nLayerID = 0,
unsigned _nFlags = 0):
fBlendInTime (_fBlendInTime),
fBlendOutTime (_fBlendOutTime),
nLayerID (_nLayerID),
nFlags (_nFlags)
{
}
// Summary:
// Flags used by CryCharAnimationParams to set the playback and synchronization of the animation.
enum EFlagsEnum
{
// Means that the corresponding animation for attachments will be played
// (by default, no animated attachments receive the command to play this animation).
FLAGS_RECURSIVE = 1,
// If set, the animation is started at the same phase as the one in layer 0.
FLAGS_SYNCHRONIZE_WITH_LAYER_0 = 1 << 1,
// Means that the animation will be queued until the current one is finished
// and that the next animation will also be queued until this (aligned) one is finished.
FLAGS_ALIGNED = 1 << 2,
// If set, the animation is not treated as default idle animation
// otherwise, if it's looped, it'll be used as default idle animation.
FLAGS_NO_DEFAULT_IDLE = 1 << 3
};
// blendin and out times of the animation
// Used to specify the blend-in length of the animation.
float fBlendInTime;
// Used to specify the blend-out length of the animation.
float fBlendOutTime;
// Specify the layer where to start the animation.
int nLayerID;
// Combination of flags defined above.
unsigned nFlags;
};
#endif

View File

@@ -0,0 +1,26 @@
#ifndef _CRY_COMMON_CRY_CHAR_FX_TRAIL_PARAMS_HDR_
#define _CRY_COMMON_CRY_CHAR_FX_TRAIL_PARAMS_HDR_
struct CryCharFxTrailParams
{
CryCharFxTrailParams(){}
CryCharFxTrailParams (int nBone, int nTextureId = -1, float fLength = 0.25f, const Vec3d& vStart = Vec3d(0,0,0), const Vec3d& vEnd = Vec3d(0,0,1), unsigned numMaxQuads = 24)
{
this->nBone = nBone;
this->nTextureId = nTextureId;
this->vLine[0] = vStart;
this->vLine[1] = vEnd;
this->fLength = fLength;
this->numMaxQuads = numMaxQuads;
}
int nBone; // bone to which to attach the trail
int nTextureId; // tid of the trail
enum {numVerts = 2}; // number of vertices in the line strip
Vec3d vLine[numVerts]; // the line strip to extrude, in the coordinate frame of the bone
float fLength; // length of the trail, in SECONDS
unsigned numMaxQuads; // max number of quads constituting the strape
};
#endif

View File

@@ -0,0 +1,63 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek CryENGINE Source code
//
// File:CryCharMorphParams.h
// Parameters for the morphing functions in ICryCharInstance interface
//
// History:
// -March 3,2003:Created by Sergiy Migdalskiy
//
//////////////////////////////////////////////////////////////////////
#ifndef _CRY_CHAR_MORPH_PARAMS_HDR_
#define _CRY_CHAR_MORPH_PARAMS_HDR_
// StartMorph will accept this
struct CryCharMorphParams
{
CryCharMorphParams (
float _fBlendIn = 0.15f,
float _fLength = 0,
float _fBlendOut = 0.15f,
float _fAmplitude = 1,
float _fStartTime = 0,
float _fSpeed = 1,
unsigned _nFlags = 0
):
fBlendIn (_fBlendIn),
fLength (_fLength),
fBlendOut (_fBlendOut),
fAmplitude (_fAmplitude),
fStartTime (_fStartTime),
fSpeed (_fSpeed),
nFlags(_nFlags)
{
}
// the blend-in time
float fBlendIn;
// the time to stay in static position
float fLength;
// the blend-out time
float fBlendOut;
// the maximum amplitude
float fAmplitude;
// the initial time phase from which to start morphing, within the cycle
float fStartTime;
// multiplier of speed of the update; 1 is default:
float fSpeed;
enum FlagsEnum
{
// with this flag set, the attachments will be traversed to attempt to start the same morph target
FLAGS_RECURSIVE = 1,
// with this flag set, the morph will not be time-updated (it'll be frozen at the point where it is)
FLAGS_FREEZE = 1 << 1,
FLAGS_NO_BLENDOUT = 1 << 2
};
// optional flags, as specified by the FlagsEnum
unsigned nFlags;
};
#endif

446
CryCommon/CryCommon.vcproj Normal file
View File

@@ -0,0 +1,446 @@
<?xml version="1.0" encoding="windows-1251"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="7.10"
Name="CryCommon"
ProjectGUID="{AEB958D4-45CA-478B-BA8E-D0E897CE974B}"
SccProjectName="Perforce Project"
SccAuxPath=""
SccLocalPath="."
SccProvider="MSSCCI:Perforce SCM"
Keyword="MakeFileProj">
<Platforms>
<Platform
Name="Win32"/>
</Platforms>
<Configurations>
<Configuration
Name="Release|Win32"
OutputDirectory="D:\Games\FC\Bin32"
IntermediateDirectory=".\Release"
ConfigurationType="10"
UseOfMFC="0">
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
</Configuration>
<Configuration
Name="Debug|Win32"
OutputDirectory="D:\Games\FC\Bin32"
IntermediateDirectory=".\Debug_XBox"
ConfigurationType="10"
UseOfMFC="0">
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
</Configuration>
<Configuration
Name="Profile|Win32"
OutputDirectory="D:\Games\FC\Bin32"
IntermediateDirectory=".\Profile"
ConfigurationType="10"
UseOfMFC="0">
<Tool
Name="VCCustomBuildTool"/>
<Tool
Name="VCMIDLTool"/>
<Tool
Name="VCPostBuildEventTool"/>
<Tool
Name="VCPreBuildEventTool"/>
</Configuration>
</Configurations>
<References>
</References>
<Files>
<Filter
Name="Interfaces_h"
Filter="">
<File
RelativePath="AgentParams.h">
</File>
<File
RelativePath="crysound.h">
</File>
<File
RelativePath=".\I3DEngine.h">
</File>
<File
RelativePath=".\I3DIndoorEngine.h">
</File>
<File
RelativePath="IAgent.h">
</File>
<File
RelativePath=".\IAISystem.h">
</File>
<File
RelativePath="IBindable.h">
</File>
<File
RelativePath=".\IBitStream.h">
</File>
<File
RelativePath=".\ICompressionHelper.h">
</File>
<File
RelativePath=".\IConsole.h">
</File>
<File
RelativePath=".\ICryAnimation.h">
</File>
<File
RelativePath="ICryPak.h">
</File>
<File
RelativePath=".\IDataProbe.h">
</File>
<File
RelativePath="IEdgeConnectivityBuilder.h">
</File>
<File
RelativePath="IEntityRenderState.h">
</File>
<File
RelativePath=".\IEntitySystem.h">
</File>
<File
RelativePath=".\IFont.h">
</File>
<File
RelativePath=".\IGame.h">
</File>
<File
RelativePath=".\IInput.h">
</File>
<File
RelativePath="ILipSync.h">
</File>
<File
RelativePath="ILMSerializationManager.h">
</File>
<File
RelativePath=".\ILog.h">
</File>
<File
RelativePath=".\IMarkers.h">
</File>
<File
RelativePath="IMiniLog.h">
</File>
<File
RelativePath="IMovieSystem.h">
</File>
<File
RelativePath=".\INetwork.h">
</File>
<File
RelativePath="IPhysics.h">
</File>
<File
RelativePath=".\IProcess.h">
</File>
<File
RelativePath=".\IRenderer.h">
</File>
<File
RelativePath=".\IScriptSystem.h">
</File>
<File
RelativePath="IShader.h">
</File>
<File
RelativePath=".\ISound.h">
</File>
<File
RelativePath=".\IStatObj.h">
</File>
<File
RelativePath="IStreamEngine.h">
</File>
<File
RelativePath=".\IStreamPersist.h">
</File>
<File
RelativePath=".\ISystem.h">
</File>
<File
RelativePath=".\ITimer.h">
</File>
<File
RelativePath="IValidator.h">
</File>
<File
RelativePath=".\IXGame.h">
</File>
<File
RelativePath="IXml.h">
</File>
<File
RelativePath=".\IXMLDOM.h">
</File>
<File
RelativePath="LMCompStructures.h">
</File>
<File
RelativePath=".\physinterface.h">
</File>
</Filter>
<Filter
Name="Common_h"
Filter="">
<File
RelativePath="_ScriptableEx.h">
</File>
<File
RelativePath="AnimKey.h">
</File>
<File
RelativePath=".\ColorDefs.h">
</File>
<File
RelativePath="CrtDebugStats.h">
</File>
<File
RelativePath="CryAnimationScriptCommands.h">
</File>
<File
RelativePath=".\CryCharAnimationParams.h">
</File>
<File
RelativePath="CryCharMorphParams.h">
</File>
<File
RelativePath="CryCompiledFile.h">
</File>
<File
RelativePath="CryEngineDecalInfo.h">
</File>
<File
RelativePath="CryFile.h">
</File>
<File
RelativePath=".\CryHeaders.h">
</File>
<File
RelativePath=".\CryMemoryManager.h">
</File>
<File
RelativePath="CryParticleSpawnInfo.h">
</File>
<File
RelativePath="CrySizer.h">
</File>
<File
RelativePath="CryVersion.h">
</File>
<File
RelativePath=".\EntityDesc.h">
</File>
<File
RelativePath="Font.h">
</File>
<File
RelativePath="FrameProfiler.h">
</File>
<File
RelativePath=".\IPAddress.h">
</File>
<File
RelativePath="LeafBuffer.h">
</File>
<File
RelativePath=".\list2.h">
</File>
<File
RelativePath="MakMatInfoFromMAT_ENTITY.h">
</File>
<File
RelativePath="MeshIdx.h">
</File>
<File
RelativePath="Names.h">
</File>
<File
RelativePath="primitives.h">
</File>
<File
RelativePath=".\ProjectDefines.h">
</File>
<File
RelativePath="Range.h">
</File>
<File
RelativePath="RendElement.h">
</File>
<File
RelativePath="ScriptObjectVector.h">
</File>
<File
RelativePath="SerializeBuffer.h">
</File>
<File
RelativePath="smartptr.h">
</File>
<File
RelativePath="StlDbgAlloc.h">
</File>
<File
RelativePath="StlUtils.h">
</File>
<File
RelativePath=".\Stream.h">
</File>
<File
RelativePath="StreamData.h">
</File>
<File
RelativePath="StringUtils.h">
</File>
<File
RelativePath="TAlloc.h">
</File>
<File
RelativePath=".\Tarray.h">
</File>
<File
RelativePath="TArrays.h">
</File>
<File
RelativePath="TimeValue.h">
</File>
<File
RelativePath="TString.h">
</File>
<File
RelativePath="VertexBufferSource.h">
</File>
<File
RelativePath=".\VertexFormats.h">
</File>
<File
RelativePath="XboxSpecific.h">
</File>
<File
RelativePath="XmlParserFont.h">
</File>
<File
RelativePath=".\XmlStream.h">
</File>
<Filter
Name="RenderElements"
Filter="">
<File
RelativePath="CRE2DQuad.h">
</File>
<File
RelativePath="CREDummy.h">
</File>
<File
RelativePath="CREFlashBang.h">
</File>
<File
RelativePath="CREGlare.h">
</File>
<File
RelativePath="CREOcclusionQuery.h">
</File>
<File
RelativePath="CREOcLeaf.h">
</File>
<File
RelativePath="CREPolyMesh.h">
</File>
<File
RelativePath="CREScreenProcess.h">
</File>
<File
RelativePath="CRESky.h">
</File>
<File
RelativePath="CRETerrainSector.h">
</File>
<File
RelativePath="CRETriMeshAdditionalShadow.h">
</File>
<File
RelativePath="CRETriMeshShadow.h">
</File>
</Filter>
</Filter>
<Filter
Name="MatLib"
Filter="">
<File
RelativePath=".\AABBSV.h">
</File>
<File
RelativePath=".\Cry_Camera.h">
</File>
<File
RelativePath=".\Cry_Color4.h">
</File>
<File
RelativePath=".\Cry_Geo.h">
</File>
<File
RelativePath=".\Cry_GeoDistance.h">
</File>
<File
RelativePath=".\Cry_GeoIntersect.h">
</File>
<File
RelativePath=".\Cry_GeoOverlap.h">
</File>
<File
RelativePath=".\Cry_Math.h">
</File>
<File
RelativePath=".\Cry_Matrix.h">
</File>
<File
RelativePath="Cry_Quat.h">
</File>
<File
RelativePath="Cry_Vector2.h">
</File>
<File
RelativePath="Cry_Vector3.h">
</File>
<File
RelativePath="Cry_XOptimise.h">
</File>
</Filter>
<Filter
Name="Platform_h"
Filter="">
<File
RelativePath=".\CryLibrary.h">
</File>
<File
RelativePath=".\Linux32Specific.h">
</File>
<File
RelativePath="platform.h">
</File>
<File
RelativePath="Win32specific.h">
</File>
<File
RelativePath="Win64specific.h">
</File>
</Filter>
</Files>
<Globals>
</Globals>
</VisualStudioProject>

View File

@@ -0,0 +1,10 @@
""
{
"FILE_VERSION" = "9237"
"ENLISTMENT_CHOICE" = "NEVER"
"PROJECT_FILE_RELATIVE_PATH" = ""
"NUMBER_OF_EXCLUDED_FILES" = "0"
"ORIGINAL_PROJECT_FILE_PATH" = "file:E:\\Game01\\CryCommon\\CryCommon.vcproj"
"NUMBER_OF_NESTED_PROJECTS" = "0"
"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROJECT"
}

599
CryCommon/CryCompiledFile.h Normal file
View File

@@ -0,0 +1,599 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek (C) 2002
//
// CryCommon Source Code
//
// File:CryCompiledFile.h
// Description: Cry Compiled File Format declarations: necessary structures,
// chunk descriptions.
//
// Notes on Cry Compiled File Format.
// Generally, compiled format is used for faster load times in the game.
// The source files exported from Max and otherwise created are compiled
// into compiled files that are fast to read, but whose format can be changed
// frequently and be inflexible.
//
// The compiled format is essentially a bitstream structured with light-weight chunks.
// THe compiled format file consists of several pieces (chunks) that can either contain some
// binary data, or other chunks. Each chunk begins with CCFHeader structure.
//
// If you need chunk identification (like ChunkId in the CGF/CAF), write another DWORD after the CCFChunkHeader
//
// If you need chunk type version, write the version number as another DWORD after the CCFChunkHeader
//
// If you need ANYTHING else, just write it after the CCFChunkHeader. DO NOT expand CCFChunkHeader.
// If you need, use your own convention to write some other structure right after the CCFChunkHeader,
// but everybody must be able to skip chunks using the nSize field in the CCFChunkHeader
//
// The CCF format is for one-time stream-like reading, not for random access.
// There's no point in having any chunk table or other dictionary structures.
//
// History:
// - Jan 16, 2003 - Created by Sergiy Migdalskiy
//
// Prerequisities:
// #include <stdio.h>
//
//////////////////////////////////////////////////////////////////////
#ifndef __CRY_COMMON_CRY_COMPILED_FILE_FORMAT_HDR__
#define __CRY_COMMON_CRY_COMPILED_FILE_FORMAT_HDR__
// the required header for file i/o operations
#include <stdio.h>
// Cry Compiled File format chunk header
// Each chunk in the file begins with this structure
struct CCFChunkHeader
{
// the chunk size, in bytes, including this header.
// this must always be 4-byte aligned
unsigned nSize;
// the chunk type, must be one of the CCFChunkTypeEnum constants
unsigned nType;
};
enum CCFChunkTypeEnum
{
CCF_NOT_CHUNK = -1, // this is used to signal absence of chunk
CCF_EMPTY_CHUNK = 0,
// the Compiled Cry Geometry header, contains one structure CCFCCGHeader
CCF_HEADER_CCG,
// information about geometry included into a compiled CGF file
// this chunk is followed by the structure CCFAnimGeomInfo
// and contains also subchunks:
// CCF_GI_PRIMITIVE_GROUPS
// CCF_GI_INDEX_BUFFER
// CCF_GI_EXT_TO_INT_MAP
// CCF_GI_EXT_UVS
// CCF_GI_EXT_TANGENTS
// CCF_GI_EXT_COLORS {optionally}
CCF_GEOMETRY_INFO,
// This is a pure array of material groups in CCFMaterialGroup structures
CCF_GI_PRIMITIVE_GROUPS,
// this is purely an array of unsigned shorts representing the index buffer
CCF_GI_INDEX_BUFFER,
// external to internal indexation map, again, an array of unsigned shorts.
CCF_GI_EXT_TO_INT_MAP,
// an array of CryUV's - in external indexation, for immediate copying into the vertex buffer
CCF_GI_EXT_UVS,
// an array of tangent bases in TangData structures (external indexation)
CCF_GI_EXT_TANGENTS,
// an array of DWORDs representing colors - in internal indexation
CCF_GI_INT_COLORS,
// First, struct CCFBoneDescArray followed by
// the linearized hierarchy of bones: each bone represented by serialized by CryBoneDesc data
CCF_BONE_DESC_ARRAY,
// this is an array of vertices, internal indexation; must be the exact size to contain
// number of vertices specified in CCF_GEOMETRY_INFO chunk
CCF_VERTICES,
// this is an array of normals, internal indexation; must be the exact size to contain
// all the normals (specified in CCF_GEOMETRY_INFO chunk)
CCF_NORMALS,
// this is the serialized connectivity info, without any header
CCF_STENCIL_SHADOW_CONNECTIVITY,
// this is the vertex skin, serialized CrySkinFull
CCF_SKIN_VERTICES,
// the normal skin, serialized CrySkinFull
CCF_SKIN_NORMALS,
// the skin representing tangents,
CCF_SKIN_TANGENTS,
// the array of materials: it's just followed by an integral number of structures MAT_ENTITY
CCF_MATERIALS,
// these are the faces, in internal indexation. The chunk data is a set of triples of
// ushorts (CCFIntFace) representing each face's vertices (internal indexation) and
// a set of unsigned chars (CCFIntFaceMtlID) representing the face materials
CCF_GI_INT_FACES,
// This is compound chunk containing physical info for bones of the corresponding LOD
// (The LOD is the # of occurence of this chunk in the file; there must be at most 2 such chunks)
// It's followed by a CCFBoneGeometry with the number of subsequent CCF_BG_BONE chunks
CCF_BONE_GEOMETRY,
// This is one bone geometry info for a bone. Followed by struct CCFBGBone
// and the necessary info arrays (see CCFBGBone comments)
CCF_BG_BONE,
// This is the morph target set for the geometry in this file. It contains
// ALL the morph targets for ALL LODs
// The header is CCFMorphTargetSet, followed by the specified number of
// CCF_MORPH_TARGET chunks
CCF_MORPH_TARGET_SET,
// This is the morph target. The header is CCFMorphTarget, followed by
// the raw morph target skin (serialized from the CrySkinMorph) and then the name
// All the serialized skins and the name are padded for 4 byte alignment
CCF_MORPH_TARGET,
// This is the array of light description for a character
// this chunk has the header CCFCharLightDesc and then
// the corresponding number of serialized CBoneLightBindInfo's
// all of them must be 4-byte-aligned.
CCF_CHAR_LIGHT_DESC,
// this is the compiled CAL file, that contains information about the
// animation names, file names and directives
// in case there's no CAL, the Resource Compiler finds all the proper files
// in the current directory and forms a simple CAL script from them.
// this chunk consists of subchunks that define animations or commands (CCF_ANIM_SCRIPT_*)
CCF_ANIM_SCRIPT,
// this subchunk registers a dummy animation (animation that's ignored if it's started)
// It's followed by the name of the animation
CCF_ANIM_SCRIPT_DUMMYANIM,
// the subchunk of CCF_ANIM_SCRIPT, defines the animation name and path, delimited by \0
// it contains CCFAnimInfo structure with the base info about the animation (needed to avoid loading animation
// at the beginning of the frame), which is followed by the animation name, then \0, then the path
CCF_ANIM_SCRIPT_ANIMINFO,
// the subchunk of CCF_ANIM_SCRIPT, defines a directive AnimationDir, contains the directory itself
// this should be concatenated with the last directory (new current dir relative to the current directory)
CCF_ANIM_SCRIPT_ANIMDIR,
// the subchunks of CCF_ANIM_SCRIPT, define directives ModelOffsetX, ModelOffsetY, ModelOffsetZ
// contains 3 floats with the values of offsets
CCF_ANIM_SCRIPT_MODELOFFSET,
// chunk with a set of string pairs representing the name and value of
// user-defined scene properties. It can be inside a LOD (geometry) chunk
// or as a top-level ccg chunk
CCF_USER_PROPERTIES
};
// THis is the header of CCF_ANIM_SCRIPT_ANIMINFO
struct CCFAnimInfo
{
// combination of GlobalAnimation internal flags
unsigned nAnimFlags;
// timing data, retrieved from the timing_chunk_desc
int nTicksPerFrame;
float fSecsPerTick;
// the start/end of the animation, in ticks
int nRangeStart;
int nRangeEnd;
// number of controllers in the file
unsigned numControllers;
// initializes the values in the structure to some sensible defaults
void init()
{
nAnimFlags = 0;
nTicksPerFrame = 160;
fSecsPerTick = 0.000208f;
nRangeStart = 0;
nRangeEnd = 900; // this is in ticks, means 30 frames
numControllers = 0;
}
};
// this is the header of CCF_CHAR_LIGHT_DESC chunk and is followed by
// the corresponding number of serialized CBoneLightBindInfo's
// all of them must be 4-byte-aligned.
struct CCFCharLightDesc
{
// total number of lights
unsigned numLights;
// the first numLocalLights lights are local
unsigned numLocalLights;
};
// This is the header of CCF_MORPH_TARGET_SET chunk, followed by the specified number of
// CCF_MORPH_TARGET chunks
struct CCFMorphTargetSet
{
// the number of morph targets in this set.
unsigned numMorphTargets;
};
// Represents one morph target; header of CCF_MORPH_TARGET chunk
// followed by the raw morph target skin (serialized from the CrySkinMorph) and then the name
// All the serialized skins and the name are padded for 4 byte alignment
struct CCFMorphTarget
{
// number of LODs (skins) in this morph target. Must be 1 by now
unsigned numLODs;
};
// this is the bone geometry for physics chunk header
struct CCFBoneGeometry
{
// the number of CCF_BG_BONE chunks inside this chunk
unsigned numBGBones;
};
//////////////////////////////////////////////////////////////////////////
// The header of the physical bone chunk, containing the whole info to initialize
// physical geometry of the bone
struct CCFBGBone
{
// the index of the bone, in LOD0 indexation (to be directly plugged into the bone array)
unsigned nBone;
// the geometry data
// the number of vertices in the mesh. This structure is immediately followed by
// a Vec3d array of this size
unsigned numVertices;
// the number of faces. The number of CCFIntFace structures immediately follow the
// vertex array. After them, the same number of unsigned chars follow, that describe each face material
unsigned numFaces;
};
#pragma pack(push,2)
struct CCFIntFace
{
unsigned short v[3];
CCFIntFace (){}
CCFIntFace (const unsigned short* p)
{
v[0] = p[0]; v[1] = p[1]; v[2] = p[2];
}
void operator = (const CryFace& face)
{
v[0] = face.v0;
v[1] = face.v1;
v[2] = face.v2;
}
};
#pragma pack(pop)
typedef unsigned char CCFIntFaceMtlID;
// this structure appears in the CCF_HEADER_CCG chunk at the top of the CCG file
// and contains general information about the model being loaded
struct CCFCCGHeader
{
// number of lods in this file
unsigned numLODs;
};
struct CCFAnimGeomInfo
{
// number of vertices and normals in internal indexation
unsigned numVertices;
// number of vertices, normals, UVs and Tangent Bases (external indexation)
unsigned numExtTangents;
// number of faces
unsigned numFaces;
// number of indices in the index buffer (currently always 3*numFaces)
unsigned numIndices;
// number of material/primitive groups
unsigned numPrimGroups;
};
struct CCFBoneDescArrayHeader
{
// number of bones in the hierarchy; each bone should be read with Serialize function of CryBoneDesc
unsigned numBones;
};
// array of these structures represents the groups of indices in the index buffer:
// each group has its own material id and number of elements (indices, i.e. number of faces * 3 in case of strip stripification)
struct CCFMaterialGroup
{
// material index in the original indexation of CGF
unsigned nMaterial;
// the first index in the final index buffer
unsigned short nIndexBase;
// number of indices in the final index buffer
unsigned short numIndices;
};
// This is utility that can be used to easily write CCF format files
// just open the file, create this object on stack and add the chunk with
// AddChunk(nType)
// Then write the chunk directly to the file, and then add new chunk,
// repeat the process..
// Destroy (or call CloseChunk()) this object before you close the file.
// To have nested chunks, create another instance of CCFWriter and use it for some time.
// When you destruct it, you can use the upper-level writer. And so on.
class CCFFileWriter
{
public:
CCFFileWriter (FILE* f):
m_pFile (f), m_nLastChunk (-1)
{
}
CCFFileWriter ():
m_pFile(NULL), m_nLastChunk(-1)
{
}
~CCFFileWriter()
{
CloseChunk();
}
// changes the file handle
void SetFile (FILE* f)
{
CloseChunk();
m_pFile = f;
}
// adds a new chunk of the specified type
// returns 1 if successfully wrote the chunk header or 0 if an error occurred
size_t AddChunk(CCFChunkTypeEnum nType)
{
// first, end the previous chunk
CloseChunk();
// remember the current position
m_nLastChunk = ftell (m_pFile);
// write the chunk header
CCFChunkHeader header;
header.nType = nType;
header.nSize = 0;
return fwrite (&header, sizeof(header), 1, m_pFile);
}
// Signals the end of the chunk that was added with AddChunk
// Automatically aligns the chunk data by 4-byte boundary, if needed
void CloseChunk()
{
if (m_nLastChunk < 0)
return; // no last chunk, or the last chunk was closed
long nNewChunkPos = ftell (m_pFile);
if (nNewChunkPos&3)
{
// align by 4-byte boundary
int nPad = 0;
fwrite (&nPad, 1, 4-(nNewChunkPos&3), m_pFile);
nNewChunkPos = ftell (m_pFile);
}
// write the size of the chunk to the chunk header
fseek (m_pFile, (INT_PTR)(&((CCFChunkHeader*)0)->nSize)+m_nLastChunk, SEEK_SET);
unsigned nSize = nNewChunkPos - m_nLastChunk;
fwrite (&nSize, sizeof(nSize), 1, m_pFile);
// set the file pointer back where it was
fseek (m_pFile, nNewChunkPos, SEEK_SET);
// forget about the last chunk
m_nLastChunk = -1;
}
protected:
// the file to which the chunks are written
FILE* m_pFile;
// the last chunk position within the file (used to update the chunk)
long m_nLastChunk;
};
//////////////////////////////////////////////////////////////////////////
// This class is used to read the CCF files.
// Just open the file, and pass it to an instance of this class CCFReader.
// Immediately after construction, check IsEnd(). If it's false, the chunk header will be available via
// getType(), getChunkSize(), getDataSize() and readData()
// Call Skip() until there are no more available data (in which case Skip() will return false)
class CCFFileReader
{
public:
// ASSUMES: the file pointer is exactly at some chunk header
CCFFileReader (FILE* f):
m_pFile (f)
{
Reset();
}
// starts all over again
void Reset()
{
m_nNextChunk = 0;
Skip();
}
// indicates the end of data stream, or error
bool IsEnd()
{
return m_Header.nType == CCF_NOT_CHUNK;
}
CCFChunkTypeEnum GetChunkType()
{
return (CCFChunkTypeEnum)m_Header.nType;
}
// returns the whole chunk size, including the chunk header, in bytes
unsigned GetChunkSize()const
{
return m_Header.nSize;
}
// returns the chunk data size, in bytes
unsigned GetDataSize ()const
{
return m_Header.nSize - sizeof(m_Header);
}
// reads the data into the supplied buffer (must be at least GetDataSize() bytes)
// returns true when successful
bool ReadData (void* pBuffer)
{
return 1 == fread (pBuffer, GetDataSize(), 1, m_pFile);
}
// skips the current chunk and goes no to the next one.
// returns true if successful
bool Skip ()
{
// be pessimistic - we won't read it
m_Header.nType = CCF_NOT_CHUNK;
m_Header.nSize = -1;
if (!m_pFile)
return false;
if (fseek (m_pFile, m_nNextChunk, SEEK_SET))
return false; // couldn't seek
if (1 != fread (&m_Header, sizeof(m_Header),1, m_pFile))
return false; // couldn't read
m_nNextChunk += m_Header.nSize;
return true;// read it
}
protected:
// current file
FILE* m_pFile;
// current chunk header (the file pointer is located after this chunk)
CCFChunkHeader m_Header;
// the next chunk absolute position
int m_nNextChunk;
};
//////////////////////////////////////////////////////////////////////////
// This class is used to read the CCF-formatted memory mapped files.
// Just pass the block of memory representing contents of CCF file to an instance of this class.
// Immediately after construction, check IsEnd(). If it's false, the chunk header will be available via
// getChunkType(), getChunkSize(), getDataSize() and getData()
// Call Skip() until there are no more available data (in which case Skip() will return false)
class CCFMemReader
{
public:
// we don't support chunks of > this size
enum {g_nMaxChunkSize = 0x40000000};
// ASSUMES: the file pointer is exactly at some chunk header
CCFMemReader (const void* pData, unsigned nSize):
m_pData ((const char*)pData), m_pEnd ((const char*)pData + nSize)
{
Reset();
}
// starts all over again
void Reset ()
{
if (m_pEnd - m_pData > sizeof(CCFChunkHeader) && ((unsigned)(m_pEnd - m_pData)) <= g_nMaxChunkSize)
{
m_pHeader = (CCFChunkHeader*)m_pData;
if (((const char*)m_pHeader)+m_pHeader->nSize > m_pEnd || m_pHeader->nSize > g_nMaxChunkSize)
m_pHeader = NULL; // Error: data truncated
}
else
m_pHeader = NULL; // Error: header truncated
}
// indicates the end of data stream, or error
bool IsEnd()
{
return !m_pHeader;
}
CCFChunkTypeEnum GetChunkType()
{
return (CCFChunkTypeEnum)m_pHeader->nType;
}
// returns the whole chunk size, including the chunk header, in bytes
unsigned GetChunkSize()const
{
return m_pHeader->nSize;
}
// returns the chunk data size, in bytes
unsigned GetDataSize ()const
{
return m_pHeader->nSize - sizeof(*m_pHeader);
}
// reads the data into the supplied buffer (must be at least GetDataSize() bytes)
// returns true when successful
const void* GetData ()
{
return m_pHeader+1;
}
// skips the current chunk and goes no to the next one.
// returns true if successful
bool Skip ()
{
// be optimistic - assume we will end up with successful step to the next chunk
m_pHeader = (const CCFChunkHeader*)(((const char*)m_pHeader) + m_pHeader->nSize);
if ((const char*)(m_pHeader+1) > m_pEnd)
{
// there's no next chunk, or its header is truncated
m_pHeader = NULL;
return false;
}
if (m_pHeader->nSize < sizeof(CCFChunkHeader)
|| (unsigned)m_pHeader->nSize > g_nMaxChunkSize)
{
// the header size is unsupported (most probably a noisy header)
m_pHeader = NULL;
return false;
}
if (((const char*)m_pHeader)+m_pHeader->nSize > m_pEnd)
{
// the chunk header is maybe ok, but the chunk data is truncated; or maybe
// the chunk header contains noise
m_pHeader = NULL;
return false;
}
return true;
}
protected:
// the whole data
const char* m_pData;
// the end of the whole data
const char* m_pEnd;
// current chunk header (the file pointer is located after this chunk)
const CCFChunkHeader* m_pHeader;
};
#endif

View File

@@ -0,0 +1,50 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Common Source code
//
// File:CryEngineDecalInfo.h
// Description: declaration of struct CryEngineDecalInfo.
//
// History:
// -Sep 23, 2002: Created by Sergiy Migdalskiy
//
// Note:
// 3D Engine and Character Animation subsystems (as well as perhaps
// some others) transfer data about the decals that need to be spawned
// via this structure. This is to avoid passing many parameters through
// each function call, and to save on copying these parameters when just
// simply passing the structure from one function to another.
//
//////////////////////////////////////////////////////////////////////
#ifndef _CRY_ENGINE_DECAL_INFO_HDR_
#define _CRY_ENGINE_DECAL_INFO_HDR_
// Summary:
// Structure containing common parameters that describe a decal
struct CryEngineDecalInfo
{
struct IEntityRender * pDecalOwner; // Owner (decal will be rendered on this entity)
Vec3_tpl<float> vPos; // Decal position (world coordinates)
Vec3_tpl<float> vNormal; // Decal/face normal
float fSize; // Decal size
float fLifeTime; // Decal life time (in seconds)
INT_PTR nTid; // Texture Id //@@ AMD Port
float fAngle; // Angle of rotation
INT_PTR nPartID; // Entity part id which determines the bone id in case of a character which has been the hit //@@AMD Port
struct IStatObj * pStatObj; // Decal geometry
Vec3_tpl<float> vHitDirection; // Direction from weapon/player position to decal position (bullet direction)
float m_fGrowTime; // Used for blood pools
bool bAdjustPos; // Place decal on some visible surface
// the constructor fills in some non-obligatory fields; the other fields must be filled in by the client
CryEngineDecalInfo ()
{
memset(this,0,sizeof(*this));
nPartID = -1;
bAdjustPos = true;
}
};
#endif

217
CryCommon/CryFile.h Normal file
View File

@@ -0,0 +1,217 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2002.
// -------------------------------------------------------------------------
// File name: cryfile.h
// Version: v1.00
// Created: 3/7/2003 by Timur.
// Compilers: Visual Studio.NET
// Description: File wrapper.
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#ifndef __cryfile_h__
#define __cryfile_h__
#pragma once
#include "ISystem.h"
#include "ICryPak.h"
//////////////////////////////////////////////////////////////////////////
// Wrapper on file system.
//////////////////////////////////////////////////////////////////////////
class CCryFile
{
public:
CCryFile();
CCryFile( const char *filename, const char *mode );
virtual ~CCryFile();
virtual bool Open( const char *filename, const char *mode );
virtual void Close();
//! Writes data in a file to the current file position.
virtual size_t Write( void *lpBuf,size_t nSize );
//! Reads data from a file at the current file position.
virtual size_t Read( void *lpBuf,size_t nSize );
//! Retrieves the length of the file.
virtual size_t GetLength();
//! Positions the current file pointer.
virtual size_t Seek( size_t seek, int mode );
//! Positions the current file pointer at the beginning of the file.
void SeekToBegin();
//! Positions the current file pointer at the end of the file.
size_t SeekToEnd();
//! Retrieves the current file pointer.
size_t GetPosition();
//! Tests for end-of-file on a selected file.
virtual bool IsEof();
//! Flushes any data yet to be written.
virtual void Flush();
//! A handle to a pack object.
FILE* GetHandle() const { return m_file; };
// Retrieves the filename of the selected file.
const char* GetFilename() const { return m_filename.c_str(); };
//! Check if file is opened from pak file.
bool IsInPak() const;
//! Get path of archive this file is in.
const char* GetPakPath() const;
private:
string m_filename;
FILE *m_file;
ICryPak *m_pIPak;
};
//////////////////////////////////////////////////////////////////////////
// CCryFile implementation.
//////////////////////////////////////////////////////////////////////////
inline CCryFile::CCryFile()
{
m_file = 0;
m_pIPak = GetISystem()->GetIPak();
}
//////////////////////////////////////////////////////////////////////////
inline CCryFile::CCryFile( const char *filename, const char *mode )
{
m_file = 0;
m_pIPak = GetISystem()->GetIPak();
Open( filename,mode );
}
//////////////////////////////////////////////////////////////////////////
inline CCryFile::~CCryFile()
{
Close();
}
//////////////////////////////////////////////////////////////////////////
inline bool CCryFile::Open( const char *filename, const char *mode )
{
if (m_file)
Close();
m_filename = filename;
m_file = m_pIPak->FOpen( filename,mode );
return m_file != NULL;
}
//////////////////////////////////////////////////////////////////////////
inline void CCryFile::Close()
{
if (m_file)
{
m_pIPak->FClose(m_file);
m_file = 0;
m_filename = "";
}
}
//////////////////////////////////////////////////////////////////////////
inline size_t CCryFile::Write( void *lpBuf,size_t nSize )
{
assert( m_file );
return m_pIPak->FWrite( lpBuf,1,nSize,m_file );
}
//////////////////////////////////////////////////////////////////////////
inline size_t CCryFile::Read( void *lpBuf,size_t nSize )
{
assert( m_file );
return m_pIPak->FRead( lpBuf,1,nSize,m_file );
}
//////////////////////////////////////////////////////////////////////////
inline size_t CCryFile::GetLength()
{
assert( m_file );
long curr = m_pIPak->FTell(m_file);
m_pIPak->FSeek( m_file,0,SEEK_END );
long size = m_pIPak->FTell(m_file);
m_pIPak->FSeek(m_file,curr,SEEK_SET);
return size;
}
#ifdef WIN64
#pragma warning( push ) //AMD Port
#pragma warning( disable : 4267 )
#endif
//////////////////////////////////////////////////////////////////////////
inline size_t CCryFile::Seek( size_t seek, int mode )
{
assert( m_file );
return m_pIPak->FSeek( m_file,seek,mode );
}
#ifdef WIN64
#pragma warning( pop ) //AMD Port
#endif
//////////////////////////////////////////////////////////////////////////
inline void CCryFile::SeekToBegin()
{
Seek( 0,SEEK_SET );
}
//////////////////////////////////////////////////////////////////////////
inline size_t CCryFile::SeekToEnd()
{
Seek( 0,SEEK_END );
}
//////////////////////////////////////////////////////////////////////////
inline size_t CCryFile::GetPosition()
{
assert(m_file);
return m_pIPak->FTell(m_file);
}
//////////////////////////////////////////////////////////////////////////
inline bool CCryFile::IsEof()
{
assert(m_file);
return m_pIPak->FEof(m_file) != 0;
}
//////////////////////////////////////////////////////////////////////////
inline void CCryFile::Flush()
{
assert( m_file );
m_pIPak->FFlush( m_file );
}
//////////////////////////////////////////////////////////////////////////
inline bool CCryFile::IsInPak() const
{
if (m_file)
{
if (m_pIPak->GetFileArchivePath(m_file) != NULL)
return true;
}
return false;
}
//////////////////////////////////////////////////////////////////////////
inline const char* CCryFile::GetPakPath() const
{
if (m_file)
{
const char *sPath = m_pIPak->GetFileArchivePath(m_file);
if (sPath != NULL)
return sPath;
}
return "";
}
#endif // __cryfile_h__

1264
CryCommon/CryHeaders.h Normal file

File diff suppressed because it is too large Load Diff

98
CryCommon/CryLibrary.h Normal file
View File

@@ -0,0 +1,98 @@
#ifndef CRYLIBRARY_H__
#define CRYLIBRARY_H__
/*!
CryLibrary
Convenience-Macros which abstract the use of DLLs/shared libraries in a platform independent way.
A short explanation of the different macros follows:
CrySharedLibraySupported:
This macro can be used to test if the current active platform support shared library calls. The default
value is false. This gets redefined if a certain platform (WIN32 or LINUX) is desired.
CrySharedLibrayExtension:
The default extension which will get appended to library names in calls to CryLoadLibraryDefExt
(see below).
CryLoadLibrary(libName):
Loads a shared library.
CryLoadLibraryDefExt(libName):
Loads a shared library. The platform-specific default extension is appended to the libName. This allows
writing of somewhat platform-independent library loading code and is therefore the function which should
be used most of the time, unless some special extensions are used (e.g. for plugins).
CryGetProcAddress(libHandle, procName):
Import function from the library presented by libHandle.
CryFreeLibrary(libHandle):
Unload the library presented by libHandle.
HISTORY:
03.03.2004 MarcoK
- initial version
- added to CryPlatform
*/
#include <stdio.h>
#if defined(WIN32)
#include <windows.h>
#define CrySharedLibraySupported true
#define CrySharedLibrayExtension ".dll"
#define CryLoadLibrary(libName) ::LoadLibrary(libName)
#define CryGetProcAddress(libHandle, procName) ::GetProcAddress((HMODULE)libHandle, procName)
#define CryFreeLibrary(libHandle) ::FreeLibrary(libHandle)
#elif defined(LINUX)
#include <dlfcn.h>
#include <stdlib.h>
#include "platform.h"
// for compatibility with code written for windows
#define CrySharedLibraySupported true
#define CrySharedLibrayExtension ".so"
#define CryGetProcAddress(libHandle, procName) ::dlsym(libHandle, procName)
#define CryFreeLibrary(libHandle) ::dlclose(libHandle)
#define HMODULE void*
static const char* gEnvName("MODULE_PATH");
static const char* GetModulePath()
{
return getenv(gEnvName);
}
static void SetModulePath(const char* pModulePath)
{
setenv(gEnvName, pModulePath?pModulePath:"",true);
}
static HMODULE CryLoadLibrary(const char* libName, const bool cAppend = true, const bool cLoadLazy = false)
{
string newLibName(GetModulePath());
#if !defined(NDEBUG)
string t(libName);
string c("_debug.so");
if(cAppend)
t.replace(t.size()-3, c.size(), c.c_str());
newLibName += t;
printf("loading library %s...\n",newLibName.c_str());
#else
newLibName += libName;
#endif
return ::dlopen(newLibName.c_str(), cLoadLazy?(RTLD_LAZY | RTLD_GLOBAL):(RTLD_NOW | RTLD_GLOBAL));
}
#else
#define CrySharedLibraySupported false
#define CrySharedLibrayExtension ""
#define CryLoadLibrary(libName) NULL
#define CryLoadLibraryDefExt(libName) CryLoadLibrary(libName CrySharedLibrayExtension)
#define CryGetProcAddress(libHandle, procName) NULL
#define CryFreeLibrary(libHandle)
#endif
#endif //CRYLIBRARY_H__

View File

@@ -0,0 +1,354 @@
#ifndef _CRY_MEMORY_MANAGER_H_
#define _CRY_MEMORY_MANAGER_H_
#include <malloc.h>
#include <platform.h>
#include <stdlib.h>
#ifdef WIN32
#ifdef CRYSYSTEM_EXPORTS
#define CRYMEMORYMANAGER_API __declspec(dllexport)
#else
#define CRYMEMORYMANAGER_API __declspec(dllimport)
#endif
#endif //WIN32
#if defined(LINUX)
#define CRYMEMORYMANAGER_API
#endif //LINUX
#if defined(LINUX)
#define HMODULE void*
#include <dlfcn.h>
#endif
//! Structure filled by call to CryModuleGetMemoryInfo()
struct CryModuleMemoryInfo
{
//! Total Ammount of memory allocated.
uint64 allocated;
//! Total Ammount of memory freed.
uint64 freed;
//! Total number of memory allocations.
int num_allocations;
};
#if defined(LINUX)
#undef _ACCESS_POOL
#undef _SYSTEM_POOL
#define _SYSTEM_POOL(a)
#define _ACCESS_POOL
#define CryModuleMalloc malloc
#define CryModuleRealloc realloc
#define CryModuleFree free
#ifdef __cplusplus
inline void* CryModuleReallocSize(void *ptr,size_t oldsize,size_t size) { return CryModuleRealloc(ptr,size);}
inline void CryModuleFreeSize(void *ptr,size_t size) { CryModuleFree(ptr);}
#include <new>
inline void * __cdecl operator new (size_t size) throw(std::bad_alloc) { return CryModuleMalloc(size); }
inline void * __cdecl operator new[](size_t size) throw(std::bad_alloc) { return CryModuleMalloc(size); };
inline void __cdecl operator delete (void *p) { CryModuleFree(p); };
inline void __cdecl operator delete[](void *p) { CryModuleFree(p); };
#else
static void* CryModuleReallocSize(void *ptr,size_t oldsize,size_t size) { return CryModuleRealloc(ptr,size);}
static void CryModuleFreeSize(void *ptr,size_t size) { CryModuleFree(ptr);}
#endif
#else
//////////////////////////////////////////////////////////////////////////
// Used by overrided new and delete operators.
//////////////////////////////////////////////////////////////////////////
#ifdef __cplusplus
// C++ methods.
extern "C"
{
void* CryModuleMalloc(size_t size) throw();
void* CryModuleRealloc(void *memblock,size_t size) throw();
void CryModuleFree(void *ptr) throw();
void* CryModuleReallocSize(void *memblock,size_t oldsize,size_t size);
void CryModuleFreeSize(void *ptr,size_t size);
}
#else
// C methods.
extern void* CryModuleMalloc(size_t size);
extern void* CryModuleRealloc(void *memblock,size_t size);
extern void CryModuleFree(void *ptr);
extern void* CryModuleReallocSize(void *memblock,size_t oldsize,size_t size);
extern void CryModuleFreeSize(void *ptr,size_t size);
#endif //__cplusplus
//////////////////////////////////////////////////////////////////////////
#ifdef __cplusplus
extern "C" {
#endif
#if defined(CRYSYSTEM_EXPORTS) || (!defined(WIN32) && !defined(LINUX))
CRYMEMORYMANAGER_API void *CryMalloc(size_t size);
CRYMEMORYMANAGER_API void *CryRealloc(void *memblock,size_t size);
CRYMEMORYMANAGER_API void *CryReallocSize(void *memblock,size_t oldsize,size_t size);
CRYMEMORYMANAGER_API void CryFree(void *p);
CRYMEMORYMANAGER_API void CryFreeSize(void *p,size_t size);
CRYMEMORYMANAGER_API int CryStats(char *buf);
CRYMEMORYMANAGER_API void CryFlushAll();
#endif
#ifdef __cplusplus
}
#endif
//#ifndef CRYSYSTEM_EXPORTS
#define _ACCESS_POOL
#if defined(_DEBUG) || defined(DONT_USE_CRY_MEMORY_MANAGER)
#define CryModuleMalloc malloc
#define CryModuleRealloc realloc
#define CryModuleFree free
#else
#ifdef USE_NEWPOOL
#define USING_CRY_MEMORY_MANAGER
// - check this covers all prototypes
// - way to check memory in use by old malloc?
// issues
// only release
// - globals with allocs -> can make it possible but rather not
// - calloc? also malloc -> new
//////////////////////////////////////////////////////////////////////////
// _PoolHelper definition.
//////////////////////////////////////////////////////////////////////////
#ifdef __cplusplus
struct _CryMemoryManagerPoolHelper
{
uint64 allocatedMemory;
uint64 freedMemory;
int numAllocations;
#if defined(WIN32) || defined(LINUX)
HMODULE hSystem;
#endif
typedef void *(*FNC_CryMalloc)(size_t size);
typedef void *(*FNC_CryRealloc)(void *memblock,size_t size);
typedef void *(*FNC_CryReallocSize)(void *memblock,size_t oldsize,size_t size);
typedef void (*FNC_CryFree)(void *p);
typedef void (*FNC_CryFreeSize)(void *p,size_t size);
typedef int (*FNC_CryStats)(char *buf);
FNC_CryMalloc _CryMalloc;
FNC_CryRealloc _CryRealloc;
FNC_CryReallocSize _CryReallocSize;
FNC_CryFree _CryFree;
FNC_CryFreeSize _CryFreeSize;
explicit _CryMemoryManagerPoolHelper( void *pHandle = NULL )
{
allocatedMemory = 0;
freedMemory = 0;
numAllocations = 0;
#if defined(WIN32)
if (pHandle)
hSystem = (HMODULE)pHandle;
else
hSystem = LoadLibrary("CrySystem.dll");
#endif
#if defined(LINUX)
if (pHandle)
hSystem = (HMODULE)pHandle;
else
hSystem = ::dlopen("crysystem.so", (RTLD_NOW/*RTLD_LAZY*/ | RTLD_GLOBAL));
if(!hSystem)
{
hSystem = ::dlopen("./crysystem.so", (RTLD_NOW/*RTLD_LAZY*/ | RTLD_GLOBAL));
if(!hSystem)
{
//try some dlopen locations
const char* envName = getenv("MODULE_PATH");
if(envName)
{
char tmp[MAX_PATH+12]; //allocate statically
strcpy(tmp, envName);
strcpy(&tmp[strlen(envName)], "crysystem.so");
tmp[strlen(envName) + strlen("crysystem.so")] = '\0';
hSystem = ::dlopen(tmp, (RTLD_NOW/*RTLD_LAZY*/ | RTLD_GLOBAL));
}
if(!hSystem)
{
printf("Could not access crysystem.so (either working directory must the executable directory or LD_LIBRARY_PATH must contain the executable directory)\n");
exit(1);
}
}
}
#endif
if(hSystem)
{
#if defined(LINUX)
_CryMalloc=(FNC_CryMalloc)::dlsym(hSystem,"CryMalloc");
_CryRealloc=(FNC_CryRealloc)::dlsym(hSystem,"CryRealloc");
_CryReallocSize=(FNC_CryReallocSize)::dlsym(hSystem,"CryReallocSize");
_CryFree=(FNC_CryFree)::dlsym(hSystem,"CryFree");
_CryFreeSize=(FNC_CryFreeSize)::dlsym(hSystem,"CryFreeSize");
#else
_CryMalloc=(FNC_CryMalloc)GetProcAddress((HINSTANCE)hSystem,"CryMalloc");
_CryRealloc=(FNC_CryRealloc)GetProcAddress((HINSTANCE)hSystem,"CryRealloc");
_CryReallocSize=(FNC_CryReallocSize)GetProcAddress((HINSTANCE)hSystem,"CryReallocSize");
_CryFree=(FNC_CryFree)GetProcAddress((HINSTANCE)hSystem,"CryFree");
_CryFreeSize=(FNC_CryFreeSize)GetProcAddress((HINSTANCE)hSystem,"CryFreeSize");
#endif
};
// Not need system anymore.
#if defined(LINUX)
if(!_CryMalloc)
printf("Could not read symbol: CryMalloc from crysystem.so\n");
if(!_CryRealloc)
printf("Could not read symbol: CryRealloc from crysystem.so\n");
if(!_CryReallocSize)
printf("Could not read symbol: CryReallocSize from crysystem.so\n");
if(!_CryFree)
printf("Could not read symbol: CryFree from crysystem.so\n");
if(!_CryMalloc)
printf("Could not read symbol: CryFreeSize from crysystem.so\n");
if(!_CryMalloc || !_CryRealloc || !_CryReallocSize || !_CryFree || !_CryFreeSize)
exit(1);
#else
if(!hSystem || !_CryMalloc || !_CryRealloc || !_CryReallocSize || !_CryFree || !_CryFreeSize)
{
MessageBox(NULL, "Could not access CrySystem.dll (check working directory)", "Memory Manager", MB_OK);
if (hSystem)
::FreeLibrary( hSystem );
exit(1);
};
if (hSystem)
::FreeLibrary( hSystem );
#endif
}
~_CryMemoryManagerPoolHelper()
{
#if defined(LINUX)
if (hSystem)
::dlclose( hSystem );
#endif
}
void GetMemoryInfo( CryModuleMemoryInfo *pMmemInfo )
{
pMmemInfo->allocated = allocatedMemory;
pMmemInfo->freed = freedMemory;
pMmemInfo->num_allocations = numAllocations;
}
//////////////////////////////////////////////////////////////////////////
// Local version of allocations, does memory counting per module.
//////////////////////////////////////////////////////////////////////////
__forceinline void* Malloc(size_t size)
{
allocatedMemory += size;
numAllocations++;
return _CryMalloc( size );
}
//////////////////////////////////////////////////////////////////////////
__forceinline void* Realloc(void *memblock,size_t size)
{
if (memblock == NULL)
{
allocatedMemory += size;
numAllocations++;
}
else
{
numAllocations++;
size_t oldsize = ((int*)memblock)[-1];
allocatedMemory += size;
freedMemory += oldsize;
}
return _CryRealloc( memblock,size );
}
//////////////////////////////////////////////////////////////////////////
__forceinline void Free( void *memblock )
{
if (memblock != 0)
{
size_t size = ((int*)memblock)[-1];
freedMemory += size;
}
_CryFree( memblock );
}
//////////////////////////////////////////////////////////////////////////
__forceinline void* ReallocSize(void *memblock,size_t oldsize,size_t size)
{
allocatedMemory += size;
freedMemory += oldsize;
numAllocations++;
return _CryReallocSize( memblock,oldsize,size );
}
//////////////////////////////////////////////////////////////////////////
__forceinline void FreeSize( void *memblock,size_t size )
{
freedMemory += size;
_CryFreeSize( memblock,size );
}
};
#endif //__cplusplus
#ifdef _USRDLL
#define CRY_MEM_USAGE_API extern "C" __declspec(dllexport)
#else
#define CRY_MEM_USAGE_API
#endif
#ifndef _XBOX
#undef _ACCESS_POOL
#define _ACCESS_POOL \
_CryMemoryManagerPoolHelper g_CryMemoryManagerHelper;\
void* CryModuleMalloc( size_t size ) throw(){ return g_CryMemoryManagerHelper.Malloc(size); };\
void* CryModuleRealloc( void *ptr,size_t size ) throw(){ return g_CryMemoryManagerHelper.Realloc(ptr,size); };\
void CryModuleFree( void *ptr ) throw() { g_CryMemoryManagerHelper.Free(ptr); };\
void* CryModuleReallocSize(void *ptr,size_t oldsize,size_t size) { return g_CryMemoryManagerHelper.ReallocSize(ptr,oldsize,size); };\
void CryModuleFreeSize(void *ptr,size_t size) { g_CryMemoryManagerHelper.FreeSize(ptr,size); };\
CRY_MEM_USAGE_API void CryModuleGetMemoryInfo( CryModuleMemoryInfo *pMemInfo ) { g_CryMemoryManagerHelper.GetMemoryInfo(pMemInfo); };
// To be created inside CrySystem.
#define _SYSTEM_POOL( hSystemHandle ) \
_CryMemoryManagerPoolHelper g_CryMemoryManagerHelper( hSystemHandle );\
void* CryModuleMalloc( size_t size ) throw() {return g_CryMemoryManagerHelper.Malloc(size); };\
void* CryModuleRealloc( void *ptr,size_t size ) throw(){ return g_CryMemoryManagerHelper.Realloc(ptr,size); };\
void CryModuleFree( void *ptr ) { g_CryMemoryManagerHelper.Free(ptr); };\
void* CryModuleReallocSize(void *ptr,size_t oldsize,size_t size) { return g_CryMemoryManagerHelper.ReallocSize(ptr,oldsize,size); };\
void CryModuleFreeSize(void *ptr,size_t size) { g_CryMemoryManagerHelper.FreeSize(ptr,size); };\
CRY_MEM_USAGE_API void CryModuleGetMemoryInfo( CryModuleMemoryInfo *pMemInfo ) { g_CryMemoryManagerHelper.GetMemoryInfo(pMemInfo); };
#endif
#ifdef __cplusplus
#include <new.h>
#endif
#undef malloc
#undef realloc
#undef free
/*
inline void *malloc(unsigned int size) { return _CryMalloc(size); };
inline void *realloc(void *block, unsigned int size) { return _CryRealloc(block, size); };
inline void free(void *p) { _CryFree(p); };
*/
#define malloc CryModuleMalloc
#define realloc CryModuleRealloc
#define free CryModuleFree
#define realloc_size CryModuleReallocSize
#define free_size CryModuleFreeSize
#ifdef __cplusplus
#ifndef GAMECUBE //I don't know how to compile this on GC
inline void * __cdecl operator new (size_t size) { return CryModuleMalloc(size); }
inline void * __cdecl operator new[](size_t size) { return CryModuleMalloc(size); };
inline void __cdecl operator delete (void *p) { CryModuleFree(p); };
inline void __cdecl operator delete[](void *p) { CryModuleFree(p); };
#endif //GAMECUBE
#endif //__cplusplus
#endif // USE_NEWPOOL
#endif // _DEBUG
//#endif // CRYSYSTEM_EXPORTS
#endif //LINUX
#endif //_CRY_MEMORY_MANAGER_H_

View File

@@ -0,0 +1,90 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Common Source code
//
// File:CryParticleSpawnInfo.h
// Description: declaration of struct CryParticleSpawnInfo.
//
// History:
// -Sep 23, 2002: Created by Sergiy Migdalskiy
//
// Notes:
// 3D Engine and Character Animation subsystems (as well as perhaps
// some others) transfer data about the particles that need to be spawned
// via this structure. This is to avoid passing many parameters through
// each function call, and to save on copying these parameters when just
// simply passing the structure from one function to another.
//
//////////////////////////////////////////////////////////////////////
#ifndef __CRY_COMMON_PARTICLE_SPAWN_INFO_HDR__
#define __CRY_COMMON_PARTICLE_SPAWN_INFO_HDR__
//! Structure containing common parameters describing particle spawning
//! This is in addition to the ParticleParams defined in the 3D Engine
struct CryParticleSpawnInfo
{
public:
// Particle spawn rate: the number of particles to be spawned
// PER SECOND. The number of particles to spawn per Frame is:
// fSpawnRate * fFrameDurationSeconds
float fSpawnRate;
/*
// particle spawn mode
enum SpawnModeEnum
{
// rain mode: particles (rain drops) should reflect from the normals
// vDir sets the rain direction
SPAWN_RAIN = 0,
// particles are spawned along normal direction
SPAWN_NORMAL,
// particles are spawned randomly into the normal hemisphere (randomly, but outside the skin)
SPAWN_OUTSIDE,
// particles are spawned into the direction of vDir
SPAWN_CONST,
// particles are spawned absolutely randomly
SPAWN_RANDOM
};
SpawnModeEnum nSpawnMode;
// particle direction
Vec3 vDir;
*/
enum FlagEnum
{
// in this mode, only up-looking normals will be taken into account
FLAGS_RAIN_MODE = 1,
// with this flag, the spawn will occur only on one frame
FLAGS_ONE_TIME_SPAWN = 1 << 1,
// with this flag, nBoneId will determine the bone from which the particle will be spawned,
// vBonePos will be the position in bone coordinates at which the particles will be spawned
FLAGS_SPAWN_FROM_BONE = 1 << 2
};
// flags - combination of FlagEnum flags
unsigned nFlags;
// valid only with FLAGS_SPAWN_FROM_BONE:
// the bone number, can be determined with the ICryCharModel::GetBoneByName(), should be non-negative
unsigned nBone;
// valid only with FLAGS_SPAWN_FROM_BONE:
// the position of the particle in local bone coordinates
Vec3 vBonePos;
CryParticleSpawnInfo():
fSpawnRate (0),
nFlags (0),
nBone (0),
vBonePos(0,0,0)
{
}
CryParticleSpawnInfo (float _fSpawnRate, unsigned _nFlags = 0):
fSpawnRate(_fSpawnRate),
nFlags (_nFlags)
{
}
};
#endif

22
CryCommon/CryPhysics.h Normal file
View File

@@ -0,0 +1,22 @@
#ifndef cryphysics_h
#define cryphysics_h
#pragma once
#ifndef _XBOX
#ifdef PHYSICS_EXPORTS
#define CRYPHYSICS_API __declspec(dllexport)
#else
#define CRYPHYSICS_API __declspec(dllimport)
#define vector_class Vec3d
#endif
#else
#define CRYPHYSICS_API
#endif
#include "utils.h"
#include "primitives.h"
#include "physinterface.h"
extern "C" CRYPHYSICS_API IPhysicalWorld *CreatePhysicalWorld();
#endif

196
CryCommon/CrySizer.h Normal file
View File

@@ -0,0 +1,196 @@
//////////////////////////////////////////////////////////////////////
//
// CryEngine Source code
//
// File:CrySizer.h
// Declaration and definition of the CrySizer class, which is used to
// calculate the memory usage by the subsystems and components, to help
// the artists keep the memory budged low.
//
// History:
// December 03, 2002 : Created by Sergiy Migdalskiy <sergiy@crytek.de>
//
//////////////////////////////////////////////////////////////////////
#ifndef _CRY_COMMON_CRY_SIZER_INTERFACE_HDR_
#define _CRY_COMMON_CRY_SIZER_INTERFACE_HDR_
#ifdef GAMECUBE
#include "GCDefines.h"
#endif
#ifdef WIN64
#include <string.h> // workaround for Amd64 compiler
#endif
// prerequisities
//#include <string>
//#include <vector>
// flags applicable to the ICrySizer (retrieved via getFlags() method)
//
enum ICrySizerFlagsEnum
{
// if this flag is set, during getSize(), the subsystem must count all the objects
// it uses in the other subsystems also
CSF_RecurseSubsystems = 1 << 0,
CSF_Reserved1 = 1 << 1,
CSF_Reserved2 = 1 << 2
};
//////////////////////////////////////////////////////////////////////////
// interface ICrySizer
// USAGE
// An instance of this class is passed down to each and every component in the system.
// Every component it's passed to optionally pushes its name on top of the
// component name stack (thus ensuring that all the components calculated down
// the tree will be assigned the correct subsystem/component name)
// Every component must Add its size with one of the Add* functions, and Add the
// size of all its subcomponents recursively
// In order to push the component/system name on the name stack, the clients must
// use the SIZER_COMPONENT_NAME macro or CrySizerComponentNameHelper class:
//
// void X::getSize (ICrySizer* pSizer)
// {
// SIZER_COMPONENT_NAME(pSizer, X);
// if (!pSizer->Add (this))
// return;
// pSizer->Add (m_arrMySimpleArray);
// pSizer->Add (m_setMySimpleSet);
// m_pSubobject->getSize (pSizer);
// }
//
// The Add* functions return bool. If they return true, then the object has been added
// to the set for the first time, and you should go on recursively adding all its children.
// If it returns false, then you can spare time and rather not go on into recursion;
// however it doesn't reflect on the results: an object that's added more than once is
// counted only once.
//
// WARNING:
// If you have an array (pointer), you should Add its size with addArray
class ICrySizer
{
public:
// this class is used to push/pop the name to/from the stack automatically
// (to exclude stack overruns or underruns at runtime)
friend class CrySizerComponentNameHelper;
ICrySizer ():
m_nFlags(0)
{
}
virtual ~ICrySizer () {}
// adds an object identified by the unique pointer (it needs not be
// the actual object position in the memory, though it would be nice,
// but it must be unique throughout the system and unchanging for this object)
// RETURNS: true if the object has actually been added (for the first time)
// and calculated
virtual bool AddObject (const void* pIdentifier, size_t nSizeBytes) = 0;
template <typename T>
bool Add (const T* pId, size_t num)
{
return AddObject(pId, num * sizeof(T));
}
template <class T>
bool Add (const T& rObject)
{
return AddObject (&rObject, sizeof(T));
}
bool Add (const char* szText)
{
return AddObject(szText, strlen(szText)+1);
}
template <class String>
bool AddString (const String& strText)
{
if (!strText.empty())
return AddObject (strText.c_str(), strText.length()+1);
else
return false;
}
#ifdef _XSTRING_
template <class Elem, class Traits, class Allocator>
bool Add (const std::basic_string<Elem, Traits, Allocator>& strText)
{
AddString (strText);
}
#endif
#ifdef _STRING_
bool Add (const string& strText)
{
AddString(strText);
}
#endif
template <class Container>
bool AddContainer (const Container& rContainer)
{
if (!rContainer.empty())
return AddObject (&(*rContainer.begin()),rContainer.size()*sizeof(typename Container::value_type));
return false;
}
// returns the flags
unsigned GetFlags()const {return m_nFlags;}
protected:
// these functions must operate on the component name stack
// they are to be only accessible from within class CrySizerComponentNameHelper
// which should be used through macro SIZER_COMPONENT_NAME
virtual void Push (const char* szComponentName) = 0;
// pushes the name that is the name of the previous component . (dot) this name
virtual void PushSubcomponent (const char* szSubcomponentName) = 0;
virtual void Pop () = 0;
unsigned m_nFlags;
};
//////////////////////////////////////////////////////////////////////////
// This is on-stack class that is only used to push/pop component names
// to/from the sizer name stack.
//
// USAGE:
//
// Create an instance of this class at the start of a function, before
// calling Add* methods of the sizer interface. Everything added in the
// function and below will be considered this component, unless
// explicitly set otherwise.
//
class CrySizerComponentNameHelper
{
public:
// pushes the component name on top of the name stack of the given sizer
CrySizerComponentNameHelper (ICrySizer* pSizer, const char* szComponentName, bool bSubcomponent):
m_pSizer(pSizer)
{
if (bSubcomponent)
pSizer->PushSubcomponent (szComponentName);
else
pSizer->Push (szComponentName);
}
// pops the component name off top of the name stack of the sizer
~CrySizerComponentNameHelper()
{
m_pSizer->Pop();
}
protected:
ICrySizer* m_pSizer;
};
// use this to push (and automatically pop) the sizer component name at the beginning of the
// getSize() function
#define SIZER_COMPONENT_NAME(pSizerPointer, szComponentName) CrySizerComponentNameHelper __sizerHelper(pSizerPointer, szComponentName, false)
#define SIZER_SUBCOMPONENT_NAME(pSizerPointer, szComponentName) CrySizerComponentNameHelper __sizerHelper(pSizerPointer, szComponentName, true)
#endif //_CRY_COMMON_CRY_SIZER_INTERFACE_HDR_

107
CryCommon/CryVersion.h Normal file
View File

@@ -0,0 +1,107 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2002.
// -------------------------------------------------------------------------
// File name: cryversion.h
// Version: v1.00
// Created: 27/8/2003 by Timur.
// Compilers: Visual Studio.NET
// Description: Defines File version structure.
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#ifndef __cryversion_h__
#define __cryversion_h__
#if defined(LINUX)
# include "string.h"
# include "stdlib.h"
# include "stdio.h"
#endif
//////////////////////////////////////////////////////////////////////////
/** This class keeps file version information.
*/
struct SFileVersion
{
int v[4];
SFileVersion() {
v[0] = v[1] = v[2] = v[3] = 0;
}
SFileVersion( const int vers[] ) {
v[0] = vers[0];
v[1] = vers[1];
v[2] = vers[2];
v[3] = 1;
}
void Set(const char *s)
{
v[0] = v[1] = v[2] = v[3] = 0;
char t[50]; char* p;
strcpy(t,s);
if(!(p = strtok(t,"."))) return;
v[3] = atoi(p);
if(!(p = strtok(NULL,"."))) return;
v[2] = atoi(p);
if(!(p = strtok(NULL,"."))) return;
v[1] = atoi(p);
if(!(p = strtok(NULL,"."))) return;
v[0] = atoi(p);
}
explicit SFileVersion( const char* s )
{
Set(s);
}
bool operator <( const SFileVersion &v2 ) const {
if (v[3] < v2.v[3]) return true;
if (v[3] > v2.v[3]) return false;
if (v[2] < v2.v[2]) return true;
if (v[2] > v2.v[2]) return false;
if (v[1] < v2.v[1]) return true;
if (v[1] > v2.v[1]) return false;
if (v[0] < v2.v[0]) return true;
if (v[0] > v2.v[0]) return false;
return false;
}
bool operator ==( const SFileVersion &v1 ) const {
if (v[0] == v1.v[0] && v[1] == v1.v[1] &&
v[2] == v1.v[2] && v[3] == v1.v[3]) return true;
return false;
}
bool operator >( const SFileVersion &v1) const {
return !(*this < v1);
}
bool operator >=( const SFileVersion &v1) const {
return (*this == v1) || (*this > v1);
}
bool operator <=( const SFileVersion &v1) const {
return (*this == v1) || (*this < v1);
}
int& operator[](int i) { return v[i];}
int operator[](int i) const { return v[i];}
void ToShortString( char *s ) const
{
sprintf( s,"%d.%d.%d",v[2],v[1],v[0] );
}
void ToString( char *s ) const
{
sprintf( s,"%d.%d.%d.%d",v[3],v[2],v[1],v[0] );
}
};
#endif // __cryversion_h__

1084
CryCommon/Cry_Camera.h Normal file

File diff suppressed because it is too large Load Diff

550
CryCommon/Cry_Color4.h Normal file
View File

@@ -0,0 +1,550 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek (C) 2001
//
// File: CryColor4.h
// Description: 4D Color template.
//
// History:
// - August 12, 2001: Created by Alberto Demichelis
//
//////////////////////////////////////////////////////////////////////
#ifndef CRYTEK_CRYCOLOR4_H
#define CRYTEK_CRYCOLOR4_H
//////////////////////////////////////////////////////////////////////////////////////////////
#define RGBA8( r,g,b,a ) ( uint32( ##(r)|(g<<8)|(b<<16)|(a<<24)##) )
template <class T> struct color4;
typedef color4<uint8> Color; // [0, 255]
typedef color4<f32> color4f; // [0.0, 1.0]
typedef color4<f64> color4d; // [0.0, 1.0]
typedef color4<uint8> color4b; // [0, 255]
typedef color4<uint16> color4w; // [0, 65535]
//////////////////////////////////////////////////////////////////////////////////////////////
// RGBA Color structure.
//////////////////////////////////////////////////////////////////////////////////////////////
template <class T> struct color4
{
union {
struct { T r,g,b,a; };
T v[4];
};
inline color4();
inline color4(const T *p_elts);
inline color4(const color4 & v);
inline color4(T _x, T _y = 0, T _z = 0, T _w = 0);
inline color4( uint32 c ) { *(uint32*)(&v)=c; } //use this with RGBA8 macro!
inline void set(T _x, T _y = 0, T _z = 0, T _w = 0);
inline void set(T _x, T _y = 0, T _z = 0);
inline color4 operator + () const;
inline color4 operator - () const;
inline color4 & operator += (const color4 & v);
inline color4 & operator -= (const color4 & v);
inline color4 & operator *= (const color4 & v);
inline color4 & operator /= (const color4 & v);
inline color4 & operator *= (T s);
inline color4 & operator /= (T s);
inline color4 operator + (const color4 & v) const;
inline color4 operator - (const color4 & v) const;
inline color4 operator * (const color4 & v) const;
inline color4 operator / (const color4 & v) const;
inline color4 operator * (T s) const;
inline color4 operator / (T s) const;
inline bool operator == (const color4 & v) const;
inline bool operator != (const color4 & v) const;
inline unsigned char pack_rgb332();
inline unsigned short pack_argb4444();
inline unsigned short pack_rgb555();
inline unsigned short pack_rgb565();
inline unsigned int pack_rgb888();
inline unsigned int pack_argb8888();
inline unsigned int pack8() { return pack_rgb332(); }
inline unsigned int pack12() { return pack_argb4444(); }
inline unsigned int pack15() { return pack_rgb555(); }
inline unsigned int pack16() { return pack_rgb565(); }
inline unsigned int pack24() { return pack_rgb888(); }
inline unsigned int pack32() { return pack_argb8888(); }
inline void clamp(T bottom = 0.0f, T top = 1.0f);
inline void maximum(const color4<T> &ca, const color4<T> &cb);
inline void minimum(const color4<T> &ca, const color4<T> &cb);
inline void abs();
inline void adjust_contrast(T c);
inline void adjust_saturation(T s);
inline void lerp(const color4<T> &ca, const color4<T> &cb, T s);
inline void negative(const color4<T> &c);
inline void grey(const color4<T> &c);
inline void black_white(const color4<T> &c, T s);
};
//////////////////////////////////////////////////////////////////////////////////////////////
// functions implementation
///////////////////////////////////////////////
template <class T>
inline color4<T>::color4() { }
///////////////////////////////////////////////
template <class T>
inline color4<T>::color4(const T *p_elts)
{
r = p_elts[0]; g = p_elts[1]; b = p_elts[2]; a = p_elts[3];
}
///////////////////////////////////////////////
template <class T>
inline color4<T>::color4(const color4<T> & v)
{
r = v.r; g = v.g; b = v.b; a = v.a;
}
///////////////////////////////////////////////
template <class T>
inline color4<T>::color4(T _x, T _y, T _z, T _w)
{
r = _x; g = _y; b = _z; a = _w;
}
///////////////////////////////////////////////
template <class T>
inline void color4<T>::set(T _x, T _y, T _z, T _w)
{
r = _x; g = _y; b = _z; a = _w;
}
///////////////////////////////////////////////
template <class T>
inline void color4<T>::set(T _x, T _y, T _z)
{
r = _x; g = _y; b = _z; a = 1;
}
///////////////////////////////////////////////
template <class T>
inline color4<T> color4<T>::operator + () const
{
return *this;
}
///////////////////////////////////////////////
template <class T>
inline color4<T> color4<T>::operator - () const
{
return color4<T>(-r, -g, -b, -a);
}
///////////////////////////////////////////////
template <class T>
inline color4<T> & color4<T>::operator += (const color4<T> & v)
{
r += v.r; g += v.g; b += v.b; a += v.a;
return *this;
}
///////////////////////////////////////////////
template <class T>
inline color4<T> & color4<T>::operator -= (const color4<T> & v)
{
r -= v.r; g -= v.g; b -= v.b; a -= v.a;
return *this;
}
///////////////////////////////////////////////
template <class T>
inline color4<T> & color4<T>::operator *= (const color4<T> & v)
{
r *= v.r; g *= v.g; b *= v.b; a *= v.a;
return *this;
}
///////////////////////////////////////////////
template <class T>
inline color4<T> & color4<T>::operator /= (const color4<T> & v)
{
r /= v.r; g /= v.g; b /= v.b; a /= v.a;
return *this;
}
///////////////////////////////////////////////
template <class T>
inline color4<T> & color4<T>::operator *= (T s)
{
r *= s; g *= s; b *= s; a *= s;
return *this;
}
///////////////////////////////////////////////
template <class T>
inline color4<T> & color4<T>::operator /= (T s)
{
s = 1.0f / s;
r *= s; g *= s; b *= s; a *= s;
return *this;
}
///////////////////////////////////////////////
template <class T>
inline color4<T> color4<T>::operator + (const color4<T> & v) const
{
return color4<T>(r + v.r, g + v.g, b + v.b, a + v.a);
}
///////////////////////////////////////////////
template <class T>
inline color4<T> color4<T>::operator - (const color4<T> & v) const
{
return color4<T>(r - v.r, g - v.g, b - v.b, a - v.a);
}
///////////////////////////////////////////////
template <class T>
inline color4<T> color4<T>::operator * (T s) const
{
return color4<T>(r * s, g * s, b * s, a * s);
}
///////////////////////////////////////////////
template <class T>
inline color4<T> color4<T>::operator / (T s) const
{
s = 1.0f / s;
return color4<T>(r * s, g * s, b * s, a * s);
}
///////////////////////////////////////////////
template <class T>
inline bool color4<T>::operator == (const color4<T> & v) const
{
return (r == v.r) && (g == v.g) && (b == v.b) && (a == v.a);
}
///////////////////////////////////////////////
template <class T>
inline bool color4<T>::operator != (const color4<T> & v) const
{
return (r != v.r) || (g != v.g) || (b != v.b) || (a != v.a);
}
///////////////////////////////////////////////
template <class T>
inline color4<T> operator * (T s, const color4<T> & v)
{
return color4<T>(v.r * s, v.g * s, v.b * s, v.a * s);
}
///////////////////////////////////////////////
template <class T>
inline unsigned char color4<T>::pack_rgb332()
{
unsigned char cr;
unsigned char cg;
unsigned char cb;
if(sizeof(r) == 1) // char and unsigned char
{
cr = r;
cg = g;
cb = b;
}
else if(sizeof(r) == 2) // short and unsigned short
{
cr = (unsigned short)(r)>>8;
cg = (unsigned short)(g)>>8;
cb = (unsigned short)(b)>>8;
}
else // float or double
{
cr = (unsigned char)(r * 255.0f);
cg = (unsigned char)(g * 255.0f);
cb = (unsigned char)(b * 255.0f);
}
return ((cr >> 5) << 5) | ((cg >> 5) << 2) | (cb >> 5);
}
///////////////////////////////////////////////
template <class T>
inline unsigned short color4<T>::pack_argb4444()
{
unsigned char cr;
unsigned char cg;
unsigned char cb;
unsigned char ca;
if(sizeof(r) == 1) // char and unsigned char
{
cr = r;
cg = g;
cb = b;
ca = a;
}
else if(sizeof(r) == 2) // short and unsigned short
{
cr = (unsigned short)(r)>>8;
cg = (unsigned short)(g)>>8;
cb = (unsigned short)(b)>>8;
ca = (unsigned short)(a)>>8;
}
else // float or double
{
cr = (unsigned char)(r * 255.0f);
cg = (unsigned char)(g * 255.0f);
cb = (unsigned char)(b * 255.0f);
ca = (unsigned char)(a * 255.0f);
}
return ((ca >> 4) << 12) | ((cr >> 4) << 8) | ((cg >> 4) << 4) | (cb >> 4);
}
///////////////////////////////////////////////
template <class T>
inline unsigned short color4<T>::pack_rgb555()
{
unsigned char cr;
unsigned char cg;
unsigned char cb;
if(sizeof(r) == 1) // char and unsigned char
{
cr = r;
cg = g;
cb = b;
}
else if(sizeof(r) == 2) // short and unsigned short
{
cr = (unsigned short)(r)>>8;
cg = (unsigned short)(g)>>8;
cb = (unsigned short)(b)>>8;
}
else // float or double
{
cr = (unsigned char)(r * 255.0f);
cg = (unsigned char)(g * 255.0f);
cb = (unsigned char)(b * 255.0f);
}
return ((cr >> 3) << 10) | ((cg >> 3) << 5) | (cb >> 3);
}
///////////////////////////////////////////////
template <class T>
inline unsigned short color4<T>::pack_rgb565()
{
unsigned char cr;
unsigned char cg;
unsigned char cb;
if(sizeof(r) == 1) // char and unsigned char
{
cr = r;
cg = g;
cb = b;
}
else if(sizeof(r) == 2) // short and unsigned short
{
cr = (unsigned short)(r)>>8;
cg = (unsigned short)(g)>>8;
cb = (unsigned short)(b)>>8;
}
else // float or double
{
cr = (unsigned char)(r * 255.0f);
cg = (unsigned char)(g * 255.0f);
cb = (unsigned char)(b * 255.0f);
}
return ((cr >> 3) << 11) | ((cg >> 2) << 5) | (cb >> 3);
}
///////////////////////////////////////////////
template <class T>
inline unsigned int color4<T>::pack_rgb888()
{
unsigned char cr;
unsigned char cg;
unsigned char cb;
if(sizeof(r) == 1) // char and unsigned char
{
cr = r;
cg = g;
cb = b;
}
else if(sizeof(r) == 2) // short and unsigned short
{
cr = (unsigned short)(r)>>8;
cg = (unsigned short)(g)>>8;
cb = (unsigned short)(b)>>8;
}
else // float or double
{
cr = (unsigned char)(r * 255.0f);
cg = (unsigned char)(g * 255.0f);
cb = (unsigned char)(b * 255.0f);
}
return (cr << 16) | (cg << 8) | cb;
}
///////////////////////////////////////////////
template <class T>
inline unsigned int color4<T>::pack_argb8888()
{
unsigned char cr;
unsigned char cg;
unsigned char cb;
unsigned char ca;
if(sizeof(r) == 1) // char and unsigned char
{
cr = r;
cg = g;
cb = b;
ca = a;
}
else if(sizeof(r) == 2) // short and unsigned short
{
cr = (unsigned short)(r)>>8;
cg = (unsigned short)(g)>>8;
cb = (unsigned short)(b)>>8;
ca = (unsigned short)(a)>>8;
}
else // float or double
{
cr = (unsigned char)(r * 255.0f);
cg = (unsigned char)(g * 255.0f);
cb = (unsigned char)(b * 255.0f);
ca = (unsigned char)(a * 255.0f);
}
return (ca << 24) | (cr << 16) | (cg << 8) | cb;
}
///////////////////////////////////////////////
template <class T>
inline void color4<T>::clamp(T bottom, T top)
{
if(r < bottom) r = bottom;
else if(r > top) r = top;
if(g < bottom) g = bottom;
else if(g > top) g = top;
if(b < bottom) b = bottom;
else if(b > top) b = top;
if(a < bottom) a = bottom;
else if(a > top) a = top;
}
///////////////////////////////////////////////
template <class T>
void color4<T>::maximum(const color4<T> &ca, const color4<T> &cb)
{
r = (ca.r > cb.r) ? ca.r : cb.r;
g = (ca.g > cb.g) ? ca.g : cb.g;
b = (ca.b > cb.b) ? ca.b : cb.b;
a = (ca.a > cb.a) ? ca.a : cb.a;
}
///////////////////////////////////////////////
template <class T>
void color4<T>::minimum(const color4<T> &ca, const color4<T> &cb)
{
r = (ca.r < cb.r) ? ca.r : cb.r;
g = (ca.g < cb.g) ? ca.g : cb.g;
b = (ca.b < cb.b) ? ca.b : cb.b;
a = (ca.a < cb.a) ? ca.a : cb.a;
}
///////////////////////////////////////////////
template <class T>
void color4<T>::abs()
{
r = (r < 0) ? -r : r;
g = (g < 0) ? -g : g;
b = (b < 0) ? -b : b;
a = (a < 0) ? -a : a;
}
///////////////////////////////////////////////
template <class T>
void color4<T>::adjust_contrast(T c)
{
r = 0.5f + c * (r - 0.5f);
g = 0.5f + c * (g - 0.5f);
b = 0.5f + c * (b - 0.5f);
a = 0.5f + c * (a - 0.5f);
}
///////////////////////////////////////////////
template <class T>
void color4<T>::adjust_saturation(T s)
{
// Approximate values for each component's contribution to luminance.
// Based upon the NTSC standard described in ITU-R Recommendation BT.709.
T grey = r * 0.2125f + g * 0.7154f + b * 0.0721f;
r = grey + s * (r - grey);
g = grey + s * (g - grey);
b = grey + s * (b - grey);
a = grey + s * (a - grey);
}
///////////////////////////////////////////////
template <class T>
void color4<T>::lerp(const color4<T> &ca, const color4<T> &cb, T s)
{
r = ca.r + s * (cb.r - ca.r);
g = ca.g + s * (cb.g - ca.g);
b = ca.b + s * (cb.b - ca.b);
a = ca.a + s * (cb.a - ca.a);
}
///////////////////////////////////////////////
template <class T>
void color4<T>::negative(const color4<T> &c)
{
r = T(1.0f) - r;
g = T(1.0f) - g;
b = T(1.0f) - b;
a = T(1.0f) - a;
}
///////////////////////////////////////////////
template <class T>
void color4<T>::grey(const color4<T> &c)
{
T m = (r + g + b) / T(3);
r = m;
g = m;
b = m;
a = a;
}
/*
///////////////////////////////////////////////
template <class T>
void color4<T>::black_white(const color4<T> &c, T s)
{
T add = r + g + b;
if(add <= s)
{
r = T(0.0f);
g = T(0.0f);
b = T(0.0f);
}
else
{
r = T(1.0f);
g = T(1.0f);
b = T(1.0f);
}
a = pC->a;
}
*/
#endif // CRYTEK_CRYCOLOR4_H

468
CryCommon/Cry_Geo.h Normal file
View File

@@ -0,0 +1,468 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Common Source code
//
// File: Cry_Geo.h
// Description: Common structures for geometry computations
//
// History:
// -March 15,2003: Created by Ivo Herzeg
//
//////////////////////////////////////////////////////////////////////
#ifndef CRYGEOSTRUCTS_H
#define CRYGEOSTRUCTS_H
#include "Cry_Math.h"
#if _MSC_VER > 1000
# pragma once
#endif
///////////////////////////////////////////////////////////////////////////////
// Forward declarations //
///////////////////////////////////////////////////////////////////////////////
struct Line;
struct Ray;
struct Lineseg;
template <typename F> struct Triangle_tpl;
struct AABB;
template <typename F> struct OBB_tpl;
struct Sphere;
struct AAEllipsoid;
struct Ellipsoid;
//-----------------------------------------------------
///////////////////////////////////////////////////////////////////////////////
// Definitions //
///////////////////////////////////////////////////////////////////////////////
#define FINDMINMAX(x0,x1,x2,min,max) \
min = max = x0; \
if(x1<min) min=x1;\
if(x1>max) max=x1;\
if(x2<min) min=x2;\
if(x2>max) max=x2;
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// struct Line
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
struct Line {
Vec3 pointonline;
Vec3 direction; //caution: the direction is important for any intersection test
//default Line constructor (without initialisation)
inline Line( void ) {}
inline Line( const Vec3 &o, const Vec3 &d ) { pointonline=o; direction=d; }
inline void operator () ( const Vec3 &o, const Vec3 &d ) { pointonline=o; direction=d; }
~Line( void ) {};
};
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// struct Ray
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
struct Ray {
Vec3 origin;
Vec3 direction;
//default Ray constructor (without initialisation)
inline Ray( void ) {}
inline Ray( const Vec3 &o, const Vec3 &d ) { origin=o; direction=d; }
inline void operator () ( const Vec3 &o, const Vec3 &d ) { origin=o; direction=d; }
~Ray( void ) {};
};
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// struct Lineseg
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
struct Lineseg {
Vec3 start;
Vec3 end;
//default Lineseg constructor (without initialisation)
inline Lineseg( void ) {}
inline Lineseg( const Vec3 &s, const Vec3 &e ) { start=s; end=e; }
inline void operator () ( const Vec3 &s, const Vec3 &e ) { start=s; end=e; }
~Lineseg( void ) {};
};
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// struct Triangle
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
template <typename F> struct Triangle_tpl {
Vec3_tpl<F> v0,v1,v2;
//default Lineseg constructor (without initialisation)
inline Triangle_tpl( void ) {}
inline Triangle_tpl( const Vec3_tpl<F>& a, const Vec3_tpl<F>& b, const Vec3_tpl<F>& c ) { v0=a; v1=b; v2=c; }
inline void operator () ( const Vec3_tpl<F>& a, const Vec3_tpl<F>& b, const Vec3_tpl<F>& c ) { v0=a; v1=b; v2=c; }
~Triangle_tpl( void ) {};
};
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// struct AABB
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
struct AABB {
Vec3 min;
Vec3 max;
//default AABB constructor (without initialisation)
inline AABB( void ) {}
inline AABB( const Vec3 &vmin, const Vec3 &vmax ) { min=vmin; max=vmax; }
inline void operator () ( const Vec3 &vmin, const Vec3 &vmax ) { min=vmin; max=vmax; }
~AABB( void ) {};
//! Reset Bounding box before calculating bounds.
void Reset() { min = Vec3(MAX); max = Vec3(MIN); }
//! Check if bounding box is empty (Zero volume).
bool IsEmpty() const { return min == max; }
void Add( const Vec3 &v ) {
min.x=__min( min.x,v.x ); min.y=__min( min.y,v.y ); min.z=__min( min.z,v.z );
max.x=__max( max.x,v.x ); max.y=__max( max.y,v.y ); max.z=__max( max.z,v.z );
}
//! Check if this bounding box overlap with bounding box of sphere.
bool IsOverlapSphereBounds( const Vec3 &pos,float radius ) const
{
if (pos.x > min.x && pos.x < max.x && pos.y > min.y && pos.y < max.y && pos.z > min.z && pos.z < max.z)
return true;
if (pos.x+radius < min.x) return false;
if (pos.y+radius < min.y) return false;
if (pos.z+radius < min.z) return false;
if (pos.x-radius > max.x) return false;
if (pos.y-radius > max.y) return false;
if (pos.z-radius > max.z) return false;
return true;
}
//! Check if this bounding box contain sphere within itself.
bool IsContainSphere( const Vec3 &pos,float radius ) const
{
if (pos.x-radius < min.x) return false;
if (pos.y-radius < min.y) return false;
if (pos.z-radius < min.z) return false;
if (pos.x+radius > max.x) return false;
if (pos.y+radius > max.y) return false;
if (pos.z+radius > max.z) return false;
return true;
}
// Check two bounding boxes for intersection.
inline bool IsIntersectBox( const AABB &b ) const {
// Check for intersection on X axis.
if ((min.x > b.max.x)||(b.min.x > max.x)) return false;
// Check for intersection on Y axis.
if ((min.y > b.max.y)||(b.min.y > max.y)) return false;
// Check for intersection on Z axis.
if ((min.z > b.max.z)||(b.min.z > max.z)) return false;
// Boxes overlap in all 3 axises.
return true;
}
//! Transforms AABB with specified matrix.
void Transform( const Matrix44 &tm ) {
Vec3 m = tm.TransformPointOLD( min );
Vec3 vx = Vec3(tm(0,0),tm(0,1),tm(0,2))*(max.x-min.x);
Vec3 vy = Vec3(tm(1,0),tm(1,1),tm(1,2))*(max.y-min.y);
Vec3 vz = Vec3(tm(2,0),tm(2,1),tm(2,2))*(max.z-min.z);
min = m;
max = m;
if (vx.x < 0) min.x += vx.x; else max.x += vx.x;
if (vx.y < 0) min.y += vx.y; else max.y += vx.y;
if (vx.z < 0) min.z += vx.z; else max.z += vx.z;
if (vy.x < 0) min.x += vy.x; else max.x += vy.x;
if (vy.y < 0) min.y += vy.y; else max.y += vy.y;
if (vy.z < 0) min.z += vy.z; else max.z += vy.z;
if (vz.x < 0) min.x += vz.x; else max.x += vz.x;
if (vz.y < 0) min.y += vz.y; else max.y += vz.y;
if (vz.z < 0) min.z += vz.z; else max.z += vz.z;
}
/*!
* calculate the new bounds of a transformed AABB
*
* Example:
* AABB aabb = AABB::CreateAABBfromOBB(m34,aabb);
*
* return values:
* expanded AABB in world-space
*/
ILINE void SetTransformedAABB( const Matrix34& m34, const AABB& aabb ) {
Vec3 sz = Matrix33(m34).GetFabs()*((aabb.max-aabb.min)*0.5f);
Vec3 pos = m34*((aabb.max+aabb.min)*0.5f);
min=pos-sz; max=pos+sz;
}
ILINE static AABB CreateTransformedAABB( const Matrix34& m34, const AABB& aabb ) { AABB taabb; taabb.SetTransformedAABB(m34,aabb); return taabb; }
//create an AABB using just the extensions of the OBB and ignore the orientation.
template<typename F>
ILINE void SetAABBfromOBB( const OBB_tpl<F>& obb ) { min=obb.c-obb.h; max=obb.c+obb.h; }
template<typename F>
ILINE static AABB CreateAABBfromOBB( const OBB_tpl<F>& obb ) { return AABB(obb.c-obb.h,obb.c+obb.h); }
/*!
* converts an OBB into an tight fitting AABB
*
* Example:
* AABB aabb = AABB::CreateAABBfromOBB(wposition,obb,1.0f);
*
* return values:
* expanded AABB in world-space
*/
template<typename F>
ILINE void SetAABBfromOBB( const Vec3& wpos, const OBB_tpl<F>& obb, f32 scaling=1.0f ) {
Vec3 pos = obb.m33*obb.c*scaling + wpos;
Vec3 sz = obb.m33.GetFabs()*obb.h*scaling;
min=pos-sz; max=pos+sz;
}
template<typename F>
ILINE static AABB CreateAABBfromOBB( const Vec3& wpos, const OBB_tpl<F>& obb, f32 scaling=1.0f) { AABB taabb; taabb.SetAABBfromOBB(wpos,obb,scaling); return taabb; }
};
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// struct OBB
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
template <typename F> struct OBB_tpl {
Matrix33 m33; //orientation vectors
Vec3 h; //half-length-vector
Vec3 c; //center of obb
//default OBB constructor (without initialisation)
inline OBB_tpl() {}
ILINE void SetOBB( const Matrix33& m33, const Vec3& hlv, const Vec3& center ) { m33=m33; h=hlv; c=center; }
ILINE static OBB_tpl<F> CreateOBB( const Matrix33& m33, const Vec3& hlv, const Vec3& center ) { OBB_tpl<f32> obb; obb.m33=m33; obb.h=hlv; obb.c=center; return obb; }
ILINE void SetOBBfromAABB( const Matrix33& mat33, const AABB& aabb ) {
m33 = mat33;
h = (aabb.max-aabb.min)*0.5f; //calculate the half-length-vectors
c = (aabb.max+aabb.min)*0.5f; //the center is relative to the PIVOT
}
ILINE static OBB_tpl<F> CreateOBBfromAABB( const Matrix33& m33, const AABB& aabb ) { OBB_tpl<f32> obb; obb.SetOBBfromAABB(m33,aabb); return obb; }
~OBB_tpl( void ) {};
};
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// struct Sphere
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
struct Sphere {
Vec3 center;
float radius;
//default Sphere constructor (without initialisation)
inline Sphere( void ) {}
inline Sphere( const Vec3 &c, const float &r ) { center=c; radius=r; }
inline void operator () ( const Vec3 &c, const float &r ) { center=c; radius=r; }
~Sphere( void ) {};
};
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// struct AAEllipsoid
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
struct AAEllipsoid {
Vec3 center;
Vec3 radius_vec;
//default AAEllipsoid constructor (without initialisation)
inline AAEllipsoid( void ) {}
inline AAEllipsoid( const Vec3 &c, const Vec3 &rv ) { radius_vec=rv; center=c; }
inline void operator () ( const Vec3 &c, const Vec3 &rv ) { radius_vec=rv; center=c; }
~AAEllipsoid( void ) {};
};
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// struct Ellipsoid
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
struct Ellipsoid {
Matrix34 ExtensionPos;
//default Ellipsoid constructor (without initialisation)
inline Ellipsoid( void ) {}
inline Ellipsoid( const Matrix34 &ep ) { ExtensionPos=ep; }
inline void operator () ( const Matrix34 &ep ) { ExtensionPos=ep; }
~Ellipsoid( void ) {};
};
typedef Triangle_tpl<f32> Triangle;
typedef Triangle_tpl<f64> Triangle_f64;
typedef OBB_tpl<f32> OBB;
#include "Cry_GeoDistance.h"
#include "Cry_GeoOverlap.h"
#include "Cry_GeoIntersect.h"
/////////////////////////////////////////////////////////////////////////
//this is some special engine stuff, should be moved to a better location
/////////////////////////////////////////////////////////////////////////
// for bbox's checks and calculations
#define MAX_BB +99999.0f
#define MIN_BB -99999.0f
//! checks if this has been set to minBB
inline bool IsMinBB( const Vec3& v ) {
if (v.x<=MIN_BB) return (true);
if (v.y<=MIN_BB) return (true);
if (v.z<=MIN_BB) return (true);
return (false);
}
//! checks if this has been set to maxBB
inline bool IsMaxBB( const Vec3& v ) {
if (v.x>=MAX_BB) return (true);
if (v.y>=MAX_BB) return (true);
if (v.z>=MAX_BB) return (true);
return (false);
}
inline Vec3 SetMaxBB( void ) { return Vec3(MAX_BB,MAX_BB,MAX_BB); }
inline Vec3 SetMinBB( void ) { return Vec3(MIN_BB,MIN_BB,MIN_BB); }
inline void AddToBounds (const Vec3& v, Vec3& mins, Vec3& maxs) {
if (v.x < mins.x) mins.x = v.x;
if (v.x > maxs.x) maxs.x = v.x;
if (v.y < mins.y) mins.y = v.y;
if (v.y > maxs.y) maxs.y = v.y;
if (v.z < mins.z) mins.z = v.z;
if (v.z > maxs.z) maxs.z = v.z;
}
////////////////////////////////////////////////////////////////
//! calc the area of a polygon giving a list of vertices and normal
inline float CalcArea(const Vec3 *vertices,int numvertices,const Vec3 &normal)
{
Vec3 csum(0,0,0);
int n=numvertices;
for (int i = 0, j = 1; i <= n-2; i++, j++)
{
csum.x += vertices[i].y*vertices[j].z-vertices[i].z*vertices[j].y;
csum.y += vertices[i].z*vertices[j].x-vertices[i].x*vertices[j].z;
csum.z += vertices[i].x*vertices[j].y-vertices[i].y*vertices[j].x;
}
csum.x += vertices[n-1].y*vertices[0].z-vertices[n-1].z*vertices[0].y;
csum.y += vertices[n-1].z*vertices[0].x-vertices[n-1].x*vertices[0].z;
csum.z += vertices[n-1].x*vertices[0].y-vertices[n-1].y*vertices[0].x;
float area=0.5f*(float)fabs(normal*csum);
return (area);
}
#endif //geostructs

136
CryCommon/Cry_GeoDistance.h Normal file
View File

@@ -0,0 +1,136 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Common Source code
//
// File:Cry_GeoDistance.h
// Description: Common distance-computations
//
// History:
// -March 15,2003: Created by Ivo Herzeg
//
//////////////////////////////////////////////////////////////////////
#ifndef CRYDISTANCE_H
#define CRYDISTANCE_H
#if _MSC_VER > 1000
# pragma once
#endif
#include <Cry_Geo.h>
namespace Distance {
/*!
* Distance: Origin_Triangle2D
* Calculate the closest distance of a triangle in XY-plane to the coordinate origin.
* it is assumed that the z-values of the triangle are all in the same plane.
* The function returns the 3d-position of the closest point on the triangle.
*
* Example:
* Vec3 result = Distance::Origin_Triangle2D( triangle );
*/
template<typename F>
ILINE Vec3_tpl<F> Origin_Triangle2D( const Triangle_tpl<F>& t ) {
Vec3_tpl<F> a=t.v0;
Vec3_tpl<F> b=t.v1;
Vec3_tpl<F> c=t.v2;
//check if (0,0,0) is inside or in fron of any triangle sides.
u32 flag = ((a.x*(a.y-b.y)-a.y*(a.x-b.x))<0) | (((b.x*(b.y-c.y)-b.y*(b.x-c.x))<0)<<1) | (((c.x*(c.y-a.y)-c.y*(c.x-a.x))<0)<<2);
switch (flag) {
case 0: return Vec3_tpl<F>(0,0,a.z); //center is inside of triangle
case 1: if ((a|(b-a))>0.0f) flag=5; else if ((b|(a-b))>0.0f) flag=3; break;
case 2: if ((b|(c-b))>0.0f) flag=3; else if ((c|(b-c))>0.0f) flag=6; break;
case 3: return b; //vertex B is closed
case 4: if ((c|(a-c))>0.0f) flag=6; else if ((a|(c-a))>0.0f) flag=5; break;
case 5: return a; //vertex A is closed
case 6: return c; //vertex C is closed
}
//check again using expanded area
switch (flag) {
case 1: { Vec3_tpl<F> n=(b-a).GetNormalized(); return n*(-a|n)+a; }
case 2: { Vec3_tpl<F> n=(c-b).GetNormalized(); return n*(-b|n)+b; }
case 3: return b;
case 4: { Vec3_tpl<F> n=(a-c).GetNormalized(); return n*(-c|n)+c; }
case 5: return a;
case 6: return c;
}
return Vec3_tpl<F>(0,0,0);
}
/*!
* Distance: Point_Triangle
* Calculate the closest distance of a point to a triangle in 3d-space.
* The function returns the squared distance.
*
* Example:
* float result = Distance::Point_Triangle( pos, triangle );
*/
template<typename F>
ILINE F Point_Triangle( const Vec3_tpl<F>& p, const Triangle_tpl<F> &t ) {
//translate triangle into origin
Vec3_tpl<F> a=t.v0-p;
Vec3_tpl<F> b=t.v1-p;
Vec3_tpl<F> c=t.v2-p;
//transform triangle into XY-plane to simplify the test
Matrix33_tpl<F,3,1> r33=Matrix33_tpl<F,3,1>::CreateRotationV0( ((b-a)%(a-c)).GetNormalized() );
Vec3_tpl<F> h = Origin_Triangle2D(Triangle_tpl<F>(r33*a,r33*b,r33*c));
return (h|h); //return squared distance
}
/*!
* Distance: Point_Triangle
* Calculate the closest distance of a point to a triangle in 3d-space.
* The function returns the squared distance and the 3d-position of the
* closest point on the triangle.
*
* Example:
* float result = Distance::Point_Triangle( pos, triangle, output );
*/
template<typename F>
ILINE F Point_Triangle( const Vec3_tpl<F>& p, const Triangle_tpl<F> &t, Vec3_tpl<F>& output ) {
//translate triangle into origin
Vec3_tpl<F> a=t.v0-p;
Vec3_tpl<F> b=t.v1-p;
Vec3_tpl<F> c=t.v2-p;
//transform triangle into XY-plane to simplify the test
Matrix33_tpl<F,3,1> r33=Matrix33_tpl<F,3,1>::CreateRotationV0( ((b-a)%(a-c)).GetNormalized() );
Vec3_tpl<F> h = Origin_Triangle2D(Triangle_tpl<F>(r33*a,r33*b,r33*c));
output=h*r33+p;
return (h|h); //return squared distance
}
//----------------------------------------------------------------------------------
// Distance: Sphere_Triangle
//----------------------------------------------------------------------------------
// Calculate the closest distance of a sphere to a triangle in 3d-space.
// The function returns the squared distance. If sphere and triangle overlaps,
// the returned distance is 0
//
// Example:
// float result = Distance::Point_Triangle( pos, triangle );
//----------------------------------------------------------------------------------
template<typename F>
ILINE F Sphere_Triangle( const Sphere &s, const Triangle_tpl<F> &t ) {
F sqdistance = Distance::Point_Triangle(s.center,t) - (s.radius*s.radius);
if (sqdistance<0) sqdistance=0;
return sqdistance;
}
template<typename F>
ILINE F Sphere_Triangle( const Sphere &s, const Triangle_tpl<F> &t, Vec3_tpl<F>& output ) {
F sqdistance = Distance::Point_Triangle(s.center,t,output) - (s.radius*s.radius);
if (sqdistance<0) sqdistance=0;
return sqdistance;
}
} //namespace Distance
#endif

View File

@@ -0,0 +1,385 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Common Source code
//
// File:Cry_GeoIntersect.h
// Description: Common intersection-tests
//
// History:
// -March 15,2003: Created by Ivo Herzeg
//
//////////////////////////////////////////////////////////////////////
#ifndef CRYINTERSECTION_H
#define CRYINTERSECTION_H
#if _MSC_VER > 1000
# pragma once
#endif
#include <Cry_Geo.h>
namespace Intersect {
inline bool Ray_Plane(const Ray &ray, const Plane &plane, Vec3 &output ) {
float numer = plane|ray.origin;
float cosine = plane.n|ray.direction;
//REJECTION 1: if "line-direction" is perpendicular to "plane-normal", an intersection is not possible!
//REJECTION 2: we deal with single-sided planes.
// if "line-direction" is pointing in the same direction as "the plane-normal",
// an intersection is not possible!
if (cosine > 0) return 0; //normal is orthogonal to vector, cant intersect
output = ray.origin+(ray.direction*(-numer/cosine));
//skip, if cutting-point is "behind" ray.origin
if (((output-ray.origin)|ray.direction)<0) return 0;
return 1; //intersection occured
}
inline bool Line_Plane(const Line &line, const Plane &plane, Vec3 &output ) {
double perpdist = plane|line.pointonline;
double cosine = plane.n|line.direction;
//REJECTION 1: if "line-direction" is perpendicular to "plane-normal", an intersection is not possible!
//REJECTION 2: we deal with single-sided planes.
// if "line-direction" is pointing in the same direction as "the plane-normal",
// an intersection is not possible!
if (cosine > 0) return 0;
//an intersection is possible: calculate the exact point!
float pd_c = (float)(-perpdist/cosine);
output = line.pointonline+(line.direction*pd_c);
return 1; //intersection occured
}
/*
* calculates intersection between a line and a triangle.
* IMPORTANT: this is a single-sided intersection test. That means its not enough
* that the triangle and line overlap, its also important that the triangle
* is "visible" when you are looking along the line-direction.
*
* If you need a double-sided test, you'll have to call this function twice with
* reversed order of triangle vertices.
*
* return values
* if there is an intertection the functions return "true" and stores the
* 3d-intersection point in "output". if the function returns "false" the value in
* "output" is undefined
*
*/
inline bool Line_Triangle( const Line &line, const Vec3 &v0, const Vec3 &v1, const Vec3 &v2, Vec3 &output ) {
//find vectors for two edges sharing v0
Vec3 edge_1 = v1-v0;
Vec3 edge_2 = v2-v0;
//begin calculating determinant - also used to calculate U parameter
Vec3 pvec = line.direction % edge_1;
//if determinat is near zero, ray lies in plane of triangel
float det = edge_2 | pvec;
if (det<=0) return 0;
//calculate distance from v0 to ray origin
Vec3 tvec=line.pointonline-v0;
//calculate U parameter and test bounds
float u=tvec | pvec;
if (u<0.0f || u>det) return 0;
//prepare to test V parameter
Vec3 qvec=tvec % edge_2;
//calculate V parameter and test bounds
float v= (line.direction | qvec);
if ( v<0.0f || (u+v)>det) return 0;
//------------------------------------------------------
//we have an intersection and now we can calculate t
float t = (edge_1 | qvec) / det;
//we use t als a scale parameter, to get the 3D-intersection point
output = (line.direction*t)+line.pointonline;
return 1;
}
/*
* calculates intersection between a ray and a triangle.
* IMPORTANT: this is a single-sided intersection test. That means its not sufficient
* that the triangle and rayt overlap, its also important that the triangle
* is "visible" when you from the origin along the ray-direction.
*
* If you need a double-sided test, you'll have to call this function twice with
* reversed order of triangle vertices.
*
* return values
* if there is an intertection the functions return "true" and stores the
* 3d-intersection point in "output". if the function returns "false" the value in
* "output" is undefined
*/
inline bool Ray_Triangle( const Ray &ray, const Vec3 &v0, const Vec3 &v1, const Vec3 &v2, Vec3 &output ) {
//find vectors for two edges sharing v0
Vec3 edge_1 = v1-v0;
Vec3 edge_2 = v2-v0;
//begin calculating determinant - also used to calculate U parameter
Vec3 pvec = ray.direction % edge_1;
//if determinat is near zero, ray lies in plane of triangle
float det = edge_2 | pvec;
if (det<=0) return 0;
//calculate distance from v0 to ray origin
Vec3 tvec=ray.origin-v0;
//calculate U parameter and test bounds
float u=tvec | pvec;
if (u<0.0f || u>det) return 0;
//prepare to test V parameter
Vec3 qvec=tvec % edge_2;
//calculate V parameter and test bounds
float v= (ray.direction | qvec);
if ( v<0.0f || (u+v)>det) return 0;
//------------------------------------------------------
//We have an intersection and we can calculate t
float t = (edge_1 | qvec) / det;
//we use t als a scale parameter, to get the 3D-intersection point
output = (ray.direction*t)+ray.origin;
//skip, if cutting-point is "behind" ray.origin
if (((output-ray.origin)|ray.direction)<0) return 0;
return 1;
}
/*!
*
* calculates intersection between a line-segment and a triangle.
* IMPORTANT: this is a single-sided intersection test. That means its not sufficient
* that the triangle and line-segment overlap, its also important that the triangle
* is "visible" when you are looking along the linesegment from "start" to "end".
*
* If you need a double-sided test, you'll have to call this function twice with
* reversed order of triangle vertices.
*
* return values
* if there is an intertection the the functions return "true" and stores the
* 3d-intersection point in "output". if the function returns "false" the value in
* "output" is undefined
*
*/
inline bool Lineseg_Triangle( const Lineseg &lineseg, const Vec3 &v0, const Vec3 &v1, const Vec3 &v2, Vec3 &output ) {
//find vectors for two edges sharing v0
Vec3 edge_1 = v1-v0;
Vec3 edge_2 = v2-v0;
//direction of lineseg. normalizing is not necessary
Vec3 direction=(lineseg.end-lineseg.start);
//begin calculating determinant - also used to calculate U parameter
Vec3 pvec = direction % edge_1;
//if determinat is near zero, ray lies in plane of triangle
float det = edge_2 | pvec;
if (det<=0) return 0;
//calculate distance from v0 to ray origin
Vec3 tvec=lineseg.start-v0;
//calculate U parameter and test bounds
float u=tvec | pvec;
if (u<0.0f || u>det) return 0;
//prepare to test V parameter
Vec3 qvec=tvec % edge_2;
//calculate V parameter and test bounds
float v= (direction | qvec);
if ( v<0.0f || (u+v)>det) return 0;
//------------------------------------------------------
//If we ignore the limitations of linesegment, then we have an intersection and we calcultate t
float t = (edge_1 | qvec) / det;
//we use t als a scale parameter, to get the 3D-intersection point
output = (direction*t)+lineseg.start;
//skip, if lineseg and triangle are not overlapping
if (((output-lineseg.start)|direction)<0) return 0;
if (((output-lineseg.end)|direction)>0) return 0;
return 1;
}
//----------------------------------------------------------------------------------
//--- 0x00 = no intersection --------------------------
//--- 0x01 = not possible --
//--- 0x02 = not possible --
//--- 0x03 = two intersection, lineseg has ENTRY and EXIT point --
//----------------------------------------------------------------------------------
inline unsigned char Line_Sphere( const Line &line, const Sphere &s, Vec3 &i0, Vec3 &i1 ) {
Vec3 end=line.pointonline+line.direction;
float a = line.direction|line.direction;
float b = (line.direction|(line.pointonline-s.center))*2.0f;
float c = ((line.pointonline-s.center)|(line.pointonline-s.center)) - (s.radius*s.radius);
float desc = (b*b) - (4 * a *c);
unsigned char intersection=0;
if (desc >= 0.0f)
{
float lamba0 = (-b - cry_sqrtf(desc)) / (2.0f * a);
//_stprintf(d3dApp.token,"lamba0: %20.12f",lamba0);
//d3dApp.m_pFont->DrawText( 2, d3dApp.PrintY, D3DCOLOR_ARGB(255,255,255,0), d3dApp.token ); d3dApp.PrintY+=20;
i0 = line.pointonline + ((end-line.pointonline)*lamba0);
intersection=1;
float lamba1 = (-b + cry_sqrtf(desc))/(2.0f*a);
//_stprintf(d3dApp.token,"lamba1: %20.12f",lamba1);
//d3dApp.m_pFont->DrawText( 2, d3dApp.PrintY, D3DCOLOR_ARGB(255,255,255,0), d3dApp.token ); d3dApp.PrintY+=20;
i1 = line.pointonline + ((end-line.pointonline)*lamba1);
intersection|=2;
}
return intersection;
}
//----------------------------------------------------------------------------------
//--- 0x00 = no intersection --------------------------
//--- 0x01 = not possible --
//--- 0x02 = one intersection, lineseg has just an EXIT point but no ENTRY point (ls.start is inside the sphere) --
//--- 0x03 = two intersection, lineseg has ENTRY and EXIT point --
//----------------------------------------------------------------------------------
inline unsigned char Ray_Sphere( const Ray &ray, const Sphere &s, Vec3 &i0, Vec3 &i1 ) {
Vec3 end=ray.origin+ray.direction;
float a = ray.direction|ray.direction;
float b = (ray.direction|(ray.origin-s.center))*2.0f;
float c = ((ray.origin-s.center)|(ray.origin-s.center)) - (s.radius*s.radius);
float desc = (b*b) - (4 * a *c);
unsigned char intersection=0;
if (desc >= 0.0f)
{
float lamba0 = (-b - cry_sqrtf(desc)) / (2.0f * a);
// _stprintf(d3dApp.token,"lamba0: %20.12f",lamba0);
// d3dApp.m_pFont->DrawText( 2, d3dApp.PrintY, D3DCOLOR_ARGB(255,255,255,0), d3dApp.token ); d3dApp.PrintY+=20;
if (lamba0>0.0f) {
i0 = ray.origin + ((end-ray.origin)*lamba0);
intersection=1;
}
float lamba1 = (-b + cry_sqrtf(desc))/(2.0f*a);
// _stprintf(d3dApp.token,"lamba1: %20.12f",lamba1);
// d3dApp.m_pFont->DrawText( 2, d3dApp.PrintY, D3DCOLOR_ARGB(255,255,255,0), d3dApp.token ); d3dApp.PrintY+=20;
if (lamba1>0.0f) {
i1 = ray.origin + ((end-ray.origin)*lamba1);
intersection|=2;
}
}
return intersection;
}
inline bool Ray_SphereFirst( const Ray &ray, const Sphere &s, Vec3 &intPoint )
{
Vec3 p2;
unsigned char res = Ray_Sphere( ray,s,intPoint,p2 );
if (res == 2) { intPoint = p2; }
if (res > 1) return true;
return false;
}
//----------------------------------------------------------------------------------
//--- 0x00 = no intersection --------------------------
//--- 0x01 = one intersection, lineseg has just an ENTRY point but no EXIT point (ls.end is inside the sphere) --
//--- 0x02 = one intersection, lineseg has just an EXIT point but no ENTRY point (ls.start is inside the sphere) --
//--- 0x03 = two intersection, lineseg has ENTRY and EXIT point --
//----------------------------------------------------------------------------------
inline unsigned char Lineseg_Sphere( const Lineseg &ls, const Sphere &s, Vec3 &i0, Vec3 &i1 ) {
Vec3 dir = (ls.end - ls.start);
float a = dir|dir;
float b = (dir|(ls.start-s.center))*2.0f;
float c = ((ls.start-s.center)|(ls.start-s.center)) - (s.radius*s.radius);
float desc = (b*b) - (4 * a *c);
unsigned char intersection=0;
if (desc >= 0.0f) {
float lamba0 = (-b - cry_sqrtf(desc)) / (2.0f * a);
//_stprintf(d3dApp.token,"lamba0: %20.12f",lamba0);
//d3dApp.m_pFont->DrawText( 2, d3dApp.PrintY, D3DCOLOR_ARGB(255,255,255,0), d3dApp.token ); d3dApp.PrintY+=20;
if (lamba0 >0.0f) {
i0 = ls.start + ((ls.end-ls.start)*lamba0);
//skip, if 1st cutting-point is "in front" of ls.end
if (((i0-ls.end)|dir)>0) return 0;
intersection=0x01;
}
float lamba1 = (-b + cry_sqrtf(desc)) / (2.0f * a);
//_stprintf(d3dApp.token,"lamba1: %20.12f",lamba1);
//d3dApp.m_pFont->DrawText( 2, d3dApp.PrintY, D3DCOLOR_ARGB(255,255,255,0), d3dApp.token ); d3dApp.PrintY+=20;
if ( lamba1 > 0.0f) {
i1 = ls.start + ((ls.end-ls.start)*lamba1);
//skip, if 2nd cutting-point is "in front" of ls.end (=ls.end is inside sphere)
if (((i1-ls.end)|dir)>0) return intersection;
intersection|=0x02;
}
}
return intersection;
}
// line/sphere-intersection
// p1: 1st point of line
// p2: 2nd point of line
// p3: center of sphere
// r: radius of sphere
// i1: 1st intersection point
// i2: 2nd intersection point
// return number of intersections
inline int Lineseg_Sphere(Vec3 p1, Vec3 p2, Vec3 p3, float r, Vec3 &i1, Vec3 i2)
{
float dx=p2.x-p1.x;
float dy=p2.y-p1.y;
float dz=p2.z-p1.z;
float a=dx*dx+dy*dy+dz*dz;
float b=2.0f*(dx*(p1.x-p3.x)+dy*(p1.y-p3.y)+dz*(p1.z-p3.z));
float c=p3.Dot(p3)+p2.Dot(p2)-2.0f*(p3.x*p1.x+p3.y*p1.y+p3.z-p1.z)-r*r;
float d=b*b-4.0f*a*c;
if (d<0.0f)
return 0;
float u;
u=(-b+(float)sqrt((double)d))/a*a;
i1=p1+((p2-p1)*u);
if (d==0.0)
return 1;
u=(-b-(float)sqrt((double)d))/a*a;
i2=p1+((p2-p1)*u);
return 2;
}
}; //CIntersect
#endif //vector

944
CryCommon/Cry_GeoOverlap.h Normal file
View File

@@ -0,0 +1,944 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Common Source code
//
// File:Cry_GeoOverlap.h
// Description: Common overlap-tests
//
// History:
// -March 15,2003: Created by Ivo Herzeg
//
//////////////////////////////////////////////////////////////////////
#ifndef CRYOVERLAP_H
#define CRYOVERLAP_H
#if _MSC_VER > 1000
# pragma once
#endif
#include <Cry_Geo.h>
namespace Overlap {
////////////////////////////////////////////////////////////////
//! check if the point is inside an AABB
inline bool Point_AABB(const Vec3 &p, const Vec3 &mins,const Vec3 &maxs)
{
if ((p.x>=mins.x && p.x<=maxs.x) && (p.y>=mins.y && p.y<=maxs.y) && (p.z>=mins.z && p.z<=maxs.z)) return (true);
return (false);
}
/*!
* check if a point is inside an OBB.
*
* Example:
* bool result=Overlap::Point_OBB( point, obb );
*
*/
ILINE bool Point_OBB(const Vec3& p, const Vec3& wpos, const OBB& obb) {
AABB aabb=AABB(obb.c-obb.h,obb.c+obb.h);
Vec3 t=(p-wpos)*obb.m33;
return ((t.x>=aabb.min.x && t.x<=aabb.max.x) && (t.y>=aabb.min.y && t.y<=aabb.max.y) && (t.z>=aabb.min.z && t.z<=aabb.max.z));
}
//-----------------------------------------------------------------------------------------
//! check if a Lineseg and a Sphere overlap
inline bool Lineseg_Sphere(const Lineseg& ls,const Sphere& s)
{
float radius2=s.radius*s.radius;
//check if one of the two edpoints of the line is inside the sphere
Vec3 diff = ls.end-s.center;
if (diff.x*diff.x+diff.y*diff.y+diff.z*diff.z <= radius2) return true;
Vec3 AC = s.center-ls.start;
if (AC.x*AC.x+AC.y*AC.y+AC.z*AC.z <= radius2) return true;
//check distance from the sphere to the line
Vec3 AB = ls.end-ls.start;
float r = (AC.x*AB.x+AC.y*AB.y+AC.z*AB.z) / (AB.x*AB.x+AB.y*AB.y+AB.z*AB.z);
//projection falls outside the line
if (r<0 || r>1) return false;
//check if the distance from the line to the center of the sphere is less than radius
Vec3 point = ls.start + r*AB;
if ((point.x-s.center.x)*(point.x-s.center.x) + (point.y-s.center.y)*(point.y-s.center.y) + (point.z-s.center.z)*(point.z-s.center.z) > radius2) return false;
return true;
}
/*!
* we use the SEPARATING AXIS TEST to check if a Linesegment overlap an AABB.
*
* Example:
* bool result=Overlap::Lineseg_AABB( ls, pos,aabb );
*
*/
inline bool Lineseg_AABB ( const Lineseg &ls, const Vec3 &pos, const AABB &aabb ) {
//calculate the half-length-vectors of the AABB
Vec3 h = (aabb.max-aabb.min)*0.5f;
//"t" is the transfer-vector from one center to the other
Vec3 t = ((ls.start+ls.end)*0.5f - ((aabb.max+aabb.min)*0.5f+pos));
//calculate line-direction
Vec3 ld = (ls.end-ls.start)*0.5f;
if( fabsf(t.x) > (h.x + fabsf(ld.x)) ) return 0;
if( fabsf(t.y) > (h.y + fabsf(ld.y)) ) return 0;
if( fabsf(t.z) > (h.z + fabsf(ld.z)) ) return 0;
if( fabsf(t.z*ld.y-t.y*ld.z) > (fabsf(h.y*ld.z) + fabsf(h.z*ld.y)) ) return 0;
if( fabsf(t.x*ld.z-t.z*ld.x) > (fabsf(h.x*ld.z) + fabsf(h.z*ld.x)) ) return 0;
if( fabsf(t.y*ld.x-t.x*ld.y) > (fabsf(h.x*ld.y) + fabsf(h.y*ld.x)) ) return 0;
return 1; //no separating axis found, objects overlap
}
/*!
* we use the SEPARATING AXIS TEST to check if two OBB's overlap.
*
* Example:
* bool result=Overlap::Lineseg_OBB( lineseg, pos,obb );
*
*/
inline bool Lineseg_OBB ( const Lineseg &ls, const Vec3 &pos, const OBB &obb ) {
//the new center-position of Lineseg and OBB in world-space
Vec3 wposobb = obb.m33*obb.c + pos;
Vec3 wposls = (ls.start+ls.end)*0.5f;
//"t" is the transfer-vector from one center to the other
Vec3 t = (wposls - wposobb)*obb.m33;
//calculate line-direction in local obb-space
Vec3 ld = ( (ls.end-ls.start)*obb.m33 )*0.5f;
if( fabsf(t.x) > (obb.h.x + fabsf(ld.x)) ) return 0;
if( fabsf(t.y) > (obb.h.y + fabsf(ld.y)) ) return 0;
if( fabsf(t.z) > (obb.h.z + fabsf(ld.z)) ) return 0;
if( fabsf(t.z*ld.y-t.y*ld.z) > (fabsf(obb.h.y*ld.z) + fabsf(obb.h.z*ld.y)) ) return 0;
if( fabsf(t.x*ld.z-t.z*ld.x) > (fabsf(obb.h.x*ld.z) + fabsf(obb.h.z*ld.x)) ) return 0;
if( fabsf(t.y*ld.x-t.x*ld.y) > (fabsf(obb.h.x*ld.y) + fabsf(obb.h.y*ld.x)) ) return 0;
return 1; //no separating axis found, objects overlap
}
/*!
*
* overlap-test between a line and a triangle.
* IMPORTANT: this is a single-sided test. That means its not enough
* that the triangle and line overlap, its also important that the triangle
* is "visible" when you are looking along the line-direction.
*
* If you need a double-sided test, you'll have to call this function twice with
* reversed order of triangle vertices.
*
* return values
* return "true" if line and triangle overlap.
*
*/
inline bool Line_Triangle( const Line &line, const Vec3 &v0, const Vec3 &v1, const Vec3 &v2 ) {
//find vectors for two edges sharing v0
Vec3 edge_1 = v1-v0;
Vec3 edge_2 = v2-v0;
//begin calculating determinant - also used to calculate U parameter
Vec3 pvec = line.direction % edge_1;
//if determinat is near zero, line lies in plane of triangel
float det = edge_2 | pvec;
if (det<=0) return 0;
//calculate distance from v0 to line origin
Vec3 tvec=line.pointonline-v0;
float u=tvec | pvec;
if ( (u<0.0f) || (u>det)) return 0;
//prepare to test V parameter
Vec3 qvec=tvec % edge_2;
float v= (line.direction | qvec);
if ( (v<0.0f) || ((u+v)>det)) return 0;
return 1;
}
/*!
*
* overlap-test between a ray and a triangle.
* IMPORTANT: this is a single-sided test. That means its not sufficient
* that the triangle and ray overlap, its also important that the triangle
* is "visible" when you are looking from the origin along the ray-direction.
*
* If you need a double-sided test, you'll have to call this function twice with
* reversed order of triangle vertices.
*
* return values
* return "true" if ray and triangle overlap.
*/
inline bool Ray_Triangle( const Ray &ray, const Vec3 &v0, const Vec3 &v1, const Vec3 &v2 ) {
//find vectors for two edges sharing v0
Vec3 edge_1 = v1-v0;
Vec3 edge_2 = v2-v0;
//begin calculating determinant - also used to calculate U parameter
Vec3 pvec = ray.direction % edge_1;
//if determinat is near zero, ray lies in plane of triangle
float det = edge_2 | pvec;
if (det<=0) return 0;
//calculate distance from v0 to ray origin
Vec3 tvec=ray.origin-v0;
//calculate U parameter and test bounds
float u=tvec | pvec;
if ( u<0.0f || u>det) return 0;
//prepare to test V parameter
Vec3 qvec=tvec % edge_2;
//calculate V parameter and test bounds
float v= (ray.direction | qvec);
if ( v<0.0f || (u+v)>det) return 0;
//------------------------------------------------------
//We have an intersection and now we can calculate t
float t = (edge_1 | qvec) / det;
//we use t als a scale parameter, to get the 3D-intersection point
Vec3 output = (ray.direction*t)+ray.origin;
//skip, if cutting-point is "behind" ray.origin
if (((output-ray.origin)|ray.direction)<0) return 0;
return 1;
}
/*!
*
* overlap-test between line-segment and a triangle.
* IMPORTANT: this is a single-sided test. That means its not sufficient
* that the triangle and line-segment overlap, its also important that the triangle
* is "visible" when you are looking along the linesegment from "start" to "end".
*
* If you need a double-sided test, you'll have to call this function twice with
* reversed order of triangle vertices.
*
* return values
* return "true" if linesegment and triangle overlap.
*/
inline bool Lineseg_Triangle( const Lineseg &lineseg, const Vec3 &v0, const Vec3 &v1, const Vec3 &v2 ) {
//find vectors for two edges sharing v0
Vec3 edge_1 = v1-v0;
Vec3 edge_2 = v2-v0;
//direction of lineseg. normalizing is not necessary
Vec3 direction=(lineseg.end-lineseg.start);
//begin calculating determinant - also used to calculate U parameter
Vec3 pvec = direction % edge_1;
//if determinat is near zero, ray lies in plane of triangle
float det = edge_2 | pvec;
if (det<=0) return 0;
//calculate distance from v0 to ray origin
Vec3 tvec=lineseg.start-v0;
//calculate U parameter and test bounds
float u=tvec | pvec;
if (u<0.0f || u>det) return 0;
//prepare to test V parameter
Vec3 qvec=tvec % edge_2;
//calculate V parameter and test bounds
float v= (direction | qvec);
if ( v<0.0f || (u+v)>det) return 0;
//------------------------------------------------------
//If we ignore the limitations of linesegment, then we have an intersection and we can calculate t
float t = (edge_1 | qvec) / det;
//skip, if lineseg and triangle are not overlapping
Vec3 output = (direction*t)+lineseg.start;
if (((output-lineseg.start)|direction)<0) return 0;
if (((output-lineseg.end)|direction)>0) return 0;
return 1;
}
/*----------------------------------------------------------------------------------
* Sphere_AABB
* Sphere and AABB are assumed to be in the same space
*
* Example:
* bool result=Overlap::Sphere_AABB_Inside( sphere, aabb );
*
* 0 = no overlap
* 1 = overlap
*----------------------------------------------------------------------------------*/
ILINE bool Sphere_AABB( const Sphere &s, const AABB &aabb ) {
//we are using Arvo's method, to check if the objects are overlaping
float quatradius = s.radius * s.radius;
Vec3 quat(0,0,0);
if(s.center.x < aabb.min.x) { quat.x = s.center.x - aabb.min.x; }
else if(s.center.x > aabb.max.x) { quat.x = s.center.x - aabb.max.x;}
if(s.center.y < aabb.min.y) { quat.y = s.center.y - aabb.min.y; }
else if(s.center.y > aabb.max.y) { quat.y = s.center.y - aabb.max.y; }
if(s.center.z < aabb.min.z) { quat.z=s.center.z-aabb.min.z; }
else if(s.center.z > aabb.max.z) { quat.z = s.center.z - aabb.max.z; }
return( (quat|quat) < quatradius);
}
/*!
*
* conventional method to check if a Sphere and an AABB overlap,
* or if the Sphere is completely inside the AABB.
* Sphere and AABB are assumed to be in the same space
*
* Example:
* bool result=Overlap::Sphere_AABB_Inside( sphere, aabb );
*
* return values:
* 0x00 = no overlap
* 0x01 = Sphere and AABB overlap
* 0x02 = Sphere in inside AABB
*/
ILINE char Sphere_AABB_Inside( const Sphere &s, const AABB& aabb ) {
if ( Sphere_AABB(s,aabb) ) {
Vec3 amin=aabb.min-s.center;
Vec3 amax=aabb.max-s.center;
if (amin.x>=(-s.radius)) return 1;
if (amin.y>=(-s.radius)) return 1;
if (amin.z>=(-s.radius)) return 1;
if (amax.x<=(+s.radius)) return 1;
if (amax.y<=(+s.radius)) return 1;
if (amax.z<=(+s.radius)) return 1;
//yes, its inside
return 2;
}
return 0;
}
//----------------------------------------------------------------------------------
// Sphere_OBB
// VERY IMPORTANT: Sphere is assumed to be in the space of the OBB, otherwise it won't work
//
//--- 0 = no overlap ---------------------------
//--- 1 = overlap -----------------
//----------------------------------------------------------------------------------
inline bool Sphere_OBB( const Sphere &s, const OBB &obb ) {
//first we transform the sphere-center into the AABB-space of the OBB
Vec3 SphereInOBBSpace = s.center*obb.m33;
//the rest ist the same as the "Overlap::Sphere_AABB" calculation
float quatradius = s.radius * s.radius;
Vec3 quat(0,0,0);
AABB aabb=AABB(obb.c-obb.h,obb.c+obb.h);
if(SphereInOBBSpace.x < aabb.min.x) { quat.x = SphereInOBBSpace.x - aabb.min.x; }
else if(SphereInOBBSpace.x > aabb.max.x) { quat.x = SphereInOBBSpace.x - aabb.max.x;}
if(SphereInOBBSpace.y < aabb.min.y) { quat.y = SphereInOBBSpace.y - aabb.min.y; }
else if(SphereInOBBSpace.y > aabb.max.y) { quat.y = SphereInOBBSpace.y - aabb.max.y; }
if(SphereInOBBSpace.z < aabb.min.z) { quat.z=SphereInOBBSpace.z-aabb.min.z; }
else if(SphereInOBBSpace.z > aabb.max.z) { quat.z = SphereInOBBSpace.z - aabb.max.z; }
return((quat|quat) < quatradius);
}
//----------------------------------------------------------------------------------
// Sphere_Sphere overlap test
//
//--- 0 = no overlap ---------------------------
//--- 1 = overlap -----------------
//----------------------------------------------------------------------------------
inline bool Sphere_Sphere( const Sphere &s1, const Sphere &s2 ) {
Vec3 distc = s1.center-s2.center;
f32 sqrad = (s1.radius+s2.radius) * (s1.radius+s2.radius);
return ( sqrad>(distc|distc) );
}
//----------------------------------------------------------------------------------
// Sphere_Triangle overlap test
//
//--- 0 = no overlap ---------------------------
//--- 1 = overlap -----------------
//----------------------------------------------------------------------------------
template<typename F>
ILINE bool Sphere_Triangle( const Sphere &s, const Triangle_tpl<F> &t ) {
//create a "bouding sphere" around triangle for fast rejection test
Vec3_tpl<F> middle=(t.v0+t.v1+t.v2)*(1/3.0f);
Vec3_tpl<F> ov0=t.v0-middle;
Vec3_tpl<F> ov1=t.v1-middle;
Vec3_tpl<F> ov2=t.v2-middle;
F SqRad1=(ov0|ov0);
if (SqRad1<(ov1|ov1)) SqRad1=(ov1|ov1);
if (SqRad1<(ov2|ov2)) SqRad1=(ov2|ov2);
//first simple rejection-test...
if ( Sphere_Sphere(s,Sphere(middle,sqrt_tpl(SqRad1)))==0 ) return 0; //overlap not possible
//...and now the hardcore-test!
if ( (s.radius*s.radius)<Distance::Point_Triangle(s.center,t)) return 0;
return 1; //sphere and triangle are overlapping
}
/*!
*
* we use the SEPARATING-AXIS-TEST for OBB/Plane overlap.
*
* Example:
* bool result=Overlap::OBB_Plane( pos,obb, plane );
*
*/
inline bool OBB_Plane( const Vec3 &pos, const OBB &obb, const Plane &plane ) {
//the new center-position in world-space
Vec3 p = obb.m33*obb.c + pos;
//extract the orientation-vectors from the columns of the 3x3 matrix
//and scale them by the half-lengths
Vec3 ax = Vec3(obb.m33(0,0), obb.m33(1,0), obb.m33(2,0))*obb.h.x;
Vec3 ay = Vec3(obb.m33(0,1), obb.m33(1,1), obb.m33(2,1))*obb.h.y;
Vec3 az = Vec3(obb.m33(0,2), obb.m33(1,2), obb.m33(2,2))*obb.h.z;
//check OBB against Plane, using the plane-normal as separating axis
return fabsf(plane|p) < (fabsf(plane.n|ax) + fabsf(plane.n|ay) + fabsf(plane.n|az));
}
/*!
*
* we use the SEPARATING AXIS TEST to check if a triangle and AABB overlap.
*
* Example:
* bool result=Overlap::AABB_Triangle( pos,aabb, tv0,tv1,tv2 );
*
*/
inline bool AABB_Triangle ( const AABB &aabb, const Vec3 &tv0, const Vec3 &tv1, const Vec3 &tv2 ) {
//------ convert AABB into half-length AABB -----------
Vec3 h = (aabb.max-aabb.min)*0.5f; //calculate the half-length-vectors
Vec3 c = (aabb.max+aabb.min)*0.5f; //the center is relative to the PIVOT
//move everything so that the boxcenter is in (0,0,0)
Vec3 v0 = tv0-c;
Vec3 v1 = tv1-c;
Vec3 v2 = tv2-c;
//compute triangle edges
Vec3 e0 = v1-v0;
Vec3 e1 = v2-v1;
Vec3 e2 = v0-v2;
//--------------------------------------------------------------------------------------
// use SEPARATING AXIS THEOREM to test overlap between AABB and triangle
// cross-product(edge from triangle, {x,y,z}-direction), this are 3x3=9 tests
//--------------------------------------------------------------------------------------
float min,max,p0,p1,p2,rad,fex,fey,fez;
fex = fabsf(e0.x);
fey = fabsf(e0.y);
fez = fabsf(e0.z);
//AXISTEST_X01(e0.z, e0.y, fez, fey);
p0 = e0.z*v0.y - e0.y*v0.z;
p2 = e0.z*v2.y - e0.y*v2.z;
if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;}
rad = fez * h.y + fey * h.z;
if(min>rad || max<-rad) return 0;
//AXISTEST_Y02(e0.z, e0.x, fez, fex);
p0 = -e0.z*v0.x + e0.x*v0.z;
p2 = -e0.z*v2.x + e0.x*v2.z;
if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;}
rad = fez * h.x + fex * h.z;
if(min>rad || max<-rad) return 0;
//AXISTEST_Z12(e0.y, e0.x, fey, fex);
p1 = e0.y*v1.x - e0.x*v1.y;
p2 = e0.y*v2.x - e0.x*v2.y;
if(p2<p1) {min=p2; max=p1;} else {min=p1; max=p2;}
rad = fey * h.x + fex * h.y;
if(min>rad || max<-rad) return 0;
//-----------------------------------------------
fex = fabsf(e1.x);
fey = fabsf(e1.y);
fez = fabsf(e1.z);
//AXISTEST_X01(e1.z, e1.y, fez, fey);
p0 = e1.z*v0.y - e1.y*v0.z;
p2 = e1.z*v2.y - e1.y*v2.z;
if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;}
rad = fez * h.y + fey * h.z;
if(min>rad || max<-rad) return 0;
//AXISTEST_Y02(e1.z, e1.x, fez, fex);
p0 = -e1.z*v0.x + e1.x*v0.z;
p2 = -e1.z*v2.x + e1.x*v2.z;
if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;}
rad = fez * h.x + fex * h.z;
if(min>rad || max<-rad) return 0;
//AXISTEST_Z0(e1.y, e1.x, fey, fex);
p0 = e1.y*v0.x - e1.x*v0.y;
p1 = e1.y*v1.x - e1.x*v1.y;
if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;}
rad = fey * h.x + fex * h.y;
if(min>rad || max<-rad) return 0;
//-----------------------------------------------
fex = fabsf(e2.x);
fey = fabsf(e2.y);
fez = fabsf(e2.z);
//AXISTEST_X2(e2.z, e2.y, fez, fey);
p0 = e2.z*v0.y - e2.y*v0.z;
p1 = e2.z*v1.y - e2.y*v1.z;
if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;}
rad = fez * h.y + fey * h.z;
if(min>rad || max<-rad) return 0;
//AXISTEST_Y1(e2.z, e2.x, fez, fex);
p0 = -e2.z*v0.x + e2.x*v0.z;
p1 = -e2.z*v1.x + e2.x*v1.z;
if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;}
rad = fez * h.x + fex * h.z;
if(min>rad || max<-rad) return 0;
//AXISTEST_Z12(e2.y, e2.x, fey, fex);
p1 = e2.y*v1.x - e2.x*v1.y;
p2 = e2.y*v2.x - e2.x*v2.y;
if(p2<p1) {min=p2; max=p1;} else {min=p1; max=p2;}
rad = fey * h.x + fex * h.y;
if(min>rad || max<-rad) return 0;
//the {x,y,z}-directions (actually, since we use the AABB of the triangle we don't even need to test these)
//first test overlap in the {x,y,z}-directions
//find min, max of the triangle each direction, and test for overlap in that direction --
//this is equivalent to testing a minimal AABB around the triangle against the AABB
AABB taabb;
FINDMINMAX(v0.x, v1.x, v2.x, taabb.min.x,taabb.max.x);
FINDMINMAX(v0.y, v1.y, v2.y, taabb.min.y,taabb.max.y);
FINDMINMAX(v0.z, v1.z, v2.z, taabb.min.z,taabb.max.z);
//test in X-direction
FINDMINMAX(v0.x, v1.x, v2.x, taabb.min.x,taabb.max.x);
if(taabb.min.x>h.x || taabb.max.x<-h.x) return 0;
//test in Y-direction
FINDMINMAX(v0.y, v1.y, v2.y, taabb.min.y,taabb.max.y);
if(taabb.min.y>h.y || taabb.max.y<-h.y) return 0;
//test in Z-direction
FINDMINMAX(v0.z, v1.z, v2.z, taabb.min.z,taabb.max.z);
if(taabb.min.z>h.z || taabb.max.z<-h.z) return 0;
//test if the box intersects the plane of the triangle
//compute plane equation of triangle: normal*x+d=0
Plane plane=GetPlane( (e0%e1), v0);
Vec3 vmin,vmax;
if(plane.n.x>0.0f) { vmin.x=-h.x; vmax.x=+h.x; }
else { vmin.x=+h.x; vmax.x=-h.x; }
if(plane.n.y>0.0f) { vmin.y=-h.y; vmax.y=+h.y; }
else { vmin.y=+h.y; vmax.y=-h.y; }
if(plane.n.z>0.0f) { vmin.z=-h.z; vmax.z=+h.z; }
else { vmin.z=+h.z; vmax.z=-h.z; }
if( (plane|vmin) > 0.0f) return 0;
if( (plane|vmax) < 0.0f) return 0;
return 1;
}
/*!
*
* we use the SEPARATING AXIS TEST to check if a triangle and an OBB overlaps.
*
* Example:
* bool result=Overlap::OBB_Trinagle( pos1,obb1, tv0,tv1,tv2 );
*
*/
inline bool OBB_Triangle( const Vec3 &pos, const OBB &obb, const Vec3 &tv0, const Vec3 &tv1, const Vec3 &tv2 ) {
Vec3 p = obb.m33*obb.c + pos; //the new center-position in world-space
//move everything so that the boxcenter is in (0,0,0)
Vec3 v0 = (tv0-p)*obb.m33; //pre-transform
Vec3 v1 = (tv1-p)*obb.m33; //pre-transform
Vec3 v2 = (tv2-p)*obb.m33; //pre-transform
//compute triangle edges
Vec3 e0 = v1-v0;
Vec3 e1 = v2-v1;
Vec3 e2 = v0-v2;
//--------------------------------------------------------------------------------------
// use SEPARATING AXIS THEOREM to test intersection between AABB and triangle
// cross-product(edge from triangle, {x,y,z}-direction), this are 3x3=9 tests
//--------------------------------------------------------------------------------------
float min,max,p0,p1,p2,rad,fex,fey,fez;
fex = fabsf(e0.x);
fey = fabsf(e0.y);
fez = fabsf(e0.z);
//AXISTEST_X01(e0.z, e0.y, fez, fey);
p0 = e0.z*v0.y - e0.y*v0.z;
p2 = e0.z*v2.y - e0.y*v2.z;
if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;}
rad = fez * obb.h.y + fey * obb.h.z;
if(min>rad || max<-rad) return 0;
//AXISTEST_Y02(e0.z, e0.x, fez, fex);
p0 = -e0.z*v0.x + e0.x*v0.z;
p2 = -e0.z*v2.x + e0.x*v2.z;
if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;}
rad = fez * obb.h.x + fex * obb.h.z;
if(min>rad || max<-rad) return 0;
//AXISTEST_Z12(e0.y, e0.x, fey, fex);
p1 = e0.y*v1.x - e0.x*v1.y;
p2 = e0.y*v2.x - e0.x*v2.y;
if(p2<p1) {min=p2; max=p1;} else {min=p1; max=p2;}
rad = fey * obb.h.x + fex * obb.h.y;
if(min>rad || max<-rad) return 0;
//-----------------------------------------------
fex = fabsf(e1.x);
fey = fabsf(e1.y);
fez = fabsf(e1.z);
//AXISTEST_X01(e1.z, e1.y, fez, fey);
p0 = e1.z*v0.y - e1.y*v0.z;
p2 = e1.z*v2.y - e1.y*v2.z;
if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;}
rad = fez * obb.h.y + fey * obb.h.z;
if(min>rad || max<-rad) return 0;
//AXISTEST_Y02(e1.z, e1.x, fez, fex);
p0 = -e1.z*v0.x + e1.x*v0.z;
p2 = -e1.z*v2.x + e1.x*v2.z;
if(p0<p2) {min=p0; max=p2;} else {min=p2; max=p0;}
rad = fez * obb.h.x + fex * obb.h.z;
if(min>rad || max<-rad) return 0;
//AXISTEST_Z0(e1.y, e1.x, fey, fex);
p0 = e1.y*v0.x - e1.x*v0.y;
p1 = e1.y*v1.x - e1.x*v1.y;
if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;}
rad = fey * obb.h.x + fex * obb.h.y;
if(min>rad || max<-rad) return 0;
//-----------------------------------------------
fex = fabsf(e2.x);
fey = fabsf(e2.y);
fez = fabsf(e2.z);
//AXISTEST_X2(e2.z, e2.y, fez, fey);
p0 = e2.z*v0.y - e2.y*v0.z;
p1 = e2.z*v1.y - e2.y*v1.z;
if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;}
rad = fez * obb.h.y + fey * obb.h.z;
if(min>rad || max<-rad) return 0;
//AXISTEST_Y1(e2.z, e2.x, fez, fex);
p0 = -e2.z*v0.x + e2.x*v0.z;
p1 = -e2.z*v1.x + e2.x*v1.z;
if(p0<p1) {min=p0; max=p1;} else {min=p1; max=p0;}
rad = fez * obb.h.x + fex * obb.h.z;
if(min>rad || max<-rad) return 0;
//AXISTEST_Z12(e2.y, e2.x, fey, fex);
p1 = e2.y*v1.x - e2.x*v1.y;
p2 = e2.y*v2.x - e2.x*v2.y;
if(p2<p1) {min=p2; max=p1;} else {min=p1; max=p2;}
rad = fey * obb.h.x + fex * obb.h.y;
if(min>rad || max<-rad) return 0;
//the {x,y,z}-directions (actually, since we use the AABB of the triangle we don't even need to test these)
//first test overlap in the {x,y,z}-directions
//find min, max of the triangle each direction, and test for overlap in that direction --
//this is equivalent to testing a minimal AABB around the triangle against the AABB
AABB taabb;
FINDMINMAX(v0.x, v1.x, v2.x, taabb.min.x,taabb.max.x);
FINDMINMAX(v0.y, v1.y, v2.y, taabb.min.y,taabb.max.y);
FINDMINMAX(v0.z, v1.z, v2.z, taabb.min.z,taabb.max.z);
// test in X-direction
FINDMINMAX(v0.x, v1.x, v2.x, taabb.min.x,taabb.max.x);
if(taabb.min.x>obb.h.x || taabb.max.x<-obb.h.x) return 0;
// test in Y-direction
FINDMINMAX(v0.y, v1.y, v2.y, taabb.min.y,taabb.max.y);
if(taabb.min.y>obb.h.y || taabb.max.y<-obb.h.y) return 0;
// test in Z-direction
FINDMINMAX(v0.z, v1.z, v2.z, taabb.min.z,taabb.max.z);
if(taabb.min.z>obb.h.z || taabb.max.z<-obb.h.z) return 0;
//test if the box overlaps the plane of the triangle
//compute plane equation of triangle: normal*x+d=0
Plane plane=GetPlane( (e0%e1), v0);
Vec3 vmin,vmax;
if(plane.n.x>0.0f) { vmin.x=-obb.h.x; vmax.x=+obb.h.x; }
else { vmin.x=+obb.h.x; vmax.x=-obb.h.x; }
if(plane.n.y>0.0f) { vmin.y=-obb.h.y; vmax.y=+obb.h.y; }
else { vmin.y=+obb.h.y; vmax.y=-obb.h.y; }
if(plane.n.z>0.0f) { vmin.z=-obb.h.z; vmax.z=+obb.h.z; }
else { vmin.z=+obb.h.z; vmax.z=-obb.h.z; }
if( (plane|vmin) > 0.0f) return 0;
if( (plane|vmax) < 0.0f) return 0;
return 1;
}
/*!
*
* conventional method to check if two AABB's overlap.
* both AABBs are assumed to be in the same space
*
* Example:
* bool result=Overlap::AABB_AABB( aabb1, aabb2 );
*
*/
ILINE bool AABB_AABB( const AABB &aabb1, const AABB &aabb2 ) {
if (aabb1.min.x>=aabb2.max.x) return 0;
if (aabb1.min.y>=aabb2.max.y) return 0;
if (aabb1.min.z>=aabb2.max.z) return 0;
if (aabb1.max.x<=aabb2.min.x) return 0;
if (aabb1.max.y<=aabb2.min.y) return 0;
if (aabb1.max.z<=aabb2.min.z) return 0;
return 1; //the aabb's overlap
}
/*!
*
* Conventional method to check if two AABB's overlap.
* Both AABBs are in local object space. Used the position-vector
* to translate them into world-space
*
* Example:
* bool result=Overlap::AABB_AABB( pos1,aabb1, pos2,aabb2 );
*
*/
ILINE bool AABB_AABB( const Vec3 &pos1,const AABB &aabb1, const Vec3 &pos2,const AABB &aabb2 ) {
AABB waabb1(aabb1.min+pos1,aabb1.max+pos1);
AABB waabb2(aabb2.min+pos2,aabb2.max+pos2);
return AABB_AABB( waabb1, waabb2 );
}
/*!
*
* conventional method to check if two AABB's overlap
* or if AABB1 is comletely inside AABB2.
* both AABBs are assumed to be in the same space
*
* Example:
* bool result=Overlap::AABB_AABB_Inside( aabb1, aabb2 );
*
* return values:
* 0x00 = no overlap
* 0x01 = both AABBs one overlap
* 0x02 = AABB1 in inside AABB2
*/
ILINE char AABB_AABB_Inside( const AABB& aabb1, const AABB& aabb2 ) {
if ( AABB_AABB(aabb1,aabb2) ) {
if (aabb1.min.x<=aabb2.min.x) return 1;
if (aabb1.min.y<=aabb2.min.y) return 1;
if (aabb1.min.z<=aabb2.min.z) return 1;
if (aabb1.max.x>=aabb2.max.x) return 1;
if (aabb1.max.y>=aabb2.max.y) return 1;
if (aabb1.max.z>=aabb2.max.z) return 1;
//yes, its inside
return 2;
}
return 0;
}
/*!
*
* we use the SEPARATING AXIS TEST to check if two OBB's overlap.
*
* Example:
* bool result=Overlap::OBB_OBB( pos1,obb1, pos2,obb2 );
*
*/
inline bool OBB_OBB ( const Vec3 &pos1,const OBB &obb1, const Vec3 &pos2,const OBB &obb2 ) {
//tranform obb2 in local space of obb1
Matrix33 M=obb1.m33.T()*obb2.m33;
//the new center-position in world-space
Vec3 p1 = obb1.m33*obb1.c + pos1;
Vec3 p2 = obb2.m33*obb2.c + pos2;
//"t" is the transfer-vector from one center to the other
Vec3 t = (p2-p1)*obb1.m33;
float ra,rb;
//--------------------------------------------------------------------------
//-- we use the vectors "1,0,0","0,1,0" and "0,0,1" as separating axis
//--------------------------------------------------------------------------
rb = fabsf(M(0,0)*obb2.h.x) + fabsf(M(0,1)*obb2.h.y) + fabsf(M(0,2)*obb2.h.z);
if( fabsf(t.x) > (fabsf(obb1.h.x)+rb) ) return 0;
rb = fabsf(M(1,0)*obb2.h.x) + fabsf(M(1,1)*obb2.h.y) + fabsf(M(1,2)*obb2.h.z);
if( fabsf(t.y) > (fabsf(obb1.h.y)+rb) ) return 0;
rb = fabsf(M(2,0)*obb2.h.x) + fabsf(M(2,1)*obb2.h.y) + fabsf(M(2,2)*obb2.h.z);
if( fabsf(t.z) > (fabsf(obb1.h.z)+rb) ) return 0;
//--------------------------------------------------------------------------
//-- we use the orientation-vectors "Mx","My" and "Mz" as separating axis
//--------------------------------------------------------------------------
ra = fabsf(M(0,0)*obb1.h.x) + fabsf(M(1,0)*obb1.h.y) + fabsf(M(2,0)*obb1.h.z);
if( fabsf(t|Vec3(M(0,0),M(1,0),M(2,0))) > (ra+obb2.h.x) ) return 0;
ra = fabsf(M(0,1)*obb1.h.x) + fabsf(M(1,1)*obb1.h.y) + fabsf(M(2,1)*obb1.h.z);
if( fabsf(t|Vec3(M(0,1),M(1,1),M(2,1))) > (ra+obb2.h.y) ) return 0;
ra = fabsf(M(0,2)*obb1.h.x) + fabsf(M(1,2)*obb1.h.y) + fabsf(M(2,2)*obb1.h.z);
if( fabsf(t|Vec3(M(0,2),M(1,2),M(2,2))) > (ra+obb2.h.z) ) return 0;
//---------------------------------------------------------------------
//---- using 9 cross products we generate new separating axis
//---------------------------------------------------------------------
ra = obb1.h.y*fabsf(M(2,0)) + obb1.h.z*fabsf(M(1,0));
rb = obb2.h.y*fabsf(M(0,2)) + obb2.h.z*fabsf(M(0,1));
if( fabsf(t.z*M(1,0)-t.y*M(2,0)) > (ra+rb) ) return 0;
ra = obb1.h.y*fabsf(M(2,1)) + obb1.h.z*fabsf(M(1,1));
rb = obb2.h.x*fabsf(M(0,2)) + obb2.h.z*fabsf(M(0,0));
if( fabsf(t.z*M(1,1)-t.y*M(2,1)) > (ra+rb) ) return 0;
ra = obb1.h.y*fabsf(M(2,2)) + obb1.h.z*fabsf(M(1,2));
rb = obb2.h.x*fabsf(M(0,1)) + obb2.h.y*fabsf(M(0,0));
if( fabsf(t.z*M(1,2)-t.y*M(2,2)) > (ra+rb) ) return 0;
ra = obb1.h.x*fabsf(M(2,0)) + obb1.h.z*fabsf(M(0,0));
rb = obb2.h.y*fabsf(M(1,2)) + obb2.h.z*fabsf(M(1,1));
if( fabsf(t.x*M(2,0)-t.z*M(0,0)) > (ra+rb) ) return 0;
ra = obb1.h.x*fabsf(M(2,1)) + obb1.h.z*fabsf(M(0,1));
rb = obb2.h.x*fabsf(M(1,2)) + obb2.h.z*fabsf(M(1,0));
if( fabsf(t.x*M(2,1)-t.z*M(0,1)) > (ra+rb) ) return 0;
ra = obb1.h.x*fabsf(M(2,2)) + obb1.h.z*fabsf(M(0,2));
rb = obb2.h.x*fabsf(M(1,1)) + obb2.h.y*fabsf(M(1,0));
if( fabsf(t.x*M(2,2)-t.z*M(0,2)) > (ra+rb) ) return 0;
ra = obb1.h.x*fabsf(M(1,0)) + obb1.h.y*fabsf(M(0,0));
rb = obb2.h.y*fabsf(M(2,2)) + obb2.h.z*fabsf(M(2,1));
if( fabsf(t.y*M(0,0)-t.x*M(1,0)) > (ra+rb) ) return 0;
ra = obb1.h.x*fabsf(M(1,1)) + obb1.h.y*fabsf(M(0,1));
rb = obb2.h.x*fabsf(M(2,2)) + obb2.h.z*fabsf(M(2,0));
if( fabsf(t.y*M(0,1)-t.x*M(1,1)) > (ra+rb) ) return 0;
ra = obb1.h.x*fabsf(M(1,2)) + obb1.h.y*fabsf(M(0,2));
rb = obb2.h.x*fabsf(M(2,1)) + obb2.h.y*fabsf(M(2,0));
if( fabsf(t.y*M(0,2)-t.x*M(1,2)) > (ra+rb) ) return 0;
return 1; //no separating axis found, we have an overlap
}
#define PLANE_X 0
#define PLANE_Y 1
#define PLANE_Z 2
#define PLANE_NON_AXIAL 3
//! check if the point is inside a triangle
inline bool PointInTriangle(const Vec3& point, const Vec3& v0,const Vec3& v1,const Vec3& v2,const Vec3& normal)
{
float xt,yt;
Vec3 nn;
int p1,p2;
nn = normal;
nn.x = (float)fabs(nn.x);
nn.y = (float)fabs(nn.y);
nn.z = (float)fabs(nn.z);
if ((nn.x>=nn.y) && (nn.x>=nn.z))
{
xt=point.y; yt=point.z;
p1=PLANE_Y;p2=PLANE_Z;
}
else
if ((nn.y>=nn.x) && (nn.y>=nn.z))
{
xt=point.x;yt=point.z;
p1=PLANE_X;p2=PLANE_Z;
}
else
{
xt=point.x;yt=point.y;
p1=PLANE_X;p2=PLANE_Y;
}
float Ax,Ay,Bx,By;
float s;
bool front=false;
bool back=false;
Ax=(v0)[p1];Bx=(v1)[p1];
Ay=(v0)[p2];By=(v1)[p2];
s=((Ay-yt)*(Bx-Ax)-(Ax-xt)*(By-Ay));
if (s>=0)
{
if (back)
return (false);
front=true;
}
else
{
if (front)
return (false);
back=true;
}
Ax=(v1)[p1];Bx=(v2)[p1];
Ay=(v1)[p2];By=(v2)[p2];
s=((Ay-yt)*(Bx-Ax)-(Ax-xt)*(By-Ay));
if (s>=0)
{
if (back)
return (false);
front=true;
}
else
{
if (front) return (false);
back=true;
}
Ax=(v2)[p1];Bx=(v0)[p1];
Ay=(v2)[p2];By=(v0)[p2];
s=((Ay-yt)*(Bx-Ax)-(Ax-xt)*(By-Ay));
if (s>=0)
{
if (back)
return (false);
front=true;
}
else
{
if (front)
return (false);
back=true;
}
return (true);
}
}
#endif //overlap

582
CryCommon/Cry_Math.h Normal file
View File

@@ -0,0 +1,582 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Common Source code
//
// File:Cry_Math.h
// Description: Common math class
//
// History:
// -Feb 27,2003: Created by Ivo Herzeg
//
//////////////////////////////////////////////////////////////////////
#ifndef CRYMATH_H
#define CRYMATH_H
#if _MSC_VER > 1000
# pragma once
#endif
//========================================================================================
#include <math.h>
#include "platform.h"
#if !defined(LINUX)
#include <assert.h>
#endif
///////////////////////////////////////////////////////////////////////////////
// Forward declarations //
///////////////////////////////////////////////////////////////////////////////
template <class F> struct Vec3_tpl;
template <class F> struct Ang3_tpl;
template <class F> struct AngleAxis_tpl;
template <class F> struct Quaternion_tpl;
template <class F> struct Matrix33diag_tpl;
template <class F,int SI,int SJ> struct Matrix33_tpl;
template <class F> struct Matrix34_tpl;
template <class F,int SI,int SJ> struct Matrix44_tpl;
///////////////////////////////////////////////////////////////////////////////
// Definitions //
///////////////////////////////////////////////////////////////////////////////
const float gf_PI = 3.14159265358979323846264338327950288419716939937510f; // pi
const float gf_PI_MUL_2 = 3.14159265358979323846264338327950288419716939937510f*2; // 2*pi
const float gf_PI_DIV_2 = 3.14159265358979323846264338327950288419716939937510f*0.5f; // pi/2
const float gf_DEGTORAD = 0.01745329251994329547f; // Degrees to Radians
const float gf_RADTODEG = 57.29577951308232286465f; // Radians to Degrees
// the check for compatibility with Max SDK: Max gfx.h header defines its own pi
#if !defined(_GFX_H_)
const real pi = (real)3.1415926535897932384626433832795;
#endif
const real sqrt2 = (real)1.4142135623730950488016887242097;
const real sqrt3 = (real)1.7320508075688772935274463415059;
#define MAX(a,b) (((a) > (b)) ? (a) : (b))
#define MIN(a,b) (((a) < (b)) ? (a) : (b))
//-----------------------------------------------------------------------
#if defined(LINUX)
#undef assert
#define assert(exp) (void)( (exp) || (printf("Assert: ' %s ' has failed\n", #exp), 0) )
#endif
//-------------------------------------------
//-- the portability functions for AMD64
//-------------------------------------------
#if defined(WIN64) && defined(_CPU_AMD64) && !defined(LINUX)
#define ILINE __forceinline
extern "C" void fastsincosf(float x, float * sincosfx);
extern "C" float fastsinf(float x);
extern "C" float fastcosf(float x);
ILINE void cry_sincosf (float angle, float* pCosSin) { fastsincosf(angle,pCosSin); }
ILINE void cry_sincos (double angle, double* pCosSin) { pCosSin[0] = cos(angle); pCosSin[1] = sin(angle); }
ILINE float cry_sinf(float x) {return fastsinf(x); }
ILINE float cry_cosf(float x) {return fastcosf(x); }
ILINE float cry_fmod(float x, float y) {return (float)fmod((double)x,(double)y);}
ILINE float cry_asinf(float x) {return (float)asin((double)x);}
ILINE float cry_acosf(float x) {return (float)acos((double)x);}
ILINE float cry_atanf(float x) {return (float)atan((double)x);}
ILINE float cry_atan2f(float x, float y) {return (float)atan2((double)x,(double)y);}
ILINE float cry_tanhf(float x) { double expz = exp(double(x)), exp_z = exp(-double(x)); return (float)((expz-exp_z)/(expz+exp_z)); }
ILINE float cry_tanf(float x) {return (float)tan((double)x);}
ILINE float cry_sqrtf(float x) {return (float)sqrt((double)x);}
ILINE float cry_fabsf(float x) {return (float)fabs((double)x);}
ILINE float cry_expf(float x) {return (float)exp((double)x);}
ILINE float cry_logf(float x) {return (float)log((double)x);}
ILINE float cry_powf(float x, float y) {return (float) pow((double)x,(double)y);}
ILINE float cry_ceilf(float x) {return (float)ceil((double)x);}
ILINE float cry_floorf(float x) {return (float)floor((double)x);}
ILINE double cry_sinh(double z) {return (exp (z) - exp (-z)) * 0.5;}
ILINE double cry_cosh(double z) {return (exp (z) + exp (-z)) * 0.5;}
#endif
//-------------------------------------------
//-- the portability functions for CPU_X86
//-------------------------------------------
#if defined(_CPU_X86) && defined(_MSC_VER) && !defined(LINUX)
#define ILINE __forceinline
// calculates the cosine and sine of the given angle in radians
ILINE void cry_sincosf (float angle, float* pCosSin) {
__asm {
FLD DWORD PTR angle
FSINCOS
MOV EAX,pCosSin
FSTP DWORD PTR [EAX] //put cosine into pCosSin[0]
FSTP DWORD PTR [EAX+4] //put sine into cossin[1]
}
}
// calculates the cosine and sine of the given angle in radians
ILINE void cry_sincos (double angle, double* pCosSin) {
__asm {
FLD QWORD PTR angle
FSINCOS
MOV EAX,pCosSin
FSTP QWORD PTR [EAX] //put cosine into pCosSin[0]
FSTP QWORD PTR [EAX+8] //put sine into cossin[1]
}
}
ILINE float cry_sinf(float x) {return sinf(x);}
ILINE float cry_cosf(float x) {return cosf(x);}
ILINE float cry_fmod(float x, float y) {return (float)fmodf(x,y);}
ILINE float cry_ceilf(float x) {return ceilf(x);}
ILINE float cry_asinf(float x) {return asinf(x);}
ILINE float cry_acosf(float x) {return acosf(x);}
ILINE float cry_atanf(float x) {return atanf(x);}
ILINE float cry_atan2f(float x, float y) {return atan2f(x,y);}
ILINE float cry_sqrtf(float x) {return sqrtf(x);}
ILINE float cry_tanhf(float x) {return tanhf(x);}
ILINE float cry_fabsf(float x) {return fabsf(x);}
ILINE float cry_expf(float x) {return expf(x);}
ILINE float cry_logf(float x) {return logf(x);}
ILINE float cry_floorf(float x) {return floorf(x);}
ILINE float cry_tanf(float x) {return tanf(x);}
ILINE float cry_powf(float x, float y) {return powf(x,y);}
#endif
//-------------------------------------------
//-- the portability functions for LINUX
//-------------------------------------------
#if defined(LINUX)
#define ILINE inline
ILINE void cry_sincosf (float angle, float* pCosSin) { pCosSin[0] = (float)cos(angle); pCosSin[1] = (float)sin(angle); }
ILINE void cry_sincos (double angle, double* pCosSin) { pCosSin[0] = cos(angle); pCosSin[1] = sin(angle); }
ILINE float cry_sinf(float x) {return sinf(x);}
ILINE float cry_cosf(float x) {return cosf(x);}
ILINE float cry_fmod(float x, float y) {return (float)fmodf(x,y);}
ILINE float cry_ceilf(float x) {return ceilf(x);}
ILINE float cry_asinf(float x) {return asinf(x);}
ILINE float cry_acosf(float x) {return acosf(x);}
ILINE float cry_atanf(float x) {return atanf(x);}
ILINE float cry_atan2f(float x, float y) {return atan2f(x,y);}
ILINE float cry_sqrtf(float x) {return sqrtf(x);}
ILINE float cry_tanhf(float x) {return tanhf(x);}
ILINE float cry_fabsf(float x) {return fabsf(x);}
ILINE float cry_expf(float x) {return expf(x);}
ILINE float cry_logf(float x) {return logf(x);}
ILINE float cry_floorf(float x) {return floorf(x);}
ILINE float cry_tanf(float x) {return tanf(x);}
ILINE float cry_powf(float x, float y) {return powf(x,y);}
#endif
//-----------------------------------------------------------------------
ILINE void sincos_tpl(double angle, double* pCosSin) { cry_sincos(angle,pCosSin); }
ILINE void sincos_tpl(float angle, float* pCosSin) { cry_sincosf(angle,pCosSin); }
ILINE double cos_tpl(double op) { return cos(op); }
ILINE float cos_tpl(float op) { return cry_cosf(op); }
ILINE double sin_tpl(double op) { return sin(op); }
ILINE float sin_tpl(float op) { return cry_sinf(op); }
ILINE double acos_tpl(double op) { return acos(op); }
ILINE float acos_tpl(float op) { return cry_acosf(op); }
ILINE double asin_tpl(double op) { return asin(op); }
ILINE float asin_tpl(float op) { return cry_asinf(op); }
ILINE double atan_tpl(double op) { return atan(op); }
ILINE float atan_tpl(float op) { return cry_atanf(op); }
ILINE double atan2_tpl(double op1,double op2) { return atan2(op1,op2); }
ILINE float atan2_tpl(float op1,float op2) { return cry_atan2f(op1,op2); }
ILINE double exp_tpl(double op) { return exp(op); }
ILINE float exp_tpl(float op) { return cry_expf(op); }
ILINE double log_tpl(double op) { return log(op); }
ILINE float log_tpl(float op) { return cry_logf(op); }
ILINE double sqrt_tpl(double op) { return sqrt(op); }
ILINE float sqrt_tpl(float op) { return cry_sqrtf(op); }
ILINE double fabs_tpl(double op) { return fabs(op); }
ILINE float fabs_tpl(float op) { return cry_fabsf(op); }
ILINE int fabs_tpl(int op) { int mask=op>>31; return op+mask^mask; }
ILINE int floor_tpl(int op) {return op;}
ILINE float floor_tpl(float op) {return cry_floorf(op);}
ILINE double floor_tpl(double op) {return floor(op);}
ILINE int ceil_tpl(int op) {return op;}
ILINE float ceil_tpl(float op) {return cry_ceilf(op);}
ILINE double ceil_tpl(double op) {return ceil(op);}
ILINE float tan_tpl(float op) {return cry_tanf(op);}
ILINE double tan_tpl(double op) {return tan(op);}
static int inc_mod3[]={1,2,0}, dec_mod3[]={2,0,1};
#ifdef PHYSICS_EXPORTS
#define incm3(i) inc_mod3[i]
#define decm3(i) dec_mod3[i]
#else
inline int incm3(int i) { return i+1 & (i-2)>>31; }
inline int decm3(int i) { return i-1 + ((i-1)>>31&3); }
#endif
template <class T> T clamp_tpl( T X, T Min, T Max ) { return X<Min ? Min : X<Max ? X : Max; }
template<class F> inline F square(F fOp) { return(fOp*fOp); }
//this can easily be confused with square-root?
template<class F> inline F sqr(const F &op) { return op*op; }
template<class F> inline F cube(const F &op) { return op*op*op; }
template<class F> inline F sqr_signed(const F &op) { return op*fabs_tpl(op); }
#define cx csx[0]
#define sx csx[1]
#define cy csy[0]
#define sy csy[1]
#define cz csz[0]
#define sz csz[1]
//#include "Cry_Vector2.h"
//#include "Cry_Vector3.h"
#include "Cry_Matrix.h"
//#include "Cry_Quat.h"
#undef cx
#undef sx
#undef cy
#undef sy
#undef cz
#undef sz
#if (defined(WIN32) || defined (_XBOX))
#include "Cry_XOptimise.h"
#endif
inline float sqr(vectorf op) { return op*op; }
inline real sqr(vectorr op) { return op*op; }
inline int sgnnz(double x) {
union { float f; int i; } u;
u.f=(float)x; return ((u.i>>31)<<1)+1;
}
inline int sgnnz(float x) {
union { float f; int i; } u;
u.f=x; return ((u.i>>31)<<1)+1;
}
inline int sgnnz(int x) {
return ((x>>31)<<1)+1;
}
inline int sgn(double x) {
union { float f; int i; } u;
u.f=(float)x; return (u.i>>31)+((u.i-1)>>31)+1;
}
inline int sgn(float x) {
union { float f; int i; } u;
u.f=x; return (u.i>>31)+((u.i-1)>>31)+1;
}
inline int sgn(int x) {
return (x>>31)+((x-1)>>31)+1;
}
inline int isneg(double x) {
union { float f; unsigned int i; } u;
u.f=(float)x; return (int)(u.i>>31);
}
inline int isneg(float x) {
union { float f; unsigned int i; } u;
u.f=x; return (int)(u.i>>31);
}
inline int isneg(int x) {
return (int)((unsigned int)x>>31);
}
inline int isnonneg(double x) {
union { float f; unsigned int i; } u;
u.f=(float)x; return (int)(u.i>>31^1);
}
inline int isnonneg(float x) {
union { float f; unsigned int i; } u;
u.f=x; return (int)(u.i>>31^1);
}
inline int isnonneg(int x) {
return (int)((unsigned int)x>>31^1);
}
inline int iszero(double x) {
union { float f; int i; } u;
u.f=(float)x;
u.i&=0x7FFFFFFF;
return -((u.i>>31)^(u.i-1)>>31);
}
inline int iszero(float x) {
union { float f; int i; } u;
u.f=x; u.i&=0x7FFFFFFF; return -(u.i>>31^(u.i-1)>>31);
}
inline int iszero(int x) {
return -(x>>31^(x-1)>>31);
}
#if defined(WIN64) || defined(LINUX64)
// AMD64 port: TODO: optimize
inline int64 iszero(__int64 x)
{
return -(x>>63^(x-1)>>63);
}
#endif
#if defined(LINUX64)
inline int64 iszero(intptr_t x)
{
return (sizeof(x) == 8)?iszero((__int64)x) : iszero((int)x);
}
#endif
template<class F> int inrange(F x, F end1, F end2) {
return isneg(fabs_tpl(end1+end2-x*(F)2) - fabs_tpl(end1-end2));
}
template<class F> F cond_select(int bFirst, F op1,F op2) {
F arg[2] = { op1,op2 };
return arg[bFirst^1];
}
template<class F> int idxmax3(F *pdata) {
int imax = isneg(pdata[0]-pdata[1]);
imax |= isneg(pdata[imax]-pdata[2])<<1;
return imax & (2|(imax>>1^1));
}
template<class F> int idxmin3(F *pdata) {
int imin = isneg(pdata[1]-pdata[0]);
imin |= isneg(pdata[2]-pdata[imin])<<1;
return imin & (2|(imin>>1^1));
}
inline int getexp(float x) { return (int)(*(unsigned int*)&x>>23&0x0FF)-127; }
inline int getexp(double x) { return (int)(*((unsigned int*)&x+1)>>20&0x7FF)-1023; }
inline float &setexp(float &x,int iexp) { (*(unsigned int*)&x &= ~(0x0FF<<23)) |= (iexp+127)<<23; return x; }
inline double &setexp(double &x,int iexp) { (*((unsigned int*)&x+1) &= ~(0x7FF<<20)) |= (iexp+1023)<<20; return x; }
class unused_marker {
public:
unused_marker() {}
unused_marker& operator,(float &x) { *(int*)&x = 0xFFBFFFFF; return *this; }
unused_marker& operator,(double &x) { *((int*)&x+1) = 0xFFF7FFFF; return *this; }
unused_marker& operator,(int &x) { x=1<<31; return *this; }
unused_marker& operator,(unsigned int &x) { x=1u<<31; return *this; }
template<class ref> unused_marker& operator,(ref *&x) { x=(ref*)-1; return *this; }
template<class F> unused_marker& operator,(Vec3_tpl<F> &x) { return *this,x.x; }
template<class F> unused_marker& operator,(Quaternion_tpl<F> &x) { return *this,x.w; }
};
inline bool is_unused(const float &x) { return (*(int*)&x & 0xFFA00000) == 0xFFA00000; }
inline bool is_unused(int x) { return x==1<<31; }
inline bool is_unused(unsigned int x) { return x==1u<<31; }
template<class ref> bool is_unused(ref *x) { return x==(ref*)-1; }
template<class F> bool is_unused(const Vec3_tpl<F> &x) { return is_unused(x.x); }
template<class F> bool is_unused(const Quaternion_tpl<F> &x) { return is_unused(x.w); }
inline bool is_unused(const double &x) { return (*((int*)&x+1) & 0xFFF40000) == 0xFFF40000; }
#define MARK_UNUSED unused_marker(),
template<class dtype> class strided_pointer {
public:
strided_pointer() { data=0; iStride=sizeof(dtype); }
strided_pointer(dtype *pdata,int stride=sizeof(dtype)) { data=pdata; iStride=stride; }
strided_pointer(const strided_pointer &src) { data=src.data; iStride=src.iStride; }
template<class dtype1> strided_pointer(const strided_pointer<dtype1> &src) { data=src.data; iStride=src.iStride; }
strided_pointer& operator=(dtype *pdata) { data=pdata; return *this; }
strided_pointer& operator=(const strided_pointer<dtype> &src) { data=src.data; iStride=src.iStride; return *this; }
template<class dtype1> strided_pointer& operator=(const strided_pointer<dtype1> &src) { data=src.data; iStride=src.iStride; return *this; }
dtype& operator[](int idx) { return *(dtype*)((char*)data+idx*iStride); }
const dtype& operator[](int idx) const { return *(const dtype*)((const char*)data+idx*iStride); }
strided_pointer<dtype> operator+(int idx) const { return strided_pointer<dtype>((dtype*)((char*)data+idx*iStride),iStride); }
strided_pointer<dtype> operator-(int idx) const { return strided_pointer<dtype>((dtype*)((char*)data-idx*iStride),iStride); }
dtype& operator*() const { return *data; }
operator void*() const { return (void*)data; }
dtype *data;
int iStride;
};
template<class F> F _condmax(F, int masknot) {
return 1<<(sizeof(int)*8-2) & ~masknot;
}
inline float _condmax(float, int masknot) {
return 1E30f*(masknot+1);
}
template<class F> int unite_lists(F *pSrc0,INT_PTR nSrc0, F *pSrc1,INT_PTR nSrc1, F *pDst,int szdst) //AMD Port
{
int i0,i1,n;
INT_PTR inrange0=-nSrc0>>((sizeof(size_t)*8)-1),inrange1=-nSrc1>>((sizeof(size_t)*8)-1); //AMD Port
F a0,a1,ares,dummy=0;
INT_PTR pDummy( (INT_PTR) &dummy );
pSrc0 = (F*)((INT_PTR)pSrc0&inrange0 | pDummy&~inrange0); // make pSrc point to valid data even if nSrc is zero //AMD Port
pSrc1 = (F*)((INT_PTR)pSrc1&inrange1 | pDummy&~inrange1); //AMD Port
for(n=i0=i1=0; (inrange0 | inrange1) & n-szdst>>31; inrange0=(i0+=isneg(a0-ares-1))-nSrc0>>31, inrange1=(i1+=isneg(a1-ares-1))-nSrc1>>31)
{
a0 = pSrc0[i0&inrange0] + _condmax(pSrc0[0],inrange0); //(1<<(sizeof(index)*8-2)&~inrange0);
a1 = pSrc1[i1&inrange1] + _condmax(pSrc1[0],inrange1); //(1<<(sizeof(index)*8-2)&~inrange1);
pDst[n++] = ares = min(a0,a1);
}
return n;
}
template<class F> int intersect_lists(F *pSrc0,int nSrc0, F *pSrc1,int nSrc1, F *pDst)
{
int i0,i1,n; F ares;
for(i0=i1=n=0; isneg(i0-nSrc0) & isneg(i1-nSrc1); i0+=isneg(pSrc0[i0]-ares-1),i1+=isneg(pSrc1[i1]-ares-1)) {
pDst[n] = ares = min(pSrc0[i0],pSrc1[i1]); n += iszero(pSrc0[i0]-pSrc1[i1]);
}
return n;
}
#if defined(PHYSICS_EXPORTS) || (defined(WIN64) && defined(CRYENTITYDLL_EXPORTS)) || (defined(LINUX))
#ifdef max
#undef max
#endif
#ifdef min
#undef min
#endif
inline double min(double op1,double op2) { return (op1+op2-fabs(op1-op2))*0.5; }
inline double max(double op1,double op2) { return (op1+op2+fabs(op1-op2))*0.5; }
inline float max(float op1,float op2) { return (op1+op2+fabsf(op1-op2))*0.5f; }
inline float min(float op1,float op2) { return (op1+op2-fabsf(op1-op2))*0.5f; }
inline int max(int op1,int op2) { return op1 - (op1-op2 & (op1-op2)>>31); }
inline int min(int op1,int op2) { return op2 + (op1-op2 & (op1-op2)>>31); }
inline double minmax(double op1,double op2,int bMax) { return (op1+op2+fabs(op1-op2)*(bMax*2-1))*0.5; }
inline float minmax(float op1,float op2,int bMax) { return (op1+op2+fabsf(op1-op2)*(bMax*2-1))*0.5f; }
inline int minmax(int op1,int op2,int bMax) { return (op1&-bMax | op2&~-bMax) + ((op1-op2 & (op1-op2)>>31)^-bMax)+bMax; }
#endif
template<class F> inline F max_safe(F op1,F op2) { return op1>op2 ? op1:op2; }//int mask=isneg(op2-op1); return op1*mask+op2*(mask^1); }
template<class F> inline F min_safe(F op1,F op2) { return op1<op2 ? op1:op2; }//{ int mask=isneg(op1-op2); return op1*mask+op2*(mask^1); }
#ifndef PHYSICS_EXPORTS
#define VALIDATOR_LOG(pLog,str)
#define VALIDATORS_START
#define VALIDATOR(member)
#define VALIDATOR_NORM(member)
#define VALIDATOR_NORM_MSG(member,msg,member1)
#define VALIDATOR_RANGE(member,minval,maxval)
#define VALIDATOR_RANGE2(member,minval,maxval)
#define VALIDATORS_END
#endif
typedef struct VALUE16 {
union {
struct { unsigned char a,b; } c;
unsigned short ab;
};
} VALUE16;
inline unsigned short SWAP16(unsigned short l) {
VALUE16 l16;
unsigned char a,b;
l16.ab=l;
a=l16.c.a; b=l16.c.b;
l16.c.a=b; l16.c.b=a;
return l16.ab;
}
//--------------------------------------------
typedef struct VALUE32 {
union {
struct { unsigned char a,b,c,d; } c;
float FLOAT;
unsigned long abcd;
const void* ptr;
};
} VALUE32;
inline unsigned long SWAP32(unsigned long l) {
VALUE32 l32;
unsigned char a,b,c,d;
l32.abcd=l;
a=l32.c.a; b=l32.c.b; c=l32.c.c; d=l32.c.d;
l32.c.a=d; l32.c.b=c; l32.c.c=b; l32.c.d=a;
return l32.abcd;
}
inline const void* SWAP32(const void* l) {
VALUE32 l32;
unsigned char a,b,c,d;
l32.ptr=l;
a=l32.c.a; b=l32.c.b; c=l32.c.c; d=l32.c.d;
l32.c.a=d; l32.c.b=c; l32.c.c=b; l32.c.d=a;
return l32.ptr;
}
inline float FSWAP32(float f) {
VALUE32 l32;
unsigned char a,b,c,d;
l32.FLOAT=f;
a=l32.c.a; b=l32.c.b; c=l32.c.c; d=l32.c.d;
l32.c.a=d; l32.c.b=c; l32.c.c=b; l32.c.d=a;
return l32.FLOAT;
}
#endif //math

2122
CryCommon/Cry_Matrix.h Normal file

File diff suppressed because it is too large Load Diff

893
CryCommon/Cry_Quat.h Normal file
View File

@@ -0,0 +1,893 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Common Source code
//
// File:Cry_Quat.h
// Description: Common quaternion class
//
// History:
// -Feb 27,2003: Created by Ivo Herzeg
//
//////////////////////////////////////////////////////////////////////
#ifndef _CRYQUAT_H
#define _CRYQUAT_H
#include "platform.h"
#include "Cry_Vector2.h"
#include "Cry_Vector3.h"
#include "Cry_Matrix.h"
#if defined(LINUX)
#undef assert
#define assert(exp) (void)( (exp) || (printf("Assert: ' %s ' has failed\n", #exp), 0) )
#endif
///////////////////////////////////////////////////////////////////////////////
// Typedefs //
///////////////////////////////////////////////////////////////////////////////
typedef Quaternion_tpl<f32> CryQuat;
#ifndef MAX_API_NUM
typedef Quaternion_tpl<f32> Quat;
typedef Quaternion_tpl<real> Quat_f64;
#endif
typedef Quaternion_tpl<f32> quaternionf;
typedef Quaternion_tpl<real> quaternion;
///////////////////////////////////////////////////////////////////////////////
// Definitions //
///////////////////////////////////////////////////////////////////////////////
#define M00 data[SI*0+SJ*0]
#define M10 data[SI*1+SJ*0]
#define M20 data[SI*2+SJ*0]
#define M30 data[SI*3+SJ*0]
#define M01 data[SI*0+SJ*1]
#define M11 data[SI*1+SJ*1]
#define M21 data[SI*2+SJ*1]
#define M31 data[SI*3+SJ*1]
#define M02 data[SI*0+SJ*2]
#define M12 data[SI*1+SJ*2]
#define M22 data[SI*2+SJ*2]
#define M32 data[SI*3+SJ*2]
#define M03 data[SI*0+SJ*3]
#define M13 data[SI*1+SJ*3]
#define M23 data[SI*2+SJ*3]
#define M33 data[SI*3+SJ*3]
#define m_00 m.data[SI1*0+SJ1*0]
#define m_10 m.data[SI1*1+SJ1*0]
#define m_20 m.data[SI1*2+SJ1*0]
#define m_30 m.data[SI1*3+SJ1*0]
#define m_01 m.data[SI1*0+SJ1*1]
#define m_11 m.data[SI1*1+SJ1*1]
#define m_21 m.data[SI1*2+SJ1*1]
#define m_31 m.data[SI1*3+SJ1*1]
#define m_02 m.data[SI1*0+SJ1*2]
#define m_12 m.data[SI1*1+SJ1*2]
#define m_22 m.data[SI1*2+SJ1*2]
#define m_32 m.data[SI1*3+SJ1*2]
#define m_03 m.data[SI1*0+SJ1*3]
#define m_13 m.data[SI1*1+SJ1*3]
#define m_23 m.data[SI1*2+SJ1*3]
#define m_33 m.data[SI1*3+SJ1*3]
#if defined(LINUX)
template<class F,int SI,int SJ>
Quaternion_tpl<F> GetQuatFromMat33(const Matrix33_tpl<F,SI,SJ>& m);
#endif
//----------------------------------------------------------------------
// Quaternion
//----------------------------------------------------------------------
template <class F> struct Quaternion_tpl
{
Vec3_tpl<F> v; F w;
//-------------------------------
//constructors
Quaternion_tpl() { w=1; v(0,0,0); }
Quaternion_tpl( F W,F X,F Y,F Z ) { w = W; v.x=X; v.y=Y; v.z=Z; }
Quaternion_tpl( const F angle, const Vec3_tpl<F> &axis);
template<class F1,int SI,int SJ>
explicit ILINE Quaternion_tpl(const Matrix33_tpl<F1,SI,SJ>& m) { *this=GetQuatFromMat33(m); }
template<class T>
explicit ILINE Quaternion_tpl(const Matrix34_tpl<T>& m) { *this=GetQuatFromMat33(Matrix33(m)); }
template<class F1,int SI,int SJ>
explicit ILINE Quaternion_tpl(const Matrix44_tpl<F1,SI,SJ>& m) { *this=GetQuatFromMat33(Matrix33_tpl<f32,3,1>(m)); }
//CONSTRUCTOR: implement the copy/casting/assignement constructor:
template <class T>
ILINE Quaternion_tpl( const Quaternion_tpl<T>& q ) { w=q.w; v.x=q.v.x; v.y=q.v.y; v.z=q.v.z; }
//assignement of equal types
ILINE Quaternion_tpl& operator=(const Quaternion_tpl<F>& q) {
w=q.w; v=q.v; return *this;
}
//double=f32
template<typename U> ILINE Quaternion_tpl& operator=(const U& q) {
w=(F)q.w; v.x=(F)q.v.x; v.y=(F)q.v.y; v.z=(F)q.v.z; return *this;
}
/* declared as static but never used or implemented as static member functions, Linux gcc don't like it too
#ifndef WIN64
//dot-product
template<typename F1,typename F2> static f32 operator | (const Quaternion_tpl<F1>& q, const Quaternion_tpl<F2>& p);
//multiplication operator
template<typename F1,typename F2> static Quaternion_tpl<F1> operator * (const Quaternion_tpl<F1> &q, const Quaternion_tpl<F2> &p);
template<typename F1,typename F2> static void operator*=(Quaternion_tpl<F1> &q, const Quaternion_tpl<F2> &p);
//division operator
template<typename F1,typename F2> static Quaternion_tpl<F1> operator / (const Quaternion_tpl<F1> &q, const Quaternion_tpl<F2> &p);
template<typename F1,typename F2> static void operator /= (Quaternion_tpl<F1> &q, const Quaternion_tpl<F2> &p);
//addition operator
template<typename F1,typename F2> static Quaternion_tpl<F1> operator+(const Quaternion_tpl<F1> &q, const Quaternion_tpl<F2> &p);
template<typename F1,typename F2> static void operator+=(Quaternion_tpl<F1> &q, const Quaternion_tpl<F2> &p);
//subtraction operator
template<typename F1,typename F2> static Quaternion_tpl<F1> operator - (const Quaternion_tpl<F1> &q, const Quaternion_tpl<F2> &p);
template<typename F1,typename F2> static void operator-=(Quaternion_tpl<F1> &q, const Quaternion_tpl<F2> &p);
//rotate a vector by a quaternion
template<typename F1,typename F2> static Vec3_tpl<F2> operator*(const Quaternion_tpl<F1> &q, const Vec3_tpl<F2> &v);
template<typename F1,typename F2> static Vec3_tpl<F1> operator*(const Vec3_tpl<F1> &v, const Quaternion_tpl<F2> &q);
#endif
*/
//multiplication by a scalar
//friend Quaternion_tpl<F> operator * ( const Quaternion_tpl<F> &q, f32 t );
//friend Quaternion_tpl<F> operator * ( f32 t, const Quaternion_tpl<F> &q );
void operator *= (F op) { w*=op; v*=op; }
//negate quaternion. dont confuse this with quaternion-inversion.
Quaternion_tpl<F> operator - () const { return Quaternion_tpl<F>( -w,-v ); };
Quaternion_tpl<F> operator ! () const;
void SetIdentity(void);
static Quaternion_tpl<F> GetIdentity(void);
void SetRotationAA(F rad, const Vec3_tpl<F> &axis);
static Quaternion_tpl<F> GetRotationAA(F rad, const Vec3_tpl<F> &axis);
void SetRotationAA(F cosha, F sinha, const Vec3_tpl<F> &axis);
static Quaternion_tpl<F> GetRotationAA(F cosha, F sinha, const Vec3_tpl<F> &axis);
void SetRotationV0V1(const Vec3_tpl<F>& v0, const Vec3_tpl<F>& v1);
static Quaternion_tpl<F> GetRotationV0V1(const Vec3_tpl<F>& v0, const Vec3_tpl<F>& v1);
void SetRotationXYZ(const Ang3 &a);
static Quaternion_tpl<F> GetRotationXYZ(const Ang3 &a);
void Invert( void );
static Quaternion_tpl<F> GetInverted(Quaternion_tpl<F>& q);
void Normalize(void);
static Quaternion_tpl<F> GetNormalized( const Quaternion_tpl<F> &q );
static F GetLength( const Quaternion_tpl<F> &q );
};
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
/*!
* Constructor using a scalar and a vector
*
* Example:
* Vec3 vec;
* Quaternion quat = quaternionf( 0.5f, vec );
*/
template<class F>
ILINE Quaternion_tpl<F>::Quaternion_tpl( const F angle, const Vec3_tpl<F> &axis) { w=angle; v=axis; }
/*!
*
* The "inner product" or "dot product" operation.
*
* calculate the "inner product" between two Quaternion.
* If both Quaternion are unit-quaternions, the result is the cosine: p*q=cos(angle)
*
* Example:
* Quaternion p(1,0,0,0),q(1,0,0,0);
* f32 cosine = ( p | q );
*
*/
template<typename F1,typename F2>
ILINE f32 operator | (const Quaternion_tpl<F1>& q, const Quaternion_tpl<F2>& p) {
return (q.v.x*p.v.x + q.v.y*p.v.y + q.v.z*p.v.z + q.w*p.w);
}
/*!
* multiplication operator
*
* Example 1:
* Quaternion p(1,0,0,0),q(1,0,0,0);
* Quaternion result=p*q;
*
* Example 2: (self-multiplication)
* Quaternion p(1,0,0,0),q(1,0,0,0);
* Quaternion p*=q;
*
*/
template<class F1,class F2>
ILINE Quaternion_tpl<F1> operator * (const Quaternion_tpl<F1> &q, const Quaternion_tpl<F2> &p) {
return Quaternion_tpl<F1>(q.w*p.w-(q.v|p.v), q.v*p.w + q.w*p.v + (q.v%p.v) );
}
template<class F1,class F2>
ILINE void operator *= (Quaternion_tpl<F1> &q, const Quaternion_tpl<F2> &p) {
F1 s0=q.w; q.w=q.w*p.w-(q.v|p.v); q.v=p.v*s0+q.v*p.w+(q.v%p.v);
}
/*!
* division operator
*
* Example 1:
* Quaternion p(1,0,0,0),q(1,0,0,0);
* Quaternion result=p/q;
*
* Example 2: (self-division)
* Quaternion p(1,0,0,0),q(1,0,0,0);
* Quaternion p/=q;
*
*/
template<class F1,class F2>
ILINE Quaternion_tpl<F1> operator / (const Quaternion_tpl<F1> &q, const Quaternion_tpl<F2> &p) {
return (!p*q);
}
template<class F1,class F2>
ILINE void operator /= (Quaternion_tpl<F1> &q, const Quaternion_tpl<F2> &p) {
q=(!p*q);
}
/*!
* addition operator
*
* Example:
* Quaternion p(1,0,0,0),q(1,0,0,0);
* Quaternion result=p+q;
*
* Example:(self-addition operator)
* Quaternion p(1,0,0,0),q(1,0,0,0);
* Quaternion p-=q;
*
*/
template<class F1,class F2>
ILINE Quaternion_tpl<F1> operator+(const Quaternion_tpl<F1> &q, const Quaternion_tpl<F2> &p) {
return Quaternion_tpl<F1>( q.w+p.w, q.v+p.v );
}
template<class F1,class F2>
ILINE void operator+=(Quaternion_tpl<F1> &q, const Quaternion_tpl<F2> &p) {
q.w+=p.w; q.v+=p.v;
}
/*!
* subtraction operator
*
* Example:
* Quaternion p(1,0,0,0),q(1,0,0,0);
* Quaternion result=p-q;
*
* Example: (self-subtraction operator)
* Quaternion p(1,0,0,0),q(1,0,0,0);
* Quaternion p-=q;
*
*/
template<class F1,class F2>
ILINE Quaternion_tpl<F1> operator-(const Quaternion_tpl<F1> &q, const Quaternion_tpl<F2> &p) {
return Quaternion_tpl<F1>( q.w-p.w, q.v-p.v);
}
template<class F1,class F2>
ILINE void operator-=(Quaternion_tpl<F1> &q, const Quaternion_tpl<F2> &p) {
q.w-=p.w; q.v-=p.v;
}
//! Scale quaternion free function.
template <typename F1>
ILINE Quaternion_tpl<F1> operator * ( const Quaternion_tpl<F1> &q, f32 t ) {
return Quaternion_tpl<F1>( q.w*t, q.v*t );
};
//! Scale quaternion free function.
template <typename F1>
ILINE Quaternion_tpl<F1> operator *( f32 t, const Quaternion_tpl<F1> &q ) {
return Quaternion_tpl<F1>( t*q.w, t*q.v );
};
/*!
*
* multiplication operator with a Vec3 (3D rotations with quaternions)
*
* Example:
* Quaternion q(1,0,0,0);
* Vec3 v(33,44,55);
* Vec3 result = q*v;
*/
template<class F1,class F2>
ILINE Vec3_tpl<F2> operator*(const Quaternion_tpl<F1> &q, const Vec3_tpl<F2> &v) {
#if !defined(LINUX)
assert((fabs_tpl(1-(q|q)))<0.05); //check if unit-quaternion
#endif
F1 vxvx=q.v.x*q.v.x;
F1 vzvz=q.v.z*q.v.z;
F1 vyvy=q.v.y*q.v.y;
F1 vxvy=q.v.x*q.v.y;
F1 vxvz=q.v.x*q.v.z;
F1 vyvz=q.v.y*q.v.z;
F1 svx=q.w*q.v.x,svy=q.w*q.v.y,svz=q.w*q.v.z;
Vec3_tpl<F2> res;
res.x = v.x*(1-(vyvy+vzvz)*2) + v.y*(vxvy-svz)*2 + v.z*(vxvz+svy)*2;
res.y = v.x*(vxvy+svz)*2 + v.y*(1-(vxvx+vzvz)*2) + v.z*(vyvz-svx)*2;
res.z = v.x*(vxvz-svy)*2 + v.y*(vyvz+svx)*2 + v.z*(1-(vxvx+vyvy)*2);
return res;
}
/*!
* multiplication operator with a Vec3 (3D rotations with quaternions)
*
* Example:
* Quaternion q(1,0,0,0);
* Vec3 v(33,44,55);
* Vec3 result = v*q;
*/
template<class F1,class F2>
ILINE Vec3_tpl<F1> operator*(const Vec3_tpl<F1> &v, const Quaternion_tpl<F2> &q) {
#if !defined(LINUX)
assert((fabs_tpl(1-(q|q)))<0.001); //check if unit-quaternion
#endif
F2 vxvx=q.v.x*q.v.x;
F2 vzvz=q.v.z*q.v.z;
F2 vyvy=q.v.y*q.v.y;
F2 vxvy=q.v.x*q.v.y;
F2 vxvz=q.v.x*q.v.z;
F2 vyvz=q.v.y*q.v.z;
F2 svx=q.w*q.v.x,svy=q.w*q.v.y,svz=q.w*q.v.z;
Vec3_tpl<F1> res;
res.x = v.x*(1-(vyvy+vzvz)*2) + v.y*(vxvy+svz)*2 + v.z*(vxvz-svy)*2;
res.y = v.x*(vxvy-svz)*2 + v.y*(1-(vxvx+vzvz)*2) + v.z*(vyvz+svx)*2;
res.z = v.x*(vxvz+svy)*2 + v.y*(vyvz-svx)*2 + v.z*(1-(vxvx+vyvy)*2);
return res;
}
/*!
*
* invert quaternion.
*
* Example 1:
* Quaternion q=GetRotationXYZ<f32>(Ang3(1,2,3));
* Quaternion result = !q;
*
* Quaternion result = GetInverted(q);
*
* q.Invert();
*
*/
template<class F> ILINE Quaternion_tpl<F> Quaternion_tpl<F>::operator ! () const {
#if !defined(LINUX)
assert((fabs_tpl(1-(*this|*this)))<0.001); //check if unit-quaternion
#endif
return Quaternion_tpl(w,-v);
}
template<class F> ILINE void Quaternion_tpl<F>::Invert( void ) { *this=!*this; }
template<class F> ILINE Quaternion_tpl<F> Quaternion_tpl<F>::GetInverted(Quaternion_tpl<F>& q) { return !q; }
template<class F> ILINE Quaternion_tpl<F> GetInverted(Quaternion_tpl<F>& q) { return !q; }
/*!
*
* Create rotation-quaternion around an arbitrary axis (=CVector).
* This is an implemetation of "Eulers Theorem". the axis is assumed to be nomalised.
*
* Example:
* Quaternion_tpl<f32> q=GetRotationAA( 2.14255f, GetNormalized(Vec3(1,2,3)) );
* q.SetRotationAA( 2.14255f, GetNormalized(Vec3(1,2,3)) );
*/
template<class F>
ILINE void Quaternion_tpl<F>::SetRotationAA(F rad, const Vec3_tpl<F> &axis) { F cs[2]; sincos_tpl( rad*(F)0.5, cs); SetRotationAA(cs[0],cs[1], axis); }
template<class F>
ILINE Quaternion_tpl<F> Quaternion_tpl<F>::GetRotationAA(F rad, const Vec3_tpl<F> &axis) { Quaternion_tpl<F> q; q.SetRotationAA(rad,axis); return q; }
template<class F>
ILINE Quaternion_tpl<F> GetRotationAA(F rad, const Vec3_tpl<F> &axis) { Quaternion_tpl<F> q; q.SetRotationAA(rad,axis); return q; }
template<class F>ILINE void Quaternion_tpl<F>::SetRotationAA(F cosha, F sinha, const Vec3_tpl<F> &axis) {
#if !defined(LINUX)
assert((fabs_tpl(1-(axis|axis)))<0.001); //check if unit-vector
#endif
w=cosha; v=axis*sinha;
}
template<class F>
ILINE Quaternion_tpl<F> Quaternion_tpl<F>::GetRotationAA(F cosha, F sinha, const Vec3_tpl<F> &axis) { Quaternion_tpl<F> q; q.SetRotationAA(cosha,sinha,axis); return q; }
template<class F>
ILINE Quaternion_tpl<F> GetRotationAA(F cosha, F sinha, const Vec3_tpl<F> &axis) { Quaternion_tpl<F> q; q.SetRotationAA(cosha,sinha,axis); return q; }
/*!
*
* Create rotation-quaternion that rotates from one vector to another.
* Both vectors are assumed to be nomalised.
*
* Example:
* Quaternion_tpl<f32> q=GetRotationV0V1( GetNormalized(Vec3(3,1,7)), GetNormalized(Vec3(1,2,3)) );
* q.SetRotationV0V1( GetNormalized(Vec3(3,1,7)), GetNormalized(Vec3(1,2,3)) );
*/
template<class F>
void Quaternion_tpl<F>::SetRotationV0V1(const Vec3_tpl<F>& v0, const Vec3_tpl<F>& v1)
{
#if !defined(LINUX)
assert((fabs_tpl(1-(v0|v0)))<0.001); //check if unit-vector
assert((fabs_tpl(1-(v1|v1)))<0.001); //check if unit-vector
#endif
w=sqrt_tpl(max((F)0.0,(1+v0*v1)*(F)0.5));
if (w>0.001) {
v=v0^v1; v*=(F)0.5/w;
} else {
//v=v0.orthogonal().normalized(); w=0;
v=GetOrthogonal(v0).normalized(); w=0;
}
}
template<class F>
ILINE Quaternion_tpl<F> Quaternion_tpl<F>::GetRotationV0V1(const Vec3_tpl<F>& v0, const Vec3_tpl<F>& v1) { Quaternion_tpl<F> q; q.SetRotationV0V1(v0,v1); return q; }
template<class F>
ILINE Quaternion_tpl<F> GetRotationV0V1(const Vec3_tpl<F>& v0, const Vec3_tpl<F>& v1) { Quaternion_tpl<F> q; q.SetRotationV0V1(v0,v1); return q; }
/*!
*
* Create rotation-quaternion that around the fixed coordinate axes.
*
* Example:
* Quaternion_tpl<f32> q=GetRotationXYZ( Ang3(1,2,3) );
* q.SetRotationXYZ( Ang3(1,2,3) );
*/
template<class F>
ILINE void Quaternion_tpl<F>::SetRotationXYZ(const Ang3 &a) {
F csx[2]; sincos_tpl( a.x*(F)0.5, csx);
F csy[2]; sincos_tpl( a.y*(F)0.5, csy);
F csz[2]; sincos_tpl( a.z*(F)0.5, csz);
w = cx*cy*cz + sx*sy*sz;
v.x = cz*cy*sx - sz*sy*cx;
v.y = cz*sy*cx + sz*cy*sx;
v.z = sz*cy*cx - cz*sy*sx;
}
template<class F>
ILINE Quaternion_tpl<F> Quaternion_tpl<F>::GetRotationXYZ(const Ang3 &a) { Quaternion_tpl<F> q; q.SetRotationXYZ(a); return q; }
template<class F>
ILINE Quaternion_tpl<F> GetRotationXYZ(const Ang3 &a) { Quaternion_tpl<F> q; q.SetRotationXYZ(a); return q; }
/*!
* set identity quaternion
*
* Example:
* Quaternion q;
* q.Identity();
*/
template <class F>
ILINE void Quaternion_tpl<F>::SetIdentity(void) { w=1; v.x=0, v.y=0; v.z=0; }
template <class F>
ILINE Quaternion_tpl<F> Quaternion_tpl<F>::GetIdentity(void) { return Quaternion_tpl(1,0,0,0); }
template <class F>
ILINE Quaternion_tpl<F> GetIdentity(void) { return Quaternion_tpl<F>(1,0,0,0); }
/*!
* normalize quaternion.
*
* Example 1:
* Quaternion q;
* q.Normalize();
*
* Example 2:
* Quaternion q;
* Quaternion qn=GetNormalized( q );
*
*/
template <class F>
ILINE void Quaternion_tpl<F>::Normalize(void) {
#if !defined(LINUX)
assert((*this|*this)>0.00001f);
#endif
F d = GetLength(*this);
d=(F)1/d; w*=d; v*=d;
}
template <class F>
ILINE Quaternion_tpl<F> Quaternion_tpl<F>::GetNormalized( const Quaternion_tpl<F> &q ) { Quaternion_tpl<F> t=q; t.Normalize(); return t; }
template <class F>
ILINE Quaternion_tpl<F> GetNormalized( const Quaternion_tpl<F> &q ) { Quaternion_tpl<F> t=q; t.Normalize(); return t; }
/*!
* get length of quaternion.
*
* Example 1:
* f32 l=GetLength(q);
*
*/
template <class F>
ILINE F Quaternion_tpl<F>::GetLength( const Quaternion_tpl<F>& q ) { return sqrt_tpl(q|q); }
template <class F>
ILINE F GetLength( const Quaternion_tpl<F>& q ) { return sqrt_tpl(q|q); }
/*!
*
* linear-interpolation between quaternions (lerp)
*
* Example:
* CQuaternion result,p,q;
* result=qlerp( p, q, 0.5f );
*
*/
template<class F>
ILINE Quaternion_tpl<F> qlerp( const Quaternion_tpl<F> &p, const Quaternion_tpl<F> &q, f32 t ) {
#if !defined(LINUX)
assert((fabs_tpl(1-(p|p)))<0.001); //check if unit-quaternion
assert((fabs_tpl(1-(q|q)))<0.001); //check if unit-quaternion
#endif
return p*(1.0f-t) + q*t;
}
/*!
*
* spherical-interpolation between quaternions (geometrical slerp)
*
* Example:
* Quaternion_tpl<f32> result,p,q;
* result=qslerp_g( p, q, 0.5f );
*
*/
template<class F>
ILINE Quaternion_tpl<F> Slerp( const Quaternion_tpl<F> &p, const Quaternion_tpl<F> &tq, f32 t ) {
#if !defined(LINUX)
assert((fabs_tpl(1-(p|p)))<0.001); //check if unit-quaternion
assert((fabs_tpl(1-(tq|tq)))<0.001); //check if unit-quaternion
#endif
Quaternion_tpl<F> q=tq;
// calculate cosine using the "inner product" between two quaternions: p*q=cos(radiant)
f32 cosine = (p|q);
// Problem 1: given any two quaternions, there exist two possible arcs, along which one can move.
// One of them goes around the long way and this is the one that we wish to avoid.
if( cosine < 0.0 ) { cosine=-cosine; q=-q; }
//Problem 2: we explore the special cases where the both quaternions are very close together,
//in which case we approximate using the more economical LERP and avoid "divisions by zero" since sin(Angle) = 0 as Angle=0
if(cosine>=0.999f) {
return qlerp(p,q,t);
} else {
//perform qslerp_g: because of the "qlerp"-check above, a "division by zero" is not possible
f32 angle = cry_acosf(cosine);
f32 isine = 1.0f/sin_tpl(angle);
f32 scale_0 = sin_tpl((1.0f - t) * angle);
f32 scale_1 = sin_tpl(t * angle);
return (p*scale_0 + q*scale_1) * isine;
}
}
//! Spherical linear interpolation of quaternions.
//! @param a Source quaternion.
//! @param b Target quaternion.
//! @param t Interpolation time.
//! Spherical linear interpolation of quaternions.
/*template <class F>
ILINE Quaternion_tpl<F> Slerp(const Quaternion_tpl<F>& a, const Quaternion_tpl<F>& b, f32 t )
{
assert((fabs_tpl(1-(a|a)))<0.001); //check if unit-quaternion
assert((fabs_tpl(1-(b|b)))<0.001); //check if unit-quaternion
Quaternion_tpl<F> q;
f32 f1,f2; // interpolation coefficions.
f32 angle; // angle between A and B
f32 oosin_a, cos_a; // sine, cosine of angle
Quaternion_tpl<F> to;
cos_a = a|b;
if (cos_a < 0) {
cos_a = -cos_a; //????????
to = -b;
} else {
to = b;
}
if (1.0f - fabs(cos_a) < 0.001f) {
f1 = 1.0f - t;
f2 = t;
} else { // normal case
angle = (f32)acos(cos_a);
oosin_a = 1.0f / (f32)sin(angle);
f1 = (f32)sin( (1.0f - t)*angle ) * oosin_a;
f2 = (f32)sin( t*angle ) * oosin_a;
}
q.w = f1*a.w + f2*to.w;
q.v = f1*a.v + f2*to.v;
return q;
}*/
//! squad(p,a,b,q,t) = slerp( slerp(p,q,t),slerp(a,b,t), 2(1-t)t).
template <class F>
ILINE Quaternion_tpl<F> Squad( const Quaternion_tpl<F> p,const Quaternion_tpl<F> a,const Quaternion_tpl<F> b,const Quaternion_tpl<F> q,f32 t )
{
f32 k = 2.0f * (1.0f - t)*t;
//return long_slerp( long_slerp(p,q,t),long_slerp(a,b,t), k );
return Slerp( Slerp(p,q,t),Slerp(a,b,t), k );
}
//! Quaternion interpolation for angles > 2PI.
template <class F>
ILINE Quaternion_tpl<F> SquadRev( f32 angle, // angle of rotation
const Vec3& axis, // the axis of rotation
const Quaternion_tpl<F>& p, // start quaternion
const Quaternion_tpl<F>& a, // start tangent quaternion
const Quaternion_tpl<F>& b, // end tangent quaternion
const Quaternion_tpl<F>& q, // end quaternion
f32 t ) // Time parameter, in range [0,1]
{
f32 s,v;
f32 omega = 0.5f*angle;
f32 nrevs = 0;
Quaternion_tpl<F> r,pp,qq;
if (omega < (gf_PI - 0.00001f)) {
return Squad( p,a,b,q,t );
}
while (omega > (gf_PI - 0.00001f)) {
omega -= gf_PI;
nrevs += 1.0f;
}
if (omega < 0) omega = 0;
s = t*angle/gf_PI; // 2t(omega+Npi)/pi
if (s < 1.0f) {
pp = p*Quaternion_tpl<f32>(0.0f,axis);//pp = p.Orthog( axis );
r = Squad(p,a,pp,pp,s); // in first 90 degrees.
} else {
v = s + 1.0f - 2.0f*(nrevs+(omega/gf_PI));
if (v <= 0.0f) {
// middle part, on great circle(p,q).
while (s >= 2.0f) s -= 2.0f;
pp = p*Quaternion_tpl<f32>(0.0f,axis);//pp = p.Orthog(axis);
r = Slerp(p,pp,s);
} else {
// in last 90 degrees.
qq = -q*Quaternion_tpl<f32>(0.0f,axis);
r = Squad(qq,qq,b,q,v);
}
}
return r;
}
// Exponent of Quaternion.
template <class F>
ILINE Quaternion_tpl<F> exp(const Quaternion_tpl<F>& q) {
double d = sqrt( double(q.v.x*q.v.x + q.v.y*q.v.y + q.v.z*q.v.z) );
if (d > 1e-4) {
double m = sin(d)/d;
return Quaternion_tpl<F>( (F)cos(d),F(q.v.x*m),F(q.v.y*m),F(q.v.z*m));
} else return Quaternion_tpl<F> (F(1-d*d), F(q.v.x), F(q.v.y), F(q.v.z) ); // cos(d) ~= 1-d^2 when d->0
}
// logarithm of a quaternion, imaginary part (the real part of the logarithm is always 0)
template <class F>
ILINE Quaternion_tpl<F> log (const Quaternion_tpl<F>& q) {
#if !defined(LINUX)
assert((fabs_tpl(1-(q|q)))<0.01); //check if unit-quaternion
#endif
double d = sqrt( double(q.v.x*q.v.x + q.v.y*q.v.y + q.v.z*q.v.z ));
if (d > 1e-7) {
d = atan2 ( d, (double)q.w ) / d;
return Quaternion_tpl<F>(0, F(q.v.x*d),F(q.v.y*d), F(q.v.z*d) );
} else return Quaternion_tpl<F>(0,0,0,0);
}
//////////////////////////////////////////////////////////////////////////
//! Logarithm of Quaternion difference.
template <class F>
ILINE Quaternion_tpl<F> LnDif( const Quaternion_tpl<F> &q1,const Quaternion_tpl<F> &q2 ){
#if !defined(LINUX)
assert((fabs_tpl(1-(q1|q1)))<0.001); //check if unit-quaternion
assert((fabs_tpl(1-(q2|q2)))<0.001); //check if unit-quaternion
#endif
return log(q2/q1);
//Quaternion_tpl<F> r = q2/q1;
//return log(r);
}
/*
//! Compute a, the term used in Boehm-type interpolation.
//! a[n] = q[n]* qexp(-(1/4)*( ln(qinv(q[n])*q[n+1]) +ln( qinv(q[n])*q[n-1] )))
template <class F>
ILINE Quaternion_tpl<F> CompQuatA( const Quaternion_tpl<F>& qprev,const Quaternion_tpl<F>& q,const Quaternion_tpl<F>& qnext ) {
Quaternion_tpl<F> qm,qp,r;
qm = LnDif( q,qprev );
qp = LnDif( q,qnext );
r = (-0.25f)*(Quaternion_tpl<F>(qm.v.x+qp.v.x,qm.v.y+qp.v.y,qm.v.z+qp.v.z,qm.w+qp.w));
return q*r.Exp();
}*/
/*!
*
* spherical-interpolation between quaternions (algebraic slerp_a)
* I have included this function just for the sake of completeness, because
* its the only useful application to check if exp & log really work.
* Both slerp-functions are returning the same result.
*
* Example:
* Quaternion result,p,q;
* result=qslerp_a( p, q, 0.5f );
*
*/
template<class F>
ILINE Quaternion_tpl<F> qslerp_a( const Quaternion_tpl<F> &p, const Quaternion_tpl<F> &tq, F t ) {
#if !defined(LINUX)
assert((fabs_tpl(1-(p|p)))<0.001); //check if unit-quaternion
assert((fabs_tpl(1-(tq|tq)))<0.001); //check if unit-quaternion
#endif
Quaternion_tpl<F> q=tq;
// calculate cosine using the "inner product" between two quaternions: p*q=cos(radiant)
f32 cosine = (p|q);
// Problem: given any two quaternions, there exist two possible arcs, along which one can move.
// One of them goes around the long way and this is the one that we wish to avoid.
if( cosine < 0.0 ) { cosine=-cosine; q=-q; }
//perform qslerp_a:
return exp( (log (p* !q)) * (1-t)) * q; //algebraic slerp (1)
//...and some more slerp-functions producing all the same result
//return p * exp( (log (invert(p)*q)) * t); //algebraic slerp (2)
//return exp( (log (q*invert(p))) * t) * p; //algebraic slerp (3)
//return q * exp( (log (invert(q)*p)) * (1-t)); //algebraic slerp (4)
}
/*!
*
* quaternion copy constructor; Quaternion q=mat33
* We take only the rotation of the 3x3 part
*
* Example 1:
* \code
* Matrix33 mat33;
* mat33.rotationXYZ33(0.5f, 2.5f, 1.5f);
* Quaternion q=mat33;
* \endcode
*
* Example 2:
* \code
* CMatrix34 mat34;
* mat34.rotationXYZ34(0.5f, 2.5f, 1.5f);
* Quaternion q=Matrix33(mat34);
* \endcode
*/
template<class F,int SI,int SJ>
inline Quaternion_tpl<F> GetQuatFromMat33(const Matrix33_tpl<F,SI,SJ>& m) {
Quaternion_tpl<f32> q;
//check if we have an orthonormal-base (assuming we are using a right-handed coordinate system)
//assert removed by ivo: it was impossible to load a level bacause of this asser!
//but be warned, if you convert a non-uniform-scaled matrix into a quaternion
//you get a worthless bullshit-quaternion!
//vlad: still impossible to load
//assert( IsEquivalent(m.GetOrtX(),m.GetOrtY()%m.GetOrtZ(),0.1f) );
//assert( IsEquivalent(m.GetOrtY(),m.GetOrtZ()%m.GetOrtX(),0.1f) );
//assert( IsEquivalent(m.GetOrtZ(),m.GetOrtX()%m.GetOrtY(),0.1f) );
F tr,s,p;
tr = m.M00 + m.M11 + m.M22;
//check the diagonal
if(tr > 0.0) {
s=sqrt_tpl(tr+1.0f); p=0.5f/s;
q.w=s*0.5f; q.v((m.M21-m.M12)*p,(m.M02-m.M20)*p,(m.M10-m.M01)*p); return q;
}
//diagonal is negativ. now we have to find the biggest element on the diagonal
//check if "m00" is the biggest element
if ( (m.M00>=m.M11) && (m.M00>=m.M22) ) {
s=p=sqrt_tpl(m.M00-m.M11-m.M22+1.0f); if (s) { p=0.5f/s; }
q.w=(m.M21-m.M12)*p; q.v(s*0.5f,(m.M10+m.M01)*p,(m.M20+m.M02)*p); return q;
}
//check if "m11" is the biggest element
if ( (m.M11>=m.M00) && (m.M11>=m.M22) ) {
s=p=sqrt_tpl(m.M11-m.M22-m.M00+1.0f); if (s) { p=0.5f/s; }
q.w=(m.M02-m.M20)*p; q.v((m.M01+m.M10)*p,s*0.5f,(m.M21+m.M12)*p); return q;
}
//check if "m22" is the biggest element
if ( (m.M22>=m.M00) && (m.M22>=m.M11) ) {
s=p=sqrt_tpl(m.M22-m.M00-m.M11+1.0f); if (s) { p=0.5f/s; }
q.w=(m.M10-m.M01)*p; q.v((m.M02+m.M20)*p,(m.M12+m.M21)*p,s*0.5f); return q;
}
#if !defined(LINUX)
assert(0);
#endif
return q;//if it ends here, then we have no valid rotation matrix
}
#endif // _Quaternion_tpl_H

126
CryCommon/Cry_Vector2.h Normal file
View File

@@ -0,0 +1,126 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Common Source code
//
// File:Cry_Vector2.h
// Description: Common matrix class
//
// History:
// -Feb 27,2003: Created by Ivo Herzeg
//
//////////////////////////////////////////////////////////////////////
#ifndef CRYTEK_CRYVECTOR2_H
#define CRYTEK_CRYVECTOR2_H
#include "platform.h"
#include "Cry_Vector3.h"
template <class frype> struct Vec2_tpl;
typedef Vec2_tpl<float> Vec2;
typedef Vec2_tpl<real> Vec2_f64;
typedef Vec2_tpl<float> vector2f;
#if defined(LINUX64)
typedef Vec2_tpl<int> vector2l;
#else
typedef Vec2_tpl<long> vector2l;
#endif
typedef Vec2_tpl<float> vector2df;
typedef Vec2_tpl<real> vector2d;
typedef Vec2_tpl<int> vector2di;
typedef Vec2_tpl<unsigned int> vector2dui;
template<class F> struct Vec2_tpl {
F x,y;
Vec2_tpl() {}
Vec2_tpl(F _x,F _y) { x=_x;y=_y; }
Vec2_tpl(const Vec2_tpl<F> &src) { x=src.x;y=src.y; }
Vec2_tpl& set(F nx,F ny) { x=nx;y=ny; return *this; }
template<class F1> Vec2_tpl(const Vec2_tpl<F1> &src) { x=src.x;y=src.y; }
template<class F1> explicit Vec2_tpl(const Vec3_tpl<F1> &src) { x=src.x;y=src.y; }
template<class F1> explicit Vec2_tpl(const F1 *psrc) { x=psrc[0]; y=psrc[1]; }
Vec2_tpl& operator=(const Vec2_tpl<F>& src) { x=src.x;y=src.y; return *this; }
template<class F1> Vec2_tpl& operator=(const Vec2_tpl<F1>& src) { x=src.x;y=src.y; return *this; }
template<class F1> Vec2_tpl& operator=(const Vec3_tpl<F1>& src) { x=src.x;y=src.y; return *this; }
int operator!() const { return x==0 && y==0; }
Vec2_tpl& normalize() { F rlen=sqrt_tpl(x*x+y*y); if (rlen>0) { rlen=(F)1.0/rlen; x*=rlen;y*=rlen; } return *this; }
Vec2_tpl normalized() const {
F rlen=sqrt_tpl(x*x+y*y); if (rlen>0) { rlen=(F)1.0/rlen; return Vec2_tpl<F>(x*rlen,y*rlen); }
return Vec2_tpl<F>(1,0);
}
F len() const { return sqrt_tpl(x*x+y*y); }
F len2() const { return x*x+y*y; }
F area() const { return x*y; }
F& operator[](int idx) { return *((F*)&x+idx); }
F operator[](int idx) const { return *((F*)&x+idx); }
operator F*() { return &x; }
Vec2_tpl& flip() { x=-x;y=-y; return *this; }
Vec2_tpl& zero() { x=y=0; return *this; }
Vec2_tpl rot90ccw() { return Vec2_tpl(-y,x); }
Vec2_tpl rot90cw() { return Vec2_tpl(y,-x); }
#ifdef quotient_h
quotient_tpl<F> fake_atan2() const {
quotient_tpl<F> res;
int quad = -(signnz(x*x-y*y)-1>>1); // hope the optimizer will remove complement shifts and adds
if (quad) { res.x=-y; res.y=x; }
else { res.x=x; res.y=y; }
int sgny = signnz(res.y); quad |= 1-sgny; //(res.y<0)<<1;
res.x *= sgny; res.y *= sgny;
res += 1+(quad<<1);
return res;
}
#endif
F atan2() const { return atan2_tpl(y,x); }
Vec2_tpl operator-() const { return Vec2_tpl(-x,-y); }
Vec2_tpl operator*(F k) const { return Vec2_tpl(x*k,y*k); }
Vec2_tpl& operator*=(F k) { x*=k;y*=k; return *this; }
Vec2_tpl operator/(F k) const { return *this*((F)1.0/k); }
Vec2_tpl& operator/=(F k) { return *this*=((F)1.0/k); }
};
template<class F1,class F2>
F1 operator*(const Vec2_tpl<F1> &op1, const Vec2_tpl<F2>& op2) { return op1.x*op2.x+op1.y*op2.y; } // dot product
template<class F1,class F2>
F1 operator^(const Vec2_tpl<F1> &op1, const Vec2_tpl<F2>& op2) { return op1.x*op2.y-op1.y*op2.x; } // cross product
template<class F1,class F2>
Vec2_tpl<F1> operator+(const Vec2_tpl<F1> &op1, const Vec2_tpl<F2> &op2) {
return Vec2_tpl<F1>(op1.x+op2.x,op1.y+op2.y);
}
template<class F1,class F2>
Vec2_tpl<F1> operator-(const Vec2_tpl<F1> &op1, const Vec2_tpl<F2> &op2) {
return Vec2_tpl<F1>(op1.x-op2.x,op1.y-op2.y);
}
template<class F1,class F2>
Vec2_tpl<F1>& operator+=(Vec2_tpl<F1> &op1, const Vec2_tpl<F2> &op2) {
op1.x+=op2.x;op1.y+=op2.y; return op1;
}
template<class F1,class F2>
Vec2_tpl<F1>& operator-=(Vec2_tpl<F1> &op1, const Vec2_tpl<F2> &op2) {
op1.x-=op2.x;op1.y-=op2.y; return op1;
}
#endif // CRYTEK_CRYVECTOR2_H

805
CryCommon/Cry_Vector3.h Normal file
View File

@@ -0,0 +1,805 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Common Source code
//
// File: Cry_Vector3.h
// Description: Common vector class
//
// History:
// -Feb 27,2003: Created by Ivo Herzeg
//
//////////////////////////////////////////////////////////////////////
#ifndef VECTOR_H
#define VECTOR_H
#if _MSC_VER > 1000
# pragma once
#endif
#include "platform.h"
#include <math.h>
#include "Cry_Matrix.h"
enum type_zero { zero };
enum type_min { MIN };
enum type_max { MAX };
extern const float gf_PI;
#define VEC_EPSILON ( 0.01f )
#define DEG2RAD( a ) ( (a) * (gf_PI/180.0f) )
#define RAD2DEG( a ) ( (a) * (180.0f/gf_PI) )
#if defined(LINUX)
template <class F> struct Vec3_tpl;
template<class F>
F GetLengthSquared( const Vec3_tpl<F> &v );
template<class F>
F GetLength( const Vec3_tpl<F>& v );
#endif
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// class Vec3_tpl
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
template <class F> struct Vec3_tpl
{
public:
F x,y,z;
Vec3_tpl() {};
Vec3_tpl(type_zero) { x=y=z=0; }
Vec3_tpl(type_min) { x=y=z=-100; }
Vec3_tpl(type_max) { x=y=z=100; }
Vec3_tpl( const F vx, const F vy, const F vz ) { x=vx; y=vy; z=vz; };
//bracket operator
void operator () ( const F vx,const F vy,const F vz ) { x=vx; y=vy; z=vz; };
//f32* fptr=vec;
operator F* () { return (F*)this; }
//f32 farray[3]={1,2,3};
//Vec3 v=Vec3(farray);
//
//f32* fptr;
//Vec3 newv=Vec3(fptr);
//
//Matrix44 tm=GetTranslationMat(Vec3(44,55,66));
//Vec3 tvec=Vec3(tm[3]); //really dangerous! Should be replaced by "GetTranslation(tm)"
template <class T>
explicit Vec3_tpl(const T *src) { x=src[0]; y=src[1]; z=src[2]; }
//CONSTRUCTOR: implement the copy/casting/assignement constructor:
template <class T>
ILINE Vec3_tpl( const Vec3_tpl<T>& v ) { x=(F)v.x; y=(F)v.y; z=(F)v.z; }
//overload = operator to copy f64=doube or f32=f32
//Vec3_tpl<f32>=Vec3_tpl<f32>
//Vec3_tpl<f64>=Vec3_tpl<f64>
template <class T>
ILINE Vec3_tpl& operator=(const Vec3_tpl<T> &v) { x=v.x; y=v.y; z=v.z; return *this; }
ILINE F &operator [] (int index) { assert(index>=0 && index<=2); return ((F*)this)[index]; }
ILINE F operator [] (int index) const { assert(index>=0 && index<=2); return ((F*)this)[index]; }
////////////////////////////////////////////////////////////////
//overloaded arithmetic operators
////////////////////////////////////////////////////////////////
//three methods for a "dot-product" operation
ILINE F Dot (const Vec3_tpl<F> &vec2) const { return x*vec2.x + y*vec2.y + z*vec2.z; }
//two methods for a "cross-product" operation
ILINE Vec3_tpl<F> Cross (const Vec3_tpl<F> &vec2) const { return Vec3_tpl<F>( y*vec2.z - z*vec2.y, z*vec2.x - x*vec2.z, x*vec2.y - y*vec2.x); }
ILINE Vec3_tpl<F> operator*(F k) const { return Vec3_tpl<F>(x*k,y*k,z*k); }
ILINE Vec3_tpl<F> operator/(F k) const { k=(F)1.0/k; return Vec3_tpl<F>(x*k,y*k,z*k); }
ILINE friend Vec3_tpl operator * (f32 f, const Vec3_tpl &vec) { return Vec3_tpl(f*vec.x, f*vec.y, f*vec.z); }
ILINE Vec3_tpl<F>& operator *= (F k) { x*=k;y*=k;z*=k; return *this; }
ILINE Vec3_tpl<F>& operator /= (F k) { k=(F)1.0/k; x*=k;y*=k;z*=k; return *this; }
//flip vector
ILINE Vec3_tpl<F> operator - ( void ) const { return Vec3_tpl<F>(-x,-y,-z); }
// ILINE Vec3_tpl& Negate() { x=-x; y=-y; z=-z; return *this; }
ILINE Vec3_tpl& Flip() { x=-x; y=-y; z=-z; return *this; }
ILINE Vec3_tpl& flip() { x=-x; y=-y; z=-z; return *this; }
ILINE friend bool operator ==(const Vec3_tpl<F> &v0, const Vec3_tpl<F> &v1) {
return ((v0.x==v1.x) && (v0.y==v1.y) && (v0.z==v1.z));
}
ILINE friend bool operator !=(const Vec3_tpl<F> &v0, const Vec3_tpl<F> &v1) {
return !(v0==v1);
}
ILINE friend bool IsEquivalent(const Vec3_tpl<F>& v0, const Vec3_tpl<F>& v1, f32 epsilon ) {
return ((fabs_tpl(v0.x-v1.x) <= epsilon) && (fabs_tpl(v0.y-v1.y) <= epsilon)&& (fabs_tpl(v0.z-v1.z) <= epsilon));
}
ILINE friend bool IsEquivalent(const Vec3_tpl<F>& v0, const Vec3_tpl<F>& v1 ) {
return( IsEquivalent( v0, v1, VEC_EPSILON ) );
}
ILINE bool IsZero() const { return x == 0 && y == 0 && z == 0; }
////////////////////////////////////////////////////////////////
//common methods
////////////////////////////////////////////////////////////////
ILINE Vec3_tpl& zero() { x=y=z=0; return *this; }
ILINE Vec3_tpl<F>& Set(const F xval,const F yval, const F zval) { x=xval; y=yval; z=zval; return *this; }
//! calcultae the length of the vector
ILINE F Length() const { return sqrt_tpl(x*x+y*y+z*z); }
ILINE F GetLength() const { return sqrt_tpl(x*x+y*y+z*z); }
ILINE F len() const { return sqrt_tpl(x*x+y*y+z*z); }
//! calcultae the squared length of the vector
ILINE F GetLengthSquared() const { return x*x+y*y+z*z; }
ILINE F len2() const { return x*x +y*y + z*z; }
//! normalize the vector and return the inverted length if successfull
ILINE f32 Normalize() {
f32 fLen = (f32)GetLength();
//assert(fLen>0.0f);
if (fLen<0.00001f) return(0); //no good idea! not everybody will check this
f32 fInvLen=1.0f/fLen;
x*=fInvLen; y*=fInvLen; z*=fInvLen;
return fInvLen;
}
//! return a normalized vector
ILINE friend Vec3_tpl<F> GetNormalized( const Vec3_tpl<F> &v ) {
F vlength = ::GetLength(v);
assert(vlength>0.0f);
F ivlength=1.0f/vlength;
return (v*ivlength);
}
ILINE Vec3_tpl& normalize() {
F rlen=sqrt_tpl(x*x+y*y+z*z);
//assert(rlen>0.00001f);
if (rlen>0) { rlen=(F)1.0/rlen; x*=rlen;y*=rlen;z*=rlen; }
else Set(0,0,1); return *this;
}
ILINE Vec3_tpl normalized() const {
F rlen=sqrt_tpl(x*x+y*y+z*z);
//assert(rlen>0.00001f);
if (rlen>0) { rlen=(F)1.0/rlen; return Vec3_tpl(x*rlen,y*rlen,z*rlen); }
else return Vec3_tpl(0,0,1);
}
ILINE Vec3_tpl GetNormalized() const { return normalized(); } // vlad: all get functions should begin from Get...
ILINE f32 NormalizeFast() {
f32 fLen = x*x + y*y + z*z;
//assert(fLen>0.00001f);
unsigned int *n1 = (unsigned int *)&fLen;
unsigned int n = 0x5f3759df - (*n1 >> 1);
f32 *n2 = (f32 *)&n;
fLen = (1.5f - (fLen * 0.5f) * *n2 * *n2) * *n2;
x*=fLen; y*=fLen; z*=fLen;
return fLen;
}
ILINE friend F GetSquaredDistance(const Vec3_tpl<F> &vec1, const Vec3_tpl<F> &vec2) {
return (vec2.x-vec1.x)*(vec2.x-vec1.x)+(vec2.y-vec1.y)*(vec2.y-vec1.y)+(vec2.z-vec1.z)*(vec2.z-vec1.z);
}
ILINE friend F GetDistance(const Vec3_tpl<F> &vec1, const Vec3_tpl<F> &vec2) {
return sqrt_tpl((vec2.x-vec1.x)*(vec2.x-vec1.x)+(vec2.y-vec1.y)*(vec2.y-vec1.y)+(vec2.z-vec1.z)*(vec2.z-vec1.z));
}
ILINE F GetDistance(const Vec3_tpl<F> vec1) const {
return sqrt_tpl((x-vec1.x)*(x-vec1.x)+(y-vec1.y)*(y-vec1.y)+(z-vec1.z)*(z-vec1.z));
}
//! force vector length by normalizing it
//! 08/26/2002 optimized a little by M.M.
ILINE void SetLen(const f32 fLen) {
f32 fLenMe = GetLengthSquared();
if(fLenMe<0.00001f*0.00001f)return;
fLenMe=fLen/(f32)sqrt((f64)fLenMe);
x*=fLenMe; y*=fLenMe; z*=fLenMe;
}
// permutate coordinates so that z goes to new_z slot
ILINE Vec3_tpl permutated(int new_z) const { return Vec3_tpl(*(&x+inc_mod3[new_z]), *(&x+dec_mod3[new_z]), *(&x+new_z)); }
// returns volume of a box with this vector as diagonal
ILINE F volume() const { return x*y*z; }
// returns a vector orthogonal to this one
ILINE Vec3_tpl orthogonal() const {
int i = isneg(square((F)0.9)*GetLengthSquared()-x*x);
Vec3_tpl<F> res;
res[i]=0; res[incm3(i)]=(*this)[decm3(i)]; res[decm3(i)]=-(*this)[incm3(i)];
return res;
}
// returns a vector orthogonal to this one
ILINE void SetOrthogonal( const Vec3_tpl<F>& v ) {
int i = isneg(square((F)0.9)*v.GetLengthSquared()-v.x*v.x);
(*this)[i]=0; (*this)[incm3(i)]= v[decm3(i)]; (*this)[decm3(i)]=-v[incm3(i)];
}
// returns a vector that consists of absolute values of this one's coordinates
ILINE Vec3_tpl abs() const { return Vec3_tpl(fabs_tpl(x),fabs_tpl(y),fabs_tpl(z)); }
//! check for min bounds
ILINE void CheckMin(const Vec3_tpl &other) {
if (other.x<x) x=other.x;
if (other.y<y) y=other.y;
if (other.z<z) z=other.z;
}
//! check for max bounds
ILINE void CheckMax(const Vec3_tpl &other) {
if (other.x>x) x=other.x;
if (other.y>y) y=other.y;
if (other.z>z) z=other.z;
}
//this is a special case for CAngleAxis
ILINE Vec3_tpl rotated(const Vec3_tpl &axis, F angle) const {
return rotated(axis,cos_tpl(angle),sin_tpl(angle));
}
ILINE Vec3_tpl rotated(const Vec3_tpl &axis, F cosa,F sina) const {
Vec3_tpl zax = axis*(*this*axis);
Vec3_tpl xax = *this-zax;
Vec3_tpl yax = axis^xax;
return xax*cosa + yax*sina + zax;
}
ILINE Vec3_tpl rotated(const Vec3_tpl &center,const Vec3_tpl &axis, F cosa,F sina) const {
return center+(*this-center).rotated(axis,cosa,sina);
}
ILINE Vec3_tpl rotated(const Vec3_tpl &center,const Vec3_tpl &axis, F angle) const {
return center+(*this-center).rotated(axis,angle);
}
//! set random normalized vector (=random position on unit sphere)
void SetRandomDirection( void )
{
F Length2;
do{
x=( (F)rand() )/RAND_MAX*2-1;
y=( (F)rand() )/RAND_MAX*2-1;
z=( (F)rand() )/RAND_MAX*2-1;
Length2=len2();
} while(Length2>1.0f || Length2<0.0001f);
F InvScale=1/sqrt_tpl(Length2); // dividion by 0 is prevented
x*=InvScale;y*=InvScale;z*=InvScale;
}
/*!
* Project a point/vector on a (virtual) plane
* Consider we have a plane going through the origin.
* Because d=0 we need just the normal. The vector n is assumed to be a unit-vector.
*
* Example:
* Vec3 result=Vec3::CreateProjection( incident, normal );
*/
ILINE static Vec3_tpl CreateProjection( const Vec3_tpl& i, const Vec3_tpl& n ) { return i - n*(n|i); }
/*!
* Calculate a reflection vector. Vec3 n is assumed to be a unit-vector.
*
* Example:
* Vec3 result=Vec3::CreateReflection( incident, normal );
*/
ILINE static Vec3_tpl CreateReflection( const Vec3_tpl& i, const Vec3_tpl &n ) { return (n*(i|n)*2)-i; }
};
///////////////////////////////////////////////////////////////////////////////
// Typedefs //
///////////////////////////////////////////////////////////////////////////////
typedef Vec3_tpl<f32> Vec3; //we will use only this throughout the project
typedef Vec3_tpl<real> Vec3_f64;
typedef Vec3 Vec3d; //obsolete! please use just Vec3
typedef Vec3 vectorf;
typedef Vec3_f64 vectorr;
typedef Vec3_tpl<int> vectori;
inline Vec3_tpl<f32>::Vec3_tpl(type_min) { x=y=z=-3.3E38f; }
inline Vec3_tpl<f32>::Vec3_tpl(type_max) { x=y=z=3.3E38f; }
inline Vec3_tpl<f64>::Vec3_tpl(type_min) { x=y=z=-1.7E308; }
inline Vec3_tpl<f64>::Vec3_tpl(type_max) { x=y=z=1.7E308; }
template<class F>
ILINE F GetLengthSquared( const Vec3_tpl<F> &v ) { return v.x*v.x + v.y*v.y + v.z*v.z; }
template<class F>
ILINE F GetLength( const Vec3_tpl<F>& v ) { return sqrt_tpl(v.x*v.x + v.y*v.y + v.z*v.z); }
// dot product (2 versions)
template<class F1,class F2>
ILINE F1 operator * (const Vec3_tpl<F1> &v0, const Vec3_tpl<F2> &v1) {
return (F1)(v0.x*v1.x+v0.y*v1.y+v0.z*v1.z);
}
template<class F1,class F2>
ILINE F1 operator | (const Vec3_tpl<F1> &v0, const Vec3_tpl<F2> &v1) {
return v0.x*v1.x+v0.y*v1.y+v0.z*v1.z;
}
// cross product
template<class F1,class F2>
ILINE Vec3_tpl<F1> operator ^ (const Vec3_tpl<F1> &v0, const Vec3_tpl<F2> &v1) {
return Vec3_tpl<F1>(v0.y*v1.z-v0.z*v1.y, v0.z*v1.x-v0.x*v1.z, v0.x*v1.y-v0.y*v1.x);
}
template<class F1,class F2>
ILINE Vec3_tpl<F1> operator % (const Vec3_tpl<F1> &v0, const Vec3_tpl<F2> &v1) {
return Vec3_tpl<F1>(v0.y*v1.z-v0.z*v1.y, v0.z*v1.x-v0.x*v1.z, v0.x*v1.y-v0.y*v1.x);
}
//---------------------------------------------------------------------------
//vector addition
template<class F1,class F2>
ILINE Vec3_tpl<F1> operator + (const Vec3_tpl<F1> &v0, const Vec3_tpl<F2> &v1) {
return Vec3_tpl<F1>(v0.x+v1.x, v0.y+v1.y, v0.z+v1.z);
}
//vector subtraction
template<class F1,class F2>
ILINE Vec3_tpl<F1> operator - (const Vec3_tpl<F1> &v0, const Vec3_tpl<F2> &v1) {
return Vec3_tpl<F1>(v0.x-v1.x, v0.y-v1.y, v0.z-v1.z);
}
//---------------------------------------------------------------------------
//vector self-addition
template<class F1,class F2>
ILINE Vec3_tpl<F1>& operator += (Vec3_tpl<F1> &v0, const Vec3_tpl<F2> &v1) {
v0.x+=v1.x; v0.y+=v1.y; v0.z+=v1.z; return v0;
}
//vector self-subtraction
template<class F1,class F2>
ILINE Vec3_tpl<F1>& operator -= (Vec3_tpl<F1> &v0, const Vec3_tpl<F2> &v1) {
v0.x-=v1.x; v0.y-=v1.y; v0.z-=v1.z; return v0;
}
//! calculate the angle between two vectors in 3d (by M.M.)
//! /param invA direction of vector a (don't have to be normalized)
//! /param invB direction of vector b (don't have to be normalized)
//! /return angle in the range 0 to p radians.
ILINE f32 CalcAngleBetween( const Vec3 &invA, const Vec3 &invB ) {
f64 LengthQ=GetLength(invA)*GetLength(invB);
if(LengthQ<0.01)LengthQ=0.01;
return((f32)(acos((invA*invB)/LengthQ)));
}
// returns a vector orthogonal to this one
template<class F>
ILINE Vec3_tpl<F> GetOrthogonal( const Vec3_tpl<F>& v ) {
int i = isneg(square((F)0.9)*GetLengthSquared(v)-v.x*v.x);
Vec3_tpl<F> res;
res[i]=0; res[incm3(i)]= v[decm3(i)]; res[decm3(i)]=-v[incm3(i)];
return res;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// struct Ang3_tpl
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
template <class F>
struct Ang3_tpl : public Vec3_tpl<F>
{
Ang3_tpl() {}
Ang3_tpl(const Vec3 &v) { this->x=v.x; this->y=v.y; this->z=v.z; }
Ang3_tpl &operator = (const Vec3 &v) { this->x=v.x; this->y=v.y; this->z=v.z; return *this; }
ILINE Ang3_tpl( const F vx, const F vy, const F vz ) { this->x=vx; this->y=vy; this->z=vz; }
//! normalize the vector ANGLE to -180, 180 range
ILINE void Snap180()
{
this->x = Snap_s180(this->x);
this->y = Snap_s180(this->y);
this->z = Snap_s180(this->z);
}
//! normalize the vector ANGLE to 0-360 range
ILINE void Snap360()
{
this->x = Snap_s360(this->x);
this->y = Snap_s360(this->y);
this->z = Snap_s360(this->z);
}
ILINE void Rad2Deg() { this->x=RAD2DEG(this->x); this->y=RAD2DEG(this->y); this->z=RAD2DEG(this->z); }
//! convert from degrees to radians
//ILINE void Deg2Rad() { this->x=DEG2RAD(this->x); this->y=DEG2RAD(this->y); this->z=DEG2RAD(this->z); }
template<int SI,int SJ>
ILINE void SetAnglesXYZ( const Matrix33_tpl<F,SI,SJ>& m )
{
//check if we have an orthonormal-base (assuming we are using a right-handed coordinate system)
assert( IsEquivalent(m.GetOrtX(),m.GetOrtY()%m.GetOrtZ(),0.1f) );
assert( IsEquivalent(m.GetOrtY(),m.GetOrtZ()%m.GetOrtX(),0.1f) );
assert( IsEquivalent(m.GetOrtZ(),m.GetOrtX()%m.GetOrtY(),0.1f) );
this->y = asin_tpl(MAX((F)-1.0,MIN((F)1.0,-m.data[SI*2+SJ*0])));
if (fabs_tpl(fabs_tpl(this->y)-(F)(pi*0.5))<(F)0.01)
{
this->x = 0;
this->z = atan2_tpl(-m.data[SI*0+SJ*1],m.data[SI*1+SJ*1]);
} else
{
this->x = atan2_tpl(m.data[SI*2+SJ*1], m.data[SI*2+SJ*2]);
this->z = atan2_tpl(m.data[SI*1+SJ*0], m.data[SI*0+SJ*0]);
}
}
template<int SI,int SJ>
ILINE static Ang3_tpl<F> GetAnglesXYZ( const Matrix33_tpl<F,SI,SJ>& m ) { Ang3_tpl<F> a; a.SetAnglesXYZ(m); return a; }
};
typedef Ang3_tpl<f32> Ang3;
//ILINE Ang3 Rad2Deg(const Ang3& a) { return Ang3(RAD2DEG(a.x),RAD2DEG(a.y),RAD2DEG(a.z)); }
ILINE Ang3 Deg2Rad(const Ang3& a) { return Ang3(DEG2RAD(a.x),DEG2RAD(a.y),DEG2RAD(a.z)); }
//! normalize the val to 0-360 range
ILINE f32 Snap_s360( f32 val ) {
if( val < 0.0f )
val =f32( 360.0f + cry_fmod(val,360.0f));
else
if(val >= 360.0f)
val =f32(cry_fmod(val,360.0f));
return val;
}
//! normalize the val to -180, 180 range
ILINE f32 Snap_s180( f32 val ) {
if( val > -180.0f && val < 180.0f)
return val;
val = Snap_s360( val );
if( val>180.0f )
return -(360.0f - val);
return val;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// struct CAngleAxis
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
template <class F> struct AngleAxis_tpl {
//! storage for the Angle&Axis coordinates.
F angle; Vec3_tpl<F> axis;
// default quaternion constructor
AngleAxis_tpl( void ) { };
AngleAxis_tpl( const f32 a, const f32 ax, const f32 ay, const f32 az ) { angle=a; axis.x=ax; axis.y=ay; axis.z=az; }
AngleAxis_tpl( const f32 a, const Vec3_tpl<F> &n ) { angle=a; axis=n; }
void operator () ( const f32 a, const Vec3_tpl<F> &n ) { angle=a; axis=n; }
//CONSTRUCTOR: implement the copy/casting/assignement constructor:
AngleAxis_tpl( const AngleAxis_tpl<F>& aa ); //CAngleAxis aa=angleaxis
//explicit AngleAxis_tpl( const Matrix33_tpl<F>& m ); //CAngleAxis aa=m33
explicit AngleAxis_tpl( const Quaternion_tpl<F>& q );
const Vec3_tpl<F> operator * ( const Vec3_tpl<F>& v ) const;
};
typedef AngleAxis_tpl<f32> AngleAxis;
typedef AngleAxis_tpl<f64> AngleAxis_f64;
///////////////////////////////////////////////////////////////////////////////
// CAngleAxis: Function & Operator declarations //
///////////////////////////////////////////////////////////////////////////////
/*!
*
* CAngleAxis copy constructor: CAngleAxis aa=mat33
* We take only the rotation of the 3x3 part
*
* Use with caution: this method suffers from some instability problems!
* If the rotation-radiant is near 0 or near 2pi we get an inaccurate result,
* because we have to normalize a very small vector!
* If "angle=~0" then any axis will do, since there is no rotation!
*
* Example:
* Matrix33 mat33 = rotationXYZ33(0.5f, 2.5f, 1.5f);
* CAngleAxis aa=mat33;
*/
/*template<class F>
ILINE AngleAxis_tpl<F>::AngleAxis_tpl( const Matrix33_tpl<F> &m ) {
angle = acos_tpl((m(0,0) + m(1,1) + m(2,2)-1.0f)*0.5f);
axis = GetNormalized( Vec3_tpl<F>(m(2,1)-m(1,2), m(0,2)-m(2,0), m(1,0)-m(0,1)) );
//if "angle=~0" any axis will do, since there is no rotation
if (angle<0.00001f) { axis(1,0,0); return; }
//if "angle~=pi" we need a special approach to get the axis
if (fabsf(angle-gf_PI)<0.00001f) {
//check if "m00" is the biggest element
if ( (m(0,0)>m(1,1)) && (m(0,0)>m(2,2)) ) {
axis.x = sqrtf( m(0,0) - m(1,1) - m(2,2) + 1.0f )/2;
axis.y = ( m(0,1) ) / (2*axis.x);
axis.z = ( m(0,2) ) / (2*axis.x);
return;
}
//check if "m11" is the biggest element
if ( (m(1,1)>m(0,0)) && (m(1,1)>m(2,2)) ) {
axis.x = sqrtf( m(1,1) - m(0,0) - m(2,2) + 1.0f )/2;
axis.y = ( m(0,1) ) / (2*axis.x);
axis.z = ( m(1,2) ) / (2*axis.x);
return;
}
//check if "m22" is the biggest element
if ( (m(2,2)>m(0,0)) && (m(2,2)>m(1,1)) ) {
axis.x = sqrtf( m(2,2) - m(0,0) - m(1,1) + 1.0f )/2;
axis.y = ( m(0,2) ) / (2*axis.x);
axis.z = ( m(1,2) ) / (2*axis.x);
return;
}
}
}*/
/*!
*
* CAngleAxisn copy constructor; CAngleAxis aa=q
*
* Use with caution: this method suffers from some instability problems!
* If the rotation-radiant is near 0 or near 2pi we get an inaccurate result,
* because we have to normalize a very small vector!
*
* Example:
* CQuaternion q;
* q.rotationXYZ(0.5f, 2.5f, 1.5f);
* CAngleAxis aa=mat33;
*/
template<class F>
ILINE AngleAxis_tpl<F>::AngleAxis_tpl( const Quaternion_tpl<F> &q ) {
// quaternion is assumed to be a unit-quaternion.
angle = acos_tpl(q.w)*2;
axis = q.v;
F sine = sin_tpl(angle*0.5f);
if ( sine ) { axis=q.v/sine; }
// if vector=0 then we assume this quaternion to be an identity-quaternion.
// an identity quaternion is a neutral element, so any normalized axis will do.
// we choose angle=0 and axis(1,0,0). Any arbitrary axis with zero-angle performs no rotation
if( (axis.x==0) && (axis.y==0) && (axis.z==0) ) { angle=0; axis.x=1; axis.y=0; axis.z=0; }
}
/*!
*
* rotation of a vector by axis & angle
*
* Example:
* CAngleAxis aa(3.142f,0,1,0);
* Vec3 v(33,44,55);
* Vec3 result = aa*v;
*/
template<class F>
ILINE const Vec3_tpl<F> AngleAxis_tpl<F>::operator * ( const Vec3_tpl<F> &v ) const {
Vec3_tpl<F> origin = axis*(axis|v);
return origin + (v-origin)*cos_tpl(angle) + (axis % v)*sin_tpl(angle);
}
//////////////////////////////////////////////////////////////////////
struct Plane
{
//plane-equation: n.x*x+n.y*y+n.z*z+d>0 is in front of the plane
Vec3 n; //!< normal
f32 d; //!< distance
//----------------------------------------------------------------
Plane() { };
ILINE Plane( const Plane &p ) { n=p.n; d=p.d; }
ILINE Plane( const Vec3 &normal, const f32 &distance ) { n=normal; d=distance; }
//! set normal and dist for this plane and then calculate plane type
ILINE void Set(const Vec3 &vNormal,const f32 fDist) {
n = vNormal;
d = fDist;
}
ILINE void SetPlane( const Vec3 &normal, const Vec3 &point ) {
n=normal;
d=-(point | normal);
}
ILINE friend Plane GetPlane( const Vec3 &normal, const Vec3 &point ) {
return Plane( normal,-(point|normal) );
}
/*!
*
* Constructs the plane by tree given Vec3s (=triangle)
*
* Example 1:
* \code
* Vec3 v0(1,2,3),v1(4,5,6),v2(6,5,6);
* Plane plane;
* plane.CalculatePlane(v0,v1,v2);
* \endcode
*
* Example 2:
* \code
* Vec3 v0(1,2,3),v1(4,5,6),v2(6,5,6);
* Plane plane=CalculatePlane(v0,v1,v2);
* \endcode
*
*/
ILINE void SetPlane( const Vec3 &v0, const Vec3 &v1, const Vec3 &v2 ) {
n = GetNormalized((v1-v0)%(v0-v2)); //vector cross-product
d = -(n | v0); //calculate d-value
}
ILINE friend Plane GetPlane( const Vec3 &v0, const Vec3 &v1, const Vec3 &v2 ) {
Plane p;
p.n = GetNormalized((v1-v0)%(v0-v2)); //vector cross-product
p.d = -(p.n | v0); //calculate d-value
return p;
}
/*!
*
* Computes signed distance from point to plane.
* This is the standart plane-equation: d=Ax*By*Cz+D.
* The normal-vector is assumed to be normalized.
*
* Example:
* Vec3 v(1,2,3);
* Plane plane=CalculatePlane(v0,v1,v2);
* f32 distance = plane|v;
*
*/
ILINE f32 operator | ( const Vec3 &point ) const { return (n | point) + d; }
//! check for equality between two planes
ILINE friend bool operator ==(const Plane &p1, const Plane &p2) {
if (fabsf(p1.n.x-p2.n.x)>0.0001f) return (false);
if (fabsf(p1.n.y-p2.n.y)>0.0001f) return (false);
if (fabsf(p1.n.z-p2.n.z)>0.0001f) return (false);
if (fabsf(p1.d-p2.d)<0.01f) return(true);
return (false);
}
//-------------------------------------------------------------------------------------
//---------old stuff-------------------------------------------------------------------
//---------dont use, many bugs, danger danger -----------------------------------------
//-------------------------------------------------------------------------------------
//! calc the plane giving 3 points
//DANGER, DANGER! calculation of d-value is wrong
void CalcPlane(const Vec3 &p0, const Vec3 &p1, const Vec3 &p2) {
n = (p0-p1)^(p2-p1);
n.Normalize();
d = (p0*n);
}
//! Makes the plane by 3 given points
void Init(const Vec3 & v1, const Vec3 & v2, const Vec3 & v3)
{
Vec3 u, v, t;
u = v2 - v1;
v = v2 - v3;
t = u ^ v;
t.Normalize();
n = t;
d = t*v1;
}
//! same as above for const members
ILINE f32 DistFromPlane(const Vec3 &vPoint) const {
return (n*vPoint-d);
}
Vec3 MirrorVector(Vec3& i) {
return i - n*((n|i)*2);
}
Vec3 MirrorPosition(Vec3& i) {
return i - n * (2.f * ((n|i) - d));
}
};
//! calculate 2 vector that form a orthogonal base with a given input vector (by M.M.)
//! /param invDirection input direction (has to be normalized)
//! /param outvA first output vector that is perpendicular to the input direction
//! /param outvB second output vector that is perpendicular the input vector and the first output vector
ILINE void GetOtherBaseVec( const Vec3 &invDirection, Vec3 &outvA, Vec3 &outvB )
{
if(invDirection.z<-0.5f || invDirection.z>0.5f)
{
outvA.x=invDirection.z;
outvA.y=invDirection.y;
outvA.z=-invDirection.x;
}
else
{
outvA.x=invDirection.y;
outvA.y=-invDirection.x;
outvA.z=invDirection.z;
}
outvB = invDirection.Cross(outvA);
outvB.Normalize();
outvA = invDirection.Cross(outvB);
// without this normalization the results are not good enouth (Cross product introduce a errors)
outvA.Normalize();
}
#endif //vector

2678
CryCommon/Cry_XOptimise.h Normal file

File diff suppressed because it is too large Load Diff

264
CryCommon/EntityDesc.h Normal file
View File

@@ -0,0 +1,264 @@
//////////////////////////////////////////////////////////////////////
//
// Game Source Code
//
// File: EntityDesc.h
// Description: Entity description utility class used for the creation of the entities.
//
// History:
// - 08/16/2001: Alberto Demichelis created
// - 12/04/2003: MM optimized, cleaned up
//
//////////////////////////////////////////////////////////////////////
#ifndef GAME_ENTITYDESC_H
#define GAME_ENTITYDESC_H
#include "Stream.h"
#include "IEntityRenderState.h"
#include <string>
struct IEntityContainer;
template<int _max_size> class SafeString
{
public:
SafeString(){
memset(m_s,0,_max_size);
}
SafeString &operator =(const string &s)
{
assert( s.length() < _max_size );
strcpy(m_s,s.c_str());
return *this;
}
SafeString &operator =(const char *s)
{
assert( s );
assert( strlen(s) < _max_size );
strcpy(m_s,s);
return *this;
}
operator const char*() const
{
return m_s;
}
operator const char*()
{
return m_s;
}
const char *c_str() const {return m_s;}
const char *c_str() {return m_s;}
int length(){return strlen(m_s);}
private:
char m_s[_max_size];
};
class CStream;
struct IScriptObject;
/*!
CEntityDecs class is an entity description.
This class describes what kind of entity needs to be spawned, and is passed to entity system when an entity is spawned. This
class is kept in the entity and can be later retrieved in order to (for example) clone an entity.
@see IEntitySystem::SpawnEntity(CEntityDesc &)
@see IEntity::GetEntityDesc()
*/
class CEntityDesc
{
public:
//! the net unique identifier (EntityId)
int32 id;
//! the name of the player... does not need to be unique
SafeString<256> name;
//! player, weapon, or something else - the class id of this entity
EntityClassId ClassId;
//! specify a model for the player container
SafeString<256> sModel;
Vec3 vColor; //!< used for team coloring (0xffffff=default, coloring not used)
//! this is filled out by container, defaults to ANY
bool netPresence;
//! the name of the lua table corresponding to this entity
SafeString<256> className;
Vec3 pos;
Vec3 angles;
float scale;
void * pUserData; //! used during loading from XML
IScriptObject *pProperties;
IScriptObject *pPropertiesInstance;
~CEntityDesc(){};
CEntityDesc();
CEntityDesc( int id, const EntityClassId ClassId );
CEntityDesc( const CEntityDesc &d ) { *this = d; };
CEntityDesc& operator=( const CEntityDesc &d );
bool Write( IBitStream *pIBitStream, CStream &stm);
bool Read( IBitStream *pIBitStream, CStream &stm);
bool IsDirty();
};
///////////////////////////////////////////////
inline CEntityDesc::CEntityDesc()
{
className = "";
id = 0;
netPresence = true;
ClassId = 0;
sModel= "";
pUserData =0;
pProperties=NULL;
pPropertiesInstance=NULL;
angles(0,0,0);
pos(0,0,0);
scale = 1;
vColor=Vec3(1,1,1); // default, colour not used
}
///////////////////////////////////////////////
inline CEntityDesc::CEntityDesc( int _id, const EntityClassId _ClassId )
{
className = "";
id = _id;
netPresence = true;
ClassId = _ClassId;
sModel= "";
pUserData =0;
pProperties=NULL;
pPropertiesInstance=NULL;
angles(0,0,0);
pos(0,0,0);
scale = 1;
vColor=Vec3(1,1,1); // default, colour not used
}
inline CEntityDesc& CEntityDesc::operator=( const CEntityDesc &d )
{
className = d.className;
id = d.id;
netPresence = d.netPresence;
ClassId= d.ClassId;
sModel= d.sModel;
pos = d.pos;
angles = d.angles;
pProperties=d.pProperties;
pPropertiesInstance=d.pPropertiesInstance;
vColor=d.vColor;
scale = d.scale;
return *this;
}
///////////////////////////////////////////////
inline bool CEntityDesc::Write( IBitStream *pIBitStream, CStream &stm )
{
WRITE_COOKIE(stm);
if(!pIBitStream->WriteBitStream(stm,id,eEntityId))
return false;
if(name.length())
{
stm.Write(true);
stm.Write(name.c_str());
}
else
stm.Write(false);
if(!pIBitStream->WriteBitStream(stm,ClassId,eEntityClassId))
return false;
if(sModel.length())
{
stm.Write(true);
stm.Write(sModel);
}
else
{
stm.Write(false);
}
if((*((unsigned int *)(&pos.x))==0)
&& (*((unsigned int *)(&pos.y))==0)
&& (*((unsigned int *)(&pos.z))==0))
{
stm.Write(false);
}
else
{
stm.Write(true);
stm.Write(pos);
}
if(vColor!=Vec3(1,1,1))
{
stm.Write(true);
stm.Write((unsigned char)(vColor.x*255.0f));
stm.Write((unsigned char)(vColor.y*255.0f));
stm.Write((unsigned char)(vColor.z*255.0f));
}
else
stm.Write(false);
WRITE_COOKIE(stm);
return true;
}
///////////////////////////////////////////////
inline bool CEntityDesc::Read( IBitStream *pIBitStream, CStream &stm )
{
bool bModel,bName,bPos,bTeamColor;
static char sTemp[250];
VERIFY_COOKIE(stm);
if(!pIBitStream->ReadBitStream(stm,id,eEntityId))
return false;
stm.Read(bName);
if(bName)
{
stm.Read(sTemp,250);
name=sTemp;
}
if(!pIBitStream->ReadBitStream(stm,ClassId,eEntityClassId))
return false;
stm.Read(bModel);
if(bModel)
{
stm.Read(sTemp,250);
sModel=sTemp;
}
stm.Read(bPos);
if(bPos)
stm.Read(pos);
else
pos=Vec3(0,0,0);
stm.Read(bTeamColor);
if(bTeamColor)
{
unsigned char x,y,z;
stm.Read(x);stm.Read(y);stm.Read(z);
vColor=Vec3(x/255.0f,y/255.0f,z/255.0f);
}
else
vColor=Vec3(1,1,1);
VERIFY_COOKIE(stm);
return true;
}
///////////////////////////////////////////////
inline bool CEntityDesc::IsDirty()
{
return true;
}
#endif // GAME_ENTITYDESC_H

73
CryCommon/Font.h Normal file
View File

@@ -0,0 +1,73 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek CryENGINE Source code
//
// File:Font.h
//
// History:
// -Feb 2,2001:Created by Marco Corbetta
//
//////////////////////////////////////////////////////////////////////
#ifndef FONT_H
#define FONT_H
#if _MSC_VER > 1000
# pragma once
#endif
#include <IRenderer.h>
#define FONTCOLORS 9
//////////////////////////////////////////////////////////////////////////
//! Depricated file, must be removed.
//////////////////////////////////////////////////////////////////////////
class CXFont
{
public:
CXFont( IRenderer *pRenderer )
{
m_pRenderer=pRenderer;
m_invfontsize=0;
m_charsize=0;
m_char_inc=0;
m_font_id=-1;
m_image=NULL;
}
virtual ~CXFont()
{
m_image = NULL;
}
virtual void Release()
{
delete this;
}
void SetImage(ITexPic *image)
{
m_image=image;
CalcCharSize();
}
void CalcCharSize()
{
if (m_image)
{
m_invfontsize=1.0f/(float)m_image->GetWidth();
m_charsize=(float)m_image->GetWidth()/16.0f;
m_char_inc=m_charsize*m_invfontsize;
}
}
public:
float m_invfontsize;
float m_charsize;
float m_char_inc;
int m_font_id;
ITexPic * m_image;
IRenderer *m_pRenderer;
};
#endif

440
CryCommon/FrameProfiler.h Normal file
View File

@@ -0,0 +1,440 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2002.
// -------------------------------------------------------------------------
// File name: frameprofiler.h
// Version: v1.00
// Created: 24/6/2003 by Timur,Sergey,Wouter.
// Compilers: Visual Studio.NET
// Description:
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#ifndef __frameprofiler_h__
#define __frameprofiler_h__
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define USE_FRAME_PROFILER // comment this define to remove most profiler related code in the engine
enum EProfiledSubsystem
{
PROFILE_ANY,
PROFILE_RENDERER,
PROFILE_3DENGINE,
PROFILE_AI,
PROFILE_ANIMATION,
PROFILE_MOVIE,
PROFILE_ENTITY,
PROFILE_FONT,
PROFILE_NETWORK,
PROFILE_PHYSICS,
PROFILE_SCRIPT,
PROFILE_SOUND,
PROFILE_EDITOR,
PROFILE_SYSTEM,
PROFILE_GAME,
//////////////////////////////////////////////////////////////////////////
// This enumes used for Network traffic profilers.
// They record bytes transferred instead of time.
//////////////////////////////////////////////////////////////////////////
PROFILE_NETWORK_TRAFFIC,
PROFILE_LAST_SUBSYSTEM // Must always be last.
};
#include "platform.h"
#include "ISystem.h"
class CFrameProfiler;
class CFrameProfilerSection;
class CCustomProfilerSection;
//////////////////////////////////////////////////////////////////////////
/*! This callback will be called for Profiling Peaks.
*/
struct IFrameProfilePeakCallback
{
//! Called when peak is detected for this profiler.
//! @param fPeakTime peak time in milliseconds.
virtual void OnFrameProfilerPeak( CFrameProfiler *pProfiler,float fPeakTime ) = 0;
};
//////////////////////////////////////////////////////////////////////////
//! IFrameProfileSystem interface.
//! the system which does the gathering of stats
struct IFrameProfileSystem
{
enum EDisplayQuantity
{
SELF_TIME,
TOTAL_TIME,
SELF_TIME_EXTENDED,
TOTAL_TIME_EXTENDED,
PEAK_TIME,
SUBSYSTEM_INFO,
COUNT_INFO,
};
//! Reset all profiling data.
virtual void Reset() = 0;
//! Add new frame profiler.
virtual void AddFrameProfiler( CFrameProfiler *pProfiler ) = 0;
//! Must be called at the start of the frame.
virtual void StartFrame() = 0;
//! Must be called at the end of the frame.
virtual void EndFrame() = 0;
//! Get number of registered frame profilers.
virtual int GetProfilerCount() const = 0;
//! Get frame profiler at specified index.
//! @param index must be 0 <= index < GetProfileCount()
virtual CFrameProfiler* GetProfiler( int index ) const = 0;
virtual void Enable( bool bCollect,bool bDisplay ) = 0;
virtual void SetSubsystemFilter( bool bFilterSubsystem,EProfiledSubsystem subsystem ) = 0;
//! True if profiler is turned off (even if collection is paused).
virtual bool IsEnabled() const = 0;
//! True if profiler must collect profiling data.
virtual bool IsProfiling() const = 0;
virtual void SetDisplayQuantity( EDisplayQuantity quantity ) = 0;
// For custom frame profilers.
virtual void StartCustomSection( CCustomProfilerSection *pSection ) = 0;
virtual void EndCustomSection( CCustomProfilerSection *pSection ) = 0;
//! Register peak listener callback to be called when peak value is greater then this.
virtual void AddPeaksListener( IFrameProfilePeakCallback *pPeakCallback ) = 0;
virtual void RemovePeaksListener( IFrameProfilePeakCallback *pPeakCallback ) = 0;
};
//////////////////////////////////////////////////////////////////////////
//! CFrameProfilerSamplesHistory provides information on history of sample values
//! for profiler counters.
//////////////////////////////////////////////////////////////////////////
template <class T, int TCount>
class CFrameProfilerSamplesHistory
{
public:
CFrameProfilerSamplesHistory() : m_nHistoryNext (0),m_nHistoryCount(0) {}
//! Add a new sample to history.
void Add( T sample )
{
m_history[m_nHistoryNext] = sample;
m_nHistoryNext = (m_nHistoryNext+TCount-1) % TCount;
if (m_nHistoryCount < TCount)
++m_nHistoryCount;
}
//! cleans up the data history
void Clear()
{
m_nHistoryNext = 0;
m_nHistoryCount = 0;
}
//! Get last sample value.
T GetLast()
{
if (m_nHistoryCount)
return m_history[(m_nHistoryNext+1)%TCount];
else
return 0;
}
//! calculates average sample value for at most the given number of frames (less if so many unavailable)
T GetAverage( int nCount = TCount )
{
if (m_nHistoryCount)
{
T fSum = 0;
if (nCount > m_nHistoryCount)
nCount = m_nHistoryCount;
for (int i = 1; i <= nCount; ++i)
{
fSum += m_history[(m_nHistoryNext+i) % (sizeof(m_history)/sizeof((m_history)[0]))];
}
return fSum / nCount;
}
else
return 0;
}
//! calculates average sample value for at most the given number of frames (less if so many unavailable),
//! multiplied by the Poisson function
T GetAveragePoisson(int nCount, float fMultiplier)
{
if (m_nHistoryCount)
{
float fSum = 0, fCurrMult = 1, fSumWeight = 0;
if (nCount > m_nHistoryCount)
nCount = m_nHistoryCount;
for (int i = 1; i <= nCount; ++i)
{
fSum += m_history[(m_nHistoryNext+i)%TCount] * fCurrMult;
fSumWeight += fCurrMult;
fCurrMult *= fMultiplier;
}
return (T)(fSum / fSumWeight);
}
else
return 0;
}
//! calculates Standart deviation of values.
//! stdev = Sqrt( Sum((X-Xave)^2)/(n-1) )
T GetStdDeviation( int nCount = TCount )
{
if (m_nHistoryCount)
{
T fAve = GetAverage(nCount);
T fVal = 0;
T fSumVariance = 0;
if (nCount > m_nHistoryCount)
nCount = m_nHistoryCount;
for (int i = 1; i <= nCount; ++i)
{
fVal = m_history[(m_nHistoryNext+i) % (sizeof(m_history)/sizeof((m_history)[0]))];
fSumVariance = (fVal - fAve)*(fVal - fAve); // (X-Xave)^2
}
return sqrtf( fSumVariance/(nCount-1) );
}
else
return 0;
}
//! calculates max sample value for at most the given number of frames (less if so many unavailable)
T GetMax(int nCount=TCount)
{
if (m_nHistoryCount)
{
T fMax;
if (nCount > m_nHistoryCount)
nCount = m_nHistoryCount;
for (int i = 1; i <= nCount; ++i)
{
T fCur = m_history[(m_nHistoryNext+i) % (sizeof(m_history)/sizeof((m_history)[0]))];
if (i == 1 || fCur > fMax)
fMax = fCur;
}
return fMax;
}
else
return 0;
}
//! calculates min sample value for at most the given number of frames (less if so many unavailable)
T GetMin(int nCount = TCount)
{
if (m_nHistoryCount)
{
T fMin;
if (nCount > m_nHistoryCount)
nCount = m_nHistoryCount;
for (int i = 1; i <= nCount; ++i)
{
T fCur = m_history[(m_nHistoryNext+i) % (sizeof(m_history)/sizeof((m_history)[0]))];
if (i == 1 || fCur < fMin)
fMin = fCur;
}
return fMin;
}
else
return 0;
}
protected:
// the timer values for the last frames
T m_history[TCount];
// the current pointer in the timer history, decreases
int m_nHistoryNext;
// the currently collected samples in the timer history
int m_nHistoryCount;
// adds the entry to the timer history (current timer value)
};
//////////////////////////////////////////////////////////////////////////
class CFrameProfilerGraph
{
public:
int m_x;
int m_y;
int m_width;
int m_height;
std::vector<unsigned char> m_data;
};
//////////////////////////////////////////////////////////////////////////
class CFrameProfilerOfflineHistory
{
public:
//! Self time in microseconds.
std::vector<unsigned int> m_selfTime;
//! Number of calls.
std::vector<unsigned short> m_count;
};
//////////////////////////////////////////////////////////////////////////
//! CFrameProfiler is a single profiler counter with unique name and data.
//! Multiple Sections can be executed for this profiler, they all will be merged in this class.
//! CFrameProfileSection must reference pointer to instance of this counter, to collect the sampling data.
//!
class CFrameProfiler
{
public:
ISystem *m_pISystem;
const char *m_name;
//! Total time spent in this counter including time of child profilers in current frame.
int64 m_totalTime;
//! Self frame time spent only in this counter (But includes recursive calls to same counter) in current frame.
int64 m_selfTime;
//! How many times this profiler counter was executed.
int m_count;
//! Total time spent in this counter during all profiling period.
int64 m_sumTotalTime;
//! Total self time spent in this counter during all profiling period.
int64 m_sumSelfTime;
//! Displayed quantity (interpolated or avarage).
float m_displayedValue;
//! Displayed quantity (current frame value).
float m_displayedCurrentValue;
//! How variant this value.
float m_variance;
//! Current parent profiler in last frame.
CFrameProfiler *m_pParent;
//! Expended or collapsed displaying state.
bool m_bExpended;
bool m_bHaveChildren;
EProfiledSubsystem m_subsystem;
CFrameProfilerSamplesHistory<float,64> m_totalTimeHistory;
CFrameProfilerSamplesHistory<float,64> m_selfTimeHistory;
CFrameProfilerSamplesHistory<int,64> m_countHistory;
//! Graph data for this frame profiler.
//! Graph associated with this profiler.
CFrameProfilerGraph* m_pGraph;
CFrameProfilerOfflineHistory *m_pOfflineHistory;
CFrameProfiler( ISystem *pSystem,const char *sCollectorName,EProfiledSubsystem subsystem=PROFILE_ANY )
{
m_pParent = 0;
m_pGraph = 0;
m_bExpended = false;
m_bHaveChildren = false;
m_pOfflineHistory = 0;
m_subsystem = subsystem;
m_totalTime = m_selfTime = 0;
m_sumTotalTime = m_sumSelfTime = 0;
m_count = 0;
m_pISystem = pSystem;
m_name = sCollectorName;
m_pISystem->GetIProfileSystem()->AddFrameProfiler( this );
}
};
//////////////////////////////////////////////////////////////////////////
//! CFrameProfilerSection is an auto class placed where code block need to be profiled.
//! Every time this object is constructed and destruted the time between constructor
//! and destructur is merged into the referenced CFrameProfiler instance.
//!
class CFrameProfilerSection
{
public:
int64 m_startTime;
int64 m_excludeTime;
CFrameProfiler *m_pFrameProfiler;
CFrameProfilerSection *m_pParent;
__forceinline CFrameProfilerSection( CFrameProfiler *profiler )
{
m_pFrameProfiler = profiler;
if (profiler)
m_pFrameProfiler->m_pISystem->StartProfilerSection( this );
}
__forceinline ~CFrameProfilerSection()
{
if (m_pFrameProfiler)
m_pFrameProfiler->m_pISystem->EndProfilerSection( this );
}
};
//////////////////////////////////////////////////////////////////////////
//! CCustomProfilerSection is an auto class placed where any custom data need to be profiled.
//! Works similary to CFrameProfilerSection, but records any custom data, instead of elapsed time.
//!
class CCustomProfilerSection
{
public:
int *m_pValue;
int m_excludeValue;
CFrameProfiler *m_pFrameProfiler;
CCustomProfilerSection *m_pParent;
//! pValue pointer must remain valid until after calling destructor of this custom profiler section.
__forceinline CCustomProfilerSection( CFrameProfiler *profiler,int *pValue )
{
m_pValue = pValue;
m_pFrameProfiler = profiler;
if (profiler)
m_pFrameProfiler->m_pISystem->GetIProfileSystem()->StartCustomSection( this );
}
__forceinline ~CCustomProfilerSection()
{
if (m_pFrameProfiler)
m_pFrameProfiler->m_pISystem->GetIProfileSystem()->EndCustomSection( this );
}
};
//USE_FRAME_PROFILER
#if defined(USE_FRAME_PROFILER) && (!defined(_RELEASE) || defined(WIN64))
//////////////////////////////////////////////////////////////////////////
//! Place this macro when you need to profile a function.
//!
//! void CTest::Func() {
//! FUNCTION_PROFILER( GetISystem() );
//! // function body will be profiled.
//! }
#define FUNCTION_PROFILER( pISystem,subsystem ) \
static CFrameProfiler staticFrameProfiler( pISystem,__FUNCTION__,subsystem ); \
CFrameProfilerSection frameProfilerSection( &staticFrameProfiler );
#define FUNCTION_PROFILER_FAST( pISystem,subsystem,bProfileEnabled ) \
static CFrameProfiler staticFrameProfiler( pISystem,__FUNCTION__,subsystem ); \
CFrameProfilerSection frameProfilerSection( (bProfileEnabled)?&staticFrameProfiler:NULL );
//////////////////////////////////////////////////////////////////////////
//! Place this macro when you need to profile any code block.
//! {
//! ... some code ...
//! {
//! FRAME_PROFILER( GetISystem(),"MyCode" );
//! ... more code ... // This code will be profiled with counter named "MyCode"
//! }
//! }
#define FRAME_PROFILER( szProfilerName,pISystem,subsystem ) \
static CFrameProfiler staticFrameProfiler( pISystem,szProfilerName,subsystem ); \
CFrameProfilerSection frameProfilerSection( &staticFrameProfiler );
//! Faster version of FRAME_PROFILE macro, also accept a pointer to boolean variable which turn on/off profiler.
#define FRAME_PROFILER_FAST( szProfilerName,pISystem,subsystem,bProfileEnabled ) \
static CFrameProfiler staticFrameProfiler( pISystem,szProfilerName,subsystem ); \
CFrameProfilerSection frameProfilerSection( (bProfileEnabled)?&staticFrameProfiler:NULL );
#else //#if !defined(_RELEASE) || defined(WIN64)
#define FUNCTION_PROFILER( pISystem,subsystem )
#define FUNCTION_PROFILER_FAST( pISystem,subsystem,bProfileEnabled )
#define FRAME_PROFILER( szProfilerName,pISystem,subsystem )
#define FRAME_PROFILER_FAST( szProfilerName,pISystem,subsystem,bProfileEnabled )
;
#endif //USE_FRAME_PROFILER
#endif // __frameprofiler_h__

1877
CryCommon/I3DEngine.h Normal file

File diff suppressed because it is too large Load Diff

427
CryCommon/I3DIndoorEngine.h Normal file
View File

@@ -0,0 +1,427 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Indoor Engine DLL source code
//
// File: CryIndoorEngine.h
//
// History:
// -September 03,2001:Created by Marco Corbetta
//
//////////////////////////////////////////////////////////////////////
#ifndef INDOORINTERFACE_H
#define INDOORINTERFACE_H
#if _MSC_VER > 1000
# pragma once
#endif
//////////////////////////////////////////////////////////////////////
#define INDOORSCALE 0
//forward declarations
//////////////////////////////////////////////////////////////////////
struct IStatObj;
struct ILog;
struct IRenderer;
struct IConsole;
struct I3DEngine;
struct ICVar;
struct IEntityRender;
struct ISystem;
class CShadowVolObject;
class CIndoorArea;
struct tShadowVolume;
struct RenderParams;
struct SRendParams;
//class Quaternion_tpl;
//////////////////////////////////////////////////////////////////////
struct IndoorBaseInterface
{
ILog *m_pLog;
IRenderer *m_pRenderer;
I3DEngine *m_p3dEngine;
IConsole *m_pConsole;
ISystem *m_pSystem;
ICVar *m_pCVDrawSoftEdges;
ICVar *m_pCVRefreshCubeMap;
ICVar *m_pCVRefreshLights;
ICVar *m_pCVShadowsEnable;
ICVar *m_pCVDrawBorderEdges;
ICVar *m_pCVDrawLight;
ICVar *m_pCVTransparentShadows;
ICVar *m_pCVCLipSimple;
ICVar *m_pCVStaticLights;
ICVar *m_pCVDrawModels;
ICVar *m_pCVCalcLight;
ICVar *m_pCVSetFence;
ICVar *m_pCVAmbientOnly;
ICVar *m_pCVDetectShader;
ICVar *m_pCVUpdateBuffers;
ICVar *m_pCVAnimatedShadows;
//! ambient color for the building
ICVar *m_pcvRAmbientColor;
ICVar *m_pcvGAmbientColor;
ICVar *m_pcvBAmbientColor;
ICVar *m_pcvAmbientColor;
//! M.M. for debugging stencil shadows (0 is default, use !=0 to force reacalculation of indoor stencil shadow volumes)
ICVar *m_pcvRecalcStencilVolumes;
};
/*! Interface to the Indoor Engine.
The Indoor Engine interface is very simple and consists of a few functions
to allow to load and perform some basic operations on an indoor structure,
a so called building.
December 04 changes:
- The building now is more like a building manager that includes multiple
buildings, the loading of buildings is done in the DLL using the XML parser
August 04 changes:
- The buildings are loaded dynamically from the game
IMPLEMENTATIONS NOTES:
During the loading of the building, a preprocess step is performed
(IndoorBuildingPreprocess.cpp) to create a list of potentially silhouette edges casting
shadows.
As the light source position is provided to the module (specified in the .CGF file),
a list of edges casting shadows is
detected and a list of shadow volume polygons is created; those shadow volumes polygons
are subsequently clipped with the convex hull of the corresponding area.
The shadow volumes are also capped (at the beginning and at the end of the extruded edges)
and clipped, as mentioned above, to solve the "camera-in-shadow-volume" and near clip plane
issues. (IndoorShadowVolumePreprocess.cpp).
The building basically is composed by a set of areas connected by portals; the areas to be
rendered are determined recursively based on a camera position provided by the 3d engine.
The indoor engine is also responsable for detecting if there is any outdoor area visible.
All the classes are derived from CVolume;further details are provided in the .cpp and .h files
of the DLL implementation.
*/
//! contains material information returned by ray intersection
//////////////////////////////////////////////////////////////////////
struct IndoorRayIntInfo
{
IStatObj *pObj;
int nFaceIndex;
Vec3_tpl<float> vPoint; //point of intersection
float fDist2; //squared distance from the ray's starting point
Vec3_tpl<float> vNormal; //normal of the polygon intersecting the ray
int nBuildId;
};
/*
//! holds shadow volume informations for static objects
//////////////////////////////////////////////////////////////////////
struct ItShadowVolume
{
virtual void Release()=0;
virtual Vec3d GetPos()=0;
virtual void SetPos(const Vec3d &vPos)=0;
virtual CShadowVolObject *GetShadowVolume()=0;
virtual void SetShadowVolume(CShadowVolObject *psvObj)=0;
//! /param lSource lightsource, worldspace and objectspace position is used
//! /param inArea pointer to the area whre the object is in (could be 0 - but shadow extrusion is set to maximum)
virtual void RebuildDynamicShadowVolumeBuffer( const CDLight &lSource, CIndoorArea *inArea )=0;
//! return memory usage
virtual int GetMemoryUsage(){ return 0; }; //todo: implement
};
*/
//! contains sector/building infos
//////////////////////////////////////////////////////////////////////
struct tIndoorSector
{
int nSectorId;
int nBuildingId;
};
//////////////////////////////////////////////////////////////////////
struct IIndoorBase
{
/*! Render the building
@param Camera position
*/
virtual void Render(const CCamera &cam)=0;
/*! Check if a point is inside the building
@param vPos point position, in world space
@param nBuilding building number, default -1 will check in all buildings
@return true if the point is inside the building, false otherwise
*/
virtual bool CheckInside(const Vec3d &vPos,int nBuilding=-1)=0;
/*! Check if a point is inside the building
@param vPos point position, in world space
@param nBuilding return building number
@param nSectorId return sectorid
@return true if the point is inside the building, false otherwise
*/
virtual bool CheckInside(const Vec3d &vPos,int &nBuilding,int &nSectorId)=0;
/*! Check if a point is inside the building
@param vPos point position, in world space
@param tSecInfo returns sectors info
@return true if the point is inside the building, false otherwise
*/
virtual bool CheckInside(const Vec3d &vPos,tIndoorSector &tInfo)=0;
//! delete the building manager and all buildings
virtual void Release()=0;
/*! Register an entity for rendering into the building
@param pModel interface to the entity to be added
@param vPos object position, in world space
@return true if the model is inside any building, false otherwise
*/
virtual bool RegisterEntity(IEntityRender *pModel,const Vec3d &pos)=0;
/*! UnRegister an entity from the building
@param pModel interface to the entity to be removed
*/
virtual void UnRegisterEntity(IEntityRender *pModel)=0;
/*! Activate or deactivate a light source
@param szName name of the light source, as exported into the .cgf file
@param specify if the light should be either activated or deactivated
*/
virtual void ActivateLight(const char *szName,bool bActivate)=0;
/*! For debug purposes, should not be used
*/
virtual void RenderPostProcess()=0;
/*! For debug purposes, should not be used
*/
virtual void RenderDebug(const CCamera &cam)=0;
/*! return a specific object for collision detection registration
@param nPartId an integer number speciyfing which object to return
@param nBuildId specify which building to use, -1 will start from building 0
@return the requested object
REMARKS:
if nPartId is invalid,NULL will be returned
*/
virtual IStatObj *GetStatObj(int nPartId,int nBuildId=-1)=0;
/*! return the position of the requested building in world space
@param nBuildId specify which building to get the position from
@return building position
REMARKS:
return (0,0,0) if buildid is invalid
*/
virtual Vec3d GetPosition(int nBuildId)=0;
/*! Initialize system interface
//@param pIndInterface indoorbaseinterface
*/
virtual void SetInterface(const IndoorBaseInterface &pIndInterface)=0;
/*
//! Load the buildings of the level from the xml file
//@param IndInterface interface to the system
//@param szFileName xml filename
//@param szMissionName mission name
//@return true if loading succeed
//@return false if file not found, cannot load buildings or empty building list
//
virtual bool LoadBuildings(const IndoorBaseInterface &IndInterface,const char *szFileName,const char *szMissionName=NULL)=0;
*/
/*! Add a dynamic light source to the building
@param light source structure
@param bMainLight assign the mainlight of the area to the specified position
@return true if the light is inside the building
*/
virtual bool AddLightSource(const class CDLight &lSource)=0;
//! set ambient color for indoor (default ambient is black)
virtual void SetIndoorAmbientColor(const Vec3d &Vcolor)=0;
/*! render and if necessary create shadow volume resources
@param pObj the source object
@param pParams render params
@param vLightPos light position
*/
virtual void RenderShadowVolumes(IStatObj *pObj,const SRendParams *pParams)=0;
//Editor's functions
/*! Load a Building and add to the building manager
@param pIndInterface IndoorBaseInterface filled with pointers to system interface
@return building id if loaded successfully, otherwise returns -1
*/
virtual int CreateBuilding(const IndoorBaseInterface &pIndInterface)=0;
/*! Set the building position
@param vPos building position
@param nBuildId the building's IdNumber returned by LoadBuilding
*/
virtual void SetBuildingPos(const Vec3d &vPos,int nBuildId)=0;
/*! Set the building bbox
@param vMins building mins bbox
@param vMaxs building maxs bbox
@param nBuildId the building's IdNumber returned by LoadBuilding
*/
virtual void SetBuildingBBox(const Vec3d &vMins,const Vec3d &vMaxs,int nBuildId)=0;
/*! Remove a building
@param nBuildId the building's IdNumber returned by LoadBuilding
*/
virtual void DeleteBuilding(int nBuildId)=0;
/*! Remove all buildings
*/
virtual void DeleteAllBuildings()=0;
//-1 if not found
virtual int GetBuildingIdFromObj(IStatObj *pObj)=0;
/*! Add a building to the building manager
@param szFilename cgf room filename to add to the building
@param nBuildId the building's IdNumber returned by LoadBuilding
@return true if the operation succeed
*/
virtual int AddBuilding(const char *szFilename,int nBuildId)=0;
/*! Draw a building
@param vPos building position
@param nBuildId the building's IdNumber returned by LoadBuilding
*/
virtual void DrawBuilding(const CCamera &cam,int nBuildId)=0;
/*! Get building's bbox
@param vBBMin,vBBMax bbox information (filled by the function)
@param nBuildId the building's IdNumber returned by LoadBuilding
*/
virtual void GetBBox(Vec3d &vBBMin,Vec3d &vBBMax,int nBuilID)=0;
/*! Get helper infos, to allow editor to snap to helpers
@param nHelperId helper Id
@param nBuildId the building's IdNumber returned by LoadBuilding
@param vPos return helper's position
@param pMat return helper's position & orientation
@param nHelperType return helper's type
@return helper name, NULL if nHelperId is out of range
*/
virtual const char *GetHelper(int nHelperId, int nBuildId, Vec3d &vPos, Matrix44 * pMat = NULL, int * pnHelperType = NULL)=0;
/*! Hide a building
@param bHide hide/unhide the building
@param nBuildId the building's IdNumber returned by LoadBuilding
*/
virtual void HideBuilding(bool bHide,int nBuildId)=0;
/*! Activate or deactivate a main light source
@param vPos light refernce position to detect the area with the main light
@param specify if the light should be either activated or deactivated
*/
virtual void ActivateMainLight(const Vec3d &vPos,bool bActivate)=0;
/*! Hide a sector
@param bHide hide/unhide the sector
@param nBuildId the building's IdNumber returned by LoadBuilding
@param nSectorId sector's idnumber
*/
virtual void HideSector(bool bHide,int nBuildId,int nSectorId)=0;
/*! Enable/Disable visibility processing
@param bEnable
*/
virtual void EnableVisibility(bool bEnable)=0;
/*! Enable/Disable wireframe mode for building only
@param bEnable
*/
virtual void EnableWireframe(bool bEnable)=0;
/*!tell the number of buildings loaded
@return number of buildings loaded
*/
virtual int GetBuildingsNum()=0;
/*! Check visibility between sector containing vPos and camera sector
@param vPos reference point
@param tInfo if provided will check for the specified sector and building
@return false if sector is not visible from the current camera, true otherwise
*/
virtual bool IsPointPotentiallyVisible(const Vec3d &vPos,tIndoorSector *tInfo=NULL)=0;
/*! Check visibility between sector containing the bbox and camera sector
@param vMins bbox's mins
@param vMaxs bbox's maxs
@param tInfo if provided will check for the specified sector and building
@return false if sector is not visible from the current camera, true otherwise
*/
virtual bool IsBBoxPotentiallyVisible(const Vec3d &vMins,const Vec3d &vMaxs,tIndoorSector *tInfo=NULL)=0;
/*! Return dynamic light mask of sector containing vPos
@param vPos reference point
@param tInfo if provided will check for the specified sector and building
@return dynamic light mask
*/
virtual int GetLightMaskForPoint(const Vec3d &vPos,tIndoorSector *tInfo=NULL)=0;
/*! Return the sorrounding ambient color for this point
@param vPos reference point
@param tInfo if provided will check for the specified sector and building
@return color
*/
virtual Vec3d GetAmbientColor(const Vec3d &vPos,tIndoorSector *tInfo=NULL)=0;
/*! closes/opens the portal (for example a door can totally block visibility)
@param vPos portal position (the closest portal will be detected)
@param bActivate close/open the portal
@param pEntity the entity that closes or opens the portal
*/
virtual void ActivatePortal(const Vec3d &vPos,bool bActivate,IEntityRender *pEntity)=0;
/*! decides if a sound is potentially hearable (different sectors, a door block the sounds)
@param nBuldingId (the buildingId)
@param nSecId1 (the sectorid of one of the source)
@param nSecId2 (the sectorid of one of the source)
@return true if sound is hearable, false otherwise
*/
virtual bool IsSoundPotentiallyHearable(int nBuildingId,int nSecId1,int nSecId2)=0;
/*! adds/removes a cgf to the outside part of the building (no portals / areas /occlusion)
@param nBuldingId The buildingId
@param pObj The cgf to add
@param bRemove Tells to the engine if the pObj must be added or removed.
If the obj is already present will not be added again
*/
virtual bool SetOutsideStatObj(int nBuildingId,IStatObj *pObj,bool bRemove=false)=0;
};
#ifndef _XBOX
#ifdef CRYINDOORENGINE_EXPORTS
#define CRYINDOORENGINE_API __declspec(dllexport)
#else
#define CRYINDOORENGINE_API __declspec(dllimport)
#endif
#else
#define CRYINDOORENGINE_API
#endif
//////////////////////////////////////////////////////////////////////
#ifdef __cplusplus
extern "C" {
#endif
typedef IIndoorBase * (*PFNCREATEBUILDINGMANAGER)(IndoorBaseInterface *pIndInterface);
CRYINDOORENGINE_API IIndoorBase* CreateBuildingManager(IndoorBaseInterface *pIndInterface);
#ifdef __cplusplus
}
#endif
#endif

173
CryCommon/IAISystem.h Normal file
View File

@@ -0,0 +1,173 @@
#ifndef _IAISYSTEM_H_
#define _IAISYSTEM_H_
#include <Cry_Math.h>
//#include <..\CryAISystem\CryAISystem.h>
class IPhysicalEntity;
class IPhysicalWorld;
class ICrySizer;
struct IRenderer;
struct ISystem;
struct IGame;
struct IEntity;
struct IClient;
struct IAgentProxy;
struct IAgent;
struct IAIObject;
struct IGoalPipe;
struct IGraph;
struct IVisArea;
struct ObstacleData;
enum EnumAreaType
{
AREATYPE_PATH,
AREATYPE_FORBIDDEN,
AREATYPE_NAVIGATIONMODIFIER,
AREATYPE_OCCLUSION_PLANE,
};
#define AIFAF_VISIBLE_FROM_REQUESTER 1 //! Requires whoever is requesting the anchor to also have a line of sight to it
#define AIFAF_VISIBLE_TARGET 2 //! Requires that there is a line of sight between target and anchor
typedef struct AIBalanceStats
{
int nAllowedDeaths;
int nTotalPlayerDeaths;
int nEnemiesKilled;
int nShotsFires;
int nShotsHit;
int nCheckpointsHit;
int nVehiclesDestroyed;
int nTotalEnemiesInLevel;
int nSilentKills;
float fAVGEnemyLifetime;
float fAVGPlayerLifetime;
float fTotalTimeSeconds;
bool bFinal;
AIBalanceStats()
{
bFinal = false;
nAllowedDeaths=0;
nTotalPlayerDeaths=0;
nEnemiesKilled=0;
nShotsFires=0;
nShotsHit=0;
nCheckpointsHit=0;
nVehiclesDestroyed=0;
nTotalEnemiesInLevel=0;
nSilentKills=0;
fAVGPlayerLifetime = 0;
fAVGEnemyLifetime = 0;
fTotalTimeSeconds =0;
}
} AIBalanceStats;
typedef struct IAutoBalance
{
virtual void RegisterPlayerDeath()=0;
virtual void RegisterPlayerFire(int nShots)=0;
virtual void RegisterPlayerHit()=0;
virtual void RegisterEnemyLifetime(float fLifeInSeconds)=0;
virtual void RegisterVehicleDestroyed(void)=0;
virtual void SetAllowedDeathCount(int nDeaths)=0;
virtual void Checkpoint()=0;
virtual void GetAutobalanceStats(AIBalanceStats & stats)=0;
virtual void SetMultipliers(float fAccuracy, float fAggression, float fHealth)=0;
virtual void GetMultipliers(float & fAccuracy, float & fAggression, float & fHealth)=0;
} IAutoBalance;
/*! Interface to AI system. Defines functions to control the ai system.
*/
typedef struct IAISystem
{
//! Initialize the ai system
virtual bool Init(ISystem *pSystem, const char *szLevel, const char *szMissionName) = 0;
//! Release the system
virtual void ShutDown() = 0;
//! Update system. This function is called every frame
virtual void Update() = 0;
virtual void FlushSystem(void) = 0;
virtual const ObstacleData GetObstacle(int nIndex) = 0;
//! Create an ai representation for an object
virtual IAIObject *CreateAIObject(unsigned short type, void *pAssociation) = 0;
virtual IGoalPipe *CreateGoalPipe(const char *pName) = 0;
virtual IGoalPipe *OpenGoalPipe(const char *pName) = 0;
virtual IAIObject *GetAIObjectByName(unsigned short type, const char *pName) = 0;
virtual IAIObject *GetNearestObjectOfType(const Vec3 &pos, unsigned int type, float fRadius, IAIObject* pSkip=NULL ) = 0;
virtual IAIObject *GetNearestObjectOfType(IAIObject *pObject , unsigned int type, float fRadius, int nOption = 0) = 0;
virtual IAIObject *GetNearestToObject( IAIObject *pRef , unsigned short nType, float fRadius) = 0;
virtual void Release() = 0;
virtual void Reset() = 0;
virtual void RemoveObject(IAIObject *pObject) = 0;
virtual void SoundEvent( int soundid, const Vec3 &pos, float fRadius, float fThreat, float fInterest, IAIObject *pObject) = 0;
virtual bool CreatePath(const char *szPathName, EnumAreaType aAreaType = AREATYPE_PATH, float fHeight = 0) = 0;
virtual void AddPointToPath(const Vec3 &pos, const char *szPathName, EnumAreaType aAreaType = AREATYPE_PATH) = 0;
virtual void DeletePath(const char *szPathName) = 0;
virtual void SendSignal(unsigned char cFilter, int nSignalId,const char *szText, IAIObject *pSenderObject) = 0;
virtual void SendAnonimousSignal(int nSignalId,const char *szText, const Vec3 &pos, float fRadius, IAIObject *pSenderObject) = 0;
virtual void LoadTriangulation( const char *, const char *) = 0;
virtual int GetGroupCount(int groupID) = 0;
virtual void SetAssesmentMultiplier(unsigned short type, float fMultiplier) = 0;
virtual void SetSpeciesThreatMultiplier(int nSpeciesID, float fMultiplier) = 0;
virtual IGraph *GetNodeGraph() = 0;
virtual IGraph *GetHideGraph() = 0;
virtual bool CheckInside(const Vec3 &pos, int &nBuildingID, IVisArea *&pArea, bool bIgnoreSpecialAreas = false) = 0;
virtual IAutoBalance * GetAutoBalanceInterface(void) = 0;
virtual void DumpStateOf(IAIObject * pObject) = 0;
// debug members ============= DO NOT USE
virtual void DebugDraw(IRenderer *pRenderer) = 0;
virtual float GetPerceptionValue( IAIObject *pObject) = 0;
virtual int GetAITickCount() = 0;
virtual void GetMemoryStatistics(ICrySizer *pSizer) = 0;
virtual void SetTheSkip(IPhysicalEntity* pSkip) = 0;
virtual bool IntersectsForbidden(const Vec3 & vStart, const Vec3 & vEnd, Vec3 & vClosestPoint) = 0;
} IAISystem;
#endif //_IAISYSTEM_H_

662
CryCommon/IAgent.h Normal file
View File

@@ -0,0 +1,662 @@
#ifndef _IAGENT_H_
#define _IAGENT_H_
#include "Cry_Math.h"
#include "AgentParams.h"
#include <string>
#include <vector>
#include <algorithm>
#ifdef LINUX
# include "platform.h"
#endif
struct IUnknownProxy;
//! Defines for AIObject types
#define AIOBJECT_NONE 200
#define AIOBJECT_DUMMY 0
#define AIOBJECT_PUPPET 1
#define AIOBJECT_AWARE 2
#define AIOBJECT_ATTRIBUTE 3
#define AIOBJECT_WAYPOINT 6
#define AIOBJECT_HIDEPOINT 7
#define AIOBJECT_SNDSUPRESSOR 8
#define AIOBJECT_VEHICLE 30
#define AIOBJECT_HELICOPTER 40
#define AIOBJECT_CAR 50
#define AIOBJECT_BOAT 60
#define AIOBJECT_AIRPLANE 70
#define AIOBJECT_PIPEUSER 10
#define AIOBJECT_CPIPEUSER 11
#define AIOBJECT_MOUNTEDWEAPON 90
#define AIOBJECT_PLAYER 100
#define AIOBJECT_CPUPPET 20
#define AIOBJECT_CVEHICLE 21
// defines for vehicles types
#define AIVEHICLE_BOAT 20
#define AIVEHICLE_CAR 30
#define AIVEHICLE_HELICOPTER 40
#define AIVEHICLE_AIRPLANE 50
//! Event types
#define AIEVENT_ONBODYSENSOR 1
#define AIEVENT_ONVISUALSTIMULUS 2
#define AIEVENT_ONPATHDECISION 3
#define AIEVENT_ONSOUNDEVENT 4
#define AIEVENT_AGENTDIED 5
#define AIEVENT_SLEEP 6
#define AIEVENT_WAKEUP 7
#define AIEVENT_ENABLE 8
#define AIEVENT_DISABLE 9
#define AIEVENT_REJECT 10
#define AIEVENT_PATHFINDON 11
#define AIEVENT_PATHFINDOFF 12
#define AIEVENT_CLOAK 13
#define AIEVENT_UNCLOAK 14
#define AIEVENT_CLEAR 15
#define AIEVENT_MOVEMENT_CONTROL 16 // based on parameters lets object know if he is allowed to move.
#define AIEVENT_DROPBEACON 17
#define AIREADIBILITY_INTERESTING 5
#define AIREADIBILITY_SEEN 10
#define AIREADIBILITY_LOST 20
#define AIREADIBILITY_NORMAL 30
#define AIREADIBILITY_NOPRIORITY 1
#define SIGNALFILTER_LASTOP 1
#define SIGNALFILTER_GROUPONLY 2
#define SIGNALFILTER_SPECIESONLY 3
#define SIGNALFILTER_ANYONEINCOMM 4
#define SIGNALFILTER_TARGET 5
#define SIGNALFILTER_SUPERGROUP 6
#define SIGNALFILTER_SUPERSPECIES 7
#define SIGNALFILTER_SUPERTARGET 8
#define SIGNALFILTER_NEARESTGROUP 9
#define SIGNALFILTER_NEARESTSPECIES 10
#define SIGNALFILTER_NEARESTINCOMM 11
#define SIGNALFILTER_HALFOFGROUP 12
#define SIGNALFILTER_READIBILITY 100
#define HM_NEAREST 0
#define HM_FARTHEST_FROM_TARGET 1
#define HM_NEAREST_TO_TARGET 2
#define HM_FARTHEST_FROM_GROUP 3
#define HM_NEAREST_TO_GROUP 4
#define HM_LEFTMOST_FROM_TARGET 5
#define HM_RIGHTMOST_FROM_TARGET 6
#define HM_RANDOM 7
#define HM_NEAREST_TO_FORMATION 10
#define HM_FARTHEST_FROM_FORMATION 11
#define HM_NEAREST_TO_LASTOPRESULT 20
#define HM_FARTHEST_FROM_LASTOPRESULT 21
#define HM_NEAREST_TO_LASTOPRESULT_NOSAME 22
#define HM_FRONTLEFTMOST_FROM_TARGET 8
#define HM_FRONTRIGHTMOST_FROM_TARGET 9
#define BODYPOS_STAND 0
#define BODYPOS_CROUCH 1
#define BODYPOS_PRONE 2
#define BODYPOS_RELAX 3
#define BODYPOS_STEALTH 5
typedef struct AIObjectParameters
{
AgentParameters m_sParamStruct;
IUnknownProxy *pProxy;
float fEyeHeight;
bool bUsePathfindOutdoors;
} AIObjectParameters;
struct IAIObject;
typedef struct GoalParameters
{
Vec3 m_vPosition;
IAIObject *m_pTarget;
float fValue;
float fValueAux;
int nValue;
bool bValue;
string szString;
//const char *szString;
GoalParameters()
{
fValue = 0;
fValueAux = 0;
nValue = 0;
//szString = 0;
m_pTarget = 0;
}
#if (defined(WIN64) || defined(LINUX64)) && !defined(_DLL)
// FIX: refcounted STL with static libs (e.g. on AMD64 compiler) will crash without these
// TODO: AMD64 port: make a robust solution
inline GoalParameters (const GoalParameters& params)
{
m_vPosition = params.m_vPosition;
m_pTarget = params.m_pTarget;
fValue = params.fValue;
fValueAux = params.fValueAux;
nValue = params.nValue;
bValue = params.bValue;
szString = params.szString.c_str();
}
inline GoalParameters& operator = (const GoalParameters& params)
{
m_vPosition = params.m_vPosition;
m_pTarget = params.m_pTarget;
fValue = params.fValue;
fValueAux = params.fValueAux;
nValue = params.nValue;
bValue = params.bValue;
szString = params.szString.c_str();
return *this;
}
#endif
} GoalParameters;
typedef struct IGoalPipe
{
virtual void PushGoal(const string &name, bool bBlocking, GoalParameters &params) =0;
} IGoalPipe;
struct IAIObject;
typedef struct SAIEVENT
{
bool bFuzzySight;
int nDeltaHealth;
float fThreat;
float fInterest;
IAIObject *pSeen;
bool bPathFound;
Vec3 vPosition;
} SAIEVENT;
struct SOBJECTSTATE;
class CStream;
typedef struct IAIObject
{
virtual void SetRadius(float fRadius) = 0;
virtual float GetRadius() = 0;
virtual void SetPos(const Vec3 &pos,bool bKeepEyeHeight = true) = 0;
virtual const Vec3 &GetPos() = 0;
virtual void SetAngles(const Vec3 &angles) = 0;
virtual const Vec3 &GetAngles() = 0;
virtual unsigned short GetType() = 0;
virtual void *GetAssociation() = 0;
virtual void Release()=0;
virtual void ParseParameters(const AIObjectParameters &params)=0;
virtual bool CanBeConvertedTo(unsigned short type, void **pConverted) = 0;
virtual void SetName(const char *pName)= 0;
virtual char *GetName()= 0;
virtual void IsEnabled(bool enabled)= 0;
virtual void Event(unsigned short, SAIEVENT *pEvent) = 0;
virtual void SetEyeHeight(float fHeight) = 0;
virtual SOBJECTSTATE * GetState() = 0;
virtual void Bind(IAIObject* bind) = 0;
virtual void Unbind( ) = 0;
// virtual IAIObject* GetBound( ) = 0;
virtual void CreateBoundObject( unsigned short type, const Vec3& vBindPos, const Vec3& vBindAngl)=0;
virtual void EDITOR_DrawRanges(bool bEnable = true) = 0;
virtual IUnknownProxy* GetProxy() = 0;
virtual void SetSignal(int nSignalID, const char * szText, void *pSender=0) = 0;
virtual bool IsMoving() = 0;
virtual void Save(CStream & stm)=0;
virtual void Load(CStream & stm)=0;
virtual void Load_PATCH_1(CStream & stm)=0;
virtual void NeedsPathOutdoor( bool bNeeds, bool bForce=false ) = 0;
virtual bool IfNeedsPathOutdoor( ) = 0;
} IAIObject;
typedef struct IPupeUser
{
virtual void RegisterAttack(const char *name)=0;
virtual void RegisterRetreat(const char *name)=0;
virtual void RegisterWander(const char *name)=0;
virtual void RegisterIdle(const char *name)=0;
virtual bool SelectPipe(int id, const char *name, IAIObject *pArgument = 0)=0;
virtual bool InsertSubPipe(int id, const char *name, IAIObject *pArgument = 0)=0;
virtual IAIObject *GetAttentionTarget()=0;
} IPipeUser;
typedef struct IPuppet
{
virtual AgentParameters GetPuppetParameters()=0;
virtual void SetPuppetParameters(AgentParameters &pParams)=0;
} IPuppet;
typedef struct IVehicle
{
// virtual void SetGunner(IAIObject *pGunner)=0;
// virtual AgentParameters &GetPuppetParameters()=0;
// virtual void SetPuppetParameters(AgentParameters &pParams)=0;
} IVehicle;
// test state
typedef struct SAISTATE
{
bool forward;
bool back;
bool turning;
bool jump;
bool left;
bool right;
float fValue;
} SAISTATE;
typedef struct AISIGNAL
{
int nSignal;
///const char * strText;
char strText[1024];
void * pSender;
} AISIGNAL;
typedef struct SOBJECTSTATE
{
//fixme - remove it when dom\ne with tweaking of vehicles movement
char DEBUG_controlDirection;
bool forward;
bool back;
bool turnleft;
bool turnright;
bool turnup;
bool turndown;
bool left;
bool run;
bool right;
bool dodge; // for vehicles - when avoiding rockets/grenades
// bool bLost; // proxy would like to regenerate path
enum PathUsage
{
PU_NewPathWanted, // 1 proxy would like to regenerate path
PU_PathOK, // 0 proxy don't need new path
PU_NoPathfind, // 2 proxy don't want to use pathfinder - just approach
};
PathUsage pathUsage;
char mutantJump;
bool bCloseContact;
float fDesiredSpeed; // 1 - max speed 0 - no speed
float fStickDist;
float fValue;
float fValueAux;
bool fire;
bool aimLook;
int bodystate;
Vec3 vFireDir;
Vec3 vTargetPos;
Vec3 vMoveDir;
// jump related
bool jump;
Vec3 vJumpDirection;
float fJumpDuration;
float nJumpDirection;
bool bReevaluate;
bool bTakingDamage;
bool bHaveTarget;
bool bMemory;
bool bSound;
bool bTargetEnabled;
float fThreat;
float fInterest;
float fDistanceFromTarget;
float fHealth;
int nTargetType;
std::vector<AISIGNAL> vSignals;
int nAuxSignal;
string szAuxSignalText;
SOBJECTSTATE():
vFireDir(1.0f,0.0f,0.0f),
vTargetPos(1.0f,0.0f,0.0f),
vMoveDir(1.0f,0.0f,0.0f)
{
Reset();
mutantJump = 0;
run = left = right = false;
bodystate = 0;
bMemory = false;
bSound = false;
bTakingDamage = false;
bCloseContact = false;
vSignals.clear();
//pSignalSender.clear();
fValueAux = 0;
fStickDist = -1;
pathUsage = PU_NewPathWanted;
fDistanceFromTarget = 0;
}
void Reset()
{
DEBUG_controlDirection = 0;
forward = back = turnleft = turnright = turnup = turndown = jump = fire = false;
// mutantJump = 0;
bCloseContact = false;
bHaveTarget = false;
fThreat = 0;
fInterest = 0;
//left = right = false;
//bReevaluate = false;
fValueAux = 0;
// bTakingDamage = false;
bMemory = false;
bSound = false;
vMoveDir(0,0,0);
vTargetPos(0,0,0);
bTargetEnabled = false;
nAuxSignal = 0;
fDesiredSpeed = 1.0f;
}
bool operator==(SOBJECTSTATE &other)
{
if (forward == other.forward)
if (back == other.back)
if (turnleft == other.turnleft)
if (turnright == other.turnright)
if (run == other.run)
if (jump == other.jump)
if (left == other.left)
if (right == other.right)
if (fire == other.fire)
if (bodystate == other.bodystate)
return true;
return false;
}
} SOBJECTSTATE;
typedef struct SMOTORSTATE
{
bool crouched;
bool proned;
SMOTORSTATE()
{
crouched = proned = false;
}
} SMOTORSTATE;
struct IAISystem;
// PROXY TYPES
#define AIPROXY_PUPPET 1
#define AIPROXY_OBJECT 2
#define AIPROXY_VEHICLE 3
// PROXY STATUS TYPES to check
#define AIPROXYSTATUS_INVEHICLE 1
class IPhysicalEntity;
typedef struct IUnknownProxy
{
virtual bool QueryProxy(unsigned char type, void **pProxy) = 0;
virtual int Update(SOBJECTSTATE *) = 0;
virtual void Release()=0;
virtual bool CustomUpdate(Vec3& pos, Vec3 &angles) = 0;
virtual IPhysicalEntity* GetPhysics() = 0;
virtual void DebugDraw(struct IRenderer *pRenderer) = 0;
virtual bool CheckStatus(unsigned char status) = 0;
virtual void ApplyHealth(float fHealth) = 0;
virtual void Load(CStream &str)=0;
virtual void Load_PATCH_1(CStream &str)=0;
virtual void Save(CStream &str)=0;
// virtual bool IsBound() = 0;
} IUnknownProxy;
typedef struct IPuppetProxy : public IUnknownProxy
{
virtual void GetDimensions(int bodypos, float &eye_height, float &height) = 0;
virtual void Reset() = 0;
virtual void MovementControl(bool bEnableMovement, float fDuration) = 0;
} IPuppetProxy;
typedef struct IVehicleProxy : public IUnknownProxy
{
virtual void GetDimensions(int bodypos, float &eye_height, float &height) = 0;
virtual void Reset() = 0;
virtual Vec3 UpdateThreat( void* threat ) = 0;
virtual Vec3 HeliAttackAdvance( SOBJECTSTATE &state ) = 0;
virtual void SetSpeeds(float fwd, float bkw=-1) = 0;
} IVehicleProxy;
typedef struct GameNodeData
{
Vec3 m_pos;
float fSlope; // the incline of the point 1 means very inclined (45 deg) 0 is flat;
bool bWater; // true, point in water, false point in dry land
void Reset()
{
m_pos(0,0,0);
fSlope = 0;
bWater = false;
}
} GameNodeData;
typedef struct ObstacleData
{
Vec3 vPos;
Vec3 vDir;
bool operator==(const ObstacleData &other)
{
if (IsEquivalent(other.vPos,vPos,VEC_EPSILON))
if (IsEquivalent(vDir,other.vDir,VEC_EPSILON))
return true;
return false;
}
ObstacleData()
{
vPos.Set(0,0,0);
vDir.Set(0,0,0);
}
} ObstacleData;
typedef std::vector<ObstacleData> Obstacles;
typedef std::vector<int> ObstacleIndexVector;
struct GraphNode;
typedef struct GraphLink
{
GraphNode *pLink; // next triangle this way
unsigned int nStartIndex, nEndIndex; // indices of the edge vertices of this edge
float fMaxRadius; // maximum size sphere that can pass trough this edge
Vec3 vEdgeCenter;
Vec3 vWayOut; // shows the out direction from this edge
GraphLink()
{
pLink = 0;
nStartIndex = nEndIndex = 0;
fMaxRadius = 0;
vWayOut(0,0,0);
vEdgeCenter(0,0,0);
}
bool IsNewLink()
{
if( fMaxRadius<0.0f && fMaxRadius>-5.0f )
return true;
return false;
}
} GraphLink;
typedef std::vector<GraphLink> VectorOfLinks;
struct IVisArea;
typedef struct GraphNode
{
VectorOfLinks link;
ObstacleIndexVector vertex;
bool tag;
bool mark;
bool bCreated; // is true if designer created node
float fHeuristic;
float fDistance;
int nRefCount;
IVisArea *pArea;
int nBuildingID;
GameNodeData data;
GraphNode()
{
bCreated = true;
link.reserve(5);
tag = false;
data.Reset();
mark = false;
nRefCount = 0;
fHeuristic = -9999.f;
pArea = NULL; // this is outside
nBuildingID = -1; // outside
fDistance = 0;
}
~GraphNode()
{
link.clear();
vertex.clear();
}
bool Release()
{
nRefCount--;
assert(nRefCount>=0);
if (nRefCount == 0)
return true;
return false;
}
void AddRef()
{
nRefCount++;
}
float GetDegeneracyValue();
void MakeAntiClockwise();
bool IsAntiClockwise();
float GetCross( const Vec3 &vCutStart, const Vec3 &vDir, const GraphLink &theLink );
GraphLink* FindNewLink();
/* void AddHidePoint(const Vec3 &pos, const Vec3 &dir)
{
ObstacleData od;
od.vPos = pos;
od.vDir = dir;
if (std::find(vertex.begin(),vertex.end(),od) == vertex.end())
vertex.push_back(od);
}
*/
} GraphNode;
typedef struct IGraph {
virtual GraphNode * CreateNewNode(bool bFromTriangulation = false)=0;
virtual void DeleteNode(GraphNode * pNode)=0;
virtual void WriteToFile(const char *pname)=0;
virtual bool ReadFromFile(const char *pname)=0;
virtual bool RemoveEntrance(int nBuildingID, GraphNode * pNode)=0;
virtual void RemoveIndoorNodes(void)=0;
virtual void AddIndoorEntrance(int nBuildingID, GraphNode* pNode, bool bExitOnly = false) = 0;
virtual void Connect(GraphNode *one, GraphNode *two) = 0;
virtual void Disconnect(GraphNode * pDisconnected,bool bDelete = true ) =0;
virtual GraphNode *GetEnclosing(const Vec3 &pos, GraphNode *pStart = 0 ,bool bOutsideOnly = false) = 0;
virtual void AddHidePoint(GraphNode *pOwner, const Vec3 &pos, const Vec3 &dir) = 0;
virtual void RemoveHidePoint(GraphNode *pOwner, const Vec3 &pos, const Vec3 &dir) = 0;
virtual void DisableInSphere(const Vec3 &pos,float fRadius) = 0;
virtual void EnableInSphere(const Vec3 &pos,float fRadius) = 0;
} IGraph;
#define AIHEURISTIC_DEFAULT 0
#define AIHEURISTIC_STANDARD 1
#define AIHEURISTIC_VEHICLE 2
// define additional heuristics here
// ATOMIC AI OPERATIONS
#define AIOP_ACQUIRETARGET "acqtarget" // ok
#define AIOP_LOOKAROUND "lookaround" // ok
#define AIOP_APPROACH "approach" // ok
#define AIOP_BACKOFF "backoff" // ok
#define AIOP_FIRECMD "firecmd" // ok
#define AIOP_STRAFE "strafe" // ok
#define AIOP_BODYPOS "bodypos" // ok
#define AIOP_RUN "run" // ok
#define AIOP_JUMP "jump" // ok
#define AIOP_TIMEOUT "timeout" // ok
#define AIOP_PATHFIND "pathfind" // ok
#define AIOP_LOCATE "locate" // ok
#define AIOP_TRACE "trace"
#define AIOP_SIGNAL "signal"
#define AIOP_IGNOREALL "ignoreall"
#define AIOP_DEVALUE "devalue" // ok
#define AIOP_FORGET "forget" // ok
#define AIOP_HIDE "hide" // ok
///#define AIOP_MUTANTHIDE "mutanthide" // new
#define AIOP_FORM "form" // ok
#define AIOP_STICK "stick" // ok
#define AIOP_CLEAR "clear" // ok
#define AIOP_LOOP "branch" // ok
#define AIOP_LOOKAT "lookat" // ok
#define AIOP_HELIADV "heliadv" // new
#endif //_IAGENT_H_

127
CryCommon/IBindable.h Normal file
View File

@@ -0,0 +1,127 @@
//////////////////////////////////////////////////////////////////////
//
// CryEngine Source code
//
// File:IBindable.h
// Interface for IBindable class, which must be implemented by all
// objects that can be bound to a character bone
//
// History:
// April 07, 2003: Created by Sergiy Migdalskiy
//
//////////////////////////////////////////////////////////////////////
#ifndef _CRY_COMMON_BINDABLE_INTERFACE_HDR_
#define _CRY_COMMON_BINDABLE_INTERFACE_HDR_
// Description:
// This interface define a way to allow an object to be bound to a
// character bone. An IBindable should usually be attached to a bone using
// member functions of ICryCharInstance.
struct IBindable
{
// Summary:
// Get the bounding box
// Arguments:
// Mins - Position of the bottom left close corner of the bounding box
// Maxs - Position of the top right far corner of the bounding box
virtual void GetBBox(Vec3& Mins, Vec3& Maxs)=0;
// Description:
// Will return the position of the helper named in the argument. The
// helper should have been specified during the exporting process of
// the cgf file.
// Arguments:
// szHelperName - A null terminated string holding the name of the helper
// Return Value:
// A Vec3 object which contains the position.
// Summary:
// Gets the position of a specified helper
virtual Vec3 GetHelperPos(const char * szHelperName) = 0;
// Description:
// Will return the matrix of the helper named in the argument. The
// helper should have been specified during the exporting process of
// the cgf file.
// Arguments:
// szHelperName - A null terminated string holding the name of the helper
// Return Value:
// A Matrix44 of the object
// Summary:
// Gets the matrix of a specified helper
virtual const Matrix44 * GetHelperMatrixByName(const char * szHelperName) = 0;
// renders the shadow volumes of this whole object (together with attachments if any)
// the implementation may or may not implement the limit lod functionality: if it does,
// it will render the specified or lower LOD
virtual void RenderShadowVolumes(const struct SRendParams *pParams, int nLimitLod = -1)=0;
//! Sets shader template for rendering
virtual bool SetShaderTemplate(int nTemplate, const char *TemplName, const char *ShaderName, bool bOnlyRegister=false, int * pnNewTemplateId=NULL)=0;
// Description:
// Values for the nFlags parameter of SetShaderTemplateName.
// Summary:
// Flags used for SetShaderTemplateName
enum ECharShaderFlags
{
FLAGS_SET_SHADER_RECURSIVE = 1
};
//! Set shader template to be used with character
virtual bool SetShaderTemplateName(const char *TemplName, int Id, const char *ShaderName=0,struct IMatInfo *pCustomMaterial=0,unsigned nFlags = 0)
{
// [Sergiy] please ask Tiago about details: this function maps to SetShaderTemplate because some of the derived classes (IStatObj)
// don't implement it, but do implement SetShaderTemplate. The mapping is exactly like in ScriptObjectEntity::SetShader function
return SetShaderTemplate(-1,TemplName,NULL);
}
//there must be only one function
// Description:
// Registers the object elements into the renderer.
// Arguments:
// rParams - Render parameters
// nLogLevel - Level of the LOD
// Summary:
// Renders the object
virtual void Render(const struct SRendParams & rParams,const Vec3& t, int nLodLevel)=0;
//! Start the specified animation with the given parameters, if the bindable is an animatable object
virtual bool StartAnimation (const char* szAnimName, const struct CryCharAnimationParams& params){return false;}
//! Start the specified by parameters morph target, if the bindable is a morphable object
virtual void StartMorph (const char* szMorphTarget, const struct CryCharMorphParams& params) {}
//! Resets all animation layers ( stops all animations )
virtual void ResetAnimations() {}
//! Stops all morphs
virtual void StopAllMorphs() {}
//! freezes all currently playing morphs at the point they're at
virtual void FreezeAllMorphs(){}
//! Processes skining (call this function every frame to animate character)
//! dwFlags is a bitwise OR of one of the flags specified in the UpdateEnum enumeration
virtual void Update (Vec3 vPos = Vec3(0,0,0), float fRadius=0, unsigned uFlags = 0) {}
//! start preloading of object resources
virtual void PreloadResources(float fDist, float fTime, int dwFlags) = 0;
// Summary:
// Get the character instance, if valid
// Return Value:
// A pointer to an IStatObj object if the IBindable represent a static
// object, else the NULL value will be returned.
virtual struct IStatObj* GetIStatObj() {return NULL;}
// Summary:
// Get the character instance, if valid
// Return Value:
// A pointer to an ICryCharInstance object if the IBindable represent
// a character instance, else the NULL value will be returned.
virtual struct ICryCharInstance* GetICryCharInstance() {return NULL;}
};
#endif

100
CryCommon/IBitStream.h Normal file
View File

@@ -0,0 +1,100 @@
#ifndef IBITSTREAM_H__
#define IBITSTREAM_H__
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CStream;
#include "platform.h"
enum eBitStreamHint
{
eDoNotCompress, // ...
e8BitNormal, // Vec3, low quality normalized vector
eWorldPos, // Vec3, absolute world position
eASCIIText, // char *, static huffman compression
eEntityId, // u __int32,__int32, u __int16 16bit, some entities have higher probability (e.g. player)
eEntityClassId, // __int32,u __int16, for entity creation
e8BitRGB, // Vec3, 8bit Color
e4BitRGB, // Vec3, 4bit Color
eQuaternion, // Vec3, eQuaternion
eEulerAnglesHQ, // Vec3, YAW,PITCH,ROLL cyclic in [0..360[, special compression if PITCH=0 (not float but still quite high quality)
eSignedUnitValueLQ, // float, [-1..1] 8+1+1 bit if not zero, 1 bit of zero
};
struct IBitStream
{
//!
// virtual bool ReadBitStream( bool &Value )=0;
//!
virtual bool ReadBitStream( CStream &stm, int8 &Value, const eBitStreamHint eHint )=0;
//!
virtual bool ReadBitStream( CStream &stm, int16 &Value, const eBitStreamHint eHint )=0;
//!
virtual bool ReadBitStream( CStream &stm, int32 &Value, const eBitStreamHint eHint )=0;
//!
virtual bool ReadBitStream( CStream &stm, uint8 &Value, const eBitStreamHint eHint )=0;
//!
virtual bool ReadBitStream( CStream &stm, uint16 &Value, const eBitStreamHint eHint )=0;
//!
virtual bool ReadBitStream( CStream &stm, uint32 &Value, const eBitStreamHint eHint )=0;
//!
virtual bool ReadBitStream( CStream &stm, float &Value, const eBitStreamHint eHint )=0;
//!
virtual bool ReadBitStream( CStream &stm, Vec3 &Value, const eBitStreamHint eHint )=0;
//!
//! max 256 characters
virtual bool ReadBitStream( CStream &stm, char *Value, const DWORD nBufferSize, const eBitStreamHint eHint )=0;
// ----------------------------------------------------------------------------------------------------
//!
// virtual bool WriteBitStream( const bool Value )=0;
//!
virtual bool WriteBitStream( CStream &stm, const int8 Value, const eBitStreamHint eHint )=0;
//!
virtual bool WriteBitStream( CStream &stm, const int16 Value, const eBitStreamHint eHint )=0;
//!
virtual bool WriteBitStream( CStream &stm, const int32 Value, const eBitStreamHint eHint )=0;
//!
virtual bool WriteBitStream( CStream &stm, const uint8 Value, const eBitStreamHint eHint )=0;
//!
virtual bool WriteBitStream( CStream &stm, const uint16 Value, const eBitStreamHint eHint )=0;
//!
virtual bool WriteBitStream( CStream &stm, const uint32 Value, const eBitStreamHint eHint )=0;
//!
virtual bool WriteBitStream( CStream &stm, const float Value, const eBitStreamHint eHint )=0;
//!
virtual bool WriteBitStream( CStream &stm, const Vec3 &Value, const eBitStreamHint eHint )=0;
//!
//! max 256 characters
virtual bool WriteBitStream( CStream &stm, const char *Value, const DWORD nBufferSize, const eBitStreamHint eHint )=0;
// ----------------------------------------------------------------------------------------------------
// the follwoing method make use of the WriteBitStream and the ReadBitStream to simulate the error the
// write and read operations would have
//! to get the compression error
virtual void SimulateWriteRead( int8 &Value, const eBitStreamHint eHint )=0;
//! to get the compression error
virtual void SimulateWriteRead( int16 &Value, const eBitStreamHint eHint )=0;
//! to get the compression error
virtual void SimulateWriteRead( int32 &Value, const eBitStreamHint eHint )=0;
//! to get the compression error
virtual void SimulateWriteRead( uint8 &Value, const eBitStreamHint eHint )=0;
//! to get the compression error
virtual void SimulateWriteRead( uint16 &Value, const eBitStreamHint eHint )=0;
//! to get the compression error
virtual void SimulateWriteRead( uint32 &Value, const eBitStreamHint eHint )=0;
//! to get the compression error
virtual void SimulateWriteRead( float &Value, const eBitStreamHint eHint )=0;
//! to get the compression error
virtual void SimulateWriteRead( Vec3 &Value, const eBitStreamHint eHint )=0;
//! to get the compression error
virtual void SimulateWriteRead( char *Value, const DWORD nBufferSize, const eBitStreamHint eHint )=0;
};
#endif //IBITSTREAM_H__

View File

@@ -0,0 +1,22 @@
#ifndef __ICompressionHelper_h__
#define __ICompressionHelper_h__
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CStream;
struct ICompressionHelper
{
//!
virtual bool Write( CStream &outStream, const unsigned char inChar )=0;
//!
virtual bool Read( CStream &inStream, unsigned char &outChar )=0;
//!
virtual bool Write( CStream &outStream, const char *inszString )=0;
//!
virtual bool Read( CStream &inStream, char *outszString, const DWORD indwStringSize )=0;
};
#endif // __ICompressionHelper_h__

406
CryCommon/IConsole.h Normal file
View File

@@ -0,0 +1,406 @@
#ifndef _ICONSOLE_H_
#define _ICONSOLE_H_
struct ConsoleBind;
class CXFont;
struct ICVar;
#define CVAR_INT 1
#define CVAR_FLOAT 2
#define CVAR_STRING 3
// if this flag is set during registering a console variable, and the variable exists,
// then the variable will store its value in memory given by src
#define CVF_CHANGE_SOURCE (1u<<16)
#define VF_SERVER_ONCE 0x00000001
#define VF_CHEAT 0x00000002 // stays in the default state when cheats are disabled
#define VF_USERINFO 0x00000004
#define VF_MODIFIED 0x00000008
#define VF_SERVER 0x00000010
#define VF_NONOTIFY 0x00000020
#define VF_NOCHANGELEV 0x00000040
#define VF_REQUIRE_NET_SYNC 0x00000080 // cannot be changed on client and when connecting the var sent to the client
#define VF_DUMPTODISK 0x00000100
#define VF_SAVEGAME 0x00000200 // stored when saving a savegame
#define VF_NOHELP 0x00000400
#define VF_READONLY 0x00000800 // can not be changed by the user
#define VF_REQUIRE_LEVEL_RELOAD 0x00001000
#define VF_REQUIRE_APP_RESTART 0x00002000
struct ICVarDumpSink
{
virtual void OnElementFound(ICVar *pCVar) = 0;
};
struct IKeyBindDumpSink
{
virtual void OnKeyBindFound( const char *sBind,const char *sCommand ) = 0;
};
struct IOutputPrintSink
{
virtual void Print( const char *inszText )=0;
};
//! Callback class to derive from when you want to recieve callbacks when console var changes.
struct IConsoleVarSink
{
//! Called by Console before changing console var value, to validate if var can be changed.
//! @return true if ok to change value, false if should not change value.
virtual bool OnBeforeVarChange( ICVar *pVar,const char *sNewValue ) = 0;
};
/*! Interface to the engine console.
The engine console allow to manipulate the internal engine parameters
and to invoke commands.
This interface allow external modules to integrate their functionalities
into the console as commands or variables.
IMPLEMENTATIONS NOTES:
The console takes advantage of the script engine to store the console variables,
this mean that all variables visible through script and console.
*/
struct IConsole
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! delete the variable
NOTE: the variable will automatically unregister itself from the console
*/
virtual void Release() = 0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Crate a new console variable
@param sName console variable name
@param sValue default value
@param nFlag user definded flag, this parameter is used by other subsystems
and doesn't affect the console varible (basically of user data)
@return a pointer to the interface ICVar
@see ICVar
*/
virtual ICVar *CreateVariable(const char *sName,const char *sValue,int nFlags, const char *help = "")=0;
virtual ICVar *CreateVariable(const char *sName,int iValue,int nFlags, const char *help = "")=0;
virtual ICVar *CreateVariable(const char *sName,float fValue,int nFlags, const char *help = "")=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Remove a variable from the console
@param sVarName console variable name
@param bDelete if true the variable is deleted
@see ICVar
*/
virtual void UnregisterVariable(const char *sVarName,bool bDelete=false) = 0 ;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Set the y coordinate where the console will stop to scroll when is dropped
@param value y in screen coordinates
*/
virtual void SetScrollMax(int value)=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! add output sink (clases which are interested in the output) - order is not guaranteed
@param inpSink must not be 0 and is not allowed to be added twice
*/
virtual void AddOutputPrintSink( IOutputPrintSink *inpSink )=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! remove output sink (clases which are interested in the output) - order is not guaranteed
@param inpSink must not be 0 and has to be added before
*/
virtual void RemoveOutputPrintSink( IOutputPrintSink *inpSink )=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! show/hide the console
@param specifies if the window must be (true=show,false=hide)
*/
virtual void ShowConsole(bool show)=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Crate a new console variable that store the value in a user defined memory block
@param sName console variable name
@param src pointer to the memory that will store the value
@param value default value
@param type type of the value (can be CVAR_INT|CVAR_FLOAT)
@return the value
@see ICVar
*/
virtual int Register(const char *name, void *src, float defaultvalue, int flags, int type, const char *help = "")=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Crate a new console variable that store the value in a user defined floating point
@param sName console variable name
@param src pointer to the memory that will store the value
@param value default value
@return the value
@see ICVar
*/
virtual float Register(const char *name, float *src, float defaultvalue, int flags=0, const char *help = "")=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Crate a new console variable that store the value in a user defined integer
@param sName console variable name
@param src pointer to the memory that will store the value
@param value default value
@return the value
@see ICVar
*/
virtual int Register(const char *name, int *src, float defaultvalue, int flags=0, const char *help = "")=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Dump all console-variables to a callback-interface
@param Callback callback-interface which needs to be called for each element
*/
virtual void DumpCVars(ICVarDumpSink *pCallback,unsigned int nFlagsFilter=0 )=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Bind a console command to a key
@param sCmd console command that must be executed
@param sRes name of the key to invoke the command
@param bExecute legacy parameter(will be removed soon)
*/
virtual void CreateKeyBind(const char *sCmd,const char *sRes,bool bExecute)=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Sets the background-image
@param pImage background-image
*/
virtual void SetImage(struct ITexPic *pImage,bool bDeleteCurrent)=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Retrieves the background-image
@return background-image
*/
virtual struct ITexPic *GetImage()=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Sets static/scroll background-mode
@param bStatic true if static
*/
virtual void StaticBackground(bool bStatic)=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Sets the loading-background-image
@param pImage background-image
*/
virtual void SetLoadingImage( const char *szFilename )=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Iterate through the lines - used for dedicated server (truncated if needed)
@param indwLineNo 0.. counted from the last printed line on
@param outszBuffer pointer to the destination string buffer (zero terminted afterwards), must not be 0
@param indwBufferSize 1.. size of the buffer
@return true=line was returned, false=there are no more lines
*/
virtual bool GetLineNo( const DWORD indwLineNo, char *outszBuffer, const DWORD indwBufferSize ) const=0;
/*! @return current number of lines in the console
*/
virtual int GetLineCount() const=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Retrieve a console variable by name
@param sName variable name
@param bCaseSensitive true=faster, false=much slower but allowes names with wrong case (use only where performce doesn't matter)
@return a pointer to the ICVar interface, NULL if is not found
@see ICVar
*/
virtual ICVar* GetCVar( const char *name, const bool bCaseSensitive=true )=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! legacy function */
virtual CXFont *GetFont()=0;
/*! legacy function */
virtual void Help(const char *command = NULL)=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Read a value from a configuration file (.ini) and return the value
@param szVarName variable name
@param szFileName source configuration file
@param def_val default value (if the variable is not found into the file)
@return the variable value
*/
virtual char *GetVariable( const char * szVarName, const char * szFileName, const char * def_val )=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Read a value from a configuration file (.ini) and return the value
@param szVarName variable name
@param szFileName source configuration file
@param def_val default value (if the variable is not found into the file)
@return the variable value
*/
virtual float GetVariable( const char * szVarName, const char * szFileName, float def_val )=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Print a string in the console and go to the new line
@param s the string to print
*/
virtual void PrintLine(const char *s)=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Append a string in the last console line
@param s the string to print
*/
virtual void PrintLinePlus(const char *s)=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Retreive the status of the console (active/not active)
@return the variable value(true = active/false = not active)
*/
virtual bool GetStatus()=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Clear the console text
*/
virtual void Clear()=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Update the console
*/
virtual void Update()=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Draw the console
*/
virtual void Draw()=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Add a Console command
@param sName name of the command (ex "connect")
@param sScriptFunc script buffer the contain the command implementation
EG "Game.Connect(%1)" the symbol "%1" will be replaced with the command parameter 1
writing in the console "connect 127.0.0.1" will invoke Game.Connect("127.0.0.1")
@param indwFlags bitfield consist of VF_ flags (e.g. VF_CHEAT)
*/
virtual void AddCommand(const char *sName, const char *sScriptFunc, const DWORD indwFlags=0, const char *help = "") = 0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Execute a string in the console
@param command console command
*/
virtual void ExecuteString(const char *command,bool bNeedSlash=false,bool bIgnoreDevMode=false) = 0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Print a message into the log and abort the execution of the application
@param message error string to print in the log
*/
virtual void Exit(const char *command,...) = 0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Return true if the console is opened
@return the variable value(true = opened/false = closed)
*/
virtual bool IsOpened() = 0;
//////////////////////////////////////////////////////////////////////////
// Auto completion.
//////////////////////////////////////////////////////////////////////////
virtual int GetNumVars() = 0;
virtual void GetSortedVars( const char **pszArray,size_t numItems ) = 0;
virtual const char* AutoComplete( const char* substr ) = 0;
virtual const char* AutoCompletePrev( const char* substr ) = 0;
virtual char *ProcessCompletion( const char *szInputBuffer ) = 0;
//!
virtual void ResetAutoCompletion()=0;
virtual void DumpCommandsVars(char *prefix) = 0;
//! Calculation of the memory used by the whole console system
virtual void GetMemoryUsage (class ICrySizer* pSizer) = 0;
//! Function related to progress bar
virtual void ResetProgressBar(int nProgressRange) = 0;
//! Function related to progress bar
virtual void TickProgressBar() = 0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Dump all key bindings to a callback-interface
@param Callback callback-interface which needs to be called for each element
*/
virtual void DumpKeyBinds(IKeyBindDumpSink *pCallback )=0;
virtual const char* FindKeyBind( const char *sCmd ) = 0;
//////////////////////////////////////////////////////////////////////////
// Console variable sink.
//////////////////////////////////////////////////////////////////////////
//! Adds a new console variables sink callback.
virtual void AddConsoleVarSink( IConsoleVarSink *pSink )=0;
//! Removes a console variables sink callback.
virtual void RemoveConsoleVarSink( IConsoleVarSink *pSink )=0;
//////////////////////////////////////////////////////////////////////////
// History
//////////////////////////////////////////////////////////////////////////
//! \param bUpOrDown true=after pressed "up", false=after pressed "down"
//! \return 0 if there is no history line or pointer to the null terminated history line
virtual const char* GetHistoryElement( const bool bUpOrDown )=0;
//! \param szCommand must not be 0
virtual void AddCommandToHistory( const char *szCommand )=0;
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//! this interface is the 1:1 "C++ representation"
//! of a console variable.
//! NOTE: a console variable is accessible in C++ trough
//! this interface and in all scripts as global variable
//! (with the same name of the variable in the console)
struct ICVar
{
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! delete the variable
NOTE: the variable will automatically unregister itself from the console
*/
virtual void Release() = 0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Return the integer value of the variable
@return the value
*/
virtual int GetIVal() = 0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Return the float value of the variable
@return the value
*/
virtual float GetFVal() = 0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Return the string value of the variable
@return the value
*/
virtual char *GetString() = 0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! set the string value of the variable
@param s string representation the value
*/
virtual void Set(const char* s)=0;
/*! Force to set the string value of the variable - can be called
from inside code only
@param s string representation the value
*/
virtual void ForceSet(const char* s)=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! set the float value of the variable
@param s float representation the value
*/
virtual void Set(float f)=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! set the float value of the variable
@param s integer representation the value
*/
virtual void Set(int i)=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! refresh the values of the variable
*/
virtual void Refresh()=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! clear the specified bits in the flag field
*/
virtual void ClearFlags (int flags)=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! return the variable's flags
@return the variable's flags
*/
virtual int GetFlags()=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! Set the variable's flags
*/
virtual int SetFlags( int flags )=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! return the primary variable's type
@return the primary variable's type
*/
virtual int GetType()=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! return the variable's name
@return the variable's name
*/
virtual const char* GetName()=0;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*! return the variable's name
@return the variable's name
*/
virtual const char* GetHelp()=0;
};
#endif //_ICONSOLE_H_

1449
CryCommon/ICryAnimation.h Normal file

File diff suppressed because it is too large Load Diff

304
CryCommon/ICryPak.h Normal file
View File

@@ -0,0 +1,304 @@
// Interface to the crytek pack files management
#ifndef _ICRY_PAK_HDR_
#define _ICRY_PAK_HDR_
#include <smartptr.h>
#ifdef LINUX
#include <winbase.h>
#include <stdint.h>
#endif
// this represents one particular archive filcare
struct ICryArchive: public _reference_target_t
{
// Compression methods
enum ECompressionMethods
{
METHOD_STORE = 0,
METHOD_COMPRESS = 8,
METHOD_DEFLATE = 8
};
// Compression levels
enum ECompressionLevels
{
LEVEL_FASTEST = 0,
LEVEL_FASTER = 2,
LEVEL_NORMAL = 8,
LEVEL_BETTER = 8,
LEVEL_BEST = 9,
LEVEL_DEFAULT = -1
};
enum EPakFlags
{
// support for absolute and other complex path specifications -
// all paths will be treated relatively to the current directory (normally MasterCD)
FLAGS_ABSOLUTE_PATHS = 1,
// if this is set, the object will only understand relative to the zip file paths,
// but this can give an opportunity to optimize for frequent quick accesses
// FLAGS_SIMPLE_RELATIVE_PATHS and FLAGS_ABSOLUTE_PATHS are mutually exclusive
FLAGS_RELATIVE_PATHS_ONLY = 1 << 1,
// if this flag is set, the archive update/remove operations will not work
// this is useful when you open a read-only or already opened for reading files.
// If FLAGS_OPEN_READ_ONLY | FLAGS_SIMPLE_RELATIVE_PATHS are set, ICryPak
// will try to return an object optimized for memory, with long life cycle
FLAGS_READ_ONLY = 1 << 2,
// if this flag is set, FLAGS_OPEN_READ_ONLY
// flags are also implied. The returned object will be optimized for quick access and
// memory footprint
FLAGS_OPTIMIZED_READ_ONLY = (1 << 3),
// if this is set, the existing file (if any) will be overwritten
FLAGS_CREATE_NEW = 1 << 4,
// if this flag is set, and the file is opened for writing, and some files were updated
// so that the archive is no more continuous, the archive will nevertheless NOT be compacted
// upon closing the archive file. This can be faster if you open/close the archive for writing
// multiple times
FLAGS_DONT_COMPACT = 1 << 5,
// if this is set, CryPak doesn't try to transform the path according to the MOD subdirectories
FLAGS_IGNORE_MODS = 1 << 6
};
virtual ~ICryArchive(){}
// Summary:
// Adds a new file to the zip or update an existing one.
// Description:
// Adds a new file to the zip or update an existing one
// adds a directory (creates several nested directories if needed)
// compression methods supported are METHOD_STORE == 0 (store) and
// METHOD_DEFLATE == METHOD_COMPRESS == 8 (deflate) , compression
// level is LEVEL_FASTEST == 0 till LEVEL_BEST == 9 or LEVEL_DEFAULT == -1
// for default (like in zlib)
virtual int UpdateFile (const char* szRelativePath, void* pUncompressed, unsigned nSize, unsigned nCompressionMethod = 0, int nCompressionLevel = -1) = 0;
// Summary:
// Deletes the file from the archive.
virtual int RemoveFile (const char* szRelativePath) = 0;
// Summary:
// Deletes the directory, with all its descendants (files and subdirs).
virtual int RemoveDir (const char* szRelativePath) = 0;
// Summary:
// Deletes all files and directories in the archive.
virtual int RemoveAll() = 0;
typedef void* Handle;
// Summary:
// Finds the file; you don't have to close the returned handle.
// Returns:
// NULL if the file doesn't exist
virtual Handle FindFile (const char* szPath) = 0;
// Summary:
// Get the file size (uncompressed).
// Returns:
// The size of the file (unpacked) by the handle
virtual unsigned GetFileSize (Handle) = 0;
// Summary:
// Reads the file into the preallocated buffer
// Note:
// Must be at least the size returned by GetFileSize.
virtual int ReadFile (Handle, void* pBuffer) = 0;
// Summary:
// Get the full path to the archive file.
virtual const char* GetFullPath() const = 0;
// Summary:
// Get the flags of this object.
// Description:
// The possibles flags are defined in EPakFlags.
// See Also:
// SetFlags, ResetFlags
virtual unsigned GetFlags() const = 0;
// Summary:
// Sets the flags of this object.
// Description:
// The possibles flags are defined in EPakFlags.
// See Also:
// GetFlags, ResetFlags
virtual bool SetFlags(unsigned nFlagsToSet) = 0;
// Summary:
// Resets the flags of this object.
// See Also:
// SetFlags, GetFlags
virtual bool ResetFlags(unsigned nFlagsToSet) = 0;
// Summary:
// Determines if the archive is read only.
// Returns:
// true if this archive is read-only
inline bool IsReadOnly()const {return (GetFlags() & FLAGS_READ_ONLY) != 0;}
// Summary:
// Get the class id.
virtual unsigned GetClassId()const = 0;
};
TYPEDEF_AUTOPTR(ICryArchive);
// this special flag is used for findfirst/findnext routines
// to mark the files that were actually found in Archive
enum {_A_IN_CRYPAK = 0x80000000};
struct ICryPak
{
// Flags used in file path resolution rules
enum EPathResolutionRules
{
// If used, the source path will be treated as the destination path
// and no transformations will be done. Pass this flag when the path is to be the actual
// path on the disk/in the packs and doesn't need adjustment (or after it has come through adjustments already)
FLAGS_PATH_REAL = 1 << 16,
// AdjustFileName will always copy the file path to the destination path:
// regardless of the returned value, szDestpath can be used
FLAGS_COPY_DEST_ALWAYS = 1 << 17,
// Adds trailing slash to the path
FLAGS_ADD_TRAILING_SLASH = 1 << 18,
// Doesn't take mods into account
FLAGS_IGNORE_MOD_DIRS = 1 << 19,
// Search only in MODs; if not found, return NULL; may not be used with FLAGS_IGNORE_MOD_DIRS
FLAGS_ONLY_MOD_DIRS = 1 << 20
};
// Used for widening FOpen functionality. They're ignored for the regular File System files.
enum EFOpenFlags
{
// If possible, will prevent the file from being read from memory.
FOPEN_HINT_DIRECT_OPERATION = 1,
// Will prevent a "missing file" warnings to be created.
FOPEN_HINT_QUIET = 1 << 1
};
//! the size of the buffer that receives the full path to the file
enum {g_nMaxPath = 0x800};
// given the source relative path, constructs the full path to the file according to the flags
// returns the pointer to the constructed path (can be either szSourcePath, or szDestPath, or NULL in case of error
const char* AdjustFileName(const char *szSourcePath, char szDestPath[g_nMaxPath], unsigned nFlags = 0);
virtual bool Init (const char *szBasePath)=0;
virtual void Release()=0;
//! after this call, the pak file will be searched for files when they aren't on the OS file system
virtual bool OpenPack(const char *pName, unsigned nFlags = FLAGS_PATH_REAL)=0;
//! after this call, the pak file will be searched for files when they aren't on the OS file system
virtual bool OpenPack(const char* pBindingRoot, const char *pName, unsigned nFlags = FLAGS_PATH_REAL)=0;
//! after this call, the file will be unlocked and closed, and its contents won't be used to search for files
virtual bool ClosePack(const char* pName, unsigned nFlags = FLAGS_PATH_REAL) = 0;
//! opens pack files by the path and wildcard
virtual bool OpenPacks(const char *pWildcard, unsigned nFlags = FLAGS_PATH_REAL)=0;
//! opens pack files by the path and wildcard
virtual bool OpenPacks(const char* pBindingRoot, const char *pWildcard, unsigned nFlags = FLAGS_PATH_REAL)=0;
//! closes pack files by the path and wildcard
virtual bool ClosePacks(const char* pWildcard, unsigned nFlags = FLAGS_PATH_REAL) = 0;
//! adds a mod to the list
virtual void AddMod(const char* szMod)=0;
//! removes a mod from the list
virtual void RemoveMod(const char* szMod)=0;
struct PakInfo
{
struct Pak
{
const char* szFilePath;
const char* szBindRoot;
size_t nUsedMem;
};
// the number of packs in the arrPacks array
unsigned numOpenPaks;
// the packs
Pak arrPaks[1];
};
// returns an array of PackInfo structures inside OpenPacks structure
// you MUST call FreeOpenPackInfo
virtual PakInfo* GetPakInfo() = 0;
virtual void FreePakInfo (PakInfo*) = 0;
virtual FILE *FOpen(const char *pName, const char *mode, unsigned nFlags = 0)=0;
virtual FILE *FOpen(const char *pName, const char *mode,char *szFileGamePath,int nLen)=0;
virtual size_t FRead(void *data, size_t length, size_t elems, FILE *handle)=0;
virtual size_t FWrite(void *data, size_t length, size_t elems, FILE *handle)=0;
virtual int FSeek(FILE *handle, long seek, int mode)=0;
virtual long FTell(FILE *handle)=0;
virtual int FClose(FILE *handle)=0;
virtual int FEof(FILE *handle)=0;
virtual int FFlush(FILE *handle)=0;
//virtual int FScanf(FILE *, const char *, ...)=0;
virtual int FPrintf(FILE *handle, const char *format, ...)=0;
virtual char *FGets(char *, int, FILE *)=0;
virtual int Getc(FILE *)=0;
virtual int Ungetc(int c, FILE *)=0;
virtual intptr_t
FindFirst(
const char *pDir,
struct _finddata_t *fd
)=0;
virtual int FindNext(intptr_t handle, struct _finddata_t *fd)=0;
virtual int FindClose(intptr_t handle)=0;
// virtual bool IsOutOfDate(const char * szCompiledName, const char * szMasterFile)=0;
//returns file modification time
virtual FILETIME GetModificationTime(FILE*f)=0;
// creates a directory
virtual bool MakeDir (const char* szPath) = 0;
// open the physical archive file - creates if it doesn't exist
// returns NULL if it's invalid or can't open the file
// nFlags can have the following flag set:
// FLAGS_ABSOLUTE_PATHS
virtual ICryArchive* OpenArchive (const char* szPath, unsigned nFlags = FLAGS_PATH_REAL) = 0;
// returns the current game directory, with trailing slash (or empty string if it's right in MasterCD)
// this is used to support Resource Compiler which doesn't have access to this interface:
// in case all the contents is located in a subdirectory of MasterCD, this string is the subdirectory name with slash
//virtual const char* GetGameDir() = 0;
// returns the path to the archive in which the file was opened
// returns NULL if the file is a physical file, and "" if the path to archive is unknown (shouldn't ever happen)
virtual const char* GetFileArchivePath (FILE* f) = 0;
// compresses the raw data into raw data. The buffer for compressed data itself with the heap passed. Uses method 8 (deflate)
// returns one of the Z_* errors (Z_OK upon success)
// MT-safe
virtual int RawCompress (const void* pUncompressed, unsigned long* pDestSize, void* pCompressed, unsigned long nSrcSize, int nLevel = -1) = 0;
// Uncompresses raw (without wrapping) data that is compressed with method 8 (deflated) in the Zip file
// returns one of the Z_* errors (Z_OK upon success)
// This function just mimics the standard uncompress (with modification taken from unzReadCurrentFile)
// with 2 differences: there are no 16-bit checks, and
// it initializes the inflation to start without waiting for compression method byte, as this is the
// way it's stored into zip file
virtual int RawUncompress (void* pUncompressed, unsigned long* pDestSize, const void* pCompressed, unsigned long nSrcSize) = 0;
//////////////////////////////////////////////////////////////////////////
// Files collector.
//////////////////////////////////////////////////////////////////////////
typedef void (*RecordedFilesEnumCallback)( const char *filename );
//! Turn on/off recording of filenames of opened files.
virtual void RecordFileOpen( bool bEnable ) = 0;
//! Record this file if recording is enabled.
virtual void RecordFile( const char *szFilename ) = 0;
//! Get filenames of all recorded files.
virtual void EnumerateRecordedFiles( RecordedFilesEnumCallback enumCallback ) = 0;
};
#endif

97
CryCommon/IDataProbe.h Normal file
View File

@@ -0,0 +1,97 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2001-2004.
// -------------------------------------------------------------------------
// File name: IDataProbe.h
// Version: v1.00
// Created: 19/1/2004 by Timur.
// Compilers: Visual Studio.NET 2003
// Description: Defines IDataProbe interface.
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#ifndef __IDataProbe_h__
#define __IDataProbe_h__
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
struct SDataProbeContext
{
// Folder name to check.
string sFolder;
// Filename to check.
string sFilename;
void *pBuffer;
void *pModuleBaseAddress;
unsigned int nOffset;
unsigned int nSize;
// Algorithm used fo code.
unsigned int nCodeInfo;
// Resulting code.
uint64 nCode;
SDataProbeContext()
{
pBuffer = 0;
pModuleBaseAddress = 0;
nOffset = nSize = nCodeInfo = 0;
nCode = 0;
}
};
struct IDataProbe
{
struct SModuleInfo
{
string filename;
void* handle;
};
virtual ~IDataProbe() {};
virtual bool Dummy1( SDataProbeContext &ctx ) = 0;
virtual int Dummy2( void *pBuf,int aa,SDataProbeContext &ctx ) = 0;
virtual bool GetCode( SDataProbeContext &ctx ) = 0;
virtual bool Dummy3( SDataProbeContext &ctx ) = 0;
virtual bool GetRandomFileProbe( SDataProbeContext &ctx,bool bAtEnd )=0;
virtual bool GetRandomModuleProbe( SDataProbeContext &ctx ) = 0;
virtual bool GetModuleProbe( SDataProbeContext &ctx ) = 0;
// Hash of ASCII string.
virtual uint32 GetHash( const char *sString ) = 0;
// Hash of any buffer.
virtual uint32 GetHash( const void *buffer,int len ) = 0;
// Return array of loaded modules information, returns number of modules.
virtual int GetLoadedModules( SModuleInfo **pModules ) = 0;
virtual void AddModule( SModuleInfo &moduleInfo ) = 0;
virtual void RandomAlloc() = 0;
// Compress block of data with zlib.
virtual int Compress( void *dest,unsigned int &destLen,const void *source, unsigned int sourceLen,int level=6 ) = 0;
// Uncompress block of data with zlib.
virtual int Uncompress( void *dest,unsigned int &destLen,const void *source, unsigned int sourceLen ) = 0;
//////////////////////////////////////////////////////////////////////////
// MD5 Digest.
//////////////////////////////////////////////////////////////////////////
virtual void GetMD5( const char *pSrcBuffer,int nSrcSize,char signatureMD5[16] ) = 0;
// Decrypt buffer.
// Support in place decryption, (pSrcBuffer == pDestBuffer).
// Output buffer should be at least the same size as source buffer.
// Key must be at least 32 bytes long.
virtual void AESDecryptBuffer( const char *pSrcBuffer,int nSrcSize,char *pDestBuffer,int &nDestSize,const char *sKey ) = 0;
virtual void RandSeed( uint32 seed ) = 0;
virtual uint32 GetRand() = 0;
virtual float GetRand( float fMin,float fMax ) = 0;
};
#endif // __IDataProbe_h__

View File

@@ -0,0 +1,181 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2002.
// -------------------------------------------------------------------------
// File name: IEdgeVolumeBuilder.h
// Version: v0.60
// Created: 08/27/2002 by Martin Mittring
// Compilers: Visual Studio.NET
// Description:
// -------------------------------------------------------------------------
// History: interface extracted from Serg
//
////////////////////////////////////////////////////////////////////////////
#pragma once
#ifndef __IEDGE_CONNECTIVITYBUILDER_H
#define __IEDGE_CONNECTIVITYBUILDER_H
class IStencilShadowConnectivity;
class CStencilShadowConnectivity;
//
//
class IStencilShadowConnectivity
{
public:
typedef unsigned short vindex; // vertex index (0..0xffff)
//! don't forget to call Release for freeing the memory resources
virtual void Release( void )=0;
//! to keep the interface small and the access fast
//! /return pointer to the internal memory representation (only used within module 3DEngine)
const virtual CStencilShadowConnectivity *GetInternalRepresentation( void ) const=0;
//! for debugging and profiling
//! /param outVertexCount
//! /param outTriangleCount
virtual void GetStats( DWORD &outVertexCount, DWORD &outTriangleCount )=0;
//! Memorize the vertex buffer in this connectivity object. This is needed if a static object doesn't need this info
virtual void SetVertices(const Vec3d* pVertices, unsigned numVertices) = 0;
//! Serializes this object to the given memory block; if it's NULL, only returns
//! the number of bytes required. If it's not NULL, returns the number of bytes written
//! (0 means error, insufficient space)
virtual unsigned Serialize (bool bSave, void* pStream, unsigned nSize, IMiniLog* pWarningLog = NULL) = 0;
//! Calculates the size of this object
virtual void GetMemoryUsage(ICrySizer* pSizer) = 0;
//! If this returns true, then the meshing functions don't need external input of mesh information
//! This is for static objects only
virtual bool IsStandalone()const {return false;};
#ifdef WIN32
//! /param szFilename filename with path (or relative) and extension
//! /return true=success, false otherwise
virtual bool DebugConnectivityInfo( const char *szFilename )=0;
#endif
//! number of orphaned (open) edges
//! /return orphaned (open) count
virtual unsigned numOrphanEdges() const = 0;
};
// (don't copy the interface pointer and don't forget to call Release)
class IEdgeConnectivityBuilder
{
public:
typedef IStencilShadowConnectivity::vindex vindex;
virtual ~IEdgeConnectivityBuilder() {}
//! return to the state right after construction
virtual void Reinit( void )=0;
virtual void SetWeldTolerance (float fTolerance) {}
//! reserves space for the given number of triangles that are to be added
//! /param innNumTriangles
//! /param innNumVertices
virtual void ReserveForTriangles( unsigned innNumTriangles, unsigned innNumVertices )=0;
//! adds a single triangle to the mesh
//! the triangle is defined by three vertices, in counter-clockwise order
//! these vertex indices will be used later when accessing the array of
//! deformed character/model vertices to determine the shadow volume boundary
//! /param nV0 vertex index one 0..0xffff
//! /param nV1 vertex index two 0..0xffff
//! /param nV2 vertex index three 0..0xffff
virtual void AddTriangle( vindex nV0, vindex nV1, vindex nV2 )=0;
//! slower than AddTriangle but with the auto weld feature (if there are vertices with the same position your result is smaller and therefore faster)
//! /param nV0 vertex index one 0..0xffff
//! /param nV1 vertex index two 0..0xffff
//! /param nV2 vertex index three 0..0xffff
//! /param vV0 original vertex one position
//! /param vV1 original vertex two position
//! /param vV2 original vertex three position
virtual void AddTriangleWelded( vindex nV0, vindex nV1, vindex nV2, const Vec3d &vV0, const Vec3d &vV1, const Vec3d &vV2 )=0;
//! constructs/compiles the optimum representation of the connectivity
//! to be used in run-time
//! WARNING: use Release method to dispose the connectivity object
//! /return
virtual IStencilShadowConnectivity *ConstructConnectivity( void )=0;
//! returns the number of single (with no pair faces found) or orphaned edges
//! /return
virtual unsigned numOrphanedEdges( void ) const=0;
//! Returns the list of faces for orphaned edges into the given buffer;
//! For each orphaned edge, one face will be returned; some faces may be duplicated
virtual void getOrphanedEdgeFaces (unsigned* pBuffer)= 0;
//! return memory usage
virtual void GetMemoryUsage(class ICrySizer * pSizer) {} // todo: implement
};
// *****************************************************************
// used for runtime edge calculations
class IEdgeDetector
{
public:
virtual ~IEdgeDetector(){}
// vertex index
typedef unsigned short vindex;
//! for deformable objects
//! /param pConnectivity must not be 0 - don't use if there is nothing to do
//! /param invLightPos
//! /param pDeformedVertices must not be 0 - don't use if there is nothing to do
virtual void BuildSilhuetteFromPos( const IStencilShadowConnectivity* pConnectivity, const Vec3d &invLightPos, const Vec3d* pDeformedVertices )=0;
//! for undeformed objects)
//! /param outiNumTriangles, must not be 0 - don't use if there is nothing to do
//! /return pointer to the cleared (set to zero) bitfield where each bit represents the orientation of one triangle
virtual unsigned *getOrientationBitfield( int iniNumTriangles )=0;
//! /param pConnectivity must not be 0 - don't use if there is nothing to do
//! /param inpVertices must not be 0 - don't use if there is nothing to do
virtual void BuildSilhuetteFromBitfield( const IStencilShadowConnectivity* pConnectivity, const Vec3d* inpVertices )=0;
// pointer to the triplets defining shadow faces
virtual const vindex *getShadowFaceIndices( unsigned &outCount ) const=0;
//! O(1), returs the pointer to an array of unsigned short pairs of vertex numbers
virtual const vindex *getShadowEdgeArray( unsigned &outiNumEdges ) const=0;
//!
//! /return
virtual unsigned numShadowVolumeVertices( void ) const=0;
//! number of indices required to define the shadow volume,
//! use this to determine the size of index buffer passed to meshShadowVolume
//! this is always a dividend of 3
//! /return
virtual unsigned numShadowVolumeIndices( void ) const=0;
//! make up the shadow volume
//! constructs the shadow volume mesh, and puts the mesh definition into the
//! vertex buffer (vertices that define the mesh) and index buffer (triple
//! integers defining the triangular faces, counterclockwise order)
//! /param vLight
//! /param fFactor
//! /param outpVertexBuf The size of the vertex buffer must be at least numVertices()
//! /param outpIndexBuf The size of the index buffer must be at least numIndices()
virtual void meshShadowVolume (Vec3d vLight, float fFactor, Vec3d* outpVertexBuf, unsigned short* outpIndexBuf)=0;
//! get memory usage
virtual void GetMemoryUsage(class ICrySizer * pSizer) {}
};
#endif // __IEDGE_CONNECTIVITYBUILDER_H

View File

@@ -0,0 +1,281 @@
#ifndef IENTITYRENDERSTATE_H
#define IENTITYRENDERSTATE_H
template <class T> class list2;
// !!! don't change the type !!!
typedef unsigned short EntityId; //! unique identifier for each entity instance
struct IMatInfo;
struct IVisArea;
enum EERType
{
eERType_Unknown,
eERType_Brush,
eERType_Vegetation
};
struct OcclusionTestClient
{
OcclusionTestClient() { memset(this,0,sizeof(OcclusionTestClient)); bLastResult = true; }
unsigned char ucOcclusionByTerrainFrames;
unsigned char ucOcclusionByObjectsFrames;
bool bLastResult;
int nLastVisibleFrameID;
// class CREOcclusionQuery * arrREOcclusionQuery[2];
};
//! rendering properties/state of entity
//! 3dengine/indoor/ should not have access to the game specific actual IEntity
//! 3dengine only needs access to some functions
//! this is begin of big code cleaning
//! structure and names of classes not finilized
struct IEntityRenderState
{
IEntityRenderState()
{ // init vars
pShadowMapInfo = 0;
// nScissorX1=nScissorY1=nScissorX2=nScissorY2=0;
}
virtual ~IEntityRenderState()
{
delete pShadowMapInfo;
pShadowMapInfo=0;
}
// used for shadow maps
struct ShadowMapInfo{
ShadowMapInfo() { memset(this,0,sizeof(ShadowMapInfo)); }
void Release(enum EERType eEntType, struct IRenderer * pRenderer);
list2<struct ShadowMapLightSourceInstance> * pShadowMapCasters;
struct ShadowMapLightSource * pShadowMapFrustumContainer;
struct ShadowMapLightSource * pShadowMapFrustumContainerPassiveCasters;
list2<struct CLeafBuffer *> * pShadowMapLeafBuffersList;
Vec3 vPrevTerShadowPos;
float fPrevTerShadowRadius;
} * pShadowMapInfo;
// tmp flaot (distance to the light source, used for sorting)
float fTmpDistance;
// unsigned short nScissorX1, nScissorY1, nScissorX2, nScissorY2;
unsigned int nStrongestLightId;
};
//! EntityRender flags
#define ERF_SELFSHADOW 0x1
#define ERF_CASTSHADOWVOLUME 0x2
#define ERF_RECVSHADOWMAPS 0x4
#define ERF_CASTSHADOWMAPS 0x8
#define ERF_DONOTCHECKVIS 0x10
#define ERF_CASTSHADOWINTOLIGHTMAP 0x20
#define ERF_HIDABLE 0x40
#define ERF_HIDDEN 0x80
#define ERF_SELECTED 0x100
#define ERF_USELIGHTMAPS 0x200
#define ERF_OUTDOORONLY 0x400
#define ERF_UPDATE_IF_PV 0x800
#define ERF_EXCLUDE_FROM_TRIANGULATION 0x1000
#define ERF_MERGED 0x2000
#define ERF_RECVSHADOWMAPS_ACTIVE 0x4000
#define ERF_PHYS_NONCOLL 0x8000
#define ERF_MERGED_NEW 0x10000
#define ERF_FIRST_PERSON_CAMERA_OWNER 0x20000
// Should be the same as FOB_ flags
#define ERF_NOTRANS_ROTATE 0x10000000
#define ERF_NOTRANS_SCALE 0x20000000
#define ERF_NOTRANS_TRANSLATE 0x40000000
#define ERF_NOTRANS_MASK (ERF_NOTRANS_ROTATE | ERF_NOTRANS_SCALE | ERF_NOTRANS_TRANSLATE)
struct IEntityRender
{
IEntityRender()
{
m_dwRndFlags = 0;
m_pEntityRenderState = 0;
m_narrDrawFrames[0] = m_narrDrawFrames[1] = 0;
m_narrShadowFrames[0] = m_narrShadowFrames[1] = 0;
ucViewDistRatio=100;
ucLodRatio=100;
m_pSector = 0;
m_pVisArea=0;
m_vWSBoxMin=m_vWSBoxMax=Vec3(0,0,0);
m_fWSMaxViewDist=m_fWSRadius=0;
m_arrfDistance[0] = m_arrfDistance[1] = 0;
m_nFogVolumeID = 0;
m_bForceBBox = 0;
}
virtual const char * GetEntityClassName() const = 0;
virtual const Vec3 & GetPos(bool bWorldOnly = true) const = 0;
virtual const Vec3 & GetAngles(int realA=0) const = 0;
virtual float GetScale() const = 0;
virtual const char *GetName() const = 0;
virtual void GetRenderBBox( Vec3 &mins,Vec3 &maxs ) = 0;
virtual void GetBBox( Vec3 &mins,Vec3 &maxs ) { GetRenderBBox( mins, maxs ); }
virtual float GetRenderRadius() const = 0;
virtual bool HasChanged() { return false; }
virtual bool DrawEntity(const struct SRendParams & EntDrawParams) = 0;
virtual bool IsStatic() const = 0;
virtual struct IStatObj * GetEntityStatObj( unsigned int nSlot, Matrix44 * pMatrix = NULL, bool bReturnOnlyVisible = false) { return 0; }
virtual void SetEntityStatObj( unsigned int nSlot, IStatObj * pStatObj, Matrix44 * pMatrix = NULL ) {};
virtual struct ICryCharInstance* GetEntityCharacter( unsigned int nSlot, Matrix44 * pMatrix = NULL ) { return 0; }
virtual void Physicalize(bool bInstant=false) {}
virtual class CDLight * GetLight() { return 0; }
virtual struct IEntityContainer* GetContainer() const { return 0; }
float m_fWSMaxViewDist;
// rendering flags
virtual void SetRndFlags(unsigned int dwFlags) { m_dwRndFlags = dwFlags; }
virtual void SetRndFlags(unsigned int dwFlags, bool bEnable)
{ if(bEnable) m_dwRndFlags |= dwFlags; else m_dwRndFlags &= ~dwFlags; }
virtual unsigned int GetRndFlags() { return m_dwRndFlags; }
int m_dwRndFlags;
// object draw frames (set if was drawn)
void SetDrawFrame( int nFrameID, int nRecursionLevel ) { m_narrDrawFrames[nRecursionLevel] = nFrameID; }
int GetDrawFrame( int nRecursionLevel = 0 ) const{ return m_narrDrawFrames[nRecursionLevel]; }
int m_narrDrawFrames[2];
// shadow draw frames (set if was drawn)
void SetShadowFrame( unsigned short nFrameID, int nRecursionLevel ) { m_narrShadowFrames[nRecursionLevel] = nFrameID; }
unsigned short GetShadowFrame( int nRecursionLevel = 0 ) const{ return m_narrShadowFrames[nRecursionLevel]; }
// current distance to the camera (with reqursioin)
float m_arrfDistance[2];
//! contains rendering properties, not 0 only if entity going to be rendered
struct IEntityRenderState * m_pEntityRenderState;
unsigned short m_narrShadowFrames[2];
Vec3 m_vWSBoxMin, m_vWSBoxMax;
float m_fWSRadius;
//## float m_fMaxViewDist;
unsigned char m_bForceBBox;
unsigned char ucViewDistRatio;
unsigned char ucLodRatio;
unsigned char m_nFogVolumeID;
// cur areas info
struct CSectorInfo* m_pSector;
struct CVisArea * m_pVisArea;
// Used for occlusion culling
OcclusionTestClient OcclState;
//! Access to the EntityRenderState for 3dengine
IEntityRenderState * & GetEntityRS() { return m_pEntityRenderState; }
//## Lightmaps (here dot3lightmaps only)
// Summary:
// Assigns a texture set reference for dot3 lightmapping. The object will Release() it at the end of its lifetime
virtual void SetLightmap(struct RenderLMData * pLMData, float *pTexCoords, UINT iNumTexCoords, int nLod=0) {};
// Summary:
// Assigns a texture set reference for dot3 lightmapping. The object will Release() it at the end of its lifetime, special call from lightmap serializer/compiler to set occlusion map values
virtual void SetLightmap(RenderLMData *pLMData, float *pTexCoords, UINT iNumTexCoords, const unsigned char cucOcclIDCount, const std::vector<std::pair<EntityId, EntityId> >& aIDs){};
// Returns:
// true if there are lightmap texture coodinates and a lightmap texture assignment
virtual bool HasLightmap(int nLod) { return false; };
// Returns:
// Lightmap texture set for this object, or NULL if there's none assigned. Don't release obtained copy, it's not a reference
// See Also:
// SetLightmap
virtual RenderLMData * GetLightmap(int nLod) { return 0; };
// Summary:
// Returns vertex buffer holding instance specific texture coordinate set for dot3 lightmaps
virtual struct CLeafBuffer * GetLightmapTexCoord(int nLod) { return 0; };
virtual bool IsEntityHasSomethingToRender() = 0;
virtual bool IsEntityAreasVisible() = 0;
// Returns:
// Current VisArea or null if in outdoors or entity was not registered in 3dengine
IVisArea * GetEntityVisArea() { return (IVisArea*)m_pVisArea; }
/* Allows to adjust defailt max view distance settings,
if fMaxViewDistRatio is 100 - default max view distance is used */
void SetViewDistRatio(int nViewDistRatio) { ucViewDistRatio = min(254,max(0,nViewDistRatio)); }
/*! Makes object visible at any distance */
void SetViewDistUnlimited() { ucViewDistRatio = 255; }
// Summary:
// Retrieves the view distance settings
int GetViewDistRatio() { return (ucViewDistRatio==255) ? 1000l : ucViewDistRatio; }
//! return max view distance ratio
virtual float GetViewDistRatioNormilized() { return 0.01f*GetViewDistRatio(); }
/*! Allows to adjust defailt lod distance settings,
if fLodRatio is 100 - default lod distance is used */
void SetLodRatio(int nLodRatio) { ucLodRatio = min(255,max(0,nLodRatio)); }
//! return lod distance ratio
float GetLodRatioNormilized() { return 0.01f*ucLodRatio; }
// get/set physical entity
virtual class IPhysicalEntity* GetPhysics() const = 0;
virtual void SetPhysics( IPhysicalEntity* pPhys ) = 0;
virtual ~IEntityRender() {};
//! Set override material for this instance.
virtual void SetMaterial( IMatInfo *pMatInfo ) = 0;
//! Query override material of this instance.
virtual IMatInfo* GetMaterial() const = 0;
virtual int GetEditorObjectId() { return 0; }
virtual void SetEditorObjectId(int nEditorObjectId) {}
//! Physicalize if it isn't already
virtual void CheckPhysicalized() {};
virtual int DestroyPhysicalEntityCallback(IPhysicalEntity *pent) { return 0; }
virtual void SetStatObjGroupId(int nStatObjInstanceGroupId) { }
virtual float GetMaxViewDist() { return 0; }
virtual void Serialize(bool bSave, struct ICryPak * pPak, FILE * f) {}
virtual EERType GetEntityRenderType() { return eERType_Unknown; }
virtual void Dephysicalize( ) {}
virtual void Dematerialize( ) {}
virtual int GetMemoryUsage() { return 0; }
virtual list2<struct ShadowMapLightSourceInstance> * GetShadowMapCasters()
{
if(m_pEntityRenderState && m_pEntityRenderState->pShadowMapInfo)
return m_pEntityRenderState->pShadowMapInfo->pShadowMapCasters;
return 0;
}
virtual struct ShadowMapLightSource * GetShadowMapFrustumContainer()
{
if(m_pEntityRenderState && m_pEntityRenderState->pShadowMapInfo)
return m_pEntityRenderState->pShadowMapInfo->pShadowMapFrustumContainer;
return 0;
}
virtual struct ShadowMapLightSource * GetShadowMapFrustumContainerPassiveCasters()
{
if(m_pEntityRenderState && m_pEntityRenderState->pShadowMapInfo)
return m_pEntityRenderState->pShadowMapInfo->pShadowMapFrustumContainerPassiveCasters;
return 0;
}
virtual void PreloadInstanceResources(Vec3d vPrevPortalPos, float fPrevPortalDistance, float fTime) = 0;
virtual void Precache() {};
};
#endif // IENTITYRENDERSTATE_H

1615
CryCommon/IEntitySystem.h Normal file

File diff suppressed because it is too large Load Diff

175
CryCommon/IFont.h Normal file
View File

@@ -0,0 +1,175 @@
//////////////////////////////////////////////////////////////////////
//
// CryFont Source Code
//
// File: IFont.h
// Description: CryFont interface.
//
// History:
// - August 17, 2001: Created by Alberto Demichelis
//
//////////////////////////////////////////////////////////////////////
#ifndef CRYFONT_ICRYFONT_H
#define CRYFONT_ICRYFONT_H
#include <Cry_Color4.h>
#include <Cry_Math.h>
struct ISystem;
//////////////////////////////////////////////////////////////////////////////////////////////
// THE Only exported function of the DLL
// export for the dll, very clear ;=)
extern "C"
#if !defined(_XBOX) && !defined(LINUX)
#ifdef CRYFONT_EXPORTS
__declspec(dllexport)
#else
__declspec(dllimport)
#endif
#endif
struct ICryFont* CreateCryFontInterface(ISystem *pSystem);
typedef ICryFont *(*PFNCREATECRYFONTINTERFACE)(ISystem *pSystem);
//////////////////////////////////////////////////////////////////////////////////////////////
// Rendering interfaces
enum CRYFONT_RENDERINGINTERFACE
{
CRYFONT_RI_OPENGL = 0, // pRIData is ignored
CRYFONT_RI_LAST
};
//////////////////////////////////////////////////////////////////////////////////////////////
struct ICryFont
{
virtual void Release() = 0;
//! create a named font
virtual struct IFFont *NewFont(const char *pszName) = 0;
//! get a named font
virtual struct IFFont *GetFont(const char *pszName) = 0;
//! Puts the objects used in this module into the sizer interface
virtual void GetMemoryUsage (class ICrySizer* pSizer) = 0;
};
//////////////////////////////////////////////////////////////////////////////////////////////
#define TTFFLAG_SMOOTH_NONE 0x00000000 // no smooth
#define TTFFLAG_SMOOTH_BLUR 0x00000001 // smooth by bluring it
#define TTFFLAG_SMOOTH_SUPERSAMPLE 0x00000002 // smooth by rendering the characters into a bigger texture,
// and then resize it to the normal size using bilinear filtering
#define TTFFLAG_SMOOTH_MASK 0x0000000f // mask for retrieving
#define TTFFLAG_SMOOTH_SHIFT 0 // shift amount for retrieving
#define TTFLAG_SMOOTH_AMOUNT_2X 0x00010000 // blur / supersample [2x]
#define TTFLAG_SMOOTH_AMOUNT_4X 0x00020000 // blur / supersample [4x]
#define TTFFLAG_SMOOTH_AMOUNT_MASK 0x000f0000 // mask for retrieving
#define TTFFLAG_SMOOTH_AMOUNT_SHIFT 16 // shift amount for retrieving
// create a ttflag
#define TTFFLAG_CREATE(smooth, amount) ((((smooth) << TTFFLAG_SMOOTH_SHIFT) & TTFFLAG_SMOOTH_MASK) | (((amount) << TTFFLAG_SMOOTH_AMOUNT_SHIFT) & TTFFLAG_SMOOTH_AMOUNT_MASK))
#define TTFFLAG_GET_SMOOTH(flag) (((flag) & TTFLAG_SMOOTH_MASK) >> TTFFLAG_SMOOTH_SHIFT)
#define TTFFLAG_GET_SMOOTH_AMOUNT(flag) (((flag) & TTFLAG_SMOOTH_SMOUNT_MASK) >> TTFFLAG_SMOOTH_AMOUNT_SHIFT)
#define FONTRF_HCENTERED 0x80000000 // The font will be centered horizontaly around the x coo
#define FONTRF_VCENTERED 0x40000000 // The font will be centered verticaly around the y coo
#define FONTRF_FILTERED 0x20000000 // The font will be drawn with bilinear filtering
//////////////////////////////////////////////////////////////////////////////////////////////
struct IFFont
{
//! Reset the font to the default state
virtual void Reset() = 0;
virtual void Release() = 0;
//! Load a font from a TTF file
virtual bool Load(const char *szFile, unsigned long nWidth, unsigned long nHeight, unsigned long nTTFFlags) = 0;
//! Load a font from a XML file
virtual bool Load(const char *szFile) = 0;
//! Free the memory
virtual void Free() = 0;
//! Set the current effect to use
virtual void SetEffect(const char *szEffect) = 0;
// Set clipping rectangle
virtual void SetClippingRect(float fX, float fY, float fW, float fH) = 0;
// Enable / Disable clipping (off by default)
virtual void EnableClipping(bool bEnable) = 0;
//! Set the color of the current effect
virtual void SetColor(const color4f& col, int nPass = 0) = 0;
virtual void UseRealPixels(bool bRealPixels=true)=0;
virtual bool UsingRealPixels()=0;
//! Set the characters base size
virtual void SetSize(const vector2f &size) = 0;
//! Return the seted size
virtual vector2f &GetSize() = 0;
//! Return the char width
virtual float GetCharWidth() = 0;
//! Return the char height
virtual float GetCharHeight() = 0;
//! Set the same size flag
virtual void SetSameSize(bool bSameSize) = 0;
//! Get the same size flag
virtual bool GetSameSize() = 0;
//! Set the width scaling
virtual void SetCharWidthScale(float fScale = 1.0f) = 0;
//! Get the width scaling
virtual float GetCharWidthScale() = 0;
//! Draw a formated string
//! \param bASCIIMultiLine true='\','n' is a valid return, false=it's not
virtual void DrawString( float x, float y, const char *szMsg, const bool bASCIIMultiLine=true ) = 0;
//! Compute the text size
//! \param bASCIIMultiLine true='\','n' is a valid return, false=it's not
virtual vector2f GetTextSize(const char *szMsg, const bool bASCIIMultiLine=true ) = 0;
//! Draw a formated string
//! \param bASCIIMultiLine true='\','n' is a valid return, false=it's not
virtual void DrawStringW( float x, float y, const wchar_t *swStr, const bool bASCIIMultiLine=true ) = 0;
// Draw a formated string
virtual void DrawWrappedStringW( float x, float y, float w, const wchar_t *swStr, const bool bASCIIMultiLine=true ) = 0;
//! Compute the text size
//! \param bASCIIMultiLine true='\','n' is a valid return, false=it's not
virtual vector2f GetTextSizeW(const wchar_t *swStr, const bool bASCIIMultiLine=true ) = 0;
// Compute the text size
virtual vector2f GetWrappedTextSizeW(const wchar_t *swStr, float w, const bool bASCIIMultiLine=true ) = 0;
//! Compute virtual text-length (because of special chars...)
virtual int GetTextLength(const char *szMsg, const bool bASCIIMultiLine=true) = 0;
//! Compute virtual text-length (because of special chars...)
virtual int GetTextLengthW(const wchar_t *szwMsg, const bool bASCIIMultiLine=true) = 0;
//! Puts the memory used by this font into the given sizer
virtual void GetMemoryUsage (class ICrySizer* pSizer) = 0;
};
#endif // CRYFONT_ICRYFONT_H

331
CryCommon/IGame.h Normal file
View File

@@ -0,0 +1,331 @@
//////////////////////////////////////////////////////////////////////
//
// Game Source Code
//
// File: IGame.h
// Description: Game Interface.
//
// History:
// - 08/08/2001: Created by Alberto Demichelis
// - 09/24/2001: Modified by Petar Kotevski
// - 12/14/2003: MartinM made ClassID from unsigned char(8bit) to EntityClassId (16bit))
// - 27/04/2004: First cleanup by Mathieu Pinard
//
//////////////////////////////////////////////////////////////////////
#ifndef GAME_IGAME_H
#define GAME_IGAME_H
#if _MSC_VER > 1000
# pragma once
#endif
#ifdef WIN32
#ifdef CRYGAME_EXPORTS
#define CRYGAME_API __declspec(dllexport)
#else
#define CRYGAME_API __declspec(dllimport)
#endif
#else //WIN32
#define CRYGAME_API
#endif
#if defined(LINUX)
# include "platform.h"
# include "Cry_Math.h"
# include <vector>
#endif
//#include "IEntitySystem.h" // EntityClassId
#include <CryVersion.h>
#define PLAYER_CLASS_ID 1
#define ADVCAMSYSTEM_CLASS_ID 97 // is this the right place to put that define?
#define SPECTATOR_CLASS_ID 98 //
#define SYNCHED2DTABLE_CLASS_ID 205 //
//////////////////////////////////////////////////////////////////////////
typedef unsigned short EntityClassId; //< unique identifier for the entity class (defined in ClassRegistry.lua)
//////////////////////////////////////////////////////////////////////////
struct I3DEngine;
struct ISystem;
struct ITagPoint;
struct IXArea;
class CXArea;
struct IXAreaMgr;
class CXAreaMgr;
struct ILipSync;
struct ICVar;
class CXServer;
struct IBitStream;
class ICrySizer;
struct ISound;
struct IScriptObject;
struct IEntity;
/*
This structure stores the informations to identify an entity type
@see CEntityClassRegistry
*/
//////////////////////////////////////////////////////////////////////////
struct EntityClass
{
// type id
EntityClassId ClassId;
// class name inside the script file
string strClassName;
// script relative file path
string strScriptFile;
// script fully specified file path (Relative to root folder).
string strFullScriptFile;
// Game type of this entity (Ex. Weapon,Player).
string strGameType;
//specify that this class is not level dependent and is not loaded from LevelData.xml
bool bReserved;
//
bool bLoaded;
EntityClass() { ClassId = 0;bLoaded=false; }
// Copy constrctor required by STL containers.
EntityClass( const EntityClass &ec ) { *this = ec; }
// Copy operator required by STL containers.
EntityClass& operator=( const EntityClass &ec )
{
bReserved=ec.bReserved;
ClassId = ec.ClassId;
strClassName = ec.strClassName;
strScriptFile = ec.strScriptFile;
strFullScriptFile = ec.strFullScriptFile;
strGameType = ec.strGameType;
bLoaded=ec.bLoaded;
return *this;
}
};
/* This interface allow to load or create new entity types
@see CEntityClassRegistry
*/
struct IEntityClassRegistry
{
/*Retrieves an entity class by name
@param str entity name
@return EntityClass ptr if succeded, NULL if failed
*/
virtual EntityClass *GetByClass(const char *sClassName,bool bAutoLoadScript=true)= 0;
//virtual EntityClass *GetByClass(const string &str)= 0;
/*Retrieves an entity class by ClassId
@param ClassId class id
@return EntityClass ptr if succeded, NULL if failed
*/
virtual EntityClass *GetByClassId(const EntityClassId ClassId,bool bAutoLoadScript=true)= 0;
/*Adds a class type into the registry
@param ClassId class id
@param sClassName class name(into the script file)
@param sScriptFile script file path
@param pLog pointer to the log interface
@param bForceReload if set to true force script to be eloaded for already registered class.
@return true if added, false if failed
*/
virtual bool AddClass(const EntityClassId ClassId,const char* sClassName,const char* sScriptFile,bool bReserved=false,bool bForceReload=false) = 0;
/*move the iterator to the begin of the registry
*/
virtual void MoveFirst() = 0;
/*get the next entity class into the registry
@return a pointer to the next entityclass, or NULL if is the end
*/
virtual EntityClass *Next() = 0;
/*return the count of the entity classes
@return the count of the entity classes
*/
virtual int Count() = 0;
virtual bool LoadRegistryEntry(EntityClass *pClass, bool bForceReload=false) = 0;
// debug to OutputDebugString()
virtual void Debug()=0;
};
struct INameIterator
{
virtual void Release() = 0;
virtual void MoveFirst() = 0;
virtual bool MoveNext() = 0;
virtual bool Get(char *pszBuffer, INT *pSize) = 0;
};
class IPhysicsStreamer;
class IPhysicsEventClient;
//////////////////////////////////////////////////////////////////////////
// MOD related
// flags
#define MOD_NEWGAMEDLL 1L<<1 //tells if the MOD contains a replacement of CryGame.dll
// Description of the Game MOD.
//////////////////////////////////////////////////////////////////////////
struct SGameModDescription
{
// Constructor.
SGameModDescription()
{
dwFlags=0;
};
// Mod's name.
string sName;
// Mod's title.
string sTitle;
// Folder where this mod is located.
string sFolder;
// Mod's author.
string sAuthor;
// Mod Version.
SFileVersion version;
// Mod description.
string sDescription;
// Website.
string sWebsite;
// Mod flags
int dwFlags;
};
// Interface to access Game modifications parameters.
//////////////////////////////////////////////////////////////////////////
struct IGameMods
{
// Returns description of the currently active game mode.
// @returns NULL if the game mod is not found.
virtual const SGameModDescription* GetModDescription( const char *sModName ) const = 0;
// @returns name of the mod currently active, never returns 0
virtual const char* GetCurrentMod() const = 0;
// Sets the currently active game mod.
// @returns true if Mod is successfully set, false if Mod set failed.
virtual bool SetCurrentMod( const char *sModName,bool bNeedsRestart=false ) = 0;
// Returns modified path for the currently active mod/tc (if any)
// @returns true if there is an active mod, false otherwise
virtual const char* GetModPath(const char *szSource)= 0;
};
struct ITagPointManager
{
// This function creates a tag point in the game world
virtual ITagPoint *CreateTagPoint(const string &name, const Vec3 &pos, const Vec3 &angles) = 0;
// Retrieves a tag point by name
virtual ITagPoint *GetTagPoint(const string &name) =0;
// Deletes a tag point from the game
virtual void RemoveTagPoint(ITagPoint *pPoint) = 0;
virtual void AddRespawnPoint(ITagPoint *pPoint) = 0;
virtual void RemoveRespawnPoint(ITagPoint *pPoint) = 0;
};
enum EGameCapability
{
EGameMultiplayer = 1,
EGameClient,
EGameServer,
EGameDevMode,
};
// Exposes the basic functionality to initialize and run the game.
struct IGame
{
//########################################################################
//## EXTREMELY IMPORTANT: Do not modify anything below, else the binary
//## compatibility with the gold version of Far Cry
//## will be broken.
// Summary: Initialize game.
// Returns: true on success, false otherwise
virtual bool Init( struct ISystem *pSystem, bool bDedicatedSrv, bool bInEditor, const char *szGameMod ) = 0;
// Summary: Update the module and all subsystems
// Returns: false to stop the main loop
virtual bool Update() = 0;
// Summary: Run the main loop until another subsystem force the exit
// Returns: false to stop the main loop
virtual bool Run( bool &bRelaunch ) = 0;
// Summary: Determines if a MOD is currently loaded
// Returns: A string holding the name of the MOD if one is loaded, else
// NULL will be returned if only Far Cry is loaded.
virtual const char *IsMODLoaded() = 0;
// Returns interface to access Game Mod functionality.
virtual IGameMods* GetModsInterface() = 0;
//## EXTREMELY IMPORTANT: Do not modify anything above, else the binary
//## compatibility with the gold version of Far Cry
//## will be broken.
//########################################################################
//Shutdown and destroy the module (delete this)
virtual void Release() = 0;
// Executes scheduled events, called by system before executing each fixed time step in multiplayer
virtual void ExecuteScheduledEvents() = 0;
// Tells whether fixed timestep physics in multiplayer is on
virtual bool UseFixedStep() = 0;
// Snaps to to fixed step
virtual int SnapTime(float fTime,float fOffset=0.5f) = 0;
// Snaps to to fixed step
virtual int SnapTime(int iTime,float fOffset=0.5f) = 0;
// returns fixed MP step in physworld time granularity
virtual int GetiFixedStep() = 0;
// returns fixed MP step
virtual float GetFixedStep() = 0;
// Load level [level editor only]
// @param pszLevelDirectory level directory
virtual bool LoadLevelForEditor(const char *pszLevelDirectory, const char *pszMissionName = 0) = 0;
// Get the entity class regitry
virtual IEntityClassRegistry *GetClassRegistry() = 0;
virtual void OnSetVar(ICVar *pVar)=0;
virtual void SendMessage(const char *s)=0;
virtual void ResetState() = 0;
virtual void GetMemoryStatistics(ICrySizer *pSizer) = 0;
// saves player configuration
virtual void SaveConfiguration( const char *sSystemCfg,const char *sGameCfg,const char *sProfile)=0;
// This is used by editor for changing properties from scripts (no restart).
virtual void ReloadScripts()=0;
virtual bool GetModuleState( EGameCapability eCap ) = 0;
// functions return callback sinks for the physics
virtual IPhysicsStreamer *GetPhysicsStreamer() = 0;
virtual IPhysicsEventClient *GetPhysicsEventClient() = 0;
// is called from time to time during loading (usually network updates)
// currently only called for server map loading
virtual void UpdateDuringLoading()=0;
//virtual ITagPointManager* GetTagPointManager();
virtual IXAreaMgr* GetAreaManager() = 0;
virtual ITagPointManager* GetTagPointManager() = 0;
};
#ifdef GAME_IS_FARCRY
#include "IXGame.h"
#endif
typedef IGame* (*PFNCREATEGAMEINSTANCE)();
// interface of the DLL
extern "C" CRYGAME_API IGame* CreateGameInstance();
#endif // GAME_IGAME_H

912
CryCommon/IInput.h Normal file
View File

@@ -0,0 +1,912 @@
#ifndef _IINPUT_H_
#define _IINPUT_H_
#ifdef WIN32
#ifdef CRYINPUT_EXPORTS
#define CRYINPUT_API __declspec(dllexport)
#else
#define CRYINPUT_API __declspec(dllimport)
#endif
#else
#define CRYINPUT_API
#endif
#ifndef KEYS_DEF
#define KEYS_DEF
#include "platform.h"
#include "Cry_Math.h"
#include <vector>
////////////////////////////////////////////////////////////////////////////////////////////////
//! Keys' code names
////////////////////////////////////////////////////////////////////////////////////////////////
//#ifndef _XBOX
#define IS_NULL_KEY(key) ((key)==XKEY_NULL)
#define IS_MOUSE_KEY(key) ((key)&0x00FF0000)
#define IS_JOYPAD_KEY(key) ((key)&0xFF000000)
#define IS_GAMEPAD_KEY(key) ((key)&0xFF000000)
#define IS_KEYBOARD_KEY(key) ((key)&0x0000FFFF)
//////////////////////////////////////////////////////////////////////////
enum EKeyModifiersFlags
{
XKEY_MOD_NONE = 0,
XKEY_MOD_LCONTROL = 0x01,
XKEY_MOD_RCONTROL = 0x02,
XKEY_MOD_LALT = 0x04,
XKEY_MOD_RALT = 0x08,
XKEY_MOD_LSHIFT = 0x010,
XKEY_MOD_RSHIFT = 0x020,
XKEY_MOD_CAPSLOCK = 0x040,
XKEY_MOD_NUMLOCK = 0x080,
XKEY_MOD_CONTROL = (0x01 | 0x02),
XKEY_MOD_ALT = (0x04 | 0x08),
XKEY_MOD_SHIFT = (0x010 | 0x020),
};
//JOYPAD MOUSE KEYBOARD
// 00 00 0000
enum KeyCodes {
XKEY_NULL = 0x00000000, //forbidden
XKEY_BACKSPACE = 0x00000001,
XKEY_TAB = 0x00000002,
XKEY_RETURN = 0x00000003,
XKEY_CONTROL = 0x00000004,
XKEY_ALT = 0x00000005,
XKEY_SHIFT = 0x00000006,
XKEY_PAUSE = 0x00000007,
XKEY_CAPSLOCK = 0x00000008,
XKEY_ESCAPE = 0x00000009,
XKEY_SPACE = 0x0000000a,
XKEY_PAGE_DOWN = 0x0000000b,
XKEY_PAGE_UP = 0x0000000c,
XKEY_END = 0x0000000d,
XKEY_HOME = 0x0000000e,
XKEY_LEFT = 0x0000000f,
XKEY_UP = 0x00000010,
XKEY_RIGHT = 0x00000011,
XKEY_DOWN = 0x00000012,
XKEY_PRINT = 0x00000013,
XKEY_INSERT = 0x00000014,
XKEY_DELETE = 0x00000015,
XKEY_HELP = 0x00000016,
XKEY_0 = 0x00000017,
XKEY_1 = 0x00000018,
XKEY_2 = 0x00000019,
XKEY_3 = 0x0000001a,
XKEY_4 = 0x0000001b,
XKEY_5 = 0x0000001c,
XKEY_6 = 0x0000001d,
XKEY_7 = 0x0000001e,
XKEY_8 = 0x0000001f,
XKEY_9 = 0x00000020,
XKEY_A = 0x00000021,
XKEY_B = 0x00000022,
XKEY_C = 0x00000023,
XKEY_D = 0x00000024,
XKEY_E = 0x00000025,
XKEY_F = 0x00000026,
XKEY_G = 0x00000027,
XKEY_H = 0x00000028,
XKEY_I = 0x00000029,
XKEY_J = 0x0000002a,
XKEY_K = 0x0000002b,
XKEY_L = 0x0000002c,
XKEY_M = 0x0000002d,
XKEY_N = 0x0000002e,
XKEY_O = 0x0000002f,
XKEY_P = 0x00000030,
XKEY_Q = 0x00000031,
XKEY_R = 0x00000032,
XKEY_S = 0x00000033,
XKEY_T = 0x00000034,
XKEY_U = 0x00000035,
XKEY_V = 0x00000036,
XKEY_W = 0x00000037,
XKEY_X = 0x00000038,
XKEY_Y = 0x00000039,
XKEY_Z = 0x0000003a,
XKEY_TILDE = 0x0000003b,
XKEY_MINUS = 0x0000003c,
XKEY_EQUALS = 0x0000003d,
XKEY_LBRACKET = 0x0000003e,
XKEY_RBRACKET = 0x0000003f,
XKEY_BACKSLASH = 0x00000040,
XKEY_SEMICOLON = 0x00000041,
XKEY_APOSTROPHE = 0x00000042,
XKEY_COMMA = 0x00000043,
XKEY_PERIOD = 0x00000044,
XKEY_SLASH = 0x00000045,
XKEY_NUMPAD0 = 0x00000046,
XKEY_NUMPAD1 = 0x00000047,
XKEY_NUMPAD2 = 0x00000048,
XKEY_NUMPAD3 = 0x00000049,
XKEY_NUMPAD4 = 0x0000004a,
XKEY_NUMPAD5 = 0x0000004b,
XKEY_NUMPAD6 = 0x0000004c,
XKEY_NUMPAD7 = 0x0000004d,
XKEY_NUMPAD8 = 0x0000004e,
XKEY_NUMPAD9 = 0x0000004f,
XKEY_MULTIPLY = 0x00000050,
XKEY_ADD = 0x00000051,
XKEY_SEPARATOR = 0x00000052,
XKEY_SUBTRACT = 0x00000053,
XKEY_DECIMAL = 0x00000054,
XKEY_DIVIDE = 0x00000055,
XKEY_NUMPADENTER = 0x00000056,
XKEY_F1 = 0x00000057,
XKEY_F2 = 0x00000058,
XKEY_F3 = 0x00000059,
XKEY_F4 = 0x0000005a,
XKEY_F5 = 0x0000005b,
XKEY_F6 = 0x0000005c,
XKEY_F7 = 0x0000005d,
XKEY_F8 = 0x0000005e,
XKEY_F9 = 0x0000005f,
XKEY_F10 = 0x00000060,
XKEY_F11 = 0x00000061,
XKEY_F12 = 0x00000062,
XKEY_F13 = 0x00000063,
XKEY_F14 = 0x00000064,
XKEY_F15 = 0x00000065,
XKEY_F16 = 0x00000066,
XKEY_F17 = 0x00000067,
XKEY_F18 = 0x00000068,
XKEY_F19 = 0x00000069,
XKEY_F20 = 0x0000006a,
XKEY_F21 = 0x0000006b,
XKEY_F22 = 0x0000006c,
XKEY_F23 = 0x0000006d,
XKEY_F24 = 0x0000006e,
XKEY_NUMLOCK = 0x0000006f,
XKEY_SCROLLLOCK = 0x00000070,
XKEY_LCONTROL = 0x00000071,
XKEY_RCONTROL = 0x00000072,
XKEY_LALT = 0x00000073,
XKEY_RALT = 0x00000074,
XKEY_LSHIFT = 0x00000075,
XKEY_RSHIFT = 0x00000076,
XKEY_WIN_LWINDOW = 0x00000077,
XKEY_WIN_RWINDOW = 0x00000078,
XKEY_WIN_APPS = 0x00000079,
XKEY_OEM_102 = 0x00000080,
XKEY_BUTTON0 = 0x00000100,
XKEY_BUTTON1 = 0x00000101,
XKEY_BUTTON2 = 0x00000102,
XKEY_BUTTON3 = 0x00000103,
XKEY_BUTTON4 = 0x00000104,
XKEY_BUTTON5 = 0x00000105,
XKEY_BUTTON6 = 0x00000106,
XKEY_BUTTON7 = 0x00000107,
XKEY_BUTTON8 = 0x00000108,
XKEY_BUTTON9 = 0x00000109,
XKEY_BUTTON10 = 0x0000010A,
XKEY_BUTTON11 = 0x0000010B,
XKEY_BUTTON12 = 0x0000010C,
XKEY_BUTTON13 = 0x0000010D,
XKEY_BUTTON14 = 0x0000010E,
XKEY_BUTTON15 = 0x0000010F,
XKEY_BUTTON16 = 0x00000110,
XKEY_BUTTON17 = 0x00000111,
XKEY_BUTTON18 = 0x00000112,
XKEY_BUTTON19 = 0x00000113,
XKEY_BUTTON20 = 0x00000114,
XKEY_BUTTON21 = 0x00000115,
XKEY_BUTTON22 = 0x00000116,
XKEY_BUTTON23 = 0x00000117,
XKEY_BUTTON24 = 0x00000118,
XKEY_BUTTON25 = 0x00000119,
XKEY_BUTTON26 = 0x0000011A,
XKEY_BUTTON27 = 0x0000011B,
XKEY_BUTTON28 = 0x0000011C,
XKEY_BUTTON29 = 0x0000011D,
XKEY_BUTTON30 = 0x0000011E,
XKEY_BUTTON31 = 0x0000011F,
//MOUSE
XKEY_MOUSE1 = 0x00010000,
XKEY_MOUSE2 = 0x00020000,
XKEY_MOUSE3 = 0x00030000,
XKEY_MOUSE4 = 0x00040000,
XKEY_MOUSE5 = 0x00050000,
XKEY_MOUSE6 = 0x00060000,
XKEY_MOUSE7 = 0x00070000,
XKEY_MOUSE8 = 0x00080000,
XKEY_MWHEEL_UP = 0x00090000,
XKEY_MWHEEL_DOWN = 0x000A0000,
XKEY_MAXIS_X = 0x000B0000,
XKEY_MAXIS_Y = 0x000C0000,
//JOYPAD
//GAMEPAD
XKEY_GP_A = 0x01000000,
XKEY_GP_B = 0x02000000,
XKEY_GP_X = 0x03000000,
XKEY_GP_Y = 0x04000000,
XKEY_GP_BLACK = 0x05000000,
XKEY_GP_WHITE = 0x06000000,
XKEY_GP_LEFT_TRIGGER = 0x07000000,
XKEY_GP_RIGHT_TRIGGER = 0x08000000,
XKEY_GP_DPAD_UP = 0x11000000,
XKEY_GP_DPAD_DOWN = 0x12000000,
XKEY_GP_DPAD_LEFT = 0x13000000,
XKEY_GP_DPAD_RIGHT = 0x14000000,
XKEY_GP_START = 0x15000000,
XKEY_GP_BACK = 0x16000000,
XKEY_GP_LEFT_THUMB = 0x17000000,
XKEY_GP_RIGHT_THUMB = 0x18000000,
XKEY_GP_STHUMBLUP = 0x19000000,
XKEY_GP_STHUMBLDOWN = 0x1a000000,
XKEY_GP_STHUMBLLEFT = 0x1b000000,
XKEY_GP_STHUMBLRIGHT = 0x1c000000,
XKEY_GP_STHUMBLX = 0x21000000,
XKEY_GP_STHUMBLY = 0x22000000,
XKEY_GP_STHUMBRX = 0x23000000,
XKEY_GP_STHUMBRY = 0x24000000,
};
#ifndef _XBOX
#else
/////////XBOX VK_MAPPING
#define kSYSREQ 0x54
#define kCAPSLOCK 0x3A
#define kNUMLOCK 0x45
#define kSCROLLLOCK 0x46
#define kLEFTCTRL 0x1D
#define kLEFTALT 0x38
#define kLEFTSHIFT 0x2A
#define kRIGHTCTRL 0x9D
#define kRIGHTALT 0xB8
#define kRIGHTSHIFT 0x36
#define kESC 29
#define kBACKSPACE 0x0E
#define kENTER 0x1C
#define kSPACE ' '
#define kTAB 0x0F
#define kF1 0x3B
#define kF2 0x3C
#define kF3 0x3D
#define kF4 0x3E
#define kF5 0x3F
#define kF6 0x40
#define kF7 0x41
#define kF8 0x42
#define kF9 0x43
#define kF10 0x44
#define kF11 0x57
#define kF12 0x58
#define kA 65
#define kB 'b'
#define kC 'c'
#define kD 'd'
#define kE 'e'
#define kF 'f'
#define kG 'g'
#define kH 'h'
#define kI 0x17
#define kJ 0x24
#define kK 0x25
#define kL 0x26
#define kM 0x32
#define kN 0x31
#define kO 0x18
#define kP 0x19
#define kQ 'q'
#define kR 0x13
#define kS 0x1F
#define kT 0x14
#define kU 0x16
#define kV 0x2F
#define kW 'w'
#define kX 'x'
#define kY 'y'
#define kZ 'z'
#define k1 0x02
#define k2 0x03
#define k3 0x04
#define k4 0x05
#define k5 0x06
#define k6 0x07
#define k7 0x08
#define k8 0x09
#define k9 0x0A
#define k0 0x0B
#define kMINUS '-'
#define kEQUAL '='
#define kLBRACKET 0x1A
#define kRBRACKET 0x1B
#define kSEMICOLON 0x27
#define kTICK 29
#define kAPOSTROPHE 0x29
#define kBACKSLASH 0x2B
#define kCOMMA 0x33
#define kPERIOD '.'
#define kSLASH 0x35
#define kINS 0xD2
#define kDEL 0xD3
#define kHOME 0xC7
#define kEND 0xCF
#define kPGUP 0xC9
#define kPGDN 0xD1
#define kLARROW 0xCB
#define kRARROW 0xCD
#define kUARROW 0xC8
#define kDARROW 0xD0
#define kKEYPAD0 0x52
#define kKEYPAD1 0x4F
#define kKEYPAD2 0x50
#define kKEYPAD3 0x51
#define kKEYPAD4 0x4B
#define kKEYPAD5 0x4C
#define kKEYPAD6 0x4D
#define kKEYPAD7 0x47
#define kKEYPAD8 0x48
#define kKEYPAD9 0x49
#define kKEYPADDEL 0x53
#define kKEYPADSTAR 0x37
#define kKEYPADMINUS 0x4A
#define kKEYPADPLUS 0x4E
#define kKEYPADENTER 0x9C
#define kCTRLPRTSC 0xB7
#define kSHIFTPRTSC 0xB7
#define kKEYPADSLASH 0xB5
#endif //_XBOX
#endif
/*! Interface to the Keyboard system.
*/
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
struct IKeyboard
{
virtual void ShutDown() = 0;
//! allow to force a key code value
/// virtual void SetKey(int p_key, int value) = 0;
//! allow to force a key code value
//virtual inline void SetPrevKey(int p_key, int value) = 0;
//! check for key pressed and held
virtual bool KeyDown(int p_key) = 0;
//! check for key pressed only once
virtual bool KeyPressed(int p_key) = 0;
//! check if the key has been released
virtual bool KeyReleased(int p_key) = 0;
//! clear the key status
virtual void ClearKey(int p_key) =0 ;
//! return the code of the key pressed
virtual int GetKeyPressedCode() = 0;
//! return the name of the key pressed
virtual const char *GetKeyPressedName() = 0;
//! return the code of the key down
virtual int GetKeyDownCode() = 0;
//! return the name of the key down
virtual const char *GetKeyDownName() = 0;
//! set/unset directinput to exclusive mode
virtual void SetExclusive(bool value,void *hwnd=0) = 0;
//! wait for a key pressed
virtual void WaitForKey() = 0;
//! clear the key (pressed) state
virtual void ClearKeyState() = 0;
};
/*! Interface to the Mouse system.
*/
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
struct IMouse
{
virtual void Shutdown() = 0;
//! check for a mouse button pressed and held
virtual bool MouseDown(int p_numButton) = 0;
//! check for a mouse button pressed only once
virtual bool MousePressed(int p_numButton) = 0;
//! check if the mouse button has been released
virtual bool MouseReleased(int p_numButton) = 0;
//! force the mouse wheel rotation to a certain value
virtual void SetMouseWheelRotation(int value) = 0;
//! set/reset Directinput to exclusive mode
virtual bool SetExclusive(bool value,void *hwnd=0) = 0;
//! get mouse X delta (left-right)
virtual float GetDeltaX() = 0;
//! get mouse Y delta (up-down)
virtual float GetDeltaY() = 0;
//! get mouse Z delta (mouse wheel)
virtual float GetDeltaZ() = 0;
//! set mouse inertia
virtual void SetInertia(float) = 0;
//! set mouse X screen corrdinate
virtual void SetVScreenX(float fX) = 0;
//! set mouse Y screen corrdinate
virtual void SetVScreenY(float fY) = 0;
//! get mouse X screen corrdinate
virtual float GetVScreenX() = 0;
//! get mouse Y screen corrdinate
virtual float GetVScreenY() = 0;
//! set the mouse sensitivity
virtual void SetSensitvity(float fSensitivity) = 0;
//! get the mouse sensitivity
virtual float GetSensitvity() = 0;
//! set the mouse sensitivity scale (from 0 to 1)
virtual void SetSensitvityScale(float fSensScale) = 0;
//! get the mouse sensitivity scale
virtual float GetSensitvityScale() = 0;
//! clear the key states
virtual void ClearKeyState() = 0;
};
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
typedef int XACTIONID;
#define BEGIN_INPUTACTIONMAP() void OnAction(XACTIONID nActionID, float fValue,XActivationEvent ae) { switch(nActionID) {
#define END_INPUTACTIONMAP() default: break; } }
#define REGISTER_INPUTACTIONMAP(actionid, handler) case actionid: handler(fValue,ae); break;
#ifdef _XBOX
#define MAX_BINDS_PER_ACTION 3
#else
#define MAX_BINDS_PER_ACTION 2
#endif
enum XActionActivationMode
{
aamOnPress,
aamOnDoublePress,
aamOnPressAndRelease,
aamOnRelease,
aamOnHold
};
enum XActivationEvent
{
etPressing,
etHolding,
etReleasing,
etDoublePressing
};
struct XBind
{
XBind()
{
nKey=XKEY_NULL;
nModifier=XKEY_NULL;
// aam=aamOnPress;
// bConfigurable=false;
// bReplicate=false;
}
int nKey;
int nModifier;
// XActionActivationMode aam;
// bool bConfigurable;
// bool bReplicate;
};
struct IActionMapSink
{
virtual void OnAction(XACTIONID nActionID, float fValue, XActivationEvent ae) = 0;
};
struct IActionMap
{
virtual void ResetAllBindings() = 0;
virtual void ResetBinding(XACTIONID nActionID) = 0;
virtual void RemoveBind(XACTIONID nActionID, XBind &NewBind, XActionActivationMode aam) = 0;
virtual void BindAction(XACTIONID nActionID,XBind &NewBind, int iKeyPos = -1)=0;//int nKey,int nModifier=XKEY_NULL) = 0;
virtual void BindAction(XACTIONID nActionID,int nKey, int nModifier=XKEY_NULL, int iKeyPos = -1) = 0;//, bool bConfigurable=false, bool bReplicate=false) = 0;
virtual void BindAction(XACTIONID nActionID,const char *sKey,const char *sModifier=NULL, int iKeyPos = -1) = 0;
virtual void GetBinding(XACTIONID nActionID, int nKeyPos, XBind &Bind) = 0;
virtual void GetBinding(XACTIONID nActionID, int nKeyPos, int &nKey, int &nModifier) = 0;
virtual void GetBinding(XACTIONID nActionID, int nKeyPos, char *pszKey, char *pszModifier) = 0;
// compare this action map with the one passed and store the key differences in keys
virtual void GetBindDifferences(IActionMap *pActionMap, std::vector<int>& keys) = 0;
};
struct IActionMapDumpSink
{
virtual void OnElementFound(const char *pszActionMapName, IActionMap *pActionMap) = 0;
};
struct IActionMapManager
{
virtual void SetInvertedMouse(bool bEnable)=0;
virtual bool GetInvertedMouse()=0;;
virtual void RemoveBind(XACTIONID nActionID, XBind &NewBind, XActionActivationMode aam) = 0;
virtual void SetSink(IActionMapSink *pSink) = 0;
virtual void CreateAction(XACTIONID nActionID,const char *sActionName,XActionActivationMode aam=aamOnPress) = 0;
virtual IActionMap *CreateActionMap(const char *s) = 0;
virtual IActionMap *GetActionMap(const char *s) = 0;
virtual void ResetAllBindings() = 0;
virtual void GetActionMaps(IActionMapDumpSink *pCallback) = 0;
virtual void SetActionMap(const char *s) = 0;
virtual bool CheckActionMap(XACTIONID nActionID) = 0;
virtual bool CheckActionMap(const char *sActionName) = 0;
virtual void Reset() = 0;
virtual void Update(unsigned int nTimeMSec) = 0;
virtual void Release() = 0;
virtual void Enable() = 0;
virtual void Disable() = 0;
virtual bool IsEnabled() = 0;
};
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
typedef unsigned char INPUTACTIONID;
//@{ Helper macros to implement the action triggers callback interface
#define BEGIN_INPUTACTIONTRIGGERS() void OnAction(INPUTACTIONID nActionID, float fValue) { switch(nActionID) {
#define END_INPUTACTIONTRIGGERS() default: break; } }
#define REGISTER_INPUTACTIONTRIGGER(actionid, handler) case actionid: handler(fValue); break;
//@}
// Action triggers callback interface
struct IInputActionTriggerSink
{
virtual void OnAction(INPUTACTIONID nActionID, float fValue) = 0;
};
//! Action map interface
struct IInputActionMap
{
virtual void SetSink(IInputActionTriggerSink *pIActionTrigger) = 0;
virtual void Release() = 0;
//! Check all actions
virtual void Update() = 0;
// Call the action trigger
virtual void CallActionTrigger(INPUTACTIONID nActionID, float fValue) = 0;
//! Return the amount of pressing of the action input if the action is
//! currently done
virtual float CheckAction(const INPUTACTIONID nActionID) = 0;
/*! Set a new action
@param nActionID id that identity the action[eg. ACTION_JUMP]
@param bCheckPressed if true the action event is triggered only once when a button is pressed
else the action is send every frame until the button is released
@param szCodes key identifiers [eg. "MBT_1" mouse button]
@param szMods key modifier [eg. "SHIFT"]
@return true=succeded,false=failed*/
virtual bool SetAction(const INPUTACTIONID nActionID,bool bCheckPressed, const char *szCodes, const char *szMods=NULL) = 0;
virtual void ClearAction(const INPUTACTIONID nActionID) = 0;
};
//////////////////////////////////////////////////////////////////////
// Input interface for the XBox controller
//////////////////////////////////////////////////////////////////////
#ifdef _XBOX
//@{ XBox Input code enumerations and constants
enum eController
{
eOne = 0,
eTwo = 1,
eThree = 2,
eFour = 3,
ePrimary = 10,
eAll = 11,
};
enum eDigitalButton
{
eDigitalUp = XINPUT_GAMEPAD_DPAD_UP,
eDigitalDown = XINPUT_GAMEPAD_DPAD_DOWN,
eDigitalLeft = XINPUT_GAMEPAD_DPAD_LEFT,
eDigitalRight = XINPUT_GAMEPAD_DPAD_RIGHT,
eStart = XINPUT_GAMEPAD_START,
eBack = XINPUT_GAMEPAD_BACK,
eLeftStick = XINPUT_GAMEPAD_LEFT_THUMB,
eRightStick = XINPUT_GAMEPAD_RIGHT_THUMB,
};
enum eAnalogButton
{
eA = XINPUT_GAMEPAD_A,
eB = XINPUT_GAMEPAD_B,
eX = XINPUT_GAMEPAD_X,
eY = XINPUT_GAMEPAD_Y,
eBlack = XINPUT_GAMEPAD_BLACK,
eWhite = XINPUT_GAMEPAD_WHITE,
eLeftTrigger = XINPUT_GAMEPAD_LEFT_TRIGGER,
eRightTrigger = XINPUT_GAMEPAD_RIGHT_TRIGGER,
};
enum eSide
{
eLeft,
eRight,
};
const unsigned int MAX_XBOX_CONTROLLERS = 4;
const unsigned int XBOX_ANALOGSTICK_DEADZONE = 8000;
//@}
struct IGamepad
{
virtual void ShutDown() = 0;
//! check for a mouse button pressed and held
virtual bool KeyDown(int p_numButton) = 0;
//! check for a mouse button pressed only once
virtual bool KeyPressed(int p_numButton) = 0;
//! check if the mouse button has been released
virtual bool KeyReleased(int p_numButton) = 0;
//! get mouse X delta (left-right)
virtual float GetDeltaX() = 0;
//! get mouse Y delta (up-down)
virtual float GetDeltaY() = 0;
};
#endif //_XBOX
/*! InputEvents are generated by input system and broadcasted to all event listeners.
*/
struct SInputEvent
{
//! Input Event types.
enum EType
{
UNKNOWN,
KEY_PRESS,
KEY_RELEASE,
MOUSE_MOVE,
};
//! Type of input event.
EType type;
//! Key which was pressed or released, one of the XKeys.
//! @see KeyCodes
int key;
//! Timestamp of the event, (GetTickCount compatable).
unsigned int timestamp;
//! Key modifiers enabled at the time of this event.
//! @see EKeyModifiersFlags
int moidifiers;
//! Name of the event key.
const char *keyname;
//! For mouse axises.
float value;
SInputEvent()
{
moidifiers = XKEY_MOD_NONE;
key = 0;
type = UNKNOWN;
timestamp = 0;
keyname = 0;
value = 0;
}
};
//////////////////////////////////////////////////////////////////////////
/* Input event listeners registered to input system and recieve input events when they are generated.
*/
struct IInputEventListener
{
//! Called every time input event is generated.
//! @return if return True then broadcasting of this event should be aborted and the rest of input
//! listeners should not recieve this event.
virtual bool OnInputEvent( const SInputEvent &event ) = 0;
};
/*! Interface to the Input system.
The input system give access and initialize Keyboard,Mouse and Joystick SubSystems.
*/
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
/*! Main Input system interface.
*/
struct IInput
{
//////////////////////////////////////////////////////////////////////////
//! Register new input events listener.
virtual void AddEventListener( IInputEventListener *pListener ) = 0;
virtual void RemoveEventListener( IInputEventListener *pListener ) = 0;
virtual void EnableEventPosting ( bool bEnable ) = 0;
//! Register new console input event listeners. console input listeners receive all events, no matter what.
virtual void AddConsoleEventListener( IInputEventListener *pListener ) = 0;
virtual void RemoveConsoleEventListener( IInputEventListener *pListener ) = 0;
virtual void SetExclusiveListener( IInputEventListener *pListener ) = 0;
virtual IInputEventListener *GetExclusiveListener() = 0;
//////////////////////////////////////////////////////////////////////////
//! update Keyboard, Mouse and Joystick. Set bFocus to true if window has focus and input is enabled.
virtual void Update(bool bFocus) = 0;
//! clear all subsystems
virtual void ShutDown() = 0;
//! @see IMouse::SetExclusive
virtual void SetMouseExclusive(bool exclusive,void *hwnd=0) = 0;
//! @see IKeyboard::SetExclusive
virtual void SetKeyboardExclusive(bool exclusive,void *hwnd=0) = 0;
//! @see IKeyBoard::KeyDown
virtual bool KeyDown(int p_key) = 0;
//! @see IKeyBoard::KeyPressed
virtual bool KeyPressed(int p_key) = 0;
//! @see IKeyBoard::KeyRelease
virtual bool KeyReleased(int p_key) = 0;
//! @see IMouse::MouseDown
virtual bool MouseDown(int p_numButton) = 0;
//! @see IMouse::MousePressed
virtual bool MousePressed(int p_numButton) = 0;
//! @see IMouse::MouseDblClick
virtual bool MouseDblClick(int p_numButton) = 0;
//! @see IMouse::MouseReleased
virtual bool MouseReleased(int p_numButton) = 0;
//! @see IMouse::GetDeltaX
virtual float MouseGetDeltaX() = 0;
//! @see IMouse::GetDeltaY
virtual float MouseGetDeltaY() = 0;
//! @see IMouse::GetDeltaZ
virtual float MouseGetDeltaZ() = 0;
//! @see IMouse::GetVScreenX
virtual float MouseGetVScreenX() = 0;
//! @see IMouse::GetVScreenY
virtual float MouseGetVScreenY() = 0;
//! Converts a key-name to the key-id
virtual int GetKeyID(const char *sName) = 0;
virtual void EnableBufferedInput(bool bEnable) = 0;
virtual void FeedVirtualKey(int nVirtualKey,long lParam,bool bDown)=0;
virtual int GetBufferedKey() = 0;
virtual const char* GetBufferedKeyName() = 0;
virtual void PopBufferedKey() = 0;
//! @see IMouse::SetInertia
virtual void SetMouseInertia(float) = 0;
//! check if the joystick button has been pressed
virtual bool JoyButtonPressed(int p_numButton) = 0;
//! check the joystick direction
virtual int JoyGetDir() = 0;
//! check the joy hat direction
virtual int JoyGetHatDir() = 0;
virtual Vec3 JoyGetAnalog1Dir(unsigned int joystickID) const = 0;
virtual Vec3 JoyGetAnalog2Dir(unsigned int joystickID) const = 0;
//! return the keyboard interface
virtual IKeyboard *GetIKeyboard() = 0;
//! return the mouse interface
virtual IMouse * GetIMouse() = 0;
#ifdef _XBOX
//! return the Xbox gamepad interface
virtual IGamepad * GetIGamepad() = 0;
#endif
//! Convert key code to the key name.
//! @param nKey one of xkey codes.
//! @param modifiers current modifiers (shift,ctrl,..).
//! @see KeyCodes.
virtual const char *GetKeyName(int nKey,int modifiers=0, bool bGUI = 0) = 0;
virtual bool GetOSKeyName(int nKey, wchar_t *szwKeyName, int iBufSize) = 0;
//! @see IKeyBoard::GetKeyPressedCode
virtual int GetKeyPressedCode() = 0;
//! @see IKeyBoard::GetKeyPressedName
virtual const char *GetKeyPressedName() = 0;
//! @see IKeyBoard::GetKeyDownCode
virtual int GetKeyDownCode() = 0;
//! @see IKeyBoard::GetKeyDownName
virtual const char *GetKeyDownName() = 0;
//! @see IKeyBoard::WaitForKey
virtual void WaitForKey() = 0;
//! action mapper
virtual struct IActionMapManager* CreateActionMapManager() = 0;
//! return the name of the current XKEY(both mouse and keyboard excluding mouse delta)
//! useful for the GUI to retrieve the first key pressed during the key configuration
virtual const char *GetXKeyPressedName() = 0;
//! clear key states of all devices
virtual void ClearKeyState() = 0;
virtual unsigned char GetKeyState(int nKey) = 0;
};
#ifdef __cplusplus
extern "C" {
#endif
struct ILog;
struct IInput;
struct ISystem;
typedef IInput (* CRY_PTRCREATEINPUTFNC(ISystem *pSystem,void* hinst, void* hwnd, bool usedinput));
CRYINPUT_API IInput *CreateInput(ISystem *pSystem,void* hinst, void* hwnd, bool usedinput);
#ifdef __cplusplus
};
#endif
#endif //_IINPUT_H_

View File

@@ -0,0 +1,54 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2002.
// -------------------------------------------------------------------------
// File name: ILMSerializationManager.h
// Version: v1.00
// Created: 02/07/2003 by Sergiy Migdalskiy
// Compilers: Visual Studio.NET
// Description: LightMap Serialization interface
// -------------------------------------------------------------------------
// History:
// 02/07/2003 Extracted declaration from I3dEngine.h to be able to easy
// modify it
////////////////////////////////////////////////////////////////////////////
#ifndef _CRY_COMMON_LM_SERIALIZATION_MANAGER_HDR_
#define _CRY_COMMON_LM_SERIALIZATION_MANAGER_HDR_
#include <IEntitySystem.h>
//! \brief Interface for lightmap serialization
struct ILMSerializationManager
{
virtual void Release() = 0;
//!
virtual bool ApplyLightmapfile( const char *pszFileName, std::vector<struct IEntityRender *>& vIGLMs ) = 0;
//!
virtual bool Load( const char *pszFileName, const bool cbNoTextures ) = 0;
//!
virtual unsigned int Save( const char *pszFileName, struct LMGenParam sParams, const bool cbAppend = false ) = 0;
//!
//! /param _pColorLerp4 if !=0 this memory is copied
//! /param _pDomDirection3 if !=0 this memory is copied
virtual void AddRawLMData(
const DWORD indwWidth, const DWORD indwHeight, const std::vector<int>& _cGLM_IDs_UsingPatch,
BYTE *_pColorLerp4, BYTE *_pHDRColorLerp4, BYTE *_pDomDirection3, BYTE *_pOccl2) = 0;
//!
virtual void AddTexCoordData( const std::vector<struct TexCoord2Comp>& vTexCoords, int iGLM_ID_UsingTexCoord, const DWORD indwHashValue, const std::vector<std::pair<EntityId, EntityId> >& rOcclIDs) = 0;
//! for rebuild changes feature
//! /return 0x12341234 if this object wasn't in the list
virtual DWORD GetHashValue( const int iniGLM_ID_UsingTexCoord ) const=0;
//! Create a dot3 lightmap ColorLerp / DomDirection tetxure pair
virtual RenderLMData * CreateLightmap(const char *pszFileName, int nItem, UINT iWidth, UINT iHeight, BYTE *pColorLerp4, BYTE *pHDRColorLerp4, BYTE *pDomDirection3, BYTE *pOccl2 = 0)=0;
virtual bool ExportDLights(const char *pszFileName, const CDLight **ppLights, UINT iNumLights, bool bNewZip = true) const = 0;
};
#endif

31
CryCommon/ILipSync.h Normal file
View File

@@ -0,0 +1,31 @@
#ifndef ILIPSYNC_H
#define ILIPSYNC_H
struct CryCharMorphParams;
// callback interfaces
struct IDialogLoadSink
{
virtual void OnDialogLoaded(struct ILipSync *pLipSync)=0;
virtual void OnDialogFailed(struct ILipSync *pLipSync)=0;
};
struct ILipSync
{
virtual bool Init(ISystem *pSystem, IEntity *pEntity)=0; // initializes and prepares the character for lip-synching
virtual void Release()=0; // releases all resources and deletes itself
virtual bool LoadRandomExpressions(const char *pszExprScript, bool bRaiseError=true)=0; // load expressions from script
virtual bool UnloadRandomExpressions()=0; // release expressions
// loads a dialog for later playback
virtual bool LoadDialog(const char *pszFilename, int nSoundVolume, float fMinSoundRadius, float fMaxSoundRadius, float fClipDist, int nSoundFlags=0,IScriptObject *pAITable=NULL)=0;
virtual bool UnloadDialog()=0; // releases all resources
virtual bool PlayDialog(bool bUnloadWhenDone=true)=0; // plays a loaded dialog
virtual bool StopDialog()=0; // stops (aborts) a dialog
virtual bool DoExpression(const char *pszMorphTarget, CryCharMorphParams &MorphParams, bool bAnim=true)=0; // do a specific expression
virtual bool StopExpression(const char *pszMorphTarget)=0; // stop animating the specified expression
virtual bool Update(bool bAnimate=true)=0; // updates animation & stuff
virtual void SetCallbackSink(IDialogLoadSink *pSink)=0; // set callback sink (see above)
};
#endif // ILIPSYNC_H

175
CryCommon/ILog.h Normal file
View File

@@ -0,0 +1,175 @@
#ifndef _ILOG_H_
#define _ILOG_H_
#include "IMiniLog.h"
#if defined(LINUX)
#include "platform.h"
#endif
//////////////////////////////////////////////////////////////////////
#define LOG_TO_FILE (1L<<8)
#define LOG_TO_CONSOLE (2L<<8)
#define LOG_TO_FILE_PLUS (4L<<8) //
#define LOG_TO_CONSOLE_PLUS (8L<<8) //
#define LOG_TO_SCREEN (16L<<8)
#define LOG_TO_SCREEN_PLUS (32L<<8) //
#define LOG_TO_FILE_AND_CONSOLE (LOG_TO_FILE | LOG_TO_CONSOLE)
//verbosity levels
//////////////////////////////////////////////////////////////////////
// log verbosity levels are from 1 to 5 (default is 5, 1 for messages with "ERROR", 3 for messages with "WARNING")
// global verbosity levels are from 0 to 5
// LEVEL 1 - Critical messages. Only events that are critical for the proper operation of the game need to be logged at this level. This includes features - event that are critical for a feature to work MUST be logged at this level.
// LEVEL 2 - Artifact filter - This level is for events that will not affect the basic operation of the game, but might introduce artifacts (visual or in the way the features work).
// LEVEL 3 - Startup / Shutdown logs - Basically information when systems start and when they shutdown as well as some diagnostic information if you want.
// LEVEL 4 - Events that are used for debugging purposes (like entity spawned there and there, which sector of the building we are loading etc)
// LEVEL 5 - Everything else - including stuff like (x=40 y=30 z=30 five times a frame :)
// This means that clean verbosity 2 should guarantee a top notch run of the game.
// the console variable called log_Verbosity defines the verbosity
// level.
// With this option, the level of verbosity of the output is controlled.
// This option can be given multiple times to set the verbosity level to that value.
// The default global verbosity level is 0, in which no log messages will be displayed.
//
// Usage:
//
// e.g. System:Log("\001 This is log verbosity 1") for error
// e.g. System:Log("\002 This is log verbosity 2")
// e.g. System:Log("\003 This is log verbosity 3") for warning
// e.g. System:Log("\004 This is log verbosity 4")
// e.g. System:Log("\005 This is log verbosity 5")
//
// e.g. System:Log("\002 This is log verbosity 2")
// with global_verbosity_level 1 this is not printed but with global_verbosity_level 2 or higher it is
//////////////////////////////////////////////////////////////////////
struct ILog: public IMiniLog
{
virtual void Release() = 0;
//@param dwFlags must be a combination of priority and flags, i.e. (12 | LOG_TO_FILE)
//@param szCommand string to ouput to the log
// virtual void Log(int dwFlags,const char *szCommand,...)=0;
//set the file used to log to disk
virtual void SetFileName(const char *command = NULL) = 0;
//
virtual const char* GetFileName() = 0;
//all the following functions will be removed are here just to be able to compile the project ---------------------------
//will log the text both to file and console
virtual void Log(const char *szCommand,...)=0;
virtual void LogWarning(const char *szCommand,...)=0;
virtual void LogError(const char *szCommand,...)=0;
//will log the text both to the end of file and console
virtual void LogPlus(const char *command,...) = 0;
//log to the file specified in setfilename
virtual void LogToFile(const char *command,...) = 0;
//
virtual void LogToFilePlus(const char *command,...) = 0;
//log to console only
virtual void LogToConsole(const char *command,...) = 0;
//
virtual void LogToConsolePlus(const char *command,...) = 0;
//
virtual void UpdateLoadingScreen(const char *command,...) = 0;
//
virtual void UpdateLoadingScreenPlus(const char *command,...) = 0;
//
virtual void EnableVerbosity( bool bEnable ) = 0;
//
virtual void SetVerbosity( int verbosity ) = 0;
virtual int GetVerbosityLevel()=0;
};
//////////////////////////////////////////////////////////////////////
//#include <stdio.h>
//#include <stdlib.h>
#ifdef PS2
#include "File.h"
#endif
#ifdef _XBOX
inline void _ConvertNameForXBox(char *dst, const char *src)
{
//! On XBox d:\ represents current working directory (C:\MasterCD)
//! only back slash (\) can be used
strcpy(dst, "d:\\");
if (src[0]=='.' && (src[1]=='\\' || src[1]=='/'))
strcat(dst, &src[2]);
else
strcat(dst, src);
int len = strlen(dst);
for (int n=0; dst[n]; n++)
{
if ( dst[n] == '/' )
dst[n] = '\\';
if (n > 8 && n+3 < len && dst[n] == '\\' && dst[n+1] == '.' && dst[n+2] == '.')
{
int m = n+3;
n--;
while (dst[n] != '\\')
{
n--;
if (!n)
break;
}
if (n)
{
memmove(&dst[n], &dst[m], len-m+1);
len -= m-n;
n--;
}
}
}
}
#endif
//! Everybody should use fxopen instead of fopen
//! so it will work both on PC and XBox
inline FILE * fxopen(const char *file, const char *mode)
{
//SetFileAttributes(file,FILE_ATTRIBUTE_ARCHIVE);
// FILE *pFile = fopen("C:/MasterCD/usedfiles.txt","a");
// if (pFile)
// {
// fprintf(pFile,"%s\n",file);
// fclose(pFile);
// }
#ifdef _XBOX
char name[256];
_ConvertNameForXBox(name, file);
return fopen(name, mode);
#else
#if defined(LINUX)
return fopen_nocase(file, mode);
#else
return fopen(file, mode);
#endif //LINUX
#endif
}
#endif //_ILOG_H_

67
CryCommon/IMarkers.h Normal file
View File

@@ -0,0 +1,67 @@
#ifndef _IMARKERS_H_
#define _IMARKERS_H_
typedef struct ITagPoint
{
virtual void GetPos(Vec3 &pos) = 0;
virtual void SetPos(const Vec3 &pos) = 0;
virtual void GetAngles(Vec3 &angles) = 0;
virtual void SetAngles(const Vec3 &angles) = 0;
virtual bool SetName(const char *pName) = 0;
virtual char *GetName() = 0;
virtual void Release()= 0;
} ITagPoint;
struct IXArea
{
public:
virtual ~IXArea() {};
virtual void SetPoints(const Vec3* const vPoints, const int count) = 0;
virtual void SetID( const int id ) = 0;
virtual int GetID() const = 0;
virtual void SetGroup( const int id) = 0;
virtual int GetGroup( ) const = 0;
virtual void AddEntity( const char* const clsName ) = 0;
virtual void ClearEntities( ) = 0;
virtual void SetCenter( const Vec3& center ) = 0;
virtual void SetRadius( const float rad ) = 0;
virtual void SetMin( const Vec3& min ) = 0;
virtual void SetMax( const Vec3& max ) = 0;
virtual void SetTM( const Matrix44& TM ) = 0;
virtual void SetVOrigin( float org ) = 0;
virtual void SetVSize( float sz=0.0f ) = 0;
// virtual void SetEntityName( const char* const clsName ) = 0;
// virtual char* GetEntityName( ) = 0;
virtual void SetProximity( float prx ) = 0;
virtual float GetProximity( ) = 0;
};
struct IXAreaMgr
{
public:
virtual void RetriggerAreas() = 0;
virtual IXArea *CreateArea( const Vec3d *vPoints, const int count, const std::vector<string> &names,
const int type=0, const int groupId=-1, const float width=0.0f, const float height=0.0f) = 0;
virtual IXArea *CreateArea( const Vec3d& min, const Vec3d& max, const Matrix44& TM, const std::vector<string> &names,
const int type=0, const int groupId=-1, const float width=0.0f) = 0;
virtual IXArea *CreateArea( const Vec3d& center, const float radius, const std::vector<string> &names,
const int type=0, const int groupId=-1, const float width=0.0f) = 0;
virtual IXArea* GetArea( const Vec3& point ) = 0;
virtual void DeleteArea( const IXArea* aPtr ) = 0;
};
#endif// _IMARKERS_H_

83
CryCommon/IMiniLog.h Normal file
View File

@@ -0,0 +1,83 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2003.
// -------------------------------------------------------------------------
// File name: IMiniLog.h
// Version: v1.00
// Created: 03/6/2003 by Sergiy.
// Compilers: Visual Studio.NET
// Description: This is the smallest possible interface to the Log -
// it's independent and small, so that it can be easily moved
// across the engine and test applications, to test engine
// parts that need logging (e.g. Streaming Engine) separately
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#ifndef _CRY_ENGINE_MINI_LOG_HDR_
#define _CRY_ENGINE_MINI_LOG_HDR_
#include <stdarg.h>
struct IMiniLog
{
enum ELogType
{
eMessage,
eWarning,
eError,
eAlways,
eWarningAlways,
eErrorAlways,
eInput,
};
//! you only have to implement this function
virtual void LogV (const ELogType nType, const char* szFormat, va_list args) = 0;
// --------------------------------------------------------------------------
//! destructor
virtual ~IMiniLog() {}
//! this is the simplest log function for messages
//! with the default implementation
virtual void Log(const char * szFormat,...)
{
va_list args;
va_start(args,szFormat);
LogV (eMessage, szFormat, args);
va_end(args);
}
//! this is the simplest log function for warnings
//! with the default implementation
virtual void LogWarning(const char * szFormat,...)
{
va_list args;
va_start(args,szFormat);
LogV (eWarning, szFormat, args);
va_end(args);
}
//! this is the simplest log function for errors
//! with the default implementation
virtual void LogError(const char * szFormat,...)
{
va_list args;
va_start(args,szFormat);
LogV (eError, szFormat, args);
va_end(args);
}
};
// By default, to make it possible not to implement the log at the beginning at all,
// empty implementations of the two functions are given
struct CNullMiniLog: public IMiniLog
{
// the default implementation just won't do anything
void LogV(const char* szFormat, va_list args) {}
};
#endif //_CRY_ENGINE_MINI_LOG_HDR_

905
CryCommon/IMovieSystem.h Normal file
View File

@@ -0,0 +1,905 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2002.
// -------------------------------------------------------------------------
// File name: imoviesystem.h
// Version: v1.00
// Created: 26/4/2002 by Timur.
// Compilers: Visual Studio.NET
// Description:
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#ifndef __imoviesystem_h__
#define __imoviesystem_h__
#if _MSC_VER > 1000
#pragma once
#endif
#include "CryHeaders.h"
#include <Range.h>
#include <AnimKey.h>
// forward declaraton.
struct IAnimTrack;
struct IAnimNode;
struct IAnimSequence;
struct IMovieSystem;
struct IKey;
class XmlNodeRef;
struct IGame;
typedef IMovieSystem* (*PFNCREATEMOVIESYSTEM)(struct ISystem*);
#define MAX_ANIM_NAME_LENGTH 64
//! Very high priority for cut scene sounds.
#define MOVIE_SOUND_PRIORITY 230
typedef string AnimString;
typedef std::vector<IAnimSequence*> AnimSequences;
// Common parameters of animation node.
enum AnimParamType
{
APARAM_FOV = 0, //!< FOV parameter id.
APARAM_POS, //!< Position parameter id.
APARAM_ROT, //!< Rotation parameter id.
APARAM_SCL, //!< Scale parameter id.
APARAM_EVENT, //!< Entity parameter id.
APARAM_VISIBLE, //!< Visibilty parameter id.
APARAM_CAMERA, //!< Camera parameter id.
APARAM_SOUND1, //!< Sound1 parameter id.
APARAM_SOUND2, //!< Sound2 parameter id.
APARAM_SOUND3, //!< Sound3 parameter id.
APARAM_CHARACTER1, //!< Character animation layer 1 parameter id.
APARAM_CHARACTER2, //!< Character animation layer 2 parameter id.
APARAM_CHARACTER3, //!< Character animation layer 3 parameter id.
APARAM_SEQUENCE,//!< Sequence parameter id
APARAM_EXPRESSION1,//!< Expression1 parameter id
APARAM_EXPRESSION2,//!< Expression2 parameter id
APARAM_EXPRESSION3,//!< Expression3 parameter id
APARAM_CONSOLE, //!< Console Commands.
APARAM_MUSIC, //!< Music triggering
APARAM_FLOAT_1, //!< General float parameter.
APARAM_USER = 100, //!< User node params.
APARAM_LAST //!< Last paramater id, must be always last in this enum.
};
//! Types of animation track.
enum EAnimTrackType
{
ATRACK_TCB_FLOAT,
ATRACK_TCB_VECTOR,
ATRACK_TCB_QUAT,
ATRACK_BOOL,
ATRACK_EVENT,
ATRACK_SELECT,
ATRACK_CHARACTER,
ATRACK_SOUND,
ATRACK_EXPRESSION,
ATRACK_CONSOLE,
ATRACK_MUSIC
};
//! Values that animation track can hold.
enum EAnimValue
{
AVALUE_FLOAT,
AVALUE_VECTOR,
AVALUE_QUAT,
AVALUE_BOOL,
AVALUE_EVENT,
AVALUE_SELECT,
AVALUE_CHARACTER,
AVALUE_SOUND,
AVALUE_EXPRESSION,
AVALUE_CONSOLE,
AVALUE_MUSIC
};
//! Flags that can be set on animation track.
enum EAnimTrackFlags
{
ATRACK_LINEAR = 0x01, //!< Use only linear interpolation between keys.
ATRACK_LOOP = 0x02, //!< Play this track in a loop.
ATRACK_CYCLE = 0x04, //!< Cycle track.
//////////////////////////////////////////////////////////////////////////
// Used by editor.
//////////////////////////////////////////////////////////////////////////
ATRACK_HIDDEN = 0x010, //!< Set when track is hidden in track view.
};
//////////////////////////////////////////////////////////////////////////
//! Node-Types
enum EAnimNodeType
{
ANODE_ENTITY = 0x01,
ANODE_SCENE = 0x02,
ANODE_CAMERA = 0x03,
ANODE_CVAR = 0x04,
ANODE_SCRIPTVAR = 0x05,
ANODE_MATERIAL = 0x06,
};
//! Flags that can be set on animation node.
enum EAnimNodeFlags
{
//////////////////////////////////////////////////////////////////////////
// Used by editor.
//////////////////////////////////////////////////////////////////////////
ANODE_FLAG_EXPANDED = 0x01, //!< Set when all track of animation node is expanded in track view.
ANODE_FLAG_CAN_CHANGE_NAME = 0x02, //!< Set if this node allow changing of its name.
ANODE_FLAG_SELECTED = 0x02, //!< Set if this node selected in editor.
};
//! Structure passed to Animate function.
struct SAnimContext
{
SAnimContext()
{
bSingleFrame = false;
bResetting = false;
time = 0;
dt = 0;
fps = 0;
sequence = 0;
}
float time; //!< Current time in seconds.
float dt; //!< Delta of time from previous animation frame in seconds.
float fps; //!< Last calculated frames per second value.
bool bSingleFrame; //!< This is not a playing animation, more a single-frame update
bool bResetting; //!< Set when animation sequence is resetted.
IAnimSequence *sequence; //!< Sequence in which animation performed.
};
//! Interface for Sequence-iterator.
struct ISequenceIt
{
virtual void Release() = 0;
virtual void add( IAnimSequence* element ) = 0;
virtual void clear() = 0;
virtual bool empty() const = 0;
virtual int count() const = 0;
virtual IAnimSequence* first() = 0;
virtual IAnimSequence* next() = 0;
};
/** Parameters for cut-scene cameras
*/
struct SCameraParams
{
SCameraParams()
{
cameraNode = 0;
nCameraId = 0;
fFOV = 0.0f;
}
IAnimNode *cameraNode;
unsigned short nCameraId;
float fFOV;
};
//! Interface for movie-system implemented by user for advanced function-support
struct IMovieUser
{
//! Called when movie system requests a camera-change.
virtual void SetActiveCamera( const SCameraParams &Params ) = 0;
//! Called when movie system enters into cut-scene mode.
virtual void BeginCutScene(unsigned long dwFlags,bool bResetFX) = 0;
//! Called when movie system exits from cut-scene mode.
virtual void EndCutScene() = 0;
//! Called when movie system wants to send a global event.
virtual void SendGlobalEvent( const char *pszEvent ) = 0;
//! Called to play subtitles for specified sound.
virtual void PlaySubtitles( ISound *pSound ) = 0;
};
//! Animation parameter stored in animtion node.
struct SAnimParam
{
//! Name of this animation parameter.
char name[32];
//! Id of this parameter.
AnimParamType id;
//! Pointer to animation track assigned for this track.
IAnimTrack* track;
SAnimParam() { id=(AnimParamType)0;track=0; };
SAnimParam( const char *_name,AnimParamType _id,IAnimTrack *pTrack=0 ) { strcpy(name,_name); id = _id; track = pTrack; }
SAnimParam( const SAnimParam &anim ) { *this = anim; }
SAnimParam& operator=( const SAnimParam &anim )
{
strcpy(name,anim.name);
id = anim.id;
track = anim.track;
return *this;
}
};
//! Callback-reasons
enum ECallbackReason
{
CBR_ADDNODE,
CBR_REMOVENODE,
CBR_CHANGENODE,
CBR_REGISTERNODECB,
CBR_UNREGISTERNODECB
};
//! Callback-class
struct IMovieCallback
{
virtual void OnAddNode() = 0;
virtual void OnRemoveNode() = 0;
virtual void OnChangeNode() = 0;
virtual void OnRegisterNodeCallback() = 0;
virtual void OnUnregisterNodeCallback() = 0;
virtual void OnSetCamera( const SCameraParams &Params ) = 0;
};
//! Derive from this class to get reference counting for your class.
class IRefCountBase
{
public:
IRefCountBase() { m_refCount = 0; };
//! Add new refrence to this object.
unsigned long AddRef()
{
m_refCount++;
return m_refCount;
};
//! Release refrence to this object.
//! when reference count reaches zero, object is deleted.
unsigned long Release()
{
int refs = --m_refCount;
if (m_refCount <= 0)
delete this;
return refs;
}
protected:
virtual ~IRefCountBase() {};
private:
int m_refCount;
};
/** Interface of Animation Track.
*/
struct IAnimTrack : public IRefCountBase
{
virtual EAnimTrackType GetType() = 0;
virtual EAnimValue GetValueType() = 0;
//! Return number of keys in track.
virtual int GetNumKeys() = 0;
//! Set number of keys in track.
//! If needed adds empty keys at end or remove keys from end.
virtual void SetNumKeys( int numKeys ) = 0;
//! Remove specified key.
virtual void RemoveKey( int num ) = 0;
//! Get key at specified location.
//! @param key Must be valid pointer to compatable key structure, to be filled with specified key location.
virtual void GetKey( int index,IKey *key ) = 0;
//! Get time of specified key.
//! @return key time.
virtual float GetKeyTime( int index ) = 0;
//! Find key at givven time.
//! @return Index of found key, or -1 if key with this time not found.
virtual int FindKey( float time ) = 0;
//! Get flags of specified key.
//! @return key time.
virtual int GetKeyFlags( int index ) = 0;
//! Set key at specified location.
//! @param key Must be valid pointer to compatable key structure.
virtual void SetKey( int index,IKey *key ) = 0;
//! Set time of specified key.
virtual void SetKeyTime( int index,float time ) = 0;
//! Set flags of specified key.
virtual void SetKeyFlags( int index,int flags ) = 0;
//! Sort keys in track (after time of keys was modified).
virtual void SortKeys() = 0;
//! Get track flags.
virtual int GetFlags() = 0;
//! Set track flags.
virtual void SetFlags( int flags ) = 0;
//! Create key at givven time, and return its index.
//! @return Index of new key.
virtual int CreateKey( float time ) = 0;
//! Clone key at specified index.
//! @retun Index of new key.
virtual int CloneKey( int key ) = 0;
//! Clone key at specified index from another track of SAME TYPE.
//! @retun Index of new key.
virtual int CopyKey( IAnimTrack *pFromTrack, int nFromKey ) = 0;
//! Get info about specified key.
//! @param Short human readable text description of this key.
//! @param duration of this key in seconds.
virtual void GetKeyInfo( int key,const char* &description,float &duration ) = 0;
//////////////////////////////////////////////////////////////////////////
// Get track value at specified time.
// Interpolates keys if needed.
//////////////////////////////////////////////////////////////////////////
virtual void GetValue( float time,float &value ) = 0;
virtual void GetValue( float time,Vec3 &value ) = 0;
virtual void GetValue( float time,Quat &value ) = 0;
virtual void GetValue( float time,bool &value ) = 0;
//////////////////////////////////////////////////////////////////////////
// Set track value at specified time.
// Adds new keys if required.
//////////////////////////////////////////////////////////////////////////
virtual void SetValue( float time,const float &value,bool bDefault=false ) = 0;
virtual void SetValue( float time,const Vec3 &value,bool bDefault=false ) = 0;
virtual void SetValue( float time,const Quat &value,bool bDefault=false ) = 0;
virtual void SetValue( float time,const bool &value,bool bDefault=false ) = 0;
/** Assign active time range for this track.
*/
virtual void SetTimeRange( const Range &timeRange ) = 0;
/** Serialize this animation track to XML.
*/
virtual bool Serialize( XmlNodeRef &xmlNode,bool bLoading, bool bLoadEmptyTracks=true ) = 0;
protected:
virtual ~IAnimTrack() {};
};
/** Animation block stores info about animations for one node in one sequence.
*/
struct IAnimBlock : public IRefCountBase
{
/** Assign Id to this animation block.
*/
virtual void SetId( int id ) = 0;
/** Get id of this block.
*/
virtual int GetId() const = 0;
/** Return number of parameters in block.
*/
virtual int GetTrackCount() const = 0;
/** Return parameter type at index.
*/
virtual bool GetTrackInfo( int index,int &paramId,IAnimTrack **pTrack ) const = 0;
/** Creates a new track.
*/
virtual IAnimTrack* CreateTrack( int paramId,EAnimValue valueType ) = 0;
/** Retrieve first animation track assigned to parameter type.
*/
virtual IAnimTrack* GetTrack( int paramId ) const = 0;
/** Assign animation track to parameter.
if track parameter is NULL track with parameter id param will be removed.
*/
virtual void SetTrack( int paramId,IAnimTrack *track ) = 0;
/** Set time range for all tracks in this sequence.
*/
virtual void SetTimeRange( Range timeRange ) = 0;
/** Remove track from anim block.
*/
virtual bool RemoveTrack( IAnimTrack *pTrack ) = 0;
/** Serialize this animation block to XML.
*/
virtual void Serialize( IAnimNode *pNode,XmlNodeRef &xmlNode,bool bLoading, bool bLoadEmptyTracks=true ) = 0;
};
/** Callback called by animation node when its animated.
*/
struct IAnimNodeCallback
{
virtual void OnNodeAnimated() = 0;
};
/** Base class for all Animation nodes,
can host multiple animation tracks, and execute them other time.
Animation node is reference counted.
*/
struct IAnimNode : public IRefCountBase
{
virtual ~IAnimNode() {};
//! Set node name.
virtual void SetName( const char *name ) = 0;
//! Get node name.
virtual const char* GetName() = 0;
/** Get Type of this node.
*/
virtual EAnimNodeType GetType() const = 0;
/** Set AnimNode flags.
@param flags One or more flags from EAnimNodeFlags.
@see EAnimNodeFlags
*/
virtual void SetFlags( int flags ) = 0;
/** Get AnimNode flags.
@return flags set on node.
@see EAnimNodeFlags
*/
virtual int GetFlags() const = 0;
/** Create a new track in this node for current animation block.
*/
virtual IAnimTrack* CreateTrack( int nParamId ) = 0;
/** Remove a track from this node.
*/
virtual bool RemoveTrack( IAnimTrack *pTrack ) = 0;
/** Find a track in this node and return its ParamID.
@return ParamId of this track or -1 if track not found.
*/
virtual int FindTrack(IAnimTrack *pTrack) = 0;
// Description:
// Creates default set of tracks supported by this node.
virtual void CreateDefaultTracks() = 0;
/** Get Id of this node.
*/
virtual int GetId() const = 0;
/** Assign new Entity by Id to animation node (if entity isnt spawned yet it will be assigned when animation starts).
*/
virtual void SetEntity(int Id) = 0;
/** Assign new Entity to animation node.
*/
virtual void SetEntity( IEntity *entity ) = 0;
/** Get entity controlled by this animation node.
*/
virtual IEntity* GetEntity() = 0;
/** Return movie system that created this node.
*/
virtual IMovieSystem* GetMovieSystem() = 0;
/** Called when the node needs to be resetted (eg. when anim stops)
*/
virtual void Reset() = 0;
/** Called when owning sequence pauses.
*/
virtual void Pause() = 0;
/** Called when owning sequence resumes.
*/
virtual void Resume() = 0;
//////////////////////////////////////////////////////////////////////////
// Space position/orientation scale.
//////////////////////////////////////////////////////////////////////////
//! Translate entity node.
virtual void SetPos( float time,const Vec3 &pos ) = 0;
//! Rotate entity node.
virtual void SetRotate( float time,const Quat &quat ) = 0;
//! Scale entity node.
virtual void SetScale( float time,const Vec3 &scale ) = 0;
//! Get current entity position.
virtual Vec3 GetPos() = 0;
//! Get current entity rotation.
virtual Quat GetRotate() = 0;
//! Get current entity scale.
virtual Vec3 GetScale() = 0;
// General Set param.
// Set floating point parameter at givven time.
// @return true if parameter set, false if this paremeter not exist in node.
virtual bool SetParamValue( float time,AnimParamType param,float value ) = 0;
// Get floating param at current time.
// @return true if parameter exist, false if this paremeter not exist in node.
virtual bool GetParamValue( float time,AnimParamType param,float &value ) = 0;
/** Retrieve tranformation matrix of this node in world space.
Transformations of all parent nodes are included in returned matrix.
@param tm This matrix will be filled with node matrix.
*/
virtual void GetWorldTM( Matrix44 &tm ) = 0;
//////////////////////////////////////////////////////////////////////////
// Childs nodes.
//////////////////////////////////////////////////////////////////////////
//! Return true if node have childs.
virtual bool HaveChilds() const = 0;
//! Return true if have attached childs.
virtual int GetChildCount() const = 0;
//! Get child by index.
virtual IAnimNode* GetChild( int i ) const = 0;
//! Return parent node if exist.
virtual IAnimNode* GetParent() const = 0;
//! Scans hiearachy up to determine if we child of specified node.
virtual bool IsChildOf( IAnimNode *node ) = 0;
//! Attach new child node.
virtual void AttachChild( IAnimNode* child ) = 0;
//! Detach all childs of this node.
virtual void DetachAll() = 0;
// Detach this node from parent.
virtual void DetachThis() = 0;
//////////////////////////////////////////////////////////////////////////
// Target Look-At node.
//////////////////////////////////////////////////////////////////////////
//! Set look-at target node.
//! Node's matrix will always be oriented to look-at target node position with positive Y axis.
virtual void SetTarget( IAnimNode *node ) = 0;
//! Get current look-at target.
virtual IAnimNode* GetTarget() const = 0;
//! Evaluate animation to the givven time.
virtual void Animate( SAnimContext &ec ) = 0;
/** Retrieve animation block interface assigned to this node.
*/
virtual IAnimBlock* GetAnimBlock() const = 0;
/** Assign animation block to this node.
Node can not be animated untill assigned with an anim block.
*/
virtual void SetAnimBlock( IAnimBlock *block ) = 0;
//////////////////////////////////////////////////////////////////////////
// Supported params.
//////////////////////////////////////////////////////////////////////////
enum ESupportedParamFlags
{
PARAM_MULTIPLE_TRACKS = 0x01, // Set if parameter can be assigned multiple tracks.
};
struct SParamInfo
{
SParamInfo() : name(""),paramId(0),valueType(AVALUE_FLOAT),flags(0) {};
SParamInfo( const char *_name,int _paramId,EAnimValue _valueType,int _flags ) : name(_name),paramId(_paramId),valueType(_valueType),flags(_flags) {};
//////////////////////////////////////////////////////////////////////////
const char *name; // parameter name.
int paramId; // parameter id.
EAnimValue valueType; // value type, defines type of track to use for animating this parameter.
int flags; // combination of flags from ESupportedParamFlags.
};
// Description:
// Returns number of supported parameters by this animation node (position,rotation,scale,etc..).
// Returns:
// Number of supported parameters.
virtual int GetParamCount() const = 0;
// Description:
// Returns decription of supported parameter of this animation node (position,rotation,scale,etc..).
// Arguments:
// nIndex - parameter index in range 0 <= nIndex < GetSupportedParamCount()
virtual bool GetParamInfo( int nIndex, SParamInfo &info ) const = 0;
// Description:
// Finds param info with specified param id.
// Returns:
// true if parameter found, false overwise.
// Arguments:
// paramId - parameter id
// info - Filled with parameter info.
virtual bool GetParamInfoFromId( int paramId, SParamInfo &info ) const = 0;
// Description:
// Check if parameter is supported by this node.
// Returns:
// true if parameter supported, false overwise.
// Arguments:
// paramId - parameter id
virtual bool IsParamValid( int paramId ) const = 0;
/** Creates animation block compatable with this node.
*/
// virtual IAnimBlock* CreateAnimBlock() = 0;
/** Retrieve animation track assigned to parameter.
*/
virtual IAnimTrack* GetTrack( int nParamId ) const = 0;
/** Assign animation track to parameter.
*/
virtual void SetTrack( int nParamId,IAnimTrack *track ) = 0;
//////////////////////////////////////////////////////////////////////////
// Sink for animation node used by editor.
//////////////////////////////////////////////////////////////////////////
/** Register notification callback with animation node.
*/
virtual void RegisterCallback( IAnimNodeCallback *callback ) = 0;
/** Unregister notification callback from animation node.
*/
virtual void UnregisterCallback( IAnimNodeCallback *callback ) = 0;
/** Serialize this animation node to XML.
*/
virtual void Serialize( XmlNodeRef &xmlNode,bool bLoading ) = 0;
};
/** Animation sequence, operates on animation nodes contained in it.
*/
struct IAnimSequence : public IRefCountBase
{
//! Flags used for SetFlage(),GetFlags() methods.
enum Flags
{
PLAY_ONRESET = 0x001, //!< Start playing this sequence immidiatly after reset of movie system(Level load).
ORT_CONSTANT = 0x002, //!< Constant Out-Of-Range,time continues normally past sequence time range.
ORT_LOOP = 0x004, //!< Loop Out-Of-Range,time wraps back to the start of range when reaching end of range.
CUT_SCENE = 0x008, //!< Cut scene sequence.
NO_HUD = 0x010, //!< Dont display HUD
NO_PLAYER = 0x020, //!< Disable input and drawing of player
NO_PHYSICS = 0x040, //!< Dont update phyics
NO_AI = 0x080, //!< Dont update AI
IS_16TO9 = 0x100, //!< 16:9 bars in sequence
NO_GAMESOUNDS = 0x200, //!< Suppress all game sounds.
};
//! Set animation name.
virtual void SetName( const char *name ) = 0;
//! Get animation namr.
virtual const char* GetName() = 0;
virtual void SetFlags( int flags ) = 0;
virtual int GetFlags() const = 0;
//! Return number of animation nodes in sequence.
virtual int GetNodeCount() const = 0;
//! Get animation node at specified index.
virtual IAnimNode* GetNode( int index ) const = 0;
//! Get Animation assigned to node at specified index.
virtual IAnimBlock* GetAnimBlock( int index ) const = 0;
//! Add animation node to sequence.
//! @return True if node added, same node will not be added 2 times.
virtual bool AddNode( IAnimNode *node ) = 0;
//! Remove animation node from sequence.
virtual void RemoveNode( IAnimNode *node ) = 0;
//! Add scene node to sequence.
virtual IAnimNode* AddSceneNode() = 0;
//! Remove all nodes from sequence.
virtual void RemoveAll() = 0;
/** Activate sequence by binding sequence animations to nodes.
must be called prior animating sequence.
*/
virtual void Activate() = 0;
/** Deactivates sequence by unbinding sequence animations from nodes.
*/
virtual void Deactivate() = 0;
/** Evaluate animations of all nodes in sequence.
Sequence must be activated before animating.
*/
virtual void Animate( SAnimContext &ec ) = 0;
//! Set time range of this sequence.
virtual void SetTimeRange( Range timeRange ) = 0;
//! Get time range of this sequence.
virtual Range GetTimeRange() = 0;
//! Resets the sequence
virtual void Reset() = 0;
/** Called to pause sequence.
*/
virtual void Pause() = 0;
/** Called to resume sequence.
*/
virtual void Resume() = 0;
/** Scale all key in tracks from previous time range to new time range.
*/
virtual void ScaleTimeRange( const Range &timeRange ) = 0;
/** Serialize this sequence to XML.
*/
virtual void Serialize( XmlNodeRef &xmlNode,bool bLoading, bool bLoadEmptyTracks=true ) = 0;
};
/** Movie System interface.
Main entrance point to engine movie capability.
Enumerate available movies, update all movies, create animation nodes and tracks.
*/
struct IMovieSystem
{
enum ESequenceStopBehavior
{
ONSTOP_LEAVE_TIME = 0, // When sequence is stopped it remains in last played time.
ONSTOP_GOTO_END_TIME = 1, // Default behavior in game, sequence is animated at end time before stop.
ONSTOP_GOTO_START_TIME = 2, // Default behavior in editor, sequence is animated at start time before stop.
};
//! Release movie system.
virtual void Release() = 0;
//! Set the user.
virtual void SetUser(IMovieUser *pUser) = 0;
//! Get the user.
virtual IMovieUser* GetUser() = 0;
//! Loads all nodes and sequences from a specific file (should be called when the level is loaded).
virtual bool Load(const char *pszFile, const char *pszMission) = 0;
// Description:
// Creates a new animation node with specified type.
// Arguments:
// nodeType - Type of node, one of EAnimNodeType enums.
// nodeId - Node ID if zero movie system will generate unique id.
virtual IAnimNode* CreateNode( int nodeType,int nodeId=0 ) = 0;
// Description:
// Creates a new animation track with specified type.
// Arguments:
// type - Type of track, one of EAnimTrackType enums.
virtual IAnimTrack* CreateTrack( EAnimTrackType type ) = 0;
virtual void ChangeAnimNodeId( int nodeId,int newNodeId ) = 0;
virtual IAnimSequence* CreateSequence( const char *sequence ) = 0;
virtual IAnimSequence* LoadSequence( XmlNodeRef &xmlNode, bool bLoadEmpty=true ) = 0;
virtual void RemoveSequence( IAnimSequence *seq ) = 0;
virtual IAnimSequence* FindSequence( const char *sequence ) = 0;
virtual ISequenceIt* GetSequences() = 0;
virtual ISystem* GetSystem() = 0;
/** Remove all sequences from movie system.
*/
virtual void RemoveAllSequences() = 0;
/** Remove all nodes from movie system.
*/
virtual void RemoveAllNodes() = 0;
//////////////////////////////////////////////////////////////////////////
// Sequence playback.
//////////////////////////////////////////////////////////////////////////
/** Start playing sequence.
Call ignored if sequence is already playing.
@param sequence Name of sequence to play.
*/
virtual void PlaySequence( const char *sequence,bool bResetFX ) = 0;
/** Start playing sequence.
Call ignored if sequence is already playing.
@param sequence Pointer to Valid sequence to play.
*/
virtual void PlaySequence( IAnimSequence *seq,bool bResetFX ) = 0;
/** Stop's currently playing sequence.
Ignored if sequence is not playing.
@param sequence Name of playing sequence to stop.
*/
virtual void StopSequence( const char *sequence ) = 0;
/** Stop's currently playing sequence.
Ignored if sequence is not playing.
@param sequence Pointer to Valid sequence to stop.
*/
virtual void StopSequence( IAnimSequence *seq ) = 0;
/** Stops all currently playing sequences.
*/
virtual void StopAllSequences() = 0;
/** Stops all playing cut-scene sequences.
This will not stop all sequences, but only those with CUT_SCENE flag set.
*/
virtual void StopAllCutScenes() = 0;
/** Checks if specified sequence is playing.
*/
virtual bool IsPlaying( IAnimSequence *seq ) const = 0;
/** Resets playback state of movie system,
usually called after loading of level,
sequences with PLAY_ONRESET flag will start playing after this call if bPlayOnReset is true.
*/
virtual void Reset( bool bPlayOnReset=true ) = 0;
/** Sequences with PLAY_ONRESET flag will start playing after this call.
*/
virtual void PlayOnLoadSequences() = 0;
/** Update movie system every frame to animate all playing sequences.
*/
virtual void Update( float dt ) = 0;
/** Remove node from movie system.
This node also deleted from all sequences that referencing it.
@param node Must be a valid pointer to the animation node to remove.
*/
virtual void RemoveNode( IAnimNode* node ) = 0;
/** Finds node by id.
@param nodeId Id of requested animation node.
@return Pointer to the animation node, or NULL if the node with specified id is not found.
*/
virtual IAnimNode* GetNode( int nodeId ) const = 0;
/** Finds node by Name. Much slower then getting node by id.
Name is case insesentive.
@param nodeName Name of requested animation node.
@return Pointer to the animation node, or NULL if the node with specified name is not found.
*/
virtual IAnimNode* FindNode( const char *nodeName ) const = 0;
/** Set movie system into recording mode,
While in recording mode any changes made to node will be added as keys to tracks.
*/
virtual void SetRecording( bool recording ) = 0;
virtual bool IsRecording() const = 0;
/** Pause any playing sequences.
*/
virtual void Pause() = 0;
/** Resume playing sequences.
*/
virtual void Resume() = 0;
/** Callback when animation-data changes
*/
virtual void SetCallback( IMovieCallback *pCallback ) = 0;
/** Calls the callback->OnDataChanged(), if set
*/
virtual void Callback(ECallbackReason Reason) = 0;
/** Serialize to XML.
*/
virtual void Serialize( XmlNodeRef &xmlNode,bool bLoading, bool bRemoveOldNodes=false, bool bLoadEmpty=true ) = 0;
virtual const SCameraParams& GetCameraParams() const = 0;
virtual void SetCameraParams( const SCameraParams &Params ) = 0;
virtual void SendGlobalEvent( const char *pszEvent ) = 0;
/** Gets the float time value for a sequence that is already playing
*/
virtual float GetPlayingTime(IAnimSequence * pSeq) = 0;
/** Sets the time progression of an already playing cutscene
*/
virtual bool SetPlayingTime(IAnimSequence * pSeq, float fTime)=0;
// Set behavior pattern for stopping sequences.
virtual void SetSequenceStopBehavior( ESequenceStopBehavior behavior )=0;
};
#endif // __imoviesystem_h__

687
CryCommon/INetwork.h Normal file
View File

@@ -0,0 +1,687 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Network source code
//
// File: INetwork.h
// Description: main header file
//
// History:
// -07/25/2001: Alberto Demichelis, Created
// -07/20/2002: Martin Mittring, Cleaned up
//
//////////////////////////////////////////////////////////////////////
#ifndef _INETWORK_H_
#define _INETWORK_H_
#if defined(WIN32) || defined(WIN64)
#ifdef CRYNETWORK_EXPORTS
#define CRYNETWORK_API __declspec(dllexport)
#else
#define CRYNETWORK_API __declspec(dllimport)
#endif
#else
#define CRYNETWORK_API
#endif
#if _MSC_VER > 1000
#pragma warning(disable:4786)
#endif
#include "platform.h"
#if !defined(PS2) && !defined(_XBOX) && !defined(LINUX)
#include <winsock.h>
#else
#ifdef _XBOX
#include <Xtl.h>
#endif
#ifdef LINUX
#include <sys/socket.h>
#endif
#endif
#include "Cry_Math.h" // CVec3
#include "IBitStream.h" // IBitStream
#define NRESULT DWORD
#define NET_OK 0x00000000
#define NET_FAIL 0x80000000
#define NET_FAILED(a)(((a)&NET_FAIL)?1:0)
#define NET_SUCCEDED(a)(((a)&NET_FAIL)?0:1)
#define MAKE_NRESULT(severity, facility, code)(severity | facility | code)
#define NET_FACILITY_SOCKET 0x01000000
//! regular BSD sockets error
//@{
#define NET_EINTR MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEINTR)
#define NET_EBADF MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEBADF)
#define NET_EACCES MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEACCES)
#define NET_EFAULT MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEFAULT)
#define NET_EINVAL MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEINVAL)
#define NET_EMFILE MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEMFILE)
#define NET_WSAEINTR MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEINTR)
#define NET_WSAEBADF MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEBADF)
#define NET_WSAEACCES MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEACCES)
#define NET_WSAEFAULT MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEFAULT)
#define NET_WSAEINVAL MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEINVAL)
#define NET_WSAEMFILE MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEMFILE)
#define NET_EWOULDBLOCK MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEWOULDBLOCK)
#define NET_EINPROGRESS MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEINPROGRESS)
#define NET_EALREADY MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEALREADY)
#define NET_ENOTSOCK MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAENOTSOCK)
#define NET_EDESTADDRREQ MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEDESTADDRREQ)
#define NET_EMSGSIZE MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEMSGSIZE)
#define NET_EPROTOTYPE MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEPROTOTYPE)
#define NET_ENOPROTOOPT MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAENOPROTOOPT)
#define NET_EPROTONOSUPPORT MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEPROTONOSUPPORT)
#define NET_ESOCKTNOSUPPORT MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAESOCKTNOSUPPORT)
#define NET_EOPNOTSUPP MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEOPNOTSUPP)
#define NET_EPFNOSUPPORT MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEPFNOSUPPORT)
#define NET_EAFNOSUPPORT MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEAFNOSUPPORT)
#define NET_EADDRINUSE MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEADDRINUSE)
#define NET_EADDRNOTAVAIL MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEADDRNOTAVAIL)
#define NET_ENETDOWN MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAENETDOWN)
#define NET_ENETUNREACH MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAENETUNREACH)
#define NET_ENETRESET MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAENETRESET)
#define NET_ECONNABORTED MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAECONNABORTED)
#define NET_ECONNRESET MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAECONNRESET)
#define NET_ENOBUFS MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAENOBUFS)
#define NET_EISCONN MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEISCONN)
#define NET_ENOTCONN MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAENOTCONN)
#define NET_ESHUTDOWN MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAESHUTDOWN)
#define NET_ETOOMANYREFS MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAETOOMANYREFS)
#define NET_ETIMEDOUT MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAETIMEDOUT)
#define NET_ECONNREFUSED MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAECONNREFUSED)
#define NET_ELOOP MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAELOOP)
#define NET_ENAMETOOLONG MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAENAMETOOLONG)
#define NET_EHOSTDOWN MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEHOSTDOWN)
#define NET_EHOSTUNREACH MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEHOSTUNREACH)
#define NET_ENOTEMPTY MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAENOTEMPTY)
#define NET_EPROCLIM MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEPROCLIM)
#define NET_EUSERS MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEUSERS)
#define NET_EDQUOT MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEDQUOT)
#define NET_ESTALE MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAESTALE)
#define NET_EREMOTE MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEREMOTE)
//@}
#ifdef _WIN32
//! extended winsock errors
//@{
#define NET_HOST_NOT_FOUND MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAHOST_NOT_FOUND)
#define NET_TRY_AGAIN MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSATRY_AGAIN)
#define NET_NO_RECOVERY MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSANO_RECOVERY)
#define NET_NO_DATA MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSANO_DATA)
#define NET_NO_ADDRESS MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSANO_ADDRESS)
#define NET_SYSNOTREADY MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSASYSNOTREADY)
#define NET_VERNOTSUPPORTED MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAVERNOTSUPPORTED)
#define NET_NOTINITIALISED MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSANOTINITIALISED)
#define NET_EDISCON MAKE_NRESULT(NET_FAIL, NET_FACILITY_SOCKET, WSAEDISCON)
//@}
#endif
// CryNet specific errors and messages
#define NET_FACILITY_CRYNETWORK 0x02000000
#define NET_NOIMPL MAKE_NRESULT(NET_FAIL, NET_FACILITY_CRYNETWORK, 0x01)
#define NET_SOCKET_NOT_CREATED MAKE_NRESULT(NET_FAIL, NET_FACILITY_CRYNETWORK, 0x02)
//#include "IPAddress.h"
//#include "Stream.h"
#include <vector> // STL vector<>
#define DEFAULT_SERVERPORT 49001
#define DEFAULT_SERVERPORT_STR "49001"
#define SERVER_MULTICAST_PORT 5678
//<<FIXME>> It can be changed
#define SERVER_MULTICAST_ADDRESS "234.5.6.7"
#define SERVER_QUERY_MAX_PACKETS (8)
#define SERVER_QUERY_PACKET_SIZE (1120)
enum CryNetworkVarible
{
cnvDataStreamTimeout=0
};
////////////////////////////////////////////////////////////////////////////////////////
// Interfaces
////////////////////////////////////////////////////////////////////////////////////////
struct IClient;
struct IServer;
struct IServerSnooper;
struct INETServerSnooper;
struct IClientSink;
struct IServerSlotFactory;
struct IServerSnooperSink;
struct INETServerSnooperSink;
struct IRConSystem;
struct ICompressionHelper;
class ICrySizer;
class CIPAddress;
class CStream;
struct ISystem;
/*! class factory of the Network module
@see ::CreateNetwork()
*/
struct INetwork
{
//! \return local IPAddress (needed if we have several servers on one machine), 0.0.0.0 if not used
virtual DWORD GetLocalIP() const=0;
//! also initialize Ubi.com integration (flaw in the UBI.com SDK - we would like to be able to set the IP later but they
//! need it during initialization)
//! \param dwLocalIP local IPAddress (needed if we have several servers on one machine)
virtual void SetLocalIP( const char *szLocalIP )=0;
/*! create a client object and return the related interface
@param pSink a pointer to an object the inplements IClientSink [the object that will receive all notification during the connection]
@param bClient if true the client will be only able to connect to the local server and
will use a "fake connection" (memory based)
@return an IClient interface
*/
virtual IClient *CreateClient(IClientSink *pSink,bool bLocal=false) = 0;
/*! create and start a server ,return the related interface
@param pFactory a pointer to an object the inplements IServerSlotFactory
[the object that will receive all notification during the lifetime of the server]
@param nPort local IP port where the server will listen
@return an IServer interface
*/
virtual IServer *CreateServer(IServerSlotFactory *pFactory,WORD nPort, bool local=false) = 0;
//! create an RCon System (remote control system)
virtual IRConSystem *CreateRConSystem() = 0;
/*! create an internet server snooper
@param pSink id of the error
@return Interface to a server snooper
*/
virtual INETServerSnooper *CreateNETServerSnooper(INETServerSnooperSink *pSink) = 0;
/*! create a server snooper
@param pSink id of the error
@return Interface to a server snooper
*/
virtual IServerSnooper *CreateServerSnooper(IServerSnooperSink *pSink) = 0;
/*! return the string representation of a socket error
@param err id of the error
@return string description of the error
*/
virtual const char *EnumerateError(NRESULT err) = 0;
//! release the interface(and delete the object that implements it)
virtual void Release() = 0;
//!
virtual void GetMemoryStatistics(ICrySizer *pSizer) = 0;
//!
//! \return interface pointer to the compression helper library, is always valid
virtual ICompressionHelper *GetCompressionHelper() = 0;
//! Submit to network list files, that must be matching on Client and Server.
virtual void ClearProtectedFiles() = 0;
virtual void AddProtectedFile( const char *sFilename ) = 0;
//!
//! \return 0 if there is no server registered at this port
virtual IServer *GetServerByPort( const WORD wPort ) = 0;
//! used to update things like the UBI.com services
virtual void UpdateNetwork()=0;
//! currently used to update UBI.com info and check CDKey
//! If it is a UBI type server we should the register, if we have already registered this will do nothing.
//! \param szServerName must not be 0
//! \param dwPlayerCount >0
virtual void OnAfterServerLoadLevel( const char *szServerName, const uint32 dwPlayerCount, const WORD wPort )=0;
//! \return true=it's possible (e.g. logged into UBI.com), false=it's not possible
virtual bool VerifyMultiplayerOverInternet() = 0;
//! We have to tell Ubisoft that the client has successfully connected
//! If ubisoft is not running this won't do anything.
virtual void Client_ReJoinGameServer() = 0;
//! \return 0 if there is no client
virtual IClient *GetClient() = 0;
};
////////////////////////////////////////////////////////////////////////////////////////
/*! callback interface that must implement by the host that want to use IClient
*/
struct IClientSink
{
/*! called by the client when the connection occur
*/
virtual void OnXConnect() = 0;
/*! called by the client when the disconnection occur
@param string representation of the disconnection cause
*/
virtual void OnXClientDisconnect(const char *szCause) = 0;
/*! called by the client when the server send a contex setup.
NOTES: for instance a context are all information that allow the client to load a
level.
A context setup is called every time the server want to load a new level.
@param stmContext stream that contain the context informations(game dependent)
*/
virtual void OnXContextSetup(CStream &stmContext) = 0;
/*! called by the client when some data is received
@param stmContext stream that contain the data
*/
virtual void OnXData(CStream &stm) = 0;
/*! called by the client when the server is very laggy (more than cl_timeout)
that means that the client waits cl_timeout seconds, without any data from the server...
*/
virtual void OnXServerTimeout() = 0;
/*! called by the client when the server responds, after a lot of time without doing so..
that means that the client was treating the server as "timedout", and hoppefully waiting for it,
and now, the server, magicaly responded...
*/
virtual void OnXServerRessurect() = 0;
/*! called by the server when a timeout occurs..
when a timeout is expected, because of the server loading for example,
this function should return a number in milliseconds, that is the additional time to wait for the server.
if not timeout is expected, this should return 0, and the normal timeout will take place.
*/
virtual unsigned int GetTimeoutCompensation() = 0;
//!
virtual void MarkForDestruct() = 0;
//!
virtual bool DestructIfMarked() = 0;
};
////////////////////////////////////////////////////////////////////////////////////////
/*! client interface
this interface allow to connect and exchange data with a server
REMARKS:
when a disconnection occur the object that implements this interface
CANNOT BE REUSED. This mean that the interface must be released
and a new IClient must be created for each connection.
*/
struct IClient
{
/*! start the connection to a server
@param szIP address of the server can be an ip address like 134.122.345.3 or a symbolic www.stuff.com
@param pbAuthorizationID must not be 0
@param iAuthorizationSize >0
--@param wPort the remote port of the server
*/
virtual void Connect(const char *szIP, WORD wPort, const BYTE *pbAuthorizationID, unsigned int iAuthorizationSize) = 0;
/*! start disconnect from a server
@param szCause cause of the disconneciton that will be send to the server
*/
virtual void Disconnect(const char *szCause) = 0;
/*! send reliable data to the server
@param stm the bitstream that store the data
*/
virtual void SendReliable(CStream &stm) = 0;
/*! send unreliable data to the server
@param stm the bitstream that store the data
*/
virtual void SendUnreliable(CStream &stm) = 0;
/*! notify the server that the contex setup was received and the client now is ready to
start to receive the data stream.
usually called when the client finish to load the level.
@param stm the bitstream that store the data that the server will receive(usally player name etc..)
*/
virtual void ContextReady(CStream &stm) = 0;
/*! check if the client is ready to send data to the server
@return true if the client is ready,false if not
*/
virtual bool IsReady() = 0;
/*! called to update the client status
@param nTime the current time in milliseconds
@return true=this object is still exising, false=this object was destroyed
REMARKS: to keep the connection working correctly this function must be called at least every frame
*/
virtual bool Update(unsigned int nTime) = 0;
/*! get the average bandwidth used by the current connection
@param fIncomingKbPerSec incoming kb per sec
@param fOutgoingKbPerSec outgoing kb per sec
@param nIncomingPackets per sec
@param nOutgoingPackets per sec
*/
virtual void GetBandwidth( float &fIncomingKbPerSec, float &fOutgoinKbPerSec, DWORD &nIncomingPackets, DWORD &nOutgoingPackets )=0;
/*! release the interface(and delete the object that implements it)
*/
virtual void Release() = 0;
/*! get the average round trip delay through client and server
@return the average ping in milliseconds
*/
virtual unsigned int GetPing()=0;
//!
virtual unsigned int GetRemoteTimestamp(unsigned int nTime)=0;
//!
virtual unsigned int GetPacketsLostCount()=0;
//!
virtual unsigned int GetUnreliablePacketsLostCount()=0;
//! returns IP of server.
virtual CIPAddress GetServerIP() const = 0;
//!
virtual void InitiateCDKeyAuthorization( const bool inbCDAuthorization ) = 0;
//! \param pbAuthorizationID 0 if you wanna create a fake AuthorizationID, otherwise pointer to the AuthorizationID
virtual void OnCDKeyAuthorization( BYTE *pbAuthorizationID ) = 0;
//!
virtual void SetServerIP( const char *szServerIP ) = 0;
};
struct IServerSnooper
{
/*! query the LAN for servers
*/
virtual void SearchForLANServers(unsigned int nTime=0) = 0;
virtual void Update(unsigned int nTime) = 0;
//! release the interface(and delete the object that implements it)
virtual void Release() = 0;
};
struct IServerSnooperSink
{
/*! called by the client when some server is found
@param ip IP address of the found server
@param stmServerInfo stream containing all server informations(game dependent)
*/
virtual void OnServerFound(CIPAddress &ip, const string &szServerInfoString, int ping) = 0;
};
struct INetworkPacketSink
{
virtual void OnReceivingPacket( const unsigned char inPacketID, CStream &stmPacket, CIPAddress &ip )=0;
};
struct INETServerSnooper
{
//! query internet servers for info
virtual void Update(unsigned int dwTime) = 0;
//!
virtual void AddServer(const CIPAddress &ip) = 0;
//!
virtual void AddServerList(const std::vector<CIPAddress> &vIP) = 0;
//! release the interface(and delete the object that implements it)
virtual void Release() = 0;
//! clear the current list of servers
virtual void ClearList() = 0;
};
struct INETServerSnooperSink
{
/*! called by the client when some server is found
@param ip IP address of the found server
@param stmServerInfo stream containing all serer informations(game dependent)
*/
virtual void OnNETServerFound(const CIPAddress &ip, const string &szServerInfoString, int ping) = 0;
/*! called by the client when some server timedout
@param ip IP address of the dead server
*/
virtual void OnNETServerTimeout(const CIPAddress &ip) = 0;
};
//! interface to control servers remotely
struct IRConSystem
{
//! query response packets
//! Can specify optional client, to get server ip from.
virtual void Update( unsigned int dwTime,IClient *pClient=NULL )=0;
//! release the interface(and delete the object that implements it)
virtual void Release()=0;
//!
virtual void ExecuteRConCommand( const char *inszCommand )=0;
//!
virtual void OnServerCreated( IServer *inpServer )=0;
};
////////////////////////////////////////////////////////////////////////////////////////
//! callback interface that must implement by the host that want to use ISererSlot
struct IServerSlotSink
{
//! called by the serverslot when the connection occur
virtual void OnXServerSlotConnect(const BYTE *pbAuthorizationID, unsigned int uiAuthorizationSize) = 0;
/*! called by the serverslot when the disconnection occur
@param string representation of the disconnection cause
*/
virtual void OnXServerSlotDisconnect(const char *szCause) = 0;
/*! called by the serverslot when the client send a "context ready"
@param stm bitstream that store the data sent by the client as answer of the context setup(usally player name etc..)
*/
virtual void OnContextReady(CStream &stm) = 0; //<<FIXME>> add some level validation code
/*! called by the serverslot when some data is received
@param stm bitstream that store the received data
*/
virtual void OnData(CStream &stm) = 0;
//!
virtual void OnXPlayerAuthorization( bool bAllow, const char *szError, const BYTE *pGlobalID,
unsigned int uiGlobalIDSize ) = 0;
};
struct SServerSlotBandwidthStats
{
//! constructor
SServerSlotBandwidthStats()
{
Reset();
}
unsigned int m_nReliableBitCount; //!<
unsigned int m_nReliablePacketCount; //!<
unsigned int m_nUnreliableBitCount; //!<
unsigned int m_nUnreliablePacketCount; //!<
void Reset()
{
m_nReliableBitCount=0;
m_nReliablePacketCount=0;
m_nUnreliableBitCount=0;
m_nUnreliablePacketCount=0;
}
};
////////////////////////////////////////////////////////////////////////////////////////
/*! server slot interface
The server slot is the endpoint of a client connection on the server-side. Besically for
every remote client a server slot exist on the server.
*/
struct IServerSlot
{
/*! set the host object that will receive all server slot notifications
@param pSink poiter to an object thath implements IServerSlotSink
*/
virtual void Advise(IServerSlotSink *pSink) = 0;
/*! disconnect the client associated to this server slot
@param szCause cause of the disconneciton that will be send to the client
*/
virtual void Disconnect(const char *szCause) = 0;
/*! send a context setup to the client
@param stm bitstream that store the context information(usually level name etc..)
*/
virtual bool ContextSetup(CStream &stm) = 0;
/*! send reliable data to the client
@param stm the bitstream that store the data
*/
virtual void SendReliable(CStream &stm,bool bSecondaryChannel=false) = 0;
/*! send unreliable data to the client
@param stm the bitstream that store the data
*/
virtual void SendUnreliable(CStream &stm) = 0;
/*! check if the server slot is ready to send data to the client
@return true if the serverslot is ready,false if not
*/
virtual bool IsReady() = 0;
/*! get the unique id that identify the server slot on a server
@return ID of the serverslot
*/
virtual unsigned char GetID()=0;
// Return IP in integer form.
virtual unsigned int GetClientIP() const = 0;
//! release the interface(and delete the object that implements it)
virtual void Release() = 0;
/*! get the average round trip delay through client and server
@return the average ping in milliseconds
*/
virtual unsigned int GetPing() = 0;
//!
virtual unsigned int GetPacketsLostCount() = 0;
//!
virtual unsigned int GetUnreliablePacketsLostCount() = 0;
//! used for bandwidth calculations (to adjust the bandwidth)
virtual void ResetBandwidthStats() = 0;
//! used for bandwidth calculations (to adjust the bandwidth)
virtual void GetBandwidthStats( SServerSlotBandwidthStats &out ) const = 0;
//! just calles OnXPlayerAuthorization of the corresponding game specific object
virtual void OnPlayerAuthorization( bool bAllow, const char *szError, const BYTE *pGlobalID,
unsigned int uiGlobalIDSize ) = 0;
};
////////////////////////////////////////////////////////////////////////////////////////
//the application must implement this class
struct IServerSlotFactory
{
virtual bool CreateServerSlot(IServerSlot *pIServerSlot) = 0;
//! \return true=success, false otherwise
//! fill the given string with server infos
//! \note do not overwrite the string, just append to it
virtual bool GetServerInfoStatus(string &szServerStatus) = 0;
virtual bool GetServerInfoStatus(string &szName, string &szGameType, string &szMap, string &szVersion, bool *pbPassword, int *piPlayers, int *piMaxPlayers) = 0;
virtual bool GetServerInfoRules(string &szServerRules) = 0;
virtual bool GetServerInfoPlayers(string *vszStrings[4], int &nStrings) = 0;
//! Called when someone sends XML request to server, this function must fill sResponse string with XML response.
virtual bool ProcessXMLInfoRequest( const char *sRequest,const char *sRespone,int nResponseMaxLength ) = 0;
};
// the application should implement this class
struct IServerSecuritySink
{
enum CheaterType
{
CHEAT_NOT_RESPONDING,
CHEAT_NET_PROTOCOL,
CHEAT_MODIFIED_FILE,
CHEAT_MODIFIED_CODE,
CHEAT_MODIFIED_VARS,
};
struct SSlotInfo
{
char playerName[32];
int score;
int deaths;
};
/*! check the state of an ip address before creating the slot
\return the state of the ip (banned or not)
*/
virtual bool IsIPBanned(const unsigned int dwIP) = 0;
/*! ban an ip address
\param dwIP the ip address to ban
*/
virtual void BanIP(const unsigned int dwIP) = 0;
/*! ban an ip address
\param dwIP the ip address to ban
*/
virtual void UnbanIP(const unsigned int dwIP) = 0;
/*! Report cheating user.
*
*/
virtual void CheaterFound( const unsigned int dwIP,int type,const char *sMsg ) = 0;
/*! Request slot information from the game.
*
*/
virtual bool GetSlotInfo( const unsigned int dwIP,SSlotInfo &info , int nameOnly ) = 0;
};
enum EMPServerType
{
eMPST_LAN=0, //!< LAN
eMPST_NET=1, //!< e.g. ASE
eMPST_UBI=2, //!< UBI.com
};
////////////////////////////////////////////////////////////////////////////////////////
/*!Server interface
*/
struct IServer
{
/*! called to update the server status, this update all serverslots too
@param nTime the current time in milliseconds
REMARKS: to keep the connection working correctly this function must be called at least every frame
*/
virtual void Update(unsigned int nTime) = 0;
//! release the interface and delete the implemetation
virtual void Release() = 0;
//! set a server veriable
virtual void SetVariable(enum CryNetworkVarible eVarName,unsigned int nValue) = 0;
/*! get the average bandwidth used by all active connections
@param fIncomingKbPerSec incoming kb per sec
@param fOutgoingKbPerSec outgoing kb per sec
@param nIncomingPackets per sec
@param nOutgoingPackets per sec
*/
virtual void GetBandwidth( float &fIncomingKbPerSec, float &fOutgoinKbPerSec, DWORD &nIncomingPackets, DWORD &nOutgoingPackets )=0;
/*!return the symbolic name of the localhost
@return the symbolic name of the localhost
*/
virtual const char *GetHostName() = 0;
//! \param inPacketID e.g. FT_CQP_RCON_COMMAND
//! \param inpSink must not be 0
virtual void RegisterPacketSink( const unsigned char inPacketID, INetworkPacketSink *inpSink )=0;
/*! set the security sink
\param pSecurirySink pointer to a class that implements the IServerSecuritySink interface
*/
virtual void SetSecuritySink(IServerSecuritySink *pSecuritySink) = 0;
/*! check the state of an ip address before creating the slot
\return the state of the ip (banned or not)
*/
virtual bool IsIPBanned(const unsigned int dwIP) = 0;
/*! ban an ip address
\param dwIP the ip address to ban
*/
virtual void BanIP(const unsigned int dwIP) = 0;
/*! ban an ip address
\param dwIP the ip address to ban
*/
virtual void UnbanIP(const unsigned int dwIP) = 0;
//! time complexity: O(n) n=connected server slots
//! \return 0 if there is no serverslot with this client (was never there or disconnected)
virtual IServerSlot *GetServerSlotbyID( const unsigned char ucId ) const = 0;
//! to iterate through all clients (new clients ids are the lowest available at that time)
virtual uint8 GetMaxClientID() const = 0;
//! LAN/UBI/NET
virtual EMPServerType GetServerType() const=0;
};
////////////////////////////////////////////////////////////////////////////////////////
// other stuff
// exports;
extern "C"{
CRYNETWORK_API INetwork *CreateNetwork(ISystem *pSystem);
typedef INetwork *(*PFNCREATENETWORK)(ISystem *pSystem);
}
#endif //_INETWORK_H_

310
CryCommon/IPAddress.h Normal file
View File

@@ -0,0 +1,310 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Network source code
//
// File: ipaddress.h
// Description: ip address wrapper
//
// History:
// -July 25,2001:Created by Alberto Demichelis
//
//////////////////////////////////////////////////////////////////////
#ifndef _IP_ADDRESS_H_
#define _IP_ADDRESS_H_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <Stream.h>
#include "platform.h"
#ifdef LINUX
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#endif //LINUX
struct _SOCKADDR_IN
{
short sin_family;
unsigned short sin_port;
#if defined(LINUX)
union
{
struct in_addr_windows sin_addr_win;
struct in_addr sin_addr;
};
#else
struct in_addr sin_addr;
#endif
char sin_zero[8];
};
class CStream;
#ifdef WIN32
#include <winsock.h>
#endif //WIN32
#ifdef PS2
#include <SocketManager.h>
#define PS2_MEM_SOCKET
#endif //PS2
/*
#ifdef _XBOX
#include <xtl.h>
// #include <winsockx.h>
#endif
#ifndef PS2
struct _SOCKADDR_IN{
short sin_family;
unsigned short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
#include <winsock.h>
#else
#include <SocketManager.h>
//# define PS2_SONY_SOCKET
#define PS2_MEM_SOCKET
#endif
*/
inline unsigned short __ntohs(unsigned short us)
{
unsigned short nTemp=(us>>8)|(us<<8);
return nTemp;
}
/* NOTE FOR PS2 PROGRAMMERS ABOUT THIS CLASS
I rollback this file to our version because
your change caused a bug inside our version.
in your version you changed this
m_Address.sin_addr.S_un.S_addr
to this
m_Address.sin_addr.S_addr
but you also replaced
m_Address.sin_port
with
m_Address.sin_addr.S_addr
be careful because for some strange reason
was partially working :)
*/
#if defined(LINUX)
#define ADDR sin_addr_win.S_un.S_addr
#else
#define ADDR sin_addr.S_un.S_addr
#endif
class CIPAddress
{
public:
CIPAddress(WORD wPort,const char *sAddress)
{
m_Address.sin_family = AF_INET;
m_Address.sin_port = htons(wPort);
m_Address.ADDR = inet_addr(sAddress);
m_Address.sin_zero[0] = 0;
if(m_Address.ADDR == INADDR_NONE)
{
struct hostent *pHostEntry;
pHostEntry = gethostbyname(sAddress);
if(pHostEntry)
m_Address.ADDR = *(unsigned int *)pHostEntry->h_addr_list[0];
else
m_Address.ADDR = 0;
}
}
CIPAddress(sockaddr_in *sa)
{
memcpy(&m_Address, sa, sizeof(sockaddr_in));
}
CIPAddress()
{
memset(&m_Address, 0, sizeof(sockaddr_in));
}
CIPAddress(const CIPAddress &xa)
{
memcpy(&m_Address, &xa.m_Address, sizeof(sockaddr_in));
}
virtual ~CIPAddress()
{
// delete &m_Address;
}
bool IsLocalHost()
{
if(m_Address.ADDR==inet_addr("127.0.0.1"))
return true;
return false;
}
inline void Set(WORD wPort, char *sAddress);
inline void Set(WORD wPort, UINT dwAddress);
inline void Set(sockaddr_in *sa);
inline void Set(const CIPAddress &xa);
UINT GetAsUINT() const;
inline const CIPAddress& operator =(const CIPAddress& xa);
inline bool operator !=(const CIPAddress& s1);
inline bool operator ==(const CIPAddress& s1);
inline bool operator <(const CIPAddress& s1) const ;
inline char *GetAsString(bool bPort = false) const;
inline bool Load(CStream &s);
inline bool Save(CStream &s);
public:
struct _SOCKADDR_IN m_Address;
};
inline void CIPAddress::Set(WORD wPort, char *sAddress)
{
m_Address.sin_family = AF_INET;
m_Address.sin_port = htons(wPort);
m_Address.ADDR = inet_addr(sAddress);
m_Address.sin_zero[0] = 0;
// win2003 server edition compatibility
// the behaviour changed in this OS version
// inet_addr returns INADDR_NONE instead of 0 when an empty string is passed.
if(m_Address.ADDR == INADDR_NONE)
{
m_Address.ADDR = 0;
}
}
inline void CIPAddress::Set(WORD wPort, UINT dwAddress)
{
m_Address.sin_family = AF_INET;
m_Address.sin_port = htons(wPort);
m_Address.ADDR = dwAddress;
m_Address.sin_zero[0] = 0;
}
inline void CIPAddress::Set(sockaddr_in *sa)
{
memcpy(&m_Address, sa, sizeof(sockaddr_in));
}
inline char *CIPAddress::GetAsString(bool bPort) const
{
static char s[64];
if (bPort)
#ifndef LINUX
wsprintf(s, "%i.%i.%i.%i:%i", m_Address.sin_addr.S_un.S_un_b.s_b1,
m_Address.sin_addr.S_un.S_un_b.s_b2,
m_Address.sin_addr.S_un.S_un_b.s_b3,
m_Address.sin_addr.S_un.S_un_b.s_b4, __ntohs(m_Address.sin_port));
#else //LINUX
sprintf(s, "%s:%i",
inet_ntoa(m_Address.sin_addr),
ntohs(m_Address.sin_port)
);
#endif //LINUX
else
#ifndef LINUX
wsprintf(s, "%i.%i.%i.%i", m_Address.sin_addr.S_un.S_un_b.s_b1,
m_Address.sin_addr.S_un.S_un_b.s_b2,
m_Address.sin_addr.S_un.S_un_b.s_b3,
m_Address.sin_addr.S_un.S_un_b.s_b4);
#else //LINUX
sprintf(s, "%s",
inet_ntoa(m_Address.sin_addr)
);
//sprintf(s, "%i", InAddress());
#endif //LINUX
return s;
}
inline UINT CIPAddress::GetAsUINT() const
{
return m_Address.ADDR;
}
inline void CIPAddress::Set(const CIPAddress &xa)
{
memcpy(&m_Address, &xa.m_Address, sizeof(_SOCKADDR_IN));
}
inline bool CIPAddress::operator ==(const CIPAddress& s1)
{
return (!(memcmp(&s1.m_Address, &m_Address, sizeof(_SOCKADDR_IN))))?true:false;
}
inline bool CIPAddress::operator <(const CIPAddress& s1) const
{
if(s1.m_Address.ADDR <m_Address.ADDR)
{
return true;
}
else
{
if(s1.m_Address.ADDR==m_Address.ADDR)
{
if(s1.m_Address.sin_port<m_Address.sin_port)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
inline bool CIPAddress::operator !=(const CIPAddress& s1)
{
return (memcmp(&s1.m_Address, &m_Address, sizeof(sockaddr_in)))?true:false;
}
inline const CIPAddress& CIPAddress::operator =(const CIPAddress& xa)
{
Set(xa);
return *this;
}
inline bool CIPAddress::Load(CStream &s)
{
if (!s.Read((unsigned int&)(m_Address.ADDR)))
return false;
if (!s.Read(m_Address.sin_port))
return false;
return true;
}
inline bool CIPAddress::Save(CStream &s)
{
if (!s.Write((unsigned int&)m_Address.ADDR))
return false;
if (!s.Write(m_Address.sin_port))
return false;
return true;
}
#endif

30
CryCommon/IPhysics.h Normal file
View File

@@ -0,0 +1,30 @@
#ifndef cryphysics_h
#define cryphysics_h
#pragma once
#ifdef WIN32
#ifdef PHYSICS_EXPORTS
#define CRYPHYSICS_API __declspec(dllexport)
#else
#define CRYPHYSICS_API __declspec(dllimport)
#endif
#else
#define CRYPHYSICS_API
#endif
#define vector_class Vec3_tpl
#ifndef GAMECUBE
#include <CrySizer.h>
#endif
//#include "utils.h"
#include "Cry_Math.h"
#include "primitives.h"
#include "physinterface.h"
extern "C" CRYPHYSICS_API IPhysicalWorld *CreatePhysicalWorld(struct ISystem *pLog);
#endif

33
CryCommon/IProcess.h Normal file
View File

@@ -0,0 +1,33 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek Common Source code
//
// File:IProcess.h
// Description: Process common interface
//
// History:
// -September 03,2001:Created by Marco Corbetta
//
//////////////////////////////////////////////////////////////////////
#ifndef IPROCESS_H
#define IPROCESS_H
#if _MSC_VER > 1000
# pragma once
#endif
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
struct IProcess
{
virtual bool Init() = 0;
virtual void Update() = 0;
virtual void Draw() = 0;
virtual void ShutDown(bool bEditorMode=false) = 0;
virtual void SetFlags(int flags) = 0;
virtual int GetFlags(void) = 0;
};
#endif

1268
CryCommon/IRenderer.h Normal file

File diff suppressed because it is too large Load Diff

783
CryCommon/IScriptSystem.h Normal file
View File

@@ -0,0 +1,783 @@
#ifndef _ISCRIPTSYSTEM_H_
#define _ISCRIPTSYSTEM_H_
#if !defined(_XBOX) && !defined(LINUX)
#ifdef CRYSCRIPTSYSTEM_EXPORTS
#define CRYSCRIPTSYSTEM_API __declspec(dllexport)
#else
#define CRYSCRIPTSYSTEM_API __declspec(dllimport)
#endif
#else
#define CRYSCRIPTSYSTEM_API
#endif
class ICrySizer;
struct IWeakScriptObject;
struct IScriptObject;
struct ISystem;
#define HSCRIPT void*
#define HSCRIPTFUNCTION unsigned int
enum {
//## [Sergiy] this is the same as LUA_NOREF; I think this is better to use since
//## in LUA documentation only LUA_NOREF(-2) and LUA_REFNIL (-1) are described as
//## special values, 0 isn't. Please put 0 here if you know for sure and it is documented
//## that 0 is invalid reference value for LUA
INVALID_SCRIPT_FUNCTION = -2
};
#define THIS_PTR void*
#define HTAG int
#define USER_DATA ULONG_PTR //## AMD Port
typedef int(*SCRIPT_FUNCTION)(HSCRIPT hScript);
typedef int HBREAKPOINT;
enum BreakState{
bsStepNext,
bsStepInto,
bsContinue,
bsNoBreak
};
struct IFunctionHandler;
struct IScriptDebugSink;
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
/*! IScriptSystem callback interface
this interface must be implemented by host applicatio the use the scripting system
to receive error messages and notification
*/
// Summary:
// Callback interface.
// Description:
// This interface must be implemented by the host application in order to
// receive error messages and various notifications from the Scripting
// System.
struct IScriptSystemSink
{
/*! called by the scripting system when an error occur
@param sSourceFile the script file where the error occured
@param sFuncName the script function where the error occured
@param nLineNum the line number of the the script file where the error occured (-1 if there is no line no info)
@param sErrorDesc descriptio of the error
*/
virtual void OnScriptError(const char *sSourceFile,const char *sFuncName,int nLineNum,const char *sErrorDesc) = 0;
/*! called by the scripting system to ask for permission to change a global tagged value
@return true if permission is granted, false if not
*/
virtual bool CanSetGlobal (const char* sVarName) = 0;
/*! called by the scripting system when a global tagged value is set by inside a script
@param sVarName the name of the variable that has been changed
*/
virtual void OnSetGlobal(const char *sVarName) = 0;
/*! called by the scripting system for each load script when DumpLoadedScripts is called
@param sScriptPath path of a script
*/
virtual void OnLoadedScriptDump(const char *sScriptPath) = 0;
virtual void OnCollectUserData(INT_PTR nValue,int nCookie) = 0; //## AMD Port
};
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
/*! main interface of the scripting engine
this interface is mapped 1:1 on a script state
all script loaded from the same interface instance are visible together
*/
struct IScriptSystem
{
//DOC-IGNORE-BEGIN
//! internal use
virtual IFunctionHandler *GetFunctionHandler()=0;
//! internal use
virtual HSCRIPT GetScriptHandle() = 0;
//DOC-IGNORE-END
/*! load a script file and run it
@param sFileName path of the script file
@param bRaiseError if true the script engine will call IScirptSystemSink::OnError() if
an error will occur
@return false if the execution fail if not true
REMARKS: all global variables and function declared into the executed script
will persist for all the script system lifetime
*/
virtual bool ExecuteFile(const char *sFileName,bool bRaiseError = true, bool bForceReload=false) = 0;
/*! execute an ASCII buffer
@param sBuffer an 8bit ASCII buffer containing the script that must be executed
@param bRaiseError if true the script engine will call IScirptSystemSink::OnError() if
an error will occur
@return false if the execution fail if not true
REMARKS: all global variables and function declared into the executed buffer
will persist for all the script system lifetime
*/
virtual bool ExecuteBuffer(const char *sBuffer, size_t nSize) = 0;
/*! unload a script
@param sFileName apath of the script file
NOTES: the script engine never load twice the same file(same path) because internally
stores a list of loaded files.This function simple remove the specified path from
this list
*/
virtual void UnloadScript(const char *sFileName) = 0;
/*! unload all scripts
NOTES: the script engine never load twice the same file(same path) because internally
stores a list of loaded files.This function simple remove all entries from
this list
*/
virtual void UnloadScripts() = 0;
/*! realod a script
@param sFileName apath of the script file
@param bRaiseError if true the script engine will call IScirptSystemSink::OnError() if
an error will occur
@return false if the execution fail if not true
*/
virtual bool ReloadScript(const char *sFileName,bool bRaiseError = true) = 0;
//! reload all scripts previously loaded
virtual bool ReloadScripts() = 0;
//! generate a OnLoadedScriptDump() for every loaded script
virtual void DumpLoadedScripts() = 0 ;
//! return a object that store all global variables as members
virtual IScriptObject *GetGlobalObject() = 0;
/*! create a new IScriptObject that is not mapped to a object in the script
this is used to store an object that lua pass to a C++ function
@return a pointer to the created object
*/
virtual IScriptObject* CreateEmptyObject() = 0;
/*! create a new IScriptObject
@return a pointer to the created object
*/
virtual IScriptObject* CreateObject() = 0;
/*! create a global IScriptObject
@param sName the name of the object into the script scope
@param pThis pointer to the C++ class that will receive a call from the script
[this parameter can be NULL]
@return a pointer to the created object
*/
virtual IScriptObject* CreateGlobalObject(const char *sName) = 0;
/*! start a call to script function
@param sTableName name of the script table that contai the function
@param sFuncName function name
CALLING A SCRIPT FUNCTION:
to call a function in the script object you must
call BeginCall
push all parameters whit PushParam
call EndCall
EXAMPLE:
m_ScriptSystem->BeginCall("Player","OnInit");
m_ScriptSystem->PushParam(pObj);
m_ScriptSystem->PushParam(nTime);
m_ScriptSystem->EndCall();
*/
//##@{
virtual int BeginCall(HSCRIPTFUNCTION hFunc) = 0; // M<>rcio: changed the return type
virtual int BeginCall(const char *sFuncName) = 0; // from void to int for error checking
virtual int BeginCall(const char *sTableName, const char *sFuncName) = 0;//
//##@}
/*! end a call to script function
@param ret reference to the variable that will store an eventual return value
*/
//##@{
virtual void EndCall()=0;
virtual void EndCall(int &nRet)=0;
virtual void EndCall(float &fRet)=0;
virtual void EndCall(const char *&sRet)=0;
#if defined(WIN64) || defined(LINUX)
inline void EndCall(char *&sRet) {EndCall ((const char*&)sRet);}
#endif
virtual void EndCall(bool &bRet)=0;
virtual void EndCall(IScriptObject *pScriptObject)=0;
//##@}
/*! function under development ingnore it*/
//##@{
virtual HSCRIPTFUNCTION GetFunctionPtr(const char *sFuncName) = 0;
virtual HSCRIPTFUNCTION GetFunctionPtr(const char *sTableName, const char *sFuncName) = 0;
//##@}
virtual void ReleaseFunc(HSCRIPTFUNCTION f) = 0;
/*! push a parameter during a function call
@param val value that must be pushed
*/
//##@{
virtual void PushFuncParam(int nVal) = 0;
virtual void PushFuncParam(float fVal) = 0;
virtual void PushFuncParam(const char *sVal) = 0;
virtual void PushFuncParam(bool bVal) = 0;
virtual void PushFuncParam(IScriptObject *pVal) = 0;
//##@}
/*! set a global script variable
@param sKey variable name
@param val variable value
*/
//##@{
virtual void SetGlobalValue(const char *sKey, int nVal) = 0;
virtual void SetGlobalValue(const char *sKey, float fVal) = 0;
virtual void SetGlobalValue(const char *sKey, const char *sVal) = 0;
virtual void SetGlobalValue(const char *sKey, IScriptObject *pObj) = 0;
//##@}
//! get the value of a global variable
//##@{
virtual bool GetGlobalValue(const char *sKey, int &nVal) = 0;
virtual bool GetGlobalValue(const char *sKey, float &fVal) = 0;
virtual bool GetGlobalValue(const char *sKey, const char * &sVal) = 0;
virtual bool GetGlobalValue(const char *sKey, IScriptObject *pObj) = 0;
virtual void SetGlobalToNull(const char *sKey) = 0;
//##@}
/*! create a global tagged value
a tagged value is a varible tha is visible in lua as a normal
script variable but his value is stored into a c++ defined memory block
@param sKey name of the value
@param pVal pointer to the C++ variable tha will store the value
@return if succeded an handle to the tagged value else NULL
*/
//##@{
virtual HTAG CreateTaggedValue(const char *sKey, int *pVal) = 0;
virtual HTAG CreateTaggedValue(const char *sKey, float *pVal) = 0;
virtual HTAG CreateTaggedValue(const char *sKey, char *pVal) = 0;
//##@}
virtual USER_DATA CreateUserData(INT_PTR nVal,int nCookie)=0;
/*! remove a tagged value
@param tag handle to a tagged value
*/
virtual void RemoveTaggedValue(HTAG tag) = 0;
/*! generate a script error
@param sErr "printf like" string tha define the error
*/
virtual void RaiseError(const char *sErr,...) = 0;
/*! force a Garbage collection cycle
in the current status of the engine the automatic GC is disabled
so this function must be called explicitly
*/
virtual void ForceGarbageCollection() = 0;
/*! number of "garbaged" object
*/
virtual int GetCGCount() = 0;
/*! legacy function*/
virtual void SetGCThreshhold(int nKb) = 0;
/*! un bind all gc controlled userdata variables (from this point is the application that must explicitly delete those objs)*/
virtual void UnbindUserdata() = 0;
/*! release and destroy the script system*/
virtual void Release() = 0;
//!debug functions
//##@{
virtual void EnableDebugger(IScriptDebugSink *pDebugSink) = 0;
virtual IScriptObject *GetBreakPoints() = 0;
virtual HBREAKPOINT AddBreakPoint(const char *sFile,int nLineNumber)=0;
virtual IScriptObject *GetLocalVariables(int nLevel = 0) = 0;
/*!return a table containing 1 entry per stack level(aka per call)
an entry will look like this table
[1]={
description="function bau()",
line=234,
sourcefile="/scripts/bla/bla/bla.lua"
}
*/
virtual IScriptObject *GetCallsStack() = 0;
virtual void DebugContinue() = 0;
virtual void DebugStepNext() = 0;
virtual void DebugStepInto() = 0;
virtual void DebugDisable() = 0;
virtual BreakState GetBreakState() = 0;
//##@}
virtual void GetMemoryStatistics(ICrySizer *pSizer) = 0;
//! Is not recusive but combines the hash values of the whole table when the specifies variable is a table
//! otherwise is has to be a lua function
//! @param sPath zero terminated path to the variable (e.g. _localplayer.cnt), max 255 characters
//! @param szKey zero terminated name of the variable (e.g. luaFunc), max 255 characters
//! @param dwHash is used as input and output
virtual void GetScriptHash( const char *sPath, const char *szKey, unsigned int &dwHash )=0;
//////////////////////////////////////////////////////////////////////////
// Called one time after initialization of system to register script system console vars.
//////////////////////////////////////////////////////////////////////////
virtual void PostInit() = 0;
};
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
struct IScriptObjectSink
{
virtual void OnRelease()=0;
};
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
enum ScriptVarType
{
svtNull = 0,
svtString,
svtNumber,
svtFunction,
svtObject,
svtUserData,
};
// Returns literal representation of the type value
inline const char* ScriptVarTypeAsCStr(ScriptVarType t)
{
switch (t)
{
case svtNull: return "Null";
case svtString: return "String";
case svtNumber: return "Number";
case svtFunction: return "Function";
case svtObject: return "Object";
case svtUserData: return "UserData";
default: return "#Unknown";
}
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
struct IScriptObjectDumpSink
{
virtual void OnElementFound(const char *sName,ScriptVarType type) = 0;
virtual void OnElementFound(int nIdx,ScriptVarType type) = 0;
};
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
struct IScriptObject
{
//DOC-IGNORE-BEGIN
//! internal use
virtual int GetRef() = 0;
//! internal use
//DOC-IGNORE-END
virtual void Attach() = 0;
virtual void Attach(IScriptObject *so) = 0;
virtual void Delegate(IScriptObject *pObj) = 0;
virtual void PushBack(int nVal) = 0;
virtual void PushBack(float fVal) = 0;
virtual void PushBack(const char *sVal) = 0;
virtual void PushBack(bool bVal) = 0;
virtual void PushBack(IScriptObject *pObj) = 0;
/*! Set the value of a memeber varible
@param sKey variable name
@param val variable value
*/
//##@{
virtual void SetValue(const char *sKey, int nVal) = 0;
virtual void SetValue(const char *sKey, float fVal) = 0;
virtual void SetValue(const char *sKey, const char *sVal) = 0;
virtual void SetValue(const char *sKey, bool bVal) = 0;
virtual void SetValue(const char *sKey, IScriptObject *pObj) = 0;
virtual void SetValue(const char *sKey, USER_DATA ud) = 0;
//##@}
/*! Set the value of a member variable to nil
@param sKey variable name
*/
virtual void SetToNull(const char *sKey) = 0;
/*! Get the value of a memeber varible
@param sKey variable name
@param val reference to the C++ variable that will store the value
@return false if failed true if succeded
*/
//##@{
virtual bool GetValue(const char *sKey, int &nVal) = 0;
virtual bool GetValue(const char *sKey, float &fVal) = 0;
virtual bool GetValue(const char *sKey, bool &bVal) = 0;
virtual bool GetValue(const char *sKey, const char* &sVal) = 0;
//#if defined(WIN64)
// inline bool GetValue(const char *sKey, char* &sVal) {return GetValue (sKey, (const char*&)sVal);}
//#endif
virtual bool GetValue(const char *sKey, IScriptObject *pObj) = 0;
virtual bool GetValue(const char *sKey, HSCRIPTFUNCTION &funcVal) = 0;
virtual bool GetUDValue(const char *sKey, USER_DATA &nValue, int &nCookie) = 0; //## AMD Port
//#ifdef WIN64
inline bool GetUDValue(const char *sKey, INT_PTR &nValue, int &nCookie){return GetUDValue(sKey, (USER_DATA&)nValue, nCookie);} //## AMD Port
//#endif
//! used to create a hash value out of a lua function (for cheat protection)
virtual bool GetFuncData(const char *sKey, unsigned int * &pCode, int &iSize) = 0;
//##@}
/*! Get the value of a memeber varible
@param sKey variable name
@param val reference to the C++ variable that will store the value
@return false if failed true if succeded
*/
//##@{
virtual bool BeginSetGetChain()=0;
virtual bool GetValueChain(const char *sKey, int &nVal) = 0;
//virtual bool GetValueChain(const char *sKey, unsigned int &nVal) = 0;
virtual bool GetValueChain(const char *sKey, float &fVal) = 0;
virtual bool GetValueChain(const char *sKey, bool &bVal) = 0;
virtual bool GetValueChain(const char *sKey, const char* &sVal) = 0;
virtual bool GetValueChain(const char *sKey, IScriptObject *pObj) = 0;
virtual bool GetValueChain(const char *sKey, HSCRIPTFUNCTION &funcVal) = 0;
virtual bool GetUDValueChain(const char *sKey, USER_DATA &nValue, int &nCookie) = 0; //## AMD Port
//#ifdef WIN64
inline bool GetUDValueChain(const char *sKey, INT_PTR &nValue, int &nCookie){return GetUDValueChain(sKey, (USER_DATA&)nValue, nCookie);} //#ingore AMD Port
//#endif
virtual void SetValueChain(const char *sKey, int nVal) = 0;
virtual void SetValueChain(const char *sKey, float fVal) = 0;
virtual void SetValueChain(const char *sKey, const char *sVal) = 0;
virtual void SetValueChain(const char *sKey, bool bVal) = 0;
virtual void SetValueChain(const char *sKey, IScriptObject *pObj) = 0;
virtual void SetValueChain(const char *sKey, USER_DATA ud) = 0;
virtual void SetToNullChain(const char *sKey)=0;
virtual void EndSetGetChain()=0;
//##@}
/*!Get the vaue type of a table member
@param sKey variable name
@return the value type (svtNull if doesn't exist)
*/
virtual ScriptVarType GetValueType(const char *sKey) = 0;
virtual ScriptVarType GetAtType(int nIdx) = 0;
/*! Set the value of a memeber varible at the specified index
this mean that you will use the object as vector into the script
@param nIdx index of the variable
@param val variable value
*/
//##@{
virtual void SetAt(int nIdx,int nVal)=0;
virtual void SetAt(int nIdx,float fVal)=0;
virtual void SetAt(int nIdx,bool bVal)=0;
virtual void SetAt(int nIdx,const char* sVal)=0;
virtual void SetAt(int nIdx,IScriptObject *pObj)=0;
virtual void SetAtUD(int nIdx,USER_DATA nValue)=0;
//##@}
/*! Set the value of a member variable to nil at the specified index
@param nIdx index of the variable
*/
virtual void SetNullAt(int nIdx)=0;
/*! Get the value of a memeber varible at the specified index
@param nIdx index of the variable
@param val reference to the C++ variable that will store the value
@return false if failed true if succeded
*/
//##@{
virtual bool GetAt(int nIdx,int &nVal)=0;
virtual bool GetAt(int nIdx,float &fVal)=0;
virtual bool GetAt(int nIdx,bool &bVal)=0;
virtual bool GetAt(int nIdx,const char* &sVal)=0;
virtual bool GetAt(int nIdx,IScriptObject *pObj)=0;
virtual bool GetAtUD(int nIdx, USER_DATA &nValue, int &nCookie)=0;
//##@}
virtual bool BeginIteration() = 0;
virtual bool MoveNext() = 0;
virtual bool GetCurrent(int &nVal) = 0;
virtual bool GetCurrent(float &fVal) = 0;
virtual bool GetCurrent(bool &bVal) = 0;
virtual bool GetCurrent(const char* &sVal) = 0;
virtual bool GetCurrent(IScriptObject *pObj) = 0;
//! used to get a unique identifier for the table (to iterate without problems with cycles)
virtual bool GetCurrentPtr(const void * &pObj)=0;
//! used to create a hash value out of a lua function (for cheat protection)
virtual bool GetCurrentFuncData(unsigned int * &pCode, int &iSize) = 0;
virtual bool GetCurrentKey(const char* &sVal) = 0;
#if defined(WIN64) || defined(LINUX)
inline bool GetCurrentKey(char* &sVal) {return GetCurrentKey((const char*&)sVal);}
inline bool GetCurrent(char* &sVal) {return GetCurrent ((const char*&)sVal);}
inline bool GetAt(int nIdx,char* &sVal) {return GetAt(nIdx, (const char*&)sVal);}
#endif
virtual bool GetCurrentKey(int &nKey) = 0;
virtual ScriptVarType GetCurrentType() = 0;
virtual void EndIteration() = 0;
virtual void SetNativeData(void *) =0;
virtual void *GetNativeData() = 0;
virtual void Clear() = 0;
//! get the count of elements into the object
virtual int Count()=0 ;
/*
*/
virtual bool Clone(IScriptObject *pObj)=0;
//DOC-IGNORE-BEGIN
/*under development*/
virtual void Dump(IScriptObjectDumpSink *p) = 0;
//DOC-IGNORE-END
/*! add a function to the object
@param name of the function
@param C++ function pointer(declared as SCRIPT_FUNCTION)
@param nFuncID id of the function that will be passed beck by the engine
@return false if failed true if succeded
*/
virtual bool AddFunction(const char *sName, SCRIPT_FUNCTION pThunk, int nFuncID) = 0;
//!
virtual bool AddSetGetHandlers(SCRIPT_FUNCTION pSetThunk,SCRIPT_FUNCTION pGetThunk) = 0;
/*! register the host object as parent
@param pSink pointer to an object that implement IScriptObjectSink
NOTE: if the parent is registered the script object will notify when is deleted
*/
virtual void RegisterParent(IScriptObjectSink *pSink) = 0;
//! detach the IScriptObject from the "real" script object
//! used to detach from the C++ code quick objects like vectors or temporary structures
virtual void Detach() = 0;
//! delete the IScriptObject/
virtual void Release() = 0;
//! @param szPath e.g. "cnt.table1.table2", "", "mytable", max 255 characters
//! @return true=path was valid, false otherwise
virtual bool GetValueRecursive( const char *szPath, IScriptObject *pObj ) = 0;
};
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
//DOC-IGNORE-BEGIN
/*! internal use*/
struct IWeakScriptObject
{
virtual IScriptObject *GetScriptObject() = 0;
virtual void Release() = 0 ;
};
//DOC-IGNORE-END
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
// Description:
// This interface is used by the C++ function mapped to the script
// to retrieve the function parameters passed by the script and
// to return an optiona result value to the script.
struct IFunctionHandler
{
//DOC-IGNORE-BEGIN
/*! internal use */
virtual void __Attach(HSCRIPT hScript) = 0;
/*! internal use */
virtual THIS_PTR GetThis() = 0;
//virtual THIS_PTR GetThis2() = 0;
/*! internal use */
virtual int GetFunctionID() = 0;
//DOC-IGNORE-END
//! Get the number of parameter passed by lua
virtual int GetParamCount() = 0;
/*! get the nIdx param passed by the script
@param nIdx 1-based index of the parameter
@param val reference to the C++ variable that will store the value
@param nReference should the function create strong reference to the object? By default 0, means weak reference is created
*/
//##@{
virtual bool GetParam(int nIdx, int &n) = 0;
virtual bool GetParam(int nIdx, float &f) = 0;
virtual bool GetParam(int nIdx, const char * &s) = 0;
#if defined(WIN64) || defined(LINUX)
inline bool GetParam(int nIdx, char * &s) {return GetParam(nIdx, (const char*&)s);}
#endif
#if defined(WIN64) || defined(LINUX64)
virtual bool GetParam(int nIdx, INT_PTR &n) = 0; //## AMD Port
#endif
virtual bool GetParam(int nIdx,bool &b) = 0;
virtual bool GetParam(int nIdx, IScriptObject *pObj) = 0;
virtual bool GetParam(int nIdx, HSCRIPTFUNCTION &hFunc, int nReference = 0) = 0;
virtual bool GetParam(int nIdx,USER_DATA &ud)=0;
virtual bool GetParamUDVal(int nIdx,USER_DATA &val,int &cookie)=0; //## AMD Port
//#ifdef WIN64
inline bool GetParamUDVal(int nIdx,INT_PTR&val,int &cookie){return GetParamUDVal(nIdx, (USER_DATA&)val, cookie);} //## AMD Port
//#endif
//##@}
virtual ScriptVarType GetParamType(int nIdx) = 0;
/*! get the return value that you must return from your "SCRIPT_FUNCTION"
@param the value that xou want to return to the script
*/
//##@{
virtual int EndFunctionNull() = 0;
virtual int EndFunction(int nRetVal) = 0;
virtual int EndFunction(float fRetVal) = 0;
virtual int EndFunction(const char* fRetVal) = 0;
virtual int EndFunction(bool bRetVal) = 0;
virtual int EndFunction(IScriptObject *pObj) = 0;
virtual int EndFunction(HSCRIPTFUNCTION hFunc) = 0;
virtual int EndFunction(USER_DATA ud) = 0;
virtual int EndFunction() = 0;
// 2 return params versions.
virtual int EndFunction(int nRetVal1,int nRetVal2) = 0;
virtual int EndFunction(float fRetVal1,float fRetVal2) = 0;
//##@}
virtual void Unref(HSCRIPTFUNCTION hFunc) = 0;
};
//DOC-IGNORE-BEGIN
//! under development
struct ScriptDebugInfo{
const char *sSourceName;
int nCurrentLine;
};
//! under development
struct IScriptDebugSink{
virtual void OnLoadSource(const char *sSourceName,unsigned char *sSource,long nSourceSize)=0;
virtual void OnExecuteLine(ScriptDebugInfo &sdiDebugInfo)=0;
};
//DOC-IGNORE-END
/////////////////////////////////////////////////////////////////////////////
//Utility classes
/////////////////////////////////////////////////////////////////////////////
//#define USE_WEAK_OBJS
class _SmartScriptObject
{
_SmartScriptObject(const _SmartScriptObject&)
{
}
_SmartScriptObject& operator =(const _SmartScriptObject &)
{
return *this;
}
_SmartScriptObject& operator =(IScriptObject *)
{
return *this;
}
public:
_SmartScriptObject()
{
m_pSO=NULL;
}
explicit _SmartScriptObject(IScriptSystem *pSS,IScriptObject *p)
{
m_pSO=pSS->CreateEmptyObject();
m_pSO->Attach(p);
}
explicit _SmartScriptObject(IScriptSystem *pSS,bool bCreateEmpty=false)
{
if(!bCreateEmpty)
{
m_pSO=pSS->CreateObject();
}
else{
m_pSO=pSS->CreateEmptyObject();
}
}
~_SmartScriptObject()
{
if(m_pSO)
m_pSO->Release();
}
IScriptObject *operator ->(){
return m_pSO;
}
IScriptObject *operator *(){
return m_pSO;
}
operator const IScriptObject*() const
{
return m_pSO;
}
operator IScriptObject*()
{
return m_pSO;
}
bool Create(IScriptSystem *pSS)
{
m_pSO=pSS->CreateObject();
return m_pSO?true:false;
}
//////////////////////////////////////////////////////////////////////////
// Boolean comparasions.
//////////////////////////////////////////////////////////////////////////
bool operator !() const
{
return m_pSO == NULL;
};
bool operator ==(const IScriptObject* p2) const
{
return m_pSO == p2;
};
bool operator ==(IScriptObject* p2) const
{
return m_pSO == p2;
};
bool operator !=(const IScriptObject* p2) const
{
return m_pSO != p2;
};
bool operator !=(IScriptObject* p2) const
{
return m_pSO != p2;
};
bool operator <(const IScriptObject* p2) const
{
return m_pSO < p2;
};
bool operator >(const IScriptObject* p2) const
{
return m_pSO > p2;
};
protected:
IScriptObject *m_pSO;
};
class _HScriptFunction
{
public:
_HScriptFunction(){m_pScriptSystem=0;m_hFunc=0;};
_HScriptFunction(IScriptSystem *pSS){m_pScriptSystem=pSS;m_hFunc=0;}
_HScriptFunction(IScriptSystem *pSS,HSCRIPTFUNCTION hFunc){m_pScriptSystem=pSS;m_hFunc=0;}
~_HScriptFunction(){ if(m_hFunc)m_pScriptSystem->ReleaseFunc(m_hFunc);m_hFunc=0; }
void Init(IScriptSystem *pSS,HSCRIPTFUNCTION hFunc){if(m_hFunc)m_pScriptSystem->ReleaseFunc(m_hFunc);m_hFunc=hFunc;m_pScriptSystem=pSS;}
operator HSCRIPTFUNCTION() const
{
return m_hFunc;
}
_HScriptFunction& operator =(HSCRIPTFUNCTION f){
if(m_hFunc)m_pScriptSystem->ReleaseFunc(m_hFunc);
m_hFunc=f;
return *this;
}
private:
HSCRIPTFUNCTION m_hFunc;
IScriptSystem *m_pScriptSystem;
};
extern "C"{
CRYSCRIPTSYSTEM_API IScriptSystem *CreateScriptSystem( ISystem *pSystem,IScriptSystemSink *pSink,IScriptDebugSink *pDebugSink,bool bStdLibs);
}
typedef IScriptSystem *(*CREATESCRIPTSYSTEM_FNCPTR)(ISystem *pSystem,IScriptSystemSink *pSink,IScriptDebugSink *pDebugSink,bool bStdLibs);
#endif //_ISCRIPTSYSTEM_H_

2399
CryCommon/IShader.h Normal file

File diff suppressed because it is too large Load Diff

622
CryCommon/ISound.h Normal file
View File

@@ -0,0 +1,622 @@
//////////////////////////////////////////////////////////////////////
//
// Crytek (C) 2001
//
// CrySound Source Code
//
// File: ISound.h
// Description: Sound interface.
//
// History:
// - August 28, 2001: Created by Marco Corbetta
//
//////////////////////////////////////////////////////////////////////
#ifndef CRYSOUND_ISOUND_H
#define CRYSOUND_ISOUND_H
//forward declarations
//////////////////////////////////////////////////////////////////////
#include "Cry_Math.h"
#include <vector>
#include <map>
#include "StlUtils.h"
#include "TString.h"
class CCamera;
struct IMusicSystem;
class ICrySizer;
struct IVisArea;
//////////////////////////////////////////////////////////////////////
#define MAX_SFX 1024
//////////////////////////////////////////////////////////////////////
#define FLAG_SOUND_LOOP 1<<0
#define FLAG_SOUND_2D 1<<1
#define FLAG_SOUND_3D 1<<2
#define FLAG_SOUND_STEREO 1<<3
#define FLAG_SOUND_16BITS 1<<4
#define FLAG_SOUND_STREAM 1<<5
#define FLAG_SOUND_RELATIVE 1<<6 // sound position moves relative to player
#define FLAG_SOUND_RADIUS 1<<7 // sound has a radius, custom attenuation calculation
#define FLAG_SOUND_DOPPLER 1<<8 // use doppler effect for this sound
#define FLAG_SOUND_NO_SW_ATTENUATION 1<<9 // doesn't use SW attenuation for this sound
#define FLAG_SOUND_MUSIC 1<<10 // pure music sound, to use to set pure music volume
#define FLAG_SOUND_OUTDOOR 1<<11 // play the sound only if the listener is in outdoor
#define FLAG_SOUND_INDOOR 1<<12 // play the sound only if the listener is in indoor
#define FLAG_SOUND_UNSCALABLE 1<<13 // for all sounds with this flag the volume can be scaled separately respect to the master volume
#define FLAG_SOUND_OCCLUSION 1<<14 // the sound uses sound occlusion
//#define FLAG_SOUND_FAILED 32768 // the loading of this sound has failed - do not try to load again every frame
#define FLAG_SOUND_LOAD_SYNCHRONOUSLY 1<<15 // the loading of this sound will be synchronous (asynchronously by default).
#define FLAG_SOUND_FADE_OUT_UNDERWATER 1<<16
#define FLAG_SOUND_ACTIVELIST (FLAG_SOUND_RADIUS | FLAG_SOUND_OCCLUSION | FLAG_SOUND_INDOOR | FLAG_SOUND_OUTDOOR)
#define SOUNDBUFFER_FLAG_MASK (FLAG_SOUND_LOOP | FLAG_SOUND_2D | FLAG_SOUND_3D | FLAG_SOUND_STEREO | FLAG_SOUND_16BITS | FLAG_SOUND_STREAM) // flags affecting the sound-buffer, not its instance
#define MAX_SOUNDSCALE_GROUPS 8
#define SOUNDSCALE_MASTER 0
#define SOUNDSCALE_SCALEABLE 1
#define SOUNDSCALE_DEAFNESS 2
#define SOUNDSCALE_UNDERWATER 3
#define SOUNDSCALE_MISSIONHINT 4
struct ISound;
//These values are used with CS_FX_Enable to enable DirectX 8 FX for a channel.
//////////////////////////////////////////////////////////////////////////////////////////////
enum SOUND_FX_MODES
{
S_FX_CHORUS,
S_FX_COMPRESSOR,
S_FX_DISTORTION,
S_FX_ECHO,
S_FX_FLANGER,
S_FX_GARGLE,
S_FX_I3DL2REVERB,
S_FX_PARAMEQ,
S_FX_WAVES_REVERB
};
//eax modes
//////////////////////////////////////////////////////////////////////////////////////////////
enum {
EAX_PRESET_OFF=0,
EAX_PRESET_GENERIC,
EAX_PRESET_PADDEDCELL,
EAX_PRESET_ROOM,
EAX_PRESET_BATHROOM,
EAX_PRESET_LIVINGROOM,
EAX_PRESET_STONEROOM,
EAX_PRESET_AUDITORIUM,
EAX_PRESET_CONCERTHALL,
EAX_PRESET_CAVE,
EAX_PRESET_ARENA,
EAX_PRESET_HANGAR,
EAX_PRESET_CARPETTEDHALLWAY,
EAX_PRESET_HALLWAY,
EAX_PRESET_STONECORRIDOR,
EAX_PRESET_ALLEY,
EAX_PRESET_FOREST,
EAX_PRESET_CITY,
EAX_PRESET_MOUNTAINS,
EAX_PRESET_QUARRY,
EAX_PRESET_PLAIN,
EAX_PRESET_PARKINGLOT,
EAX_PRESET_SEWERPIPE,
EAX_PRESET_UNDERWATER
};
//! Sound events sent to callback that can registered to every sound.
enum ESoundCallbackEvent
{
SOUND_EVENT_ON_LOADED, //!< Fired when sound is loaded.
SOUND_EVENT_ON_LOAD_FAILED, //!< Fired if sound loading is failed.
SOUND_EVENT_ON_PLAY, //!< Fired when sound is begin playing on channel.
SOUND_EVENT_ON_STOP //!< Fired when sound stops being playing on channel and frees channel.
};
//////////////////////////////////////////////////////////////////////////
//! Listener interface for the sound.
//////////////////////////////////////////////////////////////////////////
struct ISoundEventListener
{
//! Callback event.
virtual void OnSoundEvent( ESoundCallbackEvent event,ISound *pSound ) = 0;
};
// Marco's NOTE: this is a redefine of the EAX preset OFF, since it seems
// that audigy cards are having problems when the default EAX off preset
#define MY_CS_PRESET_OFF {0, 1.0f, 0.00f, -10000, -10000, -10000, 0.1f, 0.1f, 0.1f, -10000, 0.0f, { 0.0f,0.0f,0.0f }, -10000, 0.0f, { 0.0f,0.0f,0.0f }, 0.0750f, 0.00f, 0.04f, 0.000f, 0.0f, 1000.0f, 20.0f, 0.0f, 0.0f, 0.0f, 0 }
//////////////////////////////////////////////////////////////////////////////////////////////
//crysound definitions
#ifdef WIN64
#include <CrySound64.h>
#else
#include <CrySound.h>
#endif
//////////////////////////////////////////////////////////////////////////////////////////////
// Sound system interface
struct ISoundSystem
{
virtual void Release() = 0;
virtual void Update() = 0;
/*! Create a music-system. You should only create one music-system at a time.
*/
virtual IMusicSystem* CreateMusicSystem() = 0;
/*! Load a sound from disk
@param szfile filename
@param nFlags sound flags combination
@return sound interface
*/
virtual struct ISound* LoadSound(const char *szFile, int nFlags) = 0;
/*! SetMasterVolume
@param nVol volume (0-255)
*/
virtual void SetMasterVolume(unsigned char nVol) = 0;
/*! Set the volume scale for all sounds with FLAG_SOUND_SCALABLE
@param fScale volume scale (default 1.0)
*/
virtual void SetMasterVolumeScale(float fScale, bool bForceRecalc=false) = 0;
/*! Get a sound interface from the sound system
@param nSoundId sound id
*/
virtual struct ISound* GetSound(int nSoundID) = 0;
/*! Play a sound from the sound system
@param nSoundId sound id
*/
virtual void PlaySound(int nSoundID) = 0;
/*! Set the listener position
@param cCam camera position
@param vVel velocity
*/
virtual void SetListener(const CCamera &cCam, const Vec3 &vVel)=0;
/*! to be called when something changes in the environment which could affect
sound occlusion, for example a door closes etc.
@param bRecomputeListener recomputes the listener vis area
@param bForceRecompute forces to recompute the vis area connections even if
the listener didn't move (useful for moving objects that can occlude)
*/
virtual void RecomputeSoundOcclusion(bool bRecomputeListener,bool bForceRecompute,bool bReset=false)=0;
//! Check for EAX support.
virtual bool IsEAX( int version ) = 0;
//! Set EAX listener environment; one of the predefined presets
//! listened above or a custom environmental reverb set
virtual bool SetEaxListenerEnvironment(int nPreset, CS_REVERB_PROPERTIES *pProps=NULL, int nFlags=0) = 0;
//! Gets current EAX listener environment or one of the predefined presets
//! used to save into the savegame
virtual bool GetCurrentEaxEnvironment(int &nPreset, CS_REVERB_PROPERTIES &Props)=0;
//! Set the scaling factor for a specific scale group (0-31)
virtual bool SetGroupScale(int nGroup, float fScale) = 0;
//! Stop all sounds and music
virtual void Silence()=0;
//! pause all sounds
virtual void Pause(bool bPause,bool bResetVolume=false)=0;
//! Mute/unmute all sounds
virtual void Mute(bool bMute)=0;
//! get memory usage info
virtual void GetSoundMemoryUsageInfo(size_t &nCurrentMemory,size_t &nMaxMemory)=0;
//! get number of voices playing
virtual int GetUsedVoices()=0;
//! get cpu-usuage
virtual float GetCPUUsage()=0;
//! get music-volume
virtual float GetMusicVolume()=0;
//! sets parameters for directional attenuation (for directional microphone effect); set fConeInDegree to 0 to disable the effect
virtual void CalcDirectionalAttenuation(Vec3 &Pos, Vec3 &Dir, float fConeInRadians) = 0;
//! returns the maximum sound-enhance-factor to use it in the binoculars as "graphical-equalizer"...
virtual float GetDirectionalAttenuationMaxScale() = 0;
//! returns if directional attenuation is used
virtual bool UsingDirectionalAttenuation() = 0;
virtual void GetMemoryUsage(class ICrySizer* pSizer) = 0;
//! get the current area the listener is in
virtual IVisArea *GetListenerArea()=0;
//! get listener position
virtual Vec3 GetListenerPos()=0;
//! returns true if sound is being debugged
virtual bool DebuggingSound()=0;
//! Set minimal priority for sounds to be played.
//! Sound`s with priority less then that will not be played.
//! @return previous minimal priority.
virtual int SetMinSoundPriority( int nPriority ) = 0;
//! Lock all sound buffer resources to prevent them from unloading (when restoring checkpoint).
virtual void LockResources() = 0;
//! Unlock all sound buffer resources to prevent them from unloading.
virtual void UnlockResources() = 0;
};
//////////////////////////////////////////////////////////////////////////
// String Iterator
struct IStringItVec
{
virtual bool IsEnd() = 0;
virtual const char* Next() = 0;
virtual void MoveFirst() = 0;
virtual void AddRef() = 0;
virtual void Release() = 0;
};
//////////////////////////////
// A sound...
struct ISound
{
// Register listener to the sound.
virtual void AddEventListener( ISoundEventListener *pListener ) = 0;
virtual void RemoveEventListener( ISoundEventListener *pListener ) = 0;
virtual bool IsPlaying() = 0;
virtual bool IsPlayingVirtual() = 0;
//! Return true if sound is now in the process of asynchronous loading of sound buffer.
virtual bool IsLoading() = 0;
//! Return true if sound have already loaded sound buffer.
virtual bool IsLoaded() = 0;
virtual void Play(float fVolumeScale=1.0f, bool bForceActiveState=true, bool bSetRatio=true) = 0;
virtual void PlayFadeUnderwater(float fVolumeScale=1.0f, bool bForceActiveState=true, bool bSetRatio=true) = 0;
virtual void Stop() = 0;
//! Get name of sound file.
virtual const char* GetName() = 0;
//! Get uniq id of sound.
virtual const int GetId() = 0;
//! Set looping mode of sound.
virtual void SetLoopMode(bool bLoop) = 0;
virtual bool Preload() = 0;
//! retrieves the currently played sample-pos, in milliseconds or bytes
virtual unsigned int GetCurrentSamplePos(bool bMilliSeconds=false)=0;
//! set the currently played sample-pos in bytes or milliseconds
virtual void SetCurrentSamplePos(unsigned int nPos,bool bMilliSeconds)=0;
//! sets automatic pitching amount (0-1000)
virtual void SetPitching(float fPitching) = 0;
//! sets the volume ratio
virtual void SetRatio(float fRatio)=0;
//! Return frequency of sound.
virtual int GetFrequency() = 0;
//! Set sound pitch.
//! 1000 is default pitch.
virtual void SetPitch(int nPitch) = 0;
//! Set panning values
virtual void SetPan(int nPan)=0;
//! set the maximum distance / the sound will be stopped if the
//! distance from the listener and this sound is bigger than this max distance
// virtual void SetMaxSoundDistance(float fMaxSoundDistance)=0;
//! Set Minimal/Maximal distances for sound.
//! Sound is not attenuated below minimal distance and not heared outside of max distance.
virtual void SetMinMaxDistance(float fMinDist, float fMaxDist) = 0;
//! Define sound cone.
//! Angles are in degrees, in range 0-360.
virtual void SetConeAngles(float fInnerAngle,float fOuterAngle) = 0;
//! Add sound to specific sound-scale-group (0-31)
virtual void AddToScaleGroup(int nGroup) = 0;
//! Remove sound from specific sound-scale-group (0-31)
virtual void RemoveFromScaleGroup(int nGroup) = 0;
//! Set sound-scale-groups by bitfield.
virtual void SetScaleGroup(unsigned int nGroupBits) = 0;
//! Set sound volume.
//! Range: 0-100
virtual void SetVolume( int nVolume ) = 0;
//! Get sound volume.
virtual int GetVolume() = 0;
//! Set sound source position.
//IVO
virtual void SetPosition(const Vec3 &pos) = 0;
//! Get sound source position.
virtual const bool GetPosition(Vec3 &vPos) = 0;
//! Set sound source velocity.
virtual void SetVelocity(const Vec3 &vel) = 0;
//! Get sound source velocity.
virtual Vec3 GetVelocity( void ) = 0;
//! Set orientation of sound.
//! Only relevant when cone angles are specified.
virtual void SetDirection( const Vec3 &dir ) = 0;
virtual Vec3 GetDirection() = 0;
virtual void SetLoopPoints(const int iLoopStart, const int iLoopEnd) = 0;
virtual bool IsRelative() const = 0;
// Add/remove sounds.
virtual int AddRef() = 0;
virtual int Release() = 0;
/* Sets certain sound properties
//@param fFadingValue the value that should be used for fading / sound occlusion
// more to come
*/
virtual void SetSoundProperties(float fFadingValue)=0;
//virtual void AddFlags(int nFlags) = 0;
//! enable fx effects for this sound
//! must be called after each play
virtual void FXEnable(int nEffectNumber)=0;
virtual void FXSetParamEQ(float fCenter,float fBandwidth,float fGain)=0;
//! returns the size of the stream in ms
virtual int GetLengthMs()=0;
//! returns the size of the stream in bytes
virtual int GetLength()=0;
//! set sound priority (0-255)
virtual void SetSoundPriority(unsigned char nSoundPriority)=0;
};
//////////////////////////////////////////////////////////////////////////
// MusicSystem
//////////////////////////////////////////////////////////////////////////
// Structures to pass as data-entry for musicsystem
//////////////////////////////////////////////////////////////////////////
struct SPatternDef;
struct SMusicPatternSet;
struct SMusicMood;
struct SMusicTheme;
// Helper integer-vector
typedef std::vector<int> TIntVec;
typedef TIntVec::iterator TIntVecIt;
typedef std::vector<SPatternDef*> TPatternDefVec;
typedef TPatternDefVec::iterator TPatternDefVecIt;
typedef std::map<CryBasicString,string,stl::less_stricmp<CryBasicString> > TThemeBridgeMap;
typedef TThemeBridgeMap::iterator TThemeBridgeMapIt;
typedef std::map<CryBasicString,SMusicMood*,stl::less_stricmp<CryBasicString> > TMoodMap;
typedef TMoodMap::iterator TMoodMapIt;
typedef std::vector<SMusicPatternSet*> TPatternSetVec;
typedef TPatternSetVec::iterator TPatternSetVecIt;
typedef std::map<CryBasicString,SMusicTheme*,stl::less_stricmp<CryBasicString> > TThemeMap;
typedef TThemeMap::iterator TThemeMapIt;
// Pattern-definition
struct SPatternDef
{
CryBasicString sName;
CryBasicString sFilename;
TIntVec vecFadePoints;
int nLayeringVolume;
float fProbability;
SPatternDef()
{
nLayeringVolume = 255;
fProbability = 0;
}
};
// PatternSet-Structure used by moods
struct SMusicPatternSet
{
float fMinTimeout;
float fMaxTimeout;
float fTotalMainPatternProbability; // added probabilities of all containing patterns
TPatternDefVec vecMainPatterns;
int nMaxSimultaneousRhythmicPatterns;
float fRhythmicLayerProbability;
float fTotalRhythmicPatternProbability; // added probabilities of all containing patterns
TPatternDefVec vecRhythmicPatterns;
int nMaxSimultaneousIncidentalPatterns;
float fIncidentalLayerProbability;
float fTotalIncidentalPatternProbability; // added probabilities of all containing patterns
TPatternDefVec vecIncidentalPatterns;
SMusicPatternSet()
{
fMinTimeout = 0;
fMaxTimeout = 0;
fRhythmicLayerProbability = 0;
fTotalMainPatternProbability = 0;
fTotalRhythmicPatternProbability = 0;
fIncidentalLayerProbability = 0;
fTotalIncidentalPatternProbability = 0;
nMaxSimultaneousRhythmicPatterns = 1;
nMaxSimultaneousIncidentalPatterns = 1;
}
};
// Mood-Structure
struct SMusicMood
{
CryBasicString sName;
int nPriority;
float fFadeOutTime;
TPatternSetVec vecPatternSets;
bool bPlaySingle;
// internal
SMusicPatternSet *pCurrPatternSet;
float fCurrPatternSetTime;
float fCurrPatternSetTimeout;
SMusicMood()
{
nPriority = 0;
fFadeOutTime = 0;
bPlaySingle = false;
pCurrPatternSet = NULL;
fCurrPatternSetTime = 0;
fCurrPatternSetTimeout = 0;
}
};
// Theme-Structure
struct SMusicTheme
{
CryBasicString sName;
TMoodMap mapMoods;
TThemeBridgeMap mapBridges;
// default mood
CryBasicString sDefaultMood;
float fDefaultMoodTimeout;
SMusicTheme()
{
fDefaultMoodTimeout = 0;
}
};
// Data-struct (which needs to be passed to SetData())
struct SMusicData
{
TPatternDefVec vecPatternDef;
TThemeMap mapThemes;
};
// Different layers
#define MUSICLAYER_MAIN 0
#define MUSICLAYER_RHYTHMIC 1
#define MUSICLAYER_INCIDENTAL 2
#define DEFAULT_CROSSFADE_TIME 3.0
//////////////////////////////////////////////////////////////////////////
// Status struct
//////////////////////////////////////////////////////////////////////////
struct SPlayingPatternsStatus
{
CryBasicString sName;
int nLayer;
int nVolume;
};
typedef std::vector<SPlayingPatternsStatus> TPatternStatusVec;
typedef TPatternStatusVec::iterator TPatternStatusVecIt;
struct SMusicSystemStatus
{
bool bPlaying;
CryBasicString sTheme;
CryBasicString sMood;
TPatternStatusVec m_vecPlayingPatterns;
};
//////////////////////////////////////////////////////////////////////////
// Main music-interface
//////////////////////////////////////////////////////////////////////////
struct IMusicSystem
{
virtual void Release() = 0;
virtual struct ISystem* GetSystem() = 0;
virtual int GetBytesPerSample() = 0;
virtual struct IMusicSystemSink* SetSink(struct IMusicSystemSink *pSink) = 0;
virtual bool SetData(struct SMusicData *pMusicData,bool bNoRelease=false) = 0;
virtual void Unload() = 0;
virtual void Pause(bool bPause) = 0;
virtual void EnableEventProcessing(bool bEnable) = 0;
virtual bool ResetThemeOverride() = 0;
virtual bool SetTheme(const char *pszTheme, bool bOverride=false) = 0;
virtual const char* GetTheme() = 0;
virtual bool SetMood(const char *pszMood) = 0;
virtual bool SetDefaultMood(const char *pszMood) = 0;
virtual const char* GetMood() = 0;
virtual IStringItVec* GetThemes() = 0;
virtual IStringItVec* GetMoods(const char *pszTheme) = 0;
virtual bool AddMusicMoodEvent(const char *pszMood, float fTimeout) = 0;
virtual void Update() = 0;
virtual SMusicSystemStatus* GetStatus() = 0; // retrieve status of music-system... dont keep returning pointer !
virtual void GetMemoryUsage(class ICrySizer* pSizer) = 0;
virtual bool LoadMusicDataFromLUA(struct IScriptSystem* pScriptSystem, const char *pszFilename) = 0;
virtual bool StreamOGG() = 0;
virtual void LogMsg( const char *pszFormat, ... ) = 0;
//////////////////////////////////////////////////////////////////////////
//! Load music data from XML.
//! @param bAddAdata if true data from XML will be added to currently loaded music data.
virtual bool LoadFromXML( const char *sFilename,bool bAddData ) = 0;
//////////////////////////////////////////////////////////////////////////
// Editing support.
//////////////////////////////////////////////////////////////////////////
virtual void UpdateTheme( SMusicTheme *pTheme ) = 0;
virtual void UpdateMood( SMusicMood *pMood ) = 0;
virtual void UpdatePattern( SPatternDef *pPattern ) = 0;
virtual void RenamePattern( const char *sOldName,const char *sNewName ) = 0;
virtual void PlayPattern( const char *sPattern,bool bStopPrevious ) = 0;
virtual void DeletePattern( const char *sPattern ) = 0;
virtual void Silence() = 0;
};
//////////////////////////////////////////////////////////////////////////
// Sink to release data (if allocated in a different DLL
//////////////////////////////////////////////////////////////////////////
struct IMusicSystemSink
{
virtual void ReleaseData(struct SMusicData *pData) = 0;
};
//////////////////////////////////////////////////////////////////////////////////////////////
typedef ISoundSystem* (*PFNCREATESOUNDSYSTEM)(struct ISystem*, void*);
#ifdef WIN32
extern "C"
#ifdef CRYSOUNDSYSTEM_EXPORTS
#define CRYSOUND_API __declspec(dllexport)
#else
#define CRYSOUND_API __declspec(dllimport)
#endif
#else //WIN32
#define CRYSOUND_API
#endif //WIN32
extern "C"
{
CRYSOUND_API ISoundSystem* CreateSoundSystem(struct ISystem*, void *pInitData);
}
#endif // CRYSOUND_ISOUND_H

291
CryCommon/IStatObj.h Normal file
View File

@@ -0,0 +1,291 @@
//////////////////////////////////////////////////////////////////////
//
// CryEngine Source code
//
// File:IStatObj.h
// Interface for CStatObj class
//
// History:
// -:Created by Vladimir Kajalin
//
//////////////////////////////////////////////////////////////////////
#ifndef _IStatObj_H_
#define _IStatObj_H_
// forward declarations
//////////////////////////////////////////////////////////////////////
class CIndexedMesh;
struct CLeafBuffer;
template <class T> class list2;
struct ShadowMapLightSourceInstance;
struct ShadowMapLightSource;
class CCObject;
struct ItShadowVolume;
struct IShader;
class CDLight;
class CIndoorArea;
//! Interface to non animated object
struct phys_geometry;
#include "IBindable.h"
// Summary:
// Interface to hold static object data
struct IStatObj: public IBindable
{
// Description:
// Provide access to the faces, vertices, texture coordinates, normals and
// colors of the object.
// Return Value:
//
// Summary:
// Get the object geometry
virtual CIndexedMesh * GetTriData()=0;
//! Access to rendering geometry for indoor engine ( optimized vert arrays, lists of shader pointers )
virtual CLeafBuffer * GetLeafBuffer()=0;
//! Assign leaf buffer to static object.
virtual void SetLeafBuffer( CLeafBuffer *buf ) = 0;
//! Prepare leaf buffer for lightmaps, return true if success
virtual bool EnableLightamapSupport() = 0;
// Description:
// Returns the physical representation of the object.
// Arguments:
// nType - Pass 0 to get the physic geometry or pass 1 to get the obstruct geometry
// Return Value:
// A pointer to a phys_geometry class.
// Summary:
// Get the physic representation
virtual phys_geometry * GetPhysGeom(int nType = 0)=0;
//! Returns script material name
virtual const char * GetScriptMaterialName(int Id=-1)=0;
// Return Value:
// A Vec3 object countaining the bounding box.
// Summary:
// Get the minimal bounding box component
virtual Vec3 GetBoxMin()=0;
// Return Value:
// A Vec3 object countaining the bounding box.
// Summary:
// Get the minimal bounding box component
virtual Vec3 GetBoxMax()=0;
// Arguments:
// Minimum bounding box component
// Summary:
// Set the minimum bounding box component
virtual void SetBBoxMin(const Vec3 &vBBoxMin)=0;
// Arguments:
// Minimum bounding box component
// Summary:
// Set the minimum bounding box component
virtual void SetBBoxMax(const Vec3 &vBBoxMax)=0;
// Summary:
// Get the object radius
// Return Value:
// A float containing the radius
virtual float GetRadius()=0;
//! Sets shader template for rendering
// virtual bool SetShaderTemplate(int nTemplate, const char *TemplName, const char *ShaderName, bool bOnlyRegister=false)=0;
//! Sets shader float parameter
virtual void SetShaderFloat(const char *Name, float Val)=0;
//DOC-IGNORE-BEGIN
// not implemented
//! Sets color parameter
virtual void SetColor(const char *Name, float fR, float fG, float fB, float fA)=0;
//DOC-IGNORE-END
// Description:
// Reloads one or more component of the object. The possible flags
// are FRO_SHADERS, FRO_TEXTURES and FRO_GEOMETRY.
// Arguments:
// nFlags - One or more flag which indicate which element of the object
// to reload
// Summary:
// Reloads the object
virtual void Refresh(int nFlags)=0;
// Description:
// Registers the object elements into the renderer.
// Arguments:
// rParams - Render parameters
// nLogLevel - Level of the LOD
// Summary:
// Renders the object
virtual void Render(const struct SRendParams & rParams, const Vec3& t, int nLodLevel=0)=0;
// Description:
// Returns the LOD object, if present.
// Arguments:
// nLodLevel - Level of the LOD
// Return Value:
// A static object with the desired LOD. The value NULL will be return if
// there isn't any LOD object for the level requested.
// Summary:
// Get the LOD object
virtual IStatObj * GetLodObject(int nLodLevel)=0;
// Description:
// Draw the shadow volumes for the object into the stencil buffer.
// Arguments:
// rParams - Rendering Parameters
// nLimitLOD - The maximum LOD to be used, this functionality may or
// may not supported in the implementation
// Summary:
// Draw the shadow volumes
virtual void RenderShadowVolumes(const struct SRendParams *pParams, int nLimitLod = -1)=0;
// Description:
// Returns a light source specified by the id.
// Arguments:
// nId - Id of the light source
// Return Value:
// A pointer to a CDLight object will be returned. In case the id
// specified as parameter was out of range, the value NULL will be
// returned.
// Summary:
// Get the light sources
virtual const CDLight * GetLightSources(int nId) = 0;
// Summary:
// Returns the folder name of the object
// Return Value:
// A null terminated string which contain the folder name of the object.
virtual const char *GetFolderName()=0;
// Summary:
// Returns the filename of the object
// Return Value:
// A null terminated string which contain the filename of the object.
virtual const char *GetFileName()=0;
// Summary:
// Returns the name of the geometry
// Return Value:
// A null terminated string which contains the name of the geometry
virtual const char *GetGeoName()=0;
// Summary:
// Compares if another object is the same
// Arguments:
// szFileName - Filename of the object to compare
// szGeomName - Geometry name of the object to compare (optional)
// Return Value:
// A boolean which equals to true in case both object are the same, or false in the opposite case.
virtual bool IsSameObject(const char * szFileName, const char * szGeomName)=0;
// Description:
// Will return the position of the helper named in the argument. The
// helper should have been specified during the exporting process of
// the cgf file.
// Arguments:
// szHelperName - A null terminated string holding the name of the helper
// Return Value:
// A Vec3 object which contains the position.
// Summary:
// Gets the position of a specified helper
virtual Vec3 GetHelperPos(const char * szHelperName)=0;
//! Returns name, position and rotation for specified helper id, returns false if id is out of range
virtual const char *GetHelperById(int nId, Vec3 & vPos, Matrix44 * pMat = NULL, int * pnType = NULL)=0;
// Description:
// Will return the matrix of the helper named in the argument. The
// helper should have been specified during the exporting process of
// the cgf file.
// Arguments:
// szHelperName - A null terminated string holding the name of the helper
// Return Value:
// A Matrix44 of the object
// Summary:
// Gets the matrix of a specified helper
virtual const Matrix44 * GetHelperMatrixByName(const char * szHelperName) = 0;
// Description:
// Increase the reference count of the object.
// Summary:
// Notifies that the object is being used
virtual void RegisterUser() = 0;
// Description:
// Decrease the reference count of the object. If the reference count
// reaches zero, the object will be deleted from memory.
// Summary:
// Notifies that the object is no longer needed
virtual void UnregisterUser() = 0;
//DOC-IGNORE-BEGIN
//! Tell us if the object is not found
virtual bool IsDefaultObject()=0;
//DOC-IGNORE-END
// Summary: Unsupported. Should not be used.
virtual bool MakeObjectPicture(unsigned char * pRGBAData, int nWidth) = 0;
// Summary:
// Get the shadow volume object
// Return Value:
// An ItShadowVolume object.
virtual ItShadowVolume *GetShadowVolume()=0;
// Summary:
// Set the shadow volume object
// Arguments:
// pSvObj - A new shadow volume
virtual void SetShadowVolume(ItShadowVolume *pSvObj)=0;
//! returns occlusion volume in object space
virtual bool GetOcclusionVolume(list2<Vec3> * & plstOcclVolVerts, list2<int> * & plstOcclVolInds) = 0;
// Summary:
// Free the geometry data
virtual void FreeTriData() = 0;
//DOC-IGNORE-BEGIN
// Pushes the underlying tree of objects into the given Sizer object for statistics gathering
virtual void GetMemoryUsage(class ICrySizer* pSizer) {} // TODO: implement
//DOC-IGNORE-END
// Description:
// Will looks if the object has all the needed shaders to be used as vegetation.
// Return Value:
// true will be returned if the object can be used as vegetation, else false will be returned.
// Summary:
// Determines if the object can be used as vegetation
virtual bool CheckValidVegetation() = 0;
//DOC-IGNORE-BEGIN
//! used for sprites
virtual float & GetRadiusVert() = 0;
//! used for sprites
virtual float & GetRadiusHors() = 0;
//DOC-IGNORE-END
// Summary:
// Determines if the object has physics capabilities
virtual bool IsPhysicsExist() = 0;
// Summary:
// Starts preloading textures, shaders and sprites
virtual void PreloadResources(float fDist, float fTime, int dwFlags) = 0;
// Summary:
// Returns a pointer to the object
// Return Value:
// A pointer to the current object, which is simply done like this "return this;"
virtual struct IStatObj* GetIStatObj() {return this;}
};
#endif // _IStatObj_H_

380
CryCommon/IStreamEngine.h Normal file
View File

@@ -0,0 +1,380 @@
// This is the prototypes of interfaces that will be used for asynchronous
// I/O (streaming).
// THIS IS NOT FINAL AND IS SUBJECT TO CHANGE WITHOUT NOTICE
// Some excerpts explaining basic ideas behind streaming design here:
/*
* The idea is that the data loaded is ready for usage and ideally doesn't need further transformation,
* therefore the client allocates the buffer (to avoid extra copy). All the data transformations should take place in the Resource Compiler. If you have to allocate a lot of small memory objects, you should revise this strategy in favor of one big allocation (again, that will be read directly from the compiled file).
* Anyway, we can negotiate that the streaming engine allocates this memory.
* In the end, it could make use of a memory pool, and copying data is not the bottleneck in our engine
*
* The client should take care of all fast operations. Looking up file size should be fast on the virtual
* file system in a pak file, because the directory should be preloaded in memory
*/
#ifndef _CRY_COMMON_STREAM_ENGINE_HDR_
#define _CRY_COMMON_STREAM_ENGINE_HDR_
#include "smartptr.h"
struct StreamEngineParams;
class IStreamCallback;
class ICrySizer;
enum
{
ERROR_UNKNOWN_ERROR = 0xF0000000,
ERROR_UNEXPECTED_DESTRUCTION = 0xF0000001,
ERROR_INVALID_CALL = 0xF0000002,
ERROR_CANT_OPEN_FILE = 0xF0000003,
ERROR_REFSTREAM_ERROR = 0xF0000004,
ERROR_OFFSET_OUT_OF_RANGE = 0xF0000005,
ERROR_REGION_OUT_OF_RANGE = 0xF0000006,
ERROR_SIZE_OUT_OF_RANGE = 0xF0000007,
ERROR_CANT_START_READING = 0xF0000008,
ERROR_OUT_OF_MEMORY = 0xF0000009,
ERROR_ABORTED_ON_SHUTDOWN = 0xF000000A,
ERROR_OUT_OF_MEMORY_QUOTA = 0xF000000B,
ERROR_ZIP_CACHE_FAILURE = 0xF000000C,
ERROR_USER_ABORT = 0xF000000D
};
// these are the flags for the StreamReadParams structure
enum StreamReadParamsFlagEnum
{
// if this flag is set, the callback can be called from within stream engine's worker thread
// WARNING: Use with care
SRP_FLAGS_ASYNC_CALLBACK = 1,
// If this flag is set, the file will be read synchronously
// NOTE: Not implemented yet
SRP_FLAGS_SYNC_READ = 1 << 1,
// if this flag is set, the stream will be treated as "permanent" and the file handle will
// be cached. This is needed for files which are accessed frequently, e.g. Resource files.
SRP_FLAGS_MAKE_PERMANENT = 1<<2,
// if this flag is set and the stream was made permanent before (either explicitly because of
// the SRP_FLAGS_MAKE_PERMANENT flag, or implicitly because of the policy of the StreamEngine),
// the stream will be removed as soon as the last proxy will be released.
SRP_FLAGS_MAKE_TRANSIENT = 1 << 3,
// with this flag, the progress routine will be called asynchronously
SRP_FLAGS_ASYNC_PROGRESS = 1 << 4,
// this means that the path passed to StartRead is real path, and shouldn't undergo
// adjustments through mod searching mechanics
SRP_FLAGS_PATH_REAL = 1 << 5,
// if this is set, it is adviced that Update(0) be called during startread, which
// can effectively call the callback before StartRead returns
// SRP_IMMEDIATE_UPDATE and SRP_QUICK_RETURN are mutually exclusive
SRP_IMMEDIATE_UPDATE = 1 << 6,
// if this is set, it is adviced that Update(0) not be called during StartRead,
// which yields quicker response.
// SRP_IMMEDIATE_UPDATE and SRP_QUICK_RETURN are mutually exclusive
SRP_QUICK_STARTREAD = 1 << 7
};
//////////////////////////////////////////////////////////////////////////
// this is used as parameter to the asynchronous read function
// all the unnecessary parameters go here, because there are many of them
struct StreamReadParams
{
StreamReadParams (
//const char* _szFile,
//IStreamCallback* _pCallback,
DWORD_PTR _dwUserData = 0,
int _nPriority = 0,
unsigned _nLoadTime = 0,
unsigned _nMaxLoadTime = 0,
unsigned _nOffset = 0,
unsigned _nSize = 0,
void* _pBuffer = NULL,
unsigned _nFlags = 0
):
//szFile (_szFile),
//pCallback(_pCallback),
dwUserData (_dwUserData),
nPriority(_nPriority),
nLoadTime(_nLoadTime),
nMaxLoadTime(_nMaxLoadTime),
pBuffer (_pBuffer),
nOffset (_nOffset),
nSize (_nSize),
nFlags (_nFlags)
{
}
// file name
//const char* szFile;
// the callback
//IStreamCallback* pCallback;
// the user data that'll be used to call the callback
DWORD_PTR dwUserData;
// the priority of this read; INT_MIN is the idle, INT_MAX is the highest, 0 is the average
int nPriority;
// the desirable loading time, in milliseconds, from the time of call
// 0 means as fast as possible (desirably in this frame)
unsigned nLoadTime;
// the maximum load time, in milliseconds. 0 means forever. If the read lasts longer, it can be discarded.
// WARNING: avoid too small max times, like 1-10 ms, because many loads will be discarded in this case.
unsigned nMaxLoadTime;
// the buffer into which to read the file or the file piece
// if this is NULL, the streaming engine will supply the buffer
// DO NOT USE THIS BUFFER during read operation! DO NOT READ from it, it can lead to memory corruption!
void* pBuffer;
// offset in the file to read; if this is not 0, then the file read
// occurs beginning with the specified offset in bytes.
// the callback interface receives the size of already read data as nSize
// and generally behaves as if the piece of file would be a file of its own.
unsigned nOffset;
// number of bytes to read; if this is 0, then the whole file is read
// if nSize == 0 && nOffset != 0, then the file from the offset to the end is read
// If nSize != 0, then the file piece from nOffset is read, at most nSize bytes
// (if less, an error is reported). So, from nOffset byte to nOffset + nSize - 1 byte in the file
unsigned nSize;
// the combination of one or several flags from StreamReadParamsFlagEnum
unsigned nFlags;
};
class IReadStream;
//typedef IReadStream_AutoPtr auto ptr wrapper
TYPEDEF_AUTOPTR(IReadStream);
typedef IReadStream_AutoPtr IReadStreamPtr;
//////////////////////////////////////////////////////////////////////////
// The highest level. THere is only one StreamingEngine in the application
// and it controls all I/O streams.
struct IStreamEngine
{
public:
// general purpose flags
enum
{
// if this is set in the call to Update, the time quota for callbacks is ignored,
// and all the callbacks for which the data is available are called
FLAGS_DISABLE_CALLBACK_TIME_QUOTA = 1
};
// Starts asynchronous read from the specified file (the file may be on a
// virtual file system, in pak or zip file or wherever).
// Reads the file contents into the given buffer, up to the given size.
// Upon success, calls success callback. If the file is truncated or for other
// reason can not be read, calls error callback. THe callback can be NULL (in this case, the client should poll
// the returned IReadStream object; the returned object must be locked for that)
// NOTE: the error/success/ progress callbacks can also be called from INSIDE this function.
// pParams - PLACEHOLDER for the future additional parameters (like priority), or really
// a pointer to a structure that will hold the parameters if there are too many of them
//
// IReadStream is reference-counted and will be automatically deleted if you don't refer to it;
// If you don't store it immediately in an auto-pointer, it may be deleted as soon as on the next line of code,
// because the read operation may complete immediately inside StartRead() and the object is self-disposed
// as soon as the callback is called
//
// in some implementations disposal of the old pointers happen synchronously
// (in the main thread) outside StartRead() (it happens in the entity update),
// so you're guaranteed that it won't trash inside the calling function. However, this may change in the future
// and you'll be required to assign it to IReadStream immediately (StartRead will return IReadStream_AutoPtr then)
virtual IReadStreamPtr StartRead (const char* szSource, const char* szFile, IStreamCallback* pCallback = NULL, StreamReadParams* pParams = NULL) = 0;
// returns the size of the file; returns 0 if there's no such file.
// nCryPakFlags is the flag set as in ICryPak
virtual unsigned GetFileSize (const char* szFile, unsigned nCryPakFlags = 0) = 0;
// waits at most the specified number of milliseconds, or until at least one pending operation is completed
// nFlags: may have the following flag set:
// FLAGS_DISABLE_CALLBACK_TIME_QUOTA
virtual void Update (unsigned nFlags = 0) = 0;
// wait at most the specified time for the IO jobs to be completed.
// Returns the number of jobs that actually were completed (finalized) during the call.
// It may be different from the number of executed jobs.
virtual unsigned Wait(unsigned nMilliseconds, unsigned nFlags = 0) = 0;
//! Puts the memory statistics into the given sizer object
//! According to the specifications in interface ICrySizer
virtual void GetMemoryStatistics(ICrySizer *pSizer) = 0;
//! Enables or disables callback time quota per frame
virtual void SuspendCallbackTimeQuota(){}
virtual void ResumeCallbackTimeQuota(){}
//! lossy stream compression useful for network comunication (affects load/save as well)
//! /return 0=no compression
virtual DWORD GetStreamCompressionMask() const=0;
virtual ~IStreamEngine() {}
};
class AutoSuspendTimeQuota
{
public:
AutoSuspendTimeQuota(IStreamEngine* pStreamEngine)
{
m_pStreamEngine = pStreamEngine;
pStreamEngine->SuspendCallbackTimeQuota();
}
~AutoSuspendTimeQuota()
{
m_pStreamEngine->ResumeCallbackTimeQuota();
}
protected:
IStreamEngine* m_pStreamEngine;
};
class AutoResumeTimeQuota
{
public:
AutoResumeTimeQuota(IStreamEngine* pStreamEngine)
{
m_pStreamEngine = pStreamEngine;
pStreamEngine->ResumeCallbackTimeQuota();
}
~AutoResumeTimeQuota()
{
m_pStreamEngine->SuspendCallbackTimeQuota();
}
protected:
IStreamEngine* m_pStreamEngine;
};
//////////////////////////////////////////////////////////////////////////
// This is the file "handle" that can be used to query the status
// of the asynchronous operation on the file. The same object may be returned
// for the same file to multiple clients.
//
// It will actually represent the asynchronous object in memory, and will be
// thread-safe reference-counted (both AddRef() and Release() will be virtual
// and thread-safe, just like the others)
// USE:
// IReadStream_AutoPtr pReadStream = pStreamEngine->StartRead ("bla.xxx", this);
// OR:
// pStreamEngine->StartRead ("MusicSystem","bla.xxx", this);
class IReadStream: public _reference_target_MT
{
public:
// returns true if the file read was not successful.
virtual bool IsError() = 0;
// returns true if the file read was completed successfully
// check IsError to check if the whole requested file (piece) was read
virtual bool IsFinished() = 0;
// returns the number of bytes read so far (the whole buffer size if IsFinished())
// if bWait == true, then waits until the pending I/O operation completes
// returns the total number of bytes read (if it completes successfully, returns the size of block being read)
virtual unsigned int GetBytesRead(bool bWait=false) = 0;
// returns the buffer into which the data has been or will be read
// at least GetBytesRead() bytes in this buffer are guaranteed to be already read
// DO NOT USE THIS BUFFER during read operation! DO NOT READ from it, it can lead to memory corruption!
virtual const void* GetBuffer () = 0;
// tries to stop reading the stream; this is advisory and may have no effect
// but the callback will not be called after this. If you just destructing object,
// dereference this object and it will automatically abort and release all associated resources.
virtual void Abort() {}
// tries to raise the priority of the read; this is advisory and may have no effect
virtual void RaisePriority (int nPriority) {}
// Returns the transparent DWORD that was passed in the StreamReadParams::dwUserData field
// of the structure passed in the call to IStreamEngine::StartRead
virtual DWORD_PTR GetUserData() = 0;
// unconditionally waits until the callback is called
// i.e. if the stream hasn't yet finish, it's guaranteed that the user-supplied callback
// is called before return from this function (unless no callback was specified)
virtual void Wait() = 0;
protected:
// the clients are not allowed to destroy this object directly; only via Release()
virtual ~IReadStream() {}
};
//////////////////////////////////////////////////////////////////////////
// the callback that will be called by the streaming engine
// must be implemented by all clients that want to use StreamingEngine services
// NOTE:
// the pStream interface is guaranteed to be locked (have reference count > 0)
// while inside the function, but can vanish any time outside the function.
// If you need it, keep it from the beginning (after call to StartRead())
// some or all callbacks MAY be called from inside IStreamEngine::StartRead()
class IStreamCallback
{
public:
// For some applications, even partially loaded data can be useful.
// To have this callback possibly called, specify the corresponding flag in IStreamEngine::StartRead()
// This callback signals about finish of reading of nSize bytes to the specified buffer pData
// so the client can read that much data inside this callback
// NOTE:
// The default implementation is {} so the clients need not implement it if they don't care
// This callback is not guaranteed to be called.
// If this callback is called, it doesn't mean the data load will finish successfully;
// it still may not finish (then the OnError is called)
// nSize is always LESS than the requested data size; when it's equal, StreamOnFinish is called instead
virtual void StreamOnProgress (IReadStream* pStream) {}
// signals that reading the requested data has completed (with or without error).
// this callback is always called, whether an error occurs or not
// pStream will signal either IsFinished() or IsError() and will hold the (perhaps partially) read data until this interface is released
// GetBytesRead() will return the size of the file (the completely read buffer) in case of successful operation end
// or the size of partially read data in case of error (0 if nothing was read)
// Pending status is true during this callback, because the callback itself is the part of IO operation
// nError == 0 : Success
// nError != 0 : Error code
virtual void StreamOnComplete (IReadStream* pStream, unsigned nError) = 0;
};
enum StreamingStrategy
{
// First in-first out, the strategy which ignores priorities
SS_FIFO,
// Random order, ignoring priorities, but the sequence is chosen to read as fast as possible
SS_FAST,
// Inside the same priority class, first in - first out.
// The highest priorities get serviced first
SS_PRIORITIZED,
// attempt to make read smooth, taking priorities into account
SS_MULTISTREAM
};
//////////////////////////////////////////////////////////////////////////
// this is the approximate parameter block for the streaming engine
// set up
struct StreamEngineParams
{
// the strategy to use when queuing clients
StreamingStrategy nStrategy;
// the stream capacity to use, at most N bytes per second
// if read requests come faster than that, delay loading
unsigned nMaxBytesPerSecond;
// the maximum number of ticks (TICK is yet to be defined -
// CPU clock, or mcs, or ms, or whatever) to spend inside
// the callbacks per SECOND. If callbacks spend more than that,
// delay callback execution until the next frame
// The actual limit is per-frame, the streaming engine uses estimated
// FPS to calculate the per-frame max callback time.
unsigned nMaxCallbackTicksPerSecond;
// the maximum allowable simultaneously open streams
unsigned nMaxStreams;
};
#endif //_CRY_COMMON_STREAM_ENGINE_HDR_

View File

@@ -0,0 +1,85 @@
//////////////////////////////////////////////////////////////////////
//
// CryCommon Source Code
//
// File: IStreamPersist.h
// Description: IStreamPersist interface.
//
// History:
// - August 6, 2001: Created by Alberto Demichelis
//
//////////////////////////////////////////////////////////////////////
#ifndef GAME_ISTREAMPERSIST_H
#define GAME_ISTREAMPERSIST_H
#if _MSC_VER > 1000
# pragma once
#endif
struct IScriptObject;
class CStream;
enum DirtyFlags
{
DIRTY_NAME = 0x1,
DIRTY_POS = 0x2,
DIRTY_ANGLES = 0x4,
};
//!store the stream status per connection(per serverslot)
/*struct StreamStatus
{
StreamStatus()
{
nUserFlags=0;
nLastUpdate=0;
nUpdateNumber=0;
}
unsigned int nUserFlags;
unsigned int nLastUpdate;
unsigned int nUpdateNumber;
};*/
///////////////////////////////////////////////
/*! This interface must be implemented by all objects that must be serialized
through the network or file.
REMARKS: The main pourpose of the serialization is reproduce the game remotely
or saving and restoring.This mean that the object must not save everything
but only what really need to be restored correctly.
*/
struct IStreamPersist
{
/*! serialize the object to a bitstream(network)
@param stm the stream class that will store the bitstream
@return true if succeded,false failed
@see CStream
*/
virtual bool Write(CStream&) = 0;
/*! read the object from a stream(network)
@param stm the stream class that store the bitstream
@return true if succeded,false failed
@see CStream
*/
virtual bool Read(CStream&) = 0;
/*! check if the object must be syncronized since the last serialization
@return true must be serialized, false the object didn't change
*/
virtual bool IsDirty() = 0;
/*! serialize the object to a bitstream(file persistence)
@param stm the stream class that will store the bitstream
@param pStream script wrapper for the stream(optional)
@return true if succeded,false failed
@see CStream
*/
virtual bool Save(CStream &stm) = 0;
/*! read the object from a stream(file persistence)
@param stm the stream class that store the bitstream
@param pStream script wrapper for the stream(optional)
@return true if succeded,false failed
@see CStream
*/
virtual bool Load(CStream &stm,IScriptObject *pStream=NULL) = 0;
};
#endif // GAME_ISTREAMPERSIST_H

471
CryCommon/ISystem.h Normal file
View File

@@ -0,0 +1,471 @@
#ifndef _CRY_SYSTEM_H_
#define _CRY_SYSTEM_H_
#ifdef WIN32
#ifdef CRYSYSTEM_EXPORTS
#define CRYSYSTEM_API __declspec(dllexport)
#else
#define CRYSYSTEM_API __declspec(dllimport)
#endif
#else
#define CRYSYSTEM_API
#endif
#include "platform.h" // Needed for LARGE_INTEGER (for consoles).
////////////////////////////////////////////////////////////////////////////////////////////////
// Forward declarations
////////////////////////////////////////////////////////////////////////////////////////////////
#include <IXMLDOM.h>
#include <IXml.h>
#include <IValidator.h>
#include <ILog.h>
struct ISystem;
struct ILog;
struct IEntitySystem;
struct IEntity;
struct ICryPak;
struct IKeyboard;
struct IMouse;
struct IConsole;
struct IInput;
struct IRenderer;
struct IConsole;
struct IProcess;
struct I3DEngine;
struct ITimer;
struct IGame;
struct IScriptSystem;
struct IAISystem;
struct IFlash;
struct INetwork;
struct ICryFont;
struct IMovieSystem;
class IPhysicalWorld;
struct IMemoryManager;
struct ISoundSystem;
struct IMusicSystem;
struct XDOM::IXMLDOMDocument;
struct IFrameProfileSystem;
struct FrameProfiler;
struct IStreamEngine;
struct ICryCharManager;
struct SFileVersion;
struct IDataProbe;
class CFrameProfilerSection;
#define DEFAULT_GAME_PATH "FarCry"
#define DATA_FOLDER "FCData"
#define PROC_MENU 1
#define PROC_3DENGINE 2
//ID for script userdata typing (maybe they should be moved into the game.dll)
#define USER_DATA_SOUND 1
#define USER_DATA_TEXTURE 2
#define USER_DATA_OBJECT 3
#define USER_DATA_LIGHT 4
#define USER_DATA_BONEHANDLER 5
#define USER_DATA_POINTER 6
enum ESystemUpdateFlags
{
ESYSUPDATE_IGNORE_AI = 0x0001,
ESYSUPDATE_IGNORE_PHYSICS = 0x0002,
// Special update mode for editor.
ESYSUPDATE_EDITOR = 0x0004,
ESYSUPDATE_MULTIPLAYER = 0x0008
};
enum ESystemConfigSpec
{
CONFIG_LOW_SPEC = 0,
CONFIG_MEDIUM_SPEC = 1,
CONFIG_HIGH_SPEC = 2,
CONFIG_VERYHIGH_SPEC = 3,
};
// User defined callback, which can be passed to ISystem.
struct ISystemUserCallback
{
/** Signals to User that engine error occured.
@return true to Halt execution or false to ignore this error.
*/
virtual bool OnError( const char *szErrorString ) = 0;
/** If working in Editor environment notify user that engine want to Save current document.
This happens if critical error have occured and engine gives a user way to save data and not lose it
due to crash.
*/
virtual void OnSaveDocument() = 0;
/** Notify user that system wants to switch out of current process.
(For ex. Called when pressing ESC in game mode to go to Menu).
*/
virtual void OnProcessSwitch() = 0;
};
// Structure passed to Init method of ISystem interface.
struct SSystemInitParams
{
void *hInstance; //
void *hWnd; //
char szSystemCmdLine[512]; // command line, used to execute the early commands e.g. -DEVMODE "g_gametype ASSAULT"
ISystemUserCallback *pUserCallback; //
ILog *pLog; // You can specify your own ILog to be used by System.
IValidator *pValidator; // You can specify different validator object to use by System.
const char* sLogFileName; // File name to use for log.
bool bEditor; // When runing in Editor mode.
bool bPreview; // When runing in Preview mode (Minimal initialization).
bool bTestMode; // When runing in Automated testing mode.
bool bDedicatedServer; // When runing a dedicated server.
ISystem *pSystem; // Pointer to existing ISystem interface, it will be reused if not NULL.
// char szLocalIP[256]; // local IP address (needed if we have several servers on one machine)
#if defined(LINUX)
void (*pCheckFunc)(void*); // authentication function (must be set).
#else
void *pCheckFunc; // authentication function (must be set).
#endif
// Initialization defaults.
SSystemInitParams()
{
hInstance = 0;
hWnd = 0;
memset(szSystemCmdLine,0,sizeof(szSystemCmdLine));
pLog = 0;
pValidator = 0;
pUserCallback = 0;
sLogFileName = 0;
bEditor = false;
bPreview = false;
bTestMode = false;
bDedicatedServer = false;
pSystem = 0;
pCheckFunc = 0;
// memset(szLocalIP,0,256);
}
};
// Structure passed to CreateGame method of ISystem interface.
struct SGameInitParams
{
const char * sGameDLL; // Name of Game DLL. (Win32 Only)
IGame * pGame; // Pointer to already created game interface.
bool bDedicatedServer; // When runing a dedicated server.
char szGameCmdLine[256]; // command line, used to execute the console commands after game creation e.g. -DEVMODE "g_gametype ASSAULT"
SGameInitParams()
{
sGameDLL = NULL;
pGame = NULL;
bDedicatedServer = false;
memset(szGameCmdLine,0,256);
}
};
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
// Main Engine Interface
// initialize and dispatch all engine's subsystems
struct ISystem
{
// Loads GameDLL and creates game instance.
virtual bool CreateGame( const SGameInitParams &params ) = 0;
// Release ISystem.
virtual void Release() = 0;
// Update all subsystems (including the ScriptSink() )
// @param flags one or more flags from ESystemUpdateFlags sructure.
// @param boolean to set when in pause or cutscene mode in order to avoid
// certain subsystem updates 0=menu/pause, 1=cutscene mode
virtual bool Update( int updateFlags=0,int nPauseMode=0) = 0;
// update _time, _frametime (useful after loading level to apply the time value)
virtual void UpdateScriptSink()=0;
// Begin rendering frame.
virtual void RenderBegin() = 0;
// Render subsystems.
virtual void Render() = 0;
// End rendering frame and swap back buffer.
virtual void RenderEnd() = 0;
// Renders the statistics; this is called from RenderEnd, but if the
// Host application (Editor) doesn't employ the Render cycle in ISystem,
// it may call this method to render the essencial statistics
virtual void RenderStatistics () = 0;
// Retrieve the name of the user currently logged in to the computer
virtual const char *GetUserName() = 0;
// Gets current supported CPU features flags. (CPUF_SSE, CPUF_SSE2, CPUF_3DNOW, CPUF_MMX)
virtual int GetCPUFlags() = 0;
// Get seconds per processor tick
virtual double GetSecondsPerCycle() = 0;
// dumps the memory usage statistics to the log
virtual void DumpMemoryUsageStatistics() = 0;
// Quit the appliacation
virtual void Quit() = 0;
// Tells the system if it is relaunching or not
virtual void Relaunch(bool bRelaunch) = 0;
// return true if the application is in the shutdown phase
virtual bool IsQuitting() = 0;
// Display error message.
// Logs it to console and file and error message box.
// Then terminates execution.
virtual void Error( const char *sFormat,... ) = 0;
//DOC-IGNORE-BEGIN
//[Timur] DEPRECATED! Use Validator Warning instead.
// Display warning message.
// Logs it to console and file and display a warning message box.
// Not terminates execution.
//__declspec(deprecated) virtual void Warning( const char *sFormat,... ) = 0;
//DOC-IGNORE-END
// Report warning to current Validator object.
// Not terminates execution.
virtual void Warning( EValidatorModule module,EValidatorSeverity severity,int flags,const char *file,const char *format,... ) = 0;
// Compare specified verbosity level to the one currently set.
virtual bool CheckLogVerbosity( int verbosity ) = 0;
// returns true if this is dedicated server application
virtual bool IsDedicated() {return false;}
// return the related subsystem interface
virtual IGame *GetIGame() = 0;
virtual INetwork *GetINetwork() = 0;
virtual IRenderer *GetIRenderer() = 0;
virtual IInput *GetIInput() = 0;
virtual ITimer *GetITimer() = 0;
virtual IConsole *GetIConsole() = 0;
virtual IScriptSystem *GetIScriptSystem() = 0;
virtual I3DEngine *GetI3DEngine() = 0;
virtual ISoundSystem *GetISoundSystem() = 0;
virtual IMusicSystem *GetIMusicSystem() = 0;
virtual IPhysicalWorld *GetIPhysicalWorld() = 0;
virtual IMovieSystem *GetIMovieSystem() = 0;
virtual IAISystem *GetAISystem() = 0;
virtual IMemoryManager *GetIMemoryManager() = 0;
virtual IEntitySystem *GetIEntitySystem() = 0;
virtual ICryFont *GetICryFont() = 0;
virtual ICryPak *GetIPak() = 0;
virtual ILog *GetILog() = 0;
virtual IStreamEngine *GetStreamEngine() = 0;
virtual ICryCharManager *GetIAnimationSystem() = 0;
virtual IValidator *GetIValidator() = 0;
virtual IFrameProfileSystem* GetIProfileSystem() = 0;
//virtual const char *GetGamePath()=0;
virtual void DebugStats(bool checkpoint, bool leaks) = 0;
virtual void DumpWinHeaps() = 0;
virtual int DumpMMStats(bool log) = 0;
//////////////////////////////////////////////////////////////////////////
// @param bValue set to true when running on a cheat protected server or a client that is connected to it (not used in singlplayer)
virtual void SetForceNonDevMode( const bool bValue )=0;
// @return is true when running on a cheat protected server or a client that is connected to it (not used in singlplayer)
virtual bool GetForceNonDevMode() const=0;
virtual bool WasInDevMode() const=0;
virtual bool IsDevMode() const=0;
//////////////////////////////////////////////////////////////////////////
virtual XDOM::IXMLDOMDocument *CreateXMLDocument() = 0;
//////////////////////////////////////////////////////////////////////////
// IXmlNode interface.
//////////////////////////////////////////////////////////////////////////
// Creates new xml node.
virtual XmlNodeRef CreateXmlNode( const char *sNodeName="" ) = 0;
// Load xml file, return 0 if load failed.
virtual XmlNodeRef LoadXmlFile( const char *sFilename ) = 0;
// Load xml from string, return 0 if load failed.
virtual XmlNodeRef LoadXmlFromString( const char *sXmlString ) = 0;
virtual void SetViewCamera(class CCamera &Camera) = 0;
virtual CCamera& GetViewCamera() = 0;
virtual void CreateEntityScriptBinding(IEntity *pEntity)=0;
// When ignore update sets to true, system will ignore and updates and render calls.
virtual void IgnoreUpdates( bool bIgnore ) = 0;
// Set rate of Garbage Collection for script system.
// @param fRate in seconds
virtual void SetGCFrequency( const float fRate ) = 0;
/* Set the active process
@param process a pointer to a class that implement the IProcess interface
*/
virtual void SetIProcess(IProcess *process) = 0;
/* Get the active process
@return a pointer to the current active process
*/
virtual IProcess* GetIProcess() = 0;
#if defined (WIN32) || defined (PS2)
virtual IRenderer* CreateRenderer(bool fullscreen, void* hinst, void* hWndAttach = 0) = 0;
#endif
// Returns true if system running in Test mode.
virtual bool IsTestMode() const = 0;
virtual void ShowDebugger(const char *pszSourceFile, int iLine, const char *pszReason) = 0;
//////////////////////////////////////////////////////////////////////////
// Frame profiler functions
virtual void SetFrameProfiler(bool on, bool display, char *prefix) = 0;
// Starts section profiling.
virtual void StartProfilerSection( CFrameProfilerSection *pProfileSection ) = 0;
// Stops section profiling.
virtual void EndProfilerSection( CFrameProfilerSection *pProfileSection ) = 0;
//////////////////////////////////////////////////////////////////////////
// VTune Profiling interface.
// Resume vtune data collection.
virtual void VTuneResume() = 0;
// Pauses vtune data collection.
virtual void VTunePause() = 0;
//////////////////////////////////////////////////////////////////////////
virtual void Deltree(const char *szFolder, bool bRecurse) = 0;
//////////////////////////////////////////////////////////////////////////
// File version.
//////////////////////////////////////////////////////////////////////////
virtual const SFileVersion& GetFileVersion() = 0;
virtual const SFileVersion& GetProductVersion() = 0;
// Compressed file read & write
virtual bool WriteCompressedFile(char *filename, void *data, unsigned int bitlen) = 0;
virtual unsigned int ReadCompressedFile(char *filename, void *data, unsigned int maxbitlen) = 0;
virtual unsigned int GetCompressedFileSize(char *filename)=0;
// Sample: char str[256]; bool bRet=GetSSFileInfo("C:\\mastercd\\materials\\compound_indoor.xml",str,256);
// get info about the last SourceSafe action for a specifed file (Name,Comment,Date)
// @param inszFileName inszFileName!=0, e.g. "c:\\mastercd\\AssMan\\AssManShellExt\\AssManMenu.cpp"
// @param outszInfo outszInfo!=0, [0..indwBufferSize-1]
// @param indwBufferSize >0
// @return true=success, false otherwise (output parameter is set to empty strings)
virtual bool GetSSFileInfo( const char *inszFileName, char *outszInfo, const DWORD indwBufferSize )=0;
// Retrieve IDataProbe interface.
virtual IDataProbe* GetIDataProbe() = 0;
//////////////////////////////////////////////////////////////////////////
// Configuration.
//////////////////////////////////////////////////////////////////////////
// Saves system configuration.
virtual void SaveConfiguration() = 0;
// Loads system configuration
virtual void LoadConfiguration(const string &sFilename)=0;
// Get current configuration specification.
virtual ESystemConfigSpec GetConfigSpec() = 0;
};
//////////////////////////////////////////////////////////////////////////
// CrySystem DLL Exports.
//////////////////////////////////////////////////////////////////////////
typedef ISystem* (*PFNCREATESYSTEMINTERFACE)( SSystemInitParams &initParams );
// Get the system interface (must be defined locally in each module)
extern ISystem *GetISystem();
// interface of the DLL
extern "C"
{
CRYSYSTEM_API ISystem* CreateSystemInterface( SSystemInitParams &initParams );
}
//////////////////////////////////////////////////////////////////////////
// Display error message.
// Logs it to console and file and error message box.
// Then terminates execution.
inline void CryError( const char *format,... )
{
if (!GetISystem())
return;
va_list ArgList;
char szBuffer[MAX_WARNING_LENGTH];
va_start(ArgList, format);
vsprintf(szBuffer, format, ArgList);
va_end(ArgList);
GetISystem()->Error( "%s",szBuffer );
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
// Display warning message.
// Logs it to console and file and display a warning message box.
// Not terminates execution.
inline void CryWarning( EValidatorModule module,EValidatorSeverity severity,const char *format,... )
{
if (!GetISystem() || !format)
return;
va_list ArgList;
char szBuffer[MAX_WARNING_LENGTH];
va_start(ArgList, format);
vsprintf(szBuffer, format, ArgList);
va_end(ArgList);
GetISystem()->Warning( module,severity,0,0,szBuffer );
}
//////////////////////////////////////////////////////////////////////////
// Simple log of data with low verbosity.
inline void CryLog( const char *format,... )
{
if (GetISystem() && GetISystem()->CheckLogVerbosity(8))
{
va_list args;
va_start(args,format);
GetISystem()->GetILog()->LogV( ILog::eMessage,format,args );
va_end(args);
}
}
//////////////////////////////////////////////////////////////////////////
// Very rarely used log comment.
inline void CryLogComment( const char *format,... )
{
if (GetISystem() && GetISystem()->CheckLogVerbosity(9))
{
va_list args;
va_start(args,format);
GetISystem()->GetILog()->LogV( ILog::eMessage,format,args );
va_end(args);
}
}
//////////////////////////////////////////////////////////////////////////
// Logs important data that must be printed regardless verbosity.
inline void CryLogAlways( const char *format,... )
{
if (GetISystem())
{
va_list args;
va_start(args,format);
GetISystem()->GetILog()->LogV( ILog::eAlways,format,args );
va_end(args);
}
}
//////////////////////////////////////////////////////////////////////////
// Additional headers.
//////////////////////////////////////////////////////////////////////////
#include <FrameProfiler.h>
#endif //_CRY_SYSTEM_H_

77
CryCommon/ITimer.h Normal file
View File

@@ -0,0 +1,77 @@
#ifndef _ITIMER_H_
#define _ITIMER_H_
#include "TimeValue.h" // CTimeValue
/*! Interface to the Timer System.
*/
////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////
struct ITimer
{
// virtual bool Init() = 0;
//! reset the timer
virtual void Reset() = 0;
//! update the timer every frame
virtual void Update() = 0;
//! return the current time as calculated by the last call to update
virtual const float GetCurrTime() const = 0;
//! return the current time as calculated by the last call to update
// virtual const CTimeValue GetFrameStart() const = 0;
//! return the current time
virtual const CTimeValue GetCurrTimePrecise() const = 0;
//! return the current time at the moment of the call
virtual const float GetAsyncCurTime()= 0;
//! return the time passed from the last update
virtual const float GetFrameTime() const = 0;
//! enable/disable timer
virtual void Enable(bool bEnable) = 0;
//! return the current framerate
virtual float GetFrameRate() = 0;
//! time profiling
virtual float gfGetTime() = 0;
//! time profiling
virtual float MeasureTime(const char* comment) = 0;
};
// this class is used for automatic profiling of a section of the code.
// create an instance of this class, and upon exiting from the code section
template <typename time>
class CITimerAutoProfiler
{
public:
CITimerAutoProfiler (ITimer* pTimer, time& rTime):
m_pTimer (pTimer),
m_rTime (rTime)
{
rTime -= pTimer->GetAsyncCurTime();
}
~CITimerAutoProfiler ()
{
m_rTime += m_pTimer->GetAsyncCurTime();
}
protected:
ITimer* m_pTimer;
time& m_rTime;
};
// include this string AUTO_PROFILE_SECTION(pITimer, g_fTimer) for the section of code where the profiler timer must be turned on and off
// The profiler timer is just some global or static float or double value that accumulates the time (in seconds) spent in the given block of code
// pITimer is a pointer to the ITimer interface, g_fTimer is the global accumulator
#define AUTO_PROFILE_SECTION(pITimer, g_fTimer) CITimerAutoProfiler<double> __section_auto_profiler(pITimer, g_fTimer)
#endif //_ITIMER_H_

92
CryCommon/IValidator.h Normal file
View File

@@ -0,0 +1,92 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2002.
// -------------------------------------------------------------------------
// File name: ivalidator.h
// Version: v1.00
// Created: 3/6/2003 by Timur.
// Compilers: Visual Studio.NET
// Description: IValidator interface used to check objects for warnings and errors
// Report missing resources or invalid files.
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#ifndef __ivalidator_h__
#define __ivalidator_h__
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define MAX_WARNING_LENGTH 4096
enum EValidatorSeverity
{
VALIDATOR_ERROR,
VALIDATOR_WARNING,
VALIDATOR_COMMENT
};
enum EValidatorModule
{
VALIDATOR_MODULE_UNKNOWN,
VALIDATOR_MODULE_RENDERER,
VALIDATOR_MODULE_3DENGINE,
VALIDATOR_MODULE_AI,
VALIDATOR_MODULE_ANIMATION,
VALIDATOR_MODULE_ENTITYSYSTEM,
VALIDATOR_MODULE_SCRIPTSYSTEM,
VALIDATOR_MODULE_SYSTEM,
VALIDATOR_MODULE_SOUNDSYSTEM,
VALIDATOR_MODULE_GAME,
VALIDATOR_MODULE_MOVIE,
VALIDATOR_MODULE_EDITOR
};
enum EValidatorFlags
{
VALIDATOR_FLAG_FILE = 0x0001, // Indicate that required file was not found or file was invalid.
VALIDATOR_FLAG_TEXTURE = 0x0002, // Problem with texture.
VALIDATOR_FLAG_SCRIPT = 0x0004, // Problem with script.
VALIDATOR_FLAG_SOUND = 0x0008, // Problem with sound.
VALIDATOR_FLAG_AI = 0x0010, // Problem with AI.
};
struct SValidatorRecord
{
//! Severety of this error.
EValidatorSeverity severity;
//! In which module error occured.
EValidatorModule module;
//! Error Text.
const char *text;
//! File which is missing or causing problem.
const char *file;
//! Additional description for this error.
const char *description;
//! Flags that suggest kind of error.
int flags;
//////////////////////////////////////////////////////////////////////////
SValidatorRecord()
{
module = VALIDATOR_MODULE_UNKNOWN;
text = NULL;
file = NULL;
description = NULL;
severity = VALIDATOR_WARNING;
flags = 0;
}
};
/*! This interface will be givven to Validate methods of engine, for resources and objects validation.
*/
struct IValidator
{
virtual void Report( SValidatorRecord &record ) = 0;
};
#endif // __ivalidator_h__

204
CryCommon/IXGame.h Normal file
View File

@@ -0,0 +1,204 @@
#ifndef __IXGAME_H__
#define __IXGAME_H__
#include "IGame.h"
/* This interface exposes the basic functionality
to initialize and run the game.
*/
//////////////////////////////////////////////////////////////////////////
struct IXGame : public IGame
{
/* Initialize game.
@return true on success, false otherwise
*/
virtual bool Init(struct ISystem *pSystem,bool bDedicatedSrv,bool bInEditor,const char *szGameMod) = 0;
/*Upadate the module and all subsystems
@return false to stop the main loop
*/
virtual bool Update() = 0;
/*run the main loop until another subsystem force the exit
@return false to stop the main loop
*/
virtual bool Run(bool &bRelaunch) = 0;
/* Returns current MOD
NULL if FarCry, name of MOD otherwise
*/
virtual const char *IsMODLoaded() = 0;
/* Returns interface to access Game Mod functionality.
*/
virtual IGameMods* GetModsInterface() = 0;
/*Executes scheduled events, called by system before executing each fixed time step in multiplayer
*/
virtual void ExecuteScheduledEvents() = 0;
/*Tells whether fixed timestep physics in multiplayer is on
*/
virtual bool UseFixedStep() = 0;
/*Snaps to to fixed step
*/
virtual int SnapTime(float fTime,float fOffset=0.5f) = 0;
/*Snaps to to fixed step
*/
virtual int SnapTime(int iTime,float fOffset=0.5f) = 0;
/*returns fixed MP step in physworld time granularity
*/
virtual int GetiFixedStep() = 0;
/*returns fixed MP step
*/
virtual float GetFixedStep() = 0;
/*Shutdown and destroy the module (delete this)
*/
virtual void Release() = 0;
/*Load level [level editor only]
@param pszLevelDirectory level directory
*/
virtual bool LoadLevelForEditor(const char *pszLevelDirectory, const char *pszMissionName = 0) = 0;
/* Check if a sound is potentially hearable (used to check if loading a dialog is needed)
*/
virtual bool IsSoundPotentiallyHearable(Vec3d &SoundPos, float fClipRadius)=0;
/*Assign a material to a tarrain layer
*/
virtual void SetTerrainSurface(const char *sMaterial,int nLayerID)=0;
/*Get the local player entity[editor only]
*/
virtual IEntity *GetMyPlayer() = 0;
/*Get the entity class regitry
*/
virtual IEntityClassRegistry *GetClassRegistry() = 0;
/*Set the angles of the view camera of the game
*/
virtual void SetViewAngles(const Vec3 &angles) = 0;
/*Retrieves the player-system
*/
virtual class CPlayerSystem *GetPlayerSystem() = 0;
/* This function creates a tag point in the game world
*/
virtual ITagPoint *CreateTagPoint(const string &name, const Vec3 &pos, const Vec3 &angles) = 0;
/* Retieves a tag point by name
*/
virtual ITagPoint *GetTagPoint(const string &name) =0;
/* Deletes a tag point from the game
*/
virtual void RemoveTagPoint(ITagPoint *pPoint) = 0;
// shape
virtual IXArea *CreateArea( const Vec3 *vPoints, const int count, const std::vector<string> &names,
const int type=0, const int groupId=-1, const float width=0.0f, const float height=0.0f) = 0;
// box
virtual IXArea *CreateArea( const Vec3& min, const Vec3& max, const Matrix44& TM, const std::vector<string> &names,
const int type=0, const int groupId=-1, const float width=0.0f) = 0;
// sphere
virtual IXArea *CreateArea( const Vec3& center, const float radius, const std::vector<string> &names,
const int type=0, const int groupId=-1, const float width=0.0f) = 0;
// const char* const className, const int type=0, const float width=0.0f) = 0;
virtual void DeleteArea( const IXArea *pArea ) = 0;
virtual IXArea *GetArea( const Vec3 &point ) = 0;
// detect areas the listener is in before system update
virtual void CheckSoundVisAreas()=0;
// retrigger them if necessary after system update
virtual void RetriggerAreas()=0;
/* Returns an enumeration of the currently available weapons
*/
virtual INameIterator * GetAvailableWeaponNames() = 0;
virtual INameIterator * GetAvailableProjectileNames() = 0;
/* Add a weapon and load it
*/
virtual bool AddWeapon(const char *pszName) = 0;
/* Remove a loaded weapon by name
*/
virtual bool RemoveWeapon(const char *pszName) = 0;
/* Remove all loaded weapons
*/
virtual void RemoveAllWeapons() = 0;
virtual bool AddEquipPack(const char *pszXML) = 0;
virtual void RestoreWeaponPacks() = 0;
virtual void SetPlayerEquipPackName(const char *pszPackName) = 0;
virtual void SetViewMode(bool bThirdPerson) = 0;
virtual void AddRespawnPoint(ITagPoint *pPoint) = 0;
virtual void RemoveRespawnPoint(ITagPoint *pPoint) = 0;
virtual void OnSetVar(ICVar *pVar)=0;
virtual void SendMessage(const char *s)=0;
virtual void ResetState() = 0;
virtual void GetMemoryStatistics(ICrySizer *pSizer) = 0;
virtual void HideLocalPlayer( bool hide,bool bEditor ) = 0;
// saves player configuration
virtual void SaveConfiguration( const char *sSystemCfg,const char *sGameCfg,const char *sProfile)=0;
/* This is used by editor for changing properties from scripts (no restart).
*/
virtual void ReloadScripts()=0;
// sets a timer for a generic script object table
virtual int AddTimer(IScriptObject *pTable,unsigned int nStartTimer,unsigned int nTimer,IScriptObject *pUserData,bool bUpdateDuringPause)=0;
virtual CXServer *GetServer() = 0;
// functions to know if the current terminal is a server and/or a client
virtual bool IsServer() = 0;
virtual bool IsClient() = 0;
virtual bool IsMultiplayer()=0; // can be used for disabling cheats, or disabling features which cannot be synchronised over a network game
virtual bool IsDevModeEnable()=0;
virtual void EnableUIOverlay(bool bEnable, bool bExclusiveInput) = 0;
virtual bool IsUIOverlay() = 0;
virtual bool IsInMenu() = 0;
virtual void GotoMenu(bool bTriggerOnSwitch = false) = 0;
virtual void GotoGame(bool bTriggerOnSwitch = false) = 0;
// functions return callback sinks for the physics
virtual IPhysicsStreamer *GetPhysicsStreamer() = 0;
virtual IPhysicsEventClient *GetPhysicsEventClient() = 0;
// checks if gore enabled in the game
virtual bool GoreOn() const = 0;
// for compressed readwrite operation with CStreams
// /return you can assume the returned pointer is always valid
virtual IBitStream *GetIBitStream()=0;
// is called from time to time during loading (usually network updates)
// currently only called for server map loading
virtual void UpdateDuringLoading()=0;
virtual bool GetModuleState( EGameCapability eCap ) = 0;
virtual string& GetName() = 0;
virtual int GetInterfaceVersion() = 0;
};
//DOC-IGNORE-BEGIN
//## Macros used to access FarCry specific elements from it's previous IGame interface
#define CheckFarCryIGame_Begin( pGame ) \
{ \
if ( pGame != NULL && pGame->GetInterfaceVersion() == 1 ) \
{
#define CheckFarCryIGame_End() \
}\
}
#define GetIXGame( pGame ) ((IXGame*)pGame)
//DOC-IGNORE-END
#endif

139
CryCommon/IXMLDOM.h Normal file
View File

@@ -0,0 +1,139 @@
#ifndef _IXMLDOM_H_
#define _IXMLDOM_H_
#include <stdio.h>
#if !defined _XBOX && !defined(LINUX)
#ifdef CRYXMLDOM_EXPORTS
#define CRYXMLDOM_API __declspec(dllexport)
#else
#define CRYXMLDOM_API __declspec(dllimport)
#endif
#else
#define CRYXMLDOM_API
#endif
#define XMLCHAR char
#define __MSXML_LIBRARY_DEFINED__
//////////////////////////////////////////////////////////////////
#define USE_NAMESPACE
#include <string>
#ifdef USE_NAMESPACE
namespace XDOM{
#endif
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
struct IXMLDOMNodeList;
enum _DOMNodeType
{
NODE_ELEMENT,
NODE_ATTRIBUTE,
NODE_TEXT
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
struct IXMLDOMBase
{
virtual int AddRef() = 0;
virtual void Release() = 0;
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
struct IXMLDOMNode :
public IXMLDOMBase
{
virtual _DOMNodeType getNodeType() = 0;
virtual const char *getText() = 0;
virtual const char *getName() = 0;
virtual IXMLDOMNodeList *getChildNodes() = 0;
virtual void setText(const char *sText) = 0;
virtual void setName(const char *sName) = 0;
virtual bool hasChildNodes() = 0;
virtual bool appendChild(IXMLDOMNode *pNode) = 0;
virtual IXMLDOMNode *getAttribute(const XMLCHAR *sName) = 0;
virtual IXMLDOMNodeList *getElementsByTagName(const XMLCHAR *sName) = 0;
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
struct IXMLDOMNodeList :
public IXMLDOMBase
{
virtual size_t length() = 0;
virtual void reset() = 0;
virtual IXMLDOMNode *nextNode() = 0;
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
struct IXMLDOMDocument :
public IXMLDOMNode
{
virtual bool load(const XMLCHAR *sSourceFile) = 0;
virtual bool loadXML(const XMLCHAR *szString) = 0;
virtual IXMLDOMNode *getRootNode() = 0;
virtual IXMLDOMNode *createNode(_DOMNodeType Type, const char *name) = 0;
//virtual const XMLCHAR *getXML() = 0;
virtual const XMLCHAR *getErrorString() = 0;
virtual unsigned short getCheckSum() = 0;
};
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
#ifdef USE_NAMESPACE
}
#endif
#include "smartptr.h"
//////////////////////////////////////////////////////////////////
#include "Cry_Math.h"
#if defined(LINUX)
inline Vec3 StringToVector(std::string str)
#else
inline Vec3 StringToVector(string str)
#endif
{
Vec3 vTemp(0,0,0);
float x,y,z;
if (sscanf( str.c_str(),"%f,%f,%f",&x,&y,&z ) == 3)
{
vTemp(x,y,z);
}
else
{
vTemp(0,0,0);
}
return vTemp;
}
#ifdef USE_NAMESPACE
namespace XDOM{
#endif
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
typedef _smart_ptr <XDOM::IXMLDOMDocument> IXMLDOMDocumentPtr;
typedef _smart_ptr <XDOM::IXMLDOMNode> IXMLDOMNodePtr;
typedef _smart_ptr <XDOM::IXMLDOMNodeList> IXMLDOMNodeListPtr;
#ifdef USE_NAMESPACE
}
#endif
/*
extern "C"{
//hack (think if this can be solved in some clean way)
CRYXMLDOM_API XDOM::IXMLDOMDocument *CreateDOMDocument();
typedef XDOM::IXMLDOMDocument *( *CREATEDOMDOCUMENT_FNCPTR)();
}
*/
#endif //_IXMLDOM_H_

341
CryCommon/IXml.h Normal file
View File

@@ -0,0 +1,341 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2002.
// -------------------------------------------------------------------------
// File name: ixml.h
// Version: v1.00
// Created: 16/7/2002 by Timur.
// Compilers: Visual Studio.NET
// Description:
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#ifndef __ixml_h__
#define __ixml_h__
#if _MSC_VER > 1000
#pragma once
#endif
#include "platform.h"
#include <vector>
#include <set>
#ifdef _AFX
#include "Util\GuidUtil.h"
#endif //_AFX
/**
This is wrapper arround expat library to provide DOM type of access for xml.
Do not use IXmlNode class directly instead always use XmlNodeRef wrapper that
takes care of memory managment issues.
Usage Example:
-------------------------------------------------------
void testXml()
{
XmlParser xml;
XmlNodeRef root = xml.parse( "test.xml" );
if (root) {
for (int i = 0; i < root->getChildCount(); i++) {
XmlNodeRef child = root->getChild(i);
if (child->isTag("world")) {
if (child->getAttr("name") == "blah") {
}
}
}
}
};
*/
// Special string wrapper for xml nodes.
class XmlString : public string
{
public:
XmlString() {};
XmlString( const char *str ) : string(str) {};
#ifdef _AFX
XmlString( const CString &str ) : string( (const char*)str ) {};
#endif // _AFX
operator const char*() const { return c_str(); }
};
class IXmlNode;
/**
******************************************************************************
* XmlNodeRef, wrapper class implementing reference counting for IXmlNode.
******************************************************************************
*/
class XmlNodeRef {
private:
IXmlNode* p;
public:
XmlNodeRef() : p(NULL) {}
XmlNodeRef( int Null ) : p(NULL) {}
XmlNodeRef( IXmlNode* p_ );
XmlNodeRef( const XmlNodeRef &p_ );
//explicit XmlNodeRef( const char *tag,IXmlNode *node );
~XmlNodeRef();
operator IXmlNode*() const { return p; }
operator const IXmlNode*() const { return p; }
IXmlNode& operator*() const { return *p; }
IXmlNode* operator->(void) const { return p; }
XmlNodeRef& operator=( IXmlNode* newp );
XmlNodeRef& operator=( const XmlNodeRef &newp );
operator bool() const { return p != NULL; };
bool operator !() const { return p == NULL; };
// Misc compare functions.
bool operator == ( const IXmlNode* p2 ) const { return p == p2; };
bool operator == ( IXmlNode* p2 ) const { return p == p2; };
bool operator != ( const IXmlNode* p2 ) const { return p != p2; };
bool operator != ( IXmlNode* p2 ) const { return p != p2; };
bool operator < ( const IXmlNode* p2 ) const { return p < p2; };
bool operator > ( const IXmlNode* p2 ) const { return p > p2; };
bool operator == ( const XmlNodeRef &n ) const { return p == n.p; };
bool operator != ( const XmlNodeRef &n ) const { return p != n.p; };
bool operator < ( const XmlNodeRef &n ) const { return p < n.p; };
bool operator > ( const XmlNodeRef &n ) const { return p > n.p; };
friend bool operator == ( const XmlNodeRef &p1,int null );
friend bool operator != ( const XmlNodeRef &p1,int null );
friend bool operator == ( int null,const XmlNodeRef &p1 );
friend bool operator != ( int null,const XmlNodeRef &p1 );
};
/**
******************************************************************************
* IXmlNode class
* Never use IXmlNode directly instead use reference counted XmlNodeRef.
******************************************************************************
*/
class IXmlNode {
public:
virtual ~IXmlNode() {};
//! Create new XML node.
virtual XmlNodeRef createNode( const char *tag ) = 0;
//////////////////////////////////////////////////////////////////////////
//! Reference counting.
virtual void AddRef() = 0;
//! When ref count reach zero XML node dies.
virtual void Release() = 0;
//////////////////////////////////////////////////////////////////////////
//! Get XML node tag.
virtual const char *getTag() const = 0;
virtual void setTag( const char *tag ) = 0;
//! Return true if givven tag equal to node tag.
virtual bool isTag( const char *tag ) const = 0;
//! Get XML Node attributes.
virtual int getNumAttributes() const = 0;
//! Return attribute key and value by attribute index.
virtual bool getAttributeByIndex( int index,const char **key,const char **value ) = 0;
//! Copy attributes to this node from givven node.
virtual void copyAttributes( XmlNodeRef fromNode ) = 0;
//! Get XML Node attribute for specified key.
virtual const char* getAttr( const char *key ) const = 0;
//! Check if attributes with specified key exist.
virtual bool haveAttr( const char *key ) const = 0;
//! Adds new child node.
virtual void addChild( XmlNodeRef &node ) = 0;
//! Creates new xml node and add it to childs list.
virtual XmlNodeRef newChild( const char *tagName ) = 0;
//! Remove child node.
virtual void removeChild( XmlNodeRef &node ) = 0;
//! Remove all child nodes.
virtual void removeAllChilds() = 0;
//! Get number of child XML nodes.
virtual int getChildCount() const = 0;
//! Get XML Node child nodes.
virtual XmlNodeRef getChild( int i ) const = 0;
//! Find node with specified tag.
virtual XmlNodeRef findChild( const char *tag ) const = 0;
//! Get parent XML node.
virtual XmlNodeRef getParent() const = 0;
//! Returns content of this node.
virtual const char* getContent() const = 0;
virtual void setContent( const char *str ) = 0;
virtual void addContent( const char *str ) = 0;
//! Deep clone of this and all child xml nodes.
virtual XmlNodeRef clone() = 0;
//! Returns line number for XML tag.
virtual int getLine() const = 0;
//! Set line number in xml.
virtual void setLine( int line ) = 0;
//! Returns XML of this node and sub nodes.
virtual XmlString getXML( int level=0 ) const = 0;
virtual bool saveToFile( const char *fileName ) = 0;
//! Set new XML Node attribute (or override attribute with same key).
virtual void setAttr( const char* key,const char* value ) = 0;
virtual void setAttr( const char* key,int value ) = 0;
virtual void setAttr( const char* key,unsigned int value ) = 0;
virtual void setAttr( const char* key,float value ) = 0;
virtual void setAttr( const char* key,const Vec3 &value ) = 0;
virtual void setAttr( const char* key,const Quat &value ) = 0;
//////////////////////////////////////////////////////////////////////////
// Inline Helpers.
void setAttr( const char* key,unsigned long value ) { setAttr( key,(unsigned int)value ); };
void setAttr( const char* key,long value ) { setAttr( key,(int)value ); };
//////////////////////////////////////////////////////////////////////////
//! Delete attrbute.
virtual void delAttr( const char* key ) = 0;
//! Remove all node attributes.
virtual void removeAllAttributes() = 0;
//! Get attribute value of node.
virtual bool getAttr( const char *key,int &value ) const = 0;
virtual bool getAttr( const char *key,unsigned int &value ) const = 0;
virtual bool getAttr( const char *key,float &value ) const = 0;
virtual bool getAttr( const char *key,Vec3 &value ) const = 0;
virtual bool getAttr( const char *key,Quat &value ) const = 0;
virtual bool getAttr( const char *key,bool &value ) const = 0;
virtual bool getAttr( const char *key,XmlString &value ) const = 0;
//////////////////////////////////////////////////////////////////////////
// Inline Helpers.
bool getAttr( const char *key,long &value ) const { int v; if (getAttr(key,v)) { value = v; return true; } else return false; }
bool getAttr( const char *key,unsigned long &value ) const { unsigned int v; if (getAttr(key,v)) { value = v; return true; } else return false; }
bool getAttr( const char *key,unsigned short &value ) const { unsigned int v; if (getAttr(key,v)) { value = v; return true; } else return false; }
bool getAttr( const char *key,unsigned char &value ) const { unsigned int v; if (getAttr(key,v)) { value = v; return true; } else return false; }
bool getAttr( const char *key,short &value ) const { int v; if (getAttr(key,v)) { value = v; return true; } else return false; }
bool getAttr( const char *key,char &value ) const { int v; if (getAttr(key,v)) { value = v; return true; } else return false; }
#ifdef _AFX
//////////////////////////////////////////////////////////////////////////
// Get CString attribute.
//////////////////////////////////////////////////////////////////////////
bool getAttr( const char *key,CString &value ) const
{
if (!haveAttr(key))
return false;
value = getAttr(key);
return true;
}
//////////////////////////////////////////////////////////////////////////
// Set GUID attribute.
//////////////////////////////////////////////////////////////////////////
void setAttr( const char* key,REFGUID value )
{
const char *str = GuidUtil::ToString(value);
setAttr( key,str );
};
//////////////////////////////////////////////////////////////////////////
// Get GUID from attribute.
//////////////////////////////////////////////////////////////////////////
bool getAttr( const char *key,GUID &value ) const
{
if (!haveAttr(key))
return false;
const char *guidStr = getAttr(key);
value = GuidUtil::FromString( guidStr );
if (value.Data1 == 0)
{
memset( &value,0,sizeof(value) );
// If bad GUID, use old guid system.
value.Data1 = atoi(guidStr);
}
return true;
}
#endif //_AFX
//! Lets be friendly to him.
friend class XmlNodeRef;
};
/*
///////////////////////////////////////////////////////////////////////////////
// Inline Implementation of XmlNodeRef
inline XmlNodeRef::XmlNodeRef( const char *tag,IXmlNode *node )
{
if (node)
p = node->createNode( tag );
else
p = new XmlNode( tag );
p->AddRef();
}
*/
//////////////////////////////////////////////////////////////////////////
inline XmlNodeRef::XmlNodeRef( IXmlNode* p_ ) : p(p_)
{
if (p) p->AddRef();
}
inline XmlNodeRef::XmlNodeRef( const XmlNodeRef &p_ ) : p(p_.p)
{
if (p) p->AddRef();
}
inline XmlNodeRef::~XmlNodeRef()
{
if (p) p->Release();
}
inline XmlNodeRef& XmlNodeRef::operator=( IXmlNode* newp )
{
if (newp) newp->AddRef();
if (p) p->Release();
p = newp;
return *this;
}
inline XmlNodeRef& XmlNodeRef::operator=( const XmlNodeRef &newp )
{
if (newp.p) newp.p->AddRef();
if (p) p->Release();
p = newp.p;
return *this;
}
inline bool operator == ( const XmlNodeRef &p1,int null ) {
return p1.p == 0;
}
inline bool operator != ( const XmlNodeRef &p1,int null ) {
return p1.p != 0;
}
inline bool operator == ( int null,const XmlNodeRef &p1 ) {
return p1.p == 0;
}
inline bool operator != ( int null,const XmlNodeRef &p1 ) {
return p1.p != 0;
}
#endif // __ixml_h__

View File

@@ -0,0 +1,282 @@
#ifndef __LM_COMP_STRUCTURES_H__
#define __LM_COMP_STRUCTURES_H__
#pragma once
#include "IRenderer.h"
#include <IEntitySystem.h>
#include <vector>
#include <string>
#define USE_DOT3_ALPHA
#ifdef USE_DOT3_ALPHA
#define APPLY_COLOUR_FIX
#endif
#ifdef USE_DOT3_ALPHA
// #define USE_ALPHA_FOR_LOWSPEC
#endif
//lightmap generation modes
typedef enum ELMMode
{
ELMMode_ALL = 0,
ELMMode_CHANGES,
ELMMode_SEL
}ELMMode;
namespace NSAVE_RESULT
{
static const unsigned int ESUCCESS = 0;
static const unsigned int EPAK_FILE_UPDATE_FAIL = 1;
static const unsigned int EDXT_COMPRESS_FAIL = 2;
static const unsigned int EPAK_FILE_OPEN_FAIL = 3;
};
//! \brief Contains a Color + lerp factor / Dominant direction texture pair
struct RenderLMData : public _reference_target_t
{
//! \brief Requires renderer for texture resource release
RenderLMData(struct IRenderer *pIRenderer, int iColorLerpTex, int iHDRColorLerpTex, int iDomDirectionTex, int iOcclTex = 0)
{
m_pIRenderer = pIRenderer;
m_iColorLerpTex = iColorLerpTex;
m_iHDRColorLerpTex = iHDRColorLerpTex;
m_iDomDirectionTex = iDomDirectionTex;
m_iOcclTex = iOcclTex;
};
//! \brief Obtain textures
int GetColorLerpTex() { return m_iColorLerpTex; };
int GetHDRColorLerpTex() { return m_iHDRColorLerpTex; };
int GetDomDirectionTex() { return m_iDomDirectionTex; };
int GetOcclTex() { return m_iOcclTex; };
protected:
//! \brief Destrucktor protected, call Release()
~RenderLMData()
{
m_pIRenderer->RemoveTexture(m_iColorLerpTex);
m_pIRenderer->RemoveTexture(m_iDomDirectionTex);
if(m_iOcclTex != 0)
m_pIRenderer->RemoveTexture(m_iOcclTex);
if(m_iHDRColorLerpTex != 0)
m_pIRenderer->RemoveTexture(m_iHDRColorLerpTex);
};
struct IRenderer *m_pIRenderer; //!< Needed to correctly release texture resources
int m_iColorLerpTex; //!< Color + lerp factor texture
int m_iHDRColorLerpTex; //!< HDR Color in RGBE representation
int m_iDomDirectionTex; //!< Dominant direction texture
int m_iOcclTex; //!< occlusion map texture
};
TYPEDEF_AUTOPTR(RenderLMData);
struct LMGenParam
{
//! \brief Initializes fields with useable defaults
LMGenParam()
{
m_iTextureResolution = 256;
m_fTexelSize = 0.25f;
m_bDebugBorders = false;
m_iSubSampling = 9;
m_bGenOcclMaps = false;
m_iMinBlockSize = 4;
m_uiSmoothingAngle = 45;
m_bComputeShadows = true;
m_bUseSunLight = false;
m_bDontMergePolys = false;
m_bSpotAsPointlight = true;
m_bOnlyExportLights = false;
m_bHDR = false;
};
UINT m_iTextureResolution; //!< Resolution of the produced textures
float m_fTexelSize; //!< World space size of one texel
UINT m_iSubSampling; //!< Amount of sub-sampling used for shadows etc.
UINT m_iMinBlockSize; //!< Smallest possible block assigned on a lightmap
UINT m_uiSmoothingAngle; //!< smoothing angle where edge sharing triangles be treated as smooth even when the normal is not smoothed and normal generation gets smoothed to
bool m_bDebugBorders; //!< Add colored borders to the generated lightmaps
bool m_bGenOcclMaps; //!< indicates whether to generate occlusion maps or not
bool m_bComputeShadows; //!< Set to true to enable shadow casting
bool m_bUseSunLight; //!< Specifies if lighting coming from the sun should be taken into account
bool m_bDontMergePolys; //!<
bool m_bSpotAsPointlight; //!< overrides spotlight to be used as omnilight source
bool m_bOnlyExportLights; //!< Export only static lights sources, does not recompile lightmaps.
bool m_bHDR; //!< Generate HDR light map data in RGBE representation
};
struct TexCoord2Comp
{
TexCoord2Comp(float _s, float _t) { s = _s; t = _t; };
TexCoord2Comp() : s(0.f), t(0.f){};
float s;
float t;
};
//! \brief Callback interface for compiler output
struct ICompilerProgress
{
virtual void Output(const char *pszText) = 0;
};
struct LMStatLightFileHeader
{
LMStatLightFileHeader()
{
iVersion = 0;
iSizeOfDLight = sizeof(CDLight);
iNumDLights = 0;
};
uint8 iVersion;
UINT iSizeOfDLight;
UINT iNumDLights;
};
typedef struct SSharedLMEditorData
{
HWND hwnd; //!< window handle to set the progress
bool bCancelled; //!< if cancel has been pressed, change that to true
unsigned char ucProgress; //!< progress in percent (corresponds to processed GLMs)
unsigned int uiProgressMessage; //!< message to send to progress bar
unsigned int uiMemUsageMessage; //!< message to send to memory usage bar
unsigned int uiMemUsageStatic; //!< message to send to text for memory usage bar static element
unsigned int uiGLMNameEdit; //!< message to send to display the current glm name
SSharedLMEditorData() : ucProgress(0), uiMemUsageMessage(0), bCancelled(false), hwnd(0), uiMemUsageStatic(0), uiGLMNameEdit(0)
{}
}SSharedLMEditorData;
//!< colour corresponding to an stored occlusion index
typedef enum EOCCLCOLOURASSIGNMENT
{
EOCCLCOLOURASSIGNMENT_NONE = -1,
EOCCLCOLOURASSIGNMENT_RED = 0,
EOCCLCOLOURASSIGNMENT_GREEN,
EOCCLCOLOURASSIGNMENT_BLUE,
EOCCLCOLOURASSIGNMENT_ALPHA,
}EOCCLCOLOURASSIGNMENT;
typedef struct SOcclusionMapTexel
{
uint16 colour;
SOcclusionMapTexel() : colour(0){}
const SOcclusionMapTexel& operator =(const SOcclusionMapTexel& rTexel){colour = rTexel.colour; return *this;}
const bool operator ==(const SOcclusionMapTexel& rTexel)const{return rTexel.colour == colour;}
const bool operator !=(const SOcclusionMapTexel& rTexel)const{return rTexel.colour != colour;}
const uint8 operator [](const EOCCLCOLOURASSIGNMENT eChannel) const
{
switch(eChannel)
{
case EOCCLCOLOURASSIGNMENT_NONE:
assert(true);
return 0;
break;
case EOCCLCOLOURASSIGNMENT_BLUE:
return (uint8)(colour & 0x000F);
break;
case EOCCLCOLOURASSIGNMENT_GREEN:
return (uint8)((colour >> 4)& 0x000F);
break;
case EOCCLCOLOURASSIGNMENT_RED:
return (uint8)((colour >> 8)& 0x000F);
break;
case EOCCLCOLOURASSIGNMENT_ALPHA:
return (uint8)((colour >> 12)& 0x000F);
break;
}
return 0;
}
const SOcclusionMapTexel& SetValue(const EOCCLCOLOURASSIGNMENT eChannel, const uint8 cValue)
{
assert(cValue < 0x10);
switch(eChannel)
{
case EOCCLCOLOURASSIGNMENT_NONE:
assert(true);
break;
case EOCCLCOLOURASSIGNMENT_BLUE:
colour &= 0xFFF0;
colour |= cValue;
break;
case EOCCLCOLOURASSIGNMENT_GREEN:
colour &= 0xFF0F;
colour |= (((uint32)cValue) << 4);
break;
case EOCCLCOLOURASSIGNMENT_RED:
colour &= 0xF0FF;
colour |= (((uint32)cValue) << 8);
break;
case EOCCLCOLOURASSIGNMENT_ALPHA:
colour &= 0x0FFF;
colour |= (((uint32)cValue) << 12);
break;
}
return *this;
}
}SOcclusionMapTexel;
//!< colour channel info for GLM
typedef struct GLMOcclLightInfo
{
EOCCLCOLOURASSIGNMENT iChannelAssignment[4]; //!< channels assigned, -1 if not used, usually assigned in ascending order 0..3
unsigned int uiLightCount; //!< number of active lights
std::pair<EntityId, EntityId> iLightIDs[4];
GLMOcclLightInfo() : uiLightCount(0)
{
iChannelAssignment[0] = iChannelAssignment[1] = iChannelAssignment[2] = iChannelAssignment[3] = EOCCLCOLOURASSIGNMENT_NONE;
iLightIDs[0] = iLightIDs[1] = iLightIDs[2] = iLightIDs[3] = std::pair<EntityId, EntityId>(0,0);
}
const unsigned int UsedChannelCount()const{return uiLightCount;}
const EOCCLCOLOURASSIGNMENT FindLightSource(const std::pair<EntityId, EntityId>& ciID)
{
EOCCLCOLOURASSIGNMENT ret = EOCCLCOLOURASSIGNMENT_NONE;
int i = 0;
while(iChannelAssignment[i] != EOCCLCOLOURASSIGNMENT_NONE && i<4)
{
if(iLightIDs[i] == ciID)
return iChannelAssignment[i];
i++;
}
return ret;
}
const EOCCLCOLOURASSIGNMENT AddLightsource(const std::pair<EntityId, EntityId>& cID)
{
if(uiLightCount >= 4)
return EOCCLCOLOURASSIGNMENT_NONE;//already 4 light sources used
EOCCLCOLOURASSIGNMENT eChannel = FindLightSource(cID);
if(eChannel != EOCCLCOLOURASSIGNMENT_NONE)
return eChannel;//already contained
//else insert
switch(uiLightCount)
{
case 0:
iChannelAssignment[0] = EOCCLCOLOURASSIGNMENT_RED;
break;
case 1:
iChannelAssignment[1] = EOCCLCOLOURASSIGNMENT_GREEN;
break;
case 2:
iChannelAssignment[2] = EOCCLCOLOURASSIGNMENT_BLUE;
break;
case 3:
iChannelAssignment[3] = EOCCLCOLOURASSIGNMENT_ALPHA;
break;
}
iLightIDs[uiLightCount] = cID;
uiLightCount++;
return iChannelAssignment[uiLightCount-1];
}
}GLMOcclLightInfo;
//! \brief Name of the lightmap data file in the level's directory
#define LM_EXPORT_FILE_NAME "Dot3LM.dat"
//! \brief
#define LM_STAT_LIGHTS_EXPORT_FILE_NAME "StatLights.dat"
#endif // __LM_COMP_STRUCTURES_H__

372
CryCommon/LeafBuffer.h Normal file
View File

@@ -0,0 +1,372 @@
#ifndef _LEAFBUFFER_H_
#define _LEAFBUFFER_H_
class CIndexedMesh;
struct SMRendTexVert;
union UCol;
struct GeomInfo;
//! structure for tangent basises storing
struct TangData
{
Vec3 tangent;
Vec3 binormal;
Vec3 tnormal;
};
struct CLeafBuffer
{
//! constructor
//! /param szSource this pointer is stored - make sure the memory stays
CLeafBuffer( const char *szSource );
//! destructor
~CLeafBuffer();
// --------------------------------------------------------------
static CLeafBuffer m_Root;
CLeafBuffer * m_Next; //!<
CLeafBuffer * m_Prev; //!<
char * m_sSource; //!< pointer to the give name in the constructor call
_inline void Unlink()
{
if (!m_Next || !m_Prev)
return;
m_Next->m_Prev = m_Prev;
m_Prev->m_Next = m_Next;
m_Next = m_Prev = NULL;
}
_inline void Link( CLeafBuffer* Before )
{
if (m_Next || m_Prev)
return;
m_Next = Before->m_Next;
Before->m_Next->m_Prev = this;
Before->m_Next = this;
m_Prev = Before;
}
static CLeafBuffer m_RootGlobal; //!<
CLeafBuffer * m_NextGlobal; //!<
CLeafBuffer * m_PrevGlobal; //!<
_inline void UnlinkGlobal()
{
if (!m_NextGlobal || !m_PrevGlobal)
return;
m_NextGlobal->m_PrevGlobal = m_PrevGlobal;
m_PrevGlobal->m_NextGlobal = m_NextGlobal;
m_NextGlobal = m_PrevGlobal = NULL;
}
_inline void LinkGlobal( CLeafBuffer* Before )
{
if (m_NextGlobal || m_PrevGlobal)
return;
m_NextGlobal = Before->m_NextGlobal;
Before->m_NextGlobal->m_PrevGlobal = this;
Before->m_NextGlobal = this;
m_PrevGlobal = Before;
}
Vec3 * m_TempNormals; //!<
SMRendTexVert * m_TempTexCoords; //!<
UCol * m_TempColors; //!<
UCol * m_TempSecColors; //!<
void * m_pCustomData; //!< userdata, useful for PrepareBufferCallback, currently this is used only for CDetailGrass
bool (*PrepareBufferCallback)(CLeafBuffer *Data, bool bNeedTangents);
_inline void SetVertexContainer(CLeafBuffer *pBuf)
{
m_pVertexContainer = pBuf;
}
_inline CLeafBuffer *GetVertexContainer( void )
{
if (m_pVertexContainer)
return m_pVertexContainer;
return this;
}
_inline byte *GetNormalPtr(int& Stride, int Id=0, bool bSys=true)
{
CLeafBuffer *lb = GetVertexContainer();
byte *pData;
SBufInfoTable * pOffs;
if (bSys)
{
pData = (byte *)lb->m_pSecVertBuffer->m_VS[VSF_GENERAL].m_VData;
pOffs = &gBufInfoTable[lb->m_pSecVertBuffer->m_vertexformat];
Stride = m_VertexSize[lb->m_pSecVertBuffer->m_vertexformat];
}
else
{
pData = (byte *)lb->m_pVertexBuffer->m_VS[VSF_GENERAL].m_VData;
pOffs = &gBufInfoTable[lb->m_pVertexBuffer->m_vertexformat];
Stride = m_VertexSize[lb->m_pVertexBuffer->m_vertexformat];
}
if (pOffs->OffsNormal)
{
return &pData[Id*Stride+pOffs->OffsNormal];
}
Stride = sizeof(Vec3);
return (byte*)&lb->m_TempNormals[Id];
}
_inline byte *GetPosPtr(int& Stride, int Id=0, bool bSys=true)
{
CLeafBuffer *lb = GetVertexContainer();
byte *pData;
if (bSys)
{
pData = (byte *)lb->m_pSecVertBuffer->m_VS[VSF_GENERAL].m_VData;
Stride = m_VertexSize[lb->m_pSecVertBuffer->m_vertexformat];
}
else
{
pData = (byte *)lb->m_pVertexBuffer->m_VS[VSF_GENERAL].m_VData;
Stride = m_VertexSize[lb->m_pVertexBuffer->m_vertexformat];
}
return &pData[Id*Stride];
}
_inline byte *GetBinormalPtr(int& Stride, int Id=0, bool bSys=true)
{
CLeafBuffer *lb = GetVertexContainer();
byte *pData;
if (bSys)
{
pData = (byte *)lb->m_pSecVertBuffer->m_VS[VSF_TANGENTS].m_VData;
}
else
{
pData = (byte *)lb->m_pVertexBuffer->m_VS[VSF_TANGENTS].m_VData;
}
Stride = sizeof(SPipTangents);
return &pData[Id*Stride+12];
}
_inline byte *GetTangentPtr(int& Stride, int Id=0, bool bSys=true)
{
CLeafBuffer *lb = GetVertexContainer();
byte *pData;
if (bSys)
{
pData = (byte *)lb->m_pSecVertBuffer->m_VS[VSF_TANGENTS].m_VData;
}
else
{
pData = (byte *)lb->m_pVertexBuffer->m_VS[VSF_TANGENTS].m_VData;
}
Stride = sizeof(SPipTangents);
return &pData[Id*Stride];
}
_inline byte *GetTNormalPtr(int& Stride, int Id=0, bool bSys=true)
{
CLeafBuffer *lb = GetVertexContainer();
byte *pData;
if (bSys)
{
pData = (byte *)lb->m_pSecVertBuffer->m_VS[VSF_TANGENTS].m_VData;
}
else
{
pData = (byte *)lb->m_pVertexBuffer->m_VS[VSF_TANGENTS].m_VData;
}
Stride = sizeof(SPipTangents);
return &pData[Id*Stride+24];
}
_inline byte *GetColorPtr(int & Stride, int Id=0, bool bSys=true)
{
CLeafBuffer *lb = GetVertexContainer();
SBufInfoTable * pOffs;
byte *pData;
if (bSys)
{
pData = (byte *)lb->m_pSecVertBuffer->m_VS[VSF_GENERAL].m_VData;
pOffs = &gBufInfoTable[lb->m_pSecVertBuffer->m_vertexformat];
Stride = m_VertexSize[lb->m_pSecVertBuffer->m_vertexformat];
}
else
{
pData = (byte *)lb->m_pVertexBuffer->m_VS[VSF_GENERAL].m_VData;
pOffs = &gBufInfoTable[lb->m_pVertexBuffer->m_vertexformat];
Stride = m_VertexSize[lb->m_pVertexBuffer->m_vertexformat];
}
if (pOffs->OffsColor)
{
return &pData[Id*Stride+pOffs->OffsColor];
}
Stride = sizeof(UCol);
return (byte*)&lb->m_TempColors[Id];
}
_inline byte *GetSecColorPtr(int& Stride, int Id=0, bool bSys=true)
{
CLeafBuffer *lb = GetVertexContainer();
SBufInfoTable * pOffs;
byte *pData;
if (bSys)
{
pData = (byte *)lb->m_pSecVertBuffer->m_VS[VSF_GENERAL].m_VData;
pOffs = &gBufInfoTable[lb->m_pSecVertBuffer->m_vertexformat];
Stride = m_VertexSize[lb->m_pSecVertBuffer->m_vertexformat];
}
else
{
pData = (byte *)lb->m_pVertexBuffer->m_VS[VSF_GENERAL].m_VData;
pOffs = &gBufInfoTable[lb->m_pVertexBuffer->m_vertexformat];
Stride = m_VertexSize[lb->m_pVertexBuffer->m_vertexformat];
}
if (pOffs->OffsSecColor)
{
return &pData[Id*Stride+pOffs->OffsSecColor];
}
return NULL;
}
_inline byte *GetUVPtr(int & Stride, int Id=0, bool bSys=true)
{
CLeafBuffer *lb = GetVertexContainer();
SBufInfoTable * pOffs;
byte *pData;
if (bSys)
{
pData = (byte *)lb->m_pSecVertBuffer->m_VS[VSF_GENERAL].m_VData;
pOffs = &gBufInfoTable[lb->m_pSecVertBuffer->m_vertexformat];
Stride = m_VertexSize[m_pSecVertBuffer->m_vertexformat];
}
else
{
pData = (byte *)lb->m_pVertexBuffer->m_VS[VSF_GENERAL].m_VData;
pOffs = &gBufInfoTable[lb->m_pVertexBuffer->m_vertexformat];
Stride = m_VertexSize[m_pVertexBuffer->m_vertexformat];
}
if (pOffs->OffsTC)
{
return &pData[Id*Stride+pOffs->OffsTC];
}
Stride = sizeof(SMRendTexVert);
return (byte*)&lb->m_TempTexCoords[Id];
}
CVertexBuffer * m_pVertexBuffer; //!< video memory
CLeafBuffer * m_pVertexContainer; //!<
uint m_bMaterialsWasCreatedInRenderer : 1;
uint m_bOnlyVideoBuffer : 1;
uint m_bDynamic : 1;
uint m_UpdateVBufferMask; //!<
uint m_UpdateFrame;
uint m_SortFrame; //!< to prevent unneccessary sorting during one frame
int m_SecVertCount; //!< number of vertices in m_pSecVertBuffer
CVertexBuffer * m_pSecVertBuffer; //!< system memory
SVertexStream m_Indices;
TArray <ushort> m_SecIndices;
int m_NumIndices;
list2<ushort> * m_pIndicesPreStrip;
uint * m_arrVertStripMap; //!<
int m_nVertexFormat;
int m_nPrimetiveType; //!< R_PRIMV_TRIANGLES, R_PRIMV_TRIANGLE_STRIP, R_PRIMV...
list2<CMatInfo> * m_pMats; //!<
uint * m_arrVtxMap; //!< [Anton] mapping table leaf buffer vertex idx->original vertex idx
float m_fMinU, m_fMinV, m_fMaxU, m_fMaxV; //!< only needed for fur rendering (room for improvement)
//! /param StripType e.g. STRIPTYPE_NONE,STRIPTYPE_ONLYLISTS,STRIPTYPE_SINGLESTRIP,STRIPTYPE_MULTIPLESTRIPS,STRIPTYPE_DEFAULT (in IRenderer.h)
void StripifyMesh( int inStripType );
virtual void CalcFaceNormals( void );
virtual void AddRE(CCObject * pObj, IShader * pEf, int nNumSort=0, IShader * pStateEff = 0);
void SaveTexCoords(byte *pD, SBufInfoTable *pOffs, int Size);
void SaveColors(byte *pD, SBufInfoTable *pOffs, int Size);
void SaveSecColors(byte *pD, SBufInfoTable *pOffs, int Size);
void SaveNormals(byte *pD, SBufInfoTable *pOffs, int Size);
void SortTris();
bool ReCreateSystemBuffer(int VertFormat);
void UpdateDynBufPtr(int VertFormat);
virtual bool CheckUpdate(int VertFormat, int Flags, bool bNeedAddNormals);
virtual bool CreateTangBuffer();
virtual void ReleaseShaders();
virtual void InvalidateVideoBuffer(int flags=-1) { m_UpdateVBufferMask |= flags; };
virtual void CopyTo(CLeafBuffer *pDst, bool bUseSysBuf);
virtual void CreateBuffer( CIndexedMesh * pTriData, bool bStripifyAndShareVerts, bool bRemoveNoDrawFaces = true, bool bKeepRemapTable = false);
virtual bool CreateBuffer( struct VertexBufferSource* pSource );
virtual int GetAllocatedBytes( bool bVideoMem );
// compact buffer
int FindInBuffer(struct_VERTEX_FORMAT_P3F_N_COL4UB_TEX2F &opt, SPipTangents &origBasis, uint nMatInfo, uint *uiInfo, struct_VERTEX_FORMAT_P3F_N_COL4UB_TEX2F* _vbuff, SPipTangents *_vbasis, int _vcount, list2<unsigned short> * pHash, TArray<uint>& ShareNewInfo);
void CompactBuffer(struct_VERTEX_FORMAT_P3F_N_COL4UB_TEX2F *_vbuff, SPipTangents *_tbuff, int * _vcount, TArray<unsigned short> * pindices, bool bShareVerts[128], uint *uiInfo);
virtual void Unload();
virtual void UpdateCustomLighting(float fBackSideLevel, Vec3 vStatObjAmbientColor, const Vec3 & vLight, bool bCalcLighting);
virtual void AddRenderElements(CCObject * pObj=0, int DLightMask=0, int nTemplate=-1, int nFogVolumeID=0, int nSortId=0, IMatInfo * pIMatInfo=NULL);
virtual unsigned short *GetIndices(int *pIndicesCount);
virtual void DestroyIndices();
virtual void UpdateVidIndices(const ushort *pNewInds, int nInds);
virtual void UpdateSysIndices(const ushort *pNewInds, int nInds);
virtual void UpdateSysVertices(void * pNewVertices, int nNewVerticesCount);
virtual void UpdateVidVertices(void * pNewVertices, int nNewVerticesCount);
virtual bool CreateSysVertices(int nVerts, int VertFormat);
virtual void CreateVidVertices(int nVerts, int VertFormat);
virtual void SetRECustomData(float * pfCustomData, float fFogScale=0, float fAlpha=1);
virtual void SetChunk( IShader * pShader,
int nFirstVertId, int nVertCount,
int nFirstIndexId, int nIndexCount, int nMatID = 0,
bool bForceInitChunk = false);
int m_nClientTextureBindID;
virtual void SetShader( IShader * pShader, int nCustomTID = 0 );
virtual void * GetSecVerticesPtr(int * pVerticesCount);
//! /param Flags ????
//! /return memory consumption of the object in bytes
int Size( int Flags );
Vec3 m_vBoxMin, m_vBoxMax; //!< used for hw occlusion test
Vec3 * m_pLoadedColors; //!<
virtual void AllocateSystemBuffer( int nVertCount );
virtual void FreeSystemBuffer( void );
virtual bool Serialize(int & nPos, uchar * pSaveBuffer, bool bSaveToBuffer,
char * szFolderName, char * szFileName, double & dCIndexedMesh__LoadMaterial);
void SerializeMemBuffer(uchar * pSerialBuffer, uchar * pData, int nSize, bool bSaveToBuffer);
virtual void DrawImmediately( void );
bool LoadMaterial(int m,
const char *szFileName, const char *szFolderName,
list2<CMatInfo> & lstMatTable, IRenderer * pRenderer,
MAT_ENTITY * me, bool bFake);
static int SetTexType(struct TextureMap3 *tm);
virtual bool UpdateTangBuffer(SPipTangents *pBasis);
bool IsEmpty() { return !m_SecVertCount || !m_pSecVertBuffer || !m_SecIndices.Num(); }
virtual void RenderDebugLightPass(const Matrix44 & mat, int nLightMask, float fAlpha);
virtual void Render(const struct SRendParams & rParams, CCObject * pObj, TArray<int> & ShaderTemplates, int e_overlay_geometry, bool bNotCurArea, IMatInfo *pMaterial, bool bSupportDefaultShaderTemplates);
};
#endif // _LEAFBUFFER_H_

View File

@@ -0,0 +1,65 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2004.
// -------------------------------------------------------------------------
// File name: Linux32Specific.h
// Version: v1.00
// Created: 05/03/2004 by MarcoK.
// Compilers: Visual Studio.NET, GCC 3.2
// Description: Specific to Linux declarations, inline functions etc.
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#ifndef _CRY_COMMON_LINUX32_SPECIFIC_HDR_
#define _CRY_COMMON_LINUX32_SPECIFIC_HDR_
#include "LinuxSpecific.h"
// platform independent types
typedef signed char int8;
typedef signed short int16;
typedef signed int int32;
typedef signed long long int64;
typedef signed long long INT64;
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint32;
typedef unsigned long long uint64;
typedef float f32;
typedef double f64;
// old-style (will be removed soon)
typedef signed char s8;
typedef signed short s16;
typedef signed int s32;
typedef signed long long s64;
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned int u32;
typedef unsigned long long u64;
typedef DWORD DWORD_PTR;
typedef int intptr_t, INT_PTR, *PINT_PTR;
typedef unsigned int uintptr_t, UINT_PTR, *PUINT_PTR;
typedef char *LPSTR, *PSTR;
typedef long LONG_PTR, *PLONG_PTR, *PLONG;
typedef unsigned long ULONG_PTR, *PULONG_PTR;
typedef unsigned char BYTE;
typedef unsigned short WORD;
typedef void* HWND;
typedef UINT_PTR WPARAM;
typedef LONG_PTR LPARAM;
typedef LONG_PTR LRESULT;
#define PLARGE_INTEGER LARGE_INTEGER*
typedef const char *LPCSTR, *PCSTR;
typedef long long LONGLONG;
typedef ULONG_PTR SIZE_T;
typedef unsigned char byte;
#endif //_CRY_COMMON_LINUX32_SPECIFIC_HDR_

View File

@@ -0,0 +1,69 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2004.
// -------------------------------------------------------------------------
// File name: Linux32Specific.h
// Version: v1.00
// Created: 05/03/2004 by MarcoK.
// Compilers: Visual Studio.NET, GCC 3.2
// Description: Specific to Linux declarations, inline functions etc.
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#ifndef _CRY_COMMON_LINUX64_SPECIFIC_HDR_
#define _CRY_COMMON_LINUX64_SPECIFIC_HDR_
#include "LinuxSpecific.h"
#include </usr/include/stdint.h>
typedef signed char int8;
typedef signed short int16;
typedef signed int int32;
typedef signed long long int64;
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint32;
typedef unsigned long long uint64;
typedef float f32;
typedef double f64;
// old-style (will be removed soon)
typedef signed char s8;
typedef signed short s16;
typedef signed int s32;
typedef signed long long s64;
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned int u32;
typedef unsigned long long u64;
typedef uint64 DWORD_PTR;
typedef intptr_t INT_PTR, *PINT_PTR;
typedef uintptr_t UINT_PTR, *PUINT_PTR;
typedef char *LPSTR, *PSTR;
typedef unsigned long long __uint64;
typedef signed long long __int64;
typedef signed long long INT64;
typedef long long UINT64;
typedef long LONG_PTR, *PLONG_PTR, *PLONG;
typedef unsigned long ULONG_PTR, *PULONG_PTR;
typedef unsigned char BYTE;
typedef unsigned short WORD;
typedef void* HWND;
typedef UINT_PTR WPARAM;
typedef LONG_PTR LPARAM;
typedef LONG_PTR LRESULT;
#define PLARGE_INTEGER LARGE_INTEGER*
typedef const char *LPCSTR, *PCSTR;
typedef long long LONGLONG;
typedef ULONG_PTR SIZE_T;
typedef unsigned char byte;
#endif //_CRY_COMMON_LINUX64_SPECIFIC_HDR_

360
CryCommon/LinuxSpecific.h Normal file
View File

@@ -0,0 +1,360 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2004.
// -------------------------------------------------------------------------
// File name: Linux32Specific.h
// Version: v1.00
// Created: 05/03/2004 by MarcoK.
// Compilers: Visual Studio.NET, GCC 3.2
// Description: Specific to Linux declarations, inline functions etc.
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#ifndef _CRY_COMMON_LINUX_SPECIFIC_HDR_
#define _CRY_COMMON_LINUX_SPECIFIC_HDR_
#include <pthread.h>
#include <math.h>
#include <string.h>
#include <errno.h>
#include </usr/include/ctype.h>
typedef unsigned int DWORD;
typedef unsigned int* LPDWORD;
typedef void* LPVOID;
#define VOID void
#define PVOID void*
#define PHYSICS_EXPORTS
#ifdef __cplusplus
// checks if the heap is valid in debug; in release, this function shouldn't be called
// returns non-0 if it's valid and 0 if not valid
inline int IsHeapValid ()
{
return true;
}
#endif //__cplusplus
// MSVC compiler-specific keywords
#define __forceinline inline
#define _inline inline
#define __cdecl
#define __stdcall
#define __fastcall
#define IN
#define OUT
// Safe memory freeing
#ifndef SAFE_DELETE
#define SAFE_DELETE(p) { if(p) { delete (p); (p)=NULL; } }
#endif
#ifndef SAFE_DELETE_ARRAY
#define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p)=NULL; } }
#endif
#ifndef SAFE_RELEASE
#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } }
#endif
#ifndef SAFE_RELEASE_FORCE
#define SAFE_RELEASE_FORCE(p) { if(p) { (p)->Release(1); (p)=NULL; } }
#endif
#define MAKEWORD(a, b) ((WORD)(((BYTE)((DWORD_PTR)(a) & 0xff)) | ((WORD)((BYTE)((DWORD_PTR)(b) & 0xff))) << 8))
#define MAKELONG(a, b) ((LONG)(((WORD)((DWORD_PTR)(a) & 0xffff)) | ((DWORD)((WORD)((DWORD_PTR)(b) & 0xffff))) << 16))
#define LOWORD(l) ((WORD)((DWORD_PTR)(l) & 0xffff))
#define HIWORD(l) ((WORD)((DWORD_PTR)(l) >> 16))
#define LOBYTE(w) ((BYTE)((DWORD_PTR)(w) & 0xff))
#define HIBYTE(w) ((BYTE)((DWORD_PTR)(w) >> 8))
#define CALLBACK
#define WINAPI
#ifndef __cplusplus
#ifndef _WCHAR_T_DEFINED
typedef unsigned short wchar_t;
#define TCHAR wchar_t;
#define _WCHAR_T_DEFINED
#endif
#endif
typedef wchar_t WCHAR; // wc, 16-bit UNICODE character
typedef WCHAR *PWCHAR;
typedef WCHAR *LPWCH, *PWCH;
typedef const WCHAR *LPCWCH, *PCWCH;
typedef WCHAR *NWPSTR;
typedef WCHAR *LPWSTR, *PWSTR;
typedef WCHAR *LPUWSTR, *PUWSTR;
typedef const WCHAR *LPCWSTR, *PCWSTR;
typedef const WCHAR *LPCUWSTR, *PCUWSTR;
#define MAKEFOURCC(ch0, ch1, ch2, ch3) \
((DWORD)(BYTE)(ch0) | ((DWORD)(BYTE)(ch1) << 8) | \
((DWORD)(BYTE)(ch2) << 16) | ((DWORD)(BYTE)(ch3) << 24 ))
#define FILE_ATTRIBUTE_NORMAL 0x00000080
typedef int BOOL;
typedef int LONG;
typedef unsigned int ULONG;
typedef int HRESULT;
#define TRUE 1
#define FALSE 0
#ifndef MAX_PATH
#define MAX_PATH 256
#endif
#ifndef _MAX_PATH
#define _MAX_PATH MAX_PATH
#endif
//-------------------------------------socket stuff------------------------------------------
#define SOCKET int
#define INVALID_SOCKET (-1)
#define SOCKET_ERROR (-1)
typedef struct in_addr_windows
{
union
{
struct { unsigned char s_b1,s_b2,s_b3,s_b4; } S_un_b;
struct { unsigned short s_w1,s_w2; } S_un_w;
unsigned int S_addr;
} S_un;
}in_addr_windows;
#define WSAEINTR EINTR
#define WSAEBADF EBADF
#define WSAEACCES EACCES
#define WSAEFAULT EFAULT
#define WSAEACCES EACCES
#define WSAEFAULT EFAULT
#define WSAEINVAL EINVAL
#define WSAEMFILE EMFILE
#define WSAEWOULDBLOCK EAGAIN
#define WSAEINPROGRESS EINPROGRESS
#define WSAEALREADY EALREADY
#define WSAENOTSOCK ENOTSOCK
#define WSAEDESTADDRREQ EDESTADDRREQ
#define WSAEMSGSIZE EMSGSIZE
#define WSAEPROTOTYPE EPROTOTYPE
#define WSAENOPROTOOPT ENOPROTOOPT
#define WSAEPROTONOSUPPORT EPROTONOSUPPORT
#define WSAESOCKTNOSUPPORT ESOCKTNOSUPPORT
#define WSAEOPNOTSUPP EOPNOTSUPP
#define WSAEPFNOSUPPORT EPFNOSUPPORT
#define WSAEAFNOSUPPORT EAFNOSUPPORT
#define WSAEADDRINUSE EADDRINUSE
#define WSAEADDRNOTAVAIL EADDRNOTAVAIL
#define WSAENETDOWN ENETDOWN
#define WSAENETUNREACH ENETUNREACH
#define WSAENETRESET ENETRESET
#define WSAECONNABORTED ECONNABORTED
#define WSAECONNRESET ECONNRESET
#define WSAENOBUFS ENOBUFS
#define WSAEISCONN EISCONN
#define WSAENOTCONN ENOTCONN
#define WSAESHUTDOWN ESHUTDOWN
#define WSAETOOMANYREFS ETOOMANYREFS
#define WSAETIMEDOUT ETIMEDOUT
#define WSAECONNREFUSED ECONNREFUSED
#define WSAELOOP ELOOP
#define WSAENAMETOOLONG ENAMETOOLONG
#define WSAEHOSTDOWN EHOSTDOWN
#define WSAEHOSTUNREACH EHOSTUNREACH
#define WSAENOTEMPTY ENOTEMPTY
#define WSAEPROCLIM EPROCLIM
#define WSAEUSERS EUSERS
#define WSAEDQUOT EDQUOT
#define WSAESTALE ESTALE
#define WSAEREMOTE EREMOTE
//-------------------------------------end socket stuff------------------------------------------
#define __TIMESTAMP__ __DATE__" "__TIME__
// function renaming
#define _finite __finite
#define _snprintf snprintf
#define _isnan isnan
#define stricmp strcasecmp
#define _stricmp strcasecmp
#define strnicmp strncasecmp
#define _vsnprintf vsnprintf
#define _wtof( str ) wcstod( str, 0 )
/*static unsigned char toupper(unsigned char c)
{
return c & ~0x40;
}
*/
typedef union _LARGE_INTEGER
{
struct
{
DWORD LowPart;
LONG HighPart;
};
struct
{
DWORD LowPart;
LONG HighPart;
} u;
long long QuadPart;
} LARGE_INTEGER;
// stdlib.h stuff
#define _MAX_DRIVE 3 // max. length of drive component
#define _MAX_DIR 256 // max. length of path component
#define _MAX_FNAME 256 // max. length of file name component
#define _MAX_EXT 256 // max. length of extension component
// fcntl.h
#define _O_RDONLY 0x0000 /* open for reading only */
#define _O_WRONLY 0x0001 /* open for writing only */
#define _O_RDWR 0x0002 /* open for reading and writing */
#define _O_APPEND 0x0008 /* writes done at eof */
#define _O_CREAT 0x0100 /* create and open file */
#define _O_TRUNC 0x0200 /* open and truncate */
#define _O_EXCL 0x0400 /* open only if file doesn't already exist */
#define _O_TEXT 0x4000 /* file mode is text (translated) */
#define _O_BINARY 0x8000 /* file mode is binary (untranslated) */
#define _O_RAW _O_BINARY
#define _O_NOINHERIT 0x0080 /* child process doesn't inherit file */
#define _O_TEMPORARY 0x0040 /* temporary file bit */
#define _O_SHORT_LIVED 0x1000 /* temporary storage file, try not to flush */
#define _O_SEQUENTIAL 0x0020 /* file access is primarily sequential */
#define _O_RANDOM 0x0010 /* file access is primarily random */
// io.h stuff
typedef unsigned int _fsize_t;
struct _OVERLAPPED;
typedef void (*LPOVERLAPPED_COMPLETION_ROUTINE)(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, struct _OVERLAPPED *lpOverlapped);
typedef struct _OVERLAPPED
{
void* pCaller;//this is orginally reserved for internal purpose, we store the Caller pointer here
LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine; ////this is orginally ULONG_PTR InternalHigh and reserved for internal purpose
union {
struct {
DWORD Offset;
DWORD OffsetHigh;
};
PVOID Pointer;
};
DWORD dwNumberOfBytesTransfered; //additional member temporary speciying the number of bytes to be read
/*HANDLE*/void* hEvent;
} OVERLAPPED, *LPOVERLAPPED;
typedef struct _SECURITY_ATTRIBUTES
{
DWORD nLength;
LPVOID lpSecurityDescriptor;
BOOL bInheritHandle;
} SECURITY_ATTRIBUTES, *PSECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES;
#ifdef __cplusplus
static pthread_mutex_t mutex_t;
template<typename T>
const volatile T InterlockedIncrement(volatile T* pT)
{
pthread_mutex_lock(&mutex_t);
++(*pT);
pthread_mutex_unlock(&mutex_t);
return *pT;
}
template<typename T>
const volatile T InterlockedDecrement(volatile T* pT)
{
pthread_mutex_lock(&mutex_t);
--(*pT);
pthread_mutex_unlock(&mutex_t);
return *pT;
}
template<typename S, typename T>
inline const S& min(const S& rS, const T& rT)
{
return (rS <= rT)? rS : rT;
}
template<typename S, typename T>
inline const S& max(const S& rS, const T& rT)
{
return (rS >= rT)? rS : rT;
}
template<typename S, typename T>
inline const S& __min(const S& rS, const T& rT)
{
return min(rS, rT);
}
template<typename S, typename T>
inline const S& __max(const S& rS, const T& rT)
{
return max(rS, rT);
}
typedef enum {INVALID_HANDLE_VALUE = -1l}INVALID_HANDLE_VALUE_ENUM;
//for compatibility reason we got to create a class which actually contains an int rather than a void* and make sure it does not get mistreated
template <class T, T U>//U is default type for invalid handle value, T the encapsulated handle type to be used instead of void* (as under windows and never linux)
class CHandle
{
public:
typedef T HandleType;
typedef void* PointerType; //for compatibility reason to encapsulate a void* as an int
static const HandleType sciInvalidHandleValue = U;
CHandle(const CHandle<T,U>& cHandle) : m_Value(cHandle.m_Value){}
CHandle(const HandleType cHandle = U) : m_Value(cHandle){}
CHandle(const PointerType cpHandle) : m_Value(reinterpret_cast<HandleType>(cpHandle)){}
CHandle(INVALID_HANDLE_VALUE_ENUM) : m_Value(U){}//to be able to use a common value for all InvalidHandle - types
#if defined(LINUX64)
//treat __null tyope also as invalid handle type
CHandle(typeof(__null)) : m_Value(U){}//to be able to use a common value for all InvalidHandle - types
#endif
operator HandleType(){return m_Value;}
bool operator!() const{return m_Value == sciInvalidHandleValue;}
const CHandle& operator =(const CHandle& crHandle){m_Value = crHandle.m_Value;return *this;}
const CHandle& operator =(const PointerType cpHandle){m_Value = reinterpret_cast<HandleType>(cpHandle);return *this;}
const bool operator ==(const CHandle& crHandle) const{return m_Value == crHandle.m_Value;}
const bool operator ==(const HandleType cHandle) const{return m_Value == cHandle;}
const bool operator ==(const PointerType cpHandle)const{return m_Value == reinterpret_cast<HandleType>(cpHandle);}
const bool operator !=(const HandleType cHandle) const{return m_Value != cHandle;}
const bool operator !=(const CHandle& crHandle) const{return m_Value != crHandle.m_Value;}
const bool operator !=(const PointerType cpHandle)const{return m_Value != reinterpret_cast<HandleType>(cpHandle);}
const bool operator < (const CHandle& crHandle) const{return m_Value < crHandle.m_Value;}
HandleType Handle()const{return m_Value;}
private:
HandleType m_Value; //the actual value, remember that file descriptors are ints under linux
typedef void ReferenceType;//for compatibility reason to encapsulate a void* as an int
//forbid these function which would actually not work on an int
PointerType operator->();
PointerType operator->() const;
ReferenceType operator*();
ReferenceType operator*() const;
operator PointerType();
};
typedef CHandle<int, (int)-1l> HANDLE;
#endif //__cplusplus
#endif //_CRY_COMMON_LINUX_SPECIFIC_HDR_

5
CryCommon/MSSCCPRJ.SCC Normal file
View File

@@ -0,0 +1,5 @@
SCC = This is a source code control file
[CryCommon.vcproj]
SCC_Aux_Path = "P4SCC#perforce:1666##marcoc_code##PC018"
SCC_Project_Name = Perforce Project

View File

@@ -0,0 +1,287 @@
#ifndef _MAKEMATINFOFROMMAT_ENTITY_H_
#define _MAKEMATINFOFROMMAT_ENTITY_H_
// material loading code is shared between resource compiler and 3dengine
inline int SetTexType(TextureMap3 *tm)
{
if (tm->type == TEXMAP_CUBIC)
return eTT_Cubemap;
else
if (tm->type == TEXMAP_AUTOCUBIC)
return eTT_AutoCubemap;
return eTT_Base;
}
// szFileName - [May be NULL] the file name (without the path) of the file containing the MAT_ENTITY chunk
// szFolderName - the folder path where the file containing the MAT_ENTITY chunk resides; with the trailing shash.
// This is used for searching textures.
inline bool CIndexedMesh__LoadMaterial(const char *szFileName, const char *szFolderName,
CMatInfo & newMat, IRenderer * pRenderer, MAT_ENTITY * me)
{
SInputShaderResources Res;
memset(&Res, 0, sizeof(Res));
SLightMaterial LMs;
if (me->m_New && (me->col_d.r>5 || me->col_d.g>5 || me->col_d.b>5 || me->col_s.r>5 || me->col_s.g>5 || me->col_s.b>5))
{
Res.m_LMaterial = &LMs;
Res.m_LMaterial->Front.m_Ambient = CFColor(me->col_a.r/255.f,me->col_a.g/255.f,me->col_a.b/255.f);
Res.m_LMaterial->Front.m_Diffuse = CFColor(me->col_d.r/255.f,me->col_d.g/255.f,me->col_d.b/255.f);
Res.m_LMaterial->Front.m_Specular = CFColor(me->col_s.r/255.f,me->col_s.g/255.f,me->col_s.b/255.f);
Res.m_LMaterial->Front.m_Specular *= me->specLevel;
Res.m_LMaterial->Front.m_Specular.Clamp();
Res.m_LMaterial->Front.m_Emission = Res.m_LMaterial->Front.m_Diffuse * me->selfIllum;
Res.m_LMaterial->Front.m_SpecShininess = me->specShininess;
}
char diffuse[256]="";
strcpy(diffuse, me->map_d.name);
char bump[256]="";
strcpy(bump, me->map_b.name);
char normalmap[256]="";
if(me->map_displ.name[0] && (me->flags & MTLFLAG_CRYSHADER))
strcpy(normalmap, me->map_displ.name);
char opacity[256]="";
char decal[256]="";
if(me->map_o.name[0])
{
if (me->flags & MTLFLAG_CRYSHADER)
strcpy(decal, me->map_o.name);
else
strcpy(opacity, me->map_o.name);
}
char gloss[256]="";
if(me->map_g.name[0])
strcpy(gloss, me->map_g.name);
char cubemap[256]="";
char env[256]="";
if(me->map_e.name[0])
strcpy(env, me->map_e.name);
char spec[256]="";
if(me->map_s.name[0])
strcpy(spec, me->map_s.name);
char det[256]="";
if(me->map_detail.name[0])
strcpy(det, me->map_detail.name);
char subsurf[256]="";
if(me->map_subsurf.name[0])
strcpy(subsurf, me->map_subsurf.name);
char refl[256]="";
if(me->map_e.name[0])
strcpy(refl, me->map_e.name);
char * mat_name = me->name;
// fill MatInfo struct
// CMatInfo newMat & = MatInfo;
// strcpy(newMat.szDiffuse, diffuse);
if (me->Dyn_Bounce == 1.0f)
newMat.m_Flags |= MIF_PHYSIC;
if (me->Dyn_StaticFriction == 1.0f)
newMat.m_Flags |= MIF_NOCASTSHADOWS;
/* if (nLM > 0)
{
Res.m_Textures[EFTT_LIGHTMAP].m_TU.m_ITexPic = m_pSystem->GetIRenderer()->EF_GetTextureByID(nLM);
Res.m_Textures[EFTT_LIGHTMAP].m_Name = Res.m_Textures[EFTT_LIGHTMAP].m_TU.m_ITexPic->GetName();
}
if (nLM_LD > 0)
{
Res.m_Textures[EFTT_LIGHTMAP_DIR].m_TU.m_ITexPic = m_pSystem->GetIRenderer()->EF_GetTextureByID(nLM_LD);
Res.m_Textures[EFTT_LIGHTMAP_DIR].m_Name = Res.m_Textures[EFTT_LIGHTMAP].m_TU.m_ITexPic->GetName();
}*/
Res.m_TexturePath = szFolderName;
Res.m_Textures[EFTT_DIFFUSE].m_Name = diffuse;
Res.m_Textures[EFTT_GLOSS].m_Name = gloss;
Res.m_Textures[EFTT_SUBSURFACE].m_Name = subsurf;
Res.m_Textures[EFTT_BUMP].m_Name = bump;
Res.m_Textures[EFTT_NORMALMAP].m_Name = normalmap;
Res.m_Textures[EFTT_CUBEMAP].m_Name = cubemap[0] ? cubemap : env;
Res.m_Textures[EFTT_SPECULAR].m_Name = spec;
Res.m_Textures[EFTT_DETAIL_OVERLAY].m_Name = det;
Res.m_Textures[EFTT_OPACITY].m_Name = opacity;
Res.m_Textures[EFTT_DECAL_OVERLAY].m_Name = decal;
Res.m_Textures[EFTT_SUBSURFACE].m_Name = subsurf;
Res.m_Textures[EFTT_REFLECTION].m_Name = refl;
Res.m_Textures[EFTT_REFLECTION].m_TU.m_eTexType = (ETexType)SetTexType(&me->map_e);
Res.m_Textures[EFTT_SUBSURFACE].m_TU.m_eTexType = (ETexType)SetTexType(&me->map_subsurf);
Res.m_Textures[EFTT_BUMP].m_TU.m_eTexType = eTT_Bumpmap;
Res.m_ResFlags = me->flags;
Res.m_Opacity = me->opacity;
Res.m_AlphaRef = me->Dyn_SlidingFriction;
if (me->flags & MTLFLAG_CRYSHADER)
Res.m_AlphaRef = me->alpharef;
if (decal[0])
Res.m_Textures[EFTT_DECAL_OVERLAY].m_Amount = me->map_o.Amount;
Res.m_Textures[EFTT_DIFFUSE].m_Amount = me->map_d.Amount;
Res.m_Textures[EFTT_BUMP].m_Amount = me->map_b.Amount;
if (me->flags & MTLFLAG_CRYSHADER)
Res.m_Textures[EFTT_NORMALMAP].m_Amount = me->map_displ.Amount;
Res.m_Textures[EFTT_OPACITY].m_Amount = me->map_o.Amount;
Res.m_Textures[EFTT_REFLECTION].m_Amount = me->map_e.Amount;
Res.m_Textures[EFTT_SUBSURFACE].m_Amount = me->map_subsurf.Amount;
Res.m_Textures[EFTT_DIFFUSE].m_TexFlags = me->map_d.flags;
//Res.m_Textures[EFTT_SUBSURFACE].m_TexFlags = me->map_d.flags;
Res.m_Textures[EFTT_GLOSS].m_TexFlags = me->map_g.flags;
Res.m_Textures[EFTT_BUMP].m_TexFlags = me->map_b.flags;
Res.m_Textures[EFTT_CUBEMAP].m_TexFlags = me->map_e.flags;
Res.m_Textures[EFTT_SPECULAR].m_TexFlags = me->map_s.flags;
Res.m_Textures[EFTT_DETAIL_OVERLAY].m_TexFlags = me->map_detail.flags;
Res.m_Textures[EFTT_SUBSURFACE].m_TexFlags = me->map_subsurf.flags;
Res.m_Textures[EFTT_DIFFUSE].m_TexModificator.m_Tiling[0] = me->map_d.uscl_val;
Res.m_Textures[EFTT_DIFFUSE].m_TexModificator.m_Tiling[1] = me->map_d.vscl_val;
Res.m_Textures[EFTT_DIFFUSE].m_TexModificator.m_Offs[0] = me->map_d.uoff_val;
Res.m_Textures[EFTT_DIFFUSE].m_TexModificator.m_Offs[1] = me->map_d.voff_val;
Res.m_Textures[EFTT_DIFFUSE].m_TexModificator.m_Rot[0] = Degr2Word(me->map_d.urot_val);
Res.m_Textures[EFTT_DIFFUSE].m_TexModificator.m_Rot[1] = Degr2Word(me->map_d.vrot_val);
Res.m_Textures[EFTT_DIFFUSE].m_bUTile = me->map_d.utile;
Res.m_Textures[EFTT_DIFFUSE].m_bVTile = me->map_d.vtile;
Res.m_Textures[EFTT_BUMP].m_TexModificator.m_Tiling[0] = me->map_b.uscl_val;
Res.m_Textures[EFTT_BUMP].m_TexModificator.m_Tiling[1] = me->map_b.vscl_val;
Res.m_Textures[EFTT_BUMP].m_TexModificator.m_Offs[0] = me->map_b.uoff_val;
Res.m_Textures[EFTT_BUMP].m_TexModificator.m_Offs[1] = me->map_b.voff_val;
Res.m_Textures[EFTT_BUMP].m_TexModificator.m_Rot[0] = Degr2Word(me->map_b.urot_val);
Res.m_Textures[EFTT_BUMP].m_TexModificator.m_Rot[1] = Degr2Word(me->map_b.vrot_val);
Res.m_Textures[EFTT_BUMP].m_bUTile = me->map_b.utile;
Res.m_Textures[EFTT_BUMP].m_bVTile = me->map_b.vtile;
Res.m_Textures[EFTT_SPECULAR].m_TexModificator.m_Tiling[0] = me->map_s.uscl_val;
Res.m_Textures[EFTT_SPECULAR].m_TexModificator.m_Tiling[1] = me->map_s.vscl_val;
Res.m_Textures[EFTT_SPECULAR].m_TexModificator.m_Offs[0] = me->map_s.uoff_val;
Res.m_Textures[EFTT_SPECULAR].m_TexModificator.m_Offs[1] = me->map_s.voff_val;
Res.m_Textures[EFTT_SPECULAR].m_TexModificator.m_Rot[0] = Degr2Word(me->map_s.urot_val);
Res.m_Textures[EFTT_SPECULAR].m_TexModificator.m_Rot[1] = Degr2Word(me->map_s.vrot_val);
Res.m_Textures[EFTT_SPECULAR].m_bUTile = me->map_b.utile;
Res.m_Textures[EFTT_SPECULAR].m_bVTile = me->map_b.vtile;
Res.m_Textures[EFTT_GLOSS].m_TexModificator.m_Tiling[0] = me->map_g.uscl_val;
Res.m_Textures[EFTT_GLOSS].m_TexModificator.m_Tiling[1] = me->map_g.vscl_val;
Res.m_Textures[EFTT_GLOSS].m_TexModificator.m_Offs[0] = me->map_g.uoff_val;
Res.m_Textures[EFTT_GLOSS].m_TexModificator.m_Offs[1] = me->map_g.voff_val;
Res.m_Textures[EFTT_GLOSS].m_TexModificator.m_Rot[0] = Degr2Word(me->map_g.urot_val);
Res.m_Textures[EFTT_GLOSS].m_TexModificator.m_Rot[1] = Degr2Word(me->map_g.vrot_val);
Res.m_Textures[EFTT_GLOSS].m_bUTile = me->map_g.utile;
Res.m_Textures[EFTT_GLOSS].m_bVTile = me->map_g.vtile;
if (!Res.m_Textures[EFTT_DETAIL_OVERLAY].m_Name.empty())
{
Res.m_Textures[EFTT_DETAIL_OVERLAY].m_TexModificator.m_Tiling[0] = me->map_detail.uscl_val;
Res.m_Textures[EFTT_DETAIL_OVERLAY].m_TexModificator.m_Tiling[1] = me->map_detail.vscl_val;
Res.m_Textures[EFTT_DETAIL_OVERLAY].m_TexModificator.m_Offs[0] = me->map_detail.uoff_val;
Res.m_Textures[EFTT_DETAIL_OVERLAY].m_TexModificator.m_Offs[1] = me->map_detail.voff_val;
Res.m_Textures[EFTT_DETAIL_OVERLAY].m_TexModificator.m_Rot[0] = Degr2Word(me->map_detail.urot_val);
Res.m_Textures[EFTT_DETAIL_OVERLAY].m_TexModificator.m_Rot[1] = Degr2Word(me->map_detail.vrot_val);
Res.m_Textures[EFTT_DETAIL_OVERLAY].m_bUTile = me->map_detail.utile;
Res.m_Textures[EFTT_DETAIL_OVERLAY].m_bVTile = me->map_detail.vtile;
}
if (!Res.m_Textures[EFTT_OPACITY].m_Name.empty())
{
Res.m_Textures[EFTT_OPACITY].m_TexModificator.m_Tiling[0] = me->map_o.uscl_val;
Res.m_Textures[EFTT_OPACITY].m_TexModificator.m_Tiling[1] = me->map_o.vscl_val;
Res.m_Textures[EFTT_OPACITY].m_TexModificator.m_Rot[0] = Degr2Word(me->map_o.urot_val);
Res.m_Textures[EFTT_OPACITY].m_TexModificator.m_Rot[1] = Degr2Word(me->map_o.vrot_val);
Res.m_Textures[EFTT_OPACITY].m_TexModificator.m_Offs[0] = me->map_o.uoff_val;
Res.m_Textures[EFTT_OPACITY].m_TexModificator.m_Offs[1] = me->map_o.voff_val;
Res.m_Textures[EFTT_OPACITY].m_bUTile = me->map_o.utile;
Res.m_Textures[EFTT_OPACITY].m_bVTile = me->map_o.vtile;
}
if (!Res.m_Textures[EFTT_DECAL_OVERLAY].m_Name.empty())
{
Res.m_Textures[EFTT_DECAL_OVERLAY].m_TexModificator.m_Tiling[0] = me->map_o.uscl_val;
Res.m_Textures[EFTT_DECAL_OVERLAY].m_TexModificator.m_Tiling[1] = me->map_o.vscl_val;
Res.m_Textures[EFTT_DECAL_OVERLAY].m_TexModificator.m_Rot[0] = Degr2Word(me->map_o.urot_val);
Res.m_Textures[EFTT_DECAL_OVERLAY].m_TexModificator.m_Rot[1] = Degr2Word(me->map_o.vrot_val);
Res.m_Textures[EFTT_DECAL_OVERLAY].m_TexModificator.m_Offs[0] = me->map_o.uoff_val;
Res.m_Textures[EFTT_DECAL_OVERLAY].m_TexModificator.m_Offs[1] = me->map_o.voff_val;
Res.m_Textures[EFTT_DECAL_OVERLAY].m_bUTile = me->map_o.utile;
Res.m_Textures[EFTT_DECAL_OVERLAY].m_bVTile = me->map_o.vtile;
}
char mName[128];
strcpy(mName, mat_name);
char *str = strchr(mat_name, '/');
if (str)
{
mName[str-mat_name] = 0;
strncpy(newMat.sScriptMaterial, &str[1], sizeof(newMat.sScriptMaterial));
newMat.sScriptMaterial[sizeof(newMat.sScriptMaterial)-1]=0;
}
else
{
newMat.sScriptMaterial[0] = 0;
}
char *templName = NULL;;
if(strnicmp(mName, "$s_",3)==0)
{
templName = &mName[3];
}
else if(str=strchr(mName, '('))
{
mName[str-mName] = 0;
templName = &mName[str-mName+1];
if(str=strchr(templName, ')'))
templName[str-templName] = 0;
}
uchar nInvert = 0;
if (templName && templName[0] == '#')
{
templName++;
nInvert = 1;
}
// newMat.SetName(mName); // set material name
strncpy( newMat.sMaterialName, mName, sizeof(newMat.sMaterialName) );
newMat.sMaterialName[sizeof(newMat.sMaterialName)-1] = 0;
// load shader
if(mName[0]==0)
strcpy(mName,"nodraw");
if(!templName || !templName[0])
templName = "nodraw";
if(pRenderer) // in compiler there is no renderer
newMat.shaderItem = pRenderer->EF_LoadShaderItem(mName, eSH_World, true, templName, 0, &Res);
// newMat.shaderItem->m_pShader->AdjustResources(newMat.shaderItem->m_pShaderResources);
// IShader * ef = newMat.shaderItem.m_pShader->GetTemplate(-1);
// if(ef->GetPhysMaterialFlags() & MATF_NOCLIP)
// newMat.m_Flags &= ~MIF_PHYSIC;
// strcpy(newMat.szFolderName, szFolderName);
// remember polybump state
newMat.m_Flags &= ~MIF_POLYBUMP;
newMat.fAlpha = me->opacity;
if(!pRenderer)
{ // in compiler remember also source MAT_ENTITY
assert(newMat.pMatEnt != me);
newMat.pMatEnt = new MAT_ENTITY;
*newMat.pMatEnt = *me;
}
return true;
}
#endif // _MAKEMATINFOFROMMAT_ENTITY_H_

254
CryCommon/MeshIdx.h Normal file
View File

@@ -0,0 +1,254 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2002.
// -------------------------------------------------------------------------
// File name: meshidx.h
// Version: v1.00
// Created: 28/5/2001 by Vladimir Kajalin
// Compilers: Visual Studio.NET
// Description: prepare shaders for object
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#ifndef IDX_MESH_H
#define IDX_MESH_H
#include "list2.h"
#define CCGF_CACHE_DIR_NAME "CCGF_CACHE"
#define CCGF_FILE_VERSION "CCGF_0.6"
#define CCGFHF_PHYSICS_EXIST 1
struct CCGFHeader
{
CCGFHeader()
{
memset(this,0,sizeof(*this));
nStructuresCheckSummm = GetStructuresCheckSummm();
}
static int GetStructuresCheckSummm()
{
return sizeof(CDLight)+sizeof(list2<int>)+sizeof(CMatInfo)+//sizeof(MAT_ENTITY)+
sizeof(CVertexBuffer)+sizeof(SPipTangents)+m_VertexSize[0]+
sizeof(uint); // [Anton] - for m_arrVtxMap in CLeafBuffer
}
int nDataSize;
char szVersion[16];
int nStructuresCheckSummm;
FILETIME SourceFileTime;
Vec3d vBoxMin, vBoxMax;
int nFacesInCGFNum;
int dwFlags;
};
struct TexCoord
{
float s,t;
bool operator == (TexCoord & other)
{
if(s == other.s)
if(t == other.t)
return 1;
return 0;
}
};
struct UColor
{
uchar r,g,b,a;
};
#include "CryHeaders.h"
struct TextureMap2;
struct CryStaticModel;
struct StatHelperInfo
{
StatHelperInfo(char * new_name, int new_type, IShader *pShader, const Matrix44 & newMat)
{
// vPos = new_pos;
// qRot = new_rot;
strncpy(sName,new_name,64);
nType = new_type;
m_pShader = pShader;
// m_pObject = NULL;
tMat = newMat;
}
//Vec3d vPos; CryQuat qRot;
int nType;
char sName[64];
IShader *m_pShader;
// CCObject *m_pObject;
Matrix44 tMat;
};
#define OBJFACE_FLAG_REMOVE 1
class CIndexedMesh
{
public:
// geometry data
CObjFace * m_pFaces;
Vec3d * m_pVerts;
TexCoord * m_pCoors;
struct CBasis * m_pTangBasis;
int * m_pVertMats;
Vec3d * m_pNorms;
UColor* m_pColor;
UColor* m_pColorSec;
int m_nFaceCount;
int m_nVertCount;
int m_nCoorCount; // number of texture coordinates in m_pCoors array
int m_nNormCount;
// bbox
Vec3d m_vBoxMin, m_vBoxMax;
// materials table
list2<CMatInfo> m_lstMatTable;
// list of geom names from cgf file
list2<char*> m_lstGeomNames;
FILETIME m_fileTime;
// constructor
CIndexedMesh(){}
// [Sergiy] constructs the CINdexedMesh object out of the given data,
// [Sergiy] required by the CryAnimation module in order to create leaf buffers (generate render arrays)
// [Sergiy] This code should be here, it deals with internal structure of the CIndexedMesh.
// [Sergiy] Originally this was done externally in the GenerateRenderArrays method of CryModelState
// PARAMETERS:
// nFaces, pFaces, pTexFaces - number of faces and texture faces and their arrays
// nVertices, pVertices - number of vertices and the array of vertices, in object coordinate system
// nUVs, pUVs - number of UVs and the UVs themselves
CIndexedMesh (
unsigned nFaces, const CryFace* pFaces, const CryTexFace* pTexFaces,
unsigned nVertices, const Vec3d* pVertices, const Vec3d* pNormals,
unsigned nUVs, const CryUV* pUVs
):
m_pColor (NULL), m_pColorSec (NULL) // not initialized
{
m_pTangBasis=0;
m_nFaceCount = nFaces;
m_pFaces = (CObjFace *)malloc(sizeof(CObjFace)*nFaces);
unsigned i=0;
for (i=0; i<nFaces; i++)
{
const CryFace& face = pFaces[i];
m_pFaces[i].v[0] = face.v0;//flip
m_pFaces[i].v[1] = face.v1;
m_pFaces[i].v[2] = face.v2;
m_pFaces[i].n[0] = face.v0;//flip
m_pFaces[i].n[1] = face.v1;
m_pFaces[i].n[2] = face.v2;
m_pFaces[i].shader_id = face.MatID;
// m_pFaces[i].m_lInfo = NULL;
if (pTexFaces)
{
const CryTexFace& texface = pTexFaces[i];
m_pFaces[i].t[0] = texface.t0;//flip
m_pFaces[i].t[1] = texface.t1;
m_pFaces[i].t[2] = texface.t2;
}
/*// Exit if the vertex index is out of range
if(m_pFaces[i].v[0] >= nVertices
|| m_pFaces[i].v[1] >= nVertices
|| m_pFaces[i].v[2] >= nVertices)
GetConsole()->Exit("CIndexedMesh: indices out of range");
*/
}
m_pCoors = (TexCoord *)malloc(sizeof(TexCoord)*nUVs);
m_nCoorCount = nUVs;
for (i=0; i<nUVs; i++)
{
m_pCoors[i].s = pUVs[i].u;
m_pCoors[i].t = pUVs[i].v;
}
m_pNorms = (Vec3d *)malloc(sizeof(Vec3d)*nVertices);
m_nNormCount = nVertices;
m_pVerts = (Vec3d *)malloc(sizeof(Vec3d)*nVertices);
m_nVertCount = nVertices;
for (i=0; i<nVertices; i++)
{
m_pNorms[i].x = pNormals[i].x;
m_pNorms[i].y = pNormals[i].y;
m_pNorms[i].z = pNormals[i].z;
m_pVerts[i].x = pVertices[i].x;
m_pVerts[i].y = pVertices[i].y;
m_pVerts[i].z = pVertices[i].z;
}
}
CIndexedMesh(ISystem * pSystem,
const char*szFileName,const char*szGeomName,//Vec3d * pvAngles,
int*_count, bool bLoadAdditinalInfo, bool bKeepInLocalSpace, bool bIgnoreFakeMats = false);
~CIndexedMesh();
void FreeLMInfo();
bool LoadCGF(const char*szFileName, const char * szGeomName, bool bLoadAdditinalInfo, bool bKeepInLocalSpace, bool bIgnoreFakeMats);
static bool LoadMaterial(const char *szFileName, const char *szFolderName,
CMatInfo & MatInfo, IRenderer * pRenderer, MAT_ENTITY * me);
void SetMinMax();
int GetAllocatedBytes();
void * ReAllocElements(void * old_ptr, int old_elem_num, int new_elem_num, int size_of_element);
void MakeLightSources(CryStaticModel * pStaticCGF);
list2<StatHelperInfo> * GetHelpers() { return &m_lstHelpers; }
list2<CDLight*> * GetLightSourcesList() { return &m_lstLSources; }
size_t GetMemoryUsage();
bool CalcTangentSpace();
void DoBoxTexGen(float fScale, Vec3d * pvNormal = NULL);
void SmoothMesh(bool bSmoothVerts, bool bSmoothNorms, Vec3d * pvBoxMin = NULL, Vec3d * pvBoxMax = NULL, bool bMarkInvalidFaces = false);
void SimplifyMesh(float fMaxEdgeLen, Vec3d vBoundaryMin, Vec3d vBoundaryMax);
void FixMesh();
float GetEdgeError(struct TriEdge & tEdge, Vec3d * pVertsShared, struct VertInfo * pVertsInfo, list2<int> & lstIndices, UColor * pColorShared);
void RebuildMesh(Vec3d * pVertsShared, TexCoord * pCoordShared,Vec3d * pNormsShared, UColor * pColorShared, list2<int> & lstIndices, int nVertCountShared, int * pVertMatsShared);
bool RemoveEdge(Vec3d * pVertsShared, struct VertInfo * pVertsInfo, TexCoord * pCoordShared,Vec3d * pNormsShared, UColor * pColorShared, UColor * pColorSharedSec, list2<int> & lstIndices, int nVertCountShared,
list2<struct TriEdge> & lstTriEdges, int nEdgeForRemoveId, const Vec3d & vBoundaryMin, const Vec3d & vBoundaryMax);
void RemoveDuplicatedEdges(list2<struct TriEdge> & lstTriEdges);
bool TestEdges(int nBeginWith, list2<TriEdge> & lstTriEdges, list2<int> & lstIndices, TriEdge * pEdgeForDelete);
void MergeVertexFaceLists(int v0, int v1, struct VertInfo * pVertsInfo);
bool InitEdgeFaces(TriEdge & e, VertInfo * pVertsInfo, Vec3d * pVertsShared, TriEdge * pe0, const Vec3d & vBoundaryMin, const Vec3d & vBoundaryMax);
void MergeVertexComponents(TriEdge & e0, Vec3d * pVertsShared, struct VertInfo * pVertsInfo,
TexCoord * pCoordShared,Vec3d * pNormsShared, UColor * pColorShared, UColor * pColorSharedSec);
CIndexedMesh * MakeMaterialMesh(int nMatId, uchar ucAxis);
struct ISystem * m_pSystem;
Vec3d m_vOrigin;
protected:
list2<StatHelperInfo> m_lstHelpers;
list2<CDLight *> m_tgtLSources;
list2<CDLight *> m_lstLSources;
};
#endif // IDX_MESH_H

109
CryCommon/Names.h Normal file
View File

@@ -0,0 +1,109 @@
#ifndef __CNAME_H__
#define __CNAME_H__
#include <TArray.h>
#define MAX_SNAME_LEN 256
// Name index.
typedef INT NAME_INDEX;
#define checkName ASSERT
enum EFindName
{
eFN_Find = 0,
eFN_Add,
eFN_Intrinsic
};
extern long gHashTable[];
struct SNameEntry
{
int mNumName;
unsigned int mFlags;
SNameEntry* mNext;
char mName[MAX_SNAME_LEN];
size_t Size()
{
size_t nSize = sizeof(*this) - MAX_SNAME_LEN;
nSize += strlen(mName) + 1;
return nSize;
}
};
#define NF_Intrinsic 0x1
class CName
{
private:
int mNameIndex;
public:
// constructors
CName() {mNameIndex=0;}
CName(int nIndex) {mNameIndex=nIndex;}
CName(char const *, enum EFindName=eFN_Add);
~CName() {}
CName& operator=(const CName& cFN) { mNameIndex = cFN.mNameIndex; return *this; }
const char* operator*(void) const { return mNames[mNameIndex]->mName; }
int operator!=(const CName& cFN) const { return (cFN.mNameIndex != mNameIndex); }
int operator==(const CName& cFN) const { return (cFN.mNameIndex == mNameIndex); }
const char* c_str() const { return mNames[mNameIndex]->mName; }
unsigned long mfGetFlags(void) const { return mNames[mNameIndex]->mFlags; }
long mfGetHash(const char *str)
{
unsigned char ch;
unsigned int hash = 0;
int temp;
while ( ch=*str++ )
{
ch = toupper(ch);
temp = hash & 0xff;
hash >>= 8;
hash ^= gHashTable[ch ^ temp];
}
return (hash & 0x1fff);
}
NAME_INDEX GetIndex() const
{
return mNameIndex;
}
void mfClear() { mNameIndex=0; }
void mfClearFlags(unsigned int flag) { mNames[mNameIndex]->mFlags &= ~flag; }
void mfSetFlags(unsigned int flag) { mNames[mNameIndex]->mFlags |= flag; }
int mfGetIndex(void) const { return mNameIndex; }
int mfIsValid(void)
{
if ( mNameIndex<0 || mNameIndex>=mNames.Num() || !mNames[mNameIndex] )
return 0;
return 1;
}
void mfInitTables(void);
static void mfDisplayHash(void);
static void mfExitSubsystem(void);
static void mfInitSubsystem(void);
static SNameEntry* mfGetEntry(int i) { return mNames[i]; }
void mfRegister(SNameEntry&);
static int mfGetMaxNames(void) { return mNames.Num(); }
static int Size();
void mfDeleteEntry(int);
static TArray<SNameEntry *> mNames;
static TArray<int> mAvailable;
static SNameEntry* mNameHash[8192];
static int mDuplicate;
};
//===========================================================
#endif // __CNAME_H__

View File

@@ -0,0 +1,43 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2002.
// -------------------------------------------------------------------------
// File name: ProjectDefines.h
// Version: v1.00
// Created: 3/30/2004 by MartinM.
// Compilers: Visual Studio.NET
// Description: to get some defines available in every CryEngine project
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#ifndef PROJECTDEFINES_H
#define PROJECTDEFINES_H
#define GAME_IS_FARCRY
#if defined(LINUX)
#if defined(LINUX64)
#define NOT_USE_PUNKBUSTER_SDK
#endif
#define _DATAPROBE
#define NOT_USE_BINK_SDK // mainly needed for licencees to compile without the Bink integration
#define NOT_USE_DIVX_SDK // mainly needed for licencees to compile without the DivX integration
#define EXCLUDE_UBICOM_CLIENT_SDK // to compile a standalone server without the client integration
#else
#define _DATAPROBE
// #define NOT_USE_UBICOM_SDK // mainly needed for licencees to compile without the UBI.com integration
// #define NOT_USE_PUNKBUSTER_SDK // mainly needed for licencees to compile without the Punkbuster integration
// #define NOT_USE_BINK_SDK // mainly needed for licencees to compile without the Bink integration
// #define NOT_USE_DIVX_SDK // mainly needed for licencees to compile without the DivX integration
// #define NOT_USE_ASE_SDK // mainly needed for licencees to compile without the ASE integration
// #define EXCLUDE_UBICOM_CLIENT_SDK // to compile a standalone server without the client integration
#endif //LINUX
#endif // PROJECTDEFINES_H

104
CryCommon/Range.h Normal file
View File

@@ -0,0 +1,104 @@
////////////////////////////////////////////////////////////////////////////
//
// Crytek Engine Source File.
// Copyright (C), Crytek Studios, 2002.
// -------------------------------------------------------------------------
// File name: range.h
// Version: v1.00
// Created: 25/4/2002 by Timur.
// Compilers: Visual Studio.NET
// Description: Time TRange class.
// -------------------------------------------------------------------------
// History:
//
////////////////////////////////////////////////////////////////////////////
#ifndef __range_h__
#define __range_h__
#if _MSC_VER > 1000
#pragma once
#endif
#ifndef MIN
#define MIN(a,b) ((a)<(b)?(a):(b))
#endif
#ifndef MAX
#define MAX(a,b) ((a)>(b)?(a):(b))
#endif
/*!
Class TRange, can represent anything that is range between two values, mostly used for time ranges.
*/
template <class T>
class TRange
{
public:
T start;
T end;
TRange() { start = 0; end = 0; };
TRange( const TRange &r ) { start = r.start; end = r.end; };
TRange( T s,T e ) { start = s; end = e; };
void Set( T s,T e ) { start = s; end = e; };
void Clear() { start = 0; end = 0; };
//! Get length of range.
T Length() const { return end - start; };
//! Check if range is empty.
bool IsEmpty() const { return (start == 0 && end == 0); }
//! Check if value is inside range.
bool IsInside( T val ) { return val >= start && val <= end; };
void ClipValue( T &val )
{
if (val < start) val = start;
if (val > end) val = end;
}
//! Compare two ranges.
bool operator == ( const TRange &r ) const {
return start == r.start && end == r.end;
}
//! Assign operator.
TRange& operator =( const TRange &r ) {
start = r.start;
end = r.end;
return *this;
}
//! Interect two ranges.
TRange operator & ( const TRange &r ) {
return TRange( MAX(start,r.start),MIN(end,r.end) );
}
TRange& operator &= ( const TRange &r ) {
return (*this = (*this & r));
}
//! Concatent two ranges.
TRange operator | ( const TRange &r ) {
return TRange( MIN(start,r.start),MAX(end,r.end) );
}
TRange& operator |= ( const TRange &r ) {
return (*this = (*this | r));
}
//! Add new value to range.
TRange operator + ( T v ) {
T s = start, e = end;
if (v < start) s = v;
if (v > end) e = v;
return TRange( s,e );
}
//! Add new value to range.
TRange& operator += ( T v ) {
if (v < start) start = v;
if (v > end) end = v;
return *this;
}
};
//! CRange if just TRange for floats..
typedef TRange<float> Range;
#endif // __range_h__

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