1
0
forked from 0ad/0ad

Delete lots of obsolete unused script-interface code.

Delete unused code from various other places.

This was SVN commit r7839.
This commit is contained in:
Ykkrosh 2010-08-01 20:56:34 +00:00
parent 41ad5bd965
commit 8286218cad
33 changed files with 24 additions and 3098 deletions

View File

@ -161,21 +161,6 @@ void CCamera::GetCameraPlanePoints(float dist,CVector3D pts[4]) const
pts[3].Z=dist;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// GetFrustumPoints: calculate and return the position of the 8 points of the frustum in world space
void CCamera::GetFrustumPoints(CVector3D pts[8]) const
{
// get camera space points for near and far planes
CVector3D cpts[8];
GetCameraPlanePoints(m_NearPlane,pts);
GetCameraPlanePoints(m_FarPlane,pts+4);
// transform to world space
for (int i=0;i<8;i++) {
m_Orientation.Transform(cpts[i],pts[i]);
}
}
void CCamera::BuildCameraRay( int px, int py, CVector3D& origin, CVector3D& dir )
{
CVector3D cPts[4];
@ -401,5 +386,3 @@ void CCamera::Render(int intermediates) const
glEnd();
}
}

View File

@ -26,8 +26,6 @@
#include "Frustum.h"
#include "maths/Matrix3D.h"
extern int g_mouse_x, g_mouse_y;
// view port
struct SViewPort
{
@ -45,7 +43,6 @@ class CCamera
~CCamera ();
// Methods for projection
void SetProjection (CMatrix3D *proj) { m_ProjMat = *proj; }
void SetProjection (float nearp, float farp, float fov);
void SetProjectionTile (int tiles, int tile_x, int tile_y);
CMatrix3D& GetProjection () { return m_ProjMat; }
@ -65,9 +62,6 @@ class CCamera
float GetFarPlane() const { return m_FarPlane; }
float GetFOV() const { return m_FOV; }
// calculate and return the position of the 8 points of the frustum in world space
void GetFrustumPoints(CVector3D pts[8]) const;
// return four points in camera space at given distance from camera
void GetCameraPlanePoints(float dist,CVector3D pts[4]) const;
@ -76,11 +70,6 @@ class CCamera
// BuildCameraRay: calculate origin and ray direction of a ray through
// the pixel (px,py) on the screen
void BuildCameraRay(int px, int py, CVector3D& origin, CVector3D& dir);
// BuildCameraRay: as previous, using global mouse position
void BuildCameraRay(CVector3D& origin, CVector3D& dir)
{
BuildCameraRay(g_mouse_x, g_mouse_y, origin, dir);
}
// General helpers that seem to fit here
@ -90,8 +79,6 @@ class CCamera
// Get the point on the terrain corresponding to pixel (px,py) (or the mouse coordinates)
// The aboveWater parameter determines whether we want to stop at the water plane or also get underwater points
CVector3D GetWorldCoordinates(int px, int py, bool aboveWater=false);
CVector3D GetWorldCoordinates(bool aboveWater=false)
{ return GetWorldCoordinates(g_mouse_x, g_mouse_y, aboveWater); }
// Get the point on the plane at height h corresponding to pixel (px,py)
CVector3D GetWorldCoordinates(int px, int py, float h);
// Get the point on the terrain the camera is pointing towards

View File

@ -479,7 +479,7 @@ void CGameView::ResetCameraOrientation()
void CGameView::RotateAboutTarget()
{
m->CameraPivot = m->ViewCamera.GetWorldCoordinates(true);
m->CameraPivot = m->ViewCamera.GetWorldCoordinates(g_mouse_x, g_mouse_y, true);
}
void CGameView::Update(float DeltaTime)

View File

@ -21,19 +21,13 @@
#include "graphics/Camera.h"
#include "graphics/CinemaTrack.h"
#include "graphics/GameView.h"
#include "graphics/Model.h"
#include "graphics/ObjectManager.h"
#include "graphics/Patch.h"
#include "graphics/Terrain.h"
#include "graphics/TextureEntry.h"
#include "graphics/TextureManager.h"
#include "graphics/Unit.h"
#include "graphics/UnitManager.h"
#include "lib/timer.h"
#include "maths/MathUtil.h"
#include "ps/CLogger.h"
#include "ps/Game.h"
#include "ps/Loader.h"
#include "ps/LoaderThunks.h"
#include "ps/XML/Xeromyces.h"
@ -781,7 +775,7 @@ void CXMLReader::ReadCinema(XMBElement parent)
m_MapReader.pCinema->SetAllPaths(pathList);
}
void CXMLReader::ReadTriggers(XMBElement parent)
void CXMLReader::ReadTriggers(XMBElement UNUSED(parent))
{
// MapTriggerGroup rootGroup( L"Triggers", L"" );
// if (m_MapReader.pTrigMan)

View File

@ -22,20 +22,13 @@
#include "LightEnv.h"
#include "MapReader.h"
#include "MapWriter.h"
#include "Model.h"
#include "ObjectBase.h"
#include "ObjectEntry.h"
#include "ObjectManager.h"
#include "Patch.h"
#include "Terrain.h"
#include "TextureEntry.h"
#include "TextureManager.h"
#include "Unit.h"
#include "UnitManager.h"
#include "maths/MathUtil.h"
#include "maths/NUSpline.h"
#include "ps/Game.h"
#include "ps/Loader.h"
#include "ps/Filesystem.h"
#include "ps/XML/XMLWriter.h"
@ -56,7 +49,7 @@ CMapWriter::CMapWriter()
///////////////////////////////////////////////////////////////////////////////////////////////////
// SaveMap: try to save the current map to the given file
void CMapWriter::SaveMap(const VfsPath& pathname, CTerrain* pTerrain,
CUnitManager* pUnitMan, WaterManager* pWaterMan, SkyManager* pSkyMan,
WaterManager* pWaterMan, SkyManager* pSkyMan,
CLightEnv* pLightEnv, CCamera* pCamera, CCinemaManager* pCinema,
CSimulation2* pSimulation2)
{
@ -69,7 +62,7 @@ void CMapWriter::SaveMap(const VfsPath& pathname, CTerrain* pTerrain,
packer.Write(pathname);
VfsPath pathnameXML = fs::change_extension(pathname, L".xml");
WriteXML(pathnameXML, pUnitMan, pWaterMan, pSkyMan, pLightEnv, pCamera, pCinema, pSimulation2);
WriteXML(pathnameXML, pWaterMan, pSkyMan, pLightEnv, pCamera, pCinema, pSimulation2);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
@ -175,7 +168,7 @@ void CMapWriter::PackTerrain(CFilePacker& packer, CTerrain* pTerrain)
packer.PackRaw(&tiles[0],sizeof(STileDesc)*tiles.size());
}
void CMapWriter::WriteXML(const VfsPath& filename,
CUnitManager* pUnitMan, WaterManager* pWaterMan, SkyManager* pSkyMan,
WaterManager* pWaterMan, SkyManager* pSkyMan,
CLightEnv* pLightEnv, CCamera* pCamera, CCinemaManager* pCinema,
CSimulation2* pSimulation2)
{
@ -285,7 +278,7 @@ void CMapWriter::WriteXML(const VfsPath& filename,
{
XML_Element("Entities");
CSimulation2& sim = *g_Game->GetSimulation2();
CSimulation2& sim = *pSimulation2;
CmpPtr<ICmpTemplateManager> cmpTemplateManager(sim, SYSTEM_ENTITY);
debug_assert(!cmpTemplateManager.null());
@ -495,10 +488,10 @@ void CMapWriter::WriteTrigger(XMLWriter_File& xml_file_, const MapTrigger& trigg
///////////////////////////////////////////////////////////////////////////////////////////////////
// RewriteAllMaps
void CMapWriter::RewriteAllMaps(CTerrain* pTerrain, CUnitManager* pUnitMan,
void CMapWriter::RewriteAllMaps(CTerrain* pTerrain,
WaterManager* pWaterMan, SkyManager* pSkyMan,
CLightEnv* pLightEnv, CCamera* pCamera, CCinemaManager* pCinema,
CTriggerManager* pTrigMan, CSimulation2* pSimulation2, CEntityManager* pEntityMan)
CTriggerManager* pTrigMan, CSimulation2* pSimulation2)
{
VfsPaths pathnames;
(void)fs_util::GetPathnames(g_VFS, L"maps/scenarios", L"*.pmp", pathnames);
@ -513,6 +506,6 @@ void CMapWriter::RewriteAllMaps(CTerrain* pTerrain, CUnitManager* pUnitMan,
CStrW newPathname(pathnames[i].string());
newPathname.Replace(L"scenarios/", L"scenarios/new/");
CMapWriter writer;
writer.SaveMap(newPathname, pTerrain, pUnitMan, pWaterMan, pSkyMan, pLightEnv, pCamera, pCinema, pSimulation2);
writer.SaveMap(newPathname, pTerrain, pWaterMan, pSkyMan, pLightEnv, pCamera, pCinema, pSimulation2);
}
}

View File

@ -1,4 +1,4 @@
/* Copyright (C) 2009 Wildfire Games.
/* Copyright (C) 2010 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
@ -27,14 +27,12 @@
class CLightEnv;
class CTerrain;
class CUnitManager;
class CCamera;
class CCinemaManager;
class CTriggerManager;
class WaterManager;
class SkyManager;
class CSimulation2;
class CEntityManager;
struct MapTrigger;
struct MapTriggerGroup;
class XMLWriter_File;
@ -45,17 +43,17 @@ public:
// constructor
CMapWriter();
// SaveMap: try to save the current map to the given file
void SaveMap(const VfsPath& pathname, CTerrain* pTerr, CUnitManager* pUnitMan,
void SaveMap(const VfsPath& pathname, CTerrain* pTerr,
WaterManager* pWaterMan, SkyManager* pSkyMan,
CLightEnv* pLightEnv, CCamera* pCamera,
CCinemaManager* pCinema, CSimulation2* pSimulation2);
// RewriteAllMaps: for use during development: load/save all maps, to
// update them to the newest format.
static void RewriteAllMaps(CTerrain* pTerrain, CUnitManager* pUnitMan, WaterManager* pWaterMan,
static void RewriteAllMaps(CTerrain* pTerrain, WaterManager* pWaterMan,
SkyManager* pSkyMan, CLightEnv* pLightEnv, CCamera* pCamera,
CCinemaManager* pCinema, CTriggerManager* pTrigMan,
CSimulation2* pSimulation2, CEntityManager* pEntityMan);
CSimulation2* pSimulation2);
private:
// PackMap: pack the current world into a raw data stream
@ -69,7 +67,7 @@ private:
std::vector<STileDesc>& tileIndices);
// WriteXML: output some other data (entities, etc) in XML format
void WriteXML(const VfsPath& pathname, CUnitManager* pUnitMan, WaterManager* pWaterMan,
void WriteXML(const VfsPath& pathname, WaterManager* pWaterMan,
SkyManager* pSkyMan, CLightEnv* pLightEnv, CCamera* pCamera,
CCinemaManager* pCinema, CSimulation2* pSimulation2);
// void WriteTriggerGroup(XMLWriter_File& xml_file_, const MapTriggerGroup& group,

View File

@ -25,8 +25,6 @@
#include "ps/CStr.h"
#include "lib/file/vfs/vfs_path.h"
class CEntityTemplate;
class CMatrix3D;
class CMeshManager;
class CObjectBase;
class CObjectEntry;

View File

@ -22,7 +22,6 @@
#ifndef INCLUDED_TERRAIN
#define INCLUDED_TERRAIN
#include "ps/Vector2D.h"
#include "maths/Vector3D.h"
#include "maths/Fixed.h"
#include "graphics/SColor.h"

View File

@ -1,4 +1,4 @@
/* Copyright (C) 2009 Wildfire Games.
/* Copyright (C) 2010 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
@ -26,8 +26,6 @@
#include "graphics/Terrain.h"
#include "graphics/TextureEntry.h"
#include "graphics/TextureManager.h"
#include "graphics/Unit.h"
#include "graphics/UnitManager.h"
#include "lib/ogl.h"
#include "lib/external_libraries/sdl.h"
#include "lib/bits.h"
@ -44,13 +42,6 @@
bool g_TerrainModified = false;
bool g_GameRestarted = false;
// used by GetMapSpaceCoords (precalculated as an optimization).
// this was formerly access via inline asm, which required it to be
// static data instead of a class member. that is no longer the case,
// but we leave it because this is slightly more efficient.
static float m_scaleX, m_scaleY;
static unsigned int ScaleColor(unsigned int color, float x)
{
unsigned int r = unsigned(float(color & 0xff) * x);
@ -61,7 +52,7 @@ static unsigned int ScaleColor(unsigned int color, float x)
CMiniMap::CMiniMap()
: m_TerrainTexture(0), m_TerrainData(0), m_MapSize(0), m_Terrain(0),
m_LOSTexture(0), m_LOSData(0), m_UnitManager(0)
m_LOSTexture(0), m_LOSData(0)
{
AddSetting(GUIST_CColor, "fov_wedge_color");
AddSetting(GUIST_CStr, "tooltip");
@ -256,15 +247,11 @@ void CMiniMap::Draw()
// Set our globals in case they hadn't been set before
m_Camera = g_Game->GetView()->GetCamera();
m_Terrain = g_Game->GetWorld()->GetTerrain();
m_UnitManager = &g_Game->GetWorld()->GetUnitManager();
m_Width = (u32)(m_CachedActualSize.right - m_CachedActualSize.left);
m_Height = (u32)(m_CachedActualSize.bottom - m_CachedActualSize.top);
m_MapSize = m_Terrain->GetVerticesPerSide();
m_TextureSize = (GLsizei)round_up_to_pow2((size_t)m_MapSize);
m_scaleX = float(m_Width) / float(m_MapSize - 1);
m_scaleY = float(m_Height) / float(m_MapSize - 1);
if(!m_TerrainTexture || g_GameRestarted)
CreateTextures();
@ -394,8 +381,8 @@ void CMiniMap::Draw()
// (~70msec/frame on a GF4 rendering a thousand points)
glPointSize(3.f);
float sx = m_scaleX / CELL_SIZE;
float sy = m_scaleY / CELL_SIZE;
float sx = (float)m_Width / ((m_MapSize - 1) * CELL_SIZE);
float sy = (float)m_Height / ((m_MapSize - 1) * CELL_SIZE);
CSimulation2* sim = g_Game->GetSimulation2();
const CSimulation2::InterfaceList& ents = sim->GetEntitiesWithInterface(IID_Minimap);
@ -569,13 +556,3 @@ void CMiniMap::Destroy()
delete[] m_TerrainData; m_TerrainData = 0;
delete[] m_LOSData; m_LOSData = 0;
}
CVector2D CMiniMap::GetMapSpaceCoords(CVector3D worldPos)
{
float x = rintf(worldPos.X / CELL_SIZE);
float y = rintf(worldPos.Z / CELL_SIZE);
// Entity's Z coordinate is really its longitudinal coordinate on the terrain
// Calculate map space scale
return CVector2D(x * m_scaleX, y * m_scaleY);
}

View File

@ -1,4 +1,4 @@
/* Copyright (C) 2009 Wildfire Games.
/* Copyright (C) 2010 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
@ -20,11 +20,8 @@
#include "gui/GUI.h"
class CVector2D;
class CVector3D;
class CCamera;
class CTerrain;
class CUnitManager;
extern bool g_TerrainModified;
@ -55,16 +52,9 @@ protected:
void FireWorldClickEvent(int button, int clicks);
// calculate the relative heightmap space coordinates
// for a units world position
CVector2D GetMapSpaceCoords(CVector3D worldPos);
// the terrain we are mini-mapping
const CTerrain* m_Terrain;
// the unit manager with unit positions
const CUnitManager* m_UnitManager;
// not const: camera is moved by clicking on minimap
CCamera* m_Camera;

View File

@ -37,7 +37,6 @@
#include "ps/Hotkey.h"
#include "ps/Pyrogenesis.h"
#include "scripting/ScriptingHost.h"
#include "scripting/ScriptableComplex.inl"
#define LOG_CATEGORY L"Console"

View File

@ -230,76 +230,6 @@ void CGame::Interpolate(float frameLength)
m_TurnManager->Interpolate(frameLength);
}
/**
* Test player statistics and update game status as required.
*
**/
/*
void CGame::UpdateGameStatus()
{
bool EOG_lose = true;
bool EOG_win = true;
CPlayer *local = GetLocalPlayer();
for (int i=0; i<MAX_HANDLES; i++)
{
CHandle *handle = m_World->GetEntityManager().GetHandle(i);
if ( !handle )
continue;
CPlayer *tmpPlayer = handle->m_entity->GetPlayer();
//Are we still alive?
if ( local == tmpPlayer && handle->m_entity->m_extant )
{
EOG_lose = false;
if (EOG_win == false)
break;
}
//Are they still alive?
else if ( handle->m_entity->m_extant )
{
EOG_win = false;
if (EOG_lose == false)
break;
}
}
if (EOG_lose && EOG_win)
GameStatus = EOG_SPECIAL_DRAW;
else if (EOG_win)
GameStatus = EOG_WIN;
else if (EOG_lose)
GameStatus = EOG_LOSE;
else
GameStatus = EOG_NEUTRAL;
}*/
/**
* End of game console message creation.
*
**/
void CGame::EndGame()
{
g_Console->InsertMessage( L"It's the end of the game as we know it!");
switch (GameStatus)
{
case EOG_DRAW:
g_Console->InsertMessage( L"A diplomatic draw ain't so bad, eh?");
break;
case EOG_SPECIAL_DRAW:
g_Console->InsertMessage( L"Amazingly, you managed to draw from dieing at the same time as your opponent...you have my respect.");
break;
case EOG_LOSE:
g_Console->InsertMessage( L"My condolences on your loss.");
break;
case EOG_WIN:
g_Console->InsertMessage( L"Thou art victorious!");
break;
default:
break;
}
}
static CColor BrokenColor(0.3f, 0.3f, 0.3f, 1.0f);
CColor CGame::GetPlayerColour(int player) const
{

View File

@ -66,18 +66,6 @@ class CGame
int m_PlayerID;
/**
* enumerated values for game status.
**/
enum EOG
{
EOG_NEUTRAL, /// Game is in progress
EOG_DRAW, /// Game is over as a Draw by means of agreement of civilizations
EOG_SPECIAL_DRAW, /// Game is over by players dying at the same time...?
EOG_LOSE, /// Game is over, local player loses
EOG_WIN /// Game is over, local player wins
} GameStatus;
CNetTurnManager* m_TurnManager;
public:
@ -105,9 +93,6 @@ public:
void Interpolate(float frameLength);
void UpdateGameStatus();
void EndGame();
int GetPlayerID();
void SetPlayerID(int playerID);
@ -130,6 +115,7 @@ public:
**/
inline CWorld *GetWorld()
{ return m_World; }
/**
* Get the pointer to the game view object.
*
@ -137,6 +123,7 @@ public:
**/
inline CGameView *GetView()
{ return m_GameView; }
/**
* Get the pointer to the simulation2 object.
*
@ -155,13 +142,6 @@ public:
**/
inline void SetSimRate(float simRate)
{ m_SimRate = std::max(simRate, 0.0f); }
/**
* Get the simulation scale multiplier.
*
* @return float value of m_SimRate.
**/
inline float GetSimRate() const
{ return m_SimRate; }
/**
* Replace the current turn manager.

View File

@ -65,11 +65,8 @@
#include "simulation2/Simulation2.h"
#include "scripting/ScriptableComplex.inl"
#include "scripting/ScriptingHost.h"
#include "scripting/ScriptGlue.h"
#include "scripting/DOMEvent.h"
#include "scripting/ScriptableComplex.h"
#include "scriptinterface/ScriptInterface.h"
@ -314,9 +311,6 @@ static void RegisterJavascriptInterfaces()
// sound
JSI_Sound::ScriptingInit();
// scripting
CScriptEvent::ScriptingInit();
// ps
JSI_Console::init();

View File

@ -1,131 +0,0 @@
/* Copyright (C) 2009 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
*/
// Vector2D.h
//
// 2-dimensional vector class, primarily for use by simulation code.
#ifndef INCLUDED_VECTOR2D
#define INCLUDED_VECTOR2D
#include <math.h>
#include "maths/Vector3D.h"
class CVector2D
{
public:
float x;
float y;
inline CVector2D() { x = 0.0f; y = 0.0f; }
inline CVector2D( float _x, float _y )
{
x = _x; y = _y;
}
inline CVector2D( const CVector3D& v3 ) // This is done an awful lot.
{
x = v3.X; y = v3.Z;
}
inline operator CVector3D() const
{
return( CVector3D( x, 0, y ) );
}
inline bool operator==( const CVector2D& rhs ) const
{
return( x == rhs.x && y == rhs.y );
}
static inline float Dot( const CVector2D& u, const CVector2D& v )
{
return( u.x * v.x + u.y * v.y );
}
static inline float betadot( const CVector2D& u, const CVector2D& v )
{
// Beta-dot product. I have no idea if that's its correct name
// but use of it tends to simplify collision formulae.
// At the moment I think all of my code uses separate vectors
// and dots them together, though.
return( u.x * v.y - u.y * v.x );
}
inline CVector2D beta() const
{
return( CVector2D( y, -x ) );
}
inline float Dot( const CVector2D& u ) const
{
return( Dot( *this, u ) );
}
inline float betadot( const CVector2D& u ) const
{
return( betadot( *this, u ) );
}
inline CVector2D operator+( const CVector2D& u ) const
{
return( CVector2D( x + u.x, y + u.y ) );
}
inline CVector2D operator-( const CVector2D& u ) const
{
return( CVector2D( x - u.x, y - u.y ) );
}
inline CVector2D& operator+=( const CVector2D& u )
{
x += u.x; y += u.y;
return( *this );
}
inline CVector2D& operator-=( const CVector2D& u )
{
x -= u.x; y -= u.y;
return( *this );
}
inline CVector2D operator*( const float scale ) const
{
return( CVector2D( x * scale, y * scale ) );
}
inline CVector2D operator/( const float scale ) const
{
return( CVector2D( x / scale, y / scale ) );
}
inline CVector2D& operator*=( const float scale )
{
x *= scale; y *= scale;
return( *this );
}
inline CVector2D& operator/=( const float scale )
{
x /= scale; y /= scale;
return( *this );
}
inline float Length() const
{
return( sqrt( x * x + y * y ) );
}
inline float length2() const
{
return( x * x + y * y );
}
CVector2D Normalize() const
{
float l = Length();
if( l < 0.00001 ) return( CVector2D( 1.0f, 0.0f ) );
l = 1 / l;
return( CVector2D( x * l, y * l ) );
}
inline bool within( const float dist ) const
{
return( ( x * x + y * y ) <= ( dist * dist ) );
}
};
#endif

View File

@ -115,9 +115,9 @@ CWorld::~CWorld()
**/
void CWorld::RewriteMap()
{
CMapWriter::RewriteAllMaps(m_Terrain, m_UnitManager,
CMapWriter::RewriteAllMaps(m_Terrain,
g_Renderer.GetWaterManager(), g_Renderer.GetSkyManager(),
&g_LightEnv, m_pGame->GetView()->GetCamera(),
m_pGame->GetView()->GetCinema(), NULL,
m_pGame->GetSimulation2(), NULL);
m_pGame->GetSimulation2());
}

View File

@ -35,8 +35,6 @@ ERROR_TYPE(Game_World, MapLoadFailed);
class CGame;
class CUnitManager;
class CEntityManager;
class CProjectileManager;
class CLOSManager;
class CTerritoryManager;
class CTerrain;

View File

@ -1,211 +0,0 @@
/* Copyright (C) 2009 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
*/
#include "precompiled.h"
#include "DOMEvent.h"
#include "lib/timer.h"
#include "ps/Profile.h"
#include "ScriptObject.h"
IEventTarget::~IEventTarget()
{
HandlerMap::iterator it;
for( it = m_Handlers_name.begin(); it != m_Handlers_name.end(); it++ )
delete( it->second );
}
bool IEventTarget::_DispatchEvent( CScriptEvent* evt, IEventTarget* target )
{
PROFILE_START( "_DispatchEvent" );
// TODO: Deal correctly with multiple handlers
if( before && before->_DispatchEvent( evt, target ) )
{
return( true ); // Stop propagation.
}
evt->m_CurrentTarget = this;
HandlerList::const_iterator it;
const HandlerList &handlers=m_Handlers_id[evt->m_TypeCode];
for( it = handlers.begin(); it != handlers.end(); it++ )
{
DOMEventHandler id = *it;
if( id && id->DispatchEvent( GetScriptExecContext( target ), evt ) )
{
return( true );
}
}
HandlerRange range = m_Handlers_name.equal_range( evt->m_Type );
HandlerMap::iterator itm;
for( itm = range.first; itm != range.second; itm++ )
{
DOMEventHandler id = itm->second;
if( id && id->DispatchEvent( GetScriptExecContext( target ), evt ) )
{
return( true );
}
}
if( after && after->_DispatchEvent( evt, target ) )
{
return( true ); // Stop propagation.
}
return( false );
PROFILE_END( "_DispatchEvent" );
}
// Dispatch an event to its handler.
// returns: whether the event arrived (i.e. wasn't cancelled) [bool]
bool IEventTarget::DispatchEvent( CScriptEvent* evt )
{
const char* data;
PROFILE_START( "intern string" );
data = g_Profiler.InternString( "script: " + (CStr8)evt->m_Type );
PROFILE_END( "intern string" );
g_Profiler.StartScript( data );
evt->m_Target = this;
_DispatchEvent( evt, this );
g_Profiler.Stop();
return( !evt->m_Cancelled );
}
bool IEventTarget::AddHandler( size_t TypeCode, DOMEventHandler handler )
{
HandlerList::iterator it;
for( it = m_Handlers_id[TypeCode].begin(); it != m_Handlers_id[TypeCode].end(); it++ )
if( **it == *handler ) return( false );
m_Handlers_id[TypeCode].push_back( handler );
return( true );
}
bool IEventTarget::AddHandler( const CStrW& TypeString, DOMEventHandler handler )
{
HandlerMap::iterator it;
HandlerRange range = m_Handlers_name.equal_range( TypeString );
for( it = range.first; it != range.second; it++ )
if( *( it->second ) == *handler ) return( false );
m_Handlers_name.insert( HandlerMap::value_type( TypeString, handler ) );
return( true );
}
bool IEventTarget::RemoveHandler( size_t TypeCode, DOMEventHandler handler )
{
HandlerList::iterator it;
for( it = m_Handlers_id[TypeCode].begin(); it != m_Handlers_id[TypeCode].end(); it++ )
if( **it == *handler )
{
m_Handlers_id[TypeCode].erase( it );
return( true );
}
return( false );
}
bool IEventTarget::RemoveHandler( const CStrW& TypeString, DOMEventHandler handler )
{
HandlerMap::iterator it;
HandlerRange range = m_Handlers_name.equal_range( TypeString );
for( it = range.first; it != range.second; it++ )
if( *( it->second ) == *handler )
{
delete( it->second );
m_Handlers_name.erase( it );
return( true );
}
return( false );
}
bool IEventTarget::AddHandlerJS( JSContext* UNUSED(cx), uintN argc, jsval* argv )
{
debug_assert( argc >= 2 );
DOMEventHandler handler = new CScriptObject( argv[1] );
if( !handler->Defined() )
{
delete( handler );
return( false );
}
if( !AddHandler( ToPrimitive<CStrW>( argv[0] ), handler ) )
{
delete( handler );
return( false );
}
return( true );
}
bool IEventTarget::RemoveHandlerJS( JSContext* UNUSED(cx), uintN argc, jsval* argv )
{
debug_assert( argc >= 2 );
DOMEventHandler handler = new CScriptObject( argv[1] );
if( !handler->Defined() )
{
delete( handler );
return( false );
}
if( !RemoveHandler( ToPrimitive<CStrW>( argv[0] ), handler ) )
{
delete( handler );
return( false );
}
delete( handler );
return( true );
}
CScriptEvent::CScriptEvent( const CStrW& Type, size_t TypeCode, bool Cancelable, bool Blockable )
{
m_Type = Type; m_TypeCode = TypeCode;
m_Cancelable = Cancelable; m_Cancelled = false;
m_Blockable = Blockable; m_Blocked = false;
m_Timestamp = (size_t)( timer_Time() * 1000.0 );
}
void CScriptEvent::ScriptingInit()
{
AddMethod<CStr, &CScriptEvent::ToString>( "toString", 0 );
AddMethod<void, &CScriptEvent::PreventDefault>( "preventDefault", 0 );
AddMethod<void, &CScriptEvent::PreventDefault>( "cancel", 0 );
AddMethod<void, &CScriptEvent::StopPropagation>( "stopPropagation", 0 );
AddProperty( L"type", &CScriptEvent::m_Type, true );
AddProperty( L"cancelable", &CScriptEvent::m_Cancelable, true );
AddProperty( L"blockable", &CScriptEvent::m_Blockable, true );
AddProperty( L"timestamp", &CScriptEvent::m_Timestamp, true );
CJSObject<CScriptEvent>::ScriptingInit( "Event" );
}
void CScriptEvent::PreventDefault( JSContext* UNUSED(cx), uintN UNUSED(argc), jsval* UNUSED(argv) )
{
if( m_Cancelable )
m_Cancelled = true;
}
void CScriptEvent::StopPropagation( JSContext* UNUSED(cx), uintN UNUSED(argc), jsval* UNUSED(argv) )
{
if( m_Blockable )
m_Blocked = true;
}
CStr CScriptEvent::ToString( JSContext* UNUSED(cx), uintN UNUSED(argc), jsval* UNUSED(argv) )
{
return "[object Event: " + CStr(m_Type) + "]";
}

View File

@ -1,152 +0,0 @@
/* Copyright (C) 2009 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
*/
// DOM-style event object
// Note: Cancellable [UK]? Cancelable [US]? DOM says one l, OED says 2.
// JS interface uses 1.
// Entity and e.g. projectile classes derive from this and use it for
// sending/receiving events.
#ifndef INCLUDED_DOMEVENT
#define INCLUDED_DOMEVENT
#include "ScriptableObject.h"
#include "EventTypes.h" // for EVENT_LAST
class CScriptObject;
class CScriptEvent;
typedef CScriptObject* DOMEventHandler;
class IEventTarget
{
// Return 'true' if we should stop propagating.
bool _DispatchEvent( CScriptEvent* evt, IEventTarget* target );
// Events dispatched to this object are sent here before being processed.
IEventTarget* before;
// Events dispatched to this object are sent here after being processed.
IEventTarget* after;
typedef std::vector<DOMEventHandler> HandlerList;
HandlerList m_Handlers_id[EVENT_LAST];
typedef STL_HASH_MULTIMAP<CStrW, DOMEventHandler, CStrW_hash_compare> HandlerMap;
HandlerMap m_Handlers_name;
typedef std::pair<HandlerMap::iterator, HandlerMap::iterator> HandlerRange;
public:
IEventTarget()
{
before = NULL;
after = NULL;
}
virtual ~IEventTarget();
// Set target that will receive each event after it is processed.
// unused
inline void SetPriorObject( IEventTarget* obj )
{
before = obj;
}
// Set target that will receive each event after it is processed.
// used by Entity and EntityTemplate.
inline void SetNextObject( IEventTarget* obj )
{
after = obj;
}
// Register a handler for the given event type.
// Returns false if the handler was already present
bool AddHandler( size_t TypeCode, DOMEventHandler handler );
bool AddHandler( const CStrW& TypeString, DOMEventHandler handler );
// Remove a previously registered handler for the specified event.
// Returns false if the handler was not present
bool RemoveHandler( size_t TypeCode, DOMEventHandler handler );
bool RemoveHandler( const CStrW& TypeString, DOMEventHandler handler );
// called by ScriptGlue.cpp for add|RemoveGlobalHandler
bool AddHandlerJS( JSContext* cx, uintN argc, jsval* argv );
bool RemoveHandlerJS( JSContext* cx, uintN argc, jsval* argv );
// Return the JSObject* we'd like to be the 'this' object
// when executing the handler. The argument is the object
// to which the event is targeted.
// It is passed to CScriptObject::DispatchEvent.
virtual JSObject* GetScriptExecContext( IEventTarget* target ) = 0;
// Dispatch an event to its handler.
// returns: whether the event arrived (i.e. wasn't cancelled) [bool]
bool DispatchEvent( CScriptEvent* evt );
};
class CScriptEvent : public CJSObject<CScriptEvent>
{
public:
enum EPhaseType
{
CAPTURING_PHASE = 1,
AT_TARGET = 2,
BUBBLING_PHASE = 3
};
// Target (currently unused)
IEventTarget* m_Target;
// Listening object currently being processed (currently unused)
IEventTarget* m_CurrentTarget;
// Phase type (currently unused)
// EPhaseType m_EventPhase;
// Can bubble? (currently unused)
// bool m_Bubbles;
// Can be cancelled (default actions prevented)
bool m_Cancelable;
// Can be blocked (prevented from propogating along the handler chain)
bool m_Blockable;
// Timestamp (milliseconds since epoch (start of game?))
size_t m_Timestamp;
// Event type string
CStrW m_Type;
// Type code (to speed lookups)
size_t m_TypeCode;
// Has been cancelled?
bool m_Cancelled;
// Has it been blocked (won't be sent to any more handlers)
bool m_Blocked;
// --
CStr ToString( JSContext* cx, uintN argc, jsval* argv );
void PreventDefault( JSContext* cx, uintN argc, jsval* argv );
void StopPropagation( JSContext* cx, uintN argc, jsval* argv );
public:
CScriptEvent( const CStrW& Type, size_t TypeCode = ~size_t(0), bool Cancelable = true, bool Blockable = true );
static void ScriptingInit();
};
#endif

View File

@ -1,80 +0,0 @@
/* Copyright (C) 2009 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
*/
// EventTypes.h
// Fairly game-specific event declarations for use with DOMEvent.
// Creates unique (for the current target) names for each event.
// DOMEvent currently uses a preallocated array of EVENT_LAST elements,
// so these must be consecutive integers starting with 0.
#ifndef INCLUDED_EVENTTYPES
#define INCLUDED_EVENTTYPES
enum EEventType
{
// Entity events
EVENT_INITIALIZE = 0,
EVENT_DEATH,
EVENT_TICK,
EVENT_CONTACT_ACTION,
EVENT_TARGET_EXHAUSTED,
EVENT_START_CONSTRUCTION,
EVENT_START_PRODUCTION,
EVENT_CANCEL_PRODUCTION,
EVENT_FINISH_PRODUCTION,
EVENT_TARGET_CHANGED,
EVENT_PREPARE_ORDER,
EVENT_ORDER_TRANSITION,
EVENT_NOTIFICATION,
EVENT_FORMATION,
EVENT_IDLE,
EVENT_LAST,
// Projectile events
EVENT_IMPACT = 0,
EVENT_MISS,
// General events
EVENT_GAME_START = 0,
EVENT_GAME_TICK,
EVENT_SELECTION_CHANGED,
EVENT_WORLD_CLICK,
};
// Only used for entity events... (adds them as a property)
static const wchar_t* const EventNames[EVENT_LAST] =
{
/* EVENT_INITIALIZE */ L"onInitialize",
/* EVENT_DEATH */ L"onDeath",
/* EVENT_TICK */ L"onTick",
/* EVENT_CONTACT_ACTION */ L"onContactAction", /* For generic contact actions on a target unit, like attack or gather */
/* EVENT_TARGET_EXHAUSTED*/ L"onTargetExhausted", /* Called when the target of a generic action dies */
/* EVENT_START_CONSTRUCTION */ L"onStartConstruction", /* We were selected when the user placed a building */
/* EVENT_START_PRODUCTION */ L"onStartProduction", /* We're about to start training/researching something (deduct resources, etc) */
/* EVENT_CANCEL_PRODUCTION */ L"onCancelProduction", /* Something in production has been cancelled */
/* EVENT_FINISH_PRODUCTION */ L"onFinishProduction", /* We've finished something in production */
/* EVENT_TARGET_CHANGED */ L"onTargetChanged", /* If this unit is selected and the mouseover object changes */
/* EVENT_PREPARE_ORDER */ L"onPrepareOrder", /* To check if a unit can execute a given order */
/* EVENT_ORDER_TRANSITION */ L"onOrderTransition", /* When we change orders (sometimes...) */
/* EVENT_NOTIFICATION */ L"onNotification", /*When we receive a notification */
/* EVENT_FORMATION */ L"onFormation", /* When this unit does something with a formation */
/* EVENT_IDLE */ L"onIdle", /* When this unit becomes idle, do something */
};
#endif // #ifndef INCLUDED_EVENTTYPES

View File

@ -24,7 +24,6 @@
#include "lib/sysdep/sysdep.h" // isfinite
#include <math.h>
#include <cfloat>
#include "scripting/ScriptableComplex.inl"
// CVector3D
@ -48,19 +47,6 @@ template<> jsval ToJSVal<CVector3D>( const CVector3D& Native )
return( OBJECT_TO_JSVAL( Script ) );
}
// CScriptObject
template<> jsval ToJSVal<CScriptObject>( CScriptObject& Native )
{
return( OBJECT_TO_JSVAL( Native.GetFunctionObject() ) );
}
template<> bool ToPrimitive<CScriptObject>( JSContext* UNUSED(cx), jsval v, CScriptObject& Storage )
{
Storage.SetJSVal( v );
return( true );
}
// int
template<> jsval ToJSVal<int>( const int& Native )

View File

@ -1,158 +0,0 @@
/* Copyright (C) 2009 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
*/
// Functions for (de)serialization of jsvals
// WIP, not yet functional
#include "network/Serialization.h"
#include "JSConversions.h"
#include "ps/CStr.h"
class jsval_ser : public ISerializable
{
enum
{
TAG_BOOLEAN_FALSE,
TAG_BOOLEAN_TRUE,
TAG_INT,
TAG_DOUBLE,
TAG_STRING,
TAG_NOT_SERIALIZABLE = -1
} m_tag;
jsval m_data;
public:
jsval_ser() : m_tag( TAG_NOT_SERIALIZABLE )
{
}
jsval_ser( jsval data ) : m_data( data )
{
if( m_data == JSVAL_FALSE )
m_tag = TAG_BOOLEAN_FALSE;
if( m_data == JSVAL_TRUE )
m_tag = TAG_BOOLEAN_TRUE;
if( JSVAL_IS_INT( m_data ) )
m_tag = TAG_INT;
if( JSVAL_IS_DOUBLE( m_data ) )
m_tag = TAG_DOUBLE;
if( JSVAL_IS_STRING( m_data ) )
m_tag = TAG_STRING;
m_tag = TAG_NOT_SERIALIZABLE;
}
operator jsval() const
{
return( m_data );
}
operator CStr() const
{
return( ToPrimitive<CStrW>( m_data ) );
}
size_t GetSerializedLength() const
{
switch( m_tag )
{
case TAG_BOOLEAN_FALSE:
case TAG_BOOLEAN_TRUE:
return( 1 );
case TAG_INT:
return( 5 );
case TAG_DOUBLE:
return( 9 );
case TAG_STRING:
return( 1 + (ToPrimitive<CStrW>(m_data)).GetSerializedLength() );
default:
debug_warn(L"An attempt was made to serialize a jsval other than a number, boolean or string." );
return( 1 );
}
}
u8* Serialize( u8* buffer ) const
{
Serialize_int_1( buffer, m_tag );
switch( m_tag )
{
case TAG_BOOLEAN_FALSE:
case TAG_BOOLEAN_TRUE:
break;
case TAG_INT:
{
u32 ival = JSVAL_TO_INT( m_data );
Serialize_int_4( buffer, ival );
}
break;
case TAG_DOUBLE:
{
union {
u64 ival;
double dval;
} val;
cassert(sizeof(u64) == sizeof(double));
val.dval = *JSVAL_TO_DOUBLE( m_data );
Serialize_int_8( buffer, val.ival );
}
break;
case TAG_STRING:
buffer = ( ToPrimitive<CStrW>( m_data ) ).Serialize( buffer );
break;
default:
debug_warn(L"An attempt was made to serialize a jsval other than a number, boolean or string." );
break;
}
return( buffer );
}
const u8* Deserialize( const u8* buffer, const u8* end )
{
Deserialize_int_1( buffer, (u8&)m_tag );
switch( m_tag )
{
case TAG_BOOLEAN_FALSE:
m_data = JSVAL_FALSE;
break;
case TAG_BOOLEAN_TRUE:
m_data = JSVAL_TRUE;
break;
case TAG_INT:
{
u32 ival;
Deserialize_int_4( buffer, ival );
m_data = INT_TO_JSVAL( ival );
}
break;
case TAG_DOUBLE:
{
union {
u64 ival;
double dval;
} val;
cassert(sizeof(u64) == sizeof(double));
Deserialize_int_8( buffer, val.ival );
JS_NewDoubleValue( g_ScriptingHost.GetContext(), val.dval, &m_data );
}
break;
case TAG_STRING:
{
CStrW ival;
buffer = ival.Deserialize( buffer, end );
m_data = ToJSVal<CStrW>( ival );
}
break;
default:
debug_warn(L"An attempt was made to deserialize a jsval other than a number, boolean or string." );
break;
}
return( buffer );
}
};

View File

@ -1,111 +0,0 @@
/* Copyright (C) 2009 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
*/
#include "precompiled.h"
#include "ScriptingHost.h"
#include "ScriptCustomTypes.h"
// POINT2D
JSClass Point2dClass =
{
"Point2d", 0,
JS_PropertyStub, JS_PropertyStub,
JS_PropertyStub, JS_PropertyStub,
JS_EnumerateStub, JS_ResolveStub,
JS_ConvertStub, JS_FinalizeStub
};
JSPropertySpec Point2dProperties[] =
{
{"x", 0, JSPROP_ENUMERATE},
{"y", 1, JSPROP_ENUMERATE},
{0}
};
JSBool Point2d_Constructor(JSContext* UNUSED(cx), JSObject* obj, uintN argc, jsval* argv, jsval* UNUSED(rval))
{
if (argc == 2)
{
g_ScriptingHost.SetObjectProperty(obj, "x", argv[0]);
g_ScriptingHost.SetObjectProperty(obj, "y", argv[1]);
}
else
{
jsval zero = INT_TO_JSVAL(0);
g_ScriptingHost.SetObjectProperty(obj, "x", zero);
g_ScriptingHost.SetObjectProperty(obj, "y", zero);
}
return JS_TRUE;
}
// Colour
void SColour::SColourInit( float _r, float _g, float _b, float _a )
{
r = _r; g = _g; b = _b; a = _a;
}
void SColour::ScriptingInit()
{
AddMethod<CStr, &SColour::ToString>( "toString", 0 );
AddProperty<float>( L"r", (float IJSObject::*)&SColour::r );
AddProperty<float>( L"g", (float IJSObject::*)&SColour::g );
AddProperty<float>( L"b", (float IJSObject::*)&SColour::b );
AddProperty<float>( L"a", (float IJSObject::*)&SColour::a );
CJSObject<SColour>::ScriptingInit( "Colour", SColour::Construct, 3 );
}
CStr SColour::ToString( JSContext* UNUSED(cx), uintN UNUSED(argc), jsval* UNUSED(argv) )
{
return "[object Colour: ( " + CStr(r) + ", " + CStr(g) + ", " + CStr(b) + ", " + CStr(a) + " )]";
}
JSBool SColour::Construct( JSContext* UNUSED(cx), JSObject* UNUSED(obj), uintN argc, jsval* argv, jsval* rval )
{
debug_assert( argc >= 3 );
float alpha = 1.0;
if( argc >= 4 ) alpha = ToPrimitive<float>( argv[3] );
SColour* col = new SColour( ToPrimitive<float>( argv[0] ),
ToPrimitive<float>( argv[1] ),
ToPrimitive<float>( argv[2] ),
alpha );
col->m_EngineOwned = false;
*rval = OBJECT_TO_JSVAL( col->GetScript() );
return( JS_TRUE );
}
// (Simon) Added this to prevent a deep copy, which evidently makes direct
// copies of the heap allocated objects within CJSObject, which eventually
// goes boom
SColour &SColour::operator = (const SColour &o)
{
r=o.r;
g=o.g;
b=o.b;
a=o.a;
return *this;
}

View File

@ -1,51 +0,0 @@
/* Copyright (C) 2009 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
*/
#include "scripting/ScriptableObject.h"
#ifndef INCLUDED_SCRIPTCUSTOMTYPES
#define INCLUDED_SCRIPTCUSTOMTYPES
// Custom object types
// Whilst Point2d is fully coded, it is never registered so is not available in script
// This is mostly as a demonstration of what you need to code to add a new type
// VECTOR2D
extern JSClass Point2dClass;
extern JSPropertySpec Point2dProperties[];
JSBool Point2d_Constructor(JSContext *cx, JSObject *obj, uintN argc, jsval *argv, jsval *rval);
// Colour
struct SColour : public CJSObject<SColour>
{
public:
float r, g, b, a; /* 0...1 */
SColour() { SColourInit( 0.0f, 0.0f, 0.0f, 0.0f ); }
SColour( float r_, float g_, float b_ ) { SColourInit( r_, g_, b_, 1.0f ); }
SColour( float r_, float g_, float b_, float a_ ) { SColourInit( r_, g_, b_, a_ ); }
SColour( const SColour& other ) : CJSObject<SColour>() { SColourInit( other.r, other.g, other.b, other.a ); }
void SColourInit( float r, float g, float b, float a );
SColour &operator = (const SColour &o);
CStr ToString( JSContext* cx, uintN argc, jsval* argv );
static void ScriptingInit();
static JSBool Construct( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval );
};
#endif

View File

@ -26,8 +26,6 @@
#include "ScriptGlue.h"
#include "JSConversions.h"
#include "ScriptableComplex.inl"
#include "graphics/GameView.h"
#include "graphics/LightEnv.h"
#include "graphics/MapWriter.h"

View File

@ -1,143 +0,0 @@
/* Copyright (C) 2009 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
*/
#include "precompiled.h"
#include "ScriptObject.h"
#include "ScriptingHost.h"
#include "JSConversions.h"
#include "DOMEvent.h"
CScriptObject::CScriptObject()
{
Function = NULL;
}
CScriptObject::~CScriptObject()
{
Uproot();
}
void CScriptObject::Root()
{
if( !Function )
return;
FunctionObject = JS_GetFunctionObject( Function );
JS_AddRoot( g_ScriptingHost.GetContext(), &FunctionObject );
}
void CScriptObject::Uproot()
{
if( Function )
JS_RemoveRoot( g_ScriptingHost.GetContext(), &FunctionObject );
}
CScriptObject::CScriptObject( JSFunction* _Function )
{
Function = NULL;
SetFunction( _Function );
}
CScriptObject::CScriptObject( jsval v )
{
Function = NULL;
SetJSVal( v );
}
CScriptObject::CScriptObject( const CScriptObject& copy )
{
Function = NULL;
SetFunction( copy.Function );
}
void CScriptObject::SetFunction( JSFunction* _Function )
{
Uproot();
Function = _Function;
Root();
}
void CScriptObject::SetJSVal( jsval v )
{
CStrW Source;
switch( JS_TypeOfValue( g_ScriptingHost.GetContext(), v ) )
{
case JSTYPE_STRING:
Source = g_ScriptingHost.ValueToUCString( v );
Compile( L"unknown", Source );
break;
case JSTYPE_FUNCTION:
SetFunction( JS_ValueToFunction( g_ScriptingHost.GetContext(), v ) );
break;
default:
Function = NULL;
}
}
JSObject* CScriptObject::GetFunctionObject()
{
if( Function )
return( FunctionObject );
return( NULL );
}
// Executes a script attached to a JS object.
// Returns false if the script isn't defined, if the script can't be executed,
// otherwise true. Script return value is in rval.
bool CScriptObject::Run( JSObject* Context, jsval* rval, uintN argc, jsval* argv )
{
if( !Function )
return( false );
return( JS_TRUE == JS_CallFunction( g_ScriptingHost.GetContext(), Context, Function, argc, argv, rval ) );
}
// This variant casts script return value to a boolean, and passes it back.
bool CScriptObject::Run( JSObject* Context, uintN argc, jsval* argv )
{
jsval Temp;
if( !Run( Context, &Temp, argc, argv ) )
return( false );
return( ToPrimitive<bool>( Temp ) );
}
// Treat this as an event handler and dispatch an event to it. Return !evt->m_cancelled, as a convenience.
bool CScriptObject::DispatchEvent( JSObject* Context, CScriptEvent* evt )
{
if( Function )
{
jsval Temp;
jsval EventObject = OBJECT_TO_JSVAL( evt->GetScript() );
JS_CallFunction( g_ScriptingHost.GetContext(), Context, Function, 1, &EventObject, &Temp );
}
return( evt->m_Blocked );
}
void CScriptObject::Compile( const CStrW& FileNameTag, const CStrW& FunctionBody )
{
if( Function )
JS_RemoveRoot( g_ScriptingHost.GetContext(), &Function );
const char* argnames[] = { "evt" };
utf16string str16=FunctionBody.utf16();
Function = JS_CompileUCFunction( g_ScriptingHost.GetContext(), NULL, NULL, 1, argnames, str16.c_str(), str16.size(), CStr(FileNameTag), 0 );
Root();
}

View File

@ -1,73 +0,0 @@
/* Copyright (C) 2009 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
*/
// A generic type and some helper functions
// for scripts
#ifndef INCLUDED_SCRIPTOBJECT
#define INCLUDED_SCRIPTOBJECT
#include "scripting/SpiderMonkey.h"
class CStrW;
class CScriptEvent;
class CScriptObject
{
JSFunction* Function;
JSObject* FunctionObject;
void Root();
void Uproot();
public:
CScriptObject();
CScriptObject( JSFunction* _Function );
CScriptObject( jsval v );
CScriptObject( const CScriptObject& copy );
~CScriptObject();
// Initialize in various ways: from a JS function, a string to be compiled, or a jsval containing either.
void SetFunction( JSFunction* _Function );
void SetJSVal( jsval v );
void Compile( const CStrW& FileNameTag, const CStrW& FunctionBody );
inline bool Defined()
{
return( Function != NULL );
}
inline operator bool() { return( Function != NULL ); }
inline bool operator!() { return( !Function ); }
inline bool operator==( const CScriptObject& compare ) { return( Function == compare.Function ); }
// JSObject wrapping the function if it's defined, NULL if it isn't.
JSObject* GetFunctionObject();
// Executes a script attached to a JS object.
// Returns false if the script isn't defined, if the script can't be executed,
// otherwise true. Script return value is in rval.
bool Run( JSObject* Context, jsval* rval, uintN argc = 0, jsval* argv = NULL );
// This variant casts script return value to a boolean, and passes it back.
bool Run( JSObject* Context, uintN argc = 0, jsval* argv = NULL );
// Treat this as an event handler and dispatch an event to it.
bool DispatchEvent( JSObject* Context, CScriptEvent* evt );
};
#endif

View File

@ -1,62 +0,0 @@
/* Copyright (C) 2009 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
*/
#include "precompiled.h"
#include "ScriptableComplex.h"
#include "ScriptableComplex.inl"
#include "lib/allocators/bucket.h"
//-----------------------------------------------------------------------------
// suballocator for CJSComplex.m_Properties elements
// (must come after property defs, which are currently in the header)
//-----------------------------------------------------------------------------
static Bucket bucket;
// HACK: it needs to be created/destroyed; since there is no
// global init/shutdown call here, we keep a refcnt. this assumes that
// going to 0 <==> shutdown! if that proves wrong, bucket_alloc will warn.
static size_t suballoc_refs; // initialized in suballoc_attach
void jscomplexproperty_suballoc_attach()
{
ONCE(\
size_t el_size = std::max(sizeof(CJSValComplexProperty), sizeof(CJSComplexProperty<int, true>));\
(void)bucket_create(&bucket, el_size);\
suballoc_refs = 0;\
);
suballoc_refs++;
}
void jscomplexproperty_suballoc_detach()
{
suballoc_refs--;
if(suballoc_refs == 0)
bucket_destroy(&bucket);
}
void* jscomplexproperty_suballoc()
{
return bucket_alloc(&bucket, 0);
}
void jscomplexproperty_suballoc_free(IJSComplexProperty* p)
{
// explicit dtor since caller uses placement new
p->~IJSComplexProperty();
bucket_free(&bucket, p);
}

View File

@ -1,312 +0,0 @@
/* Copyright (C) 2009 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
*/
/*
ScriptableComplex.h
The version of CJSObject<> that retains the ability to use inheritance
in its objects. Shouldn't be used any more for anything but entity code.
This file contains only declarations of class CJSComplex and its methods.
Their implementations are in ScriptableComplex.inl. Because CJSComplex is
a templated class, any source file that uses these methods directly must
#include ScritpableComplex.inl to link to them. However, files that
only need to know that something is a CJSComplex need not do this. This
was done to speed up compile times after modifying CJSComplex's internals:
before, 30+ files had to be recompiled because they #included Entity.h
which #includes ScriptableComplex.h.
*/
#ifndef INCLUDED_SCRIPTABLECOMPLEX
#define INCLUDED_SCRIPTABLECOMPLEX
#include "scripting/ScriptingHost.h"
#include "scripting/ScriptObject.h"
#include "JSConversions.h"
#include "lib/sysdep/stl.h"
#include <set>
class IJSComplex;
class IJSComplexProperty
{
public:
bool m_AllowsInheritance;
bool m_Inherited;
bool m_Intrinsic;
// This is to make sure that all the fields are initialized at construction
inline IJSComplexProperty():
m_AllowsInheritance(true),
m_Inherited(true),
m_Intrinsic(true)
{}
virtual jsval Get( JSContext* cx, IJSComplex* owner ) = 0;
virtual void Set( JSContext* cx, IJSComplex* owner, jsval Value ) = 0;
// Copies the data directly out of a parent property
// Warning: Don't use if you're not certain the properties are not of the same type.
virtual void ImmediateCopy( IJSComplex* CopyTo, IJSComplex* CopyFrom, IJSComplexProperty* CopyProperty ) = 0;
jsval Get( IJSComplex* owner ) { return( Get( g_ScriptingHost.GetContext(), owner ) ); }
void Set( IJSComplex* owner, jsval Value ) { return( Set( g_ScriptingHost.GetContext(), owner, Value ) ); }
virtual ~IJSComplexProperty() {}
};
class IJSComplex
{
// Make copy constructor and assignment operator private - since copying of
// these objects is unsafe unless done specially.
// These will never be implemented (they are, after all, here to *prevent*
// copying)
IJSComplex(const IJSComplex &other);
IJSComplex& operator=(const IJSComplex &other);
public:
typedef STL_HASH_MAP<CStrW, IJSComplexProperty*, CStrW_hash_compare> PropertyTable;
typedef std::vector<IJSComplex*> InheritorsList;
typedef std::set<CStrW> StringTable;
typedef std::pair<StringTable, StringTable::iterator> IteratorState;
// Used for freshen/update
typedef void (IJSComplex::*NotifyFn)();
// Property getters and setters
typedef jsval (IJSComplex::*GetFn)();
typedef void (IJSComplex::*SetFn)( jsval );
// Properties of this object
PropertyTable m_Properties;
// Parent object
IJSComplex* m_Parent;
// Objects that inherit from this
InheritorsList m_Inheritors;
// Destructor
virtual ~IJSComplex() { }
// Set the base, and rebuild
void SetBase( IJSComplex* m_Parent );
// Rebuild any intrinsic (mapped-to-C++-variable) properties
virtual void Rebuild() = 0;
// HACK: Doesn't belong here.
virtual void RebuildClassSet() = 0;
// Check for a property
virtual IJSComplexProperty* HasProperty( const CStrW& PropertyName ) = 0;
// Get all properties of an object
virtual void FillEnumerateSet( IteratorState* it, CStrW* PropertyRoot = NULL ) = 0;
// Retrieve the value of a property (returning false if that property is not defined)
virtual bool GetProperty( JSContext* cx, const CStrW& PropertyName, jsval* vp ) = 0;
// Add a property (with immediate value)
virtual void AddProperty( const CStrW& PropertyName, jsval Value ) = 0;
virtual void AddProperty( const CStrW& PropertyName, const CStrW& Value ) = 0;
inline IJSComplex() {}
};
class CJSReflector;
template<typename T, bool ReadOnly, typename ReturnType, ReturnType (T::*NativeFunction)( JSContext* cx, uintN argc, jsval* argv )>
void AddMethodImpl( const char* Name, uintN MinArgs );
template<typename T, bool ReadOnly, typename PropType>
void AddClassPropertyImpl( const CStrW& PropertyName, PropType T::*Native, bool PropAllowInheritance = true, IJSComplex::NotifyFn Update = NULL, IJSComplex::NotifyFn Refresh = NULL );
template<typename T, bool ReadOnly, typename PropType>
void AddReadOnlyClassPropertyImpl( const CStrW& PropertyName, PropType T::*Native, bool PropAllowInheritance = true, IJSComplex::NotifyFn Update = NULL, IJSComplex::NotifyFn Refresh = NULL );
template<typename T, bool ReadOnly, typename PropType>
void MemberAddPropertyImpl( IJSComplex* obj, const CStrW& PropertyName, PropType* Native, bool PropAllowInheritance = true, IJSComplex::NotifyFn Update = NULL, IJSComplex::NotifyFn Refresh = NULL );
template<typename T, bool ReadOnly, typename PropType>
void MemberAddReadOnlyPropertyImpl( IJSComplex* obj, const CStrW& PropertyName, PropType* Native, bool PropAllowInheritance = true, IJSComplex::NotifyFn Update = NULL, IJSComplex::NotifyFn Refresh = NULL );
template<typename T, bool ReadOnly = false> class CJSComplex : public IJSComplex
{
public:
typedef STL_HASH_MAP<CStrW, CJSReflector*, CStrW_hash_compare> ReflectorTable;
template<typename Q> friend class CJSComplexPropertyAccessor;
JSObject* m_JS;
std::vector<CScriptObject> m_Watches;
ReflectorTable m_Reflectors;
static JSPropertySpec JSI_props[];
static std::vector<JSFunctionSpec> m_Methods;
static PropertyTable m_IntrinsicProperties;
public:
static JSClass JSI_class;
// Whether native code is responsible for managing this object.
// Script constructors should clear this *BEFORE* creating a JS
// mirror (otherwise it'll be rooted).
bool m_EngineOwned;
// JS Property access
bool GetProperty( JSContext* cx, const CStrW& PropertyName, jsval* vp );
void SetProperty( JSContext* cx, const CStrW& PropertyName, jsval* vp );
void WatchNotify( JSContext* cx, const CStrW& PropertyName, jsval* newval );
//
// Functions that must be provided to JavaScript
//
static JSBool JSGetProperty( JSContext* cx, JSObject* obj, jsval id, jsval* vp );
static JSBool JSSetProperty( JSContext* cx, JSObject* obj, jsval id, jsval* vp );
static JSBool JSEnumerate( JSContext* cx, JSObject* obj, JSIterateOp enum_op, jsval* statep, jsid *idp );
static JSBool SetWatchAll( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval );
static JSBool UnWatchAll( JSContext* cx, JSObject* obj, uintN argc, jsval* argv, jsval* rval );
static void ScriptingInit( const char* ClassName, JSNative Constructor = NULL, uintN ConstructorMinArgs = 0 );
static void ScriptingShutdown();
static void DefaultFinalize( JSContext *cx, JSObject *obj );
public:
// Creating and releasing script objects is done automatically most of the time, but you
// can do it explicitly.
void CreateScriptObject();
void ReleaseScriptObject();
JSObject* GetScript()
{
if( !m_JS )
CreateScriptObject();
return( m_JS );
}
CJSComplex();
virtual ~CJSComplex();
void Shutdown();
void SetBase( IJSComplex* Parent );
void Rebuild();
IJSComplexProperty* HasProperty( const CStrW& PropertyName );
void FillEnumerateSet( IteratorState* it, CStrW* PropertyRoot = NULL );
void AddProperty( const CStrW& PropertyName, jsval Value );
void AddProperty( const CStrW& PropertyName, const CStrW& Value );
static void AddClassProperty( const CStrW& PropertyName, GetFn Getter, SetFn Setter = NULL );
// these functions are themselves templatized. we don't want to implement
// them in the header because that would drag in many dependencies.
//
// therefore, the publicly visible functions actually only call out to
// external friend functions implemented in the .inl file.
// these receive the template parameters from the class as well as the
// ones added for the member function.
//
// for non-static members, the friends additionally take a "this" pointer.
template<typename ReturnType, ReturnType (T::*NativeFunction)( JSContext* cx, uintN argc, jsval* argv )>
static void AddMethod( const char* Name, uintN MinArgs )
{
AddMethodImpl<T, ReadOnly, ReturnType, NativeFunction>(Name, MinArgs);
}
template<typename PropType>
static void AddClassProperty( const CStrW& PropertyName, PropType T::*Native, bool PropAllowInheritance = true, NotifyFn Update = NULL, NotifyFn Refresh = NULL )
{
AddClassPropertyImpl<T, ReadOnly, PropType>(PropertyName, Native, PropAllowInheritance, Update, Refresh);
}
template<typename PropType>
static void AddReadOnlyClassProperty( const CStrW& PropertyName, PropType T::*Native, bool PropAllowInheritance = true, NotifyFn Update = NULL, NotifyFn Refresh = NULL )
{
AddReadOnlyClassPropertyImpl<T, ReadOnly, PropType>(PropertyName, Native, PropAllowInheritance, Update, Refresh);
}
// PropertyName must not already exist! (verified in debug build)
template<typename PropType>
void AddProperty( const CStrW& PropertyName, PropType* Native, bool PropAllowInheritance = true, NotifyFn Update = NULL, NotifyFn Refresh = NULL )
{
MemberAddPropertyImpl<T, ReadOnly, PropType>(this, PropertyName, Native, PropAllowInheritance, Update, Refresh);
}
// PropertyName must not already exist! (verified in debug build)
template<typename PropType>
void AddReadOnlyProperty( const CStrW& PropertyName, PropType* Native, bool PropAllowInheritance = true, NotifyFn Update = NULL, NotifyFn Refresh = NULL )
{
MemberAddReadOnlyPropertyImpl<T, ReadOnly, PropType>(this, PropertyName, Native, PropAllowInheritance, Update, Refresh);
}
// helper routine for Add*Property. Their interface requires the
// property not already exist; we check for this (in debug builds)
// and if so, warn and free the previously new-ed memory in
// m_Properties[PropertyName] (avoids mem leak).
void DeletePreviouslyAssignedProperty( const CStrW& PropertyName );
};
//
// static members
//
template<typename T, bool ReadOnly> JSClass CJSComplex<T, ReadOnly>::JSI_class = {
NULL, JSCLASS_HAS_PRIVATE | JSCLASS_NEW_ENUMERATE,
JS_PropertyStub, JS_PropertyStub,
JSGetProperty, JSSetProperty,
(JSEnumerateOp)JSEnumerate, JS_ResolveStub,
JS_ConvertStub, DefaultFinalize,
NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL
};
template<typename T, bool ReadOnly> JSPropertySpec CJSComplex<T, ReadOnly>::JSI_props[] = {
{ NULL, 0, 0, NULL, NULL },
};
template<typename T, bool ReadOnly> std::vector<JSFunctionSpec> CJSComplex<T, ReadOnly>::m_Methods;
template<typename T, bool ReadOnly> typename CJSComplex<T, ReadOnly>::PropertyTable CJSComplex<T, ReadOnly>::m_IntrinsicProperties;
template<typename T>
void ScriptableComplex_InitComplexPropertyAccessor();
//
// suballocator for CJSComplex.m_Properties elements
// (referenced from implementation in .inl)
//
extern void jscomplexproperty_suballoc_attach();
extern void jscomplexproperty_suballoc_detach();
extern void* jscomplexproperty_suballoc();
extern void jscomplexproperty_suballoc_free(IJSComplexProperty* p);
#endif

File diff suppressed because it is too large Load Diff

View File

@ -1,122 +0,0 @@
/* Copyright (C) 2009 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
*/
#include "precompiled.h"
#include "SynchedJSObject.h"
#include "ps/Parser.h"
#include "ScriptCustomTypes.h"
template <>
CStrW ToNetString(const size_t &val)
{
return CStrW((unsigned long)val);
}
template <>
void SetFromNetString(size_t &val, const CStrW& string)
{
val=string.ToUInt();
}
template <>
CStrW ToNetString(const int &val)
{
return CStrW(val);
}
template <>
void SetFromNetString(int &val, const CStrW& string)
{
val=string.ToInt();
}
template <>
CStrW ToNetString(const bool &val)
{
return val ? L"true" : L"false";
}
template <>
void SetFromNetString(bool &val, const CStrW& string)
{
val = (string == L"true");
}
template <>
CStrW ToNetString(const CStrW& data)
{
return data;
}
template <> void SetFromNetString(CStrW& data, const CStrW& string)
{
data=string;
}
template <>
CStrW ToNetString(const SColour &data)
{
wchar_t buf[256];
swprintf_s(buf, ARRAY_SIZE(buf), L"%f %f %f %f", data.r, data.g, data.b, data.a);
return buf;
}
template <>
void SetFromNetString(SColour &data, const CStrW& wstring)
{
CParser &parser(CParserCache::Get("$value_$value_$value_$value"));
CParserLine line;
line.ParseString(parser, CStr(wstring));
float values[4];
if (line.GetArgCount() != 4) return;
for (size_t i=0; i<4; ++i)
{
if (!line.GetArgFloat(i, values[i]))
{
return;
}
}
data.r = values[0];
data.g = values[1];
data.b = values[2];
data.a = values[3];
}
void CSynchedJSObjectBase::IterateSynchedProperties(IterateCB *cb, void *userdata)
{
SynchedPropertyIterator it=m_SynchedProperties.begin();
while (it != m_SynchedProperties.end())
{
cb(it->first, it->second, userdata);
++it;
}
}
ISynchedJSProperty *CSynchedJSObjectBase::GetSynchedProperty(const CStrW& name)
{
SynchedPropertyIterator prop=m_SynchedProperties.find(name);
if (prop != m_SynchedProperties.end())
return prop->second;
else
return NULL;
}

View File

@ -1,167 +0,0 @@
/* Copyright (C) 2009 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* 0 A.D. is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
*/
/*
CSynchedJSObject
DESCRIPTION:
A helper class for CJSObject that enables a callback to be called
whenever an attribute of the class changes and enables all (synched)
properties to be set and retrieved as strings for network sync.
All string conversions are performed by specific functions that use a
strictly (hrm) defined format - or at least a format that is specific
for the type in question (which is why JSParseString can't be used -
the JS interface's ToString function is also not usable since it often
produces a human-readable format that doesn't parse well and might
change outside the control of the network protocol).
This replaces CAttributeMap for both player and game attributes.
USAGE:
First you must create your subclass, make it inherit from
CSynchedJSObject and implement the pure virtual method Update (see
prototype below)
Then you may use it just like CJSObject (see ScriptableObject.h) - with
one exception: Any property you want to be synchronized (i.e. have the
new property functionality including the update callback) is added using
the AddSynchedProperty method instead: AddSynchedProperty(name, &m_Property)
The extra arguments that exist in the AddProperty method haven't been
implemented (if you by any chance would need to, just do it ;-)
*/
#ifndef INCLUDED_SYNCHEDJSOBJECT
#define INCLUDED_SYNCHEDJSOBJECT
#include "ps/CStr.h"
#include "ScriptableObject.h"
template <typename T>
void SetFromNetString(T &data, const CStrW& string);
template <typename T>
CStrW ToNetString(const T &data);
#define TYPE(type) \
template <> CStrW ToNetString(const type &data); \
template <> void SetFromNetString(type &data, const CStrW& string);
TYPE(size_t)
TYPE(CStrW)
#undef TYPE
class ISynchedJSProperty: public IJSProperty
{
public:
virtual void FromString(const CStrW& value)=0;
virtual CStrW ToString()=0;
};
// non-templated base class
struct CSynchedJSObjectBase
{
typedef void (*UpdateFn)(CSynchedJSObjectBase *owner);
template <typename PropType, bool ReadOnly = false>
class CSynchedJSProperty: public ISynchedJSProperty
{
PropType *m_Data;
CStrW m_Name;
CSynchedJSObjectBase *m_Owner;
UpdateFn m_Update;
virtual void Set(JSContext* cx, IJSObject* UNUSED(owner), jsval value)
{
if (!ReadOnly)
{
if (ToPrimitive(cx, value, *m_Data))
{
m_Owner->Update(m_Name, this);
if (m_Update)
m_Update(m_Owner);
}
}
}
virtual jsval Get(JSContext* UNUSED(cx), IJSObject* UNUSED(owner))
{
return ToJSVal(*m_Data);
}
virtual void ImmediateCopy(IJSObject* UNUSED(CopyFrom), IJSObject* UNUSED(CopyTo), IJSProperty* other)
{
*m_Data = *( ((CSynchedJSProperty<PropType, ReadOnly>*)other)->m_Data );
}
virtual void FromString(const CStrW& value)
{
SetFromNetString(*m_Data, value);
if (m_Update)
m_Update(m_Owner);
}
virtual CStrW ToString()
{
return ToNetString(*m_Data);
}
public:
inline CSynchedJSProperty(const CStrW& name, PropType* native, CSynchedJSObjectBase *owner, UpdateFn update=NULL):
m_Data(native),
m_Name(name),
m_Owner(owner),
m_Update(update)
{
}
};
typedef STL_HASH_MAP<CStrW, ISynchedJSProperty *, CStrW_hash_compare> SynchedPropertyTable;
typedef SynchedPropertyTable::iterator SynchedPropertyIterator;
SynchedPropertyTable m_SynchedProperties;
protected:
virtual ~CSynchedJSObjectBase() { }
// Called every time a property changes.
// This is where the individual callbacks are dispatched from.
virtual void Update(const CStrW& name, ISynchedJSProperty *prop)=0;
public:
ISynchedJSProperty *GetSynchedProperty(const CStrW& name);
typedef void (IterateCB)(const CStrW& name, ISynchedJSProperty *prop, void *userdata);
void IterateSynchedProperties(IterateCB *cb, void *userdata);
};
template <typename Class>
class CSynchedJSObject: public CJSObject<Class>, public CSynchedJSObjectBase
{
protected:
// Add a property to the object; if desired, a callback is called every time it changes.
// Replaces CJSObject's AddProperty.
template <typename T> void AddSynchedProperty(const CStrW& name, T *native, UpdateFn update=NULL)
{
ISynchedJSProperty *prop=new CSynchedJSProperty<T>(name, native, this, update);
this->m_NonsharedProperties[name]=prop;
this->m_SynchedProperties[name]=prop;
}
};
#endif

View File

@ -94,7 +94,7 @@ MESSAGEHANDLER(SaveMap)
CMapWriter writer;
const VfsPath pathname = VfsPath(L"maps/scenarios/") / *msg->filename;
writer.SaveMap(pathname,
g_Game->GetWorld()->GetTerrain(), &g_Game->GetWorld()->GetUnitManager(),
g_Game->GetWorld()->GetTerrain(),
g_Renderer.GetWaterManager(), g_Renderer.GetSkyManager(),
&g_LightEnv, g_Game->GetView()->GetCamera(), g_Game->GetView()->GetCinema(),
g_Game->GetSimulation2());