Initial Implementation of the Taml, Asset and Modules systems.

Only has example and shape assets currently.
This commit is contained in:
Areloch 2015-10-13 15:19:36 -05:00
parent 2044b2691e
commit 7a3b40a86d
123 changed files with 30435 additions and 181 deletions

View file

@ -283,10 +283,9 @@ public:
TIXML_ERROR_STRING_COUNT
};
protected:
static const char* SkipWhiteSpace( const char*, TiXmlEncoding encoding );
protected:
inline static bool IsWhiteSpace( char c )
{
return ( isspace( (unsigned char) c ) || c == '\n' || c == '\r' );
@ -360,6 +359,7 @@ protected:
}
}
public:
// Return true if the next characters in the stream are any of the endTag sequences.
// Ignore case only works for english, and should only be relied on when comparing
// to English words: StringEqual( p, "version", true ) is fine.
@ -368,6 +368,7 @@ protected:
bool ignoreCase,
TiXmlEncoding encoding );
protected:
static const char* errorString[ TIXML_ERROR_STRING_COUNT ];
TiXmlCursor location;
@ -375,10 +376,13 @@ protected:
/// Field containing a generic user pointer
void* userData;
public:
// None of these methods are reliable for any language except English.
// Good for approximation, not great for accuracy.
static int IsAlpha( unsigned char anyByte, TiXmlEncoding encoding );
static int IsAlphaNum( unsigned char anyByte, TiXmlEncoding encoding );
protected:
inline static int ToLower( int v, TiXmlEncoding encoding )
{
if ( encoding == TIXML_ENCODING_UTF8 )
@ -750,9 +754,10 @@ protected:
#endif
// Figure out what is at *p, and parse it. Returns null if it is not an xml node.
TiXmlNode* Identify( const char* start, TiXmlEncoding encoding );
virtual TiXmlNode* Identify( const char* start, TiXmlEncoding encoding );
public:
TiXmlNode* parent;
protected:
NodeType type;
TiXmlNode* firstChild;
@ -1047,7 +1052,7 @@ public:
/** Sets an attribute of name to a given value. The attribute
will be created if it does not exist, or changed if it does.
*/
void SetAttribute( const char* name, const char * _value );
virtual void SetAttribute( const char* name, const char * _value );
#ifdef TIXML_USE_STL
const std::string* Attribute( const std::string& name ) const;
@ -1067,7 +1072,7 @@ public:
/** Sets an attribute of name to a given value. The attribute
will be created if it does not exist, or changed if it does.
*/
void SetAttribute( const char * name, int value );
virtual void SetAttribute( const char * name, int value );
/** Sets an attribute of name to a given value. The attribute
will be created if it does not exist, or changed if it does.
@ -1152,7 +1157,6 @@ protected:
*/
const char* ReadValue( const char* in, TiXmlParsingData* prevData, TiXmlEncoding encoding );
private:
TiXmlAttributeSet attributeSet;
};
@ -1264,7 +1268,6 @@ protected :
virtual void StreamIn( std::istream * in, TIXML_STRING * tag );
#endif
private:
bool cdata; // true if this should be input and output as a CDATA style text element
};
@ -1336,8 +1339,6 @@ protected:
virtual void StreamIn( std::istream * in, TIXML_STRING * tag );
#endif
private:
TIXML_STRING version;
TIXML_STRING encoding;
TIXML_STRING standalone;
@ -1416,9 +1417,9 @@ public:
/// Save a file using the current document value. Returns true if successful.
bool SaveFile() const;
/// Load a file using the given filename. Returns true if successful.
bool LoadFile( const char * filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
virtual bool LoadFile( const char * filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
/// Save a file using the given filename. Returns true if successful.
bool SaveFile( const char * filename ) const;
virtual bool SaveFile( const char * filename ) const;
/** Load a file using the given FILE*. Returns true if successful. Note that this method
doesn't stream - the entire object pointed at by the FILE*
will be interpreted as an XML file. TinyXML doesn't stream in XML from the current
@ -1543,14 +1544,15 @@ protected :
virtual void StreamIn( std::istream * in, TIXML_STRING * tag );
#endif
private:
void CopyTo( TiXmlDocument* target ) const;
private:
bool error;
int errorId;
TIXML_STRING errorDesc;
int tabsize;
TiXmlCursor errorLocation;
protected:
bool useMicrosoftBOM; // the UTF-8 BOM were found when read. Note this, and try to write.
};
@ -1797,6 +1799,29 @@ private:
TIXML_STRING lineBreak;
};
class TiXmlParsingData
{
friend class TiXmlDocument;
public:
void Stamp( const char* now, TiXmlEncoding encoding );
const TiXmlCursor& Cursor() const { return cursor; }
private:
// Only used by the document!
TiXmlParsingData( const char* start, int _tabsize, int row, int col )
{
assert( start );
stamp = start;
tabsize = _tabsize;
cursor.row = row;
cursor.col = col;
}
TiXmlCursor cursor;
const char* stamp;
int tabsize;
};
#ifdef _MSC_VER
#pragma warning( pop )

View file

@ -168,29 +168,6 @@ void TiXmlBase::ConvertUTF32ToUTF8( unsigned long input, char* output, int* leng
}
class TiXmlParsingData
{
friend class TiXmlDocument;
public:
void Stamp( const char* now, TiXmlEncoding encoding );
const TiXmlCursor& Cursor() const { return cursor; }
private:
// Only used by the document!
TiXmlParsingData( const char* start, int _tabsize, int row, int col )
{
assert( start );
stamp = start;
tabsize = _tabsize;
cursor.row = row;
cursor.col = col;
}
TiXmlCursor cursor;
const char* stamp;
int tabsize;
};
void TiXmlParsingData::Stamp( const char* now, TiXmlEncoding encoding )

View file

@ -0,0 +1,127 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _EXAMPLE_ASSET_H_
#include "ExampleAsset.h"
#endif
#ifndef _ASSET_MANAGER_H_
#include "assets/assetManager.h"
#endif
#ifndef _CONSOLETYPES_H_
#include "console/consoleTypes.h"
#endif
#ifndef _TAML_
#include "persistence/taml/taml.h"
#endif
#ifndef _ASSET_PTR_H_
#include "assets/assetPtr.h"
#endif
// Debug Profiling.
#include "platform/profiler.h"
//-----------------------------------------------------------------------------
IMPLEMENT_CONOBJECT(ExampleAsset);
ConsoleType(ExampleAssetPtr, TypeExampleAssetPtr, ExampleAsset, ASSET_ID_FIELD_PREFIX)
//-----------------------------------------------------------------------------
ConsoleGetType(TypeExampleAssetPtr)
{
// Fetch asset Id.
return (*((AssetPtr<ExampleAsset>*)dptr)).getAssetId();
}
//-----------------------------------------------------------------------------
ConsoleSetType(TypeExampleAssetPtr)
{
// Was a single argument specified?
if (argc == 1)
{
// Yes, so fetch field value.
const char* pFieldValue = argv[0];
// Fetch asset pointer.
AssetPtr<ExampleAsset>* pAssetPtr = dynamic_cast<AssetPtr<ExampleAsset>*>((AssetPtrBase*)(dptr));
// Is the asset pointer the correct type?
if (pAssetPtr == NULL)
{
// No, so fail.
//Con::warnf("(TypeTextureAssetPtr) - Failed to set asset Id '%d'.", pFieldValue);
return;
}
// Set asset.
pAssetPtr->setAssetId(pFieldValue);
return;
}
// Warn.
Con::warnf("(TypeTextureAssetPtr) - Cannot set multiple args to a single asset.");
}
//-----------------------------------------------------------------------------
ExampleAsset::ExampleAsset() :
mAcquireReferenceCount(0),
mpOwningAssetManager(NULL),
mAssetInitialized(false)
{
// Generate an asset definition.
mpAssetDefinition = new AssetDefinition();
}
//-----------------------------------------------------------------------------
ExampleAsset::~ExampleAsset()
{
// If the asset manager does not own the asset then we own the
// asset definition so delete it.
if (!getOwned())
delete mpAssetDefinition;
}
//-----------------------------------------------------------------------------
void ExampleAsset::initPersistFields()
{
// Call parent.
Parent::initPersistFields();
}
//------------------------------------------------------------------------------
void ExampleAsset::copyTo(SimObject* object)
{
// Call to parent.
Parent::copyTo(object);
}

View file

@ -0,0 +1,70 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _EXAMPLE_ASSET_H_
#define _EXAMPLE_ASSET_H_
#ifndef _ASSET_BASE_H_
#include "assets/assetBase.h"
#endif
#ifndef _ASSET_DEFINITION_H_
#include "assets/assetDefinition.h"
#endif
#ifndef _STRINGUNIT_H_
#include "string/stringUnit.h"
#endif
#ifndef _ASSET_FIELD_TYPES_H_
#include "assets/assetFieldTypes.h"
#endif
//-----------------------------------------------------------------------------
class ExampleAsset : public AssetBase
{
typedef AssetBase Parent;
AssetManager* mpOwningAssetManager;
bool mAssetInitialized;
AssetDefinition* mpAssetDefinition;
U32 mAcquireReferenceCount;
public:
ExampleAsset();
virtual ~ExampleAsset();
/// Engine.
static void initPersistFields();
virtual void copyTo(SimObject* object);
/// Declare Console Object.
DECLARE_CONOBJECT(ExampleAsset);
protected:
virtual void initializeAsset(void) {}
virtual void onAssetRefresh(void) {}
};
DefineConsoleType(TypeExampleAssetPtr, ExampleAsset)
#endif // _ASSET_BASE_H_

View file

@ -0,0 +1,157 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _SHAPE_ASSET_H_
#include "ShapeAsset.h"
#endif
#ifndef _ASSET_MANAGER_H_
#include "assets/assetManager.h"
#endif
#ifndef _CONSOLETYPES_H_
#include "console/consoleTypes.h"
#endif
#ifndef _TAML_
#include "persistence/taml/taml.h"
#endif
#ifndef _ASSET_PTR_H_
#include "assets/assetPtr.h"
#endif
#include "core/resourceManager.h"
// Debug Profiling.
#include "platform/profiler.h"
static U32 execDepth = 0;
static U32 journalDepth = 1;
//-----------------------------------------------------------------------------
IMPLEMENT_CONOBJECT(ShapeAsset);
ConsoleType(TestAssetPtr, TypeShapeAssetPtr, ShapeAsset, ASSET_ID_FIELD_PREFIX)
//-----------------------------------------------------------------------------
ConsoleGetType(TypeShapeAssetPtr)
{
// Fetch asset Id.
return (*((AssetPtr<ShapeAsset>*)dptr)).getAssetId();
}
//-----------------------------------------------------------------------------
ConsoleSetType(TypeShapeAssetPtr)
{
// Was a single argument specified?
if (argc == 1)
{
// Yes, so fetch field value.
const char* pFieldValue = argv[0];
// Fetch asset pointer.
AssetPtr<ShapeAsset>* pAssetPtr = dynamic_cast<AssetPtr<ShapeAsset>*>((AssetPtrBase*)(dptr));
// Is the asset pointer the correct type?
if (pAssetPtr == NULL)
{
// No, so fail.
//Con::warnf("(TypeTextureAssetPtr) - Failed to set asset Id '%d'.", pFieldValue);
return;
}
// Set asset.
pAssetPtr->setAssetId(pFieldValue);
return;
}
// Warn.
Con::warnf("(TypeTextureAssetPtr) - Cannot set multiple args to a single asset.");
}
//-----------------------------------------------------------------------------
ShapeAsset::ShapeAsset() :
mAcquireReferenceCount(0),
mpOwningAssetManager(NULL),
mAssetInitialized(false)
{
// Generate an asset definition.
mpAssetDefinition = new AssetDefinition();
}
//-----------------------------------------------------------------------------
ShapeAsset::~ShapeAsset()
{
// If the asset manager does not own the asset then we own the
// asset definition so delete it.
if (!getOwned())
delete mpAssetDefinition;
}
//-----------------------------------------------------------------------------
void ShapeAsset::initPersistFields()
{
// Call parent.
Parent::initPersistFields();
addField("fileName", TypeFilename, Offset(mFileName, ShapeAsset), "Path to the script file we want to execute");
}
void ShapeAsset::initializeAsset()
{
// Call parent.
Parent::initializeAsset();
if (dStrcmp(mFileName, "") == 0)
return;
loadShape();
}
bool ShapeAsset::loadShape()
{
mShape = ResourceManager::get().load(mFileName);
if (!mShape)
{
Con::errorf("StaticMesh::updateShape : failed to load shape file!");
return false; //if it failed to load, bail out
}
return true;
}
//------------------------------------------------------------------------------
void ShapeAsset::copyTo(SimObject* object)
{
// Call to parent.
Parent::copyTo(object);
}

View file

@ -0,0 +1,86 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _SHAPE_ASSET_H_
#define _SHAPE_ASSET_H_
#ifndef _ASSET_BASE_H_
#include "assets/assetBase.h"
#endif
#ifndef _ASSET_DEFINITION_H_
#include "assets/assetDefinition.h"
#endif
#ifndef _STRINGUNIT_H_
#include "string/stringUnit.h"
#endif
#ifndef _ASSET_FIELD_TYPES_H_
#include "assets/assetFieldTypes.h"
#endif
#ifndef _TSSHAPE_H_
#include "ts/TSShape.h"
#endif
#ifndef __RESOURCE_H__
#include "core/resource.h"
#endif
//-----------------------------------------------------------------------------
class ShapeAsset : public AssetBase
{
typedef AssetBase Parent;
AssetManager* mpOwningAssetManager;
bool mAssetInitialized;
AssetDefinition* mpAssetDefinition;
U32 mAcquireReferenceCount;
protected:
StringTableEntry mFileName;
Resource<TSShape> mShape;
public:
ShapeAsset();
virtual ~ShapeAsset();
/// Engine.
static void initPersistFields();
virtual void copyTo(SimObject* object);
virtual void initializeAsset();
/// Declare Console Object.
DECLARE_CONOBJECT(ShapeAsset);
bool loadShape();
TSShape* getShape() { return mShape; }
protected:
virtual void onAssetRefresh(void) {}
};
DefineConsoleType(TypeShapeAssetPtr, ShapeAsset)
#endif // _ASSET_BASE_H_

View file

@ -236,7 +236,7 @@ DECLARE_STRUCT( Polyhedron );
IMPLEMENT_STRUCT( Polyhedron, Polyhedron,,
"" )
END_IMPLEMENT_STRUCT;
ConsoleType( floatList, TypeTriggerPolyhedron, Polyhedron )
ConsoleType(floatList, TypeTriggerPolyhedron, Polyhedron, "")
ConsoleGetType( TypeTriggerPolyhedron )

View file

@ -65,6 +65,14 @@
#include "platform/platformVFS.h"
#endif
#ifndef _MODULE_MANAGER_H
#include "module/moduleManager.h"
#endif
#ifndef _ASSET_MANAGER_H_
#include "assets/assetManager.h"
#endif
DITTS( F32, gTimeScale, 1.0 );
DITTS( U32, gTimeAdvance, 0 );
DITTS( U32, gFrameSkip, 0 );
@ -257,7 +265,7 @@ void StandardMainLoop::init()
// Initialize modules.
ModuleManager::initializeSystem();
EngineModuleManager::initializeSystem();
// Initialise ITickable.
#ifdef TORQUE_TGB_ONLY
@ -288,6 +296,15 @@ void StandardMainLoop::init()
Con::addVariable("MiniDump::Params", TypeString, &gMiniDumpParams);
Con::addVariable("MiniDump::ExecDir", TypeString, &gMiniDumpExecDir);
#endif
// Register the module manager.
ModuleDatabase.registerObject("ModuleDatabase");
// Register the asset database.
AssetDatabase.registerObject("AssetDatabase");
// Register the asset database as a module listener.
ModuleDatabase.addListener(&AssetDatabase);
ActionMap* globalMap = new ActionMap;
globalMap->registerObject("GlobalActionMap");
@ -317,10 +334,16 @@ void StandardMainLoop::shutdown()
delete tm;
preShutdown();
// Unregister the module database.
ModuleDatabase.unregisterObject();
// Unregister the asset database.
AssetDatabase.unregisterObject();
// Shut down modules.
ModuleManager::shutdownSystem();
EngineModuleManager::shutdownSystem();
ThreadPool::GlobalThreadPool::deleteSingleton();

View file

@ -0,0 +1,352 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _ASSET_BASE_H_
#include "assetBase.h"
#endif
#ifndef _ASSET_MANAGER_H_
#include "assetManager.h"
#endif
#ifndef _CONSOLETYPES_H_
#include "console/consoleTypes.h"
#endif
// Script bindings.
#include "assetBase_ScriptBinding.h"
// Debug Profiling.
#include "platform/profiler.h"
//-----------------------------------------------------------------------------
IMPLEMENT_CONOBJECT(AssetBase);
//-----------------------------------------------------------------------------
StringTableEntry assetNameField = StringTable->insert("AssetName");
StringTableEntry assetDescriptionField = StringTable->insert("AssetDescription");
StringTableEntry assetCategoryField = StringTable->insert("AssetCategory");
StringTableEntry assetAutoUnloadField = StringTable->insert("AssetAutoUnload");
StringTableEntry assetInternalField = StringTable->insert("AssetInternal");
StringTableEntry assetPrivateField = StringTable->insert("AssetPrivate");
//-----------------------------------------------------------------------------
AssetBase::AssetBase() :
mAcquireReferenceCount(0),
mpOwningAssetManager(NULL),
mAssetInitialized(false)
{
// Generate an asset definition.
mpAssetDefinition = new AssetDefinition();
}
//-----------------------------------------------------------------------------
AssetBase::~AssetBase()
{
// If the asset manager does not own the asset then we own the
// asset definition so delete it.
if (!getOwned())
delete mpAssetDefinition;
}
//-----------------------------------------------------------------------------
void AssetBase::initPersistFields()
{
// Call parent.
Parent::initPersistFields();
// Asset configuration.
addProtectedField(assetNameField, TypeString, 0, &setAssetName, &getAssetName, &writeAssetName, "The name of the asset. The is not a unique identification like an asset Id.");
addProtectedField(assetDescriptionField, TypeString, 0, &setAssetDescription, &getAssetDescription, &writeAssetDescription, "The simple description of the asset contents.");
addProtectedField(assetCategoryField, TypeString, 0, &setAssetCategory, &getAssetCategory, &writeAssetCategory, "An arbitrary category that can be used to categorized assets.");
addProtectedField(assetAutoUnloadField, TypeBool, 0, &setAssetAutoUnload, &getAssetAutoUnload, &writeAssetAutoUnload, "Whether the asset is automatically unloaded when an asset is released and has no other acquisitions or not.");
addProtectedField(assetInternalField, TypeBool, 0, &setAssetInternal, &getAssetInternal, &writeAssetInternal, "Whether the asset is used internally only or not.");
addProtectedField(assetPrivateField, TypeBool, 0, &defaultProtectedNotSetFn, &getAssetPrivate, &defaultProtectedNotWriteFn, "Whether the asset is private or not.");
}
//------------------------------------------------------------------------------
void AssetBase::copyTo(SimObject* object)
{
// Call to parent.
Parent::copyTo(object);
// Cast to asset.
AssetBase* pAsset = static_cast<AssetBase*>(object);
// Sanity!
AssertFatal(pAsset != NULL, "AssetBase::copyTo() - Object is not the correct type.");
// Copy state.
pAsset->setAssetName(getAssetName());
pAsset->setAssetDescription(getAssetDescription());
pAsset->setAssetCategory(getAssetCategory());
pAsset->setAssetAutoUnload(getAssetAutoUnload());
pAsset->setAssetInternal(getAssetInternal());
}
//-----------------------------------------------------------------------------
void AssetBase::setAssetDescription(const char* pAssetDescription)
{
// Fetch asset description.
StringTableEntry assetDescription = StringTable->insert(pAssetDescription);
// Ignore no change.
if (mpAssetDefinition->mAssetDescription == assetDescription)
return;
// Update.
mpAssetDefinition->mAssetDescription = assetDescription;
// Refresh the asset.
refreshAsset();
}
//-----------------------------------------------------------------------------
void AssetBase::setAssetCategory(const char* pAssetCategory)
{
// Fetch asset category.
StringTableEntry assetCategory = StringTable->insert(pAssetCategory);
// Ignore no change.
if (mpAssetDefinition->mAssetCategory == assetCategory)
return;
// Update.
mpAssetDefinition->mAssetCategory = assetCategory;
// Refresh the asset.
refreshAsset();
}
//-----------------------------------------------------------------------------
void AssetBase::setAssetAutoUnload(const bool autoUnload)
{
// Ignore no change.
if (mpAssetDefinition->mAssetAutoUnload == autoUnload)
return;
// Update.
mpAssetDefinition->mAssetAutoUnload = autoUnload;
// Refresh the asset.
refreshAsset();
}
//-----------------------------------------------------------------------------
void AssetBase::setAssetInternal(const bool assetInternal)
{
// Ignore no change,
if (mpAssetDefinition->mAssetInternal == assetInternal)
return;
// Update.
mpAssetDefinition->mAssetInternal = assetInternal;
// Refresh the asset.
refreshAsset();
}
//-----------------------------------------------------------------------------
StringTableEntry AssetBase::expandAssetFilePath(const char* pAssetFilePath) const
{
// Debug Profiling.
PROFILE_SCOPE(AssetBase_ExpandAssetFilePath);
// Sanity!
AssertFatal(pAssetFilePath != NULL, "Cannot expand a NULL asset path.");
// Fetch asset file-path length.
const U32 assetFilePathLength = dStrlen(pAssetFilePath);
// Are there any characters in the path?
if (assetFilePathLength == 0)
{
// No, so return empty.
return StringTable->EmptyString();
}
// Fetch the asset base-path hint.
StringTableEntry assetBasePathHint;
if (getOwned() && !getAssetPrivate())
{
assetBasePathHint = mpOwningAssetManager->getAssetPath(getAssetId());
}
else
{
assetBasePathHint = NULL;
}
// Expand the path with the asset base-path hint.
char assetFilePathBuffer[1024];
Con::expandPath(assetFilePathBuffer, sizeof(assetFilePathBuffer), pAssetFilePath, assetBasePathHint);
return StringTable->insert(assetFilePathBuffer);
}
//-----------------------------------------------------------------------------
StringTableEntry AssetBase::collapseAssetFilePath(const char* pAssetFilePath) const
{
// Debug Profiling.
PROFILE_SCOPE(AssetBase_CollapseAssetFilePath);
// Sanity!
AssertFatal(pAssetFilePath != NULL, "Cannot collapse a NULL asset path.");
// Fetch asset file-path length.
const U32 assetFilePathLength = dStrlen(pAssetFilePath);
// Are there any characters in the path?
if (assetFilePathLength == 0)
{
// No, so return empty.
return StringTable->EmptyString();
}
char assetFilePathBuffer[1024];
// Is the asset not owned or private?
if (!getOwned() || getAssetPrivate())
{
// Yes, so we can only collapse the path using the platform layer.
Con::collapsePath(assetFilePathBuffer, sizeof(assetFilePathBuffer), pAssetFilePath);
return StringTable->insert(assetFilePathBuffer);
}
// Fetch asset base-path.
StringTableEntry assetBasePath = mpOwningAssetManager->getAssetPath(getAssetId());
// Is the asset file-path location within the asset base-path?
if (Con::isBasePath(pAssetFilePath, assetBasePath))
{
// Yes, so fetch path relative to the asset base-path.
StringTableEntry relativePath = Platform::makeRelativePathName(pAssetFilePath, assetBasePath);
// Format the collapsed path.
dSprintf(assetFilePathBuffer, sizeof(assetFilePathBuffer), "%s", relativePath);
}
else
{
// No, so we can collapse the path using the platform layer.
Con::collapsePath(assetFilePathBuffer, sizeof(assetFilePathBuffer), pAssetFilePath);
}
return StringTable->insert(assetFilePathBuffer);
}
//-----------------------------------------------------------------------------
void AssetBase::refreshAsset(void)
{
// Debug Profiling.
PROFILE_SCOPE(AssetBase_RefreshAsset);
// Finish if asset is not owned or is not initialized.
if (mpOwningAssetManager == NULL || !mAssetInitialized)
return;
// Yes, so refresh the asset via the asset manager.
mpOwningAssetManager->refreshAsset(getAssetId());
}
//-----------------------------------------------------------------------------
void AssetBase::acquireAssetReference(void)
{
// Acquired the acquired reference count.
if (mpOwningAssetManager != NULL)
mpOwningAssetManager->acquireAcquiredReferenceCount();
mAcquireReferenceCount++;
}
//-----------------------------------------------------------------------------
bool AssetBase::releaseAssetReference(void)
{
// Are there any acquisition references?
if (mAcquireReferenceCount == 0)
{
// Return "unload" unless auto unload is off.
return mpAssetDefinition->mAssetAutoUnload;
}
// Release the acquired reference count.
if (mpOwningAssetManager != NULL)
mpOwningAssetManager->releaseAcquiredReferenceCount();
// Release reference.
mAcquireReferenceCount--;
// Are there any acquisition references?
if (mAcquireReferenceCount == 0)
{
// No, so return "unload" unless auto unload is off.
return mpAssetDefinition->mAssetAutoUnload;
}
// Return "don't unload".
return false;
}
//-----------------------------------------------------------------------------
void AssetBase::setOwned(AssetManager* pAssetManager, AssetDefinition* pAssetDefinition)
{
// Debug Profiling.
PROFILE_SCOPE(AssetBase_setOwned);
// Sanity!
AssertFatal(pAssetManager != NULL, "Cannot set asset ownership with NULL asset manager.");
AssertFatal(mpOwningAssetManager == NULL, "Cannot set asset ownership if it is already owned.");
AssertFatal(pAssetDefinition != NULL, "Cannot set asset ownership with a NULL asset definition.");
AssertFatal(mpAssetDefinition != NULL, "Asset ownership assigned but has a NULL asset definition.");
AssertFatal(mpAssetDefinition->mAssetName == pAssetDefinition->mAssetName, "Asset ownership differs by asset name.");
AssertFatal(mpAssetDefinition->mAssetDescription == pAssetDefinition->mAssetDescription, "Asset ownership differs by asset description.");
AssertFatal(mpAssetDefinition->mAssetCategory == pAssetDefinition->mAssetCategory, "Asset ownership differs by asset category.");
AssertFatal(mpAssetDefinition->mAssetAutoUnload == pAssetDefinition->mAssetAutoUnload, "Asset ownership differs by asset auto-unload flag.");
AssertFatal(mpAssetDefinition->mAssetInternal == pAssetDefinition->mAssetInternal, "Asset ownership differs by asset internal flag.");
// Transfer asset definition ownership state.
delete mpAssetDefinition;
mpAssetDefinition = pAssetDefinition;
// Flag as owned.
// NOTE: This must be done prior to initializing the asset so any initialization can assume ownership.
mpOwningAssetManager = pAssetManager;
// Initialize the asset.
initializeAsset();
// Flag asset as initialized.
mAssetInitialized = true;
}

View file

@ -0,0 +1,145 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _ASSET_BASE_H_
#define _ASSET_BASE_H_
#ifndef _ASSET_DEFINITION_H_
#include "assetDefinition.h"
#endif
#ifndef _STRINGUNIT_H_
#include "string/stringUnit.h"
#endif
#ifndef _ASSET_FIELD_TYPES_H_
#include "assets/assetFieldTypes.h"
#endif
//-----------------------------------------------------------------------------
class AssetManager;
//-----------------------------------------------------------------------------
extern StringTableEntry assetNameField;
extern StringTableEntry assetDescriptionField;
extern StringTableEntry assetCategoryField;
extern StringTableEntry assetInternalField;
extern StringTableEntry assetPrivateField;
extern StringTableEntry assetAutoUnloadField;
//#define ASSET_BASE_ASSETNAME_FIELD "AssetName"
//#define ASSET_BASE_ASSETDESCRIPTION_FIELD "AssetDescription"
//#define ASSET_BASE_ASSETCATEGORY_FIELD "AssetCategory"
//#define ASSET_BASE_ASSETINTERNAL_FIELD "AssetInternal"
//#define ASSET_BASE_ASSETPRIVATE_FIELD "AssetPrivate"
//#define ASSET_BASE_AUTOUNLOAD_FIELD "AssetAutoUnload"
//-----------------------------------------------------------------------------
class AssetBase : public SimObject
{
friend class AssetManager;
typedef SimObject Parent;
AssetManager* mpOwningAssetManager;
bool mAssetInitialized;
AssetDefinition* mpAssetDefinition;
U32 mAcquireReferenceCount;
public:
AssetBase();
virtual ~AssetBase();
/// Engine.
static void initPersistFields();
virtual void copyTo(SimObject* object);
/// Asset configuration.
inline void setAssetName(const char* pAssetName) { if (mpOwningAssetManager == NULL) mpAssetDefinition->mAssetName = StringTable->insert(pAssetName); }
inline StringTableEntry getAssetName(void) const { return mpAssetDefinition->mAssetName; }
void setAssetDescription(const char* pAssetDescription);
inline StringTableEntry getAssetDescription(void) const { return mpAssetDefinition->mAssetDescription; }
void setAssetCategory(const char* pAssetCategory);
inline StringTableEntry getAssetCategory(void) const { return mpAssetDefinition->mAssetCategory; }
void setAssetAutoUnload(const bool autoUnload);
inline bool getAssetAutoUnload(void) const { return mpAssetDefinition->mAssetAutoUnload; }
void setAssetInternal(const bool assetInternal);
inline bool getAssetInternal(void) const { return mpAssetDefinition->mAssetInternal; }
inline bool getAssetPrivate(void) const { return mpAssetDefinition->mAssetPrivate; }
inline StringTableEntry getAssetType(void) const { return mpAssetDefinition->mAssetType; }
inline S32 getAcquiredReferenceCount(void) const { return mAcquireReferenceCount; }
inline bool getOwned(void) const { return mpOwningAssetManager != NULL; }
// Asset Id is only available once registered with the asset manager.
inline StringTableEntry getAssetId(void) const { return mpAssetDefinition->mAssetId; }
/// Expanding/Collapsing asset paths is only available once registered with the asset manager.
StringTableEntry expandAssetFilePath(const char* pAssetFilePath) const;
StringTableEntry collapseAssetFilePath(const char* pAssetFilePath) const;
virtual bool isAssetValid(void) const { return true; }
void refreshAsset(void);
/// Declare Console Object.
DECLARE_CONOBJECT(AssetBase);
protected:
virtual void initializeAsset(void) {}
virtual void onAssetRefresh(void) {}
protected:
static bool setAssetName(void *obj, const char *array, const char *data) { static_cast<AssetBase*>(obj)->setAssetName(data); return false; }
static const char* getAssetName(void* obj, const char* data) { return static_cast<AssetBase*>(obj)->getAssetName(); }
static bool writeAssetName(void* obj, StringTableEntry pFieldName) { return static_cast<AssetBase*>(obj)->getAssetName() != StringTable->EmptyString(); }
static bool setAssetDescription(void *obj, const char *array, const char *data) { static_cast<AssetBase*>(obj)->setAssetDescription(data); return false; }
static const char* getAssetDescription(void* obj, const char* data) { return static_cast<AssetBase*>(obj)->getAssetDescription(); }
static bool writeAssetDescription(void* obj, StringTableEntry pFieldName) { return static_cast<AssetBase*>(obj)->getAssetDescription() != StringTable->EmptyString(); }
static bool setAssetCategory(void *obj, const char *array, const char *data) { static_cast<AssetBase*>(obj)->setAssetCategory(data); return false; }
static const char* getAssetCategory(void* obj, const char* data) { return static_cast<AssetBase*>(obj)->getAssetCategory(); }
static bool writeAssetCategory(void* obj, StringTableEntry pFieldName) { return static_cast<AssetBase*>(obj)->getAssetCategory() != StringTable->EmptyString(); }
static bool setAssetAutoUnload(void *obj, const char *array, const char *data) { static_cast<AssetBase*>(obj)->setAssetAutoUnload(dAtob(data)); return false; }
static const char* getAssetAutoUnload(void* obj, const char* data) { return Con::getBoolArg(static_cast<AssetBase*>(obj)->getAssetAutoUnload()); }
static bool writeAssetAutoUnload(void* obj, StringTableEntry pFieldName) { return static_cast<AssetBase*>(obj)->getAssetAutoUnload() == false; }
static bool setAssetInternal(void *obj, const char *array, const char *data) { static_cast<AssetBase*>(obj)->setAssetInternal(dAtob(data)); return false; }
static const char* getAssetInternal(void* obj, const char* data) { return Con::getBoolArg(static_cast<AssetBase*>(obj)->getAssetInternal()); }
static bool writeAssetInternal(void* obj, StringTableEntry pFieldName) { return static_cast<AssetBase*>(obj)->getAssetInternal() == true; }
static const char* getAssetPrivate(void* obj, const char* data) { return Con::getBoolArg(static_cast<AssetBase*>(obj)->getAssetPrivate()); }
private:
void acquireAssetReference(void);
bool releaseAssetReference(void);
/// Set asset manager ownership.
void setOwned(AssetManager* pAssetManager, AssetDefinition* pAssetDefinition);
};
#endif // _ASSET_BASE_H_

View file

@ -0,0 +1,41 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "console/engineAPI.h"
#include "assetBase.h"
#include "assetManager.h"
DefineEngineMethod(AssetBase, refreshAsset, void, (), ,
"Refresh the asset.\n"
"@return No return value.\n")
{
object->refreshAsset();
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetBase, getAssetId, String, (), ,
"Gets the assets' Asset Id. This is only available if the asset was acquired from the asset manager.\n"
"@return The assets' Asset Id.\n")
{
return object->getAssetId();
}

View file

@ -0,0 +1,102 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _ASSET_DEFINITION_H_
#define _ASSET_DEFINITION_H_
#ifndef _STRINGTABLE_H_
#include "core/stringTable.h"
#endif
#ifndef _STRINGUNIT_H_
#include "core/strings/stringUnit.h"
#endif
#ifndef _SIM_H_
#include "console/sim.h"
#endif
#ifndef _SIMOBJECT_H_
#include "console/simObject.h"
#endif
#ifndef _CONSOLEOBJECT_H_
#include "console/consoleObject.h"
#endif
//-----------------------------------------------------------------------------
class AssetBase;
class ModuleDefinition;
//-----------------------------------------------------------------------------
struct AssetDefinition
{
public:
AssetDefinition() { reset(); }
virtual ~AssetDefinition() {}
virtual void reset( void )
{
mAssetLoading = false;
mpModuleDefinition = NULL;
mpAssetBase = NULL;
mAssetBaseFilePath = StringTable->EmptyString();
mAssetId = StringTable->EmptyString();
mAssetLoadedCount = 0;
mAssetUnloadedCount = 0;
mAssetRefreshEnable = true;
mAssetLooseFiles.clear();
// Reset persisted state.
mAssetName = StringTable->EmptyString();
mAssetDescription = StringTable->EmptyString();
mAssetAutoUnload = true;
mAssetInternal = false;
mAssetPrivate = false;
mAssetType = StringTable->EmptyString();
mAssetCategory = StringTable->EmptyString();
}
ModuleDefinition* mpModuleDefinition;
AssetBase* mpAssetBase;
StringTableEntry mAssetBaseFilePath;
StringTableEntry mAssetId;
U32 mAssetLoadedCount;
U32 mAssetUnloadedCount;
bool mAssetRefreshEnable;
Vector<StringTableEntry> mAssetLooseFiles;
/// Persisted state.
StringTableEntry mAssetName;
StringTableEntry mAssetDescription;
bool mAssetAutoUnload;
bool mAssetInternal;
bool mAssetPrivate;
bool mAssetLoading;
StringTableEntry mAssetType;
StringTableEntry mAssetCategory;
};
#endif // _ASSET_DEFINITION_H_

View file

@ -0,0 +1,114 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _ASSET_FIELD_TYPES_H_
#include "assetFieldTypes.h"
#endif
#ifndef _ASSET_PTR_H_
#include "assetPtr.h"
#endif
#ifndef _ASSET_BASE_H_
#include "assetBase.h"
#endif
/*#ifndef _AUDIO_ASSET_H_
#include "audio/AudioAsset.h"
#endif*/
#ifndef _STRINGUNIT_H_
#include "string/stringUnit.h"
#endif
//-----------------------------------------------------------------------------
StringTableEntry assetLooseIdSignature = StringTable->insert( ASSET_ID_SIGNATURE );
StringTableEntry assetLooseFileSignature = StringTable->insert( ASSET_LOOSEFILE_SIGNATURE );
//-----------------------------------------------------------------------------
ConsoleType( assetLooseFilePath, TypeAssetLooseFilePath, String, ASSET_LOOSE_FILE_FIELD_PREFIX )
ConsoleType(assetIdString, TypeAssetId, String, ASSET_ID_FIELD_PREFIX)
//-----------------------------------------------------------------------------
ConsoleGetType( TypeAssetLooseFilePath )
{
// Fetch asset loose file-path.
return *((StringTableEntry*)dptr);
}
//-----------------------------------------------------------------------------
ConsoleSetType( TypeAssetLooseFilePath )
{
// Was a single argument specified?
if( argc == 1 )
{
// Yes, so fetch field value.
const char* pFieldValue = argv[0];
// Fetch asset loose file-path.
StringTableEntry* assetLooseFilePath = (StringTableEntry*)(dptr);
// Update asset loose file-path value.
*assetLooseFilePath = StringTable->insert(pFieldValue);
return;
}
// Warn.
Con::warnf( "(TypeAssetLooseFilePath) - Cannot set multiple args to a single asset loose-file." );
}
//-----------------------------------------------------------------------------
ConsoleGetType( TypeAssetId )
{
// Fetch asset Id.
return *((StringTableEntry*)dptr);
}
//-----------------------------------------------------------------------------
ConsoleSetType( TypeAssetId )
{
// Was a single argument specified?
if( argc == 1 )
{
// Yes, so fetch field value.
const char* pFieldValue = argv[0];
// Fetch asset Id.
StringTableEntry* assetId = (StringTableEntry*)(dptr);
// Update asset value.
*assetId = StringTable->insert(pFieldValue);
return;
}
// Warn.
Con::warnf( "(TypeAssetId) - Cannot set multiple args to a single asset." );
}

View file

@ -0,0 +1,56 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _ASSET_FIELD_TYPES_H_
#define _ASSET_FIELD_TYPES_H_
#ifndef _CONSOLE_BASE_TYPE_H_
#include "console/consoleTypes.h"
#endif
//-----------------------------------------------------------------------------
DefineConsoleType( TypeAssetId, S32 )
DefineConsoleType( TypeAssetLooseFilePath, String )
//-----------------------------------------------------------------------------
/// Asset scope.
#define ASSET_SCOPE_TOKEN ":"
/// Asset assignment.
#define ASSET_ASSIGNMENT_TOKEN "="
/// Asset Id.
#define ASSET_ID_SIGNATURE "@asset"
#define ASSET_ID_FIELD_PREFIX "@asset="
/// Asset loose file.
#define ASSET_LOOSEFILE_SIGNATURE "@assetFile"
#define ASSET_LOOSE_FILE_FIELD_PREFIX "@assetFile="
//-----------------------------------------------------------------------------
extern StringTableEntry assetLooseIdSignature;
extern StringTableEntry assetLooseFileSignature;
#endif // _ASSET_FIELD_TYPES_H_

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,395 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _ASSET_MANAGER_H_
#define _ASSET_MANAGER_H_
#ifndef _SIMBASE_H_
#include "console/sim.h"
#endif
#ifndef _TAML_H_
#include "persistence/taml/taml.h"
#endif
#ifndef _MODULE_DEFINITION_H
#include "module/moduleDefinition.h"
#endif
#ifndef _MODULE_CALLBACKS_H_
#include "module/moduleCallbacks.h"
#endif
#ifndef _ASSET_BASE_H_
#include "assets/assetBase.h"
#endif
#ifndef _ASSET_DEFINITION_H_
#include "assets/assetDefinition.h"
#endif
#ifndef _ASSET_TAGS_MANIFEST_H_
#include "assets/assetTagsManifest.h"
#endif
#ifndef _ASSET_QUERY_H_
#include "assets/assetQuery.h"
#endif
#ifndef _ASSET_FIELD_TYPES_H_
#include "assets/assetFieldTypes.h"
#endif
// Debug Profiling.
#include "platform/profiler.h"
//-----------------------------------------------------------------------------
class AssetPtrCallback;
class AssetPtrBase;
//-----------------------------------------------------------------------------
class AssetManager : public SimObject, public ModuleCallbacks
{
private:
typedef SimObject Parent;
typedef StringTableEntry typeAssetId;
typedef StringTableEntry typeAssetName;
typedef StringTableEntry typeReferenceFilePath;
typedef HashMap<typeAssetId, AssetDefinition*> typeDeclaredAssetsHash;
typedef HashTable<typeAssetId, typeReferenceFilePath> typeReferencedAssetsHash;
typedef HashTable<typeAssetId, typeAssetId> typeAssetDependsOnHash;
typedef HashTable<typeAssetId, typeAssetId> typeAssetIsDependedOnHash;
typedef HashMap<AssetPtrBase*, AssetPtrCallback*> typeAssetPtrRefreshHash;
/// Declared assets.
typeDeclaredAssetsHash mDeclaredAssets;
/// Referenced assets.
typeReferencedAssetsHash mReferencedAssets;
/// Asset dependencies.
typeAssetDependsOnHash mAssetDependsOn;
typeAssetIsDependedOnHash mAssetIsDependedOn;
/// Asset tags.
SimObjectPtr<AssetTagsManifest> mAssetTagsManifest;
SimObjectPtr<ModuleDefinition> mAssetTagsModuleDefinition;
/// Asset pointer refresh notifications.
typeAssetPtrRefreshHash mAssetPtrRefreshNotifications;
/// Miscellaneous.
bool mEchoInfo;
bool mIgnoreAutoUnload;
U32 mLoadedInternalAssetsCount;
U32 mLoadedExternalAssetsCount;
U32 mLoadedPrivateAssetsCount;
U32 mAcquiredReferenceCount;
U32 mMaxLoadedInternalAssetsCount;
U32 mMaxLoadedExternalAssetsCount;
U32 mMaxLoadedPrivateAssetsCount;
Taml mTaml;
public:
AssetManager();
virtual ~AssetManager() {}
/// SimObject overrides
virtual bool onAdd();
virtual void onRemove();
static void initPersistFields();
/// Declared assets.
bool addModuleDeclaredAssets( ModuleDefinition* pModuleDefinition );
bool addDeclaredAsset( ModuleDefinition* pModuleDefinition, const char* pAssetFilePath );
StringTableEntry addPrivateAsset( AssetBase* pAssetBase );
bool removeDeclaredAssets( ModuleDefinition* pModuleDefinition );
bool removeDeclaredAsset( const char* pAssetId );
bool renameDeclaredAsset( const char* pAssetIdFrom, const char* pAssetIdTo );
StringTableEntry getAssetName( const char* pAssetId );
StringTableEntry getAssetDescription( const char* pAssetId );
StringTableEntry getAssetCategory( const char* pAssetId );
StringTableEntry getAssetType( const char* pAssetId );
StringTableEntry getAssetFilePath( const char* pAssetId );
StringTableEntry getAssetPath( const char* pAssetId );
ModuleDefinition* getAssetModuleDefinition( const char* pAssetId );
bool isAssetInternal( const char* pAssetId );
bool isAssetPrivate( const char* pAssetId );
bool isAssetAutoUnload( const char* pAssetId );
bool isAssetLoaded( const char* pAssetId );
bool isDeclaredAsset( const char* pAssetId );
bool doesAssetDependOn( const char* pAssetId, const char* pDependsOnAssetId );
bool isAssetDependedOn( const char* pAssetId, const char* pDependedOnByAssetId );
/// Referenced assets.
bool compileReferencedAssets( ModuleDefinition* pModuleDefinition );
bool isReferencedAsset( const char* pAssetId );
bool renameReferencedAsset( const char* pAssetIdFrom, const char* pAssetIdTo );
/// Public asset acquisition.
template<typename T> T* acquireAsset( const char* pAssetId )
{
// Sanity!
AssertFatal( pAssetId != NULL, "Cannot acquire NULL asset Id." );
// Is this an empty asset Id?
if ( *pAssetId == 0 )
{
// Yes, so return nothing.
return NULL;
}
// Find asset.
AssetDefinition* pAssetDefinition = findAsset( pAssetId );
// Did we find the asset?
if ( pAssetDefinition == NULL )
{
// No, so warn.
Con::warnf( "Asset Manager: Failed to acquire asset Id '%s' as it does not exist.", pAssetId );
return NULL;
}
// Is asset loading?
if ( pAssetDefinition->mAssetLoading == true )
{
// Yes, so we've got a circular loop which we cannot resolve!
Con::warnf( "Asset Manager: Failed to acquire asset Id '%s' as loading it involves a cyclic dependency on itself which cannot be resolved.", pAssetId );
return NULL;
}
// Info.
if ( mEchoInfo )
{
Con::printSeparator();
Con::printf( "Asset Manager: Started acquiring Asset Id '%s'...", pAssetId );
}
// Is the asset already loaded?
if ( pAssetDefinition->mpAssetBase == NULL )
{
// No, so info
if ( mEchoInfo )
{
// Fetch asset Id.
StringTableEntry assetId = StringTable->insert( pAssetId );
// Find any asset dependencies.
typeAssetDependsOnHash::Iterator assetDependenciesItr = mAssetDependsOn.find( assetId );
// Does the asset have any dependencies?
if ( assetDependenciesItr != mAssetDependsOn.end() )
{
// Yes, so show all dependency assets.
Con::printf( "Asset Manager: > Found dependencies:" );
// Iterate all dependencies.
while( assetDependenciesItr != mAssetDependsOn.end() && assetDependenciesItr->key == assetId )
{
// Info.
Con::printf( "Asset Manager: > Asset Id '%s'", assetDependenciesItr->value );
// Next dependency.
assetDependenciesItr++;
}
}
}
// Flag asset as loading.
pAssetDefinition->mAssetLoading = true;
// Generate primary asset.
pAssetDefinition->mpAssetBase = mTaml.read<T>( pAssetDefinition->mAssetBaseFilePath );
// Flag asset as finished loading.
pAssetDefinition->mAssetLoading = false;
// Did we generate the asset?
if ( pAssetDefinition->mpAssetBase == NULL )
{
// No, so warn.
Con::warnf( "Asset Manager: > Failed to acquire asset Id '%s' as loading the asset file failed to return the asset or the correct asset type: '%s'.",
pAssetId, pAssetDefinition->mAssetBaseFilePath );
return NULL;
}
// Increase loaded count.
pAssetDefinition->mAssetLoadedCount++;
// Info.
if ( mEchoInfo )
{
Con::printf( "Asset Manager: > Loading asset into memory as object Id '%d' from file '%s'.",
pAssetDefinition->mpAssetBase->getId(), pAssetDefinition->mAssetBaseFilePath );
}
// Set ownership by asset manager.
pAssetDefinition->mpAssetBase->setOwned( this, pAssetDefinition );
// Is the asset internal?
if ( pAssetDefinition->mAssetInternal )
{
// Yes, so increase internal loaded asset count.
if ( ++mLoadedInternalAssetsCount > mMaxLoadedInternalAssetsCount )
mMaxLoadedInternalAssetsCount = mLoadedInternalAssetsCount;
}
else
{
// No, so increase external loaded assets count.
if ( ++mLoadedExternalAssetsCount > mMaxLoadedExternalAssetsCount )
mMaxLoadedExternalAssetsCount = mLoadedExternalAssetsCount;
}
}
else if ( pAssetDefinition->mpAssetBase->getAcquiredReferenceCount() == 0 )
{
// Info.
if ( mEchoInfo )
{
Con::printf( "Asset Manager: > Acquiring from idle state." );
}
}
// Set acquired asset.
T* pAcquiredAsset = dynamic_cast<T*>( (AssetBase*)pAssetDefinition->mpAssetBase );
// Is asset the correct type?
if ( pAcquiredAsset == NULL )
{
// No, so warn.
Con::warnf( "Asset Manager: > Failed to acquire asset Id '%s' as it was not the required asset type: '%s'.", pAssetId, pAssetDefinition->mAssetBaseFilePath );
return NULL;
}
// Acquire asset reference.
pAcquiredAsset->acquireAssetReference();
// Info.
if ( mEchoInfo )
{
Con::printf( "Asset Manager: > Finished acquiring asset. Reference count now '%d'.", pAssetDefinition->mpAssetBase->getAcquiredReferenceCount() );
Con::printSeparator();
}
return pAcquiredAsset;
}
/// Private asset acquisition.
template<typename T> T* acquireAsPrivateAsset( const char* pAssetId )
{
// Acquire the asset normally.
T* pAsset = acquireAsset<T>( pAssetId );
// Finish if the asset was not acquired.
if ( pAsset == NULL )
return NULL;
// Clone the asset.
T* pAssetClone = dynamic_cast<T*>( pAsset->clone() );
// Sanity!
AssertFatal( pAssetClone != NULL, "acquireAsPrivateAsset() - Failed to clone asset type." );
// Release the public asset.
releaseAsset( pAssetId );
// Add as a private asset.
addPrivateAsset( pAssetClone );
return pAssetClone;
}
bool releaseAsset( const char* pAssetId );
void purgeAssets( void );
/// Asset deletion.
bool deleteAsset( const char* pAssetId, const bool deleteLooseFiles, const bool deleteDependencies );
// Asset refresh notification.
bool refreshAsset( const char* pAssetId );
void refreshAllAssets( const bool includeUnloaded = false );
void registerAssetPtrRefreshNotify( AssetPtrBase* pAssetPtrBase, AssetPtrCallback* pCallback );
void unregisterAssetPtrRefreshNotify( AssetPtrBase* pAssetPtrBase );
/// Asset tags.
bool loadAssetTags( ModuleDefinition* pModuleDefinition );
bool saveAssetTags( void );
bool restoreAssetTags( void );
inline AssetTagsManifest* getAssetTags( void ) const { return mAssetTagsManifest; }
/// Info.
inline U32 getDeclaredAssetCount( void ) const { return (U32)mDeclaredAssets.size(); }
inline U32 getReferencedAssetCount( void ) const { return (U32)mReferencedAssets.size(); }
inline U32 getLoadedInternalAssetCount( void ) const { return mLoadedInternalAssetsCount; }
inline U32 getLoadedExternalAssetCount( void ) const { return mLoadedExternalAssetsCount; }
inline U32 getLoadedPrivateAssetCount( void ) const { return mLoadedPrivateAssetsCount; }
inline U32 getMaxLoadedInternalAssetCount( void ) const { return mMaxLoadedInternalAssetsCount; }
inline U32 getMaxLoadedExternalAssetCount( void ) const { return mMaxLoadedExternalAssetsCount; }
inline U32 getMaxLoadedPrivateAssetCount( void ) const { return mMaxLoadedPrivateAssetsCount; }
void dumpDeclaredAssets( void ) const;
/// Total acquired asset references.
inline void acquireAcquiredReferenceCount( void ) { mAcquiredReferenceCount++; }
inline void releaseAcquiredReferenceCount( void ) { AssertFatal( mAcquiredReferenceCount != 0, "AssetManager: Invalid acquired reference count." ); mAcquiredReferenceCount--; }
inline U32 getAcquiredReferenceCount( void ) const { return mAcquiredReferenceCount; }
/// Asset queries.
S32 findAllAssets( AssetQuery* pAssetQuery, const bool ignoreInternal = true, const bool ignorePrivate = true );
S32 findAssetName( AssetQuery* pAssetQuery, const char* pAssetName, const bool partialName = false );
S32 findAssetCategory( AssetQuery* pAssetQuery, const char* pAssetCategory, const bool assetQueryAsSource = false );
S32 findAssetAutoUnload( AssetQuery* pAssetQuery, const bool assetAutoUnload, const bool assetQueryAsSource = false );
S32 findAssetInternal( AssetQuery* pAssetQuery, const bool assetInternal, const bool assetQueryAsSource = false );
S32 findAssetPrivate( AssetQuery* pAssetQuery, const bool assetPrivate, const bool assetQueryAsSource = false );
S32 findAssetType( AssetQuery* pAssetQuery, const char* pAssetType, const bool assetQueryAsSource = false );
S32 findAssetDependsOn( AssetQuery* pAssetQuery, const char* pAssetId );
S32 findAssetIsDependedOn( AssetQuery* pAssetQuery, const char* pAssetId );
S32 findInvalidAssetReferences( AssetQuery* pAssetQuery );
S32 findTaggedAssets( AssetQuery* pAssetQuery, const char* pAssetTagNames, const bool assetQueryAsSource = false );
S32 findAssetLooseFile( AssetQuery* pAssetQuery, const char* pLooseFile, const bool assetQueryAsSource = false );
/// Declare Console Object.
DECLARE_CONOBJECT( AssetManager );
private:
bool scanDeclaredAssets( const char* pPath, const char* pExtension, const bool recurse, ModuleDefinition* pModuleDefinition );
bool scanReferencedAssets( const char* pPath, const char* pExtension, const bool recurse );
AssetDefinition* findAsset( const char* pAssetId );
void addReferencedAsset( StringTableEntry assetId, StringTableEntry referenceFilePath );
void renameAssetReferences( StringTableEntry assetIdFrom, StringTableEntry assetIdTo );
void removeAssetReferences( StringTableEntry assetId );
void renameAssetDependencies( StringTableEntry assetIdFrom, StringTableEntry assetIdTo );
void removeAssetDependencies( const char* pAssetId );
void removeAssetLooseFiles( const char* pAssetId );
void unloadAsset( AssetDefinition* pAssetDefinition );
/// Module callbacks.
virtual void onModulePreLoad( ModuleDefinition* pModuleDefinition );
virtual void onModulePreUnload( ModuleDefinition* pModuleDefinition );
virtual void onModulePostUnload( ModuleDefinition* pModuleDefinition );
};
//-----------------------------------------------------------------------------
extern AssetManager AssetDatabase;
#endif // _ASSET_MANAGER_H_

View file

@ -0,0 +1,811 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "console/engineAPI.h"
#include "assetBase.h"
#include "assetManager.h"
#include "module/moduleDefinition.h"
#include "console/sim.h"
DefineEngineMethod(AssetManager, compileReferencedAssets, bool, (const char* moduleDefinition), (""),
"Compile the referenced assets determined by the specified module definition.\n"
"@param moduleDefinition The module definition specifies the asset manifest.\n"
"@return Whether the compilation was successful or not.\n")
{
// Fetch module definition.
ModuleDefinition* pModuleDefinition;
Sim::findObject(moduleDefinition, pModuleDefinition);
// Did we find the module definition?
if ( pModuleDefinition == NULL )
{
// No, so warn.
Con::warnf("AssetManager::compileReferencedAssets() - Could not find the module definition '%s'.", moduleDefinition);
return false;
}
// Compile referenced assets.
return object->compileReferencedAssets( pModuleDefinition );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, addModuleDeclaredAssets, bool, (const char* moduleDefinition), (""),
"Add any the declared assets specified by the module definition.\n"
"@param moduleDefinition The module definition specifies the asset manifest.\n"
"@return Whether adding declared assets was successful or not.\n")
{
// Fetch module definition.
ModuleDefinition* pModuleDefinition;
Sim::findObject(moduleDefinition, pModuleDefinition);
// Did we find the module definition?
if ( pModuleDefinition == NULL )
{
// No, so warn.
Con::warnf("AssetManager::addDeclaredAssets() - Could not find the module definition '%s'.", moduleDefinition);
return false;
}
// Add module declared assets.
return object->addModuleDeclaredAssets( pModuleDefinition );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, addDeclaredAsset, bool, (const char* moduleDefinition, const char* assetFilePath), ("", ""),
"Add the specified asset against the specified module definition.\n"
"@param moduleDefinition The module definition that may contain declared assets.\n"
"@return Whether adding declared assets was successful or not.\n")
{
// Fetch module definition.
ModuleDefinition* pModuleDefinition;
Sim::findObject(moduleDefinition, pModuleDefinition);
// Did we find the module definition?
if ( pModuleDefinition == NULL )
{
// No, so warn.
Con::warnf("AssetManager::addDeclaredAsset() - Could not find the module definition '%s'.", moduleDefinition);
return false;
}
// Fetch asset file-path.
const char* pAssetFilePath = assetFilePath;
// Add declared asset.
return object->addDeclaredAsset( pModuleDefinition, pAssetFilePath );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, addPrivateAsset, String, (const char* assetObject), (""),
"Adds a private asset object.\n"
"@param assetObject The asset object to add as a private asset.\n"
"@return The allocated private asset Id.\n")
{
// Fetch asset.
AssetBase* pAssetBase;
Sim::findObject(assetObject, pAssetBase);
// Did we find the asset?
if ( pAssetBase == NULL )
{
// No, so warn.
Con::warnf("AssetManager::addPrivateAsset() - Could not find the asset '%s'.", assetObject);
return StringTable->EmptyString();
}
// Add private asset.
return object->addPrivateAsset( pAssetBase );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, removeDeclaredAssets, bool, (const char* moduleDefinition), (""),
"Remove any the declared assets specified by the module definition.\n"
"@param moduleDefinition The module definition that may contain declared assets.\n"
"@return Whether removing declared assets was successful or not.\n")
{
// Fetch module definition.
ModuleDefinition* pModuleDefinition;
Sim::findObject(moduleDefinition, pModuleDefinition);
// Did we find the module definition?
if ( pModuleDefinition == NULL )
{
// No, so warn.
Con::warnf("AssetManager::removeDeclaredAssets() - Could not find the module definition '%s'.", moduleDefinition);
return false;
}
// Remove declared assets.
return object->removeDeclaredAssets( pModuleDefinition );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, removeDeclaredAsset, bool, (const char* assetId), (""),
"Remove the specified declared asset Id.\n"
"@param assetId The selected asset Id.\n"
"@return Whether removing the declared asset was successful or not.\n")
{
// Remove the declared asset Id.
return object->removeDeclaredAsset(assetId);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, getAssetName, String, (const char* assetId), (""),
"Gets the asset name from the specified asset Id.\n"
"@param assetId The selected asset Id.\n"
"@return The asset name from the specified asset Id.\n")
{
return object->getAssetName(assetId);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, getAssetDescription, String, (const char* assetId), (""),
"Gets the asset description from the specified asset Id.\n"
"@param assetId The selected asset Id.\n"
"@return The asset description from the specified asset Id.\n")
{
return object->getAssetDescription(assetId);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, getAssetCategory, String, (const char* assetId), (""),
"Gets the asset category from the specified asset Id.\n"
"@param assetId The selected asset Id.\n"
"@return The asset category from the specified asset Id.\n")
{
return object->getAssetCategory(assetId);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, getAssetType, String, (const char* assetId), (""),
"Gets the asset type from the specified asset Id.\n"
"@param assetId The selected asset Id.\n"
"@return The asset type from the specified asset Id.\n")
{
return object->getAssetType(assetId);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, getAssetFilePath, String, (const char* assetId), (""),
"Gets the asset file-path from the specified asset Id.\n"
"@param assetId The selected asset Id.\n"
"@return The asset file - path from the specified asset Id.\n")
{
return object->getAssetFilePath(assetId);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, getAssetPath, String, (const char* assetId), (""),
"Gets the asset path (not including the asset file) from the specified asset Id.\n"
"@param assetId The selected asset Id.\n"
"@return The asset path(not including the asset file) from the specified asset Id.\n")
{
return object->getAssetPath(assetId);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, getAssetModule, String, (const char* assetId), (""),
"Gets the module definition where the the specified asset Id is located.\n"
"@param assetId The selected asset Id.\n"
"@return The module definition where the the specified asset Id is located.\n")
{
// Fetch module definition.
ModuleDefinition* pModuleDefinition = object->getAssetModuleDefinition(assetId);
return pModuleDefinition == NULL ? StringTable->EmptyString() : pModuleDefinition->getIdString();
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, isAssetInternal, bool, (const char* assetId), (""),
"Check whether the specified asset Id is internal or not.\n"
"@param assetId The selected asset Id.\n"
"@return Whether the specified asset Id is internal or not.\n")
{
return object->isAssetInternal(assetId);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, isAssetPrivate, bool, (const char* assetId), (""),
"Check whether the specified asset Id is private or not.\n"
"@param assetId The selected asset Id.\n"
"@return Whether the specified asset Id is private or not.\n")
{
return object->isAssetPrivate(assetId);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, isAssetAutoUnload, bool, (const char* assetId), (""),
"Check whether the specified asset Id is auto - unload or not.\n"
"@param assetId The selected asset Id.\n"
"@return Whether the specified asset Id is auto-unload or not.\n")
{
return object->isAssetAutoUnload(assetId);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, isAssetLoaded, bool, (const char* assetId), (""),
"Check whether the specified asset Id is loaded or not.\n"
"@param assetId The selected asset Id.\n"
"@return Whether the specified asset Id is loaded or not.\n")
{
return object->isAssetLoaded(assetId);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, isDeclaredAsset, bool, (const char* assetId), (""),
"Check whether the specified asset Id is declared or not.\n"
"@param assetId The selected asset Id.\n"
"@return Whether the specified asset Id is declared or not.\n")
{
return object->isDeclaredAsset(assetId);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, isReferencedAsset, bool, (const char* assetId), (""),
"Check whether the specified asset Id is referenced or not.\n"
"@param assetId The selected asset Id.\n"
"@return Whether the specified asset Id is referenced or not.\n")
{
return object->isReferencedAsset(assetId);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, renameDeclaredAsset, bool, (const char* assetIdFrom, const char* assetIdTo), ("", ""),
"Rename declared asset Id.\n"
"@param assetIdFrom The selected asset Id to rename from.\n"
"@param assetIdFrom The selected asset Id to rename to.\n"
"@return Whether the rename was successful or not.\n")
{
return object->renameDeclaredAsset(assetIdFrom, assetIdTo);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, renameReferencedAsset, bool, (const char* assetIdFrom, const char* assetIdTo), ("", ""),
"Rename referenced asset Id. \n"
"@param assetIdFrom The selected asset Id to rename from.\n"
"@param assetIdFrom The selected asset Id to rename to.\n"
"@return Whether the rename was successful or not.\n")
{
return object->renameReferencedAsset(assetIdFrom, assetIdTo);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, acquireAsset, String, (const char* assetId, bool asPrivate), ("", false),
"Acquire the specified asset Id.\n"
"You must release the asset once you're finish with it using 'releaseAsset'.\n"
"@param assetId The selected asset Id.\n"
"@param asPrivate Whether to acquire the asset Id as a private asset.\n"
"@return The acquired asset or NULL if not acquired.\n")
{
// Fetch asset Id.
const char* pAssetId = assetId;
// Reset asset reference.
AssetBase* pAssetBase = NULL;
// Acquire private asset?
if ( asPrivate )
{
// Acquire private asset.
pAssetBase = object->acquireAsPrivateAsset<AssetBase>( pAssetId );
}
else
{
// Acquire public asset.
pAssetBase = object->acquireAsset<AssetBase>( pAssetId );
}
return pAssetBase != NULL ? pAssetBase->getIdString() : StringTable->EmptyString();
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, releaseAsset, bool, (const char* assetId), (""),
"Release the specified asset Id.\n"
"The asset should have been acquired using 'acquireAsset'.\n"
"@param assetId The selected asset Id.\n"
"@return Whether the asset was released or not.\n")
{
// Release asset.
return object->releaseAsset(assetId);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, purgeAssets, void, (),,
"Purge all assets that are not referenced even if they are set to not auto-unload.\n"
"Assets can be in this state because they are either set to not auto-unload or the asset manager has/is disabling auto-unload.\n"
"@return No return value.\n")
{
// Purge assets.
object->purgeAssets();
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, deleteAsset, bool, (const char* assetId, bool deleteLooseFiles, bool deleteDependencies), ("", false, false),
"Deletes the specified asset Id and optionally its loose files and asset dependencies.\n"
"@param assetId The selected asset Id.\n"
"@param deleteLooseFiles Whether to delete an assets loose files or not.\n"
"@param deleteDependencies Whether to delete assets that depend on this asset or not.\n"
"@return Whether the asset deletion was successful or not. A failure only indicates that the specified asset was not deleted but dependent assets and their loose files may have being deleted.\n")
{
// Fetch asset Id.
const char* pAssetId = assetId;
// Delete asset.
return object->deleteAsset( pAssetId, deleteLooseFiles, deleteDependencies );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, refreshAsset, void, (const char* assetId), (""),
"Refresh the specified asset Id.\n"
"@param assetId The selected asset Id.\n"
"@return No return value.\n")
{
object->refreshAsset(assetId);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, refreshAllAssets, void, (bool includeUnloaded), (false),
"Refresh all declared assets.\n"
"@param Whether to include currently unloaded assets in the refresh or not. Optional: Defaults to false.\n"
"Refreshing all assets can be an expensive (time-consuming) operation to perform.\n"
"@return No return value.\n")
{
// Refresh assets
object->refreshAllAssets(includeUnloaded);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, saveAssetTags, bool, (),,
"Save the currently loaded asset tags manifest.\n"
"@return Whether the save was successful or not.\n")
{
// Save asset tags.
return object->saveAssetTags();
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, restoreAssetTags, bool, (),,
"Restore the currently loaded asset tags manifest from disk (replace anything in memory).\n"
"@return Whether the restore was successful or not.\n")
{
// Restore asset tags.
return object->restoreAssetTags();
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, getAssetTags, S32, (), ,
"Gets the currently loaded asset tags manifest.\n"
"@return The currently loaded asset tags manifest or zero if not loaded.\n")
{
// Fetch the asset tags manifest.
AssetTagsManifest* pAssetTagsManifest = object->getAssetTags();
return pAssetTagsManifest == NULL ? 0 : pAssetTagsManifest->getId();
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, findAllAssets, S32, (const char* assetQuery, bool ignoreInternal, bool ignorePrivate), ("", true, true),
"Performs an asset query searching for all assets optionally ignoring internal assets.\n"
"@param assetQuery The asset query object that will be populated with the results.\n"
"@param ignoreInternal Whether to ignore internal assets or not. Optional: Defaults to true.\n"
"@param ignorePrivate Whether to ignore private assets or not. Optional: Defaults to true.\n"
"@return The number of asset Ids found or (-1) if an error occurred.\n")
{
// Fetch asset query.
AssetQuery* pAssetQuery;
Sim::findObject(assetQuery, pAssetQuery);
// Did we find the asset query?
if ( pAssetQuery == NULL )
{
// No, so warn.
Con::warnf("AssetManager::findAllAssets() - Could not find the asset query object '%s'.", assetQuery);
return -1;
}
// Perform query.
return object->findAllAssets( pAssetQuery, ignoreInternal, ignorePrivate );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, findAssetName, S32, (const char* assetQuery, const char* assetName, bool partialName), ("", "", false),
"Performs an asset query searching for the specified asset name.\n"
"@param assetQuery The asset query object that will be populated with the results.\n"
"@param assetName The asset name to search for. This may be a partial name if 'partialName' is true.\n"
"@param partialName Whether the asset name is to be used as a partial name or not. Optional: Defaults to false.\n"
"@return The number of asset Ids found or (-1) if an error occurred.\n")
{
// Fetch asset query.
AssetQuery* pAssetQuery;
Sim::findObject(assetQuery, pAssetQuery);
// Did we find the asset query?
if ( pAssetQuery == NULL )
{
// No, so warn.
Con::warnf("AssetManager::findAssetName() - Could not find the asset query object '%s'.", assetQuery);
return -1;
}
// Fetch asset name.
const char* pAssetName = assetName;
// Perform query.
return object->findAssetName( pAssetQuery, pAssetName, partialName );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, findAssetCategory, S32, (const char* assetQuery, const char* assetCategory, bool assetQueryAsSource), ("", "", false),
"Performs an asset query searching for the specified asset category.\n"
"@param assetQuery The asset query object that will be populated with the results.\n"
"@param assetCategory The asset category to search for.\n"
"@param assetQueryAsSource Whether to use the asset query as the data-source rather than the asset managers database or not. Doing this effectively filters the asset query. Optional: Defaults to false.\n"
"@return The number of asset Ids found or (-1) if an error occurred.\n")
{
// Fetch asset query.
AssetQuery* pAssetQuery;
Sim::findObject(assetQuery, pAssetQuery);
// Did we find the asset query?
if ( pAssetQuery == NULL )
{
// No, so warn.
Con::warnf("AssetManager::findAssetCategory() - Could not find the asset query object '%s'.", assetQuery);
return -1;
}
// Fetch asset category.
const char* pAssetCategory = assetCategory;
// Perform query.
return object->findAssetCategory( pAssetQuery, pAssetCategory, assetQueryAsSource );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, findAssetAutoUnload, S32, (const char* assetQuery, bool assetAutoUnload, bool assetQueryAsSource), ("", false, false),
"Performs an asset query searching for the specified asset auto-unload flag.\n"
"@param assetQuery The asset query object that will be populated with the results.\n"
"@param assetInternal The asset internal flag to search for.\n"
"@param assetQueryAsSource Whether to use the asset query as the data-source rather than the asset managers database or not. Doing this effectively filters the asset query. Optional: Defaults to false.\n"
"@return The number of asset Ids found or (-1) if an error occurred.\n")
{
// Fetch asset query.
AssetQuery* pAssetQuery;
Sim::findObject(assetQuery, pAssetQuery);
// Did we find the asset query?
if ( pAssetQuery == NULL )
{
// No, so warn.
Con::warnf("AssetManager::findAssetAutoUnload() - Could not find the asset query object '%s'.", assetQuery);
return -1;
}
// Perform query.
return object->findAssetAutoUnload( pAssetQuery, assetAutoUnload, assetQueryAsSource );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, findAssetInternal, S32, (const char* assetQuery, bool assetInternal, bool assetQueryAsSource), ("", false, false),
"Performs an asset query searching for the specified asset internal flag.\n"
"@param assetQuery The asset query object that will be populated with the results.\n"
"@param assetInternal The asset internal flag to search for.\n"
"@param assetQueryAsSource Whether to use the asset query as the data-source rather than the asset managers database or not. Doing this effectively filters the asset query. Optional: Defaults to false.\n"
"@return The number of asset Ids found or (-1) if an error occurred.\n")
{
// Fetch asset query.
AssetQuery* pAssetQuery;
Sim::findObject(assetQuery, pAssetQuery);
// Did we find the asset query?
if ( pAssetQuery == NULL )
{
// No, so warn.
Con::warnf("AssetManager::findAssetInternal() - Could not find the asset query object '%s'.", assetQuery);
return -1;
}
// Perform query.
return object->findAssetInternal( pAssetQuery, assetInternal, assetQueryAsSource );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, findAssetPrivate, S32, (const char* assetQuery, bool assetPrivate, bool assetQueryAsSource), ("", false, false),
"Performs an asset query searching for the specified asset private flag.\n"
"@param assetQuery The asset query object that will be populated with the results.\n"
"@param assetPrivate The asset private flag to search for.\n"
"@param assetQueryAsSource Whether to use the asset query as the data-source rather than the asset managers database or not. Doing this effectively filters the asset query. Optional: Defaults to false.\n"
"@return The number of asset Ids found or (-1) if an error occurred.\n")
{
// Fetch asset query.
AssetQuery* pAssetQuery;
Sim::findObject(assetQuery, pAssetQuery);
// Did we find the asset query?
if ( pAssetQuery == NULL )
{
// No, so warn.
Con::warnf("AssetManager::findAssetPrivate() - Could not find the asset query object '%s'.", assetQuery);
return -1;
}
// Perform query.
return object->findAssetInternal( pAssetQuery, assetPrivate, assetQueryAsSource );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, findAssetType, S32, (const char* assetQuery, const char* assetType, bool assetQueryAsSource), ("", "", false),
"Performs an asset query searching for the specified asset type.\n"
"@param assetQuery The asset query object that will be populated with the results.\n"
"@param assetType The asset type to search for.\n"
"@param assetQueryAsSource Whether to use the asset query as the data-source rather than the asset managers database or not. Doing this effectively filters the asset query. Optional: Defaults to false.\n"
"@return The number of asset Ids found or (-1) if an error occurred.\n")
{
// Fetch asset query.
AssetQuery* pAssetQuery;
Sim::findObject(assetQuery, pAssetQuery);
// Did we find the asset query?
if ( pAssetQuery == NULL )
{
// No, so warn.
Con::warnf("AssetManager::findAssetType() - Could not find the asset query object '%s'.", assetQuery);
return -1;
}
// Fetch asset type.
const char* pAssetType = assetType;
// Perform query.
return object->findAssetType( pAssetQuery, pAssetType, assetQueryAsSource );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, findAssetDependsOn, S32, (const char* assetQuery, const char* assetId), ("", ""),
"Performs an asset query searching for asset Ids that the specified asset Id depends on.\n"
"@param assetQuery The asset query object that will be populated with the results.\n"
"@param assetId The asset Id to query for any asset Ids that it depends on.\n"
"@return The number of asset Ids found or (-1) if an error occurred.\n")
{
// Fetch asset query.
AssetQuery* pAssetQuery;
Sim::findObject(assetQuery, pAssetQuery);
// Did we find the asset query?
if ( pAssetQuery == NULL )
{
// No, so warn.
Con::warnf("AssetManager::findAssetDependsOn() - Could not find the asset query object '%s'.", assetQuery);
return -1;
}
// Fetch asset Id.
const char* pAssetId = assetId;
// Perform query.
return object->findAssetDependsOn( pAssetQuery, pAssetId );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, findAssetIsDependedOn, S32, (const char* assetQuery, const char* assetId), ("", ""),
"Performs an asset query searching for asset Ids that depend on the specified asset Id.\n"
"@param assetQuery The asset query object that will be populated with the results.\n"
"@param assetId The asset Id to query for any asset Ids that may depend on it.\n"
"@return The number of asset Ids found or (-1) if an error occurred.\n")
{
// Fetch asset query.
AssetQuery* pAssetQuery;
Sim::findObject(assetQuery, pAssetQuery);
// Did we find the asset query?
if ( pAssetQuery == NULL )
{
// No, so warn.
Con::warnf("AssetManager::findAssetIsDependedOn() - Could not find the asset query object '%s'.", assetQuery);
return -1;
}
// Fetch asset Id.
const char* pAssetId = assetId;
// Perform query.
return object->findAssetIsDependedOn( pAssetQuery, pAssetId );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, findInvalidAssetReferences, S32, (const char* assetQuery), (""),
"Performs an asset query searching for invalid asset references.\n"
"@param assetQuery The asset query object that will be populated with the results.\n"
"@return The number of asset Ids found that are invalid or (-1) if an error occurred.\n")
{
// Fetch asset query.
AssetQuery* pAssetQuery;
Sim::findObject(assetQuery, pAssetQuery);
// Did we find the asset query?
if ( pAssetQuery == NULL )
{
// No, so warn.
Con::warnf("AssetManager::findInvalidAssetReferences() - Could not find the asset query object '%s'.", assetQuery);
return -1;
}
// Perform query.
return object->findInvalidAssetReferences( pAssetQuery );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, findTaggedAssets, S32, (const char* assetQuery, const char* assetTagNames, bool assetQueryAsSource), ("", "", false),
"Performs an asset query searching for the specified asset tag name(s).\n"
"@param assetQuery The asset query object that will be populated with the results.\n"
"@param assetTagNames The asset tag name or names to search for. Multiple names can be specified using comma, space, tab or newline separation. Tags use an OR operation i.e. only assets tagged with ANY of the specified tags will be returned.\n"
"@param assetQueryAsSource Whether to use the asset query as the data-source rather than the asset managers database or not. Doing this effectively filters the asset query. Optional: Defaults to false.\n"
"@return The number of asset Ids found or (-1) if an error occurred.\n")
{
// Fetch asset query.
AssetQuery* pAssetQuery;
Sim::findObject(assetQuery, pAssetQuery);
// Did we find the asset query?
if ( pAssetQuery == NULL )
{
// No, so warn.
Con::warnf("AssetManager::findTaggedAssets() - Could not find the asset query object '%s'.", assetQuery);
return -1;
}
// Fetch asset tag name(s).
const char* pAssetTagNames = assetTagNames;
// Perform query.
return object->findTaggedAssets( pAssetQuery, pAssetTagNames, assetQueryAsSource );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, findAssetLooseFile, S32, (const char* assetQuery, const char* assetLooseFile, bool assetQueryAsSource), ("", "", false),
"Performs an asset query searching for the specified loose file.\n"
"@param assetQuery The asset query object that will be populated with the results.\n"
"@param assetLooseFile The loose-file used by the asset to search for.\n"
"@param assetQueryAsSource Whether to use the asset query as the data-source rather than the asset managers database or not. Doing this effectively filters the asset query. Optional: Defaults to false.\n"
"@return The number of asset Ids found or (-1) if an error occurred.\n")
{
// Fetch asset query.
AssetQuery* pAssetQuery;
Sim::findObject(assetQuery, pAssetQuery);
// Did we find the asset query?
if ( pAssetQuery == NULL )
{
// No, so warn.
Con::warnf("AssetManager::findAssetLooseFile() - Could not find the asset query object '%s'.", assetQuery);
return -1;
}
// Fetch asset loose file.
const char* pAssetLooseFile = assetLooseFile;
// Perform query.
return object->findAssetLooseFile( pAssetQuery, pAssetLooseFile, assetQueryAsSource );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, getDeclaredAssetCount, bool, (),,
"Gets the number of declared assets.\n"
"@return Returns the number of declared assets.\n")
{
return object->getDeclaredAssetCount();
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, getReferencedAssetCount, bool, (), ,
"Gets the number of asset referenced.\n"
"@return Returns the number of asset references.\n")
{
return object->getReferencedAssetCount();
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, getLoadedInternalAssetCount, bool, (), ,
"Gets the number of loaded internal assets.\n"
"@return Returns the number of loaded internal assets.\n")
{
return object->getLoadedInternalAssetCount();
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, getMaxLoadedInternalAssetCount, bool, (), ,
"Gets the maximum number of loaded internal assets.\n"
"@return Returns the maximum number of loaded internal assets.\n")
{
return object->getMaxLoadedInternalAssetCount();
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, getLoadedExternalAssetCount, bool, (), ,
"Gets the number of loaded external assets.\n"
"@return Returns the number of loaded external assets.\n")
{
return object->getLoadedExternalAssetCount();
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, getMaxLoadedExternalAssetCount, bool, (), ,
"Gets the maximum number of loaded external assets.\n"
"@return Returns the maximum number of loaded external assets.\n")
{
return object->getMaxLoadedExternalAssetCount();
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetManager, dumpDeclaredAssets, void, (), ,
"Dumps a breakdown of all declared assets.\n"
"@return No return value.\n")
{
return object->dumpDeclaredAssets();
}

View file

@ -0,0 +1,184 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _ASSET_PTR_H_
#define _ASSET_PTR_H_
#ifndef _ASSET_MANAGER_H_
#include "assetManager.h"
#endif
//-----------------------------------------------------------------------------
class AssetPtrCallback
{
friend class AssetManager;
protected:
virtual void onAssetRefreshed( AssetPtrBase* pAssetPtrBase ) = 0;
};
//-----------------------------------------------------------------------------
class AssetPtrBase
{
public:
AssetPtrBase() {};
virtual ~AssetPtrBase()
{
// Un-register any notifications.
unregisterRefreshNotify();
};
/// Referencing.
virtual void clear( void ) = 0;
virtual void setAssetId( const char* pAssetId ) = 0;
virtual StringTableEntry getAssetId( void ) const = 0;
virtual StringTableEntry getAssetType( void ) const = 0;
virtual bool isAssetId( const char* pAssetId ) const = 0;
/// Validity.
virtual bool isNull( void ) const = 0;
virtual bool notNull( void ) const = 0;
/// Notification.
inline void registerRefreshNotify( AssetPtrCallback* pCallback )
{
// Sanity!
AssertFatal( AssetDatabase.isProperlyAdded(), "AssetPtrBase::registerRefreshNotify() - Cannot register an asset pointer with the asset system." );
// register refresh notify.
AssetDatabase.registerAssetPtrRefreshNotify( this, pCallback );
}
void unregisterRefreshNotify( void )
{
// Un-register the refresh notify if the asset system is available.
if ( AssetDatabase.isProperlyAdded() )
AssetDatabase.unregisterAssetPtrRefreshNotify( this );
}
};
//-----------------------------------------------------------------------------
template<typename T> class AssetPtr : public AssetPtrBase
{
private:
SimObjectPtr<T> mpAsset;
public:
AssetPtr() {}
AssetPtr( const char* pAssetId )
{
// Finish if this is an invalid asset Id.
if ( pAssetId == NULL || *pAssetId == 0 )
return;
// Acquire asset.
mpAsset = AssetDatabase.acquireAsset<T>( pAssetId );
}
AssetPtr( const AssetPtr<T>& assetPtr )
{
// Does the asset pointer have an asset?
if ( assetPtr.notNull() )
{
// Yes, so acquire the asset.
mpAsset = AssetDatabase.acquireAsset<T>( assetPtr->getAssetId() );
}
}
virtual ~AssetPtr()
{
// Do we have an asset?
if ( notNull() )
{
// Yes, so release it.
AssetDatabase.releaseAsset( mpAsset->getAssetId() );
}
}
/// Assignment.
AssetPtr<T>& operator=( const char* pAssetId )
{
// Do we have an asset?
if ( notNull() )
{
// Yes, so finish if the asset Id is already assigned.
if ( isAssetId( pAssetId ) )
return *this;
// No, so release it.
AssetDatabase.releaseAsset( mpAsset->getAssetId() );
}
// Is the asset Id at least okay to attempt to acquire the asset?
if ( pAssetId != NULL && *pAssetId != 0 )
{
// Yes, so acquire the asset.
mpAsset = AssetDatabase.acquireAsset<T>( pAssetId );
}
else
{
// No, so remove reference.
mpAsset = NULL;
}
// Return Reference.
return *this;
}
AssetPtr<T>& operator=( const AssetPtr<T>& assetPtr )
{
// Set asset pointer.
*this = assetPtr->getAssetId();
// Return Reference.
return *this;
}
/// Referencing.
virtual void clear( void )
{
// Do we have an asset?
if ( notNull() )
{
// Yes, so release it.
AssetDatabase.releaseAsset( mpAsset->getAssetId() );
}
// Reset the asset reference.
mpAsset = NULL;
}
T* operator->( void ) const { return mpAsset; }
T& operator*( void ) const { return *mpAsset; }
operator T*( void ) const { return mpAsset; }
virtual void setAssetId( const char* pAssetId ) { *this = pAssetId; }
virtual StringTableEntry getAssetId( void ) const { return isNull() ? StringTable->EmptyString() : mpAsset->getAssetId(); }
virtual StringTableEntry getAssetType(void) const { return isNull() ? StringTable->EmptyString() : mpAsset->getClassName(); }
virtual bool isAssetId( const char* pAssetId ) const { return pAssetId == NULL ? isNull() : getAssetId() == StringTable->insert(pAssetId); }
/// Validity.
virtual bool isNull( void ) const { return mpAsset.isNull(); }
virtual bool notNull( void ) const { return !mpAsset.isNull(); }
};
#endif // _ASSET_PTR_H_

View file

@ -0,0 +1,121 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _ASSET_QUERY_H_
#include "assetQuery.h"
#endif
#ifndef _CONSOLETYPES_H_
#include "console/consoleTypes.h"
#endif
#ifndef _TAML_CUSTOM_H_
#include "persistence/taml/tamlCustom.h"
#endif
// Script bindings.
#include "assetQuery_ScriptBinding.h"
//-----------------------------------------------------------------------------
IMPLEMENT_CONOBJECT( AssetQuery );
//-----------------------------------------------------------------------------
void AssetQuery::initPersistFields()
{
// Call parent.
Parent::initPersistFields();
addProtectedField("Count", TypeS32, 0, &defaultProtectedSetFn, &getCount, &writeCount, "Gets the number of results in the asset query.");
}
//-----------------------------------------------------------------------------
void AssetQuery::onTamlCustomWrite( TamlCustomNodes& customNodes )
{
// Call parent.
Parent::onTamlCustomWrite( customNodes );
// Add node.
TamlCustomNode* pCustomNode = customNodes.addNode( ASSETQUERY_RESULTS_NODE_NAME );
// Finish if no assets.
if (mAssetList.size() == 0)
return;
// Iterate asset.
for (Vector<StringTableEntry>::iterator assetItr = mAssetList.begin(); assetItr != mAssetList.end(); ++assetItr)
{
// Add asset node.
TamlCustomNode* pAssetNode = pCustomNode->addNode( ASSETQUERY_ASSETNODE_NAME );
// Add field.
pAssetNode->addField( ASSETQUERY_ASSETID_FIELD_NAME, *assetItr );
}
}
//-----------------------------------------------------------------------------
void AssetQuery::onTamlCustomRead( const TamlCustomNodes& customNodes )
{
// Call parent.
Parent::onTamlCustomRead( customNodes );
// Find custom node name.
const TamlCustomNode* pResultsNode = customNodes.findNode( ASSETQUERY_RESULTS_NODE_NAME );
// Finish if we don't have a results name.
if ( pResultsNode == NULL )
return;
// Fetch node name.
StringTableEntry assetNodeName = StringTable->insert( ASSETQUERY_ASSETNODE_NAME );
// Fetch children asset nodes.
const TamlCustomNodeVector& assetNodes = pResultsNode->getChildren();
// Iterate asset nodes.
for( TamlCustomNodeVector::const_iterator assetNodeItr = assetNodes.begin(); assetNodeItr != assetNodes.end(); ++assetNodeItr )
{
// Fetch asset node.
const TamlCustomNode* pAssetNode = *assetNodeItr;
// Skip if an unknown node name.
if ( pAssetNode->getNodeName() != assetNodeName )
continue;
// Fetch field.
const TamlCustomField* pField = pAssetNode->findField( ASSETQUERY_ASSETID_FIELD_NAME );
// Do we find the field?
if ( pField == NULL )
{
// No, so warn.
Con::warnf( "AssetQuery::onTamlCustomRead() - Could not find '%s' field.", ASSETQUERY_ASSETID_FIELD_NAME );
continue;
}
// Store asset.
mAssetList.push_back(pField->getFieldValue());
}
}

View file

@ -0,0 +1,90 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _ASSET_QUERY_H_
#define _ASSET_QUERY_H_
#ifndef _SIMBASE_H_
#include "console/simBase.h"
#endif
#ifndef _TVECTOR_H_
#include "core/util/tVector.h"
#endif
#ifndef _STRINGUNIT_H_
#include "core/strings/stringUnit.h"
#endif
#ifndef _TAML_CUSTOM_H_
#include "persistence/taml/tamlCustom.h"
#endif
//-----------------------------------------------------------------------------
#define ASSETQUERY_RESULTS_NODE_NAME "Results"
#define ASSETQUERY_ASSETNODE_NAME "Asset"
#define ASSETQUERY_ASSETID_FIELD_NAME "AssetId"
//-----------------------------------------------------------------------------
class AssetQuery : public SimObject
{
private:
typedef SimObject Parent;
protected:
virtual void onTamlCustomWrite( TamlCustomNodes& customNodes );
virtual void onTamlCustomRead( const TamlCustomNodes& customNodes );
static const char* getCount(void* obj, const char* data) { return Con::getIntArg(static_cast<AssetQuery*>(obj)->mAssetList.size()); }
static bool writeCount( void* obj, StringTableEntry pFieldName ) { return false; }
public:
AssetQuery() {}
virtual ~AssetQuery() {}
/// SimObject overrides
static void initPersistFields();
Vector<StringTableEntry> mAssetList;
/// Whether asset is contained or not.
inline bool containsAsset( StringTableEntry assetId )
{
for (Vector<StringTableEntry>::const_iterator assetItr = mAssetList.begin(); assetItr != mAssetList.end(); ++assetItr)
{
if ( *assetItr == assetId )
return true;
}
return false;
}
/// Set assets.
inline void set( const AssetQuery& assetQuery ) { this->mAssetList = assetQuery.mAssetList; }
/// Declare Console Object.
DECLARE_CONOBJECT( AssetQuery );
};
#endif // _ASSET_QUERY_H_

View file

@ -0,0 +1,85 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _ASSET_QUERY_H_
#include "assets/assetQuery.h"
#endif
#include "console/engineAPI.h"
DefineConsoleMethod(AssetQuery, clear, void, (),,"Clears all asset Id results."
"Clears all asset Id results.\n"
"@return () No return value.\n")
{
object->mAssetList.clear();
}
//-----------------------------------------------------------------------------
DefineConsoleMethod(AssetQuery, set, bool, (S32 queryId), ,
"Sets the asset query to a copy of the specified asset query.\n"
"@param assetQuery The asset query to copy.\n"
"@return Whether the operation succeeded or not.\n")
{
// Find asset query.
AssetQuery* pAssetQuery;
if (!Sim::findObject(queryId, pAssetQuery))
{
// No, so warn.
Con::warnf("AssetQuery::set() - Could not find asset query '%i'.", queryId);
return false;
}
// Set asset query.
object->set( *pAssetQuery );
return true;
}
//-----------------------------------------------------------------------------
DefineConsoleMethod(AssetQuery, getCount, S32, (), ,
"Gets the count of asset Id results.\n"
"@return (int)The count of asset Id results.\n")
{
return object->mAssetList.size();
}
//-----------------------------------------------------------------------------
DefineConsoleMethod(AssetQuery, getAsset, const char*, (S32 resultIndex), (-1),
"Gets the asset Id at the specified query result index.\n"
"@param resultIndex The query result index to use.\n"
"@return (assetId)The asset Id at the specified index or NULL if not valid.\n")
{
// Is index within bounds?
if (resultIndex >= object->mAssetList.size())
{
// No, so warn.
Con::warnf("AssetQuery::getAsset() - Result index '%s' is out of bounds.", resultIndex);
return StringTable->EmptyString();
}
return object->mAssetList[resultIndex];
}

View file

@ -0,0 +1,564 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _ASSET_TAGS_MANIFEST_H_
#include "assetTagsManifest.h"
#endif
#ifndef _ASSET_MANAGER_H_
#include "assetManager.h"
#endif
#ifndef _CONSOLETYPES_H_
#include "console/consoleTypes.h"
#endif
// Script binding.
#include "assetTagsManifest_ScriptBinding.h"
//-----------------------------------------------------------------------------
IMPLEMENT_CONOBJECT( AssetTagsManifest );
//-----------------------------------------------------------------------------
AssetTagsManifest::AssetTagsManifest()
{
}
//-----------------------------------------------------------------------------
AssetTagsManifest::~AssetTagsManifest()
{
// Iterate tags.
for( typeTagNameHash::iterator tagNameItr = mTagNameDatabase.begin(); tagNameItr != mTagNameDatabase.end(); ++tagNameItr )
{
// Delete asset tag.
delete tagNameItr->value;
}
// Clear database.
mTagNameDatabase.clear();
mAssetToTagDatabase.clear();
}
//-----------------------------------------------------------------------------
StringTableEntry AssetTagsManifest::fetchTagName( const char* pTagName )
{
// Sanity!
AssertFatal( pTagName != NULL, "Cannot use a NULL tag name." );
return StringTable->insert( pTagName, true );
}
//-----------------------------------------------------------------------------
AssetTagsManifest::AssetTag* AssetTagsManifest::findAssetTag( const char* pTagName )
{
// Fetch tag name.
StringTableEntry tagName = fetchTagName( pTagName );
// Finish if the tag already exists.
typeTagNameHash::iterator tagNameItr = mTagNameDatabase.find( tagName );
return tagNameItr == mTagNameDatabase.end() ? NULL : tagNameItr->value;
}
//-----------------------------------------------------------------------------
void AssetTagsManifest::renameAssetId( const char* pAssetIdFrom, const char* pAssetIdTo )
{
// Sanity!
AssertFatal( pAssetIdFrom != NULL, "Cannot rename from NULL asset Id." );
AssertFatal( pAssetIdTo != NULL, "Cannot rename to NULL asset Id." );
// Fetch asset Ids.
StringTableEntry assetIdFrom = StringTable->insert( pAssetIdFrom );
StringTableEntry assetIdTo = StringTable->insert( pAssetIdTo );
while( true )
{
// Find asset Id.
typeAssetToTagHash::Iterator assetIdItr = mAssetToTagDatabase.find( assetIdFrom );
// Finish if no asset Id to rename.
if ( assetIdItr == mAssetToTagDatabase.end() )
return;
// Fetch asset tag.
AssetTag* pAssetTag = assetIdItr->value;
// Untag old asset Id.
untag( assetIdFrom, pAssetTag->mTagName );
// Tag new asset Id.
tag( assetIdTo, pAssetTag->mTagName );
}
}
//-----------------------------------------------------------------------------
void AssetTagsManifest::onTamlCustomWrite( TamlCustomNodes& customNodes )
{
// Call parent.
Parent::onTamlCustomWrite( customNodes );
// Finish if no tags.
if ( mTagNameDatabase.size() == 0 )
return;
// Add node.
TamlCustomNode* pTagsNode = customNodes.addNode( ASSETTAGS_TAGS_NODE_NAME );
// Iterate tags.
for( typeTagNameHash::iterator tagItr = mTagNameDatabase.begin(); tagItr != mTagNameDatabase.end(); ++tagItr )
{
// Add tag node.
TamlCustomNode* pTagNode = pTagsNode->addNode( ASSETTAGS_TAGS_TYPE_NAME );
// Add fields.
pTagNode->addField( ASSETTAGS_TAGS_NAME_FIELD, tagItr->key );
}
// Add node.
TamlCustomNode* pAssetTagsNode = customNodes.addNode( ASSETTAGS_ASSETS_NODE_NAME );
// Iterate asset locations.
for( typeAssetToTagHash::Iterator assetTagItr = mAssetToTagDatabase.begin(); assetTagItr != mAssetToTagDatabase.end(); ++assetTagItr )
{
// Add asset tag node.
TamlCustomNode* pAssetNode = pAssetTagsNode->addNode( ASSETTAGS_ASSETS_TYPE_NAME );
// Add fields.
pAssetNode->addField( ASSETTAGS_ASSETS_ASSETID_FIELD, assetTagItr->key );
pAssetNode->addField( ASSETTAGS_ASSETS_TAG_FIELD, assetTagItr->value->mTagName );
}
}
//-----------------------------------------------------------------------------
void AssetTagsManifest::onTamlCustomRead( const TamlCustomNodes& customNodes )
{
// Call parent.
Parent::onTamlCustomRead( customNodes );
// Find tags nodes.
const TamlCustomNode* pTagProperty = customNodes.findNode( ASSETTAGS_TAGS_NODE_NAME );
// Finish if we don't have a tags node name.
if ( pTagProperty == NULL )
return;
// Fetch node name.
StringTableEntry tagNodeName = StringTable->insert( ASSETTAGS_TAGS_TYPE_NAME );
// Fetch children asset nodes.
const TamlCustomNodeVector& tagNodes = pTagProperty->getChildren();
// Iterate tag nodes.
for( TamlCustomNodeVector::const_iterator tagNodeItr = tagNodes.begin(); tagNodeItr != tagNodes.end(); ++tagNodeItr )
{
// Fetch tag node.
const TamlCustomNode* pTagNode = *tagNodeItr;
// Skip if an unknown node name.
if ( pTagNode->getNodeName() != tagNodeName )
continue;
// Fetch "Name" field.
const TamlCustomField* pTagNameField = pTagNode->findField( ASSETTAGS_TAGS_NAME_FIELD );
// Do we find the field?
if ( pTagNameField == NULL )
{
// No, so warn.
Con::warnf( "AssetTagsManifest::onTamlCustomRead() - Could not find '%s' field.", ASSETTAGS_TAGS_NAME_FIELD );
continue;
}
// Create the tag.
createTag( pTagNameField->getFieldValue() );
}
// Find asset tags node.
const TamlCustomNode* pAssetTagProperty = customNodes.findNode( ASSETTAGS_ASSETS_NODE_NAME );
// Finish if we don't have an asset tags node name.
if ( pAssetTagProperty == NULL )
return;
// Fetch node name.
StringTableEntry assetTagNodeName = StringTable->insert( ASSETTAGS_ASSETS_TYPE_NAME );
// Fetch children asset tag nodes.
const TamlCustomNodeVector& assetTagNodes = pAssetTagProperty->getChildren();
// Iterate property alias.
for( TamlCustomNodeVector::const_iterator assetTagNodeItr = assetTagNodes.begin(); assetTagNodeItr != assetTagNodes.end(); ++assetTagNodeItr )
{
// Fetch asset node.
const TamlCustomNode* pAssetTagNode = *assetTagNodeItr;
// Skip if an unknown node name.
if ( pAssetTagNode->getNodeName() != assetTagNodeName )
continue;
// Fetch "AssetId" field.
const TamlCustomField* pAssetIdField = pAssetTagNode->findField( ASSETTAGS_ASSETS_ASSETID_FIELD );
// Do we find the field?
if ( pAssetIdField == NULL )
{
// No, so warn.
Con::warnf( "AssetTagsManifest::onTamlCustomRead() - Could not find '%s' field.", ASSETTAGS_ASSETS_ASSETID_FIELD );
continue;
}
// Fetch "Tag" field.
const TamlCustomField* pTagField = pAssetTagNode->findField( ASSETTAGS_ASSETS_TAG_FIELD );
// Do we find the field?
if ( pTagField == NULL )
{
// No, so warn.
Con::warnf( "AssetTagsManifest::onTamlCustomRead() - Could not find '%s' field.", ASSETTAGS_ASSETS_TAG_FIELD );
continue;
}
// Tag the asset.
tag( pAssetIdField->getFieldValue(), pTagField->getFieldValue() );
}
}
//-----------------------------------------------------------------------------
const AssetTagsManifest::AssetTag* AssetTagsManifest::createTag( const char* pTagName )
{
// Sanity!
AssertFatal( pTagName != NULL, "Cannot use a NULL tag name." );
// Finish if the tag already exists.
AssetTag* pAssetTag = findAssetTag( pTagName );
// Return asset tag if already created.
if ( pAssetTag != NULL )
return pAssetTag;
// Fetch tag name.
StringTableEntry tagName = fetchTagName( pTagName );
// Generate the asset tag.
pAssetTag = new AssetTag( tagName );
// Add the tag.
mTagNameDatabase.insert( tagName, pAssetTag );
return pAssetTag;
}
//-----------------------------------------------------------------------------
bool AssetTagsManifest::renameTag( const char* pOldTagName, const char* pNewTagName )
{
// Sanity!
AssertFatal( pOldTagName != NULL, "Cannot use a NULL tag name." );
AssertFatal( pNewTagName != NULL, "Cannot use a NULL tag name." );
// Find old asset tags.
AssetTag* pOldAssetTag = findAssetTag( pOldTagName );
// Did we find the asset tag?
if ( pOldAssetTag == NULL )
{
// No, so warn.
Con::warnf( "AssetTagsManifest: Cannot rename tag '%s' as it does not exist.", pOldTagName );
return false;
}
// Are the old and new tags the same?
if ( pOldAssetTag->mTagName == fetchTagName( pNewTagName ) )
{
// Yes, so warn.
Con::warnf( "AssetTagsManifest: Cannot rename tag '%s' to tag '%s' as they are the same.", pOldTagName, pNewTagName );
return false;
}
// Create new tag.
AssetTag* pNewAssetTag = const_cast<AssetTag*>( createTag( pNewTagName ) );
// Transfer asset tags.
for ( Vector<typeAssetId>::iterator assetIdItr = pOldAssetTag->mAssets.begin(); assetIdItr != pOldAssetTag->mAssets.end(); ++assetIdItr )
{
pNewAssetTag->mAssets.push_back( *assetIdItr );
}
// Delete old tag.
deleteTag( pOldTagName );
return true;
}
//-----------------------------------------------------------------------------
bool AssetTagsManifest::deleteTag( const char* pTagName )
{
// Sanity!
AssertFatal( pTagName != NULL, "Cannot use a NULL tag name." );
// Find asset tag.
AssetTag* pAssetTag = findAssetTag( pTagName );
// Did we find the asset tag?
if ( pAssetTag == NULL )
{
// No, so warn.
Con::warnf( "AssetTagsManifest: Cannot delete tag '%s' as it does not exist.", pTagName );
return false;
}
// Remove the tag.
mTagNameDatabase.erase( pAssetTag->mTagName );
// Remove the asset tags.
for ( Vector<typeAssetId>::iterator assetIdItr = pAssetTag->mAssets.begin(); assetIdItr != pAssetTag->mAssets.end(); ++assetIdItr )
{
// Find asset Id tag.
typeAssetToTagHash::Iterator assetItr = mAssetToTagDatabase.find( *assetIdItr );
// Iterate asset Id tags.
while( assetItr != mAssetToTagDatabase.end() && assetItr->key == *assetIdItr )
{
// Is this the asset tag?
if ( assetItr->value == pAssetTag )
{
// Yes, so erase it.
mAssetToTagDatabase.erase( assetItr );
break;
}
// Next entry.
assetItr++;
}
}
// Delete the asset tag.
delete pAssetTag;
return true;
}
//-----------------------------------------------------------------------------
bool AssetTagsManifest::isTag( const char* pTagName )
{
// Sanity!
AssertFatal( pTagName != NULL, "Cannot use a NULL tag name." );
// Check whether tag exists or not.
return findAssetTag( pTagName ) != NULL;
}
//-----------------------------------------------------------------------------
StringTableEntry AssetTagsManifest::getTag( const U32 tagIndex )
{
// Finish if invalid tag count.
AssertFatal( tagIndex < getTagCount(), "Tag index is out of bounds." );
// Fetch tag iterator.
typeTagNameHash::iterator tagItr = mTagNameDatabase.begin();
// Find asset tag by index.
// NOTE: Unfortunately this is slow as it's not the natural access method.
for( U32 index = 0; index < tagIndex; ++index, ++tagItr ) {};
// Return tag name.
return tagItr->value->mTagName;
}
//-----------------------------------------------------------------------------
U32 AssetTagsManifest::getAssetTagCount( const char* pAssetId )
{
// Sanity!
AssertFatal( pAssetId != NULL, "Cannot use a NULL asset Id." );
// Fetch asset Id.
StringTableEntry assetId = StringTable->insert( pAssetId );
return (U32)mAssetToTagDatabase.count( assetId );
}
//-----------------------------------------------------------------------------
StringTableEntry AssetTagsManifest::getAssetTag( const char* pAssetId, const U32 tagIndex )
{
// Sanity!
AssertFatal( pAssetId != NULL, "Cannot use a NULL asset Id." );
// Fetch asset Id.
StringTableEntry assetId = StringTable->insert( pAssetId );
// Sanity!
AssertFatal( tagIndex < (U32)mAssetToTagDatabase.count( assetId ), "Asset tag index is out of bounds." );
// Find asset tag.
typeAssetToTagHash::Iterator assetItr = mAssetToTagDatabase.find( assetId );
// Find asset tag by index.
// NOTE: Unfortunately this is slow as it's not the natural access method.
for( U32 index = 0; index < tagIndex; ++index, ++assetItr ) {};
// Return tag name.
return assetItr->value->mTagName;
}
//-----------------------------------------------------------------------------
bool AssetTagsManifest::tag( const char* pAssetId, const char* pTagName )
{
// Sanity!
AssertFatal( pAssetId != NULL, "Cannot use a NULL asset Id." );
AssertFatal( pTagName != NULL, "Cannot use a NULL tag name." );
// Find asset tag.
AssetTag* pAssetTag = findAssetTag( pTagName );
// Does the tag exist?
if ( pAssetTag == NULL )
{
// No, so warn.
Con::warnf("AssetTagsManifest: Cannot tag asset Id '%s' with tag name '%s' as tag name does not exist.", pAssetId, pTagName );
return false;
}
// Is the asset Id valid?
if ( !AssetDatabase.isDeclaredAsset( pAssetId ) )
{
// No, so warn.
Con::warnf( "AssetTagsManifest::onTamlCustomRead() - Ignoring asset Id '%s' mapped to tag name '%s' as it is not a declared asset Id.", pAssetId, pTagName );
return false;
}
// Fetch asset Id.
typeAssetId assetId = StringTable->insert( pAssetId );
// Find asset Id tag.
typeAssetToTagHash::Iterator assetItr = mAssetToTagDatabase.find(assetId);
// Iterate asset Id tags.
while( assetItr != mAssetToTagDatabase.end() && assetItr->key == assetId )
{
// Is the asset already tagged appropriately?
if ( assetItr->value == pAssetTag )
return true;
// Next entry.
assetItr++;
}
// No, so add tag.
mAssetToTagDatabase.insertEqual( assetId, pAssetTag );
// Add to asset tag.
pAssetTag->mAssets.push_back( assetId );
return true;
}
//-----------------------------------------------------------------------------
bool AssetTagsManifest::untag( const char* pAssetId, const char* pTagName )
{
// Sanity!
AssertFatal( pAssetId != NULL, "Cannot use a NULL asset Id." );
AssertFatal( pTagName != NULL, "Cannot use a NULL tag name." );
// Find asset tag.
AssetTag* pAssetTag = findAssetTag( pTagName );
// Does the tag exist?
if ( pAssetTag == NULL )
{
// No, so warn.
Con::warnf("AssetTagsManifest: Cannot untag asset Id '%s' from tag name '%s' as tag name does not exist.", pAssetId, pTagName );
return false;
}
// Fetch asset Id.
typeAssetId assetId = StringTable->insert( pAssetId );
// Is the asset tagged?
if ( !pAssetTag->containsAsset( assetId ) )
{
// No, so warn.
Con::warnf("AssetTagsManifest: Cannot untag asset Id '%s' from tag name '%s' as the asset is not tagged with the tag name.", pAssetId, pTagName );
return false;
}
// Remove asset from assert tag.
pAssetTag->removeAsset( assetId );
// Find asset Id tag.
typeAssetToTagHash::Iterator assetItr = mAssetToTagDatabase.find(assetId);
// Iterate asset Id tags.
while( assetItr != mAssetToTagDatabase.end() && assetItr->key == assetId )
{
// Is this the asset tag?
if ( assetItr->value == pAssetTag )
{
// Yes, so remove it.
mAssetToTagDatabase.erase( assetItr );
break;
}
// Next entry.
assetItr++;
}
return true;
}
//-----------------------------------------------------------------------------
bool AssetTagsManifest::hasTag( const char* pAssetId, const char* pTagName )
{
// Sanity!
AssertFatal( pAssetId != NULL, "Cannot use a NULL asset Id." );
AssertFatal( pTagName != NULL, "Cannot use a NULL tag name." );
// Find asset tag.
AssetTag* pAssetTag = findAssetTag( pTagName );
// Does the tag exist?
if ( pAssetTag == NULL )
{
// No, so warn.
Con::warnf("AssetTagsManifest: Cannot check if asset Id '%s' has tag name '%s' as tag name does not exist.", pAssetId, pTagName );
return false;
}
// Return whether asset Id is tagged.
return pAssetTag->containsAsset( StringTable->insert( pAssetId ) );
}

View file

@ -0,0 +1,148 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _ASSET_TAGS_MANIFEST_H_
#define _ASSET_TAGS_MANIFEST_H_
#ifndef _SIMBASE_H_
#include "console/simBase.h"
#endif
#ifndef _TDICTIONARY_H_
#include "core/util/tDictionary.h"
#endif
#ifndef _TVECTOR_H_
#include "core/util/tvector.h"
#endif
#ifndef _STRINGUNIT_H_
#include "core/strings/stringUnit.h"
#endif
//-----------------------------------------------------------------------------
#define ASSETTAGS_TAGS_NODE_NAME "Tags"
#define ASSETTAGS_TAGS_TYPE_NAME "Tag"
#define ASSETTAGS_TAGS_NAME_FIELD "Name"
#define ASSETTAGS_ASSETS_NODE_NAME "Assets"
#define ASSETTAGS_ASSETS_TYPE_NAME "Tag"
#define ASSETTAGS_ASSETS_ASSETID_FIELD "AssetId"
#define ASSETTAGS_ASSETS_TAG_FIELD "Name"
//-----------------------------------------------------------------------------
class AssetManager;
//-----------------------------------------------------------------------------
class AssetTagsManifest : public SimObject
{
friend class AssetManager;
private:
typedef SimObject Parent;
typedef StringTableEntry typeAssetId;
typedef StringTableEntry typeAssetTagName;
public:
/// Asset location.
class AssetTag
{
public:
AssetTag( StringTableEntry tagName )
{
// Sanity!
AssertFatal( tagName != NULL, "Cannot use a NULL tag name." );
// Case sensitive tag name.
mTagName = tagName;
}
bool containsAsset( typeAssetId assetId )
{
for ( Vector<typeAssetId>::iterator assetIdItr = mAssets.begin(); assetIdItr != mAssets.end(); ++assetIdItr )
{
if ( *assetIdItr == assetId )
return true;
}
return false;
}
void removeAsset( typeAssetId assetId )
{
for ( Vector<typeAssetId>::iterator assetIdItr = mAssets.begin(); assetIdItr != mAssets.end(); ++assetIdItr )
{
if ( *assetIdItr == assetId )
{
mAssets.erase( assetIdItr );
return;
}
}
}
typeAssetTagName mTagName;
Vector<typeAssetId> mAssets;
};
/// Asset/Tag database.
typedef HashMap<typeAssetTagName, AssetTag*> typeTagNameHash;
typedef HashTable<typeAssetId, AssetTag*> typeAssetToTagHash;
private:
typeTagNameHash mTagNameDatabase;
typeAssetToTagHash mAssetToTagDatabase;
private:
StringTableEntry fetchTagName( const char* pTagName );
AssetTag* findAssetTag( const char* pTagName );
void renameAssetId( const char* pAssetIdFrom, const char* pAssetIdTo );
protected:
virtual void onTamlCustomWrite( TamlCustomNodes& customNodes );
virtual void onTamlCustomRead( const TamlCustomNodes& customNodes );
public:
AssetTagsManifest();
virtual ~AssetTagsManifest();
/// Tagging.
const AssetTag* createTag( const char* pTagName );
bool renameTag( const char* pOldTagName, const char* pNewTagName );
bool deleteTag( const char* pTagName );
bool isTag( const char* pTagName );
inline U32 getTagCount( void ) const { return (U32)mTagNameDatabase.size(); }
StringTableEntry getTag( const U32 tagIndex );
U32 getAssetTagCount( const char* pAssetId );
StringTableEntry getAssetTag( const char* pAssetId, const U32 tagIndex );
bool tag( const char* pAssetId, const char* pTagName );
bool untag( const char* pAssetId, const char* pTagName );
bool hasTag( const char* pAssetId, const char* pTagName );
/// Declare Console Object.
DECLARE_CONOBJECT( AssetTagsManifest );
};
#endif // _ASSET_TAGS_MANIFEST_H_

View file

@ -0,0 +1,151 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "console/engineAPI.h"
#include "assetTagsManifest.h"
DefineEngineMethod(AssetTagsManifest, createTag, void, (const char* tagName), (""),
"Creates an asset tag.\n"
"@param tagName The tag name to create.\n"
"@return No return value.\n")
{
object->createTag(tagName);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetTagsManifest, renameTag, bool, (const char* oldTagName, const char* newTagName),,
"Renames an existing asset tag.\n"
"@param tagName The tag name to rename.\n"
"@param newTagName The new tag name to assign.\n"
"@return Whether the asset tag was renamed or not.\n")
{
return object->renameTag(oldTagName, newTagName);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetTagsManifest, deleteTag, bool, (const char* tagName),,
"Deletes an asset tag.\n"
"@param tagName The tag name to delete.\n"
"@return Whether the asset tag was deleted or not.\n")
{
return object->deleteTag(tagName);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetTagsManifest, isTag, bool, (const char* tagName),,
"Checks whether the specified asset tag exists or not.\n"
"@param tagName The tag name to check.\n"
"@return Whether the specified asset tag exists or not.\n")
{
return object->isTag(tagName);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetTagsManifest, getTagCount, S32, (),,
"Gets the total asset tag count.\n"
"@return The total asset tag count.\n")
{
return object->getTagCount();
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetTagsManifest, getTag, const char*, (S32 tagIndex),,
"Gets the asset tag at the specified index.\n"
"@param tagIndex The asset tag index.This must be 0 to the asset tag count less one.\n"
"@return The asset tag at the specified index or NULL if invalid.\n")
{
// Is the tag index out-of-bounds?
if ( tagIndex >= object->getTagCount() )
{
// Yes, so warn.
Con::warnf( "AssetTagsManifest: Asset tag index '%d' is out of bounds. Asset tag count is '%d'", tagIndex, object->getTagCount() );
return StringTable->EmptyString();
}
return object->getTag( tagIndex );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetTagsManifest, getAssetTagCount, S32, (const char* assetId),,
"Gets the asset tag count on the specified asset Id.\n"
"@param assetId The asset Id to count tags on.\n"
"@return The asset tag count on the specified asset Id.\n")
{
return object->getAssetTagCount(assetId);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetTagsManifest, getAssetTag, const char*, (const char* assetId, S32 tagIndex), ,
"Gets the asset tag on the specified asset Id at the specified index.\n"
"@param assetId The asset Id to count tags on.\n"
"@param tagIndex The asset tag index.This must be 0 to the asset tag count less one.\n"
"@return The asset tag on the specified asset Id at the specified index or NULL if invalid.\n")
{
// Is the tag index out-of-bounds?
if (tagIndex >= object->getAssetTagCount(assetId))
{
// Yes, so warn.
Con::warnf("AssetTagsManifest: Asset tag index '%d' is out of bounds. Asset tag count is '%d'", tagIndex, object->getAssetTagCount(assetId));
return StringTable->EmptyString();
}
return object->getAssetTag(assetId, tagIndex);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetTagsManifest, tag, bool, (const char* assetId, const char* tagName),,
"Tags the asset Id with the specified asset tag.\n"
"@param assetId The asset Id to tag.\n"
"@param tagName The tag name to assign.\n"
"@return Whether the tag operation was successful or not.\n")
{
return object->tag(assetId, tagName);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetTagsManifest, untag, bool, (const char* assetId, const char* tagName),,
"Un-tags the asset Id from the specified asset tag.\n"
"@param assetId The asset Id to un - tag.\n"
"@param tagName The tag name to un - assign.\n"
"@return Whether the un - tag operation was successful or not.\n")
{
return object->untag(assetId, tagName);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(AssetTagsManifest, hasTag, bool, (const char* assetId, const char* tagName), ,
"Checks whether the asset Id is tagged with the specified asset tag.\n"
"@param assetId The asset Id to check.\n"
"@param tagName The tag name to check.\n"
"@return Whether the asset Id is tagged with the specified asset tag or not.\n")
{
return object->hasTag(assetId, tagName);
}

View file

@ -0,0 +1,12 @@
#ifndef _ASSET_CORE_H_
#define _ASSET_CORE_H_
#ifndef _ASSET_BASE_H_
#include "assetBase.h"
#endif
#ifndef _ASSET_DEFINITION_H_
#include "assetDefinition.h"
#endif
#endif

View file

@ -0,0 +1,45 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _DECLARED_ASSETS_H_
#include "assets/declaredAssets.h"
#endif
#ifndef _CONSOLETYPES_H_
#include "console/consoleTypes.h"
#endif
//-----------------------------------------------------------------------------
IMPLEMENT_CONOBJECT( DeclaredAssets );
//-----------------------------------------------------------------------------
void DeclaredAssets::initPersistFields()
{
// Call Parent.
Parent::initPersistFields();
addField("Path", TypeString, Offset(mPath, DeclaredAssets), "" );
addField("Extension", TypeString, Offset(mExtension, DeclaredAssets), "" );
addField("Recurse", TypeBool, Offset(mRecurse, DeclaredAssets), "" );
}

View file

@ -0,0 +1,73 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _DECLARED_ASSETS_H_
#define _DECLARED_ASSETS_H_
#ifndef _SIM_H_
#include "console/sim.h"
#endif
#ifndef _SIMOBJECT_H_
#include "console/simObject.h"
#endif
#ifndef _CONSOLEOBJECT_H_
#include "console/consoleObject.h"
#endif
//-----------------------------------------------------------------------------
class DeclaredAssets : public SimObject
{
friend class AssetManager;
private:
typedef SimObject Parent;
StringTableEntry mPath;
StringTableEntry mExtension;
bool mRecurse;
public:
DeclaredAssets() :
mPath( StringTable->EmptyString() ),
mExtension(StringTable->EmptyString()),
mRecurse( false )
{}
virtual ~DeclaredAssets() {}
static void initPersistFields();
inline void setPath( const char* pPath ) { mPath = StringTable->insert( pPath ); }
inline StringTableEntry getPath( void ) const { return mPath; }
inline void setExtension( const char* pPath ) { mExtension = StringTable->insert( pPath ); }
inline StringTableEntry getExtension( void ) const { return mExtension; }
inline void setRecurse( const bool recurse ) { mRecurse = recurse; }
inline bool getRecurse( void ) const { return mRecurse; }
/// Declare Console Object.
DECLARE_CONOBJECT( DeclaredAssets );
};
#endif // _DECLARED_ASSETS_H_

View file

@ -0,0 +1,45 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _REFERENCED_ASSETS_H_
#include "assets/referencedAssets.h"
#endif
#ifndef _CONSOLETYPES_H_
#include "console/consoleTypes.h"
#endif
//-----------------------------------------------------------------------------
IMPLEMENT_CONOBJECT( ReferencedAssets );
//-----------------------------------------------------------------------------
void ReferencedAssets::initPersistFields()
{
// Call Parent.
Parent::initPersistFields();
addField("Path", TypeString, Offset(mPath, ReferencedAssets), "" );
addField("Extension", TypeString, Offset(mExtension, ReferencedAssets), "" );
addField("Recurse", TypeBool, Offset(mRecurse, ReferencedAssets), "" );
}

View file

@ -0,0 +1,73 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _REFERENCED_ASSETS_H_
#define _REFERENCED_ASSETS_H_
#ifndef _SIM_H_
#include "console/sim.h"
#endif
#ifndef _SIMOBJECT_H_
#include "console/simObject.h"
#endif
#ifndef _CONSOLEOBJECT_H_
#include "console/consoleObject.h"
#endif
//-----------------------------------------------------------------------------
class ReferencedAssets : public SimObject
{
friend class AssetManager;
private:
typedef SimObject Parent;
StringTableEntry mPath;
StringTableEntry mExtension;
bool mRecurse;
public:
ReferencedAssets() :
mPath( StringTable->EmptyString() ),
mExtension(StringTable->EmptyString()),
mRecurse( false )
{}
virtual ~ReferencedAssets() {}
static void initPersistFields();
inline void setPath( const char* pPath ) { mPath = StringTable->insert( pPath ); }
inline StringTableEntry getPath( void ) const { return mPath; }
inline void setExtension( const char* pPath ) { mExtension = StringTable->insert( pPath ); }
inline StringTableEntry getExtension( void ) const { return mExtension; }
inline void setRecurse( const bool recurse ) { mRecurse = recurse; }
inline bool getRecurse( void ) const { return mRecurse; }
/// Declare Console Object.
DECLARE_CONOBJECT( ReferencedAssets );
};
#endif // _REFERENCED_ASSETS_H_

View file

@ -0,0 +1,132 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _TAML_ASSET_DECLARED_UPDATE_VISITOR_H_
#define _TAML_ASSET_DECLARED_UPDATE_VISITOR_H_
#ifndef _TAML_VISITOR_H_
#include "persistence/taml/tamlVisitor.h"
#endif
#ifndef _TAML_PARSER_H_
#include "persistence\/taml/tamlParser.h"
#endif
#ifndef _ASSET_FIELD_TYPES_H_
#include "assets/assetFieldTypes.h"
#endif
// Debug Profiling.
#include "platform/profiler.h"
//-----------------------------------------------------------------------------
class TamlAssetDeclaredUpdateVisitor : public TamlVisitor
{
private:
StringTableEntry mAssetIdFrom;
StringTableEntry mAssetIdTo;
StringTableEntry mAssetNameFrom;
StringTableEntry mAssetNameTo;
public:
TamlAssetDeclaredUpdateVisitor() {}
virtual ~TamlAssetDeclaredUpdateVisitor() {}
void setAssetIdFrom( const char* pAssetIdFrom )
{
// Sanity!
AssertFatal( pAssetIdFrom != NULL, "Asset Id from cannot be NULL." );
// Reset asset Id.
mAssetIdFrom = StringTable->EmptyString();
mAssetNameFrom = StringTable->EmptyString();
// Is asset Id the correct format?
if ( StringUnit::getUnitCount( pAssetIdFrom, ASSET_SCOPE_TOKEN ) != 2 )
{
// No, so warn.
Con::warnf( "TamlAssetDeclaredUpdateVisitor::setAssetIdFrom() - Cannot use asset Id '%s' as it is not the correct format.", pAssetIdFrom );
return;
}
// Set asset Id.
mAssetIdFrom = StringTable->insert( pAssetIdFrom );
mAssetNameFrom = StringTable->insert( StringUnit::getUnit( pAssetIdFrom, 1, ASSET_SCOPE_TOKEN ) );
}
StringTableEntry getAssetIdFrom( void ) const { return mAssetIdFrom; }
void setAssetIdTo( const char* pAssetIdTo )
{
// Sanity!
AssertFatal( pAssetIdTo != NULL, "Asset Id to cannot be NULL." );
// Reset asset Id.
mAssetIdTo = StringTable->EmptyString();
mAssetNameTo = StringTable->EmptyString();
// Is asset Id the correct format?
if ( StringUnit::getUnitCount( pAssetIdTo, ASSET_SCOPE_TOKEN ) != 2 )
{
// No, so warn.
Con::warnf( "TamlAssetDeclaredUpdateVisitor::setAssetIdTo() - Cannot use asset Id '%s' as it is not the correct format.", pAssetIdTo );
return;
}
// Set asset Id.
mAssetIdTo = StringTable->insert( pAssetIdTo );
mAssetNameTo = StringTable->insert( StringUnit::getUnit( pAssetIdTo, 1, ASSET_SCOPE_TOKEN ) );
}
const char* getAssetIdTo( void ) const { return mAssetIdTo; }
virtual bool wantsPropertyChanges( void ) { return true; }
virtual bool wantsRootOnly( void ) { return true; }
virtual bool visit( const TamlParser& parser, TamlVisitor::PropertyState& propertyState )
{
// Debug Profiling.
PROFILE_SCOPE(TamlAssetDeclaredUpdateVisitor_Visit);
// Finish if not the asset name field.
if ( propertyState.getPropertyName() != assetNameField )
return true;
// Is this the asset Id we're looking for?
if ( dStricmp( propertyState.getPropertyValue(), mAssetNameFrom ) != 0 )
{
// No, so warn.
Con::warnf("Cannot rename asset Name '%s' to asset Name '%s' as the declared asset Name was %s",
mAssetNameFrom, mAssetNameTo, propertyState.getPropertyValue() );
// Stop processing!
return false;
}
// Assign new value.
propertyState.updatePropertyValue( mAssetNameTo );
// Stop processing!
return false;
}
};
#endif // _TAML_ASSET_DECLARED_UPDATE_VISITOR_H_

View file

@ -0,0 +1,189 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _TAML_ASSET_DECLARED_VISITOR_H_
#define _TAML_ASSET_DECLARED_VISITOR_H_
#ifndef _TAML_VISITOR_H_
#include "persistence/taml/tamlVisitor.h"
#endif
#ifndef _TAML_PARSER_H_
#include "persistence\/taml/tamlParser.h"
#endif
#ifndef _ASSET_FIELD_TYPES_H_
#include "assets/assetFieldTypes.h"
#endif
#ifndef _ASSET_DEFINITION_H_
#include "assetDefinition.h"
#endif
#ifndef _ASSET_BASE_H_
#include "assetBase.h"
#endif
// Debug Profiling.
#include "platform/profiler.h"
//-----------------------------------------------------------------------------
class TamlAssetDeclaredVisitor : public TamlVisitor
{
public:
typedef StringTableEntry typeAssetId;
typedef Vector<typeAssetId> typeAssetIdVector;
typedef Vector<StringTableEntry> typeLooseFileVector;
private:
AssetDefinition mAssetDefinition;
typeAssetIdVector mAssetDependencies;
typeLooseFileVector mAssetLooseFiles;
public:
TamlAssetDeclaredVisitor() { mAssetDefinition.reset(); }
virtual ~TamlAssetDeclaredVisitor() {}
inline AssetDefinition& getAssetDefinition( void ) { return mAssetDefinition; }
inline typeAssetIdVector& getAssetDependencies( void ) { return mAssetDependencies; }
inline typeLooseFileVector& getAssetLooseFiles( void ) { return mAssetLooseFiles; }
void clear( void ) { mAssetDefinition.reset(); mAssetDependencies.clear(); mAssetLooseFiles.clear(); }
virtual bool wantsPropertyChanges( void ) { return false; }
virtual bool wantsRootOnly( void ) { return false; }
virtual bool visit( const TamlParser& parser, TamlVisitor::PropertyState& propertyState )
{
// Debug Profiling.
PROFILE_SCOPE(TamlAssetDeclaredVisitor_Visit);
// Fetch property name and value.
StringTableEntry propertyName = propertyState.getPropertyName();
const char* pPropertyValue = propertyState.getPropertyValue();
// Is this the root object?
if ( propertyState.isRootObject() )
{
// Yes, so is the asset type set yet?
if ( mAssetDefinition.mAssetType == StringTable->EmptyString() )
{
// No, set set asset type and base file-path.
mAssetDefinition.mAssetType = propertyState.getObjectName();
mAssetDefinition.mAssetBaseFilePath = parser.getParsingFilename();
}
// Asset name?
if ( propertyName == assetNameField )
{
// Yes, so assign it.
mAssetDefinition.mAssetName = StringTable->insert( pPropertyValue );
return true;
}
// Asset description?
else if ( propertyName == assetDescriptionField )
{
// Yes, so assign it.
mAssetDefinition.mAssetDescription = StringTable->insert( pPropertyValue );
return true;
}
// Asset description?
else if ( propertyName == assetCategoryField )
{
// Yes, so assign it.
mAssetDefinition.mAssetCategory = StringTable->insert( pPropertyValue );
return true;
}
// Asset auto-unload?
else if ( propertyName == assetAutoUnloadField )
{
// Yes, so assign it.
mAssetDefinition.mAssetAutoUnload = dAtob( pPropertyValue );
return true;
}
// Asset internal?
else if ( propertyName == assetInternalField )
{
// Yes, so assign it.
mAssetDefinition.mAssetInternal = dAtob( pPropertyValue );
return true;
}
}
// Fetch property word count.
const U32 propertyWordCount = StringUnit::getUnitCount( pPropertyValue, ASSET_ASSIGNMENT_TOKEN );
// Finish if there's not two words.
if ( propertyWordCount != 2 )
return true;
// Fetch the asset signature.
StringTableEntry assetSignature = StringTable->insert( StringUnit::getUnit( pPropertyValue, 0, ASSET_ASSIGNMENT_TOKEN ) );
// Is this an asset Id signature?
if ( assetSignature == assetLooseIdSignature )
{
// Yes, so get asset Id.
typeAssetId assetId = StringTable->insert( StringUnit::getUnit( pPropertyValue, 1, ASSET_ASSIGNMENT_TOKEN ) );
// Finish if the dependency is itself!
if ( mAssetDefinition.mAssetId == assetId )
return true;
// Iterate existing dependencies.
for( typeAssetIdVector::iterator dependencyItr = mAssetDependencies.begin(); dependencyItr != mAssetDependencies.end(); ++dependencyItr )
{
// Finish if asset Id is already a dependency.
if ( *dependencyItr == assetId )
return true;
}
// Insert asset reference.
mAssetDependencies.push_back( assetId );
}
// Is this a loose-file signature?
else if ( assetSignature == assetLooseFileSignature )
{
// Yes, so get loose-file reference.
const char* pAssetLooseFile = StringUnit::getUnit( pPropertyValue, 1, ASSET_ASSIGNMENT_TOKEN );
// Fetch asset path only.
char assetBasePathBuffer[1024];
dSprintf( assetBasePathBuffer, sizeof(assetBasePathBuffer), "%s", mAssetDefinition.mAssetBaseFilePath );
char* pFinalSlash = dStrrchr( assetBasePathBuffer, '/' );
if ( pFinalSlash != NULL ) *pFinalSlash = 0;
// Expand the path in the usual way.
char assetFilePathBuffer[1024];
Con::expandPath( assetFilePathBuffer, sizeof(assetFilePathBuffer), pAssetLooseFile, assetBasePathBuffer );
// Insert asset loose-file.
mAssetLooseFiles.push_back( StringTable->insert( assetFilePathBuffer ) );
}
return true;
}
};
#endif // _TAML_ASSET_DECLARED_VISITOR_H_

View file

@ -0,0 +1,127 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _TAML_ASSET_REFERENCED_UPDATE_VISITOR_H_
#define _TAML_ASSET_REFERENCED_UPDATE_VISITOR_H_
#ifndef _TAML_VISITOR_H_
#include "persistence/taml/tamlVisitor.h"
#endif
#ifndef _TAML_PARSER_H_
#include "persistence\/taml/tamlParser.h"
#endif
#ifndef _STRINGUNIT_H_
#include "string/stringUnit.h"
#endif
#ifndef _STRINGTABLE_H_
#include "string/stringTable.h"
#endif
#ifndef _ASSET_FIELD_TYPES_H_
#include "assets/assetFieldTypes.h"
#endif
// Debug Profiling.
#include "platform/profiler.h"
//-----------------------------------------------------------------------------
class TamlAssetReferencedUpdateVisitor : public TamlVisitor
{
private:
StringTableEntry mAssetIdFrom;
StringTableEntry mAssetIdTo;
public:
TamlAssetReferencedUpdateVisitor() {}
virtual ~TamlAssetReferencedUpdateVisitor() {}
void setAssetIdFrom( const char* pAssetIdFrom )
{
// Sanity!
AssertFatal( pAssetIdFrom != NULL, "Asset Id from cannot be NULL." );
mAssetIdFrom = StringTable->insert( pAssetIdFrom );
}
StringTableEntry getAssetIdFrom( void ) const { return mAssetIdFrom; }
void setAssetIdTo( const char* pAssetIdTo )
{
// Sanity!
AssertFatal( pAssetIdTo != NULL, "Asset Id to cannot be NULL." );
mAssetIdTo = StringTable->insert( pAssetIdTo );
}
const char* getAssetIdTo( void ) const { return mAssetIdTo; }
virtual bool wantsPropertyChanges( void ) { return true; }
virtual bool wantsRootOnly( void ) { return false; }
virtual bool visit( const TamlParser& parser, TamlVisitor::PropertyState& propertyState )
{
// Debug Profiling.
PROFILE_SCOPE(TamlAssetReferencedUpdateVisitor_Visit);
// Fetch the property value.
const char* pPropertyValue = propertyState.getPropertyValue();
// Fetch property value word count.
const U32 valueWordCount = StringUnit::getUnitCount( pPropertyValue, ASSET_ASSIGNMENT_TOKEN );
// Finish if not two words.
if ( valueWordCount != 2 )
return true;
// Finish if this is not an asset signature.
if ( dStricmp( StringUnit::getUnit( pPropertyValue, 0, ASSET_ASSIGNMENT_TOKEN), assetLooseIdSignature ) != 0 )
return true;
// Get the asset value.
const char* pAssetValue = StringUnit::getUnit( pPropertyValue, 1, ASSET_ASSIGNMENT_TOKEN );
// Finish if not the asset Id we're looking for.
if ( dStricmp( pAssetValue, mAssetIdFrom ) != 0 )
return true;
// Is the target asset empty?
if ( mAssetIdTo == StringTable->EmptyString() )
{
// Yes, so update the property as empty.
propertyState.updatePropertyValue(StringTable->EmptyString());
return true;
}
// Format asset.
char assetBuffer[1024];
dSprintf( assetBuffer, sizeof(assetBuffer), "%s%s%s", assetLooseIdSignature, ASSET_ASSIGNMENT_TOKEN, mAssetIdTo );
// Assign new value.
propertyState.updatePropertyValue( assetBuffer );
return true;
}
};
#endif // _TAML_ASSET_REFERENCED_UPDATE_VISITOR_H_

View file

@ -0,0 +1,96 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _TAML_ASSET_REFERENCED_VISITOR_H_
#define _TAML_ASSET_REFERENCED_VISITOR_H_
#ifndef _TAML_VISITOR_H_
#include "persistence/taml/tamlVisitor.h"
#endif
#ifndef _TAML_PARSER_H_
#include "persistence/taml/tamlParser.h"
#endif
#ifndef _ASSET_FIELD_TYPES_H_
#include "assets/assetFieldTypes.h"
#endif
// Debug Profiling.
#include "platform/profiler.h"
//-----------------------------------------------------------------------------
class TamlAssetReferencedVisitor : public TamlVisitor
{
public:
typedef StringTableEntry typeAssetId;
typedef HashMap<typeAssetId, StringTableEntry> typeAssetReferencedHash;
private:
typeAssetReferencedHash mAssetReferenced;
public:
TamlAssetReferencedVisitor() {}
virtual ~TamlAssetReferencedVisitor() {}
const typeAssetReferencedHash& getAssetReferencedMap( void ) const { return mAssetReferenced; }
void clear( void ) { mAssetReferenced.clear(); }
virtual bool wantsPropertyChanges( void ) { return false; }
virtual bool wantsRootOnly( void ) { return false; }
virtual bool visit( const TamlParser& parser, TamlVisitor::PropertyState& propertyState )
{
// Debug Profiling.
PROFILE_SCOPE(TamlAssetReferencedVisitor_Visit);
// Fetch property value.
const char* pPropertyValue = propertyState.getPropertyValue();
// Fetch property word count.
const U32 propertyWordCount = StringUnit::getUnitCount( pPropertyValue, ASSET_ASSIGNMENT_TOKEN );
// Finish if there's not two words.
if ( propertyWordCount != 2 )
return true;
// Finish if the first word is not an asset signature.
if ( StringTable->insert( StringUnit::getUnit( pPropertyValue, 0, ASSET_ASSIGNMENT_TOKEN ) ) != assetLooseIdSignature )
return true;
// Get asset Id.
typeAssetId assetId = StringTable->insert( StringUnit::getUnit( pPropertyValue, 1, ASSET_ASSIGNMENT_TOKEN ) );
// Finish if we already have this asset Id.
if ( mAssetReferenced.contains( assetId ) )
return true;
// Insert asset reference.
mAssetReferenced.insert( assetId, StringTable->EmptyString() );
return true;
}
};
#endif // _TAML_ASSET_REFERENCED_VISITOR_H_

View file

@ -209,6 +209,13 @@ namespace Con
return ret;
}
char* getBoolArg(bool arg)
{
char *ret = STR.getArgBuffer(32);
dSprintf(ret, 32, "%d", arg);
return ret;
}
char *getStringArg( const char *arg )
{
U32 len = dStrlen( arg ) + 1;

View file

@ -1566,6 +1566,494 @@ void popInstantGroup()
}
}
typedef HashMap<StringTableEntry, StringTableEntry> typePathExpandoMap;
static typePathExpandoMap PathExpandos;
//-----------------------------------------------------------------------------
void addPathExpando(const char* pExpandoName, const char* pPath)
{
// Sanity!
AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
AssertFatal(pPath != NULL, "Expando path cannot be NULL.");
// Fetch expando name.
StringTableEntry expandoName = StringTable->insert(pExpandoName);
// Fetch the length of the path.
S32 pathLength = dStrlen(pPath);
char pathBuffer[1024];
// Sanity!
if (pathLength == 0 || pathLength >= sizeof(pathBuffer))
{
Con::warnf("Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath);
return;
}
// Strip repeat slashes.
if (!Con::stripRepeatSlashes(pathBuffer, pPath, sizeof(pathBuffer)))
{
Con::warnf("Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath);
return;
}
// Fetch new path length.
pathLength = dStrlen(pathBuffer);
// Sanity!
if (pathLength == 0)
{
Con::warnf("Cannot add path expando '%s' with path '%s' as the path is an invalid length.", pExpandoName, pPath);
return;
}
// Remove any terminating slash.
if (pathBuffer[pathLength - 1] == '/')
pathBuffer[pathLength - 1] = 0;
// Fetch expanded path.
StringTableEntry expandedPath = StringTable->insert(pathBuffer);
// Info.
#if defined(TORQUE_DEBUG)
Con::printf("Adding path expando of '%s' as '%s'.", expandoName, expandedPath);
#endif
// Find any existing path expando.
typePathExpandoMap::iterator expandoItr = PathExpandos.find(pExpandoName);
// Does the expando exist?
if (expandoItr != PathExpandos.end())
{
// Yes, so modify the path.
expandoItr->value = expandedPath;
return;
}
// Insert expando.
PathExpandos.insert(expandoName, expandedPath);
}
//-----------------------------------------------------------------------------
StringTableEntry getPathExpando(const char* pExpandoName)
{
// Sanity!
AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
// Fetch expando name.
StringTableEntry expandoName = StringTable->insert(pExpandoName);
// Find any existing path expando.
typePathExpandoMap::iterator expandoItr = PathExpandos.find(expandoName);
// Does the expando exist?
if (expandoItr != PathExpandos.end())
{
// Yes, so return it.
return expandoItr->value;
}
// Not found.
return NULL;
}
//-----------------------------------------------------------------------------
void removePathExpando(const char* pExpandoName)
{
// Sanity!
AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
// Fetch expando name.
StringTableEntry expandoName = StringTable->insert(pExpandoName);
// Find any existing path expando.
typePathExpandoMap::iterator expandoItr = PathExpandos.find(expandoName);
// Does the expando exist?
if (expandoItr == PathExpandos.end())
{
// No, so warn.
#if defined(TORQUE_DEBUG)
Con::warnf("Removing path expando of '%s' but it does not exist.", expandoName);
#endif
return;
}
// Info.
#if defined(TORQUE_DEBUG)
Con::printf("Removing path expando of '%s' as '%s'.", expandoName, expandoItr->value);
#endif
// Remove expando.
PathExpandos.erase(expandoItr);
}
//-----------------------------------------------------------------------------
bool isPathExpando(const char* pExpandoName)
{
// Sanity!
AssertFatal(pExpandoName != NULL, "Expando name cannot be NULL.");
// Fetch expando name.
StringTableEntry expandoName = StringTable->insert(pExpandoName);
return PathExpandos.contains(expandoName);
}
//-----------------------------------------------------------------------------
U32 getPathExpandoCount(void)
{
return PathExpandos.size();
}
//-----------------------------------------------------------------------------
StringTableEntry getPathExpandoKey(U32 expandoIndex)
{
// Finish if index is out of range.
if (expandoIndex >= PathExpandos.size())
return NULL;
// Find indexed iterator.
typePathExpandoMap::iterator expandoItr = PathExpandos.begin();
while (expandoIndex > 0) { ++expandoItr; --expandoIndex; }
return expandoItr->key;
}
//-----------------------------------------------------------------------------
StringTableEntry getPathExpandoValue(U32 expandoIndex)
{
// Finish if index is out of range.
if (expandoIndex >= PathExpandos.size())
return NULL;
// Find indexed iterator.
typePathExpandoMap::iterator expandoItr = PathExpandos.begin();
while (expandoIndex > 0) { ++expandoItr; --expandoIndex; }
return expandoItr->value;
}
//-----------------------------------------------------------------------------
bool expandPath(char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint, const bool ensureTrailingSlash)
{
char pathBuffer[2048];
const char* pSrc = pSrcPath;
char* pSlash;
// Fetch leading character.
const char leadingToken = *pSrc;
// Fetch following token.
const char followingToken = leadingToken != 0 ? pSrc[1] : 0;
// Expando.
if (leadingToken == '^')
{
// Initial prefix search.
const char* pPrefixSrc = pSrc + 1;
char* pPrefixDst = pathBuffer;
// Search for end of expando.
while (*pPrefixSrc != '/' && *pPrefixSrc != 0)
{
// Copy prefix character.
*pPrefixDst++ = *pPrefixSrc++;
}
// Yes, so terminate the expando string.
*pPrefixDst = 0;
// Fetch the expando path.
StringTableEntry expandoPath = getPathExpando(pathBuffer);
// Does the expando exist?
if (expandoPath == NULL)
{
// No, so error.
Con::errorf("expandPath() : Could not find path expando '%s' for path '%s'.", pathBuffer, pSrcPath);
// Are we ensuring the trailing slash?
if (ensureTrailingSlash)
{
// Yes, so ensure it.
Con::ensureTrailingSlash(pDstPath, pSrcPath);
}
else
{
// No, so just use the source path.
dStrcpy(pDstPath, pSrcPath);
}
return false;
}
// Skip the expando and the following slash.
pSrc += dStrlen(pathBuffer) + 1;
// Format the output path.
dSprintf(pathBuffer, sizeof(pathBuffer), "%s/%s", expandoPath, pSrc);
// Are we ensuring the trailing slash?
if (ensureTrailingSlash)
{
// Yes, so ensure it.
Con::ensureTrailingSlash(pathBuffer, pathBuffer);
}
// Strip repeat slashes.
Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
return true;
}
// Script-Relative.
if (leadingToken == '.')
{
// Fetch the code-block file-path.
const StringTableEntry codeblockFullPath = CodeBlock::getCurrentCodeBlockFullPath();
// Do we have a code block full path?
if (codeblockFullPath == NULL)
{
// No, so error.
Con::errorf("expandPath() : Could not find relative path from code-block for path '%s'.", pSrcPath);
// Are we ensuring the trailing slash?
if (ensureTrailingSlash)
{
// Yes, so ensure it.
Con::ensureTrailingSlash(pDstPath, pSrcPath);
}
else
{
// No, so just use the source path.
dStrcpy(pDstPath, pSrcPath);
}
return false;
}
// Yes, so use it as the prefix.
dStrncpy(pathBuffer, codeblockFullPath, sizeof(pathBuffer) - 1);
// Find the final slash in the code-block.
pSlash = dStrrchr(pathBuffer, '/');
// Is this a parent directory token?
if (followingToken == '.')
{
// Yes, so terminate after the slash so we include it.
pSlash[1] = 0;
}
else
{
// No, it's a current directory token so terminate at the slash so we don't include it.
pSlash[0] = 0;
// Skip the current directory token.
pSrc++;
}
// Format the output path.
dStrncat(pathBuffer, "/", sizeof(pathBuffer) - 1 - strlen(pathBuffer));
dStrncat(pathBuffer, pSrc, sizeof(pathBuffer) - 1 - strlen(pathBuffer));
// Are we ensuring the trailing slash?
if (ensureTrailingSlash)
{
// Yes, so ensure it.
Con::ensureTrailingSlash(pathBuffer, pathBuffer);
}
// Strip repeat slashes.
Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
return true;
}
// All else.
//Using a special case here because the code below barfs on trying to build a full path for apk reading
#ifdef TORQUE_OS_ANDROID
if (leadingToken == '/' || strstr(pSrcPath, "/") == NULL)
Platform::makeFullPathName(pSrcPath, pathBuffer, sizeof(pathBuffer), pWorkingDirectoryHint);
else
dSprintf(pathBuffer, sizeof(pathBuffer), "/%s", pSrcPath);
#else
Platform::makeFullPathName(pSrcPath, pathBuffer, sizeof(pathBuffer), pWorkingDirectoryHint);
#endif
// Are we ensuring the trailing slash?
if (ensureTrailingSlash)
{
// Yes, so ensure it.
Con::ensureTrailingSlash(pathBuffer, pathBuffer);
}
// Strip repeat slashes.
Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
return true;
}
//-----------------------------------------------------------------------------
bool isBasePath(const char* SrcPath, const char* pBasePath)
{
char expandBuffer[1024];
Con::expandPath(expandBuffer, sizeof(expandBuffer), SrcPath);
return dStrnicmp(pBasePath, expandBuffer, dStrlen(pBasePath)) == 0;
}
//-----------------------------------------------------------------------------
void collapsePath(char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint)
{
// Check path against expandos. If there are multiple matches, choose the
// expando that produces the shortest relative path.
char pathBuffer[2048];
// Fetch expando count.
const U32 expandoCount = getPathExpandoCount();
// Iterate expandos.
U32 expandoRelativePathLength = U32_MAX;
for (U32 expandoIndex = 0; expandoIndex < expandoCount; ++expandoIndex)
{
// Fetch expando value (path).
StringTableEntry expandoValue = getPathExpandoValue(expandoIndex);
// Skip if not the base path.
if (!isBasePath(pSrcPath, expandoValue))
continue;
// Fetch path relative to expando path.
StringTableEntry relativePath = Platform::makeRelativePathName(pSrcPath, expandoValue);
// If the relative path is simply a period
if (relativePath[0] == '.')
relativePath++;
if (dStrlen(relativePath) > expandoRelativePathLength)
{
// This expando covers less of the path than any previous one found.
// We will keep the previous one.
continue;
}
// Keep track of the relative path length
expandoRelativePathLength = dStrlen(relativePath);
// Fetch expando key (name).
StringTableEntry expandoName = getPathExpandoKey(expandoIndex);
// Format against expando.
dSprintf(pathBuffer, sizeof(pathBuffer), "^%s/%s", expandoName, relativePath);
}
// Check if we've found a suitable expando
if (expandoRelativePathLength != U32_MAX)
{
// Strip repeat slashes.
Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
return;
}
// Fetch the working directory.
StringTableEntry workingDirectory = pWorkingDirectoryHint != NULL ? pWorkingDirectoryHint : Platform::getCurrentDirectory();
// Fetch path relative to current directory.
StringTableEntry relativePath = Platform::makeRelativePathName(pSrcPath, workingDirectory);
// If the relative path is simply a period
if (relativePath[0] == '.' && relativePath[1] != '.')
relativePath++;
// Format against expando.
dSprintf(pathBuffer, sizeof(pathBuffer), "%s/%s", workingDirectory, relativePath);
// Strip repeat slashes.
Con::stripRepeatSlashes(pDstPath, pathBuffer, size);
}
void ensureTrailingSlash(char* pDstPath, const char* pSrcPath)
{
// Copy to target.
dStrcpy(pDstPath, pSrcPath);
// Find trailing character index.
S32 trailIndex = dStrlen(pDstPath);
// Ignore if empty string.
if (trailIndex == 0)
return;
// Finish if the trailing slash already exists.
if (pDstPath[trailIndex - 1] == '/')
return;
// Add trailing slash.
pDstPath[trailIndex++] = '/';
pDstPath[trailIndex] = 0;
}
//-----------------------------------------------------------------------------
bool stripRepeatSlashes(char* pDstPath, const char* pSrcPath, S32 dstSize)
{
// Note original destination.
char* pOriginalDst = pDstPath;
// Reset last source character.
char lastSrcChar = 0;
// Search source...
while (dstSize > 0)
{
// Fetch characters.
const char srcChar = *pSrcPath++;
// Do we have a repeat slash?
if (srcChar == '/' && lastSrcChar == '/')
{
// Yes, so skip it.
continue;
}
// No, so copy character.
*pDstPath++ = srcChar;
// Finish if end of source.
if (srcChar == 0)
return true;
// Reduce room left in destination.
dstSize--;
// Set last character.
lastSrcChar = srcChar;
}
// Terminate the destination string as we ran out of room.
*pOriginalDst = 0;
// Fail!
return false;
}
} // end of Console namespace
#endif

View file

@ -486,6 +486,20 @@ namespace Con
bool expandToolScriptFilename(char *filename, U32 size, const char *src);
bool collapseScriptFilename(char *filename, U32 size, const char *src);
bool expandPath(char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint = NULL, const bool ensureTrailingSlash = false);
void collapsePath(char* pDstPath, U32 size, const char* pSrcPath, const char* pWorkingDirectoryHint = NULL);
bool isBasePath(const char* SrcPath, const char* pBasePath);
void ensureTrailingSlash(char* pDstPath, const char* pSrcPath);
bool stripRepeatSlashes(char* pDstPath, const char* pSrcPath, S32 dstSize);
void addPathExpando(const char* pExpandoName, const char* pPath);
void removePathExpando(const char* pExpandoName);
bool isPathExpando(const char* pExpandoName);
StringTableEntry getPathExpando(const char* pExpandoName);
U32 getPathExpandoCount(void);
StringTableEntry getPathExpandoKey(U32 expandoIndex);
StringTableEntry getPathExpandoValue(U32 expandoIndex);
bool isCurrentScriptToolScript();
StringTableEntry getModNameFromPath(const char *path);
@ -739,6 +753,13 @@ namespace Con
/// @see Con::errorf()
void errorf(ConsoleLogEntry::Type type, const char *_format, ...);
//some additions from t2d
/// Prints a separator to the console.
inline void printSeparator(void) { printf("--------------------------------------------------------------------------------"); }
/// Prints a separator to the console.
inline void printBlankLine(void) { printf(""); }
/// @}
/// Returns true when called from the main thread, false otherwise
@ -815,6 +836,7 @@ namespace Con
char* getArgBuffer(U32 bufferSize);
char* getFloatArg(F64 arg);
char* getIntArg (S32 arg);
char* getBoolArg(bool arg);
char* getStringArg( const char* arg );
char* getStringArg( const String& arg );
/// @}

View file

@ -55,7 +55,25 @@ bool AbstractClassRep::initialized = false;
//-----------------------------------------------------------------------------
AbstractClassRep* AbstractClassRep::findFieldRoot(StringTableEntry fieldName)
{
// Find the field.
const Field* pField = findField(fieldName);
// Finish if not found.
if (pField == NULL)
return NULL;
// We're the root if we have no parent.
if (getParentClass() == NULL)
return this;
// Find the field root via the parent.
AbstractClassRep* pFieldRoot = getParentClass()->findFieldRoot(fieldName);
// We're the root if the parent does not have it else return the field root.
return pFieldRoot == NULL ? this : pFieldRoot;
}
void AbstractClassRep::init()
{
@ -349,6 +367,7 @@ void ConsoleObject::addGroup(const char* in_pGroupname, const char* in_pGroupDoc
f.validator = NULL;
f.setDataFn = &defaultProtectedSetFn;
f.getDataFn = &defaultProtectedGetFn;
f.writeDataFn = &defaultProtectedWriteFn;
// Add to field list.
sg_tempFieldList.push_back(f);
@ -371,6 +390,7 @@ void ConsoleObject::endGroup(const char* in_pGroupname)
f.validator = NULL;
f.setDataFn = &defaultProtectedSetFn;
f.getDataFn = &defaultProtectedGetFn;
f.writeDataFn = &defaultProtectedWriteFn;
f.elementCount = 0;
// Add to field list.
@ -393,6 +413,7 @@ void ConsoleObject::addArray( const char *arrayName, S32 count )
f.validator = NULL;
f.setDataFn = &defaultProtectedSetFn;
f.getDataFn = &defaultProtectedGetFn;
f.writeDataFn = &defaultProtectedWriteFn;
// Add to field list.
sg_tempFieldList.push_back(f);
@ -412,6 +433,7 @@ void ConsoleObject::endArray( const char *arrayName )
f.validator = NULL;
f.setDataFn = &defaultProtectedSetFn;
f.getDataFn = &defaultProtectedGetFn;
f.writeDataFn = &defaultProtectedWriteFn;
f.elementCount = 0;
// Add to field list.
@ -433,13 +455,77 @@ void ConsoleObject::addField(const char* in_pFieldname,
flags );
}
void ConsoleObject::addField(const char* in_pFieldname,
const U32 in_fieldType,
const dsize_t in_fieldOffset,
AbstractClassRep::WriteDataNotify in_writeDataFn,
const char* in_pFieldDocs,
U32 flags)
{
addField(
in_pFieldname,
in_fieldType,
in_fieldOffset,
in_writeDataFn,
1,
in_pFieldDocs,
flags);
}
void ConsoleObject::addField(const char* in_pFieldname,
const U32 in_fieldType,
const dsize_t in_fieldOffset,
const U32 in_elementCount,
const char* in_pFieldDocs,
U32 flags)
{
addField(in_pFieldname,
in_fieldType,
in_fieldOffset,
&defaultProtectedWriteFn,
in_elementCount,
in_pFieldDocs,
flags);
}
void ConsoleObject::addField(const char* in_pFieldname,
const U32 in_fieldType,
const dsize_t in_fieldOffset,
AbstractClassRep::WriteDataNotify in_writeDataFn,
const U32 in_elementCount,
const char* in_pFieldDocs,
U32 flags)
{
AbstractClassRep::Field f;
f.pFieldname = StringTable->insert(in_pFieldname);
if (in_pFieldDocs)
f.pFieldDocs = in_pFieldDocs;
f.type = in_fieldType;
f.offset = in_fieldOffset;
f.elementCount = in_elementCount;
f.validator = NULL;
f.flag = flags;
f.setDataFn = &defaultProtectedSetFn;
f.getDataFn = &defaultProtectedGetFn;
f.writeDataFn = in_writeDataFn;
ConsoleBaseType* conType = ConsoleBaseType::getType(in_fieldType);
AssertFatal(conType, "ConsoleObject::addField - invalid console type");
f.table = conType->getEnumTable();
sg_tempFieldList.push_back(f);
}
void ConsoleObject::addProtectedField(const char* in_pFieldname,
const U32 in_fieldType,
const dsize_t in_fieldOffset,
AbstractClassRep::SetDataNotify in_setDataFn,
AbstractClassRep::GetDataNotify in_getDataFn,
const char* in_pFieldDocs,
U32 flags )
const U32 in_fieldType,
const dsize_t in_fieldOffset,
AbstractClassRep::SetDataNotify in_setDataFn,
AbstractClassRep::GetDataNotify in_getDataFn,
const char* in_pFieldDocs,
U32 flags)
{
addProtectedField(
in_pFieldname,
@ -447,67 +533,81 @@ void ConsoleObject::addProtectedField(const char* in_pFieldname,
in_fieldOffset,
in_setDataFn,
in_getDataFn,
&defaultProtectedWriteFn,
1,
in_pFieldDocs,
flags );
}
void ConsoleObject::addField(const char* in_pFieldname,
const U32 in_fieldType,
const dsize_t in_fieldOffset,
const U32 in_elementCount,
const char* in_pFieldDocs,
U32 flags )
{
AbstractClassRep::Field f;
f.pFieldname = StringTable->insert(in_pFieldname);
if(in_pFieldDocs)
f.pFieldDocs = in_pFieldDocs;
f.type = in_fieldType;
f.offset = in_fieldOffset;
f.elementCount = in_elementCount;
f.validator = NULL;
f.flag = flags;
f.setDataFn = &defaultProtectedSetFn;
f.getDataFn = &defaultProtectedGetFn;
ConsoleBaseType* conType = ConsoleBaseType::getType( in_fieldType );
AssertFatal( conType, "ConsoleObject::addField - invalid console type" );
f.table = conType->getEnumTable();
sg_tempFieldList.push_back(f);
flags);
}
void ConsoleObject::addProtectedField(const char* in_pFieldname,
const U32 in_fieldType,
const dsize_t in_fieldOffset,
AbstractClassRep::SetDataNotify in_setDataFn,
AbstractClassRep::GetDataNotify in_getDataFn,
const U32 in_elementCount,
const char* in_pFieldDocs,
U32 flags )
const U32 in_fieldType,
const dsize_t in_fieldOffset,
AbstractClassRep::SetDataNotify in_setDataFn,
AbstractClassRep::GetDataNotify in_getDataFn,
AbstractClassRep::WriteDataNotify in_writeDataFn,
const char* in_pFieldDocs,
U32 flags)
{
addProtectedField(
in_pFieldname,
in_fieldType,
in_fieldOffset,
in_setDataFn,
in_getDataFn,
in_writeDataFn,
1,
in_pFieldDocs,
flags);
}
void ConsoleObject::addProtectedField(const char* in_pFieldname,
const U32 in_fieldType,
const dsize_t in_fieldOffset,
AbstractClassRep::SetDataNotify in_setDataFn,
AbstractClassRep::GetDataNotify in_getDataFn,
const U32 in_elementCount,
const char* in_pFieldDocs,
U32 flags)
{
addProtectedField(
in_pFieldname,
in_fieldType,
in_fieldOffset,
in_setDataFn,
in_getDataFn,
&defaultProtectedWriteFn,
1,
in_pFieldDocs,
flags);
}
void ConsoleObject::addProtectedField(const char* in_pFieldname,
const U32 in_fieldType,
const dsize_t in_fieldOffset,
AbstractClassRep::SetDataNotify in_setDataFn,
AbstractClassRep::GetDataNotify in_getDataFn,
AbstractClassRep::WriteDataNotify in_writeDataFn,
const U32 in_elementCount,
const char* in_pFieldDocs,
U32 flags)
{
AbstractClassRep::Field f;
f.pFieldname = StringTable->insert(in_pFieldname);
f.pFieldname = StringTable->insert(in_pFieldname);
if(in_pFieldDocs)
f.pFieldDocs = in_pFieldDocs;
if (in_pFieldDocs)
f.pFieldDocs = in_pFieldDocs;
f.type = in_fieldType;
f.offset = in_fieldOffset;
f.type = in_fieldType;
f.offset = in_fieldOffset;
f.elementCount = in_elementCount;
f.validator = NULL;
f.flag = flags;
f.validator = NULL;
f.flag = flags;
f.setDataFn = in_setDataFn;
f.getDataFn = in_getDataFn;
f.writeDataFn = in_writeDataFn;
ConsoleBaseType* conType = ConsoleBaseType::getType( in_fieldType );
AssertFatal( conType, "ConsoleObject::addProtectedField - invalid console type" );
ConsoleBaseType* conType = ConsoleBaseType::getType(in_fieldType);
AssertFatal(conType, "ConsoleObject::addProtectedField - invalid console type");
f.table = conType->getEnumTable();
sg_tempFieldList.push_back(f);
@ -529,6 +629,7 @@ void ConsoleObject::addFieldV(const char* in_pFieldname,
f.table = NULL;
f.setDataFn = &defaultProtectedSetFn;
f.getDataFn = &defaultProtectedGetFn;
f.writeDataFn = &defaultProtectedWriteFn;
f.validator = v;
v->fieldIndex = sg_tempFieldList.size();
@ -546,6 +647,7 @@ void ConsoleObject::addDeprecatedField(const char *fieldName)
f.validator = NULL;
f.setDataFn = &defaultProtectedSetFn;
f.getDataFn = &defaultProtectedGetFn;
f.writeDataFn = &defaultProtectedWriteFn;
sg_tempFieldList.push_back(f);
}

View file

@ -47,7 +47,9 @@
#ifndef _SIMOBJECTREF_H_
#include "console/simObjectRef.h"
#endif
#ifndef TINYXML_INCLUDED
#include "tinyXML/tinyxml.h"
#endif
/// @file
/// Legacy console object system.
@ -201,6 +203,9 @@ public:
typedef ConsoleBaseType Parent;
/// Allows the writing of a custom TAML schema.
typedef void(*WriteCustomTamlSchema)(const AbstractClassRep* pClassRep, TiXmlElement* pParentElement);
/// @name 'Tructors
/// @{
@ -321,6 +326,9 @@ public:
/// Return the AbstractClassRep of the class that this class is derived from.
AbstractClassRep* getParentClass() const { return parentClass; }
virtual AbstractClassRep* getContainerChildClass(const bool recurse) = 0;
virtual WriteCustomTamlSchema getCustomTamlSchema(void) = 0;
/// Return the size of instances of this class in bytes.
S32 getSizeof() const { return mClassSizeof; }
@ -376,6 +384,8 @@ public:
virtual ConsoleObject* create () const = 0;
AbstractClassRep* findFieldRoot(StringTableEntry fieldName);
protected:
virtual void init();
@ -421,6 +431,13 @@ public:
typedef bool (*SetDataNotify)( void *obj, const char *array, const char *data );
typedef const char *(*GetDataNotify)( void *obj, const char *data );
/// This is a function pointer typedef to support optional writing for fields.
typedef bool(*WriteDataNotify)(void* obj, StringTableEntry pFieldName);
/// Allows the writing of a custom TAML schema.
typedef void(*WriteCustomTamlSchema)(const AbstractClassRep* pClassRep, TiXmlElement* pParentElement);
/// These are special field type values used to mark
/// groups and arrays in the field list.
/// @see Field::type
@ -494,6 +511,7 @@ public:
TypeValidator *validator; ///< Validator, if any.
SetDataNotify setDataFn; ///< Set data notify Fn
GetDataNotify getDataFn; ///< Get data notify Fn
WriteDataNotify writeDataFn; ///< Function to determine whether data should be written or not.
};
typedef Vector<Field> FieldList;
@ -595,6 +613,27 @@ class ConcreteClassRep : public AbstractClassRep
registerClassRep(this);
};
virtual AbstractClassRep* getContainerChildClass(const bool recurse)
{
// Fetch container children type.
AbstractClassRep* pChildren = T::getContainerChildStaticClassRep();
if (!recurse || pChildren != NULL)
return pChildren;
// Fetch parent type.
AbstractClassRep* pParent = T::getParentStaticClassRep();
if (pParent == NULL)
return NULL;
// Get parent container children.
return pParent->getContainerChildClass(recurse);
}
virtual WriteCustomTamlSchema getCustomTamlSchema(void)
{
return T::getStaticWriteCustomTamlSchema();
}
/// Perform class specific initialization tasks.
///
/// Link namespaces, call initPersistFields() and consoleInit().
@ -652,7 +691,7 @@ template< typename T > EnginePropertyTable& ConcreteClassRep< T >::smPropertyTab
//------------------------------------------------------------------------------
// Forward declaration of this function so it can be used in the class
const char *defaultProtectedGetFn( void *obj, const char *data );
bool defaultProtectedWriteFn(void* obj, StringTableEntry pFieldName);
//=============================================================================
// ConsoleObject.
@ -781,6 +820,14 @@ public:
const char* in_pFieldDocs = NULL,
U32 flags = 0 );
static void addField(const char* in_pFieldname,
const U32 in_fieldType,
const dsize_t in_fieldOffset,
AbstractClassRep::WriteDataNotify in_writeDataFn,
const U32 in_elementCount = 1,
const char* in_pFieldDocs = NULL,
U32 flags = 0);
/// Register a simple field.
///
/// @param in_pFieldname Name of the field.
@ -793,6 +840,13 @@ public:
const char* in_pFieldDocs,
U32 flags = 0 );
static void addField(const char* in_pFieldname,
const U32 in_fieldType,
const dsize_t in_fieldOffset,
AbstractClassRep::WriteDataNotify in_writeDataFn,
const char* in_pFieldDocs,
U32 flags = 0);
/// Register a validated field.
///
/// A validated field is just like a normal field except that you can't
@ -821,10 +875,20 @@ public:
const U32 in_fieldType,
const dsize_t in_fieldOffset,
AbstractClassRep::SetDataNotify in_setDataFn,
AbstractClassRep::GetDataNotify in_getDataFn,
const U32 in_elementCount,
const char* in_pFieldDocs = NULL,
U32 flags = 0 );
AbstractClassRep::GetDataNotify in_getDataFn = &defaultProtectedGetFn,
AbstractClassRep::WriteDataNotify in_writeDataFn = &defaultProtectedWriteFn,
const U32 in_elementCount = 1,
const char* in_pFieldDocs = NULL,
U32 flags = 0);
static void addProtectedField(const char* in_pFieldname,
const U32 in_fieldType,
const dsize_t in_fieldOffset,
AbstractClassRep::SetDataNotify in_setDataFn,
AbstractClassRep::GetDataNotify in_getDataFn = &defaultProtectedGetFn,
const U32 in_elementCount = 1,
const char* in_pFieldDocs = NULL,
U32 flags = 0);
/// Register a simple protected field.
///
@ -839,8 +903,17 @@ public:
const dsize_t in_fieldOffset,
AbstractClassRep::SetDataNotify in_setDataFn,
AbstractClassRep::GetDataNotify in_getDataFn = &defaultProtectedGetFn,
AbstractClassRep::WriteDataNotify in_writeDataFn = &defaultProtectedWriteFn,
const char* in_pFieldDocs = NULL,
U32 flags = 0 );
U32 flags = 0);
static void addProtectedField(const char* in_pFieldname,
const U32 in_fieldType,
const dsize_t in_fieldOffset,
AbstractClassRep::SetDataNotify in_setDataFn,
AbstractClassRep::GetDataNotify in_getDataFn = &defaultProtectedGetFn,
const char* in_pFieldDocs = NULL,
U32 flags = 0);
/// Add a deprecated field.
///
@ -1045,6 +1118,8 @@ inline bool& ConsoleObject::getDynamicGroupExpand()
static AbstractClassRep* getParentStaticClassRep(); \
static AbstractClassRep* getStaticClassRep(); \
static SimObjectRefConsoleBaseType< className > ptrRefType; \
static AbstractClassRep::WriteCustomTamlSchema getStaticWriteCustomTamlSchema(); \
static AbstractClassRep* getContainerChildStaticClassRep(); \
virtual AbstractClassRep* getClassRep() const
#define DECLARE_CATEGORY( string ) \
@ -1061,6 +1136,44 @@ inline bool& ConsoleObject::getDynamicGroupExpand()
AbstractClassRep* className::getClassRep() const { return &className::dynClassRep; } \
AbstractClassRep* className::getStaticClassRep() { return &dynClassRep; } \
AbstractClassRep* className::getParentStaticClassRep() { return Parent::getStaticClassRep(); } \
AbstractClassRep* className::getContainerChildStaticClassRep() { return NULL; } \
AbstractClassRep::WriteCustomTamlSchema className::getStaticWriteCustomTamlSchema() { return NULL; } \
ConcreteClassRep<className> className::dynClassRep( #className, "Type" #className, &_smTypeId, 0, -1, 0, className::getParentStaticClassRep(), &Parent::__description )
#define IMPLEMENT_CONOBJECT_CHILDREN( className ) \
IMPLEMENT_CLASS( className, NULL ) \
END_IMPLEMENT_CLASS; \
S32 className::_smTypeId; \
SimObjectRefConsoleBaseType< className > className::ptrRefType( "Type" #className "Ref" ); \
AbstractClassRep* className::getClassRep() const { return &className::dynClassRep; } \
AbstractClassRep* className::getStaticClassRep() { return &dynClassRep; } \
AbstractClassRep* className::getParentStaticClassRep() { return Parent::getStaticClassRep(); } \
AbstractClassRep* className::getContainerChildStaticClassRep() { return Children::getStaticClassRep(); } \
AbstractClassRep::WriteCustomTamlSchema className::getStaticWriteCustomTamlSchema() { return NULL; } \
ConcreteClassRep<className> className::dynClassRep( #className, "Type" #className, &_smTypeId, 0, -1, 0, className::getParentStaticClassRep(), &Parent::__description )
#define IMPLEMENT_CONOBJECT_SCHEMA( className, schema ) \
IMPLEMENT_CLASS( className, NULL ) \
END_IMPLEMENT_CLASS; \
S32 className::_smTypeId; \
SimObjectRefConsoleBaseType< className > className::ptrRefType( "Type" #className "Ref" ); \
AbstractClassRep* className::getClassRep() const { return &className::dynClassRep; } \
AbstractClassRep* className::getStaticClassRep() { return &dynClassRep; } \
AbstractClassRep* className::getParentStaticClassRep() { return Parent::getStaticClassRep(); } \
AbstractClassRep* className::getContainerChildStaticClassRep() { return NULL; } \
AbstractClassRep::WriteCustomTamlSchema className::getStaticWriteCustomTamlSchema() { return schema; } \
ConcreteClassRep<className> className::dynClassRep( #className, "Type" #className, &_smTypeId, 0, -1, 0, className::getParentStaticClassRep(), &Parent::__description )
#define IMPLEMENT_CONOBJECT_CHILDREN_SCHEMA( className, schema ) \
IMPLEMENT_CLASS( className, NULL ) \
END_IMPLEMENT_CLASS; \
S32 className::_smTypeId; \
SimObjectRefConsoleBaseType< className > className::ptrRefType( "Type" #className "Ref" ); \
AbstractClassRep* className::getClassRep() const { return &className::dynClassRep; } \
AbstractClassRep* className::getStaticClassRep() { return &dynClassRep; } \
AbstractClassRep* className::getParentStaticClassRep() { return Parent::getStaticClassRep(); } \
AbstractClassRep* className::getContainerChildStaticClassRep() { return Children::getStaticClassRep(); } \
AbstractClassRep::WriteCustomTamlSchema className::getStaticWriteCustomTamlSchema() { return schema; } \
ConcreteClassRep<className> className::dynClassRep( #className, "Type" #className, &_smTypeId, 0, -1, 0, className::getParentStaticClassRep(), &Parent::__description )
#define IMPLEMENT_CO_NETOBJECT_V1( className ) \
@ -1071,6 +1184,8 @@ inline bool& ConsoleObject::getDynamicGroupExpand()
AbstractClassRep* className::getClassRep() const { return &className::dynClassRep; } \
AbstractClassRep* className::getStaticClassRep() { return &dynClassRep; } \
AbstractClassRep* className::getParentStaticClassRep() { return Parent::getStaticClassRep(); } \
AbstractClassRep* className::getContainerChildStaticClassRep() { return NULL; } \
AbstractClassRep::WriteCustomTamlSchema className::getStaticWriteCustomTamlSchema() { return NULL; } \
ConcreteClassRep<className> className::dynClassRep( #className, "Type" #className, &_smTypeId, NetClassGroupGameMask, NetClassTypeObject, 0, className::getParentStaticClassRep(), &Parent::__description )
#define IMPLEMENT_CO_DATABLOCK_V1( className ) \
@ -1081,6 +1196,8 @@ inline bool& ConsoleObject::getDynamicGroupExpand()
AbstractClassRep* className::getClassRep() const { return &className::dynClassRep; } \
AbstractClassRep* className::getStaticClassRep() { return &dynClassRep; } \
AbstractClassRep* className::getParentStaticClassRep() { return Parent::getStaticClassRep(); } \
AbstractClassRep* className::getContainerChildStaticClassRep() { return NULL; } \
AbstractClassRep::WriteCustomTamlSchema className::getStaticWriteCustomTamlSchema() { return NULL; } \
ConcreteClassRep<className> className::dynClassRep(#className, "Type" #className, &_smTypeId, NetClassGroupGameMask, NetClassTypeDataBlock, 0, className::getParentStaticClassRep(), &Parent::__description )
// Support for adding properties to classes CONOBJECT style.
@ -1133,6 +1250,21 @@ inline const char *emptyStringProtectedGetFn( void *obj, const char *data )
return "";
}
inline bool defaultProtectedWriteFn(void* obj, StringTableEntry pFieldName)
{
return true;
}
inline bool defaultProtectedNotSetFn(void* obj, const char *array, const char* data)
{
return false;
}
inline bool defaultProtectedNotWriteFn(void* obj, StringTableEntry pFieldName)
{
return false;
}
/// @}
#endif //_CONSOLEOBJECT_H_

View file

@ -34,7 +34,7 @@
//-----------------------------------------------------------------------------
// TypeString
//-----------------------------------------------------------------------------
ConsoleType( string, TypeString, const char* )
ConsoleType( string, TypeString, const char*, "" )
ImplementConsoleTypeCasters( TypeString, const char* );
ConsoleGetType( TypeString )
@ -53,7 +53,7 @@ ConsoleSetType( TypeString )
//-----------------------------------------------------------------------------
// TypeCaseString
//-----------------------------------------------------------------------------
ConsoleType( caseString, TypeCaseString, const char* )
ConsoleType(caseString, TypeCaseString, const char*, "")
ConsoleSetType( TypeCaseString )
{
@ -71,7 +71,7 @@ ConsoleGetType( TypeCaseString )
//-----------------------------------------------------------------------------
// TypeRealString
//-----------------------------------------------------------------------------
ConsoleType( string, TypeRealString, String )
ConsoleType(string, TypeRealString, String, "")
ImplementConsoleTypeCasters( TypeRealString, String )
ConsoleGetType( TypeRealString )
@ -94,7 +94,7 @@ ConsoleSetType( TypeRealString )
//-----------------------------------------------------------------------------
// TypeCommand
//-----------------------------------------------------------------------------
ConsoleType( string, TypeCommand, String )
ConsoleType(string, TypeCommand, String, "")
ConsoleGetType( TypeCommand )
{
@ -284,7 +284,7 @@ ConsoleProcessData( TypeShapeFilename )
//-----------------------------------------------------------------------------
// TypeS8
//-----------------------------------------------------------------------------
ConsoleType( char, TypeS8, S8 )
ConsoleType(char, TypeS8, S8, "")
ImplementConsoleTypeCasters( TypeS8, S8 )
ConsoleGetType( TypeS8 )
@ -306,7 +306,7 @@ ConsoleSetType( TypeS8 )
//-----------------------------------------------------------------------------
// TypeS32
//-----------------------------------------------------------------------------
ConsoleType( int, TypeS32, S32 )
ConsoleType(int, TypeS32, S32, "")
ImplementConsoleTypeCasters(TypeS32, S32)
ConsoleGetType( TypeS32 )
@ -329,7 +329,7 @@ ConsoleSetType( TypeS32 )
//-----------------------------------------------------------------------------
// TypeS32Vector
//-----------------------------------------------------------------------------
ConsoleType( intList, TypeS32Vector, Vector<S32> )
ConsoleType(intList, TypeS32Vector, Vector<S32>, "")
ImplementConsoleTypeCasters( TypeS32Vector, Vector< S32 > )
ConsoleGetType( TypeS32Vector )
@ -386,7 +386,7 @@ ConsoleSetType( TypeS32Vector )
//-----------------------------------------------------------------------------
// TypeF32
//-----------------------------------------------------------------------------
ConsoleType( float, TypeF32, F32 )
ConsoleType(float, TypeF32, F32, "")
ImplementConsoleTypeCasters(TypeF32, F32)
ConsoleGetType( TypeF32 )
@ -407,7 +407,7 @@ ConsoleSetType( TypeF32 )
//-----------------------------------------------------------------------------
// TypeF32Vector
//-----------------------------------------------------------------------------
ConsoleType( floatList, TypeF32Vector, Vector<F32> )
ConsoleType(floatList, TypeF32Vector, Vector<F32>, "")
ImplementConsoleTypeCasters( TypeF32Vector, Vector< F32 > )
ConsoleGetType( TypeF32Vector )
@ -464,7 +464,7 @@ ConsoleSetType( TypeF32Vector )
//-----------------------------------------------------------------------------
// TypeBool
//-----------------------------------------------------------------------------
ConsoleType( bool, TypeBool, bool )
ConsoleType(bool, TypeBool, bool, "")
ImplementConsoleTypeCasters( TypeBool, bool )
ConsoleGetType( TypeBool )
@ -484,7 +484,7 @@ ConsoleSetType( TypeBool )
//-----------------------------------------------------------------------------
// TypeBoolVector
//-----------------------------------------------------------------------------
ConsoleType( boolList, TypeBoolVector, Vector<bool> )
ConsoleType(boolList, TypeBoolVector, Vector<bool>, "")
ImplementConsoleTypeCasters( TypeBoolVector, Vector< bool > )
ConsoleGetType( TypeBoolVector )
@ -541,7 +541,7 @@ ConsoleSetType( TypeBoolVector )
//-----------------------------------------------------------------------------
// TypeFlag
//-----------------------------------------------------------------------------
ConsoleType( flag, TypeFlag, S32 )
ConsoleType(flag, TypeFlag, S32, "")
ConsoleGetType( TypeFlag )
{
@ -567,7 +567,7 @@ ConsoleSetType( TypeFlag )
//-----------------------------------------------------------------------------
// TypeColorF
//-----------------------------------------------------------------------------
ConsoleType( ColorF, TypeColorF, ColorF )
ConsoleType(ColorF, TypeColorF, ColorF, "")
ImplementConsoleTypeCasters( TypeColorF, ColorF )
ConsoleGetType( TypeColorF )
@ -640,7 +640,7 @@ ConsoleSetType( TypeColorF )
//-----------------------------------------------------------------------------
// TypeColorI
//-----------------------------------------------------------------------------
ConsoleType( ColorI, TypeColorI, ColorI )
ConsoleType(ColorI, TypeColorI, ColorI, "")
ImplementConsoleTypeCasters( TypeColorI, ColorI )
ConsoleGetType( TypeColorI )
@ -713,7 +713,7 @@ ConsoleSetType( TypeColorI )
//-----------------------------------------------------------------------------
// TypeSimObjectName
//-----------------------------------------------------------------------------
ConsoleType( SimObject, TypeSimObjectName, SimObject* )
ConsoleType(SimObject, TypeSimObjectName, SimObject*, "")
ConsoleSetType( TypeSimObjectName )
{
@ -738,7 +738,7 @@ ConsoleGetType( TypeSimObjectName )
//-----------------------------------------------------------------------------
// TypeName
//-----------------------------------------------------------------------------
ConsoleType( string, TypeName, const char* )
ConsoleType(string, TypeName, const char*, "")
ConsoleGetType( TypeName )
{
@ -753,7 +753,7 @@ ConsoleSetType( TypeName )
//------------------------------------------------------------------------------
// TypeParticleParameterString
//------------------------------------------------------------------------------
ConsoleType( string, TypeParticleParameterString, const char* )
ConsoleType(string, TypeParticleParameterString, const char*, "")
ConsoleGetType( TypeParticleParameterString )
{
@ -772,7 +772,7 @@ ConsoleSetType( TypeParticleParameterString )
// TypeMaterialName
//-----------------------------------------------------------------------------
ConsoleType( string, TypeMaterialName, String )
ConsoleType(string, TypeMaterialName, String, "")
ConsoleGetType( TypeMaterialName )
{
@ -794,7 +794,7 @@ ConsoleSetType( TypeMaterialName )
// TypeTerrainMaterialIndex
//-----------------------------------------------------------------------------
ConsoleType( int, TypeTerrainMaterialIndex, S32 )
ConsoleType(int, TypeTerrainMaterialIndex, S32, "")
ConsoleGetType( TypeTerrainMaterialIndex )
{
@ -816,7 +816,7 @@ ConsoleSetType( TypeTerrainMaterialIndex )
// TypeTerrainMaterialName
//-----------------------------------------------------------------------------
ConsoleType( string, TypeTerrainMaterialName, const char* )
ConsoleType(string, TypeTerrainMaterialName, const char*, "")
ConsoleGetType( TypeTerrainMaterialName )
{
@ -835,7 +835,7 @@ ConsoleSetType( TypeTerrainMaterialName )
// TypeCubemapName
//-----------------------------------------------------------------------------
ConsoleType( string, TypeCubemapName, String )
ConsoleType(string, TypeCubemapName, String, "")
ConsoleGetType( TypeCubemapName )
{
@ -856,7 +856,7 @@ ConsoleSetType( TypeCubemapName )
//-----------------------------------------------------------------------------
// TypeRectUV
//-----------------------------------------------------------------------------
ConsoleType( RectF, TypeRectUV, RectF )
ConsoleType(RectF, TypeRectUV, RectF, "")
ConsoleGetType( TypeRectUV )
{
@ -882,7 +882,7 @@ ConsoleSetType( TypeRectUV )
//-----------------------------------------------------------------------------
// TypeUUID
//-----------------------------------------------------------------------------
ConsoleType( uuid, TypeUUID, Torque::UUID )
ConsoleType(uuid, TypeUUID, Torque::UUID, "")
ImplementConsoleTypeCasters( TypeUUID, Torque::UUID )
ConsoleGetType( TypeUUID )
@ -906,7 +906,7 @@ ConsoleSetType( TypeUUID )
//-----------------------------------------------------------------------------
// TypePID
//-----------------------------------------------------------------------------
ConsoleType( pid, TypePID, SimPersistID* )
ConsoleType(pid, TypePID, SimPersistID*, "")
ImplementConsoleTypeCasters( TypePID, SimPersistID* )
ConsoleGetType( TypePID )
@ -945,7 +945,7 @@ ConsoleSetType( TypePID )
//-----------------------------------------------------------------------------
// TypeSimPersistId
//-----------------------------------------------------------------------------
ConsoleType( SimPersistId, TypeSimPersistId, SimPersistID* )
ConsoleType(SimPersistId, TypeSimPersistId, SimPersistID*, "")
ConsoleGetType( TypeSimPersistId )
{

View file

@ -35,6 +35,9 @@
#include "console/engineTypeInfo.h"
#endif
#ifndef _STRINGTABLE_H_
#include "core/stringTable.h"
#endif
/// @file
/// Support for legacy TorqueScript console types.
@ -151,6 +154,8 @@ class ConsoleBaseType
virtual const bool isDatablock() { return false; };
virtual const char* prepData( const char* data, char* buffer, U32 bufferLen ) { return data; };
virtual StringTableEntry getTypePrefix(void) const { return StringTable->EmptyString(); }
/// @}
};
@ -259,7 +264,7 @@ const EngineTypeInfo* _MAPTYPE() { return TYPE< T >(); }
DefineConsoleType( type, nativeType ) \
template<> inline const EngineTypeInfo* _MAPTYPE< nativeType >() { return NULL; }
#define ConsoleType( typeName, type, nativeType ) \
#define ConsoleType( typeName, type, nativeType, typePrefix ) \
S32 type; \
class ConsoleType##type : public ConsoleBaseType \
{ \
@ -275,6 +280,7 @@ const EngineTypeInfo* _MAPTYPE() { return TYPE< T >(); }
virtual const char *getTypeClassName() { return #typeName ; } \
virtual void *getNativeVariable() { T* var = new T; return (void*)var; } \
virtual void deleteNativeVariable(void* var) { T* nativeVar = reinterpret_cast<T*>(var); delete nativeVar; } \
virtual StringTableEntry getTypePrefix( void ) const { return StringTable->insert( typePrefix ); } \
}; \
ConsoleType ## type gConsoleType ## type ## Instance;
@ -304,6 +310,9 @@ const EngineTypeInfo* _MAPTYPE() { return TYPE< T >(); }
}; \
ConsoleType ## type gConsoleType ## type ## Instance;
#define ConsoleTypeFieldPrefix( type, typePrefix ) \
StringTableEntry ConsoleType##type::getTypePrefix( void ) const { return StringTable->insert( typePrefix ); }
#define ConsoleSetType( type ) \
void ConsoleType##type::setData(void *dptr, S32 argc, const char **argv, const EnumTable *tbl, BitSet32 flag)

View file

@ -60,6 +60,27 @@ public:
parentClass = parent;
};
virtual AbstractClassRep* getContainerChildClass(const bool recurse)
{
// Fetch container children type.
AbstractClassRep* pChildren = T::getContainerChildStaticClassRep();
if (!recurse || pChildren != NULL)
return pChildren;
// Fetch parent type.
AbstractClassRep* pParent = T::getParentStaticClassRep();
if (pParent == NULL)
return NULL;
// Get parent container children.
return pParent->getContainerChildClass(recurse);
}
virtual WriteCustomTamlSchema getCustomTamlSchema(void)
{
return T::getStaticWriteCustomTamlSchema();
}
/// Perform class specific initialization tasks.
///
/// Link namespaces, call initPersistFields() and consoleInit().

View file

@ -230,6 +230,11 @@ bool expandOldScriptFilename(char *filename, U32 size, const char *src)
else if (dStrncmp(src, "./", 2) == 0)
// dot path means load from current codeblock/mod path
slash = dStrrchr(cbName, '/');
else if (dStrncmp(src, "^", 1) == 0)
{
Platform::makeFullPathName(src + 1, filename, size);
return true;
}
else
{
// otherwise path must be fully specified

View file

@ -49,13 +49,13 @@ public:
Entry *next;
ConsoleBaseType *type;
};
private:
enum
{
HashTableSize = 19
};
Entry *mHashTable[HashTableSize];
private:
static Entry *smFreeList;
void freeEntry(Entry *entry);

View file

@ -34,7 +34,7 @@
#include "core/frameAllocator.h"
#include "core/stream/fileStream.h"
#include "core/fileObject.h"
#include "persistence/taml/tamlCustom.h"
IMPLEMENT_CONOBJECT( SimObject );
@ -437,6 +437,97 @@ SimPersistID* SimObject::getOrCreatePersistentId()
return mPersistentId;
}
void SimObject::onTamlCustomRead(TamlCustomNodes const& customNodes)
{
// Debug Profiling.
//PROFILE_SCOPE(SimObject_OnTamlCustomRead);
// Fetch field list.
const AbstractClassRep::FieldList& fieldList = getFieldList();
const U32 fieldCount = fieldList.size();
for (U32 index = 0; index < fieldCount; ++index)
{
// Fetch field.
const AbstractClassRep::Field* pField = &fieldList[index];
// Ignore if field not appropriate.
if (pField->type == AbstractClassRep::StartArrayFieldType || pField->elementCount > 1)
{
// Find cell custom node.
const TamlCustomNode* pCustomCellNodes = NULL;
if (pField->pGroupname != NULL)
pCustomCellNodes = customNodes.findNode(pField->pGroupname);
if (!pCustomCellNodes)
{
char* niceFieldName = const_cast<char *>(pField->pFieldname);
niceFieldName[0] = dToupper(niceFieldName[0]);
String str_niceFieldName = String(niceFieldName);
pCustomCellNodes = customNodes.findNode(str_niceFieldName + "s");
}
// Continue if we have explicit cells.
if (pCustomCellNodes != NULL)
{
// Fetch children cell nodes.
const TamlCustomNodeVector& cellNodes = pCustomCellNodes->getChildren();
U8 idx = 0;
// Iterate cells.
for (TamlCustomNodeVector::const_iterator cellNodeItr = cellNodes.begin(); cellNodeItr != cellNodes.end(); ++cellNodeItr)
{
char buf[5];
dSprintf(buf, 5, "%d", idx);
// Fetch cell node.
TamlCustomNode* pCellNode = *cellNodeItr;
// Fetch node name.
StringTableEntry nodeName = pCellNode->getNodeName();
// Is this a valid alias?
if (nodeName != pField->pFieldname)
{
// No, so warn.
Con::warnf("SimObject::onTamlCustomRead() - Encountered an unknown custom name of '%s'. Only '%s' is valid.", nodeName, pField->pFieldname);
continue;
}
// Fetch fields.
const TamlCustomFieldVector& fields = pCellNode->getFields();
// Iterate property fields.
for (TamlCustomFieldVector::const_iterator fieldItr = fields.begin(); fieldItr != fields.end(); ++fieldItr)
{
// Fetch field.
const TamlCustomField* pField = *fieldItr;
// Fetch field name.
StringTableEntry fieldName = pField->getFieldName();
const AbstractClassRep::Field* field = findField(fieldName);
// Check common fields.
if (field)
{
setDataField(fieldName, buf, pField->getFieldValue());
}
else
{
// Unknown name so warn.
Con::warnf("SimObject::onTamlCustomRead() - Encountered an unknown custom field name of '%s'.", fieldName);
continue;
}
}
idx++;
}
}
}
}
}
//-----------------------------------------------------------------------------
bool SimObject::_setPersistentID( void* object, const char* index, const char* data )
@ -925,6 +1016,220 @@ const char *SimObject::getDataField(StringTableEntry slotName, const char *array
return "";
}
const char *SimObject::getPrefixedDataField(StringTableEntry fieldName, const char *array)
{
// Sanity!
AssertFatal(fieldName != NULL, "Cannot get field value with NULL field name.");
// Fetch field value.
const char* pFieldValue = getDataField(fieldName, array);
// Sanity.
//AssertFatal(pFieldValue != NULL, "Field value cannot be NULL.");
if (!pFieldValue)
return NULL;
// Return without the prefix if there's no value.
if (*pFieldValue == 0)
return StringTable->EmptyString();
// Fetch the field prefix.
StringTableEntry fieldPrefix = getDataFieldPrefix(fieldName);
// Sanity!
AssertFatal(fieldPrefix != NULL, "Field prefix cannot be NULL.");
// Calculate a buffer size including prefix.
const U32 valueBufferSize = dStrlen(fieldPrefix) + dStrlen(pFieldValue) + 1;
// Fetch a buffer.
char* pValueBuffer = Con::getReturnBuffer(valueBufferSize);
// Format the value buffer.
dSprintf(pValueBuffer, valueBufferSize, "%s%s", fieldPrefix, pFieldValue);
return pValueBuffer;
}
//-----------------------------------------------------------------------------
void SimObject::setPrefixedDataField(StringTableEntry fieldName, const char *array, const char *value)
{
// Sanity!
AssertFatal(fieldName != NULL, "Cannot set object field value with NULL field name.");
AssertFatal(value != NULL, "Field value cannot be NULL.");
// Set value without prefix if there's no value.
if (*value == 0)
{
setDataField(fieldName, NULL, value);
return;
}
// Fetch the field prefix.
StringTableEntry fieldPrefix = getDataFieldPrefix(fieldName);
// Sanity.
AssertFatal(fieldPrefix != NULL, "Field prefix cannot be NULL.");
// Do we have a field prefix?
if (fieldPrefix == StringTable->EmptyString())
{
// No, so set the data field in the usual way.
setDataField(fieldName, NULL, value);
return;
}
// Yes, so fetch the length of the field prefix.
const U32 fieldPrefixLength = dStrlen(fieldPrefix);
// Yes, so does it start with the object field prefix?
if (dStrnicmp(value, fieldPrefix, fieldPrefixLength) != 0)
{
// No, so set the data field in the usual way.
setDataField(fieldName, NULL, value);
return;
}
// Yes, so set the data excluding the prefix.
setDataField(fieldName, NULL, value + fieldPrefixLength);
}
//-----------------------------------------------------------------------------
const char *SimObject::getPrefixedDynamicDataField(StringTableEntry fieldName, const char *array, const S32 fieldType)
{
// Sanity!
AssertFatal(fieldName != NULL, "Cannot get field value with NULL field name.");
// Fetch field value.
const char* pFieldValue = getDataField(fieldName, array);
// Sanity.
AssertFatal(pFieldValue != NULL, "Field value cannot be NULL.");
// Return the field if no field type is specified.
if (fieldType == -1)
return pFieldValue;
// Return without the prefix if there's no value.
if (*pFieldValue == 0)
return StringTable->EmptyString();
// Fetch the console base type.
ConsoleBaseType* pConsoleBaseType = ConsoleBaseType::getType(fieldType);
// Did we find the console base type?
if (pConsoleBaseType == NULL)
{
// No, so warn.
Con::warnf("getPrefixedDynamicDataField() - Invalid field type '%d' specified for field '%s' with value '%s'.",
fieldType, fieldName, pFieldValue);
}
// Fetch the field prefix.
StringTableEntry fieldPrefix = pConsoleBaseType->getTypePrefix();
// Sanity!
AssertFatal(fieldPrefix != NULL, "Field prefix cannot be NULL.");
// Calculate a buffer size including prefix.
const U32 valueBufferSize = dStrlen(fieldPrefix) + dStrlen(pFieldValue) + 1;
// Fetch a buffer.
char* pValueBuffer = Con::getReturnBuffer(valueBufferSize);
// Format the value buffer.
dSprintf(pValueBuffer, valueBufferSize, "%s%s", fieldPrefix, pFieldValue);
return pValueBuffer;
}
//-----------------------------------------------------------------------------
void SimObject::setPrefixedDynamicDataField(StringTableEntry fieldName, const char *array, const char *value, const S32 fieldType)
{
// Sanity!
AssertFatal(fieldName != NULL, "Cannot set object field value with NULL field name.");
AssertFatal(value != NULL, "Field value cannot be NULL.");
// Set value without prefix if no field type was specified.
if (fieldType == -1)
{
setDataField(fieldName, NULL, value);
return;
}
// Fetch the console base type.
ConsoleBaseType* pConsoleBaseType = ConsoleBaseType::getType(fieldType);
// Did we find the console base type?
if (pConsoleBaseType == NULL)
{
// No, so warn.
Con::warnf("setPrefixedDynamicDataField() - Invalid field type '%d' specified for field '%s' with value '%s'.",
fieldType, fieldName, value);
}
// Set value without prefix if there's no value or we didn't find the console base type.
if (*value == 0 || pConsoleBaseType == NULL)
{
setDataField(fieldName, NULL, value);
return;
}
// Fetch the field prefix.
StringTableEntry fieldPrefix = pConsoleBaseType->getTypePrefix();
// Sanity.
AssertFatal(fieldPrefix != NULL, "Field prefix cannot be NULL.");
// Do we have a field prefix?
if (fieldPrefix == StringTable->EmptyString())
{
// No, so set the data field in the usual way.
setDataField(fieldName, NULL, value);
return;
}
// Yes, so fetch the length of the field prefix.
const U32 fieldPrefixLength = dStrlen(fieldPrefix);
// Yes, so does it start with the object field prefix?
if (dStrnicmp(value, fieldPrefix, fieldPrefixLength) != 0)
{
// No, so set the data field in the usual way.
setDataField(fieldName, NULL, value);
return;
}
// Yes, so set the data excluding the prefix.
setDataField(fieldName, NULL, value + fieldPrefixLength);
}
//-----------------------------------------------------------------------------
StringTableEntry SimObject::getDataFieldPrefix(StringTableEntry fieldName)
{
// Sanity!
AssertFatal(fieldName != NULL, "Cannot get field prefix with NULL field name.");
// Find the field.
const AbstractClassRep::Field* pField = findField(fieldName);
// Return nothing if field was not found.
if (pField == NULL)
return StringTable->EmptyString();
// Yes, so fetch the console base type.
ConsoleBaseType* pConsoleBaseType = ConsoleBaseType::getType(pField->type);
// Fetch the type prefix.
return pConsoleBaseType->getTypePrefix();
}
//-----------------------------------------------------------------------------
U32 SimObject::getDataFieldType( StringTableEntry slotName, const char* array )

View file

@ -33,6 +33,9 @@
#include "core/bitSet.h"
#endif
#ifndef _TAML_CALLBACKS_H_
#include "persistence/taml/tamlCallbacks.h"
#endif
class Stream;
class LightManager;
@ -226,7 +229,7 @@ class SimPersistID;
/// set automatically by the console constructor code.
///
/// @nosubgrouping
class SimObject: public ConsoleObject
class SimObject: public ConsoleObject, public TamlCallbacks
{
public:
@ -298,6 +301,8 @@ class SimObject: public ConsoleObject
/// Flags internal to the object management system.
BitSet32 mFlags;
StringTableEntry mProgenitorFile;
/// Object we are copying fields from.
SimObject* mCopySource;
@ -348,13 +353,42 @@ class SimObject: public ConsoleObject
static bool setSuperClass(void *object, const char *index, const char *data)
{ static_cast<SimObject*>(object)->setSuperClassNamespace(data); return false; };
static bool writeObjectName(void* obj, StringTableEntry pFieldName)
{ SimObject* simObject = static_cast<SimObject*>(obj); return simObject->objectName != NULL && simObject->objectName != StringTable->EmptyString(); }
static bool writeCanSaveDynamicFields(void* obj, StringTableEntry pFieldName)
{ return static_cast<SimObject*>(obj)->mCanSaveFieldDictionary == false; }
static bool writeInternalName(void* obj, StringTableEntry pFieldName)
{ SimObject* simObject = static_cast<SimObject*>(obj); return simObject->mInternalName != NULL && simObject->mInternalName != StringTable->EmptyString(); }
static bool setParentGroup(void* obj, const char* data);
static bool writeParentGroup(void* obj, StringTableEntry pFieldName)
{ return static_cast<SimObject*>(obj)->mGroup != NULL; }
static bool writeSuperclass(void* obj, StringTableEntry pFieldName)
{ SimObject* simObject = static_cast<SimObject*>(obj); return simObject->mSuperClassName != NULL && simObject->mSuperClassName != StringTable->EmptyString(); }
static bool writeClass(void* obj, StringTableEntry pFieldName)
{ SimObject* simObject = static_cast<SimObject*>(obj); return simObject->mClassName != NULL && simObject->mClassName != StringTable->EmptyString(); }
static bool writeClassName(void* obj, StringTableEntry pFieldName)
{ SimObject* simObject = static_cast<SimObject*>(obj); return simObject->mClassName != NULL && simObject->mClassName != StringTable->EmptyString(); }
// Group hierarchy protected set method
static bool setProtectedParent(void *object, const char *index, const char *data);
// Object name protected set method
static bool setProtectedName(void *object, const char *index, const char *data);
public:
inline void setProgenitorFile(const char* pFile) { mProgenitorFile = StringTable->insert(pFile); }
inline StringTableEntry getProgenitorFile(void) const { return mProgenitorFile; }
protected:
/// Taml callbacks.
virtual void onTamlPreWrite(void) {}
virtual void onTamlPostWrite(void) {}
virtual void onTamlPreRead(void) {}
virtual void onTamlPostRead(const TamlCustomNodes& customNodes) {}
virtual void onTamlAddParent(SimObject* pParentObject) {}
virtual void onTamlCustomWrite(TamlCustomNodes& customNodes) {}
virtual void onTamlCustomRead(const TamlCustomNodes& customNodes);
/// Id number for this object.
SimObjectId mId;
@ -461,6 +495,16 @@ class SimObject: public ConsoleObject
/// @param value Value to store.
void setDataField(StringTableEntry slotName, const char *array, const char *value);
const char *getPrefixedDataField(StringTableEntry fieldName, const char *array);
void setPrefixedDataField(StringTableEntry fieldName, const char *array, const char *value);
const char *getPrefixedDynamicDataField(StringTableEntry fieldName, const char *array, const S32 fieldType = -1);
void setPrefixedDynamicDataField(StringTableEntry fieldName, const char *array, const char *value, const S32 fieldType = -1);
StringTableEntry getDataFieldPrefix(StringTableEntry fieldName);
/// Get the type of a field on the object.
///
/// @param slotName Field to access.

View file

@ -39,6 +39,7 @@
#include "core/util/tSignal.h"
#endif
#include "persistence/taml/tamlChildren.h"
//---------------------------------------------------------------------------
/// A set of SimObjects.
@ -89,7 +90,7 @@
/// }
/// @endcode
///
class SimSet: public SimObject
class SimSet : public SimObject, public TamlChildren
{
public:
@ -152,8 +153,10 @@ class SimSet: public SimObject
iterator end() { return objectList.end(); }
value operator[] (S32 index) { return objectList[U32(index)]; }
iterator find( iterator first, iterator last, SimObject *obj)
inline iterator find( iterator first, iterator last, SimObject *obj)
{ return ::find(first, last, obj); }
inline iterator find(SimObject *obj)
{ return ::find(begin(), end(), obj); }
/// Reorder the position of "obj" to either be the last object in the list or, if
/// "target" is given, to come before "target" in the list of children.
@ -222,7 +225,7 @@ class SimSet: public SimObject
/// @note The child sets themselves count towards the total too.
U32 sizeRecursive();
SimObject* findObjectByInternalName(StringTableEntry internalName, bool searchChildren = false);
virtual SimObject* findObjectByInternalName(StringTableEntry internalName, bool searchChildren = false);
SimObject* findObjectByLineNumber(const char* fileName, S32 declarationLine, bool searchChildren = false);
/// Find the given object in this set. Returns NULL if the object
@ -277,6 +280,32 @@ class SimSet: public SimObject
virtual bool readObject(Stream *stream);
virtual SimSet* clone();
// TamlChildren
virtual U32 getTamlChildCount(void) const
{
return (U32)size();
}
virtual SimObject* getTamlChild(const U32 childIndex) const
{
// Sanity!
AssertFatal(childIndex < (U32)size(), "SimSet::getTamlChild() - Child index is out of range.");
// For when the assert is not used.
if (childIndex >= (U32)size())
return NULL;
return at(childIndex);
}
virtual void addTamlChild(SimObject* pSimObject)
{
// Sanity!
AssertFatal(pSimObject != NULL, "SimSet::addTamlChild() - Cannot add a NULL child object.");
addObject(pSimObject);
}
};
#ifdef TORQUE_DEBUG_GUARD

View file

@ -0,0 +1,86 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _FACTORY_CACHE_H_
#define _FACTORY_CACHE_H_
#ifndef _TVECTOR_H_
#include "core/util/tVector.h"
#endif
//-----------------------------------------------------------------------------
class IFactoryObjectReset
{
public:
virtual void resetState( void ) = 0;
};
//-----------------------------------------------------------------------------
template<class T>
class FactoryCache : private Vector<T*>
{
public:
FactoryCache()
{
}
virtual ~FactoryCache()
{
purgeCache();
}
T* createObject( void )
{
// Create a new object if cache is empty.
if ( this->size() == 0 )
return new T();
// Return a cached object.
T* pObject = this->back();
this->pop_back();
return pObject;
}
void cacheObject( T* pObject )
{
// Cache object.
this->push_back( pObject );
// Reset object state if available.
IFactoryObjectReset* pResetStateObject = dynamic_cast<IFactoryObjectReset*>( pObject );
if ( pResetStateObject != NULL )
pResetStateObject->resetState();
}
void purgeCache( void )
{
while( this->size() > 0 )
{
delete this->back();
this->pop_back();
}
}
};
#endif // _FACTORY_CACHE_H_

View file

@ -46,14 +46,14 @@ bool Module::_constrainedToComeBefore( Module* module, Mode mode )
Module* depModule = dependency->mModule;
if( !depModule )
{
depModule = ModuleManager::findModule( dependency->mModuleName );
depModule = EngineModuleManager::findModule( dependency->mModuleName );
if( !depModule )
{
// Module does not exist. Only emit a warning here so that modules
// can be omitted from a link without requiring the module definitions
// to be adapted.
Platform::outputDebugString( "[ModuleManager] Module %s of '%s' depends on module '%s' which does not exist",
Platform::outputDebugString( "[EngineModuleManager] Module %s of '%s' depends on module '%s' which does not exist",
mode == Module::ModeInitialize ? "init" : "shutdown",
module->getName(), dependency->mModuleName );
continue;
@ -86,14 +86,14 @@ bool Module::_constrainedToComeAfter( Module* module, Mode mode )
Module* depModule = dependency->mModule;
if( !depModule )
{
depModule = ModuleManager::findModule( dependency->mModuleName );
depModule = EngineModuleManager::findModule( dependency->mModuleName );
if( !depModule )
{
// Module does not exist. Only emit a warning here so that modules
// can be omitted from a link without requiring the module definitions
// to be adapted.
Platform::outputDebugString( "[ModuleManager] Module %s of '%s' depends on module '%s' which does not exist",
Platform::outputDebugString( "[EngineModuleManager] Module %s of '%s' depends on module '%s' which does not exist",
mode == Module::ModeInitialize ? "init" : "shutdown",
module->getName(), dependency->mModuleName );
continue;
@ -115,7 +115,7 @@ bool Module::_constrainedToComeAfter( Module* module, Mode mode )
//-----------------------------------------------------------------------------
String ModuleManager::_moduleListToString( Vector< Module* >& moduleList )
String EngineModuleManager::_moduleListToString( Vector< Module* >& moduleList )
{
StringBuilder str;
@ -136,14 +136,14 @@ String ModuleManager::_moduleListToString( Vector< Module* >& moduleList )
//-----------------------------------------------------------------------------
void ModuleManager::_printModuleList( Vector< Module* >& moduleList )
void EngineModuleManager::_printModuleList( Vector< Module* >& moduleList )
{
Platform::outputDebugString( _moduleListToString( moduleList ) );
}
//-----------------------------------------------------------------------------
void ModuleManager::_insertIntoModuleList( Module::Mode mode, Vector< Module* >& moduleList, Module* module )
void EngineModuleManager::_insertIntoModuleList( Module::Mode mode, Vector< Module* >& moduleList, Module* module )
{
// If this module is being overridden, switch over to
// the module overriding it.
@ -168,7 +168,7 @@ void ModuleManager::_insertIntoModuleList( Module::Mode mode, Vector< Module* >&
if( !module->_getDependencies( mode ) )
{
#if defined( DEBUG_SPEW ) && DEBUG_SPEW_LEVEL > 1
Platform::outputDebugString( "[ModuleManager] Appending '%s' to '%s'",
Platform::outputDebugString( "[EngineModuleManager] Appending '%s' to '%s'",
module->getName(), _moduleListToString( moduleList ).c_str() );
#endif
@ -179,7 +179,7 @@ void ModuleManager::_insertIntoModuleList( Module::Mode mode, Vector< Module* >&
// First make sure that all 'after' dependencies are in the list.
#if defined( DEBUG_SPEW ) && DEBUG_SPEW_LEVEL > 1
Platform::outputDebugString( "[ModuleManager] Resolving %s dependencies of '%s'",
Platform::outputDebugString( "[EngineModuleManager] Resolving %s dependencies of '%s'",
mode == Module::ModeInitialize ? "init" : "shutdown",
module->getName() );
#endif
@ -199,7 +199,7 @@ void ModuleManager::_insertIntoModuleList( Module::Mode mode, Vector< Module* >&
}
AssertFatal( _getIndexOfModuleInList( moduleList, module ) == -1,
avar( "ModuleManager::_insertModuleIntoList - Cycle in 'after' %s dependency chain of '%s'",
avar( "EngineModuleManager::_insertModuleIntoList - Cycle in 'after' %s dependency chain of '%s'",
mode == Module::ModeInitialize ? "init" : "shutdown",
module->getName() ) );
@ -212,7 +212,7 @@ void ModuleManager::_insertIntoModuleList( Module::Mode mode, Vector< Module* >&
const bool currentAfterThis = moduleList[ i ]->_constrainedToComeAfter( module, mode );
AssertFatal( !( thisBeforeCurrent && currentAfterThis ),
avar( "ModuleManager::_insertModuleIntoList - Ambiguous %s placement of module '%s' relative to '%s'",
avar( "EngineModuleManager::_insertModuleIntoList - Ambiguous %s placement of module '%s' relative to '%s'",
mode == Module::ModeInitialize ? "init" : "shutdown",
module->getName(), moduleList[ i ]->getName() ) );
@ -232,7 +232,7 @@ void ModuleManager::_insertIntoModuleList( Module::Mode mode, Vector< Module* >&
if( thisBeforeCurrent && !moduleList[ i ]->_getDependencies( mode ) && i != numModules - 1 )
{
#if defined( DEBUG_SPEW ) && DEBUG_SPEW_LEVEL > 1
Platform::outputDebugString( "[ModuleManager] Pushing '%s' to back end of chain for resolving '%s'",
Platform::outputDebugString( "[EngineModuleManager] Pushing '%s' to back end of chain for resolving '%s'",
moduleList[ i ]->getName(), module->getName() );
#endif
@ -251,7 +251,7 @@ void ModuleManager::_insertIntoModuleList( Module::Mode mode, Vector< Module* >&
for( U32 n = i + 1; n < numModules; ++ n )
AssertFatal( !( moduleList[ n ]->_constrainedToComeBefore( module, mode )
|| module->_constrainedToComeAfter( moduleList[ n ], mode ) ),
avar( "ModuleManager::_insertModuleIntoList - Ambiguous %s constraint on module '%s' to come before '%s' yet after '%s'",
avar( "EngineModuleManager::_insertModuleIntoList - Ambiguous %s constraint on module '%s' to come before '%s' yet after '%s'",
mode == Module::ModeInitialize ? "init" : "shutdown",
module->getName(),
moduleList[ i ]->getName(),
@ -260,7 +260,7 @@ void ModuleManager::_insertIntoModuleList( Module::Mode mode, Vector< Module* >&
// Add the module at this position.
#if defined( DEBUG_SPEW ) && DEBUG_SPEW_LEVEL > 1
Platform::outputDebugString( "[ModuleManager] Inserting '%s' at index %i into '%s'",
Platform::outputDebugString( "[EngineModuleManager] Inserting '%s' at index %i into '%s'",
module->getName(), i, _moduleListToString( moduleList ).c_str() );
#endif
@ -271,7 +271,7 @@ void ModuleManager::_insertIntoModuleList( Module::Mode mode, Vector< Module* >&
// No constraint-based position. Just append.
#if defined( DEBUG_SPEW ) && DEBUG_SPEW_LEVEL > 1
Platform::outputDebugString( "[ModuleManager] Appending '%s' to '%s'",
Platform::outputDebugString( "[EngineModuleManager] Appending '%s' to '%s'",
module->getName(), _moduleListToString( moduleList ).c_str() );
#endif
@ -280,7 +280,7 @@ void ModuleManager::_insertIntoModuleList( Module::Mode mode, Vector< Module* >&
//-----------------------------------------------------------------------------
Module* ModuleManager::_findOverrideFor( Module* module )
Module* EngineModuleManager::_findOverrideFor( Module* module )
{
const char* name = module->getName();
@ -294,7 +294,7 @@ Module* ModuleManager::_findOverrideFor( Module* module )
//-----------------------------------------------------------------------------
S32 ModuleManager::_getIndexOfModuleInList( Vector< Module* >& moduleList, Module* module )
S32 EngineModuleManager::_getIndexOfModuleInList( Vector< Module* >& moduleList, Module* module )
{
const U32 numModules = moduleList.size();
for( U32 i = 0; i < numModules; ++ i )
@ -306,7 +306,7 @@ S32 ModuleManager::_getIndexOfModuleInList( Vector< Module* >& moduleList, Modul
//-----------------------------------------------------------------------------
S32 ModuleManager::_getIndexOfModuleInList( Vector< Module* >& moduleList, const char* moduleName )
S32 EngineModuleManager::_getIndexOfModuleInList( Vector< Module* >& moduleList, const char* moduleName )
{
const U32 numModules = moduleList.size();
for( U32 i = 0; i < numModules; ++ i )
@ -318,7 +318,7 @@ S32 ModuleManager::_getIndexOfModuleInList( Vector< Module* >& moduleList, const
//-----------------------------------------------------------------------------
void ModuleManager::_createModuleList( Module::Mode mode, Vector< Module* >& moduleList )
void EngineModuleManager::_createModuleList( Module::Mode mode, Vector< Module* >& moduleList )
{
for( Module* module = Module::smFirst; module != NULL; module = module->mNext )
_insertIntoModuleList( mode, moduleList, module );
@ -326,7 +326,7 @@ void ModuleManager::_createModuleList( Module::Mode mode, Vector< Module* >& mod
//-----------------------------------------------------------------------------
void ModuleManager::initializeSystem()
void EngineModuleManager::initializeSystem()
{
Vector< Module* > modules;
@ -339,7 +339,7 @@ void ModuleManager::initializeSystem()
if( !module->mIsInitialized )
{
#ifdef DEBUG_SPEW
Platform::outputDebugString( "[ModuleManager] Initializing %s",
Platform::outputDebugString( "[EngineModuleManager] Initializing %s",
module->getName() );
#endif
@ -351,7 +351,7 @@ void ModuleManager::initializeSystem()
//-----------------------------------------------------------------------------
void ModuleManager::shutdownSystem()
void EngineModuleManager::shutdownSystem()
{
Vector< Module* > modules;
@ -363,7 +363,7 @@ void ModuleManager::shutdownSystem()
if( modules[ i ]->mIsInitialized )
{
#ifdef DEBUG_SPEW
Platform::outputDebugString( "[ModuleManager] Shutting down %s",
Platform::outputDebugString( "[EngineModuleManager] Shutting down %s",
modules[ i ]->getName() );
#endif
@ -375,7 +375,7 @@ void ModuleManager::shutdownSystem()
//-----------------------------------------------------------------------------
Module* ModuleManager::findModule( const char* name )
Module* EngineModuleManager::findModule( const char* name )
{
for( Module* module = Module::smFirst; module != NULL; module = module->mNext )
if( dStricmp( module->getName(), name ) == 0 )

View file

@ -42,7 +42,7 @@ class Module
public:
typedef void Parent;
friend struct ModuleManager;
friend struct EngineModuleManager;
protected:
@ -333,7 +333,7 @@ class Module
void _AfterModuleInit::initialize()
struct ModuleManager
struct EngineModuleManager
{
/// Initialize all modules registered with the system.
static void initializeSystem();

View file

@ -123,6 +123,19 @@ void Stream::writeString(const char *string, S32 maxLen)
write(len, string);
}
bool Stream::writeFormattedBuffer(const char *format, ...)
{
char buffer[4096];
va_list args;
va_start(args, format);
const S32 length = vsprintf(buffer, format, args);
// Sanity!
AssertFatal(length <= sizeof(buffer), "writeFormattedBuffer - String format exceeded buffer size. This will cause corruption.");
return write(length, buffer);
}
void Stream::readString(char buf[256])
{
U8 len;

View file

@ -29,7 +29,9 @@
#ifndef _ENDIAN_H_
#include "core/util/endian.h"
#endif
#ifndef _STRINGFUNCTIONS_H_
#include "core/strings/stringFunctions.h"
#endif
/// @defgroup stream_overload Primitive Type Stream Operation Overloads
/// These macros declare the read and write functions for all primitive types.
@ -130,12 +132,21 @@ public:
/// writeString is safer.
void writeLongString(U32 maxStringLen, const char *string);
inline bool Put(char character) { return write(character); }
/// Write raw text to the stream
void writeText(const char *text);
/// Writes a string to the stream.
virtual void writeString(const char *stringBuf, S32 maxLen=255);
/// Writes a formatted buffer to the stream.
/// NOTE: A maximum string length of 4K is allowed.
bool writeFormattedBuffer(const char *format, ...);
/// Writes a NULL terminated string buffer.
bool writeStringBuffer(const char* buffer) { return write(dStrlen(buffer), buffer); }
// read/write real strings
void write(const String & str) { _write(str); }
void read(String * str) { _read(str); }

View file

@ -863,5 +863,167 @@ inline Value& Map<Key,Value,Sequence>::operator[](const Key& key)
return mMap.findOrInsert(key)->value;
}
//-----------------------------------------------------------------------------
// iterator class
/// A HashMap template class.
/// The map class maps between a key and an associated value. Keys
/// are unique.
/// The hash table class is used as the default implementation so the
/// the key must be hashable, see util/hash.h for details.
/// @ingroup UtilContainers
template<typename Key, typename Value, class Sequence = HashTable<Key, Value> >
class HashMap : private Sequence
{
typedef HashTable<Key, Value> Parent;
private:
Sequence mHashMap;
public:
// types
typedef typename Parent::Pair Pair;
typedef Pair ValueType;
typedef Pair& Reference;
typedef const Pair& ConstReference;
typedef typename Parent::Iterator iterator;
typedef typename Parent::ConstIterator const_iterator;
typedef S32 DifferenceType;
typedef U32 SizeType;
// initialization
HashMap() {}
~HashMap() {}
HashMap(const HashMap& p);
// management
U32 size() const; ///< Return the number of elements
void clear(); ///< Empty the HashMap
bool isEmpty() const; ///< Returns true if the map is empty
// insert & erase elements
iterator insert(const Key& key, const Value&); // Documented below...
void erase(iterator); ///< Erase the given entry
void erase(const Key& key); ///< Erase the key from the map
// HashMap lookup
iterator find(const Key&); ///< Find entry for the given key
const_iterator find(const Key&) const; ///< Find entry for the given key
bool contains(const Key&a)
{
return mHashMap.count(a) > 0;
}
// forward iterator access
iterator begin(); ///< iterator to first element
const_iterator begin() const; ///< iterator to first element
iterator end(); ///< IIterator to last element + 1
const_iterator end() const; ///< iterator to last element + 1
// operators
Value& operator[](const Key&); ///< Index using the given key. If the key is not currently in the map it is added.
};
template<typename Key, typename Value, class Sequence> HashMap<Key, Value, Sequence>::HashMap(const HashMap& p)
{
*this = p;
}
//-----------------------------------------------------------------------------
// management
template<typename Key, typename Value, class Sequence>
inline U32 HashMap<Key, Value, Sequence>::size() const
{
return mHashMap.size();
}
template<typename Key, typename Value, class Sequence>
inline void HashMap<Key, Value, Sequence>::clear()
{
mHashMap.clear();
}
template<typename Key, typename Value, class Sequence>
inline bool HashMap<Key, Value, Sequence>::isEmpty() const
{
return mHashMap.isEmpty();
}
//-----------------------------------------------------------------------------
// add & remove elements
/// Insert the key value pair but don't allow duplicates.
/// The map class does not allow duplicates keys. If the key already exists in
/// the map the function will fail and return end().
template<typename Key, typename Value, class Sequence>
typename HashMap<Key, Value, Sequence>::iterator HashMap<Key, Value, Sequence>::insert(const Key& key, const Value& x)
{
return mHashMap.insertUnique(key, x);
}
template<typename Key, typename Value, class Sequence>
void HashMap<Key, Value, Sequence>::erase(const Key& key)
{
mHashMap.erase(key);
}
template<typename Key, typename Value, class Sequence>
void HashMap<Key, Value, Sequence>::erase(iterator node)
{
mHashMap.erase(node);
}
//-----------------------------------------------------------------------------
// Searching
template<typename Key, typename Value, class Sequence>
typename HashMap<Key, Value, Sequence>::iterator HashMap<Key, Value, Sequence>::find(const Key& key)
{
return mHashMap.find(key);
}
//-----------------------------------------------------------------------------
// iterator access
template<typename Key, typename Value, class Sequence>
inline typename HashMap<Key, Value, Sequence>::iterator HashMap<Key, Value, Sequence>::begin()
{
return mHashMap.begin();
}
template<typename Key, typename Value, class Sequence>
inline typename HashMap<Key, Value, Sequence>::const_iterator HashMap<Key, Value, Sequence>::begin() const
{
return mHashMap.begin();
}
template<typename Key, typename Value, class Sequence>
inline typename HashMap<Key, Value, Sequence>::iterator HashMap<Key, Value, Sequence>::end()
{
return mHashMap.end();
}
template<typename Key, typename Value, class Sequence>
inline typename HashMap<Key, Value, Sequence>::const_iterator HashMap<Key, Value, Sequence>::end() const
{
return mHashMap.end();
}
//-----------------------------------------------------------------------------
// operators
template<typename Key, typename Value, class Sequence>
inline Value& HashMap<Key, Value, Sequence>::operator[](const Key& key)
{
return mHashMap.findOrInsert(key)->value;
}
#endif

View file

@ -717,7 +717,7 @@ IMPLEMENT_STRUCT( RectSpacingI,
END_IMPLEMENT_STRUCT;
ConsoleType( RectSpacingI, TypeRectSpacingI, RectSpacingI )
ConsoleType(RectSpacingI, TypeRectSpacingI, RectSpacingI, "")
ImplementConsoleTypeCasters( TypeRectSpacingI, RectSpacingI )
ConsoleGetType( TypeRectSpacingI )

View file

@ -37,6 +37,7 @@
#include "math/mEase.h"
#include "math/mathUtils.h"
#include "core/strings/stringUnit.h"
IMPLEMENT_SCOPE( MathTypes, Math,, "" );
@ -117,7 +118,7 @@ END_IMPLEMENT_STRUCT;
//-----------------------------------------------------------------------------
// TypePoint2I
//-----------------------------------------------------------------------------
ConsoleType( Point2I, TypePoint2I, Point2I )
ConsoleType(Point2I, TypePoint2I, Point2I, "")
ImplementConsoleTypeCasters( TypePoint2I, Point2I )
ConsoleGetType( TypePoint2I )
@ -142,7 +143,7 @@ ConsoleSetType( TypePoint2I )
//-----------------------------------------------------------------------------
// TypePoint2F
//-----------------------------------------------------------------------------
ConsoleType( Point2F, TypePoint2F, Point2F )
ConsoleType(Point2F, TypePoint2F, Point2F, "")
ImplementConsoleTypeCasters( TypePoint2F, Point2F )
ConsoleGetType( TypePoint2F )
@ -167,7 +168,7 @@ ConsoleSetType( TypePoint2F )
//-----------------------------------------------------------------------------
// TypePoint3I
//-----------------------------------------------------------------------------
ConsoleType( Point3I, TypePoint3I, Point3I )
ConsoleType(Point3I, TypePoint3I, Point3I, "")
ImplementConsoleTypeCasters(TypePoint3I, Point3I)
ConsoleGetType( TypePoint3I )
@ -192,7 +193,7 @@ ConsoleSetType( TypePoint3I )
//-----------------------------------------------------------------------------
// TypePoint3F
//-----------------------------------------------------------------------------
ConsoleType( Point3F, TypePoint3F, Point3F )
ConsoleType(Point3F, TypePoint3F, Point3F, "")
ImplementConsoleTypeCasters(TypePoint3F, Point3F)
ConsoleGetType( TypePoint3F )
@ -217,7 +218,7 @@ ConsoleSetType( TypePoint3F )
//-----------------------------------------------------------------------------
// TypePoint4F
//-----------------------------------------------------------------------------
ConsoleType( Point4F, TypePoint4F, Point4F )
ConsoleType(Point4F, TypePoint4F, Point4F, "")
ImplementConsoleTypeCasters( TypePoint4F, Point4F )
ConsoleGetType( TypePoint4F )
@ -242,7 +243,7 @@ ConsoleSetType( TypePoint4F )
//-----------------------------------------------------------------------------
// TypeRectI
//-----------------------------------------------------------------------------
ConsoleType( RectI, TypeRectI, RectI )
ConsoleType(RectI, TypeRectI, RectI, "")
ImplementConsoleTypeCasters( TypeRectI, RectI )
ConsoleGetType( TypeRectI )
@ -269,7 +270,7 @@ ConsoleSetType( TypeRectI )
//-----------------------------------------------------------------------------
// TypeRectF
//-----------------------------------------------------------------------------
ConsoleType( RectF, TypeRectF, RectF )
ConsoleType(RectF, TypeRectF, RectF, "")
ImplementConsoleTypeCasters( TypeRectF, RectF )
ConsoleGetType( TypeRectF )
@ -296,7 +297,7 @@ ConsoleSetType( TypeRectF )
//-----------------------------------------------------------------------------
// TypeMatrix
//-----------------------------------------------------------------------------
ConsoleType( MatrixF, TypeMatrixF, MatrixF )
ConsoleType(MatrixF, TypeMatrixF, MatrixF, "")
ImplementConsoleTypeCasters( TypeMatrixF, MatrixF )
// Oh merry confusion. Torque stores matrices in row-major order yet to TorqueScript
@ -339,7 +340,7 @@ ConsoleSetType( TypeMatrixF )
//-----------------------------------------------------------------------------
// TypeMatrixPosition
//-----------------------------------------------------------------------------
ConsoleType( MatrixPosition, TypeMatrixPosition, MatrixF )
ConsoleType(MatrixPosition, TypeMatrixPosition, MatrixF, "")
ConsoleGetType( TypeMatrixPosition )
{
@ -374,7 +375,7 @@ ConsoleSetType( TypeMatrixPosition )
//-----------------------------------------------------------------------------
// TypeMatrixRotation
//-----------------------------------------------------------------------------
ConsoleType( MatrixRotation, TypeMatrixRotation, MatrixF )
ConsoleType(MatrixRotation, TypeMatrixRotation, MatrixF, "")
ConsoleGetType( TypeMatrixRotation )
{
@ -419,7 +420,7 @@ ConsoleSetType( TypeMatrixRotation )
//-----------------------------------------------------------------------------
// TypeAngAxisF
//-----------------------------------------------------------------------------
ConsoleType( AngAxisF, TypeAngAxisF, AngAxisF )
ConsoleType(AngAxisF, TypeAngAxisF, AngAxisF, "")
ImplementConsoleTypeCasters( TypeAngAxisF, AngAxisF )
ConsoleGetType( TypeAngAxisF )
@ -458,7 +459,7 @@ ConsoleSetType( TypeAngAxisF )
const TransformF TransformF::Identity( Point3F::Zero, AngAxisF( Point3F( 0, 0, 1 ), 0) );
ConsoleType( TransformF, TypeTransformF, TransformF )
ConsoleType(TransformF, TypeTransformF, TransformF, "")
ImplementConsoleTypeCasters( TypeTransformF, TransformF )
ConsoleGetType( TypeTransformF )
@ -502,7 +503,7 @@ ConsoleSetType( TypeTransformF )
//-----------------------------------------------------------------------------
// TypeBox3F
//-----------------------------------------------------------------------------
ConsoleType( Box3F, TypeBox3F, Box3F )
ConsoleType(Box3F, TypeBox3F, Box3F, "")
ImplementConsoleTypeCasters( TypeBox3F, Box3F )
ConsoleGetType( TypeBox3F )
@ -539,7 +540,7 @@ ConsoleSetType( TypeBox3F )
//-----------------------------------------------------------------------------
// TypeEaseF
//-----------------------------------------------------------------------------
ConsoleType( EaseF, TypeEaseF, EaseF )
ConsoleType(EaseF, TypeEaseF, EaseF, "")
ImplementConsoleTypeCasters( TypeEaseF, EaseF )
ConsoleGetType( TypeEaseF )

View file

@ -0,0 +1,52 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _MODULE_CALLBACKS_H_
#define _MODULE_CALLBACKS_H_
#ifndef _MODULE_DEFINITION_H
#include "moduleDefinition.h"
#endif
//-----------------------------------------------------------------------------
/// @ingroup moduleGroup
/// @see moduleGroup
class ModuleCallbacks
{
friend class ModuleManager;
private:
// Called when a module is about to be loaded.
virtual void onModulePreLoad( ModuleDefinition* pModuleDefinition ) {}
// Called when a module has been loaded.
virtual void onModulePostLoad( ModuleDefinition* pModuleDefinition ) {}
// Called when a module is about to be unloaded.
virtual void onModulePreUnload( ModuleDefinition* pModuleDefinition ) {}
// Called when a module has been unloaded.
virtual void onModulePostUnload( ModuleDefinition* pModuleDefinition ) {}
};
#endif // _MODULE_CALLBACKS_H_

View file

@ -0,0 +1,209 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "moduleDefinition.h"
#ifndef _MODULE_MANAGER_H
#include "moduleManager.h"
#endif
// Script bindings.
#include "moduleDefinition_ScriptBinding.h"
#ifndef _CONSOLETYPES_H_
#include "console/consoleTypes.h"
#endif
#ifndef _TAML_H_
#include "persistence/taml/taml.h"
#endif
//-----------------------------------------------------------------------------
IMPLEMENT_CONOBJECT( ModuleDefinition );
//-----------------------------------------------------------------------------
ModuleDefinition::ModuleDefinition() :
mModuleId(StringTable->EmptyString()),
mVersionId( 0 ),
mBuildId( 0 ),
mEnabled( true ),
mSynchronized( false ),
mDeprecated( false ),
mCriticalMerge( false ),
mModuleDescription( StringTable->EmptyString() ),
mAuthor(StringTable->EmptyString()),
mModuleGroup(StringTable->EmptyString()),
mModuleType(StringTable->EmptyString()),
mScriptFile(StringTable->EmptyString()),
mCreateFunction(StringTable->EmptyString()),
mDestroyFunction(StringTable->EmptyString()),
mAssetTagsManifest(StringTable->EmptyString()),
mModulePath(StringTable->EmptyString()),
mModuleFile(StringTable->EmptyString()),
mModuleFilePath(StringTable->EmptyString()),
mModuleScriptFilePath(StringTable->EmptyString()),
mSignature(StringTable->EmptyString()),
mLoadCount( 0 ),
mLocked( false ),
mScopeSet( 0 ),
mpModuleManager( NULL )
{
// Set Vector Associations.
VECTOR_SET_ASSOCIATION( mDependencies );
VECTOR_SET_ASSOCIATION( mModuleAssets );
}
//-----------------------------------------------------------------------------
void ModuleDefinition::initPersistFields()
{
// Call parent.
Parent::initPersistFields();
addProtectedField("ModuleId", TypeString, Offset(mModuleId, ModuleDefinition), &defaultProtectedSetFn, &defaultProtectedGetFn, "");
/// Module configuration.
addProtectedField( "ModuleId", TypeString, Offset(mModuleId, ModuleDefinition), &setModuleId, &defaultProtectedGetFn, "A unique string Id for the module. It can contain any characters except a comma or semi-colon (the asset scope character)." );
addProtectedField( "VersionId", TypeS32, Offset(mVersionId, ModuleDefinition), &setVersionId, &defaultProtectedGetFn, "The version Id. Breaking changes to a module should use a higher version Id." );
addProtectedField( "BuildId", TypeS32, Offset(mBuildId, ModuleDefinition), &setBuildId, &defaultProtectedGetFn, &writeBuildId, "The build Id. Non-breaking changes to a module should use a higher build Id. Optional: If not specified then the build Id will be zero." );
addProtectedField( "Enabled", TypeBool, Offset(mEnabled, ModuleDefinition), &setEnabled, &defaultProtectedGetFn, &writeEnabled, "Whether the module is enabled or not. When disabled, it is effectively ignored. Optional: If not specified then the module is enabled." );
addProtectedField( "Synchronized", TypeBool, Offset(mSynchronized, ModuleDefinition), &setSynchronized, &defaultProtectedGetFn, &writeSynchronized, "Whether the module should be synchronized or not. Optional: If not specified then the module is not synchronized." );
addProtectedField( "Deprecated", TypeBool, Offset(mDeprecated, ModuleDefinition), &setDeprecated, &defaultProtectedGetFn, &writeDeprecated, "Whether the module is deprecated or not. Optional: If not specified then the module is not deprecated." );
addProtectedField( "CriticalMerge", TypeBool, Offset(mCriticalMerge, ModuleDefinition), &setDeprecated, &defaultProtectedGetFn, &writeCriticalMerge, "Whether the merging of a module prior to a restart is critical or not. Optional: If not specified then the module is not merge critical." );
addProtectedField( "Description", TypeString, Offset(mModuleDescription, ModuleDefinition), &setModuleDescription, &defaultProtectedGetFn, &writeModuleDescription, "The description typically used for debugging purposes but can be used for anything." );
addProtectedField( "Author", TypeString, Offset(mAuthor, ModuleDefinition), &setAuthor, &defaultProtectedGetFn, &writeAuthor, "The author of the module." );
addProtectedField( "Group", TypeString, Offset(mModuleGroup, ModuleDefinition), &setModuleGroup, &defaultProtectedGetFn, "The module group used typically when loading modules as a group." );
addProtectedField( "Type", TypeString, Offset(mModuleType, ModuleDefinition), &setModuleType, &defaultProtectedGetFn, &writeModuleType, "The module type typically used to distinguish modules during module enumeration. Optional: If not specified then the type is empty although this can still be used as a pseudo 'global' type for instance." );
addProtectedField( "Dependencies", TypeString, Offset(mDependencies, ModuleDefinition), &setDependencies, &getDependencies, &writeDependencies, "A comma-separated list of module Ids/VersionIds (<ModuleId>=<VersionId>,<ModuleId>=<VersionId>,etc) which this module depends upon. Optional: If not specified then no dependencies are assumed." );
addProtectedField( "ScriptFile", TypeString, Offset(mScriptFile, ModuleDefinition), &setScriptFile, &defaultProtectedGetFn, &writeScriptFile, "The name of the script file to compile when loading the module. Optional." );
addProtectedField( "CreateFunction", TypeString, Offset(mCreateFunction, ModuleDefinition), &setCreateFunction, &defaultProtectedGetFn, &writeCreateFunction, "The name of the function used to create the module. Optional: If not specified then no create function is called." );
addProtectedField( "DestroyFunction", TypeString, Offset(mDestroyFunction, ModuleDefinition), &setDestroyFunction, &defaultProtectedGetFn, &writeDestroyFunction, "The name of the function used to destroy the module. Optional: If not specified then no destroy function is called." );
addProtectedField( "AssetTagsManifest", TypeString, Offset(mAssetTagsManifest, ModuleDefinition), &setAssetTagsManifest, &defaultProtectedGetFn, &writeAssetTagsManifest, "The name of tags asset manifest file if this module contains asset tags. Optional: If not specified then no asset tags will be found for this module. Currently, only a single asset tag manifest should exist." );
addProtectedField( "ScopeSet", TypeS32, Offset( mScopeSet, ModuleDefinition ), &defaultProtectedNotSetFn, &getScopeSet, &defaultProtectedNotWriteFn, "The scope set used to control the lifetime scope of objects that the module uses. Objects added to this set are destroyed automatically when the module is unloaded." );
/// Module location (Read-only).
addProtectedField( "ModulePath", TypeString, Offset(mModulePath, ModuleDefinition), &defaultProtectedNotSetFn, &defaultProtectedGetFn, &defaultProtectedNotWriteFn, "The path of the module. This is read-only and is available only after the module has been registered by a module manager." );
addProtectedField( "ModuleFile", TypeString, Offset(mModuleFile, ModuleDefinition), &defaultProtectedNotSetFn, &defaultProtectedGetFn, &defaultProtectedNotWriteFn, "The file of the module. This is read-only and is available only after the module has been registered by a module manager." );
addProtectedField( "ModuleFilePath", TypeString, Offset(mModuleFilePath, ModuleDefinition), &defaultProtectedNotSetFn, &defaultProtectedGetFn, &defaultProtectedNotWriteFn, "The file-path of the module definition. This is read-only and is available only after the module has been registered by a module manager." );
addProtectedField( "ModuleScriptFilePath", TypeString, Offset(mModuleScriptFilePath, ModuleDefinition), &defaultProtectedNotSetFn, &defaultProtectedGetFn, &defaultProtectedNotWriteFn, "The file-path of the script-file referenced in the module definition. This is read-only and is available only after the module has been registered by a module manager." );
/// Misc.
addProtectedField( "Signature", TypeString, 0, &defaultProtectedNotSetFn, &getSignature, &defaultProtectedNotWriteFn, "A unique signature of the module definition based upon its Id, version and build. This is read-only and is available only after the module has been registered by a module manager." );
}
//-----------------------------------------------------------------------------
bool ModuleDefinition::getDependency( const U32 dependencyIndex, ModuleDependency& dependency ) const
{
// Is dependency index out of bounds?
if ( dependencyIndex >= (U32)mDependencies.size() )
{
// Yes, so warn.
Con::warnf("Could not get module dependency '%d' as it is out of range.", dependencyIndex);
return false;
}
// Fetch module dependency.
dependency = mDependencies[dependencyIndex];
return true;
}
//-----------------------------------------------------------------------------
bool ModuleDefinition::addDependency( const char* pModuleId, const U32 versionId )
{
// Fetch module Id.
StringTableEntry moduleId = StringTable->insert( pModuleId );
// Do we have any existing dependencies?
if ( mDependencies.size() > 0 )
{
// Yes, so is the module Id already a dependency?
for( typeModuleDependencyVector::iterator dependencyItr = mDependencies.begin(); dependencyItr != mDependencies.end(); ++dependencyItr )
{
// Skip if not the same module Id.
if ( dependencyItr->mModuleId != moduleId )
continue;
// Dependency already exists so warn.
Con::warnf("Could not add dependency of module Id '%s' at version Id '%d' as the module Id is already a dependency.", pModuleId, versionId );
return false;
}
}
// Populate module dependency.
ModuleDefinition::ModuleDependency dependency( moduleId, versionId );
// Store dependency.
mDependencies.push_back( dependency );
return true;
}
//-----------------------------------------------------------------------------
bool ModuleDefinition::removeDependency( const char* pModuleId )
{
// Fetch module Id.
StringTableEntry moduleId = StringTable->insert( pModuleId );
// Do we have any existing dependencies?
if ( mDependencies.size() > 0 )
{
// Yes, so is the module Id a dependency?
for( typeModuleDependencyVector::iterator dependencyItr = mDependencies.begin(); dependencyItr != mDependencies.end(); ++dependencyItr )
{
// Skip if not the same module Id.
if ( dependencyItr->mModuleId != moduleId )
continue;
// Remove dependency.
mDependencies.erase( dependencyItr );
return true;
}
}
// No, so warn.
Con::warnf("Could not remove dependency of module Id '%s' as the module Id is not a dependency.", pModuleId );
return false;
}
//-----------------------------------------------------------------------------
bool ModuleDefinition::save( void )
{
// Does the module have a file-path yet?
if (mModuleFilePath == StringTable->EmptyString())
{
// No, so warn.
Con::warnf("Save() - Cannot save module definition '%s' as it does not have a file-path.", mModuleId );
return false;
}
// Save the module file.
Taml taml;
return taml.write( this, mModuleFilePath );
}

View file

@ -0,0 +1,329 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _MODULE_DEFINITION_H
#define _MODULE_DEFINITION_H
#ifndef _ASSET_DEFINITION_H_
#include "assets/assetDefinition.h"
#endif
#ifndef _SIMSET_H_
#include "console/simSet.h"
#endif
#ifndef _SIMBASE_H_
#include "console/simBase.h"
#endif
#ifndef _TVECTOR_H_
#include "core/util/tVector.h"
#endif
#ifndef _STRINGUNIT_H_
#include "core/strings/stringUnit.h"
#endif
//-----------------------------------------------------------------------------
class ModuleManager;
//-----------------------------------------------------------------------------
/// @ingroup moduleGroup
/// @see moduleGroup
class ModuleDefinition : public SimSet
{
friend class ModuleManager;
private:
typedef SimSet Parent;
public:
/// Module dependency.
struct ModuleDependency
{
ModuleDependency() :
mModuleId( StringTable->EmptyString() ),
mVersionId( 0 )
{
}
ModuleDependency( StringTableEntry moduleId, const U32 versionId ) :
mModuleId( moduleId ),
mVersionId( versionId )
{
}
StringTableEntry mModuleId;
U32 mVersionId;
};
typedef Vector<ModuleDependency> typeModuleDependencyVector;
typedef Vector<AssetDefinition*> typeModuleAssetsVector;
private:
/// Module definition.
StringTableEntry mModuleId;
U32 mVersionId;
U32 mBuildId;
bool mEnabled;
bool mSynchronized;
bool mDeprecated;
bool mCriticalMerge;
StringTableEntry mModuleDescription;
StringTableEntry mAuthor;;
StringTableEntry mModuleGroup;
StringTableEntry mModuleType;
typeModuleDependencyVector mDependencies;
StringTableEntry mScriptFile;
StringTableEntry mCreateFunction;
StringTableEntry mDestroyFunction;
/// Modules assets.
StringTableEntry mAssetTagsManifest;
typeModuleAssetsVector mModuleAssets;
/// Module location.
StringTableEntry mModulePath;
StringTableEntry mModuleFile;
StringTableEntry mModuleFilePath;
StringTableEntry mModuleScriptFilePath;
/// Miscellaneous.
StringTableEntry mSignature;
S32 mLoadCount;
SimObjectId mScopeSet;
bool mLocked;
ModuleManager* mpModuleManager;
private:
inline bool checkUnlocked( void ) const { if ( mLocked ) { Con::warnf("Ignoring changes for locked module definition."); } return !mLocked; }
inline void setModuleManager( ModuleManager* pModuleManager ) { mpModuleManager = pModuleManager; }
public:
ModuleDefinition();
virtual ~ModuleDefinition() {}
/// Engine.
static void initPersistFields();
/// Module definition.
inline void setModuleId( const char* pModuleId ) { if ( checkUnlocked() ) { mModuleId = StringTable->insert(pModuleId); } }
inline StringTableEntry getModuleId( void ) const { return mModuleId; }
inline void setVersionId( const U32 versionId ) { if ( checkUnlocked() ) { mVersionId = versionId; } }
inline U32 getVersionId( void ) const { return mVersionId; }
inline void setBuildId( const U32 buildId ) { if ( checkUnlocked() ) { mBuildId = buildId; } }
inline U32 getBuildId( void ) const { return mBuildId; }
inline void setEnabled( const bool enabled ) { if ( checkUnlocked() ) { mEnabled = enabled; } }
inline bool getEnabled( void ) const { return mEnabled; }
inline void setSynchronized( const bool synchronized ) { if ( checkUnlocked() ) { mSynchronized = synchronized; } }
inline bool getSynchronized( void ) const { return mSynchronized; }
inline void setDeprecated( const bool deprecated ) { if ( checkUnlocked() ) { mDeprecated = deprecated; } }
inline bool getDeprecated( void ) const { return mDeprecated; }
inline void setCriticalMerge( const bool mergeCritical ) { if ( checkUnlocked() ) { mCriticalMerge = mergeCritical; } }
inline bool getCriticalMerge( void ) const { return mCriticalMerge; }
inline void setModuleDescription( const char* pModuleDescription ) { if ( checkUnlocked() ) { mModuleDescription = StringTable->insert(pModuleDescription); } }
inline StringTableEntry getModuleDescription( void ) const { return mModuleDescription; }
inline void setAuthor( const char* pAuthor ) { if ( checkUnlocked() ) { mAuthor = StringTable->insert(pAuthor); } }
inline StringTableEntry getAuthor( void ) const { return mAuthor; }
inline void setModuleGroup( const char* pModuleGroup ) { if ( checkUnlocked() ) { mModuleGroup = StringTable->insert(pModuleGroup); } }
inline StringTableEntry getModuleGroup( void ) const { return mModuleGroup; }
inline void setModuleType( const char* pModuleType ) { if ( checkUnlocked() ) { mModuleType = StringTable->insert(pModuleType); } }
inline StringTableEntry getModuleType( void ) const { return mModuleType; }
inline void setDependencies( const typeModuleDependencyVector& dependencies ) { if ( checkUnlocked() ) { mDependencies.clear(); mDependencies.merge(dependencies); } }
inline const typeModuleDependencyVector& getDependencies( void ) const { return mDependencies; }
inline void setScriptFile( const char* pScriptFile ) { if ( checkUnlocked() ) { mScriptFile = StringTable->insert(pScriptFile); } }
inline StringTableEntry getScriptFile( void ) const { return mScriptFile; }
inline void setCreateFunction( const char* pCreateFunction ) { if ( checkUnlocked() ) { mCreateFunction = StringTable->insert(pCreateFunction); } }
inline StringTableEntry getCreateFunction( void ) const { return mCreateFunction; }
inline void setDestroyFunction( const char* pDestroyFunction ) { if ( checkUnlocked() ) { mDestroyFunction = StringTable->insert(pDestroyFunction); } }
inline StringTableEntry getDestroyFunction( void ) const { return mDestroyFunction; }
inline SimObjectId getScopeSet( void ) const { return mScopeSet; }
/// Module assets.
inline void setAssetTagsManifest( const char* pTagsAssetManifest ) { if ( checkUnlocked() ) { mAssetTagsManifest = StringTable->insert(pTagsAssetManifest); } }
inline StringTableEntry getAssetTagsManifest( void ) const { return mAssetTagsManifest; }
inline typeModuleAssetsVector& getModuleAssets( void ) { return mModuleAssets; }
/// Module location.
inline void setModulePath( const char* pModulePath ) { if ( checkUnlocked() ) { mModulePath = StringTable->insert(pModulePath); } }
inline StringTableEntry getModulePath( void ) const { return mModulePath; }
inline void setModuleFile( const char* pModuleDefinitionFile ) { if ( checkUnlocked() ) { mModuleFile = StringTable->insert(pModuleDefinitionFile); } }
inline StringTableEntry getModuleFile( void ) const { return mModuleFile; }
inline void setModuleFilePath( const char* pModuleDefinitionFilePath ) { if ( checkUnlocked() ) { mModuleFilePath = StringTable->insert(pModuleDefinitionFilePath); } }
inline StringTableEntry getModuleFilePath( void ) const { return mModuleFilePath; }
inline void setModuleScriptFilePath( const char* pModuleScriptFilePath ) { if ( checkUnlocked() ) { mModuleScriptFilePath = StringTable->insert(pModuleScriptFilePath); } }
inline StringTableEntry getModuleScriptFilePath( void ) const { return mModuleScriptFilePath; }
/// Specialized dependency control.
inline U32 getDependencyCount( void ) const { return mDependencies.size(); }
bool getDependency( const U32 dependencyIndex, ModuleDependency& dependency ) const;
bool addDependency( const char* pModuleId, const U32 versionId );
bool removeDependency( const char* pModuleId );
/// Miscellaneous.
inline void setSignature( const char* pSignature ) { if ( checkUnlocked() ) { mSignature = StringTable->insert(pSignature); } }
inline StringTableEntry getSignature( void ) const { return mSignature; }
inline void increaseLoadCount( void ) { ++mLoadCount; }
inline void reduceLoadCount( void ) { --mLoadCount; }
inline S32 getLoadCount( void ) const { return mLoadCount; }
inline void setLocked( const bool status ) { mLocked = status; }
inline bool getLocked( void ) const { return mLocked; }
inline ModuleManager* getModuleManager( void ) const { return mpModuleManager; }
bool save( void );
/// Declare Console Object.
DECLARE_CONOBJECT( ModuleDefinition );
protected:
static bool setModuleId(void* obj, const char* index, const char* data) { static_cast<ModuleDefinition*>(obj)->setModuleId( data ); return false; }
static bool setVersionId(void* obj, const char* index, const char* data) { static_cast<ModuleDefinition*>(obj)->setVersionId((U32)dAtoi(data)); return false; }
static bool setBuildId(void* obj, const char* index, const char* data) { static_cast<ModuleDefinition*>(obj)->setBuildId((U32)dAtoi(data)); return false; }
static bool writeBuildId( void* obj, StringTableEntry pFieldName ) { return static_cast<ModuleDefinition*>(obj)->getBuildId() != 0; }
static bool setEnabled(void* obj, const char* index, const char* data) { static_cast<ModuleDefinition*>(obj)->setEnabled(dAtob(data)); return false; }
static bool writeEnabled( void* obj, StringTableEntry pFieldName ) { return static_cast<ModuleDefinition*>(obj)->getEnabled() == false; }
static bool setSynchronized(void* obj, const char* index, const char* data) { static_cast<ModuleDefinition*>(obj)->setSynchronized(dAtob(data)); return false; }
static bool writeSynchronized( void* obj, StringTableEntry pFieldName ) { return static_cast<ModuleDefinition*>(obj)->getSynchronized() == true; }
static bool setDeprecated(void* obj, const char* index, const char* data) { static_cast<ModuleDefinition*>(obj)->setDeprecated(dAtob(data)); return false; }
static bool writeDeprecated( void* obj, StringTableEntry pFieldName ) { return static_cast<ModuleDefinition*>(obj)->getDeprecated() == true; }
static bool writeCriticalMerge( void* obj, StringTableEntry pFieldName ){ return static_cast<ModuleDefinition*>(obj)->getCriticalMerge() == true; }
static bool setModuleDescription(void* obj, const char* index, const char* data) { static_cast<ModuleDefinition*>(obj)->setModuleDescription(data); return false; }
static bool writeModuleDescription( void* obj, StringTableEntry pFieldName ) { return static_cast<ModuleDefinition*>(obj)->getModuleDescription() != StringTable->EmptyString(); }
static bool setAuthor(void* obj, const char* index, const char* data) { static_cast<ModuleDefinition*>(obj)->setAuthor(data); return false; }
static bool writeAuthor(void* obj, StringTableEntry pFieldName) { return static_cast<ModuleDefinition*>(obj)->getAuthor() != StringTable->EmptyString(); }
static bool setModuleGroup(void* obj, const char* index, const char* data) { static_cast<ModuleDefinition*>(obj)->setModuleGroup(data); return false; }
static bool setModuleType(void* obj, const char* index, const char* data) { static_cast<ModuleDefinition*>(obj)->setModuleType(data); return false; }
static bool writeModuleType(void* obj, StringTableEntry pFieldName) { return static_cast<ModuleDefinition*>(obj)->getModuleType() != StringTable->EmptyString(); }
static bool setScriptFile(void* obj, const char* index, const char* data) { static_cast<ModuleDefinition*>(obj)->setScriptFile(data); return false; }
static bool writeScriptFile(void* obj, StringTableEntry pFieldName) { return static_cast<ModuleDefinition*>(obj)->getScriptFile() != StringTable->EmptyString(); }
static bool setCreateFunction(void* obj, const char* index, const char* data) { static_cast<ModuleDefinition*>(obj)->setCreateFunction(data); return false; }
static bool writeCreateFunction(void* obj, StringTableEntry pFieldName) { return static_cast<ModuleDefinition*>(obj)->getCreateFunction() != StringTable->EmptyString(); }
static bool setDestroyFunction(void* obj, const char* index, const char* data) { static_cast<ModuleDefinition*>(obj)->setDestroyFunction(data); return false; }
static bool writeDestroyFunction(void* obj, StringTableEntry pFieldName) { return static_cast<ModuleDefinition*>(obj)->getDestroyFunction() != StringTable->EmptyString(); }
/// Asset manifest.
static bool setAssetTagsManifest(void* obj, const char* index, const char* data) { static_cast<ModuleDefinition*>(obj)->setAssetTagsManifest(data); return false; }
static bool writeAssetTagsManifest(void* obj, StringTableEntry pFieldName) { return static_cast<ModuleDefinition*>(obj)->getAssetTagsManifest() != StringTable->EmptyString(); }
static const char* getScopeSet(void* obj, const char* data) { return Con::getIntArg(static_cast<ModuleDefinition*>(obj)->getScopeSet()); }
static bool setDependencies(void* obj, const char* index, const char* data)
{
// Fetch module dependencies.
ModuleDefinition::typeModuleDependencyVector moduleDependencies;
// Fetch dependency value.
const char* pDependencyValue = data;
char slotUnit[256];
char slotName[256];
char slotValue[256];
// Fetch definition word count.
const U32 dependencyWordCount = StringUnit::getUnitCount( pDependencyValue, "," );
// Do we have any dependencies specified?
if ( dependencyWordCount > 0 )
{
// Yes, so iterate dependencies.
for ( U32 dependencyIndex = 0; dependencyIndex < dependencyWordCount; ++dependencyIndex )
{
// Fetch slot.
dStrcpy( slotUnit, StringUnit::getUnit( pDependencyValue, dependencyIndex, "," ) );
// Fetch slot name and value.
dStrcpy( slotName, StringUnit::getUnit( slotUnit, 0, "=" ) );
dStrcpy( slotValue, StringUnit::getUnit( slotUnit, 1, "=" ) );
// Fetch module Id.
StringTableEntry moduleId = StringTable->insert( slotName );
// Fetch version Id.
const U32 versionId = slotValue[0] == '*' ? 0 : dAtoi(slotValue);
// Populate module dependency.
ModuleDefinition::ModuleDependency dependency( moduleId, versionId );
// Store dependency.
moduleDependencies.push_back( dependency );
}
}
// Set dependencies.
static_cast<ModuleDefinition*>(obj)->setDependencies( moduleDependencies );
return false;
}
static const char* getDependencies(void* obj, const char* data)
{
// Fetch module dependencies.
const ModuleDefinition::typeModuleDependencyVector& moduleDependencies = static_cast<ModuleDefinition*>(obj)->getDependencies();
// Finish if no dependencies.
if ( moduleDependencies.size() == 0 )
return StringTable->EmptyString();
// Get a return buffer.
const S32 bufferSize = 1024;
char* pReturnBuffer = Con::getReturnBuffer(bufferSize);
pReturnBuffer[0] = '\0';
// Set buffer limits.
char* pValueBuffer = pReturnBuffer;
S32 bufferLeft = bufferSize;
U32 used;
// Iterate module dependencies.
for ( ModuleDefinition::typeModuleDependencyVector::const_iterator dependencyItr = moduleDependencies.begin(); dependencyItr < moduleDependencies.end(); ++dependencyItr )
{
// Fetch module dependency.
const ModuleDefinition::ModuleDependency* pDependency = dependencyItr;
// Fetch version Id.
const char* pVersionId = pDependency->mVersionId == 0 ? "*" : avar("%d", pDependency->mVersionId );
if ( dependencyItr == moduleDependencies.begin() )
{
// Write out a field/value pair
used = dSprintf( pValueBuffer, bufferLeft, "%s=%s", pDependency->mModuleId, pVersionId );
pValueBuffer += used;
bufferLeft -= used;
}
else
{
// Write out a field/value pair
used = dSprintf( pValueBuffer, bufferLeft, ",%s=%s", pDependency->mModuleId, pVersionId );
pValueBuffer += used;
bufferLeft -= used;
}
// Sanity.
AssertFatal( bufferLeft > 0, "Cannot format module dependencies as we ran out of buffer." );
}
return pReturnBuffer;
}
static bool writeDependencies( void* obj, StringTableEntry pFieldName ) { return static_cast<ModuleDefinition*>(obj)->getDependencies().size() > 0; }
static const char* getSignature(void* obj, const char* data) { return static_cast<ModuleDefinition*>(obj)->getSignature(); }
};
#endif // _MODULE_DEFINITION_H

View file

@ -0,0 +1,96 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "console/engineAPI.h"
#include "moduleDefinition.h"
#include "moduleManager.h"
DefineEngineMethod(ModuleDefinition, save, bool, (),,
"Saves the module definition to the file it was loaded from (if any).\n"
"@return (bool success) Whether the module definition was saved or not.\n")
{
// Save.
return object->save();
}
//-----------------------------------------------------------------------------
DefineEngineMethod(ModuleDefinition, getModuleManager, S32, (),,
"Gets the module manager which this module definition is registered with (if any).\n"
"@return (moduleManager) The module manager which this module definition is registered with (zero if not registered).\n")
{
// Fetch module manager.
ModuleManager* pModuleManager = object->getModuleManager();
return pModuleManager != NULL ? pModuleManager->getId() : 0;
}
//-----------------------------------------------------------------------------
DefineEngineMethod(ModuleDefinition, getDependencyCount, S32, (), ,
"Gets the number of module dependencies this module definition has.\n"
"@return (int count) The number of module dependencies this module definition has.\n")
{
// Get module dependency count.
return object->getDependencyCount();
}
//-----------------------------------------------------------------------------
DefineEngineMethod(ModuleDefinition, getDependency, String, (U32 dependencyIndex), (0),
"Gets the module dependency at the specified index.\n"
"@param dependencyIndex The module dependency index.\n"
"@return (module - dependency) The module dependency at the specified index.")
{
// Get module dependency.
ModuleDefinition::ModuleDependency dependency;
if ( object->getDependency( dependencyIndex, dependency ) == false )
return StringTable->EmptyString();
// Format module dependency.
char* pReturnBuffer = Con::getReturnBuffer( 256 );
dSprintf( pReturnBuffer, 256, "%s %d", dependency.mModuleId, dependency.mVersionId );
return pReturnBuffer;
}
//-----------------------------------------------------------------------------
DefineEngineMethod(ModuleDefinition, addDependency, bool, (const char* pModuleId, U32 versionId), ("", 0),
"Adds the specified moduleId and vesionId as a dependency.\n"
"@param moduleId The module Id to add as a dependency.\n"
"@param versionId The version Id to add as a dependency. Using zero indicates any version."
"@return (bool success) Whether the module dependency was added or not.")
{
// Add dependency.
return object->addDependency( pModuleId, versionId );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(ModuleDefinition, removeDependency, bool, (const char* pModuleId), (""),
"Removes the specified moduleId as a dependency.\n"
"@param moduleId The module Id to remove as a dependency.\n"
"@return (bool success) Whether the module dependency was removed or not.")
{
// Remove dependency.
return object->removeDependency( pModuleId );
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,215 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _MODULE_MANAGER_H
#define _MODULE_MANAGER_H
#ifndef _SIMBASE_H_
#include "console/simBase.h"
#endif
#ifndef _TVECTOR_H_
#include "core/util/tvector.h"
#endif
#ifndef _TDICTIONARY_H_
#include "core/util/tDictionary.h"
#endif
#ifndef _TAML_H_
#include "persistence/taml/taml.h"
#endif
#ifndef _MODULE_DEFINITION_H
#include "moduleDefinition.h"
#endif
//-----------------------------------------------------------------------------
#define MODULE_MANAGER_MERGE_FILE "module.merge"
#define MODULE_MANAGER_MODULE_DEFINITION_EXTENSION "module.taml"
//-----------------------------------------------------------------------------
/// @ingroup moduleGroup
/// @see moduleGroup
class ModuleManager : public SimObject
{
private:
typedef SimObject Parent;
public:
/// Module definitions.
typedef Vector<ModuleDefinition*> typeModuleDefinitionVector;
typedef Vector<const ModuleDefinition*> typeConstModuleDefinitionVector;
private:
/// Database locking.
struct LockDatabase
{
public:
LockDatabase( ModuleManager* pManager ) :
mpManager( pManager )
{
mpManager->mDatabaseLocks++;
}
~LockDatabase()
{
mpManager->mDatabaseLocks--;
// Sanity!
AssertFatal( mpManager->mDatabaseLocks >= 0, "Module Manager: Cannot unlock database as it is already unlocked." );
}
private:
ModuleManager* mpManager;
};
/// Loaded module entry.
struct ModuleLoadEntry
{
ModuleLoadEntry( ModuleDefinition* pModuleDefinition, const bool strictVersionId ) :
mpModuleDefinition( pModuleDefinition ),
mStrictVersionId( strictVersionId )
{
}
ModuleLoadEntry()
{
mpModuleDefinition = NULL;
mStrictVersionId = false;
}
ModuleDefinition* mpModuleDefinition;
bool mStrictVersionId;
};
/// Module loading.
typedef Vector<StringTableEntry> typeModuleIdVector;
typedef Vector<StringTableEntry> typeGroupVector;
typedef HashMap<StringTableEntry, typeModuleIdVector*> typeGroupModuleHash;
typedef Vector<ModuleLoadEntry> typeModuleLoadEntryVector;
typeGroupModuleHash mGroupModules;
typeGroupVector mGroupsLoaded;
typeModuleLoadEntryVector mModulesLoaded;
/// Miscellaneous.
bool mEnforceDependencies;
bool mEchoInfo;
S32 mDatabaseLocks;
char mModuleExtension[256];
Taml mTaml;
SimSet mNotificationListeners;
// Module definition entry.
struct ModuleDefinitionEntry : public typeModuleDefinitionVector
{
public:
ModuleDefinitionEntry( StringTableEntry moduleId, StringTableEntry moduleGroup, StringTableEntry moduleType ) :
mModuleId( moduleId ),
mModuleGroup( moduleGroup ),
mModuleType( moduleType )
{
}
const StringTableEntry mModuleId;
const StringTableEntry mModuleGroup;
const StringTableEntry mModuleType;
};
/// Module databases.
typedef HashMap<StringTableEntry, ModuleDefinitionEntry*> typeModuleIdDatabaseHash;
typeModuleIdDatabaseHash mModuleIdDatabase;
public:
ModuleManager();
virtual ~ModuleManager() {}
/// SimObject overrides
virtual bool onAdd();
virtual void onRemove();
virtual void onDeleteNotify( SimObject *object );
static void initPersistFields();
/// Declare Console Object.
DECLARE_CONOBJECT( ModuleManager );
/// Module definitions.
bool setModuleExtension( const char* pExtension );
/// Module discovery.
bool scanModules( const char* pPath, const bool rootOnly = false );
/// Module unregister.
bool unregisterModule( const char* pModuleId, const U32 versionId );
/// Module (un)loading.
bool loadModuleGroup( const char* pModuleGroup );
bool unloadModuleGroup( const char* pModuleGroup );
bool loadModuleExplicit( const char* pModuleId, const U32 versionId = 0 );
bool unloadModuleExplicit( const char* pModuleId );
/// Module type enumeration.
ModuleDefinition* findModule( const char* pModuleId, const U32 versionId );
ModuleDefinition* findLoadedModule( const char* pModuleId );
void findModules( const bool loadedOnly, typeConstModuleDefinitionVector& moduleDefinitions );
void findModuleTypes( const char* pModuleType, const bool loadedOnly, typeConstModuleDefinitionVector& moduleDefinitions );
/// Module synchronization.
StringTableEntry copyModule( ModuleDefinition* pSourceModuleDefinition, const char* pTargetModuleId, const char* pTargetPath, const bool useVersionPathing );
bool synchronizeDependencies( ModuleDefinition* pRootModuleDefinition, const char* pTargetDependencyPath );
/// Module updates.
inline bool isModuleMergeAvailable( void ) const { return Platform::isFile( getModuleMergeFilePath() ); }
bool canMergeModules( const char* pMergeSourcePath );
bool mergeModules( const char* pMergeTargetPath, const bool removeMergeDefinition, const bool registerNewModules );
/// Module notifications.
void addListener( SimObject* pListener );
void removeListener( SimObject* pListener );
private:
void clearDatabase( void );
bool removeModuleDefinition( ModuleDefinition* pModuleDefinition );
bool registerModule( const char* pModulePath, const char* pModuleFile );
void raiseModulePreLoadNotifications( ModuleDefinition* pModuleDefinition );
void raiseModulePostLoadNotifications( ModuleDefinition* pModuleDefinition );
void raiseModulePreUnloadNotifications( ModuleDefinition* pModuleDefinition );
void raiseModulePostUnloadNotifications( ModuleDefinition* pModuleDefinition );
ModuleDefinitionEntry* findModuleId( StringTableEntry moduleId );
ModuleDefinitionEntry::iterator findModuleDefinition( StringTableEntry moduleId, const U32 versionId );
bool resolveModuleDependencies( StringTableEntry moduleId, const U32 versionId, StringTableEntry moduleGroup, bool synchronizedOnly, typeModuleLoadEntryVector& moduleResolvingQueue, typeModuleLoadEntryVector& moduleReadyQueue );
ModuleLoadEntry* findModuleResolving( StringTableEntry moduleId, typeModuleLoadEntryVector& moduleResolvingQueue );
ModuleLoadEntry* findModuleReady( StringTableEntry moduleId, typeModuleLoadEntryVector& moduleReadyQueue );
typeModuleLoadEntryVector::iterator findModuleLoaded( StringTableEntry moduleId, const U32 versionId = 0 );
typeGroupVector::iterator findGroupLoaded( StringTableEntry moduleGroup );
StringTableEntry getModuleMergeFilePath( void ) const;
};
//-----------------------------------------------------------------------------
extern ModuleManager ModuleDatabase;
#endif // _MODULE_MANAGER_H

View file

@ -0,0 +1,344 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "console/engineAPI.h"
#include "moduleDefinition.h"
#include "moduleManager.h"
DefineEngineMethod(ModuleManager, setModuleExtension, bool, (const char* moduleExtension), (""),
"Set the module extension used to scan for modules. The default is 'module'.\n"
"@param moduleExtension The module extension used to scan for modules.Do not use a period character.\n"
"@return Whether setting the module extension was successful or not.\n")
{
// Set module extension.
return object->setModuleExtension(moduleExtension);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(ModuleManager, scanModules, bool, (const char* pRootPath, bool rootOnly), ("", false),
"Scans for modules which are sub-directories of the specified path.\n"
"@param moduleRootPath The root directory to scan for sub - directories containing modules.\n"
"@param rootOnly[Optional] - Specifies whether to only scan the root path or not when searching for modules.\n"
"@return Whether the scan was successful or not.A successful scan can still find zero modules.\n")
{
// Scan modules.
return object->scanModules( pRootPath, rootOnly );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(ModuleManager, unregisterModule, bool, (const char* pModuleId, bool versionId), ("", false),
"Unregister the specified module.\n"
"@param moduleId The module Id to unregister.\n"
"@param versionId The version Id to unregister.\n"
"@return Whether the module was unregister or not.\n")
{
// Unregister the module.
return object->unregisterModule( pModuleId, versionId );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(ModuleManager, loadGroup, bool, (const char* pModuleGroup), (""),
"Load the specified module group.\n"
"@param moduleGroup The module group to load.\n"
"@return Whether the module group was loaded or not.\n")
{
// Load module group.
return object->loadModuleGroup(pModuleGroup);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(ModuleManager, unloadGroup, bool, (const char* pModuleGroup), (""),
"Unload the specified module group.\n"
"@param moduleGroup The module group to unload.\n"
"@return Whether the module group was unloaded or not.\n")
{
// Unload module group.
return object->unloadModuleGroup(pModuleGroup);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(ModuleManager, loadExplicit, bool, (const char* pModuleId, S32 pVersionId), ("", -1),
"Load the specified module explicitly.\n"
"@param moduleId The module Id to load.\n"
"@param versionId The version Id to load.Optional: Will load the latest version.\n"
"@return Whether the module Id was loaded or not.\n")
{
if (pVersionId == -1)
return object->loadModuleExplicit(pModuleId);
else
return object->loadModuleExplicit(pModuleId, pVersionId);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(ModuleManager, unloadExplicit, bool, (const char* pModuleId), (""),
"Unload the specified module explicitly.\n"
"@param moduleId The module Id to unload.\n"
"@return Whether the module Id was unloaded or not.\n")
{
// Unload module Id explicitly.
return object->unloadModuleExplicit(pModuleId);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(ModuleManager, findModule, String, (const char* pModuleId, U32 pVersionId), ("", 0),
"Find the specific module Id optionally at the specified version Id.\n"
"@param moduleId The module Id to find.\n"
"@param versionId The version Id to find.\n"
"@return The module definition object or NULL if not found.\n")
{
// Find module definition.
ModuleDefinition* pModuleDefinition = object->findModule(pModuleId, pVersionId);
// Return nothing if not found.
if ( pModuleDefinition == NULL )
return StringTable->EmptyString();
return pModuleDefinition->getIdString();
}
//-----------------------------------------------------------------------------
DefineEngineMethod(ModuleManager, findModules, String, (bool loadedOnly), (false),
"Find all the modules registered with the specified loaded state.\n"
"@param loadedOnly Whether to return only modules that are loaded or not.\n"
"@return A list of space - separated module definition object Ids.\n")
{
// Find module type definitions.
Vector<const ModuleDefinition*> moduleDefinitions;
// Find modules.
object->findModules( loadedOnly, moduleDefinitions );
// Fetch module definition count.
const U32 moduleDefinitionCount = (U32)moduleDefinitions.size();
// Finish if no module definition were found.
if ( moduleDefinitionCount == 0 )
return StringTable->EmptyString();
// Create a return buffer.
S32 bufferSize = 4096;
char* pReturnBuffer = Con::getReturnBuffer( bufferSize );
char* pBufferWrite = pReturnBuffer;
// Iterate module definitions.
for ( ModuleManager::typeConstModuleDefinitionVector::const_iterator moduleDefinitionItr = moduleDefinitions.begin(); moduleDefinitionItr != moduleDefinitions.end(); ++moduleDefinitionItr )
{
// Fetch module definition.
const ModuleDefinition* pModuleDefinition = *moduleDefinitionItr;
// Format module definition.
const U32 offset = dSprintf( pBufferWrite, bufferSize, "%d ", pModuleDefinition->getId() );
pBufferWrite += offset;
bufferSize -= offset;
// Are we out of buffer space?
if ( bufferSize <= 0 )
{
// Yes, so warn.
Con::warnf( "ModuleManager::findModules() - Ran out of buffer space." );
break;
}
}
return pReturnBuffer;
}
//-----------------------------------------------------------------------------
DefineEngineMethod(ModuleManager, findModuleTypes, String, (const char* pModuleType, bool loadedOnly), ("", false),
"Find the modules registered with the specified module type.\n"
"@param moduleType The module type to search for.\n"
"@param loadedOnly Whether to return only modules that are loaded or not.\n"
"@return A list of space - separated module definition object Ids.\n")
{
// Find module type definitions.
Vector<const ModuleDefinition*> moduleDefinitions;
// Find module types.
object->findModuleTypes( pModuleType, loadedOnly, moduleDefinitions );
// Fetch module definition count.
const U32 moduleDefinitionCount = (U32)moduleDefinitions.size();
// Finish if no module definition were found.
if ( moduleDefinitionCount == 0 )
return StringTable->EmptyString();
// Create a return buffer.
S32 bufferSize = 4096;
char* pReturnBuffer = Con::getReturnBuffer( bufferSize );
char* pBufferWrite = pReturnBuffer;
// Iterate module definitions.
for ( ModuleManager::typeConstModuleDefinitionVector::const_iterator moduleDefinitionItr = moduleDefinitions.begin(); moduleDefinitionItr != moduleDefinitions.end(); ++moduleDefinitionItr )
{
// Fetch module definition.
const ModuleDefinition* pModuleDefinition = *moduleDefinitionItr;
// Format module definition.
const U32 offset = dSprintf( pBufferWrite, bufferSize, "%d ", pModuleDefinition->getId() );
pBufferWrite += offset;
bufferSize -= offset;
// Are we out of buffer space?
if ( bufferSize <= 0 )
{
// Yes, so warn.
Con::warnf( "ModuleManager::findTypes() - Ran out of buffer space." );
break;
}
}
return pReturnBuffer;
}
//-----------------------------------------------------------------------------
DefineEngineMethod(ModuleManager, copyModule, String, (const char* sourceModuleDefinition, const char* pTargetModuleId, const char* pTargetPath, const bool useVersionPathing),
("", "", "", false),
"Copy the module to a new location with a new module Id.\n"
"@param sourceModuleDefinition The module definition to copy.\n"
"@param targetModuleId The module Id to rename the copied module to including all references to the source module Id.It is valid to specifiy the source module Id to produce an identical copy.\n"
"@param targetPath The target path to copy the module to.Addition folders will be created depending on whether 'useVersionPathing' is used or not.\n"
"@param useVersionPathing Whether to add a '/targetModuleId/versionId' folder to the target path or not.This allows copying multiple versions of the same module Id.\n"
"@return The new module definition file if copy was successful or NULL if not.\n")
{
// Find the source module definition.
ModuleDefinition* pSourceModuleDefinition = dynamic_cast<ModuleDefinition*>(Sim::findObject(sourceModuleDefinition));
// Was the module definition found?
if ( pSourceModuleDefinition == NULL )
{
// No, so warn.
Con::warnf("ModuleManager::copyModule() - Could not find source module definition '%s'.", sourceModuleDefinition);
return "";
}
// Copy module.
return object->copyModule( pSourceModuleDefinition, pTargetModuleId, pTargetPath, useVersionPathing );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(ModuleManager, synchronizeDependencies, bool, (const char* rootModuleDefinition, const char* pTargetDependencyFolder), ("", ""),
"Synchronize the module dependencies of a module definition to a target dependency folder.\n"
"@param rootModuleDefinition The module definition used to determine dependencies.\n"
"@param targetDependencyPath The target dependency folder to copy dependencies to.\n"
"@return Whether the module dependencies were synchronized correctly or not.\n")
{
// Find the root module definition.
ModuleDefinition* pRootModuleDefinition = dynamic_cast<ModuleDefinition*>(Sim::findObject(rootModuleDefinition));
// Was the module definition found?
if ( pRootModuleDefinition == NULL )
{
// No, so warn.
Con::warnf("ModuleManager::synchronizeModules() - Could not find root module definition '%s'.", rootModuleDefinition);
return false;
}
// Synchronize dependencies.
return object->synchronizeDependencies( pRootModuleDefinition, pTargetDependencyFolder );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(ModuleManager, isModuleMergeAvailable, bool, (),,
"Checks whether a module merge definition file is available or not.\n"
"@return Whether a module merge definition file is available or not.\n")
{
// Check if module merge is available or not.
return object->isModuleMergeAvailable();
}
//-----------------------------------------------------------------------------
DefineEngineMethod(ModuleManager, canMergeModules, bool, (const char* mergeSourcePath), (""),
"Checks whether a module merge using the modules in the source path can current happen or not.\n"
"@param mergeSourcePath The path where modules to be merged are located.\n"
"@return Whether a module merge using the modules in the source path can current happen or not.\n")
{
// Check whether the merge modules can current happen or not.
return object->canMergeModules(mergeSourcePath);
}
//-----------------------------------------------------------------------------
DefineEngineMethod(ModuleManager, mergeModules, bool, (const char* pMergeTargetPath, bool removeMergeDefinition, bool registerNewModules), ("", false, false),
"Performs a module merge into the selected target path.\n"
"@param mergeTargetPath The path where modules will be merged into.\n"
"@param removeMergeDefinition Whether to remove any merge definition found or not if merge is successful.\n"
"@param registerNewModules Whether new (not replaced or updated) modules should be registered or not.\n"
"@return Whether the module merge was successful or not.Failure here could result in a corrupt module state.Reinstall is recommended or at least advised to the user is recommended.\n")
{
// Merge modules.
return object->mergeModules( pMergeTargetPath, removeMergeDefinition, registerNewModules );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(ModuleManager, addListener, void, (const char* listenerObject), (""),
"Registers the specified object as a listener for module notifications.\n"
"@param listenerObject The object to start receiving module notifications.\n"
"@return No return value.\n")
{
// Find object.
SimObject* pListener = Sim::findObject(listenerObject);
// Did we find the listener object?
if ( pListener == NULL )
{
// No, so warn.
Con::warnf("ModuleManager::addNotifications() - Could not find the listener object '%s'.", listenerObject);
return;
}
object->addListener( pListener );
}
//-----------------------------------------------------------------------------
DefineEngineMethod(ModuleManager, removeListener, void, (const char* listenerObject), (""),
"Unregisters the specified object as a listener for module notifications.\n"
"@param listenerObject The object to stop receiving module notifications.\n"
"@return No return value.\n")
{
// Find object.
SimObject* pListener = Sim::findObject(listenerObject);
// Did we find the listener object?
if ( pListener == NULL )
{
// No, so warn.
Con::warnf("ModuleManager::removeNotifications() - Could not find the listener object '%s'.", listenerObject);
return;
}
object->removeListener( pListener );
}

View file

@ -0,0 +1,49 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "moduleMergeDefinition.h"
#ifndef _CONSOLETYPES_H_
#include "console/consoleTypes.h"
#endif
//-----------------------------------------------------------------------------
IMPLEMENT_CONOBJECT( ModuleMergeDefinition );
//-----------------------------------------------------------------------------
ModuleMergeDefinition::ModuleMergeDefinition() :
mModuleMergePath( StringTable->EmptyString() )
{
}
//-----------------------------------------------------------------------------
void ModuleMergeDefinition::initPersistFields()
{
// Call parent.
Parent::initPersistFields();
/// Module merge.
addField( "MergePath", TypeString, Offset(mModuleMergePath, ModuleMergeDefinition), "The path where the modules to be merged can be found." );
}

View file

@ -0,0 +1,56 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _MODULE_MERGE_DEFINITION_H
#define _MODULE_MERGE_DEFINITION_H
#ifndef _SIMBASE_H_
#include "console/simBase.h"
#endif
//-----------------------------------------------------------------------------
class ModuleMergeDefinition : public SimObject
{
private:
typedef SimObject Parent;
/// Module update
StringTableEntry mModuleMergePath;
public:
ModuleMergeDefinition();
virtual ~ModuleMergeDefinition() {}
/// Engine.
static void initPersistFields();
/// Module merge.
inline void setModuleMergePath( const char* pModuleMergePath ) { mModuleMergePath = StringTable->insert(pModuleMergePath); }
inline StringTableEntry getModuleMergePath( void ) const { return mModuleMergePath; }
/// Declare Console Object.
DECLARE_CONOBJECT( ModuleMergeDefinition );
};
#endif // _MODULE_MERGE_DEFINITION_H

View file

@ -0,0 +1,133 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _TAML_MODULE_ID_UPDATE_VISITOR_H_
#define _TAML_MODULE_ID_UPDATE_VISITOR_H_
#ifndef _TAML_VISITOR_H_
#include "persistence/taml/tamlVisitor.h"
#endif
#ifndef _TAML_PARSER_H_
#include "persistence/taml/tamlParser.h"
#endif
#ifndef _ASSET_FIELD_TYPES_H_
#include "assets/assetFieldTypes.h"
#endif
#include "platform/profiler.h"
//-----------------------------------------------------------------------------
class TamlModuleIdUpdateVisitor : public TamlVisitor
{
private:
StringTableEntry mModuleIdFrom;
StringTableEntry mModuleIdTo;
U32 mModuleIdFromLength;
U32 mModuleIdToLength;
public:
TamlModuleIdUpdateVisitor() :
mModuleIdFrom( StringTable->EmptyString() ),
mModuleIdTo(StringTable->EmptyString()),
mModuleIdFromLength( 0 ),
mModuleIdToLength( 0 )
{}
virtual ~TamlModuleIdUpdateVisitor() {}
virtual bool wantsPropertyChanges( void ) { return true; }
virtual bool wantsRootOnly( void ) { return true; }
virtual bool visit( const TamlParser& parser, TamlVisitor::PropertyState& propertyState )
{
// Debug Profiling.
PROFILE_SCOPE(TamlModuleIdUpdateVisitor_Visit);
// Fetch property value.
const char* pPropertyValue = propertyState.getPropertyValue();
// Fetch value length.
const U32 valueLenth = dStrlen(pPropertyValue);
char newAttributeValueBuffer[1024];
// Is this an expando?
if ( *pPropertyValue == '^' )
{
// Yes, so finish if it's not the correct length.
if ( valueLenth < mModuleIdFromLength+1 )
return true;
// Is this the module Id?
if ( dStrnicmp( pPropertyValue+1, mModuleIdFrom, mModuleIdFromLength ) == 0 )
{
// Yes, so format a new value.
dSprintf( newAttributeValueBuffer, sizeof(newAttributeValueBuffer), "^%s%s",
mModuleIdTo, pPropertyValue+1+mModuleIdFromLength );
// Assign new value.
propertyState.updatePropertyValue( newAttributeValueBuffer );
}
return true;
}
// Does the field start with the module Id?
if ( dStrnicmp( pPropertyValue, mModuleIdFrom, mModuleIdFromLength ) == 0 )
{
// Yes, so format a new value.
dSprintf( newAttributeValueBuffer, sizeof(newAttributeValueBuffer), "%s%s",
mModuleIdTo, pPropertyValue+mModuleIdFromLength );
// Assign new value.
propertyState.updatePropertyValue( newAttributeValueBuffer );
}
return true;
}
void setModuleIdFrom( const char* pModuleIdFrom )
{
// Sanity!
AssertFatal( pModuleIdFrom != NULL, "Module Id from cannot be NULL." );
// Set module Id.
mModuleIdFrom = StringTable->insert( pModuleIdFrom );
mModuleIdFromLength = dStrlen(mModuleIdFrom);
}
StringTableEntry getModuleIdFrom( void ) const { return mModuleIdFrom; }
void setModuleIdTo( const char* pModuleIdTo )
{
// Sanity!
AssertFatal( pModuleIdTo != NULL, "Module Id to cannot be NULL." );
// Set module Id.
mModuleIdTo = StringTable->insert( pModuleIdTo );
mModuleIdToLength = dStrlen(mModuleIdTo);
}
const char* getModuleIdTo( void ) const { return mModuleIdTo; }
};
#endif // _TAML_MODULE_ID_UPDATE_VISITOR_H_

View file

@ -0,0 +1,111 @@
/*
www.sourceforge.net/projects/tinyxml
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#ifndef TIXML_USE_STL
#include "tinystr.h"
// Error value for find primitive
const TiXmlString::size_type TiXmlString::npos = static_cast< TiXmlString::size_type >(-1);
// Null rep.
TiXmlString::Rep TiXmlString::nullrep_ = { 0, 0, { '\0' } };
void TiXmlString::reserve (size_type cap)
{
if (cap > capacity())
{
TiXmlString tmp;
tmp.init(length(), cap);
memcpy(tmp.start(), data(), length());
swap(tmp);
}
}
TiXmlString& TiXmlString::assign(const char* str, size_type len)
{
size_type cap = capacity();
if (len > cap || cap > 3*(len + 8))
{
TiXmlString tmp;
tmp.init(len);
memcpy(tmp.start(), str, len);
swap(tmp);
}
else
{
memmove(start(), str, len);
set_size(len);
}
return *this;
}
TiXmlString& TiXmlString::append(const char* str, size_type len)
{
size_type newsize = length() + len;
if (newsize > capacity())
{
reserve (newsize + capacity());
}
memmove(finish(), str, len);
set_size(newsize);
return *this;
}
TiXmlString operator + (const TiXmlString & a, const TiXmlString & b)
{
TiXmlString tmp;
tmp.reserve(a.length() + b.length());
tmp += a;
tmp += b;
return tmp;
}
TiXmlString operator + (const TiXmlString & a, const char* b)
{
TiXmlString tmp;
TiXmlString::size_type b_len = static_cast<TiXmlString::size_type>( strlen(b) );
tmp.reserve(a.length() + b_len);
tmp += a;
tmp.append(b, b_len);
return tmp;
}
TiXmlString operator + (const char* a, const TiXmlString & b)
{
TiXmlString tmp;
TiXmlString::size_type a_len = static_cast<TiXmlString::size_type>( strlen(a) );
tmp.reserve(a_len + b.length());
tmp.append(a, a_len);
tmp += b;
return tmp;
}
#endif // TIXML_USE_STL

View file

@ -0,0 +1,305 @@
/*
www.sourceforge.net/projects/tinyxml
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#ifndef TIXML_USE_STL
#ifndef TIXML_STRING_INCLUDED
#define TIXML_STRING_INCLUDED
#include <assert.h>
#include <string.h>
/* The support for explicit isn't that universal, and it isn't really
required - it is used to check that the TiXmlString class isn't incorrectly
used. Be nice to old compilers and macro it here:
*/
#if defined(_MSC_VER) && (_MSC_VER >= 1200 )
// Microsoft visual studio, version 6 and higher.
#define TIXML_EXPLICIT explicit
#elif defined(__GNUC__) && (__GNUC__ >= 3 )
// GCC version 3 and higher.s
#define TIXML_EXPLICIT explicit
#else
#define TIXML_EXPLICIT
#endif
/*
TiXmlString is an emulation of a subset of the std::string template.
Its purpose is to allow compiling TinyXML on compilers with no or poor STL support.
Only the member functions relevant to the TinyXML project have been implemented.
The buffer allocation is made by a simplistic power of 2 like mechanism : if we increase
a string and there's no more room, we allocate a buffer twice as big as we need.
*/
class TiXmlString
{
public :
// The size type used
typedef size_t size_type;
// Error value for find primitive
static const size_type npos; // = -1;
// TiXmlString empty constructor
TiXmlString () : rep_(&nullrep_)
{
}
// TiXmlString copy constructor
TiXmlString ( const TiXmlString & copy) : rep_(0)
{
init(copy.length());
memcpy(start(), copy.data(), length());
}
// TiXmlString constructor, based on a string
TIXML_EXPLICIT TiXmlString ( const char * copy) : rep_(0)
{
init( static_cast<size_type>( strlen(copy) ));
memcpy(start(), copy, length());
}
// TiXmlString constructor, based on a string
TIXML_EXPLICIT TiXmlString ( const char * str, size_type len) : rep_(0)
{
init(len);
memcpy(start(), str, len);
}
// TiXmlString destructor
~TiXmlString ()
{
quit();
}
TiXmlString& operator = (const char * copy)
{
return assign( copy, (size_type)strlen(copy));
}
TiXmlString& operator = (const TiXmlString & copy)
{
return assign(copy.start(), copy.length());
}
// += operator. Maps to append
TiXmlString& operator += (const char * suffix)
{
return append(suffix, static_cast<size_type>( strlen(suffix) ));
}
// += operator. Maps to append
TiXmlString& operator += (char single)
{
return append(&single, 1);
}
// += operator. Maps to append
TiXmlString& operator += (const TiXmlString & suffix)
{
return append(suffix.data(), suffix.length());
}
// Convert a TiXmlString into a null-terminated char *
const char * c_str () const { return rep_->str; }
// Convert a TiXmlString into a char * (need not be null terminated).
const char * data () const { return rep_->str; }
// Return the length of a TiXmlString
size_type length () const { return rep_->size; }
// Alias for length()
size_type size () const { return rep_->size; }
// Checks if a TiXmlString is empty
bool empty () const { return rep_->size == 0; }
// Return capacity of string
size_type capacity () const { return rep_->capacity; }
// single char extraction
const char& at (size_type index) const
{
assert( index < length() );
return rep_->str[ index ];
}
// [] operator
char& operator [] (size_type index) const
{
assert( index < length() );
return rep_->str[ index ];
}
// find a char in a string. Return TiXmlString::npos if not found
size_type find (char lookup) const
{
return find(lookup, 0);
}
// find a char in a string from an offset. Return TiXmlString::npos if not found
size_type find (char tofind, size_type offset) const
{
if (offset >= length()) return npos;
for (const char* p = c_str() + offset; *p != '\0'; ++p)
{
if (*p == tofind) return static_cast< size_type >( p - c_str() );
}
return npos;
}
void clear ()
{
//Lee:
//The original was just too strange, though correct:
// TiXmlString().swap(*this);
//Instead use the quit & re-init:
quit();
init(0,0);
}
/* Function to reserve a big amount of data when we know we'll need it. Be aware that this
function DOES NOT clear the content of the TiXmlString if any exists.
*/
void reserve (size_type cap);
TiXmlString& assign (const char* str, size_type len);
TiXmlString& append (const char* str, size_type len);
void swap (TiXmlString& other)
{
Rep* r = rep_;
rep_ = other.rep_;
other.rep_ = r;
}
private:
void init(size_type sz) { init(sz, sz); }
void set_size(size_type sz) { rep_->str[ rep_->size = sz ] = '\0'; }
char* start() const { return rep_->str; }
char* finish() const { return rep_->str + rep_->size; }
struct Rep
{
size_type size, capacity;
char str[1];
};
void init(size_type sz, size_type cap)
{
if (cap)
{
// Lee: the original form:
// rep_ = static_cast<Rep*>(operator new(sizeof(Rep) + cap));
// doesn't work in some cases of new being overloaded. Switching
// to the normal allocation, although use an 'int' for systems
// that are overly picky about structure alignment.
const size_type bytesNeeded = sizeof(Rep) + cap;
const size_type intsNeeded = ( bytesNeeded + sizeof(int) - 1 ) / sizeof( int );
rep_ = reinterpret_cast<Rep*>( new int[ intsNeeded ] );
rep_->str[ rep_->size = sz ] = '\0';
rep_->capacity = cap;
}
else
{
rep_ = &nullrep_;
}
}
void quit()
{
if (rep_ != &nullrep_)
{
// The rep_ is really an array of ints. (see the allocator, above).
// Cast it back before delete, so the compiler won't incorrectly call destructors.
delete [] ( reinterpret_cast<int*>( rep_ ) );
}
}
Rep * rep_;
static Rep nullrep_;
} ;
inline bool operator == (const TiXmlString & a, const TiXmlString & b)
{
return ( a.length() == b.length() ) // optimization on some platforms
&& ( strcmp(a.c_str(), b.c_str()) == 0 ); // actual compare
}
inline bool operator < (const TiXmlString & a, const TiXmlString & b)
{
return strcmp(a.c_str(), b.c_str()) < 0;
}
inline bool operator != (const TiXmlString & a, const TiXmlString & b) { return !(a == b); }
inline bool operator > (const TiXmlString & a, const TiXmlString & b) { return b < a; }
inline bool operator <= (const TiXmlString & a, const TiXmlString & b) { return !(b < a); }
inline bool operator >= (const TiXmlString & a, const TiXmlString & b) { return !(a < b); }
inline bool operator == (const TiXmlString & a, const char* b) { return strcmp(a.c_str(), b) == 0; }
inline bool operator == (const char* a, const TiXmlString & b) { return b == a; }
inline bool operator != (const TiXmlString & a, const char* b) { return !(a == b); }
inline bool operator != (const char* a, const TiXmlString & b) { return !(b == a); }
TiXmlString operator + (const TiXmlString & a, const TiXmlString & b);
TiXmlString operator + (const TiXmlString & a, const char* b);
TiXmlString operator + (const char* a, const TiXmlString & b);
/*
TiXmlOutStream is an emulation of std::ostream. It is based on TiXmlString.
Only the operators that we need for TinyXML have been developped.
*/
class TiXmlOutStream : public TiXmlString
{
public :
// TiXmlOutStream << operator.
TiXmlOutStream & operator << (const TiXmlString & in)
{
*this += in;
return *this;
}
// TiXmlOutStream << operator.
TiXmlOutStream & operator << (const char * in)
{
*this += in;
return *this;
}
} ;
#endif // TIXML_STRING_INCLUDED
#endif // TIXML_USE_STL

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,52 @@
/*
www.sourceforge.net/projects/tinyxml
Original code (2.0 and earlier )copyright (c) 2000-2006 Lee Thomason (www.grinninglizard.com)
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product documentation
would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "tinyxml.h"
// The goal of the seperate error file is to make the first
// step towards localization. tinyxml (currently) only supports
// english error messages, but the could now be translated.
//
// It also cleans up the code a bit.
//
const char* TiXmlBase::errorString[ TiXmlBase::TIXML_ERROR_STRING_COUNT ] =
{
"No error",
"Error",
"Failed to open file",
"Error parsing Element.",
"Failed to read Element name",
"Error reading Element value.",
"Error reading Attributes.",
"Error: empty tag.",
"Error reading end tag.",
"Error parsing Unknown.",
"Error parsing Comment.",
"Error parsing Declaration.",
"Error document empty.",
"Error null (0) or unexpected EOF found in input stream.",
"Error parsing CDATA.",
"Error when TiXmlDocument added to document, because TiXmlDocument can only be at the root.",
};

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,221 @@
#ifndef RAPIDJSON_ALLOCATORS_H_
#define RAPIDJSON_ALLOCATORS_H_
#include "rapidjson.h"
namespace rapidjson {
///////////////////////////////////////////////////////////////////////////////
// Allocator
/*! \class rapidjson::Allocator
\brief Concept for allocating, resizing and freeing memory block.
Note that Malloc() and Realloc() are non-static but Free() is static.
So if an allocator need to support Free(), it needs to put its pointer in
the header of memory block.
\code
concept Allocator {
static const bool kNeedFree; //!< Whether this allocator needs to call Free().
// Allocate a memory block.
// \param size of the memory block in bytes.
// \returns pointer to the memory block.
void* Malloc(size_t size);
// Resize a memory block.
// \param originalPtr The pointer to current memory block. Null pointer is permitted.
// \param originalSize The current size in bytes. (Design issue: since some allocator may not book-keep this, explicitly pass to it can save memory.)
// \param newSize the new size in bytes.
void* Realloc(void* originalPtr, size_t originalSize, size_t newSize);
// Free a memory block.
// \param pointer to the memory block. Null pointer is permitted.
static void Free(void *ptr);
};
\endcode
*/
///////////////////////////////////////////////////////////////////////////////
// CrtAllocator
//! C-runtime library allocator.
/*! This class is just wrapper for standard C library memory routines.
\implements Allocator
*/
class CrtAllocator {
public:
static const bool kNeedFree = true;
void* Malloc(size_t size) { return malloc(size); }
void* Realloc(void* originalPtr, size_t originalSize, size_t newSize) { (void)originalSize; return realloc(originalPtr, newSize); }
static void Free(void *ptr) { free(ptr); }
};
///////////////////////////////////////////////////////////////////////////////
// MemoryPoolAllocator
//! Default memory allocator used by the parser and DOM.
/*! This allocator allocate memory blocks from pre-allocated memory chunks.
It does not free memory blocks. And Realloc() only allocate new memory.
The memory chunks are allocated by BaseAllocator, which is CrtAllocator by default.
User may also supply a buffer as the first chunk.
If the user-buffer is full then additional chunks are allocated by BaseAllocator.
The user-buffer is not deallocated by this allocator.
\tparam BaseAllocator the allocator type for allocating memory chunks. Default is CrtAllocator.
\implements Allocator
*/
template <typename BaseAllocator = CrtAllocator>
class MemoryPoolAllocator {
public:
static const bool kNeedFree = false; //!< Tell users that no need to call Free() with this allocator. (concept Allocator)
//! Constructor with chunkSize.
/*! \param chunkSize The size of memory chunk. The default is kDefaultChunkSize.
\param baseAllocator The allocator for allocating memory chunks.
*/
MemoryPoolAllocator(size_t chunkSize = kDefaultChunkCapacity, BaseAllocator* baseAllocator = 0) :
chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(0), baseAllocator_(baseAllocator), ownBaseAllocator_(0)
{
if (!baseAllocator_)
ownBaseAllocator_ = baseAllocator_ = new BaseAllocator();
AddChunk(chunk_capacity_);
}
//! Constructor with user-supplied buffer.
/*! The user buffer will be used firstly. When it is full, memory pool allocates new chunk with chunk size.
The user buffer will not be deallocated when this allocator is destructed.
\param buffer User supplied buffer.
\param size Size of the buffer in bytes. It must at least larger than sizeof(ChunkHeader).
\param chunkSize The size of memory chunk. The default is kDefaultChunkSize.
\param baseAllocator The allocator for allocating memory chunks.
*/
MemoryPoolAllocator(char *buffer, size_t size, size_t chunkSize = kDefaultChunkCapacity, BaseAllocator* baseAllocator = 0) :
chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(buffer), baseAllocator_(baseAllocator), ownBaseAllocator_(0)
{
RAPIDJSON_ASSERT(buffer != 0);
RAPIDJSON_ASSERT(size > sizeof(ChunkHeader));
chunkHead_ = (ChunkHeader*)buffer;
chunkHead_->capacity = size - sizeof(ChunkHeader);
chunkHead_->size = 0;
chunkHead_->next = 0;
}
//! Destructor.
/*! This deallocates all memory chunks, excluding the user-supplied buffer.
*/
~MemoryPoolAllocator() {
Clear();
delete ownBaseAllocator_;
}
//! Deallocates all memory chunks, excluding the user-supplied buffer.
void Clear() {
while(chunkHead_ != 0 && chunkHead_ != (ChunkHeader *)userBuffer_) {
ChunkHeader* next = chunkHead_->next;
baseAllocator_->Free(chunkHead_);
chunkHead_ = next;
}
}
//! Computes the total capacity of allocated memory chunks.
/*! \return total capacity in bytes.
*/
size_t Capacity() {
size_t capacity = 0;
for (ChunkHeader* c = chunkHead_; c != 0; c = c->next)
capacity += c->capacity;
return capacity;
}
//! Computes the memory blocks allocated.
/*! \return total used bytes.
*/
size_t Size() {
size_t size = 0;
for (ChunkHeader* c = chunkHead_; c != 0; c = c->next)
size += c->size;
return size;
}
//! Allocates a memory block. (concept Allocator)
void* Malloc(size_t size) {
size = RAPIDJSON_ALIGN(size);
if (chunkHead_->size + size > chunkHead_->capacity)
AddChunk(chunk_capacity_ > size ? chunk_capacity_ : size);
char *buffer = (char *)(chunkHead_ + 1) + chunkHead_->size;
chunkHead_->size += size;
return buffer;
}
//! Resizes a memory block (concept Allocator)
void* Realloc(void* originalPtr, size_t originalSize, size_t newSize) {
if (originalPtr == 0)
return Malloc(newSize);
// Do not shrink if new size is smaller than original
if (originalSize >= newSize)
return originalPtr;
// Simply expand it if it is the last allocation and there is sufficient space
if (originalPtr == (char *)(chunkHead_ + 1) + chunkHead_->size - originalSize) {
size_t increment = newSize - originalSize;
increment = RAPIDJSON_ALIGN(increment);
if (chunkHead_->size + increment <= chunkHead_->capacity) {
chunkHead_->size += increment;
return originalPtr;
}
}
// Realloc process: allocate and copy memory, do not free original buffer.
void* newBuffer = Malloc(newSize);
RAPIDJSON_ASSERT(newBuffer != 0); // Do not handle out-of-memory explicitly.
return memcpy(newBuffer, originalPtr, originalSize);
}
//! Frees a memory block (concept Allocator)
static void Free(void *ptr) { (void)ptr; } // Do nothing
private:
//! Creates a new chunk.
/*! \param capacity Capacity of the chunk in bytes.
*/
void AddChunk(size_t capacity) {
ChunkHeader* chunk = (ChunkHeader*)baseAllocator_->Malloc(sizeof(ChunkHeader) + capacity);
chunk->capacity = capacity;
chunk->size = 0;
chunk->next = chunkHead_;
chunkHead_ = chunk;
}
static const int kDefaultChunkCapacity = 64 * 1024; //!< Default chunk capacity.
//! Chunk header for perpending to each chunk.
/*! Chunks are stored as a singly linked list.
*/
struct ChunkHeader {
size_t capacity; //!< Capacity of the chunk in bytes (excluding the header itself).
size_t size; //!< Current size of allocated memory in bytes.
ChunkHeader *next; //!< Next chunk in the linked list.
};
ChunkHeader *chunkHead_; //!< Head of the chunk linked-list. Only the head chunk serves allocation.
size_t chunk_capacity_; //!< The minimum capacity of chunk when they are allocated.
char *userBuffer_; //!< User supplied buffer.
BaseAllocator* baseAllocator_; //!< base allocator for allocating memory chunks.
BaseAllocator* ownBaseAllocator_; //!< base allocator created by this object.
};
} // namespace rapidjson
#endif // RAPIDJSON_ENCODINGS_H_

View file

@ -0,0 +1,843 @@
#ifndef RAPIDJSON_DOCUMENT_H_
#define RAPIDJSON_DOCUMENT_H_
#include "reader.h"
#include "internal/strfunc.h"
#include <new> // placement new
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4127) // conditional expression is constant
#endif
namespace rapidjson {
///////////////////////////////////////////////////////////////////////////////
// GenericValue
//! Represents a JSON value. Use Value for UTF8 encoding and default allocator.
/*!
A JSON value can be one of 7 types. This class is a variant type supporting
these types.
Use the Value if UTF8 and default allocator
\tparam Encoding Encoding of the value. (Even non-string values need to have the same encoding in a document)
\tparam Allocator Allocator type for allocating memory of object, array and string.
*/
#pragma pack (push, 4)
template <typename Encoding, typename Allocator = MemoryPoolAllocator<> >
class GenericValue {
public:
//! Name-value pair in an object.
struct Member {
GenericValue<Encoding, Allocator> name; //!< name of member (must be a string)
GenericValue<Encoding, Allocator> value; //!< value of member.
};
typedef Encoding EncodingType; //!< Encoding type from template parameter.
typedef Allocator AllocatorType; //!< Allocator type from template parameter.
typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding.
typedef Member* MemberIterator; //!< Member iterator for iterating in object.
typedef const Member* ConstMemberIterator; //!< Constant member iterator for iterating in object.
typedef GenericValue* ValueIterator; //!< Value iterator for iterating in array.
typedef const GenericValue* ConstValueIterator; //!< Constant value iterator for iterating in array.
//!@name Constructors and destructor.
//@{
//! Default constructor creates a null value.
GenericValue() : flags_(kNullFlag) {}
//! Copy constructor is not permitted.
private:
GenericValue(const GenericValue& rhs);
public:
//! Constructor with JSON value type.
/*! This creates a Value of specified type with default content.
\param type Type of the value.
\note Default content for number is zero.
*/
GenericValue(Type type) {
static const unsigned defaultFlags[7] = {
kNullFlag, kFalseFlag, kTrueFlag, kObjectFlag, kArrayFlag, kConstStringFlag,
kNumberFlag | kIntFlag | kUintFlag | kInt64Flag | kUint64Flag | kDoubleFlag
};
RAPIDJSON_ASSERT(type <= kNumberType);
flags_ = defaultFlags[type];
memset(&data_, 0, sizeof(data_));
}
//! Constructor for boolean value.
GenericValue(bool b) : flags_(b ? kTrueFlag : kFalseFlag) {}
//! Constructor for int value.
GenericValue(int i) : flags_(kNumberIntFlag) {
data_.n.i64 = i;
if (i >= 0)
flags_ |= kUintFlag | kUint64Flag;
}
//! Constructor for unsigned value.
GenericValue(unsigned u) : flags_(kNumberUintFlag) {
data_.n.u64 = u;
if (!(u & 0x80000000))
flags_ |= kIntFlag | kInt64Flag;
}
//! Constructor for int64_t value.
GenericValue(int64_t i64) : flags_(kNumberInt64Flag) {
data_.n.i64 = i64;
if (i64 >= 0) {
flags_ |= kNumberUint64Flag;
if (!(i64 & 0xFFFFFFFF00000000LL))
flags_ |= kUintFlag;
if (!(i64 & 0xFFFFFFFF80000000LL))
flags_ |= kIntFlag;
}
else if (i64 >= -2147483648LL)
flags_ |= kIntFlag;
}
//! Constructor for uint64_t value.
GenericValue(uint64_t u64) : flags_(kNumberUint64Flag) {
data_.n.u64 = u64;
if (!(u64 & 0x8000000000000000ULL))
flags_ |= kInt64Flag;
if (!(u64 & 0xFFFFFFFF00000000ULL))
flags_ |= kUintFlag;
if (!(u64 & 0xFFFFFFFF80000000ULL))
flags_ |= kIntFlag;
}
//! Constructor for double value.
GenericValue(double d) : flags_(kNumberDoubleFlag) { data_.n.d = d; }
//! Constructor for constant string (i.e. do not make a copy of string)
GenericValue(const Ch* s, SizeType length) {
RAPIDJSON_ASSERT(s != NULL);
flags_ = kConstStringFlag;
data_.s.str = s;
data_.s.length = length;
}
//! Constructor for constant string (i.e. do not make a copy of string)
GenericValue(const Ch* s) { SetStringRaw(s, internal::StrLen(s)); }
//! Constructor for copy-string (i.e. do make a copy of string)
GenericValue(const Ch* s, SizeType length, Allocator& allocator) { SetStringRaw(s, length, allocator); }
//! Constructor for copy-string (i.e. do make a copy of string)
GenericValue(const Ch*s, Allocator& allocator) { SetStringRaw(s, internal::StrLen(s), allocator); }
//! Destructor.
/*! Need to destruct elements of array, members of object, or copy-string.
*/
~GenericValue() {
if (Allocator::kNeedFree) { // Shortcut by Allocator's trait
switch(flags_) {
case kArrayFlag:
for (GenericValue* v = data_.a.elements; v != data_.a.elements + data_.a.size; ++v)
v->~GenericValue();
Allocator::Free(data_.a.elements);
break;
case kObjectFlag:
for (Member* m = data_.o.members; m != data_.o.members + data_.o.size; ++m) {
m->name.~GenericValue();
m->value.~GenericValue();
}
Allocator::Free(data_.o.members);
break;
case kCopyStringFlag:
Allocator::Free(const_cast<Ch*>(data_.s.str));
break;
}
}
}
//@}
//!@name Assignment operators
//@{
//! Assignment with move semantics.
/*! \param rhs Source of the assignment. It will become a null value after assignment.
*/
GenericValue& operator=(GenericValue& rhs) {
RAPIDJSON_ASSERT(this != &rhs);
this->~GenericValue();
memcpy(this, &rhs, sizeof(GenericValue));
rhs.flags_ = kNullFlag;
return *this;
}
//! Assignment with primitive types.
/*! \tparam T Either Type, int, unsigned, int64_t, uint64_t, const Ch*
\param value The value to be assigned.
*/
template <typename T>
GenericValue& operator=(T value) {
this->~GenericValue();
new (this) GenericValue(value);
return *this;
}
//@}
//!@name Type
//@{
Type GetType() const { return static_cast<Type>(flags_ & kTypeMask); }
bool IsNull() const { return flags_ == kNullFlag; }
bool IsFalse() const { return flags_ == kFalseFlag; }
bool IsTrue() const { return flags_ == kTrueFlag; }
bool IsBool() const { return (flags_ & kBoolFlag) != 0; }
bool IsObject() const { return flags_ == kObjectFlag; }
bool IsArray() const { return flags_ == kArrayFlag; }
bool IsNumber() const { return (flags_ & kNumberFlag) != 0; }
bool IsInt() const { return (flags_ & kIntFlag) != 0; }
bool IsUint() const { return (flags_ & kUintFlag) != 0; }
bool IsInt64() const { return (flags_ & kInt64Flag) != 0; }
bool IsUint64() const { return (flags_ & kUint64Flag) != 0; }
bool IsDouble() const { return (flags_ & kDoubleFlag) != 0; }
bool IsString() const { return (flags_ & kStringFlag) != 0; }
//@}
//!@name Null
//@{
GenericValue& SetNull() { this->~GenericValue(); new (this) GenericValue(); return *this; }
//@}
//!@name Bool
//@{
bool GetBool() const { RAPIDJSON_ASSERT(IsBool()); return flags_ == kTrueFlag; }
GenericValue& SetBool(bool b) { this->~GenericValue(); new (this) GenericValue(b); return *this; }
//@}
//!@name Object
//@{
//! Set this value as an empty object.
GenericValue& SetObject() { this->~GenericValue(); new (this) GenericValue(kObjectType); return *this; }
//! Get the value associated with the name.
/*!
\note In version 0.1x, if the member is not found, this function returns a null value. This makes issue 7.
Since 0.2, if the name is not correct, it will assert.
If user is unsure whether a member exists, user should use HasMember() first.
A better approach is to use the now public FindMember().
*/
GenericValue& operator[](const Ch* name) {
if (Member* member = FindMember(name))
return member->value;
else {
RAPIDJSON_ASSERT(false); // see above note
static GenericValue NullValue;
return NullValue;
}
}
const GenericValue& operator[](const Ch* name) const { return const_cast<GenericValue&>(*this)[name]; }
//! Member iterators.
ConstMemberIterator MemberBegin() const { RAPIDJSON_ASSERT(IsObject()); return data_.o.members; }
ConstMemberIterator MemberEnd() const { RAPIDJSON_ASSERT(IsObject()); return data_.o.members + data_.o.size; }
MemberIterator MemberBegin() { RAPIDJSON_ASSERT(IsObject()); return data_.o.members; }
MemberIterator MemberEnd() { RAPIDJSON_ASSERT(IsObject()); return data_.o.members + data_.o.size; }
//! Check whether a member exists in the object.
/*!
\note It is better to use FindMember() directly if you need the obtain the value as well.
*/
bool HasMember(const Ch* name) const { return FindMember(name) != 0; }
//! Find member by name.
/*!
\return Return the member if exists. Otherwise returns null pointer.
*/
Member* FindMember(const Ch* name) {
RAPIDJSON_ASSERT(name);
RAPIDJSON_ASSERT(IsObject());
Object& o = data_.o;
for (Member* member = o.members; member != data_.o.members + data_.o.size; ++member)
if (name[member->name.data_.s.length] == '\0' && memcmp(member->name.data_.s.str, name, member->name.data_.s.length * sizeof(Ch)) == 0)
return member;
return 0;
}
const Member* FindMember(const Ch* name) const { return const_cast<GenericValue&>(*this).FindMember(name); }
//! Add a member (name-value pair) to the object.
/*! \param name A string value as name of member.
\param value Value of any type.
\param allocator Allocator for reallocating memory.
\return The value itself for fluent API.
\note The ownership of name and value will be transfered to this object if success.
*/
GenericValue& AddMember(GenericValue& name, GenericValue& value, Allocator& allocator) {
RAPIDJSON_ASSERT(IsObject());
RAPIDJSON_ASSERT(name.IsString());
Object& o = data_.o;
if (o.size >= o.capacity) {
if (o.capacity == 0) {
o.capacity = kDefaultObjectCapacity;
o.members = (Member*)allocator.Malloc(o.capacity * sizeof(Member));
}
else {
SizeType oldCapacity = o.capacity;
o.capacity *= 2;
o.members = (Member*)allocator.Realloc(o.members, oldCapacity * sizeof(Member), o.capacity * sizeof(Member));
}
}
o.members[o.size].name.RawAssign(name);
o.members[o.size].value.RawAssign(value);
o.size++;
return *this;
}
GenericValue& AddMember(const Ch* name, Allocator& nameAllocator, GenericValue& value, Allocator& allocator) {
GenericValue n(name, internal::StrLen(name), nameAllocator);
return AddMember(n, value, allocator);
}
GenericValue& AddMember(const Ch* name, GenericValue& value, Allocator& allocator) {
GenericValue n(name, internal::StrLen(name));
return AddMember(n, value, allocator);
}
template <typename T>
GenericValue& AddMember(const Ch* name, T value, Allocator& allocator) {
GenericValue n(name, internal::StrLen(name));
GenericValue v(value);
return AddMember(n, v, allocator);
}
//! Remove a member in object by its name.
/*! \param name Name of member to be removed.
\return Whether the member existed.
\note Removing member is implemented by moving the last member. So the ordering of members is changed.
*/
bool RemoveMember(const Ch* name) {
RAPIDJSON_ASSERT(IsObject());
if (Member* m = FindMember(name)) {
RAPIDJSON_ASSERT(data_.o.size > 0);
RAPIDJSON_ASSERT(data_.o.members != 0);
Member* last = data_.o.members + (data_.o.size - 1);
if (data_.o.size > 1 && m != last) {
// Move the last one to this place
m->name = last->name;
m->value = last->value;
}
else {
// Only one left, just destroy
m->name.~GenericValue();
m->value.~GenericValue();
}
--data_.o.size;
return true;
}
return false;
}
//@}
//!@name Array
//@{
//! Set this value as an empty array.
GenericValue& SetArray() { this->~GenericValue(); new (this) GenericValue(kArrayType); return *this; }
//! Get the number of elements in array.
SizeType Size() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.size; }
//! Get the capacity of array.
SizeType Capacity() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.capacity; }
//! Check whether the array is empty.
bool Empty() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.size == 0; }
//! Remove all elements in the array.
/*! This function do not deallocate memory in the array, i.e. the capacity is unchanged.
*/
void Clear() {
RAPIDJSON_ASSERT(IsArray());
for (SizeType i = 0; i < data_.a.size; ++i)
data_.a.elements[i].~GenericValue();
data_.a.size = 0;
}
//! Get an element from array by index.
/*! \param index Zero-based index of element.
\note
\code
Value a(kArrayType);
a.PushBack(123);
int x = a[0].GetInt(); // Error: operator[ is ambiguous, as 0 also mean a null pointer of const char* type.
int y = a[SizeType(0)].GetInt(); // Cast to SizeType will work.
int z = a[0u].GetInt(); // This works too.
\endcode
*/
GenericValue& operator[](SizeType index) {
RAPIDJSON_ASSERT(IsArray());
RAPIDJSON_ASSERT(index < data_.a.size);
return data_.a.elements[index];
}
const GenericValue& operator[](SizeType index) const { return const_cast<GenericValue&>(*this)[index]; }
//! Element iterator
ValueIterator Begin() { RAPIDJSON_ASSERT(IsArray()); return data_.a.elements; }
ValueIterator End() { RAPIDJSON_ASSERT(IsArray()); return data_.a.elements + data_.a.size; }
ConstValueIterator Begin() const { return const_cast<GenericValue&>(*this).Begin(); }
ConstValueIterator End() const { return const_cast<GenericValue&>(*this).End(); }
//! Request the array to have enough capacity to store elements.
/*! \param newCapacity The capacity that the array at least need to have.
\param allocator The allocator for allocating memory. It must be the same one use previously.
\return The value itself for fluent API.
*/
GenericValue& Reserve(SizeType newCapacity, Allocator &allocator) {
RAPIDJSON_ASSERT(IsArray());
if (newCapacity > data_.a.capacity) {
data_.a.elements = (GenericValue*)allocator.Realloc(data_.a.elements, data_.a.capacity * sizeof(GenericValue), newCapacity * sizeof(GenericValue));
data_.a.capacity = newCapacity;
}
return *this;
}
//! Append a value at the end of the array.
/*! \param value The value to be appended.
\param allocator The allocator for allocating memory. It must be the same one use previously.
\return The value itself for fluent API.
\note The ownership of the value will be transfered to this object if success.
\note If the number of elements to be appended is known, calls Reserve() once first may be more efficient.
*/
GenericValue& PushBack(GenericValue& value, Allocator& allocator) {
RAPIDJSON_ASSERT(IsArray());
if (data_.a.size >= data_.a.capacity)
Reserve(data_.a.capacity == 0 ? kDefaultArrayCapacity : data_.a.capacity * 2, allocator);
data_.a.elements[data_.a.size++].RawAssign(value);
return *this;
}
template <typename T>
GenericValue& PushBack(T value, Allocator& allocator) {
GenericValue v(value);
return PushBack(v, allocator);
}
//! Remove the last element in the array.
GenericValue& PopBack() {
RAPIDJSON_ASSERT(IsArray());
RAPIDJSON_ASSERT(!Empty());
data_.a.elements[--data_.a.size].~GenericValue();
return *this;
}
//@}
//!@name Number
//@{
int GetInt() const { RAPIDJSON_ASSERT(flags_ & kIntFlag); return data_.n.i.i; }
unsigned GetUint() const { RAPIDJSON_ASSERT(flags_ & kUintFlag); return data_.n.u.u; }
int64_t GetInt64() const { RAPIDJSON_ASSERT(flags_ & kInt64Flag); return data_.n.i64; }
uint64_t GetUint64() const { RAPIDJSON_ASSERT(flags_ & kUint64Flag); return data_.n.u64; }
double GetDouble() const {
RAPIDJSON_ASSERT(IsNumber());
if ((flags_ & kDoubleFlag) != 0) return data_.n.d; // exact type, no conversion.
if ((flags_ & kIntFlag) != 0) return data_.n.i.i; // int -> double
if ((flags_ & kUintFlag) != 0) return data_.n.u.u; // unsigned -> double
if ((flags_ & kInt64Flag) != 0) return (double)data_.n.i64; // int64_t -> double (may lose precision)
RAPIDJSON_ASSERT((flags_ & kUint64Flag) != 0); return (double)data_.n.u64; // uint64_t -> double (may lose precision)
}
GenericValue& SetInt(int i) { this->~GenericValue(); new (this) GenericValue(i); return *this; }
GenericValue& SetUint(unsigned u) { this->~GenericValue(); new (this) GenericValue(u); return *this; }
GenericValue& SetInt64(int64_t i64) { this->~GenericValue(); new (this) GenericValue(i64); return *this; }
GenericValue& SetUint64(uint64_t u64) { this->~GenericValue(); new (this) GenericValue(u64); return *this; }
GenericValue& SetDouble(double d) { this->~GenericValue(); new (this) GenericValue(d); return *this; }
//@}
//!@name String
//@{
const Ch* GetString() const { RAPIDJSON_ASSERT(IsString()); return data_.s.str; }
//! Get the length of string.
/*! Since rapidjson permits "\u0000" in the json string, strlen(v.GetString()) may not equal to v.GetStringLength().
*/
SizeType GetStringLength() const { RAPIDJSON_ASSERT(IsString()); return data_.s.length; }
//! Set this value as a string without copying source string.
/*! This version has better performance with supplied length, and also support string containing null character.
\param s source string pointer.
\param length The length of source string, excluding the trailing null terminator.
\return The value itself for fluent API.
*/
GenericValue& SetString(const Ch* s, SizeType length) { this->~GenericValue(); SetStringRaw(s, length); return *this; }
//! Set this value as a string without copying source string.
/*! \param s source string pointer.
\return The value itself for fluent API.
*/
GenericValue& SetString(const Ch* s) { return SetString(s, internal::StrLen(s)); }
//! Set this value as a string by copying from source string.
/*! This version has better performance with supplied length, and also support string containing null character.
\param s source string.
\param length The length of source string, excluding the trailing null terminator.
\param allocator Allocator for allocating copied buffer. Commonly use document.GetAllocator().
\return The value itself for fluent API.
*/
GenericValue& SetString(const Ch* s, SizeType length, Allocator& allocator) { this->~GenericValue(); SetStringRaw(s, length, allocator); return *this; }
//! Set this value as a string by copying from source string.
/*! \param s source string.
\param allocator Allocator for allocating copied buffer. Commonly use document.GetAllocator().
\return The value itself for fluent API.
*/
GenericValue& SetString(const Ch* s, Allocator& allocator) { SetString(s, internal::StrLen(s), allocator); return *this; }
//@}
//! Generate events of this value to a Handler.
/*! This function adopts the GoF visitor pattern.
Typical usage is to output this JSON value as JSON text via Writer, which is a Handler.
It can also be used to deep clone this value via GenericDocument, which is also a Handler.
\tparam Handler type of handler.
\param handler An object implementing concept Handler.
*/
template <typename Handler>
const GenericValue& Accept(Handler& handler) const {
switch(GetType()) {
case kNullType: handler.Null(); break;
case kFalseType: handler.Bool(false); break;
case kTrueType: handler.Bool(true); break;
case kObjectType:
handler.StartObject();
for (Member* m = data_.o.members; m != data_.o.members + data_.o.size; ++m) {
handler.String(m->name.data_.s.str, m->name.data_.s.length, false);
m->value.Accept(handler);
}
handler.EndObject(data_.o.size);
break;
case kArrayType:
handler.StartArray();
for (GenericValue* v = data_.a.elements; v != data_.a.elements + data_.a.size; ++v)
v->Accept(handler);
handler.EndArray(data_.a.size);
break;
case kStringType:
handler.String(data_.s.str, data_.s.length, false);
break;
case kNumberType:
if (IsInt()) handler.Int(data_.n.i.i);
else if (IsUint()) handler.Uint(data_.n.u.u);
else if (IsInt64()) handler.Int64(data_.n.i64);
else if (IsUint64()) handler.Uint64(data_.n.u64);
else handler.Double(data_.n.d);
break;
}
return *this;
}
private:
template <typename, typename>
friend class GenericDocument;
enum {
kBoolFlag = 0x100,
kNumberFlag = 0x200,
kIntFlag = 0x400,
kUintFlag = 0x800,
kInt64Flag = 0x1000,
kUint64Flag = 0x2000,
kDoubleFlag = 0x4000,
kStringFlag = 0x100000,
kCopyFlag = 0x200000,
// Initial flags of different types.
kNullFlag = kNullType,
kTrueFlag = kTrueType | kBoolFlag,
kFalseFlag = kFalseType | kBoolFlag,
kNumberIntFlag = kNumberType | kNumberFlag | kIntFlag | kInt64Flag,
kNumberUintFlag = kNumberType | kNumberFlag | kUintFlag | kUint64Flag | kInt64Flag,
kNumberInt64Flag = kNumberType | kNumberFlag | kInt64Flag,
kNumberUint64Flag = kNumberType | kNumberFlag | kUint64Flag,
kNumberDoubleFlag = kNumberType | kNumberFlag | kDoubleFlag,
kConstStringFlag = kStringType | kStringFlag,
kCopyStringFlag = kStringType | kStringFlag | kCopyFlag,
kObjectFlag = kObjectType,
kArrayFlag = kArrayType,
kTypeMask = 0xFF // bitwise-and with mask of 0xFF can be optimized by compiler
};
static const SizeType kDefaultArrayCapacity = 16;
static const SizeType kDefaultObjectCapacity = 16;
struct String {
const Ch* str;
SizeType length;
unsigned hashcode; //!< reserved
}; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
// By using proper binary layout, retrieval of different integer types do not need conversions.
union Number {
#if RAPIDJSON_ENDIAN == RAPIDJSON_LITTLEENDIAN
struct I {
int i;
char padding[4];
}i;
struct U {
unsigned u;
char padding2[4];
}u;
#else
struct I {
char padding[4];
int i;
}i;
struct U {
char padding2[4];
unsigned u;
}u;
#endif
int64_t i64;
uint64_t u64;
double d;
}; // 8 bytes
struct Object {
Member* members;
SizeType size;
SizeType capacity;
}; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
struct Array {
GenericValue<Encoding, Allocator>* elements;
SizeType size;
SizeType capacity;
}; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
union Data {
String s;
Number n;
Object o;
Array a;
}; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
// Initialize this value as array with initial data, without calling destructor.
void SetArrayRaw(GenericValue* values, SizeType count, Allocator& alloctaor) {
flags_ = kArrayFlag;
data_.a.elements = (GenericValue*)alloctaor.Malloc(count * sizeof(GenericValue));
memcpy(data_.a.elements, values, count * sizeof(GenericValue));
data_.a.size = data_.a.capacity = count;
}
//! Initialize this value as object with initial data, without calling destructor.
void SetObjectRaw(Member* members, SizeType count, Allocator& alloctaor) {
flags_ = kObjectFlag;
data_.o.members = (Member*)alloctaor.Malloc(count * sizeof(Member));
memcpy(data_.o.members, members, count * sizeof(Member));
data_.o.size = data_.o.capacity = count;
}
//! Initialize this value as constant string, without calling destructor.
void SetStringRaw(const Ch* s, SizeType length) {
RAPIDJSON_ASSERT(s != NULL);
flags_ = kConstStringFlag;
data_.s.str = s;
data_.s.length = length;
}
//! Initialize this value as copy string with initial data, without calling destructor.
void SetStringRaw(const Ch* s, SizeType length, Allocator& allocator) {
RAPIDJSON_ASSERT(s != NULL);
flags_ = kCopyStringFlag;
data_.s.str = (Ch *)allocator.Malloc((length + 1) * sizeof(Ch));
data_.s.length = length;
memcpy(const_cast<Ch*>(data_.s.str), s, length * sizeof(Ch));
const_cast<Ch*>(data_.s.str)[length] = '\0';
}
//! Assignment without calling destructor
void RawAssign(GenericValue& rhs) {
memcpy(this, &rhs, sizeof(GenericValue));
rhs.flags_ = kNullFlag;
}
Data data_;
unsigned flags_;
};
#pragma pack (pop)
//! Value with UTF8 encoding.
typedef GenericValue<UTF8<> > Value;
///////////////////////////////////////////////////////////////////////////////
// GenericDocument
//! A document for parsing JSON text as DOM.
/*!
\implements Handler
\tparam Encoding encoding for both parsing and string storage.
\tparam Alloactor allocator for allocating memory for the DOM, and the stack during parsing.
*/
template <typename Encoding, typename Allocator = MemoryPoolAllocator<> >
class GenericDocument : public GenericValue<Encoding, Allocator> {
public:
typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding.
typedef GenericValue<Encoding, Allocator> ValueType; //!< Value type of the document.
typedef Allocator AllocatorType; //!< Allocator type from template parameter.
//! Constructor
/*! \param allocator Optional allocator for allocating stack memory.
\param stackCapacity Initial capacity of stack in bytes.
*/
GenericDocument(Allocator* allocator = 0, size_t stackCapacity = kDefaultStackCapacity) : stack_(allocator, stackCapacity), parseError_(0), errorOffset_(0) {}
//! Parse JSON text from an input stream.
/*! \tparam parseFlags Combination of ParseFlag.
\param stream Input stream to be parsed.
\return The document itself for fluent API.
*/
template <unsigned parseFlags, typename SourceEncoding, typename InputStream>
GenericDocument& ParseStream(InputStream& is) {
ValueType::SetNull(); // Remove existing root if exist
GenericReader<SourceEncoding, Encoding, Allocator> reader;
if (reader.template Parse<parseFlags>(is, *this)) {
RAPIDJSON_ASSERT(stack_.GetSize() == sizeof(ValueType)); // Got one and only one root object
this->RawAssign(*stack_.template Pop<ValueType>(1)); // Add this-> to prevent issue 13.
parseError_ = 0;
errorOffset_ = 0;
}
else {
parseError_ = reader.GetParseError();
errorOffset_ = reader.GetErrorOffset();
ClearStack();
}
return *this;
}
//! Parse JSON text from a mutable string.
/*! \tparam parseFlags Combination of ParseFlag.
\param str Mutable zero-terminated string to be parsed.
\return The document itself for fluent API.
*/
template <unsigned parseFlags, typename SourceEncoding>
GenericDocument& ParseInsitu(Ch* str) {
GenericInsituStringStream<Encoding> s(str);
return ParseStream<parseFlags | kParseInsituFlag, SourceEncoding>(s);
}
template <unsigned parseFlags>
GenericDocument& ParseInsitu(Ch* str) {
return ParseInsitu<parseFlags, Encoding>(str);
}
//! Parse JSON text from a read-only string.
/*! \tparam parseFlags Combination of ParseFlag (must not contain kParseInsituFlag).
\param str Read-only zero-terminated string to be parsed.
*/
template <unsigned parseFlags, typename SourceEncoding>
GenericDocument& Parse(const Ch* str) {
RAPIDJSON_ASSERT(!(parseFlags & kParseInsituFlag));
GenericStringStream<SourceEncoding> s(str);
return ParseStream<parseFlags, SourceEncoding>(s);
}
template <unsigned parseFlags>
GenericDocument& Parse(const Ch* str) {
return Parse<parseFlags, Encoding>(str);
}
//! Whether a parse error was occured in the last parsing.
bool HasParseError() const { return parseError_ != 0; }
//! Get the message of parsing error.
const char* GetParseError() const { return parseError_; }
//! Get the offset in character of the parsing error.
size_t GetErrorOffset() const { return errorOffset_; }
//! Get the allocator of this document.
Allocator& GetAllocator() { return stack_.GetAllocator(); }
//! Get the capacity of stack in bytes.
size_t GetStackCapacity() const { return stack_.GetCapacity(); }
//private:
//friend class GenericReader<Encoding>; // for Reader to call the following private handler functions
// Implementation of Handler
void Null() { new (stack_.template Push<ValueType>()) ValueType(); }
void Bool(bool b) { new (stack_.template Push<ValueType>()) ValueType(b); }
void Int(int i) { new (stack_.template Push<ValueType>()) ValueType(i); }
void Uint(unsigned i) { new (stack_.template Push<ValueType>()) ValueType(i); }
void Int64(int64_t i) { new (stack_.template Push<ValueType>()) ValueType(i); }
void Uint64(uint64_t i) { new (stack_.template Push<ValueType>()) ValueType(i); }
void Double(double d) { new (stack_.template Push<ValueType>()) ValueType(d); }
void String(const Ch* str, SizeType length, bool copy) {
if (copy)
new (stack_.template Push<ValueType>()) ValueType(str, length, GetAllocator());
else
new (stack_.template Push<ValueType>()) ValueType(str, length);
}
void StartObject() { new (stack_.template Push<ValueType>()) ValueType(kObjectType); }
void EndObject(SizeType memberCount) {
typename ValueType::Member* members = stack_.template Pop<typename ValueType::Member>(memberCount);
stack_.template Top<ValueType>()->SetObjectRaw(members, (SizeType)memberCount, GetAllocator());
}
void StartArray() { new (stack_.template Push<ValueType>()) ValueType(kArrayType); }
void EndArray(SizeType elementCount) {
ValueType* elements = stack_.template Pop<ValueType>(elementCount);
stack_.template Top<ValueType>()->SetArrayRaw(elements, elementCount, GetAllocator());
}
private:
// Prohibit assignment
GenericDocument& operator=(const GenericDocument&);
void ClearStack() {
if (Allocator::kNeedFree)
while (stack_.GetSize() > 0) // Here assumes all elements in stack array are GenericValue (Member is actually 2 GenericValue objects)
(stack_.template Pop<ValueType>(1))->~ValueType();
else
stack_.Clear();
}
static const size_t kDefaultStackCapacity = 1024;
internal::Stack<Allocator> stack_;
const char* parseError_;
size_t errorOffset_;
};
typedef GenericDocument<UTF8<> > Document;
} // namespace rapidjson
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif // RAPIDJSON_DOCUMENT_H_

View file

@ -0,0 +1,250 @@
#ifndef RAPIDJSON_ENCODEDSTREAM_H_
#define RAPIDJSON_ENCODEDSTREAM_H_
#include "rapidjson.h"
namespace rapidjson {
//! Input byte stream wrapper with a statically bound encoding.
/*!
\tparam Encoding The interpretation of encoding of the stream. Either UTF8, UTF16LE, UTF16BE, UTF32LE, UTF32BE.
\tparam InputByteStream Type of input byte stream. For example, FileReadStream.
*/
template <typename Encoding, typename InputByteStream>
class EncodedInputStream {
RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
public:
typedef typename Encoding::Ch Ch;
EncodedInputStream(InputByteStream& is) : is_(is) {
current_ = Encoding::TakeBOM(is_);
}
Ch Peek() const { return current_; }
Ch Take() { Ch c = current_; current_ = Encoding::Take(is_); return c; }
size_t Tell() const { return is_.Tell(); }
// Not implemented
void Put(Ch c) { RAPIDJSON_ASSERT(false); }
void Flush() { RAPIDJSON_ASSERT(false); }
Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
private:
// Prohibit assignment for VC C4512 warning
EncodedInputStream& operator=(const EncodedInputStream&);
InputByteStream& is_;
Ch current_;
};
//! Output byte stream wrapper with statically bound encoding.
/*!
\tparam Encoding The interpretation of encoding of the stream. Either UTF8, UTF16LE, UTF16BE, UTF32LE, UTF32BE.
\tparam InputByteStream Type of input byte stream. For example, FileWriteStream.
*/
template <typename Encoding, typename OutputByteStream>
class EncodedOutputStream {
RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
public:
typedef typename Encoding::Ch Ch;
EncodedOutputStream(OutputByteStream& os, bool putBOM = true) : os_(os) {
if (putBOM)
Encoding::PutBOM(os_);
}
void Put(Ch c) { Encoding::Put(os_, c); }
void Flush() { os_.Flush(); }
// Not implemented
Ch Peek() const { RAPIDJSON_ASSERT(false); }
Ch Take() { RAPIDJSON_ASSERT(false); }
size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; }
Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
private:
// Prohibit assignment for VC C4512 warning
EncodedOutputStream& operator=(const EncodedOutputStream&);
OutputByteStream& os_;
};
#define RAPIDJSON_ENCODINGS_FUNC(x) UTF8<Ch>::x, UTF16LE<Ch>::x, UTF16BE<Ch>::x, UTF32LE<Ch>::x, UTF32BE<Ch>::x
//! Input stream wrapper with dynamically bound encoding and automatic encoding detection.
/*!
\tparam CharType Type of character for reading.
\tparam InputByteStream type of input byte stream to be wrapped.
*/
template <typename CharType, typename InputByteStream>
class AutoUTFInputStream {
RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
public:
typedef CharType Ch;
//! Constructor.
/*!
\param is input stream to be wrapped.
\param type UTF encoding type if it is not detected from the stream.
*/
AutoUTFInputStream(InputByteStream& is, UTFType type = kUTF8) : is_(&is), type_(type), hasBOM_(false) {
DetectType();
static const TakeFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Take) };
takeFunc_ = f[type_];
current_ = takeFunc_(*is_);
}
UTFType GetType() const { return type_; }
bool HasBOM() const { return hasBOM_; }
Ch Peek() const { return current_; }
Ch Take() { Ch c = current_; current_ = takeFunc_(*is_); return c; }
size_t Tell() const { return is_->Tell(); }
// Not implemented
void Put(Ch) { RAPIDJSON_ASSERT(false); }
void Flush() { RAPIDJSON_ASSERT(false); }
Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
private:
// Detect encoding type with BOM or RFC 4627
void DetectType() {
// BOM (Byte Order Mark):
// 00 00 FE FF UTF-32BE
// FF FE 00 00 UTF-32LE
// FE FF UTF-16BE
// FF FE UTF-16LE
// EF BB BF UTF-8
const unsigned char* c = (const unsigned char *)is_->Peek4();
if (!c)
return;
unsigned bom = c[0] | (c[1] << 8) | (c[2] << 16) | (c[3] << 24);
hasBOM_ = false;
if (bom == 0xFFFE0000) { type_ = kUTF32BE; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); is_->Take(); }
else if (bom == 0x0000FEFF) { type_ = kUTF32LE; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); is_->Take(); }
else if ((bom & 0xFFFF) == 0xFFFE) { type_ = kUTF16BE; hasBOM_ = true; is_->Take(); is_->Take(); }
else if ((bom & 0xFFFF) == 0xFEFF) { type_ = kUTF16LE; hasBOM_ = true; is_->Take(); is_->Take(); }
else if ((bom & 0xFFFFFF) == 0xBFBBEF) { type_ = kUTF8; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); }
// RFC 4627: Section 3
// "Since the first two characters of a JSON text will always be ASCII
// characters [RFC0020], it is possible to determine whether an octet
// stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking
// at the pattern of nulls in the first four octets."
// 00 00 00 xx UTF-32BE
// 00 xx 00 xx UTF-16BE
// xx 00 00 00 UTF-32LE
// xx 00 xx 00 UTF-16LE
// xx xx xx xx UTF-8
if (!hasBOM_) {
unsigned pattern = (c[0] ? 1 : 0) | (c[1] ? 2 : 0) | (c[2] ? 4 : 0) | (c[3] ? 8 : 0);
switch (pattern) {
case 0x08: type_ = kUTF32BE; break;
case 0x0A: type_ = kUTF16BE; break;
case 0x01: type_ = kUTF32LE; break;
case 0x05: type_ = kUTF16LE; break;
case 0x0F: type_ = kUTF8; break;
}
}
// RUntime check whether the size of character type is sufficient. It only perform checks with assertion.
switch (type_) {
case kUTF8:
// Do nothing
break;
case kUTF16LE:
case kUTF16BE:
RAPIDJSON_ASSERT(sizeof(Ch) >= 2);
break;
case kUTF32LE:
case kUTF32BE:
RAPIDJSON_ASSERT(sizeof(Ch) >= 4);
break;
}
}
typedef Ch (*TakeFunc)(InputByteStream& is);
InputByteStream* is_;
UTFType type_;
Ch current_;
TakeFunc takeFunc_;
bool hasBOM_;
};
//! Output stream wrapper with dynamically bound encoding and automatic encoding detection.
/*!
\tparam CharType Type of character for writing.
\tparam InputByteStream type of output byte stream to be wrapped.
*/
template <typename CharType, typename OutputByteStream>
class AutoUTFOutputStream {
RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
public:
typedef CharType Ch;
//! Constructor.
/*!
\param os output stream to be wrapped.
\param type UTF encoding type.
\param putBOM Whether to write BOM at the beginning of the stream.
*/
AutoUTFOutputStream(OutputByteStream& os, UTFType type, bool putBOM) : os_(&os), type_(type) {
// RUntime check whether the size of character type is sufficient. It only perform checks with assertion.
switch (type_) {
case kUTF16LE:
case kUTF16BE:
RAPIDJSON_ASSERT(sizeof(Ch) >= 2);
break;
case kUTF32LE:
case kUTF32BE:
RAPIDJSON_ASSERT(sizeof(Ch) >= 4);
break;
case kUTF8:
// Do nothing
break;
}
static const PutFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Put) };
putFunc_ = f[type_];
if (putBOM)
PutBOM();
}
UTFType GetType() const { return type_; }
void Put(Ch c) { putFunc_(*os_, c); }
void Flush() { os_->Flush(); }
// Not implemented
Ch Peek() const { RAPIDJSON_ASSERT(false); }
Ch Take() { RAPIDJSON_ASSERT(false); }
size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; }
Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
private:
void PutBOM() {
typedef void (*PutBOMFunc)(OutputByteStream&);
static const PutBOMFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(PutBOM) };
f[type_](*os_);
}
typedef void (*PutFunc)(OutputByteStream&, Ch);
OutputByteStream* os_;
UTFType type_;
PutFunc putFunc_;
};
#undef RAPIDJSON_ENCODINGS_FUNC
} // namespace rapidjson
#endif // RAPIDJSON_FILESTREAM_H_

View file

@ -0,0 +1,527 @@
#ifndef RAPIDJSON_ENCODINGS_H_
#define RAPIDJSON_ENCODINGS_H_
#include "rapidjson.h"
namespace rapidjson {
///////////////////////////////////////////////////////////////////////////////
// Encoding
/*! \class rapidjson::Encoding
\brief Concept for encoding of Unicode characters.
\code
concept Encoding {
typename Ch; //! Type of character. A "character" is actually a code unit in unicode's definition.
//! \brief Encode a Unicode codepoint to an output stream.
//! \param os Output stream.
//! \param codepoint An unicode codepoint, ranging from 0x0 to 0x10FFFF inclusively.
template<typename OutputStream>
static void Encode(OutputStream& os, unsigned codepoint);
//! \brief Decode a Unicode codepoint from an input stream.
//! \param is Input stream.
//! \param codepoint Output of the unicode codepoint.
//! \return true if a valid codepoint can be decoded from the stream.
template <typename InputStream>
static bool Decode(InputStream& is, unsigned* codepoint);
//! \brief Validate one Unicode codepoint from an encoded stream.
//! \param is Input stream to obtain codepoint.
//! \param os Output for copying one codepoint.
//! \return true if it is valid.
//! \note This function just validating and copying the codepoint without actually decode it.
template <typename InputStream, typename OutputStream>
static bool Validate(InputStream& is, OutputStream& os);
// The following functions are deal with byte streams.
//! Take a character from input byte stream, skip BOM if exist.
template <typename InputByteStream>
static CharType TakeBOM(InputByteStream& is);
//! Take a character from input byte stream.
template <typename InputByteStream>
static Ch Take(InputByteStream& is);
//! Put BOM to output byte stream.
template <typename OutputByteStream>
static void PutBOM(OutputByteStream& os);
//! Put a character to output byte stream.
template <typename OutputByteStream>
static void Put(OutputByteStream& os, Ch c);
};
\endcode
*/
///////////////////////////////////////////////////////////////////////////////
// UTF8
//! UTF-8 encoding.
/*! http://en.wikipedia.org/wiki/UTF-8
http://tools.ietf.org/html/rfc3629
\tparam CharType Code unit for storing 8-bit UTF-8 data. Default is char.
\implements Encoding
*/
template<typename CharType = char>
struct UTF8 {
typedef CharType Ch;
template<typename OutputStream>
static void Encode(OutputStream& os, unsigned codepoint) {
if (codepoint <= 0x7F)
os.Put(codepoint & 0xFF);
else if (codepoint <= 0x7FF) {
os.Put(0xC0 | ((codepoint >> 6) & 0xFF));
os.Put(0x80 | ((codepoint & 0x3F)));
}
else if (codepoint <= 0xFFFF) {
os.Put(0xE0 | ((codepoint >> 12) & 0xFF));
os.Put(0x80 | ((codepoint >> 6) & 0x3F));
os.Put(0x80 | (codepoint & 0x3F));
}
else {
RAPIDJSON_ASSERT(codepoint <= 0x10FFFF);
os.Put(0xF0 | ((codepoint >> 18) & 0xFF));
os.Put(0x80 | ((codepoint >> 12) & 0x3F));
os.Put(0x80 | ((codepoint >> 6) & 0x3F));
os.Put(0x80 | (codepoint & 0x3F));
}
}
template <typename InputStream>
static bool Decode(InputStream& is, unsigned* codepoint) {
#define COPY() c = is.Take(); *codepoint = (*codepoint << 6) | ((unsigned char)c & 0x3Fu)
#define TRANS(mask) result &= ((GetRange((unsigned char)c) & mask) != 0)
#define TAIL() COPY(); TRANS(0x70)
Ch c = is.Take();
if (!(c & 0x80)) {
*codepoint = (unsigned char)c;
return true;
}
unsigned char type = GetRange((unsigned char)c);
*codepoint = (0xFF >> type) & (unsigned char)c;
bool result = true;
switch (type) {
case 2: TAIL(); return result;
case 3: TAIL(); TAIL(); return result;
case 4: COPY(); TRANS(0x50); TAIL(); return result;
case 5: COPY(); TRANS(0x10); TAIL(); TAIL(); return result;
case 6: TAIL(); TAIL(); TAIL(); return result;
case 10: COPY(); TRANS(0x20); TAIL(); return result;
case 11: COPY(); TRANS(0x60); TAIL(); TAIL(); return result;
default: return false;
}
#undef COPY
#undef TRANS
#undef TAIL
}
template <typename InputStream, typename OutputStream>
static bool Validate(InputStream& is, OutputStream& os) {
#define COPY() os.Put(c = is.Take())
#define TRANS(mask) result &= ((GetRange((unsigned char)c) & mask) != 0)
#define TAIL() COPY(); TRANS(0x70)
Ch c;
COPY();
if (!(c & 0x80))
return true;
bool result = true;
switch (GetRange((unsigned char)c)) {
case 2: TAIL(); return result;
case 3: TAIL(); TAIL(); return result;
case 4: COPY(); TRANS(0x50); TAIL(); return result;
case 5: COPY(); TRANS(0x10); TAIL(); TAIL(); return result;
case 6: TAIL(); TAIL(); TAIL(); return result;
case 10: COPY(); TRANS(0x20); TAIL(); return result;
case 11: COPY(); TRANS(0x60); TAIL(); TAIL(); return result;
default: return false;
}
#undef COPY
#undef TRANS
#undef TAIL
}
static unsigned char GetRange(unsigned char c) {
// Referring to DFA of http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
// With new mapping 1 -> 0x10, 7 -> 0x20, 9 -> 0x40, such that AND operation can test multiple types.
static const unsigned char type[] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,
0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8,
};
return type[c];
}
template <typename InputByteStream>
static CharType TakeBOM(InputByteStream& is) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
Ch c = Take(is);
if ((unsigned char)c != 0xEFu) return c;
c = is.Take();
if ((unsigned char)c != 0xBBu) return c;
c = is.Take();
if ((unsigned char)c != 0xBFu) return c;
c = is.Take();
return c;
}
template <typename InputByteStream>
static Ch Take(InputByteStream& is) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
return is.Take();
}
template <typename OutputByteStream>
static void PutBOM(OutputByteStream& os) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
os.Put(0xEFu); os.Put(0xBBu); os.Put(0xBFu);
}
template <typename OutputByteStream>
static void Put(OutputByteStream& os, Ch c) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
os.Put(static_cast<typename OutputByteStream::Ch>(c));
}
};
///////////////////////////////////////////////////////////////////////////////
// UTF16
//! UTF-16 encoding.
/*! http://en.wikipedia.org/wiki/UTF-16
http://tools.ietf.org/html/rfc2781
\tparam CharType Type for storing 16-bit UTF-16 data. Default is wchar_t. C++11 may use char16_t instead.
\implements Encoding
\note For in-memory access, no need to concern endianness. The code units and code points are represented by CPU's endianness.
For streaming, use UTF16LE and UTF16BE, which handle endianness.
*/
template<typename CharType = wchar_t>
struct UTF16 {
typedef CharType Ch;
RAPIDJSON_STATIC_ASSERT(sizeof(Ch) >= 2);
template<typename OutputStream>
static void Encode(OutputStream& os, unsigned codepoint) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 2);
if (codepoint <= 0xFFFF) {
RAPIDJSON_ASSERT(codepoint < 0xD800 || codepoint > 0xDFFF); // Code point itself cannot be surrogate pair
os.Put(static_cast<typename OutputStream::Ch>(codepoint));
}
else {
RAPIDJSON_ASSERT(codepoint <= 0x10FFFF);
unsigned v = codepoint - 0x10000;
os.Put(static_cast<typename OutputStream::Ch>((v >> 10) | 0xD800));
os.Put((v & 0x3FF) | 0xDC00);
}
}
template <typename InputStream>
static bool Decode(InputStream& is, unsigned* codepoint) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 2);
Ch c = is.Take();
if (c < 0xD800 || c > 0xDFFF) {
*codepoint = c;
return true;
}
else if (c <= 0xDBFF) {
*codepoint = (c & 0x3FF) << 10;
c = is.Take();
*codepoint |= (c & 0x3FF);
*codepoint += 0x10000;
return c >= 0xDC00 && c <= 0xDFFF;
}
return false;
}
template <typename InputStream, typename OutputStream>
static bool Validate(InputStream& is, OutputStream& os) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 2);
RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 2);
Ch c;
os.Put(c = is.Take());
if (c < 0xD800 || c > 0xDFFF)
return true;
else if (c <= 0xDBFF) {
os.Put(c = is.Take());
return c >= 0xDC00 && c <= 0xDFFF;
}
return false;
}
};
//! UTF-16 little endian encoding.
template<typename CharType = wchar_t>
struct UTF16LE : UTF16<CharType> {
template <typename InputByteStream>
static CharType TakeBOM(InputByteStream& is) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
CharType c = Take(is);
return (unsigned short)c == 0xFEFFu ? Take(is) : c;
}
template <typename InputByteStream>
static CharType Take(InputByteStream& is) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
CharType c = (unsigned char)is.Take();
c |= (unsigned char)is.Take() << 8;
return c;
}
template <typename OutputByteStream>
static void PutBOM(OutputByteStream& os) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
os.Put(0xFFu); os.Put(0xFEu);
}
template <typename OutputByteStream>
static void Put(OutputByteStream& os, CharType c) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
os.Put(c & 0xFFu);
os.Put((c >> 8) & 0xFFu);
}
};
//! UTF-16 big endian encoding.
template<typename CharType = wchar_t>
struct UTF16BE : UTF16<CharType> {
template <typename InputByteStream>
static CharType TakeBOM(InputByteStream& is) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
CharType c = Take(is);
return (unsigned short)c == 0xFEFFu ? Take(is) : c;
}
template <typename InputByteStream>
static CharType Take(InputByteStream& is) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
CharType c = (unsigned char)is.Take() << 8;
c |= (unsigned char)is.Take();
return c;
}
template <typename OutputByteStream>
static void PutBOM(OutputByteStream& os) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
os.Put(0xFEu); os.Put(0xFFu);
}
template <typename OutputByteStream>
static void Put(OutputByteStream& os, CharType c) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
os.Put((c >> 8) & 0xFFu);
os.Put(c & 0xFFu);
}
};
///////////////////////////////////////////////////////////////////////////////
// UTF32
//! UTF-32 encoding.
/*! http://en.wikipedia.org/wiki/UTF-32
\tparam Ch Type for storing 32-bit UTF-32 data. Default is unsigned. C++11 may use char32_t instead.
\implements Encoding
\note For in-memory access, no need to concern endianness. The code units and code points are represented by CPU's endianness.
For streaming, use UTF32LE and UTF32BE, which handle endianness.
*/
template<typename CharType = unsigned>
struct UTF32 {
typedef CharType Ch;
RAPIDJSON_STATIC_ASSERT(sizeof(Ch) >= 4);
template<typename OutputStream>
static void Encode(OutputStream& os, unsigned codepoint) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 4);
RAPIDJSON_ASSERT(codepoint <= 0x10FFFF);
os.Put(codepoint);
}
template <typename InputStream>
static bool Decode(InputStream& is, unsigned* codepoint) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 4);
Ch c = is.Take();
*codepoint = c;
return c <= 0x10FFFF;
}
template <typename InputStream, typename OutputStream>
static bool Validate(InputStream& is, OutputStream& os) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 4);
Ch c;
os.Put(c = is.Take());
return c <= 0x10FFFF;
}
};
//! UTF-32 little endian enocoding.
template<typename CharType = unsigned>
struct UTF32LE : UTF32<CharType> {
template <typename InputByteStream>
static CharType TakeBOM(InputByteStream& is) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
CharType c = Take(is);
return (unsigned)c == 0x0000FEFFu ? Take(is) : c;
}
template <typename InputByteStream>
static CharType Take(InputByteStream& is) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
CharType c = (unsigned char)is.Take();
c |= (unsigned char)is.Take() << 8;
c |= (unsigned char)is.Take() << 16;
c |= (unsigned char)is.Take() << 24;
return c;
}
template <typename OutputByteStream>
static void PutBOM(OutputByteStream& os) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
os.Put(0xFFu); os.Put(0xFEu); os.Put(0x00u); os.Put(0x00u);
}
template <typename OutputByteStream>
static void Put(OutputByteStream& os, CharType c) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
os.Put(c & 0xFFu);
os.Put((c >> 8) & 0xFFu);
os.Put((c >> 16) & 0xFFu);
os.Put((c >> 24) & 0xFFu);
}
};
//! UTF-32 big endian encoding.
template<typename CharType = unsigned>
struct UTF32BE : UTF32<CharType> {
template <typename InputByteStream>
static CharType TakeBOM(InputByteStream& is) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
CharType c = Take(is);
return (unsigned)c == 0x0000FEFFu ? Take(is) : c;
}
template <typename InputByteStream>
static CharType Take(InputByteStream& is) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
CharType c = (unsigned char)is.Take() << 24;
c |= (unsigned char)is.Take() << 16;
c |= (unsigned char)is.Take() << 8;
c |= (unsigned char)is.Take();
return c;
}
template <typename OutputByteStream>
static void PutBOM(OutputByteStream& os) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
os.Put(0x00u); os.Put(0x00u); os.Put(0xFEu); os.Put(0xFFu);
}
template <typename OutputByteStream>
static void Put(OutputByteStream& os, CharType c) {
RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
os.Put((c >> 24) & 0xFFu);
os.Put((c >> 16) & 0xFFu);
os.Put((c >> 8) & 0xFFu);
os.Put(c & 0xFFu);
}
};
///////////////////////////////////////////////////////////////////////////////
// AutoUTF
//! Runtime-specified UTF encoding type of a stream.
enum UTFType {
kUTF8 = 0, //!< UTF-8.
kUTF16LE = 1, //!< UTF-16 little endian.
kUTF16BE = 2, //!< UTF-16 big endian.
kUTF32LE = 3, //!< UTF-32 little endian.
kUTF32BE = 4, //!< UTF-32 big endian.
};
//! Dynamically select encoding according to stream's runtime-specified UTF encoding type.
/*! \note This class can be used with AutoUTFInputtStream and AutoUTFOutputStream, which provides GetType().
*/
template<typename CharType>
struct AutoUTF {
typedef CharType Ch;
#define RAPIDJSON_ENCODINGS_FUNC(x) UTF8<Ch>::x, UTF16LE<Ch>::x, UTF16BE<Ch>::x, UTF32LE<Ch>::x, UTF32BE<Ch>::x
template<typename OutputStream>
RAPIDJSON_FORCEINLINE static void Encode(OutputStream& os, unsigned codepoint) {
typedef void (*EncodeFunc)(OutputStream&, unsigned);
static const EncodeFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Encode) };
(*f[os.GetType()])(os, codepoint);
}
template <typename InputStream>
RAPIDJSON_FORCEINLINE static bool Decode(InputStream& is, unsigned* codepoint) {
typedef bool (*DecodeFunc)(InputStream&, unsigned*);
static const DecodeFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Decode) };
return (*f[is.GetType()])(is, codepoint);
}
template <typename InputStream, typename OutputStream>
RAPIDJSON_FORCEINLINE static bool Validate(InputStream& is, OutputStream& os) {
typedef bool (*ValidateFunc)(InputStream&, OutputStream&);
static const ValidateFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Validate) };
return (*f[is.GetType()])(is, os);
}
#undef RAPIDJSON_ENCODINGS_FUNC
};
///////////////////////////////////////////////////////////////////////////////
// Transcoder
//! Encoding conversion.
template<typename SourceEncoding, typename TargetEncoding>
struct Transcoder {
//! Take one Unicode codepoint from source encoding, convert it to target encoding and put it to the output stream.
template<typename InputStream, typename OutputStream>
RAPIDJSON_FORCEINLINE static bool Transcode(InputStream& is, OutputStream& os) {
unsigned codepoint;
if (!SourceEncoding::Decode(is, &codepoint))
return false;
TargetEncoding::Encode(os, codepoint);
return true;
}
//! Validate one Unicode codepoint from an encoded stream.
template<typename InputStream, typename OutputStream>
RAPIDJSON_FORCEINLINE static bool Validate(InputStream& is, OutputStream& os) {
return Transcode(is, os); // Since source/target encoding is different, must transcode.
}
};
//! Specialization of Transcoder with same source and target encoding.
template<typename Encoding>
struct Transcoder<Encoding, Encoding> {
template<typename InputStream, typename OutputStream>
RAPIDJSON_FORCEINLINE static bool Transcode(InputStream& is, OutputStream& os) {
os.Put(is.Take()); // Just copy one code unit. This semantic is different from primary template class.
return true;
}
template<typename InputStream, typename OutputStream>
RAPIDJSON_FORCEINLINE static bool Validate(InputStream& is, OutputStream& os) {
return Encoding::Validate(is, os); // source/target encoding are the same
}
};
} // namespace rapidjson
#endif // RAPIDJSON_ENCODINGS_H_

View file

@ -0,0 +1,74 @@
#ifndef RAPIDJSON_FILEREADSTREAM_H_
#define RAPIDJSON_FILEREADSTREAM_H_
#include "rapidjson.h"
#include <cstdio>
namespace rapidjson {
//! File byte stream for input using fread().
/*!
\implements Stream
*/
class FileReadStream {
public:
typedef char Ch; //!< Character type (byte).
//! Constructor.
/*!
\param fp File pointer opened for read.
\param buffer user-supplied buffer.
\param bufferSize size of buffer in bytes. Must >=4 bytes.
*/
FileReadStream(FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferSize_(bufferSize), bufferLast_(0), current_(buffer_), readCount_(0), count_(0), eof_(false) {
RAPIDJSON_ASSERT(fp_ != 0);
RAPIDJSON_ASSERT(bufferSize >= 4);
Read();
}
Ch Peek() const { return *current_; }
Ch Take() { Ch c = *current_; Read(); return c; }
size_t Tell() const { return count_ + (current_ - buffer_); }
// Not implemented
void Put(Ch) { RAPIDJSON_ASSERT(false); }
void Flush() { RAPIDJSON_ASSERT(false); }
Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
// For encoding detection only.
const Ch* Peek4() const {
return (current_ + 4 <= bufferLast_) ? current_ : 0;
}
private:
void Read() {
if (current_ < bufferLast_)
++current_;
else if (!eof_) {
count_ += readCount_;
readCount_ = fread(buffer_, 1, bufferSize_, fp_);
bufferLast_ = buffer_ + readCount_ - 1;
current_ = buffer_;
if (readCount_ < bufferSize_) {
buffer_[readCount_] = '\0';
++bufferLast_;
eof_ = true;
}
}
}
FILE* fp_;
Ch *buffer_;
size_t bufferSize_;
Ch *bufferLast_;
Ch *current_;
size_t readCount_;
size_t count_; //!< Number of characters read
bool eof_;
};
} // namespace rapidjson
#endif // RAPIDJSON_FILESTREAM_H_

View file

@ -0,0 +1,49 @@
#ifndef RAPIDJSON_FILESTREAM_H_
#define RAPIDJSON_FILESTREAM_H_
#include "rapidjson.h"
#include <cstdio>
namespace rapidjson {
//! (Depreciated) Wrapper of C file stream for input or output.
/*!
This simple wrapper does not check the validity of the stream.
\implements Stream
\deprecated { This was only for basic testing in version 0.1, it is found that the performance is very low by using fgetc(). Use FileReadStream instead. }
*/
class FileStream {
public:
typedef char Ch; //!< Character type. Only support char.
FileStream(FILE* fp) : fp_(fp), count_(0) { Read(); }
char Peek() const { return current_; }
char Take() { char c = current_; Read(); return c; }
size_t Tell() const { return count_; }
void Put(char c) { fputc(c, fp_); }
void Flush() { fflush(fp_); }
// Not implemented
char* PutBegin() { return 0; }
size_t PutEnd(char*) { return 0; }
private:
void Read() {
RAPIDJSON_ASSERT(fp_ != 0);
int c = fgetc(fp_);
if (c != EOF) {
current_ = (char)c;
count_++;
}
else if (current_ != '\0')
current_ = '\0';
}
FILE* fp_;
char current_;
size_t count_;
};
} // namespace rapidjson
#endif // RAPIDJSON_FILESTREAM_H_

View file

@ -0,0 +1,73 @@
#ifndef RAPIDJSON_FILEWRITESTREAM_H_
#define RAPIDJSON_FILEWRITESTREAM_H_
#include "rapidjson.h"
#include <cstdio>
namespace rapidjson {
//! Wrapper of C file stream for input using fread().
/*!
\implements Stream
*/
class FileWriteStream {
public:
typedef char Ch; //!< Character type. Only support char.
FileWriteStream(FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferEnd_(buffer + bufferSize), current_(buffer_) {
RAPIDJSON_ASSERT(fp_ != 0);
}
void Put(char c) {
if (current_ >= bufferEnd_)
Flush();
*current_++ = c;
}
void PutN(char c, size_t n) {
size_t avail = bufferEnd_ - current_;
while (n > avail) {
memset(current_, c, avail);
current_ += avail;
Flush();
n -= avail;
avail = bufferEnd_ - current_;
}
if (n > 0) {
memset(current_, c, n);
current_ += n;
}
}
void Flush() {
if (current_ != buffer_) {
fwrite(buffer_, 1, current_ - buffer_, fp_);
current_ = buffer_;
}
}
// Not implemented
char Peek() const { RAPIDJSON_ASSERT(false); return 0; }
char Take() { RAPIDJSON_ASSERT(false); return 0; }
size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; }
char* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
size_t PutEnd(char*) { RAPIDJSON_ASSERT(false); return 0; }
private:
FILE* fp_;
char *buffer_;
char *bufferEnd_;
char *current_;
};
//! Implement specialized version of PutN() with memset() for better performance.
template<>
inline void PutN(FileWriteStream& stream, char c, size_t n) {
stream.PutN(c, n);
}
} // namespace rapidjson
#endif // RAPIDJSON_FILESTREAM_H_

View file

@ -0,0 +1,54 @@
#ifndef RAPIDJSON_POW10_
#define RAPIDJSON_POW10_
namespace rapidjson {
namespace internal {
//! Computes integer powers of 10 in double (10.0^n).
/*! This function uses lookup table for fast and accurate results.
\param n positive/negative exponent. Must <= 308.
\return 10.0^n
*/
inline double Pow10(int n) {
static const double e[] = { // 1e-308...1e308: 617 * 8 bytes = 4936 bytes
1e-308,1e-307,1e-306,1e-305,1e-304,1e-303,1e-302,1e-301,1e-300,
1e-299,1e-298,1e-297,1e-296,1e-295,1e-294,1e-293,1e-292,1e-291,1e-290,1e-289,1e-288,1e-287,1e-286,1e-285,1e-284,1e-283,1e-282,1e-281,1e-280,
1e-279,1e-278,1e-277,1e-276,1e-275,1e-274,1e-273,1e-272,1e-271,1e-270,1e-269,1e-268,1e-267,1e-266,1e-265,1e-264,1e-263,1e-262,1e-261,1e-260,
1e-259,1e-258,1e-257,1e-256,1e-255,1e-254,1e-253,1e-252,1e-251,1e-250,1e-249,1e-248,1e-247,1e-246,1e-245,1e-244,1e-243,1e-242,1e-241,1e-240,
1e-239,1e-238,1e-237,1e-236,1e-235,1e-234,1e-233,1e-232,1e-231,1e-230,1e-229,1e-228,1e-227,1e-226,1e-225,1e-224,1e-223,1e-222,1e-221,1e-220,
1e-219,1e-218,1e-217,1e-216,1e-215,1e-214,1e-213,1e-212,1e-211,1e-210,1e-209,1e-208,1e-207,1e-206,1e-205,1e-204,1e-203,1e-202,1e-201,1e-200,
1e-199,1e-198,1e-197,1e-196,1e-195,1e-194,1e-193,1e-192,1e-191,1e-190,1e-189,1e-188,1e-187,1e-186,1e-185,1e-184,1e-183,1e-182,1e-181,1e-180,
1e-179,1e-178,1e-177,1e-176,1e-175,1e-174,1e-173,1e-172,1e-171,1e-170,1e-169,1e-168,1e-167,1e-166,1e-165,1e-164,1e-163,1e-162,1e-161,1e-160,
1e-159,1e-158,1e-157,1e-156,1e-155,1e-154,1e-153,1e-152,1e-151,1e-150,1e-149,1e-148,1e-147,1e-146,1e-145,1e-144,1e-143,1e-142,1e-141,1e-140,
1e-139,1e-138,1e-137,1e-136,1e-135,1e-134,1e-133,1e-132,1e-131,1e-130,1e-129,1e-128,1e-127,1e-126,1e-125,1e-124,1e-123,1e-122,1e-121,1e-120,
1e-119,1e-118,1e-117,1e-116,1e-115,1e-114,1e-113,1e-112,1e-111,1e-110,1e-109,1e-108,1e-107,1e-106,1e-105,1e-104,1e-103,1e-102,1e-101,1e-100,
1e-99, 1e-98, 1e-97, 1e-96, 1e-95, 1e-94, 1e-93, 1e-92, 1e-91, 1e-90, 1e-89, 1e-88, 1e-87, 1e-86, 1e-85, 1e-84, 1e-83, 1e-82, 1e-81, 1e-80,
1e-79, 1e-78, 1e-77, 1e-76, 1e-75, 1e-74, 1e-73, 1e-72, 1e-71, 1e-70, 1e-69, 1e-68, 1e-67, 1e-66, 1e-65, 1e-64, 1e-63, 1e-62, 1e-61, 1e-60,
1e-59, 1e-58, 1e-57, 1e-56, 1e-55, 1e-54, 1e-53, 1e-52, 1e-51, 1e-50, 1e-49, 1e-48, 1e-47, 1e-46, 1e-45, 1e-44, 1e-43, 1e-42, 1e-41, 1e-40,
1e-39, 1e-38, 1e-37, 1e-36, 1e-35, 1e-34, 1e-33, 1e-32, 1e-31, 1e-30, 1e-29, 1e-28, 1e-27, 1e-26, 1e-25, 1e-24, 1e-23, 1e-22, 1e-21, 1e-20,
1e-19, 1e-18, 1e-17, 1e-16, 1e-15, 1e-14, 1e-13, 1e-12, 1e-11, 1e-10, 1e-9, 1e-8, 1e-7, 1e-6, 1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1e+0,
1e+1, 1e+2, 1e+3, 1e+4, 1e+5, 1e+6, 1e+7, 1e+8, 1e+9, 1e+10, 1e+11, 1e+12, 1e+13, 1e+14, 1e+15, 1e+16, 1e+17, 1e+18, 1e+19, 1e+20,
1e+21, 1e+22, 1e+23, 1e+24, 1e+25, 1e+26, 1e+27, 1e+28, 1e+29, 1e+30, 1e+31, 1e+32, 1e+33, 1e+34, 1e+35, 1e+36, 1e+37, 1e+38, 1e+39, 1e+40,
1e+41, 1e+42, 1e+43, 1e+44, 1e+45, 1e+46, 1e+47, 1e+48, 1e+49, 1e+50, 1e+51, 1e+52, 1e+53, 1e+54, 1e+55, 1e+56, 1e+57, 1e+58, 1e+59, 1e+60,
1e+61, 1e+62, 1e+63, 1e+64, 1e+65, 1e+66, 1e+67, 1e+68, 1e+69, 1e+70, 1e+71, 1e+72, 1e+73, 1e+74, 1e+75, 1e+76, 1e+77, 1e+78, 1e+79, 1e+80,
1e+81, 1e+82, 1e+83, 1e+84, 1e+85, 1e+86, 1e+87, 1e+88, 1e+89, 1e+90, 1e+91, 1e+92, 1e+93, 1e+94, 1e+95, 1e+96, 1e+97, 1e+98, 1e+99, 1e+100,
1e+101,1e+102,1e+103,1e+104,1e+105,1e+106,1e+107,1e+108,1e+109,1e+110,1e+111,1e+112,1e+113,1e+114,1e+115,1e+116,1e+117,1e+118,1e+119,1e+120,
1e+121,1e+122,1e+123,1e+124,1e+125,1e+126,1e+127,1e+128,1e+129,1e+130,1e+131,1e+132,1e+133,1e+134,1e+135,1e+136,1e+137,1e+138,1e+139,1e+140,
1e+141,1e+142,1e+143,1e+144,1e+145,1e+146,1e+147,1e+148,1e+149,1e+150,1e+151,1e+152,1e+153,1e+154,1e+155,1e+156,1e+157,1e+158,1e+159,1e+160,
1e+161,1e+162,1e+163,1e+164,1e+165,1e+166,1e+167,1e+168,1e+169,1e+170,1e+171,1e+172,1e+173,1e+174,1e+175,1e+176,1e+177,1e+178,1e+179,1e+180,
1e+181,1e+182,1e+183,1e+184,1e+185,1e+186,1e+187,1e+188,1e+189,1e+190,1e+191,1e+192,1e+193,1e+194,1e+195,1e+196,1e+197,1e+198,1e+199,1e+200,
1e+201,1e+202,1e+203,1e+204,1e+205,1e+206,1e+207,1e+208,1e+209,1e+210,1e+211,1e+212,1e+213,1e+214,1e+215,1e+216,1e+217,1e+218,1e+219,1e+220,
1e+221,1e+222,1e+223,1e+224,1e+225,1e+226,1e+227,1e+228,1e+229,1e+230,1e+231,1e+232,1e+233,1e+234,1e+235,1e+236,1e+237,1e+238,1e+239,1e+240,
1e+241,1e+242,1e+243,1e+244,1e+245,1e+246,1e+247,1e+248,1e+249,1e+250,1e+251,1e+252,1e+253,1e+254,1e+255,1e+256,1e+257,1e+258,1e+259,1e+260,
1e+261,1e+262,1e+263,1e+264,1e+265,1e+266,1e+267,1e+268,1e+269,1e+270,1e+271,1e+272,1e+273,1e+274,1e+275,1e+276,1e+277,1e+278,1e+279,1e+280,
1e+281,1e+282,1e+283,1e+284,1e+285,1e+286,1e+287,1e+288,1e+289,1e+290,1e+291,1e+292,1e+293,1e+294,1e+295,1e+296,1e+297,1e+298,1e+299,1e+300,
1e+301,1e+302,1e+303,1e+304,1e+305,1e+306,1e+307,1e+308
};
RAPIDJSON_ASSERT(n <= 308);
return n < -308 ? 0.0 : e[n + 308];
}
} // namespace internal
} // namespace rapidjson
#endif // RAPIDJSON_POW10_

View file

@ -0,0 +1,83 @@
#ifndef RAPIDJSON_INTERNAL_STACK_H_
#define RAPIDJSON_INTERNAL_STACK_H_
namespace rapidjson {
namespace internal {
///////////////////////////////////////////////////////////////////////////////
// Stack
//! A type-unsafe stack for storing different types of data.
/*! \tparam Allocator Allocator for allocating stack memory.
*/
template <typename Allocator>
class Stack {
public:
Stack(Allocator* allocator, size_t stack_capacity) : allocator_(allocator), own_allocator_(0), stack_(0), stack_top_(0), stack_end_(0), stack_capacity_(stack_capacity) {
RAPIDJSON_ASSERT(stack_capacity_ > 0);
if (!allocator_)
own_allocator_ = allocator_ = new Allocator();
stack_top_ = stack_ = (char*)allocator_->Malloc(stack_capacity_);
stack_end_ = stack_ + stack_capacity_;
}
~Stack() {
Allocator::Free(stack_);
delete own_allocator_; // Only delete if it is owned by the stack
}
void Clear() { /*stack_top_ = 0;*/ stack_top_ = stack_; }
template<typename T>
T* Push(size_t count = 1) {
// Expand the stack if needed
if (stack_top_ + sizeof(T) * count >= stack_end_) {
size_t new_capacity = stack_capacity_ * 2;
size_t size = GetSize();
size_t new_size = GetSize() + sizeof(T) * count;
if (new_capacity < new_size)
new_capacity = new_size;
stack_ = (char*)allocator_->Realloc(stack_, stack_capacity_, new_capacity);
stack_capacity_ = new_capacity;
stack_top_ = stack_ + size;
stack_end_ = stack_ + stack_capacity_;
}
T* ret = (T*)stack_top_;
stack_top_ += sizeof(T) * count;
return ret;
}
template<typename T>
T* Pop(size_t count) {
RAPIDJSON_ASSERT(GetSize() >= count * sizeof(T));
stack_top_ -= count * sizeof(T);
return (T*)stack_top_;
}
template<typename T>
T* Top() {
RAPIDJSON_ASSERT(GetSize() >= sizeof(T));
return (T*)(stack_top_ - sizeof(T));
}
template<typename T>
T* Bottom() { return (T*)stack_; }
Allocator& GetAllocator() { return *allocator_; }
bool Empty() const { return stack_top_ == stack_; }
size_t GetSize() const { return stack_top_ - stack_; }
size_t GetCapacity() const { return stack_capacity_; }
private:
Allocator* allocator_;
Allocator* own_allocator_;
char *stack_;
char *stack_top_;
char *stack_end_;
size_t stack_capacity_;
};
} // namespace internal
} // namespace rapidjson
#endif // RAPIDJSON_STACK_H_

View file

@ -0,0 +1,24 @@
#ifndef RAPIDJSON_INTERNAL_STRFUNC_H_
#define RAPIDJSON_INTERNAL_STRFUNC_H_
namespace rapidjson {
namespace internal {
//! Custom strlen() which works on different character types.
/*! \tparam Ch Character type (e.g. char, wchar_t, short)
\param s Null-terminated input string.
\return Number of characters in the string.
\note This has the same semantics as strlen(), the return value is not number of Unicode codepoints.
*/
template <typename Ch>
inline SizeType StrLen(const Ch* s) {
const Ch* p = s;
while (*p != '\0')
++p;
return SizeType(p - s);
}
} // namespace internal
} // namespace rapidjson
#endif // RAPIDJSON_INTERNAL_STRFUNC_H_

View file

@ -0,0 +1,160 @@
#ifndef RAPIDJSON_PRETTYWRITER_H_
#define RAPIDJSON_PRETTYWRITER_H_
#include "writer.h"
namespace rapidjson {
//! Writer with indentation and spacing.
/*!
\tparam OutputStream Type of ouptut os.
\tparam Encoding Encoding of both source strings and output.
\tparam Allocator Type of allocator for allocating memory of stack.
*/
template<typename OutputStream, typename SourceEncoding = UTF8<>, typename TargetEncoding = UTF8<>, typename Allocator = MemoryPoolAllocator<> >
class PrettyWriter : public Writer<OutputStream, SourceEncoding, TargetEncoding, Allocator> {
public:
typedef Writer<OutputStream, SourceEncoding, TargetEncoding, Allocator> Base;
typedef typename Base::Ch Ch;
//! Constructor
/*! \param os Output os.
\param allocator User supplied allocator. If it is null, it will create a private one.
\param levelDepth Initial capacity of
*/
PrettyWriter(OutputStream& os, Allocator* allocator = 0, size_t levelDepth = Base::kDefaultLevelDepth) :
Base(os, allocator, levelDepth), indentChar_(' '), indentCharCount_(4) {}
//! Set custom indentation.
/*! \param indentChar Character for indentation. Must be whitespace character (' ', '\t', '\n', '\r').
\param indentCharCount Number of indent characters for each indentation level.
\note The default indentation is 4 spaces.
*/
PrettyWriter& SetIndent(Ch indentChar, unsigned indentCharCount) {
RAPIDJSON_ASSERT(indentChar == ' ' || indentChar == '\t' || indentChar == '\n' || indentChar == '\r');
indentChar_ = indentChar;
indentCharCount_ = indentCharCount;
return *this;
}
//@name Implementation of Handler.
//@{
PrettyWriter& Null() { PrettyPrefix(kNullType); Base::WriteNull(); return *this; }
PrettyWriter& Bool(bool b) { PrettyPrefix(b ? kTrueType : kFalseType); Base::WriteBool(b); return *this; }
PrettyWriter& Int(int i) { PrettyPrefix(kNumberType); Base::WriteInt(i); return *this; }
PrettyWriter& Uint(unsigned u) { PrettyPrefix(kNumberType); Base::WriteUint(u); return *this; }
PrettyWriter& Int64(int64_t i64) { PrettyPrefix(kNumberType); Base::WriteInt64(i64); return *this; }
PrettyWriter& Uint64(uint64_t u64) { PrettyPrefix(kNumberType); Base::WriteUint64(u64); return *this; }
PrettyWriter& Double(double d) { PrettyPrefix(kNumberType); Base::WriteDouble(d); return *this; }
PrettyWriter& String(const Ch* str, SizeType length, bool copy = false) {
(void)copy;
PrettyPrefix(kStringType);
Base::WriteString(str, length);
return *this;
}
PrettyWriter& StartObject() {
PrettyPrefix(kObjectType);
new (Base::level_stack_.template Push<typename Base::Level>()) typename Base::Level(false);
Base::WriteStartObject();
return *this;
}
PrettyWriter& EndObject(SizeType memberCount = 0) {
(void)memberCount;
RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level));
RAPIDJSON_ASSERT(!Base::level_stack_.template Top<typename Base::Level>()->inArray);
bool empty = Base::level_stack_.template Pop<typename Base::Level>(1)->valueCount == 0;
if (!empty) {
Base::os_.Put('\n');
WriteIndent();
}
Base::WriteEndObject();
if (Base::level_stack_.Empty()) // end of json text
Base::os_.flush();
return *this;
}
PrettyWriter& StartArray() {
PrettyPrefix(kArrayType);
new (Base::level_stack_.template Push<typename Base::Level>()) typename Base::Level(true);
Base::WriteStartArray();
return *this;
}
PrettyWriter& EndArray(SizeType memberCount = 0) {
(void)memberCount;
RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level));
RAPIDJSON_ASSERT(Base::level_stack_.template Top<typename Base::Level>()->inArray);
bool empty = Base::level_stack_.template Pop<typename Base::Level>(1)->valueCount == 0;
if (!empty) {
Base::os_.Put('\n');
WriteIndent();
}
Base::WriteEndArray();
if (Base::level_stack_.Empty()) // end of json text
Base::os_.flush();
return *this;
}
//@}
//! Simpler but slower overload.
PrettyWriter& String(const Ch* str) { return String(str, internal::StrLen(str)); }
protected:
void PrettyPrefix(Type type) {
(void)type;
if (Base::level_stack_.GetSize() != 0) { // this value is not at root
typename Base::Level* level = Base::level_stack_.template Top<typename Base::Level>();
if (level->inArray) {
if (level->valueCount > 0) {
Base::os_.Put(','); // add comma if it is not the first element in array
Base::os_.Put('\n');
}
else
Base::os_.Put('\n');
WriteIndent();
}
else { // in object
if (level->valueCount > 0) {
if (level->valueCount % 2 == 0) {
Base::os_.Put(',');
Base::os_.Put('\n');
}
else {
Base::os_.Put(':');
Base::os_.Put(' ');
}
}
else
Base::os_.Put('\n');
if (level->valueCount % 2 == 0)
WriteIndent();
}
if (!level->inArray && level->valueCount % 2 == 0)
RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even number should be a name
level->valueCount++;
}
else
RAPIDJSON_ASSERT(type == kObjectType || type == kArrayType);
}
void WriteIndent() {
size_t count = (Base::level_stack_.GetSize() / sizeof(typename Base::Level)) * indentCharCount_;
PutN(Base::os_, indentChar_, count);
}
Ch indentChar_;
unsigned indentCharCount_;
};
} // namespace rapidjson
#endif // RAPIDJSON_RAPIDJSON_H_

View file

@ -0,0 +1,256 @@
#ifndef RAPIDJSON_RAPIDJSON_H_
#define RAPIDJSON_RAPIDJSON_H_
// Copyright (c) 2011 Milo Yip (miloyip@gmail.com)
// Version 0.1
#include <cstdlib> // malloc(), realloc(), free()
#include <cstring> // memcpy()
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_NO_INT64DEFINE
// Here defines int64_t and uint64_t types in global namespace.
// If user have their own definition, can define RAPIDJSON_NO_INT64DEFINE to disable this.
#ifndef RAPIDJSON_NO_INT64DEFINE
#ifdef _MSC_VER
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#define RAPIDJSON_FORCEINLINE __forceinline
#else
#include <inttypes.h>
#define RAPIDJSON_FORCEINLINE
#endif
#endif // RAPIDJSON_NO_INT64TYPEDEF
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_ENDIAN
#define RAPIDJSON_LITTLEENDIAN 0 //!< Little endian machine
#define RAPIDJSON_BIGENDIAN 1 //!< Big endian machine
//! Endianness of the machine.
/*! GCC provided macro for detecting endianness of the target machine. But other
compilers may not have this. User can define RAPIDJSON_ENDIAN to either
RAPIDJSON_LITTLEENDIAN or RAPIDJSON_BIGENDIAN.
*/
#ifndef RAPIDJSON_ENDIAN
#ifdef __BYTE_ORDER__
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN
#else
#define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN
#endif // __BYTE_ORDER__
#else
#define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN // Assumes little endian otherwise.
#endif
#endif // RAPIDJSON_ENDIAN
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_ALIGNSIZE
//! Data alignment of the machine.
/*!
Some machine requires strict data alignment.
Currently the default uses 4 bytes alignment. User can customize this.
*/
#ifndef RAPIDJSON_ALIGN
#define RAPIDJSON_ALIGN(x) ((x + 3) & ~3)
#endif
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_SSE2/RAPIDJSON_SSE42/RAPIDJSON_SIMD
// Enable SSE2 optimization.
//#define RAPIDJSON_SSE2
// Enable SSE4.2 optimization.
//#define RAPIDJSON_SSE42
#if defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42)
#define RAPIDJSON_SIMD
#endif
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_NO_SIZETYPEDEFINE
#ifndef RAPIDJSON_NO_SIZETYPEDEFINE
namespace rapidjson {
//! Use 32-bit array/string indices even for 64-bit platform, instead of using size_t.
/*! User may override the SizeType by defining RAPIDJSON_NO_SIZETYPEDEFINE.
*/
typedef unsigned SizeType;
} // namespace rapidjson
#endif
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_ASSERT
//! Assertion.
/*! By default, rapidjson uses C assert() for assertion.
User can override it by defining RAPIDJSON_ASSERT(x) macro.
*/
#ifndef RAPIDJSON_ASSERT
#include <cassert>
#define RAPIDJSON_ASSERT(x) assert(x)
#endif // RAPIDJSON_ASSERT
///////////////////////////////////////////////////////////////////////////////
// RAPIDJSON_STATIC_ASSERT
// Adopt from boost
#ifndef RAPIDJSON_STATIC_ASSERT
namespace rapidjson {
template <bool x> struct STATIC_ASSERTION_FAILURE;
template <> struct STATIC_ASSERTION_FAILURE<true> { enum { value = 1 }; };
template<int x> struct StaticAssertTest {};
} // namespace rapidjson
#define RAPIDJSON_JOIN(X, Y) RAPIDJSON_DO_JOIN(X, Y)
#define RAPIDJSON_DO_JOIN(X, Y) RAPIDJSON_DO_JOIN2(X, Y)
#define RAPIDJSON_DO_JOIN2(X, Y) X##Y
#define RAPIDJSON_STATIC_ASSERT(x) typedef ::rapidjson::StaticAssertTest<\
sizeof(::rapidjson::STATIC_ASSERTION_FAILURE<bool(x) >)>\
RAPIDJSON_JOIN(StaticAssertTypedef, __LINE__)
#endif
///////////////////////////////////////////////////////////////////////////////
// Helpers
#define RAPIDJSON_MULTILINEMACRO_BEGIN do {
#define RAPIDJSON_MULTILINEMACRO_END \
} while((void)0, 0)
///////////////////////////////////////////////////////////////////////////////
// Allocators and Encodings
#include "allocators.h"
#include "encodings.h"
namespace rapidjson {
///////////////////////////////////////////////////////////////////////////////
// Stream
/*! \class rapidjson::Stream
\brief Concept for reading and writing characters.
For read-only stream, no need to implement PutBegin(), Put(), Flush() and PutEnd().
For write-only stream, only need to implement Put() and Flush().
\code
concept Stream {
typename Ch; //!< Character type of the stream.
//! Read the current character from stream without moving the read cursor.
Ch Peek() const;
//! Read the current character from stream and moving the read cursor to next character.
Ch Take();
//! Get the current read cursor.
//! \return Number of characters read from start.
size_t Tell();
//! Begin writing operation at the current read pointer.
//! \return The begin writer pointer.
Ch* PutBegin();
//! Write a character.
void Put(Ch c);
//! Flush the buffer.
void Flush();
//! End the writing operation.
//! \param begin The begin write pointer returned by PutBegin().
//! \return Number of characters written.
size_t PutEnd(Ch* begin);
}
\endcode
*/
//! Put N copies of a character to a stream.
template<typename Stream, typename Ch>
inline void PutN(Stream& stream, Ch c, size_t n) {
for (size_t i = 0; i < n; i++)
stream.Put(c);
}
///////////////////////////////////////////////////////////////////////////////
// StringStream
//! Read-only string stream.
/*! \implements Stream
*/
template <typename Encoding>
struct GenericStringStream {
typedef typename Encoding::Ch Ch;
GenericStringStream(const Ch *src) : src_(src), head_(src) {}
Ch Peek() const { return *src_; }
Ch Take() { return *src_++; }
size_t Tell() const { return src_ - head_; }
Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
void Put(Ch) { RAPIDJSON_ASSERT(false); }
void Flush() { RAPIDJSON_ASSERT(false); }
size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
const Ch* src_; //!< Current read position.
const Ch* head_; //!< Original head of the string.
};
typedef GenericStringStream<UTF8<> > StringStream;
///////////////////////////////////////////////////////////////////////////////
// InsituStringStream
//! A read-write string stream.
/*! This string stream is particularly designed for in-situ parsing.
\implements Stream
*/
template <typename Encoding>
struct GenericInsituStringStream {
typedef typename Encoding::Ch Ch;
GenericInsituStringStream(Ch *src) : src_(src), dst_(0), head_(src) {}
// Read
Ch Peek() { return *src_; }
Ch Take() { return *src_++; }
size_t Tell() { return src_ - head_; }
// Write
Ch* PutBegin() { return dst_ = src_; }
void Put(Ch c) { RAPIDJSON_ASSERT(dst_ != 0); *dst_++ = c; }
void Flush() {}
size_t PutEnd(Ch* begin) { return dst_ - begin; }
Ch* src_;
Ch* dst_;
Ch* head_;
};
typedef GenericInsituStringStream<UTF8<> > InsituStringStream;
///////////////////////////////////////////////////////////////////////////////
// Type
//! Type of JSON value
enum Type {
kNullType = 0, //!< null
kFalseType = 1, //!< false
kTrueType = 2, //!< true
kObjectType = 3, //!< object
kArrayType = 4, //!< array
kStringType = 5, //!< string
kNumberType = 6, //!< number
};
} // namespace rapidjson
#endif // RAPIDJSON_RAPIDJSON_H_

View file

@ -0,0 +1,669 @@
#ifndef RAPIDJSON_READER_H_
#define RAPIDJSON_READER_H_
// Copyright (c) 2011 Milo Yip (miloyip@gmail.com)
// Version 0.1
#include "rapidjson.h"
#include "encodings.h"
#include "internal/pow10.h"
#include "internal/stack.h"
#include <csetjmp>
#ifdef RAPIDJSON_SSE42
#include <nmmintrin.h>
#elif defined(RAPIDJSON_SSE2)
#include <emmintrin.h>
#endif
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4127) // conditional expression is constant
#endif
#ifndef RAPIDJSON_PARSE_ERROR
#define RAPIDJSON_PARSE_ERROR(msg, offset) \
RAPIDJSON_MULTILINEMACRO_BEGIN \
parseError_ = msg; \
errorOffset_ = offset; \
longjmp(jmpbuf_, 1); \
RAPIDJSON_MULTILINEMACRO_END
#endif
namespace rapidjson {
///////////////////////////////////////////////////////////////////////////////
// ParseFlag
//! Combination of parseFlags
enum ParseFlag {
kParseDefaultFlags = 0, //!< Default parse flags. Non-destructive parsing. Text strings are decoded into allocated buffer.
kParseInsituFlag = 1, //!< In-situ(destructive) parsing.
kParseValidateEncodingFlag = 2, //!< Validate encoding of JSON strings.
};
///////////////////////////////////////////////////////////////////////////////
// Handler
/*! \class rapidjson::Handler
\brief Concept for receiving events from GenericReader upon parsing.
\code
concept Handler {
typename Ch;
void Null();
void Bool(bool b);
void Int(int i);
void Uint(unsigned i);
void Int64(int64_t i);
void Uint64(uint64_t i);
void Double(double d);
void String(const Ch* str, SizeType length, bool copy);
void StartObject();
void EndObject(SizeType memberCount);
void StartArray();
void EndArray(SizeType elementCount);
};
\endcode
*/
///////////////////////////////////////////////////////////////////////////////
// BaseReaderHandler
//! Default implementation of Handler.
/*! This can be used as base class of any reader handler.
\implements Handler
*/
template<typename Encoding = UTF8<> >
struct BaseReaderHandler {
typedef typename Encoding::Ch Ch;
void Default() {}
void Null() { Default(); }
void Bool(bool) { Default(); }
void Int(int) { Default(); }
void Uint(unsigned) { Default(); }
void Int64(int64_t) { Default(); }
void Uint64(uint64_t) { Default(); }
void Double(double) { Default(); }
void String(const Ch*, SizeType, bool) { Default(); }
void StartObject() { Default(); }
void EndObject(SizeType) { Default(); }
void StartArray() { Default(); }
void EndArray(SizeType) { Default(); }
};
///////////////////////////////////////////////////////////////////////////////
// SkipWhitespace
//! Skip the JSON white spaces in a stream.
/*! \param stream A input stream for skipping white spaces.
\note This function has SSE2/SSE4.2 specialization.
*/
template<typename InputStream>
void SkipWhitespace(InputStream& is) {
InputStream s = is; // Use a local copy for optimization
while (s.Peek() == ' ' || s.Peek() == '\n' || s.Peek() == '\r' || s.Peek() == '\t')
s.Take();
is = s;
}
#ifdef RAPIDJSON_SSE42
//! Skip whitespace with SSE 4.2 pcmpistrm instruction, testing 16 8-byte characters at once.
inline const char *SkipWhitespace_SIMD(const char* p) {
static const char whitespace[16] = " \n\r\t";
__m128i w = _mm_loadu_si128((const __m128i *)&whitespace[0]);
for (;;) {
__m128i s = _mm_loadu_si128((const __m128i *)p);
unsigned r = _mm_cvtsi128_si32(_mm_cmpistrm(w, s, _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_BIT_MASK | _SIDD_NEGATIVE_POLARITY));
if (r == 0) // all 16 characters are whitespace
p += 16;
else { // some of characters may be non-whitespace
#ifdef _MSC_VER // Find the index of first non-whitespace
unsigned long offset;
if (_BitScanForward(&offset, r))
return p + offset;
#else
if (r != 0)
return p + __builtin_ffs(r) - 1;
#endif
}
}
}
#elif defined(RAPIDJSON_SSE2)
//! Skip whitespace with SSE2 instructions, testing 16 8-byte characters at once.
inline const char *SkipWhitespace_SIMD(const char* p) {
static const char whitespaces[4][17] = {
" ",
"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
"\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r\r",
"\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"};
__m128i w0 = _mm_loadu_si128((const __m128i *)&whitespaces[0][0]);
__m128i w1 = _mm_loadu_si128((const __m128i *)&whitespaces[1][0]);
__m128i w2 = _mm_loadu_si128((const __m128i *)&whitespaces[2][0]);
__m128i w3 = _mm_loadu_si128((const __m128i *)&whitespaces[3][0]);
for (;;) {
__m128i s = _mm_loadu_si128((const __m128i *)p);
__m128i x = _mm_cmpeq_epi8(s, w0);
x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w1));
x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w2));
x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w3));
unsigned short r = ~_mm_movemask_epi8(x);
if (r == 0) // all 16 characters are whitespace
p += 16;
else { // some of characters may be non-whitespace
#ifdef _MSC_VER // Find the index of first non-whitespace
unsigned long offset;
if (_BitScanForward(&offset, r))
return p + offset;
#else
if (r != 0)
return p + __builtin_ffs(r) - 1;
#endif
}
}
}
#endif // RAPIDJSON_SSE2
#ifdef RAPIDJSON_SIMD
//! Template function specialization for InsituStringStream
template<> inline void SkipWhitespace(InsituStringStream& is) {
is.src_ = const_cast<char*>(SkipWhitespace_SIMD(is.src_));
}
//! Template function specialization for StringStream
template<> inline void SkipWhitespace(StringStream& is) {
is.src_ = SkipWhitespace_SIMD(is.src_);
}
#endif // RAPIDJSON_SIMD
///////////////////////////////////////////////////////////////////////////////
// GenericReader
//! SAX-style JSON parser. Use Reader for UTF8 encoding and default allocator.
/*! GenericReader parses JSON text from a stream, and send events synchronously to an
object implementing Handler concept.
It needs to allocate a stack for storing a single decoded string during
non-destructive parsing.
For in-situ parsing, the decoded string is directly written to the source
text string, no temporary buffer is required.
A GenericReader object can be reused for parsing multiple JSON text.
\tparam SourceEncoding Encoding of the input stream.
\tparam TargetEncoding Encoding of the parse output.
\tparam Allocator Allocator type for stack.
*/
template <typename SourceEncoding, typename TargetEncoding, typename Allocator = MemoryPoolAllocator<> >
class GenericReader {
public:
typedef typename SourceEncoding::Ch Ch;
//! Constructor.
/*! \param allocator Optional allocator for allocating stack memory. (Only use for non-destructive parsing)
\param stackCapacity stack capacity in bytes for storing a single decoded string. (Only use for non-destructive parsing)
*/
GenericReader(Allocator* allocator = 0, size_t stackCapacity = kDefaultStackCapacity) : stack_(allocator, stackCapacity), parseError_(0), errorOffset_(0) {}
//! Parse JSON text.
/*! \tparam parseFlags Combination of ParseFlag.
\tparam InputStream Type of input stream.
\tparam Handler Type of handler which must implement Handler concept.
\param stream Input stream to be parsed.
\param handler The handler to receive events.
\return Whether the parsing is successful.
*/
template <unsigned parseFlags, typename InputStream, typename Handler>
bool Parse(InputStream& is, Handler& handler) {
parseError_ = 0;
errorOffset_ = 0;
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4611) // interaction between '_setjmp' and C++ object destruction is non-portable
#endif
if (setjmp(jmpbuf_)) {
#ifdef _MSC_VER
#pragma warning(pop)
#endif
stack_.Clear();
return false;
}
SkipWhitespace(is);
if (is.Peek() == '\0')
RAPIDJSON_PARSE_ERROR("Text only contains white space(s)", is.Tell());
else {
switch (is.Peek()) {
case '{': ParseObject<parseFlags>(is, handler); break;
case '[': ParseArray<parseFlags>(is, handler); break;
default: RAPIDJSON_PARSE_ERROR("Expect either an object or array at root", is.Tell());
}
SkipWhitespace(is);
if (is.Peek() != '\0')
RAPIDJSON_PARSE_ERROR("Nothing should follow the root object or array.", is.Tell());
}
return true;
}
bool HasParseError() const { return parseError_ != 0; }
const char* GetParseError() const { return parseError_; }
size_t GetErrorOffset() const { return errorOffset_; }
private:
// Parse object: { string : value, ... }
template<unsigned parseFlags, typename InputStream, typename Handler>
void ParseObject(InputStream& is, Handler& handler) {
RAPIDJSON_ASSERT(is.Peek() == '{');
is.Take(); // Skip '{'
handler.StartObject();
SkipWhitespace(is);
if (is.Peek() == '}') {
is.Take();
handler.EndObject(0); // empty object
return;
}
for (SizeType memberCount = 0;;) {
if (is.Peek() != '"')
RAPIDJSON_PARSE_ERROR("Name of an object member must be a string", is.Tell());
ParseString<parseFlags>(is, handler);
SkipWhitespace(is);
if (is.Take() != ':')
RAPIDJSON_PARSE_ERROR("There must be a colon after the name of object member", is.Tell());
SkipWhitespace(is);
ParseValue<parseFlags>(is, handler);
SkipWhitespace(is);
++memberCount;
switch(is.Take()) {
case ',': SkipWhitespace(is); break;
case '}': handler.EndObject(memberCount); return;
default: RAPIDJSON_PARSE_ERROR("Must be a comma or '}' after an object member", is.Tell());
}
}
}
// Parse array: [ value, ... ]
template<unsigned parseFlags, typename InputStream, typename Handler>
void ParseArray(InputStream& is, Handler& handler) {
RAPIDJSON_ASSERT(is.Peek() == '[');
is.Take(); // Skip '['
handler.StartArray();
SkipWhitespace(is);
if (is.Peek() == ']') {
is.Take();
handler.EndArray(0); // empty array
return;
}
for (SizeType elementCount = 0;;) {
ParseValue<parseFlags>(is, handler);
++elementCount;
SkipWhitespace(is);
switch (is.Take()) {
case ',': SkipWhitespace(is); break;
case ']': handler.EndArray(elementCount); return;
default: RAPIDJSON_PARSE_ERROR("Must be a comma or ']' after an array element.", is.Tell());
}
}
}
template<unsigned parseFlags, typename InputStream, typename Handler>
void ParseNull(InputStream& is, Handler& handler) {
RAPIDJSON_ASSERT(is.Peek() == 'n');
is.Take();
if (is.Take() == 'u' && is.Take() == 'l' && is.Take() == 'l')
handler.Null();
else
RAPIDJSON_PARSE_ERROR("Invalid value", is.Tell() - 1);
}
template<unsigned parseFlags, typename InputStream, typename Handler>
void ParseTrue(InputStream& is, Handler& handler) {
RAPIDJSON_ASSERT(is.Peek() == 't');
is.Take();
if (is.Take() == 'r' && is.Take() == 'u' && is.Take() == 'e')
handler.Bool(true);
else
RAPIDJSON_PARSE_ERROR("Invalid value", is.Tell());
}
template<unsigned parseFlags, typename InputStream, typename Handler>
void ParseFalse(InputStream& is, Handler& handler) {
RAPIDJSON_ASSERT(is.Peek() == 'f');
is.Take();
if (is.Take() == 'a' && is.Take() == 'l' && is.Take() == 's' && is.Take() == 'e')
handler.Bool(false);
else
RAPIDJSON_PARSE_ERROR("Invalid value", is.Tell() - 1);
}
// Helper function to parse four hexidecimal digits in \uXXXX in ParseString().
template<typename InputStream>
unsigned ParseHex4(InputStream& is) {
InputStream s = is; // Use a local copy for optimization
unsigned codepoint = 0;
for (int i = 0; i < 4; i++) {
Ch c = s.Take();
codepoint <<= 4;
codepoint += c;
if (c >= '0' && c <= '9')
codepoint -= '0';
else if (c >= 'A' && c <= 'F')
codepoint -= 'A' - 10;
else if (c >= 'a' && c <= 'f')
codepoint -= 'a' - 10;
else
RAPIDJSON_PARSE_ERROR("Incorrect hex digit after \\u escape", s.Tell() - 1);
}
is = s; // Restore is
return codepoint;
}
class StackStream {
public:
typedef typename TargetEncoding::Ch Ch;
StackStream(internal::Stack<Allocator>& stack) : stack_(stack), length_(0) {}
void Put(Ch c) {
*stack_.template Push<Ch>() = c;
++length_;
}
internal::Stack<Allocator>& stack_;
SizeType length_;
private:
// Prohibit assignment for VC C4512 warning
StackStream& operator=(const StackStream&);
};
// Parse string and generate String event. Different code paths for kParseInsituFlag.
template<unsigned parseFlags, typename InputStream, typename Handler>
void ParseString(InputStream& is, Handler& handler) {
InputStream s = is; // Local copy for optimization
if (parseFlags & kParseInsituFlag) {
Ch *head = s.PutBegin();
ParseStringToStream<parseFlags, SourceEncoding, SourceEncoding>(s, s);
size_t length = s.PutEnd(head) - 1;
RAPIDJSON_ASSERT(length <= 0xFFFFFFFF);
handler.String((typename TargetEncoding::Ch*)head, SizeType(length), false);
}
else {
StackStream stackStream(stack_);
ParseStringToStream<parseFlags, SourceEncoding, TargetEncoding>(s, stackStream);
handler.String(stack_.template Pop<typename TargetEncoding::Ch>(stackStream.length_), stackStream.length_ - 1, true);
}
is = s; // Restore is
}
// Parse string to an output is
// This function handles the prefix/suffix double quotes, escaping, and optional encoding validation.
template<unsigned parseFlags, typename SEncoding, typename TEncoding, typename InputStream, typename OutputStream>
RAPIDJSON_FORCEINLINE void ParseStringToStream(InputStream& is, OutputStream& os) {
#define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
static const char escape[256] = {
Z16, Z16, 0, 0,'\"', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'/',
Z16, Z16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'\\', 0, 0, 0,
0, 0,'\b', 0, 0, 0,'\f', 0, 0, 0, 0, 0, 0, 0,'\n', 0,
0, 0,'\r', 0,'\t', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16
};
#undef Z16
RAPIDJSON_ASSERT(is.Peek() == '\"');
is.Take(); // Skip '\"'
for (;;) {
Ch c = is.Peek();
if (c == '\\') { // Escape
is.Take();
Ch e = is.Take();
if ((sizeof(Ch) == 1 || unsigned(e) < 256) && escape[(unsigned char)e])
os.Put(escape[(unsigned char)e]);
else if (e == 'u') { // Unicode
unsigned codepoint = ParseHex4(is);
if (codepoint >= 0xD800 && codepoint <= 0xDBFF) {
// Handle UTF-16 surrogate pair
if (is.Take() != '\\' || is.Take() != 'u')
RAPIDJSON_PARSE_ERROR("Missing the second \\u in surrogate pair", is.Tell() - 2);
unsigned codepoint2 = ParseHex4(is);
if (codepoint2 < 0xDC00 || codepoint2 > 0xDFFF)
RAPIDJSON_PARSE_ERROR("The second \\u in surrogate pair is invalid", is.Tell() - 2);
codepoint = (((codepoint - 0xD800) << 10) | (codepoint2 - 0xDC00)) + 0x10000;
}
TEncoding::Encode(os, codepoint);
}
else
RAPIDJSON_PARSE_ERROR("Unknown escape character", is.Tell() - 1);
}
else if (c == '"') { // Closing double quote
is.Take();
os.Put('\0'); // null-terminate the string
return;
}
else if (c == '\0')
RAPIDJSON_PARSE_ERROR("lacks ending quotation before the end of string", is.Tell() - 1);
else if ((unsigned)c < 0x20) // RFC 4627: unescaped = %x20-21 / %x23-5B / %x5D-10FFFF
RAPIDJSON_PARSE_ERROR("Incorrect unescaped character in string", is.Tell() - 1);
else {
if (parseFlags & kParseValidateEncodingFlag ?
!Transcoder<SEncoding, TEncoding>::Validate(is, os) :
!Transcoder<SEncoding, TEncoding>::Transcode(is, os))
RAPIDJSON_PARSE_ERROR("Invalid encoding", is.Tell());
}
}
}
template<unsigned parseFlags, typename InputStream, typename Handler>
void ParseNumber(InputStream& is, Handler& handler) {
InputStream s = is; // Local copy for optimization
// Parse minus
bool minus = false;
if (s.Peek() == '-') {
minus = true;
s.Take();
}
// Parse int: zero / ( digit1-9 *DIGIT )
unsigned i;
bool try64bit = false;
if (s.Peek() == '0') {
i = 0;
s.Take();
}
else if (s.Peek() >= '1' && s.Peek() <= '9') {
i = s.Take() - '0';
if (minus)
while (s.Peek() >= '0' && s.Peek() <= '9') {
if (i >= 214748364) { // 2^31 = 2147483648
if (i != 214748364 || s.Peek() > '8') {
try64bit = true;
break;
}
}
i = i * 10 + (s.Take() - '0');
}
else
while (s.Peek() >= '0' && s.Peek() <= '9') {
if (i >= 429496729) { // 2^32 - 1 = 4294967295
if (i != 429496729 || s.Peek() > '5') {
try64bit = true;
break;
}
}
i = i * 10 + (s.Take() - '0');
}
}
else
RAPIDJSON_PARSE_ERROR("Expect a value here.", is.Tell());
// Parse 64bit int
uint64_t i64 = 0;
bool useDouble = false;
if (try64bit) {
i64 = i;
if (minus)
while (s.Peek() >= '0' && s.Peek() <= '9') {
if (i64 >= 922337203685477580uLL) // 2^63 = 9223372036854775808
if (i64 != 922337203685477580uLL || s.Peek() > '8') {
useDouble = true;
break;
}
i64 = i64 * 10 + (s.Take() - '0');
}
else
while (s.Peek() >= '0' && s.Peek() <= '9') {
if (i64 >= 1844674407370955161uLL) // 2^64 - 1 = 18446744073709551615
if (i64 != 1844674407370955161uLL || s.Peek() > '5') {
useDouble = true;
break;
}
i64 = i64 * 10 + (s.Take() - '0');
}
}
// Force double for big integer
double d = 0.0;
if (useDouble) {
d = (double)i64;
while (s.Peek() >= '0' && s.Peek() <= '9') {
if (d >= 1E307)
RAPIDJSON_PARSE_ERROR("Number too big to store in double", is.Tell());
d = d * 10 + (s.Take() - '0');
}
}
// Parse frac = decimal-point 1*DIGIT
int expFrac = 0;
if (s.Peek() == '.') {
if (!useDouble) {
d = try64bit ? (double)i64 : (double)i;
useDouble = true;
}
s.Take();
if (s.Peek() >= '0' && s.Peek() <= '9') {
d = d * 10 + (s.Take() - '0');
--expFrac;
}
else
RAPIDJSON_PARSE_ERROR("At least one digit in fraction part", is.Tell());
while (s.Peek() >= '0' && s.Peek() <= '9') {
if (expFrac > -16) {
d = d * 10 + (s.Peek() - '0');
--expFrac;
}
s.Take();
}
}
// Parse exp = e [ minus / plus ] 1*DIGIT
int exp = 0;
if (s.Peek() == 'e' || s.Peek() == 'E') {
if (!useDouble) {
d = try64bit ? (double)i64 : (double)i;
useDouble = true;
}
s.Take();
bool expMinus = false;
if (s.Peek() == '+')
s.Take();
else if (s.Peek() == '-') {
s.Take();
expMinus = true;
}
if (s.Peek() >= '0' && s.Peek() <= '9') {
exp = s.Take() - '0';
while (s.Peek() >= '0' && s.Peek() <= '9') {
exp = exp * 10 + (s.Take() - '0');
if (exp > 308)
RAPIDJSON_PARSE_ERROR("Number too big to store in double", is.Tell());
}
}
else
RAPIDJSON_PARSE_ERROR("At least one digit in exponent", s.Tell());
if (expMinus)
exp = -exp;
}
// Finish parsing, call event according to the type of number.
if (useDouble) {
d *= internal::Pow10(exp + expFrac);
handler.Double(minus ? -d : d);
}
else {
if (try64bit) {
if (minus)
handler.Int64(-(int64_t)i64);
else
handler.Uint64(i64);
}
else {
if (minus)
handler.Int(-(int)i);
else
handler.Uint(i);
}
}
is = s; // restore is
}
// Parse any JSON value
template<unsigned parseFlags, typename InputStream, typename Handler>
void ParseValue(InputStream& is, Handler& handler) {
switch (is.Peek()) {
case 'n': ParseNull <parseFlags>(is, handler); break;
case 't': ParseTrue <parseFlags>(is, handler); break;
case 'f': ParseFalse <parseFlags>(is, handler); break;
case '"': ParseString<parseFlags>(is, handler); break;
case '{': ParseObject<parseFlags>(is, handler); break;
case '[': ParseArray <parseFlags>(is, handler); break;
default : ParseNumber<parseFlags>(is, handler);
}
}
static const size_t kDefaultStackCapacity = 256; //!< Default stack capacity in bytes for storing a single decoded string.
internal::Stack<Allocator> stack_; //!< A stack for storing decoded string temporarily during non-destructive parsing.
jmp_buf jmpbuf_; //!< setjmp buffer for fast exit from nested parsing function calls.
const char* parseError_;
size_t errorOffset_;
}; // class GenericReader
//! Reader with UTF8 encoding and default allocator.
typedef GenericReader<UTF8<>, UTF8<> > Reader;
} // namespace rapidjson
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif // RAPIDJSON_READER_H_

View file

@ -0,0 +1,50 @@
#ifndef RAPIDJSON_STRINGBUFFER_H_
#define RAPIDJSON_STRINGBUFFER_H_
#include "rapidjson.h"
#include "internal/stack.h"
namespace rapidjson {
//! Represents an in-memory output stream.
/*!
\tparam Encoding Encoding of the stream.
\tparam Allocator type for allocating memory buffer.
\implements Stream
*/
template <typename Encoding, typename Allocator = CrtAllocator>
struct GenericStringBuffer {
typedef typename Encoding::Ch Ch;
GenericStringBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {}
void Put(Ch c) { *stack_.template Push<Ch>() = c; }
void Flush() {}
void Clear() { stack_.Clear(); }
const Ch* GetString() const {
// Push and pop a null terminator. This is safe.
*stack_.template Push<Ch>() = '\0';
stack_.template Pop<Ch>(1);
return stack_.template Bottom<Ch>();
}
size_t GetSize() const { return stack_.GetSize(); }
static const size_t kDefaultCapacity = 256;
mutable internal::Stack<Allocator> stack_;
};
typedef GenericStringBuffer<UTF8<> > StringBuffer;
//! Implement specialized version of PutN() with memset() for better performance.
template<>
inline void PutN(GenericStringBuffer<UTF8<> >& stream, char c, size_t n) {
memset(stream.stack_.Push<char>(n), c, n * sizeof(c));
}
} // namespace rapidjson
#endif // RAPIDJSON_STRINGBUFFER_H_

View file

@ -0,0 +1,249 @@
#ifndef RAPIDJSON_WRITER_H_
#define RAPIDJSON_WRITER_H_
#include "rapidjson.h"
#include "internal/stack.h"
#include "internal/strfunc.h"
#include <cstdio> // snprintf() or _sprintf_s()
#include <new> // placement new
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4127) // conditional expression is constant
#endif
namespace rapidjson {
//! JSON writer
/*! Writer implements the concept Handler.
It generates JSON text by events to an output os.
User may programmatically calls the functions of a writer to generate JSON text.
On the other side, a writer can also be passed to objects that generates events,
for example Reader::Parse() and Document::Accept().
\tparam OutputStream Type of output stream.
\tparam SourceEncoding Encoding of both source strings.
\tparam TargetEncoding Encoding of and output stream.
\implements Handler
*/
template<typename OutputStream, typename SourceEncoding = UTF8<>, typename TargetEncoding = UTF8<>, typename Allocator = MemoryPoolAllocator<> >
class Writer {
public:
typedef typename SourceEncoding::Ch Ch;
Writer(OutputStream& os, Allocator* allocator = 0, size_t levelDepth = kDefaultLevelDepth) :
os_(os), level_stack_(allocator, levelDepth * sizeof(Level)) {}
//@name Implementation of Handler
//@{
Writer& Null() { Prefix(kNullType); WriteNull(); return *this; }
Writer& Bool(bool b) { Prefix(b ? kTrueType : kFalseType); WriteBool(b); return *this; }
Writer& Int(int i) { Prefix(kNumberType); WriteInt(i); return *this; }
Writer& Uint(unsigned u) { Prefix(kNumberType); WriteUint(u); return *this; }
Writer& Int64(int64_t i64) { Prefix(kNumberType); WriteInt64(i64); return *this; }
Writer& Uint64(uint64_t u64) { Prefix(kNumberType); WriteUint64(u64); return *this; }
Writer& Double(double d) { Prefix(kNumberType); WriteDouble(d); return *this; }
Writer& String(const Ch* str, SizeType length, bool copy = false) {
(void)copy;
Prefix(kStringType);
WriteString(str, length);
return *this;
}
Writer& StartObject() {
Prefix(kObjectType);
new (level_stack_.template Push<Level>()) Level(false);
WriteStartObject();
return *this;
}
Writer& EndObject(SizeType memberCount = 0) {
(void)memberCount;
RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level));
RAPIDJSON_ASSERT(!level_stack_.template Top<Level>()->inArray);
level_stack_.template Pop<Level>(1);
WriteEndObject();
if (level_stack_.Empty()) // end of json text
os_.Flush();
return *this;
}
Writer& StartArray() {
Prefix(kArrayType);
new (level_stack_.template Push<Level>()) Level(true);
WriteStartArray();
return *this;
}
Writer& EndArray(SizeType elementCount = 0) {
(void)elementCount;
RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level));
RAPIDJSON_ASSERT(level_stack_.template Top<Level>()->inArray);
level_stack_.template Pop<Level>(1);
WriteEndArray();
if (level_stack_.Empty()) // end of json text
os_.Flush();
return *this;
}
//@}
//! Simpler but slower overload.
Writer& String(const Ch* str) { return String(str, internal::StrLen(str)); }
protected:
//! Information for each nested level
struct Level {
Level(bool inArray_) : inArray(inArray_), valueCount(0) {}
bool inArray; //!< true if in array, otherwise in object
size_t valueCount; //!< number of values in this level
};
static const size_t kDefaultLevelDepth = 32;
void WriteNull() {
os_.Put('n'); os_.Put('u'); os_.Put('l'); os_.Put('l');
}
void WriteBool(bool b) {
if (b) {
os_.Put('t'); os_.Put('r'); os_.Put('u'); os_.Put('e');
}
else {
os_.Put('f'); os_.Put('a'); os_.Put('l'); os_.Put('s'); os_.Put('e');
}
}
void WriteInt(int i) {
if (i < 0) {
os_.Put('-');
i = -i;
}
WriteUint((unsigned)i);
}
void WriteUint(unsigned u) {
char buffer[10];
char *p = buffer;
do {
*p++ = (u % 10) + '0';
u /= 10;
} while (u > 0);
do {
--p;
os_.Put(*p);
} while (p != buffer);
}
void WriteInt64(int64_t i64) {
if (i64 < 0) {
os_.Put('-');
i64 = -i64;
}
WriteUint64((uint64_t)i64);
}
void WriteUint64(uint64_t u64) {
char buffer[20];
char *p = buffer;
do {
*p++ = char(u64 % 10) + '0';
u64 /= 10;
} while (u64 > 0);
do {
--p;
os_.Put(*p);
} while (p != buffer);
}
//! \todo Optimization with custom double-to-string converter.
void WriteDouble(double d) {
char buffer[100];
#if _MSC_VER
int ret = sprintf_s(buffer, sizeof(buffer), "%g", d);
#else
int ret = snprintf(buffer, sizeof(buffer), "%g", d);
#endif
RAPIDJSON_ASSERT(ret >= 1);
for (int i = 0; i < ret; i++)
os_.Put(buffer[i]);
}
void WriteString(const Ch* str, SizeType length) {
static const char hexDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
static const char escape[256] = {
#define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
//0 1 2 3 4 5 6 7 8 9 A B C D E F
'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'b', 't', 'n', 'u', 'f', 'r', 'u', 'u', // 00
'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', // 10
0, 0, '"', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20
Z16, Z16, // 30~4F
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'\\', 0, 0, 0, // 50
Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16 // 60~FF
#undef Z16
};
os_.Put('\"');
GenericStringStream<SourceEncoding> is(str);
while (is.Tell() < length) {
const Ch c = is.Peek();
if ((sizeof(Ch) == 1 || (unsigned)c < 256) && escape[(unsigned char)c]) {
is.Take();
os_.Put('\\');
os_.Put(escape[(unsigned char)c]);
if (escape[(unsigned char)c] == 'u') {
os_.Put('0');
os_.Put('0');
os_.Put(hexDigits[(unsigned char)c >> 4]);
os_.Put(hexDigits[(unsigned char)c & 0xF]);
}
}
else
Transcoder<SourceEncoding, TargetEncoding>::Transcode(is, os_);
}
os_.Put('\"');
}
void WriteStartObject() { os_.Put('{'); }
void WriteEndObject() { os_.Put('}'); }
void WriteStartArray() { os_.Put('['); }
void WriteEndArray() { os_.Put(']'); }
void Prefix(Type type) {
(void)type;
if (level_stack_.GetSize() != 0) { // this value is not at root
Level* level = level_stack_.template Top<Level>();
if (level->valueCount > 0) {
if (level->inArray)
os_.Put(','); // add comma if it is not the first element in array
else // in object
os_.Put((level->valueCount % 2 == 0) ? ',' : ':');
}
if (!level->inArray && level->valueCount % 2 == 0)
RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even number should be a name
level->valueCount++;
}
else
RAPIDJSON_ASSERT(type == kObjectType || type == kArrayType);
}
OutputStream& os_;
internal::Stack<Allocator> level_stack_;
private:
// Prohibit assignment for VC C4512 warning
Writer& operator=(const Writer& w);
};
} // namespace rapidjson
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif // RAPIDJSON_RAPIDJSON_H_

View file

@ -0,0 +1,429 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "persistence/taml/binary/tamlBinaryReader.h"
#ifndef _ZIPSUBSTREAM_H_
#include "core/util/zip/zipSubStream.h"
#endif
// Debug Profiling.
#include "platform/profiler.h"
//-----------------------------------------------------------------------------
SimObject* TamlBinaryReader::read( FileStream& stream )
{
// Debug Profiling.
PROFILE_SCOPE(TamlBinaryReader_Read);
// Read Taml signature.
StringTableEntry tamlSignature = stream.readSTString();
// Is the signature correct?
if ( tamlSignature != StringTable->insert( TAML_SIGNATURE ) )
{
// Warn.
Con::warnf("Taml: Cannot read binary file as signature is incorrect '%s'.", tamlSignature );
return NULL;
}
// Read version Id.
U32 versionId;
stream.read( &versionId );
// Read compressed flag.
bool compressed;
stream.read( &compressed );
SimObject* pSimObject = NULL;
// Is the stream compressed?
if ( compressed )
{
// Yes, so attach zip stream.
ZipSubRStream zipStream;
zipStream.attachStream( &stream );
// Parse element.
pSimObject = parseElement( zipStream, versionId );
// Detach zip stream.
zipStream.detachStream();
}
else
{
// No, so parse element.
pSimObject = parseElement( stream, versionId );
}
return pSimObject;
}
//-----------------------------------------------------------------------------
void TamlBinaryReader::resetParse( void )
{
// Debug Profiling.
PROFILE_SCOPE(TamlBinaryReader_ResetParse);
// Clear object reference map.
mObjectReferenceMap.clear();
}
//-----------------------------------------------------------------------------
SimObject* TamlBinaryReader::parseElement( Stream& stream, const U32 versionId )
{
// Debug Profiling.
PROFILE_SCOPE(TamlBinaryReader_ParseElement);
SimObject* pSimObject = NULL;
#ifdef TORQUE_DEBUG
// Format the type location.
char typeLocationBuffer[64];
dSprintf( typeLocationBuffer, sizeof(typeLocationBuffer), "Taml [format='binary' offset=%u]", stream.getPosition() );
#endif
// Fetch element name.
StringTableEntry typeName = stream.readSTString();
// Fetch object name.
StringTableEntry objectName = stream.readSTString();
// Read references.
U32 tamlRefId;
U32 tamlRefToId;
stream.read( &tamlRefId );
stream.read( &tamlRefToId );
// Do we have a reference to Id?
if ( tamlRefToId != 0 )
{
// Yes, so fetch reference.
typeObjectReferenceHash::Iterator referenceItr = mObjectReferenceMap.find( tamlRefToId );
// Did we find the reference?
if ( referenceItr == mObjectReferenceMap.end() )
{
// No, so warn.
Con::warnf( "Taml: Could not find a reference Id of '%d'", tamlRefToId );
return NULL;
}
// Return object.
return referenceItr->value;
}
#ifdef TORQUE_DEBUG
// Create type.
pSimObject = Taml::createType( typeName, mpTaml, typeLocationBuffer );
#else
// Create type.
pSimObject = Taml::createType( typeName, mpTaml );
#endif
// Finish if we couldn't create the type.
if ( pSimObject == NULL )
return NULL;
// Find Taml callbacks.
TamlCallbacks* pCallbacks = dynamic_cast<TamlCallbacks*>( pSimObject );
// Are there any Taml callbacks?
if ( pCallbacks != NULL )
{
// Yes, so call it.
mpTaml->tamlPreRead( pCallbacks );
}
// Parse attributes.
parseAttributes( stream, pSimObject, versionId );
// Does the object require a name?
if ( objectName == StringTable->EmptyString() )
{
// No, so just register anonymously.
pSimObject->registerObject();
}
else
{
// Yes, so register a named object.
pSimObject->registerObject( objectName );
// Was the name assigned?
if ( pSimObject->getName() != objectName )
{
// No, so warn that the name was rejected.
#ifdef TORQUE_DEBUG
Con::warnf( "Taml::parseElement() - Registered an instance of type '%s' but a request to name it '%s' was rejected. This is typically because an object of that name already exists. '%s'", typeName, objectName, typeLocationBuffer );
#else
Con::warnf( "Taml::parseElement() - Registered an instance of type '%s' but a request to name it '%s' was rejected. This is typically because an object of that name already exists.", typeName, objectName );
#endif
}
}
// Do we have a reference Id?
if ( tamlRefId != 0 )
{
// Yes, so insert reference.
mObjectReferenceMap.insertUnique( tamlRefId, pSimObject );
}
// Parse custom elements.
TamlCustomNodes customProperties;
// Parse children.
parseChildren( stream, pCallbacks, pSimObject, versionId );
// Parse custom elements.
parseCustomElements( stream, pCallbacks, customProperties, versionId );
// Are there any Taml callbacks?
if ( pCallbacks != NULL )
{
// Yes, so call it.
mpTaml->tamlPostRead( pCallbacks, customProperties );
}
// Return object.
return pSimObject;
}
//-----------------------------------------------------------------------------
void TamlBinaryReader::parseAttributes( Stream& stream, SimObject* pSimObject, const U32 versionId )
{
// Debug Profiling.
PROFILE_SCOPE(TamlBinaryReader_ParseAttributes);
// Sanity!
AssertFatal( pSimObject != NULL, "Taml: Cannot parse attributes on a NULL object." );
// Fetch attribute count.
U32 attributeCount;
stream.read( &attributeCount );
// Finish if no attributes.
if ( attributeCount == 0 )
return;
char valueBuffer[4096];
// Iterate attributes.
for ( U32 index = 0; index < attributeCount; ++index )
{
// Fetch attribute.
StringTableEntry attributeName = stream.readSTString();
stream.readLongString( 4096, valueBuffer );
// We can assume this is a field for now.
pSimObject->setPrefixedDataField(attributeName, NULL, valueBuffer);
}
}
//-----------------------------------------------------------------------------
void TamlBinaryReader::parseChildren( Stream& stream, TamlCallbacks* pCallbacks, SimObject* pSimObject, const U32 versionId )
{
// Debug Profiling.
PROFILE_SCOPE(TamlBinaryReader_ParseChildren);
// Sanity!
AssertFatal( pSimObject != NULL, "Taml: Cannot parse children on a NULL object." );
// Fetch children count.
U32 childrenCount;
stream.read( &childrenCount );
// Finish if no children.
if ( childrenCount == 0 )
return;
// Fetch the Taml children.
TamlChildren* pChildren = dynamic_cast<TamlChildren*>( pSimObject );
// Is this a sim set?
if ( pChildren == NULL )
{
// No, so warn.
Con::warnf("Taml: Child element found under parent but object cannot have children." );
return;
}
// Fetch any container child class specifier.
AbstractClassRep* pContainerChildClass = pSimObject->getClassRep()->getContainerChildClass( true );
// Iterate children.
for ( U32 index = 0; index < childrenCount; ++ index )
{
// Parse child element.
SimObject* pChildSimObject = parseElement( stream, versionId );
// Finish if child failed.
if ( pChildSimObject == NULL )
return;
// Do we have a container child class?
if ( pContainerChildClass != NULL )
{
// Yes, so is the child object the correctly derived type?
if ( !pChildSimObject->getClassRep()->isClass( pContainerChildClass ) )
{
// No, so warn.
Con::warnf("Taml: Child element '%s' found under parent '%s' but object is restricted to children of type '%s'.",
pChildSimObject->getClassName(),
pSimObject->getClassName(),
pContainerChildClass->getClassName() );
// NOTE: We can't delete the object as it may be referenced elsewhere!
pChildSimObject = NULL;
// Skip.
continue;
}
}
// Add child.
pChildren->addTamlChild( pChildSimObject );
// Find Taml callbacks for child.
TamlCallbacks* pChildCallbacks = dynamic_cast<TamlCallbacks*>( pChildSimObject );
// Do we have callbacks on the child?
if ( pChildCallbacks != NULL )
{
// Yes, so perform callback.
mpTaml->tamlAddParent( pChildCallbacks, pSimObject );
}
}
}
//-----------------------------------------------------------------------------
void TamlBinaryReader::parseCustomElements( Stream& stream, TamlCallbacks* pCallbacks, TamlCustomNodes& customNodes, const U32 versionId )
{
// Debug Profiling.
PROFILE_SCOPE(TamlBinaryReader_ParseCustomElement);
// Read custom node count.
U32 customNodeCount;
stream.read( &customNodeCount );
// Finish if no custom nodes.
if ( customNodeCount == 0 )
return;
// Iterate custom nodes.
for ( U32 nodeIndex = 0; nodeIndex < customNodeCount; ++nodeIndex )
{
//Read custom node name.
StringTableEntry nodeName = stream.readSTString();
// Add custom node.
TamlCustomNode* pCustomNode = customNodes.addNode( nodeName );
// Parse the custom node.
parseCustomNode( stream, pCustomNode, versionId );
}
// Do we have callbacks?
if ( pCallbacks == NULL )
{
// No, so warn.
Con::warnf( "Taml: Encountered custom data but object does not support custom data." );
return;
}
// Custom read callback.
mpTaml->tamlCustomRead( pCallbacks, customNodes );
}
//-----------------------------------------------------------------------------
void TamlBinaryReader::parseCustomNode( Stream& stream, TamlCustomNode* pCustomNode, const U32 versionId )
{
// Fetch if a proxy object.
bool isProxyObject;
stream.read( &isProxyObject );
// Is this a proxy object?
if ( isProxyObject )
{
// Yes, so parse proxy object.
SimObject* pProxyObject = parseElement( stream, versionId );
// Add child node.
pCustomNode->addNode( pProxyObject );
return;
}
// No, so read custom node name.
StringTableEntry nodeName = stream.readSTString();
// Add child node.
TamlCustomNode* pChildNode = pCustomNode->addNode( nodeName );
// Read child node text.
char childNodeTextBuffer[MAX_TAML_NODE_FIELDVALUE_LENGTH];
stream.readLongString( MAX_TAML_NODE_FIELDVALUE_LENGTH, childNodeTextBuffer );
pChildNode->setNodeText( childNodeTextBuffer );
// Read child node count.
U32 childNodeCount;
stream.read( &childNodeCount );
// Do we have any children nodes?
if ( childNodeCount > 0 )
{
// Yes, so parse children nodes.
for( U32 childIndex = 0; childIndex < childNodeCount; ++childIndex )
{
// Parse child node.
parseCustomNode( stream, pChildNode, versionId );
}
}
// Read child field count.
U32 childFieldCount;
stream.read( &childFieldCount );
// Do we have any child fields?
if ( childFieldCount > 0 )
{
// Yes, so parse child fields.
for( U32 childFieldIndex = 0; childFieldIndex < childFieldCount; ++childFieldIndex )
{
// Read field name.
StringTableEntry fieldName = stream.readSTString();
// Read field value.
char valueBuffer[MAX_TAML_NODE_FIELDVALUE_LENGTH];
stream.readLongString( MAX_TAML_NODE_FIELDVALUE_LENGTH, valueBuffer );
// Add field.
pChildNode->addField( fieldName, valueBuffer );
}
}
}

View file

@ -0,0 +1,68 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _TAML_BINARYREADER_H_
#define _TAML_BINARYREADER_H_
#ifndef _TDICTIONARY_H_
#include "core/util/tDictionary.h"
#endif
#ifndef _TAML_H_
#include "persistence/taml/taml.h"
#endif
//-----------------------------------------------------------------------------
/// @ingroup tamlGroup
/// @see tamlGroup
class TamlBinaryReader
{
public:
TamlBinaryReader( Taml* pTaml ) :
mpTaml( pTaml )
{
}
virtual ~TamlBinaryReader() {}
/// Read.
SimObject* read( FileStream& stream );
private:
Taml* mpTaml;
typedef HashTable<SimObjectId, SimObject*> typeObjectReferenceHash;
typeObjectReferenceHash mObjectReferenceMap;
private:
void resetParse( void );
SimObject* parseElement( Stream& stream, const U32 versionId );
void parseAttributes( Stream& stream, SimObject* pSimObject, const U32 versionId );
void parseChildren( Stream& stream, TamlCallbacks* pCallbacks, SimObject* pSimObject, const U32 versionId );
void parseCustomElements( Stream& stream, TamlCallbacks* pCallbacks, TamlCustomNodes& customNodes, const U32 versionId );
void parseCustomNode( Stream& stream, TamlCustomNode* pCustomNode, const U32 versionId );
};
#endif // _TAML_BINARYREADER_H_

View file

@ -0,0 +1,297 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "persistence/taml/binary/tamlBinaryWriter.h"
#ifndef _ZIPSUBSTREAM_H_
#include "core/util/zip/zipSubStream.h"
#endif
// Debug Profiling.
#include "platform/profiler.h"
//-----------------------------------------------------------------------------
bool TamlBinaryWriter::write( FileStream& stream, const TamlWriteNode* pTamlWriteNode, const bool compressed )
{
// Debug Profiling.
PROFILE_SCOPE(TamlBinaryWriter_Write);
// Write Taml signature.
stream.writeString( StringTable->insert( TAML_SIGNATURE ) );
// Write version Id.
stream.write( mVersionId );
// Write compressed flag.
stream.write( compressed );
// Are we compressed?
if ( compressed )
{
// yes, so attach zip stream.
ZipSubWStream zipStream;
zipStream.attachStream( &stream );
// Write element.
writeElement( zipStream, pTamlWriteNode );
// Detach zip stream.
zipStream.detachStream();
}
else
{
// No, so write element.
writeElement( stream, pTamlWriteNode );
}
return true;
}
//-----------------------------------------------------------------------------
void TamlBinaryWriter::writeElement( Stream& stream, const TamlWriteNode* pTamlWriteNode )
{
// Debug Profiling.
PROFILE_SCOPE(TamlBinaryWriter_WriteElement);
// Fetch object.
SimObject* pSimObject = pTamlWriteNode->mpSimObject;
// Fetch element name.
const char* pElementName = pSimObject->getClassName();
// Write element name.
stream.writeString( pElementName );
// Fetch object name.
const char* pObjectName = pTamlWriteNode->mpObjectName;
// Write object name.
stream.writeString( pObjectName != NULL ? pObjectName : StringTable->EmptyString() );
// Fetch reference Id.
const U32 tamlRefId = pTamlWriteNode->mRefId;
// Write reference Id.
stream.write( tamlRefId );
// Do we have a reference to node?
if ( pTamlWriteNode->mRefToNode != NULL )
{
// Yes, so fetch reference to Id.
const U32 tamlRefToId = pTamlWriteNode->mRefToNode->mRefId;
// Sanity!
AssertFatal( tamlRefToId != 0, "Taml: Invalid reference to Id." );
// Write reference to Id.
stream.write( tamlRefToId );
// Finished.
return;
}
// No, so write no reference to Id.
stream.write( 0 );
// Write attributes.
writeAttributes( stream, pTamlWriteNode );
// Write children.
writeChildren( stream, pTamlWriteNode );
// Write custom elements.
writeCustomElements( stream, pTamlWriteNode );
}
//-----------------------------------------------------------------------------
void TamlBinaryWriter::writeAttributes( Stream& stream, const TamlWriteNode* pTamlWriteNode )
{
// Debug Profiling.
PROFILE_SCOPE(TamlBinaryWriter_WriteAttributes);
// Fetch fields.
const Vector<TamlWriteNode::FieldValuePair*>& fields = pTamlWriteNode->mFields;
// Write placeholder attribute count.
stream.write( (U32)fields.size() );
// Finish if no fields.
if ( fields.size() == 0 )
return;
// Iterate fields.
for( Vector<TamlWriteNode::FieldValuePair*>::const_iterator itr = fields.begin(); itr != fields.end(); ++itr )
{
// Fetch field/value pair.
TamlWriteNode::FieldValuePair* pFieldValue = (*itr);
// Write attribute.
stream.writeString( pFieldValue->mName );
stream.writeLongString( 4096, pFieldValue->mpValue );
}
}
void TamlBinaryWriter::writeChildren( Stream& stream, const TamlWriteNode* pTamlWriteNode )
{
// Debug Profiling.
PROFILE_SCOPE(TamlBinaryWriter_WriteChildren);
// Fetch children.
Vector<TamlWriteNode*>* pChildren = pTamlWriteNode->mChildren;
// Do we have any children?
if ( pChildren == NULL )
{
// No, so write no children.
stream.write( (U32)0 );
return;
}
// Write children count.
stream.write( (U32)pChildren->size() );
// Iterate children.
for( Vector<TamlWriteNode*>::iterator itr = pChildren->begin(); itr != pChildren->end(); ++itr )
{
// Write child.
writeElement( stream, (*itr) );
}
}
//-----------------------------------------------------------------------------
void TamlBinaryWriter::writeCustomElements( Stream& stream, const TamlWriteNode* pTamlWriteNode )
{
// Debug Profiling.
PROFILE_SCOPE(TamlBinaryWriter_WriteCustomElements);
// Fetch custom nodes.
const TamlCustomNodes& customNodes = pTamlWriteNode->mCustomNodes;
// Fetch custom nodes.
const TamlCustomNodeVector& nodes = customNodes.getNodes();
// Write custom node count.
stream.write( (U32)nodes.size() );
// Finish if there are no nodes.
if ( nodes.size() == 0 )
return;
// Iterate custom nodes.
for( TamlCustomNodeVector::const_iterator customNodesItr = nodes.begin(); customNodesItr != nodes.end(); ++customNodesItr )
{
// Fetch the custom node.
TamlCustomNode* pCustomNode = *customNodesItr;
// Write custom node name.
stream.writeString( pCustomNode->getNodeName() );
// Fetch node children.
const TamlCustomNodeVector& nodeChildren = pCustomNode->getChildren();
// Iterate children nodes.
for( TamlCustomNodeVector::const_iterator childNodeItr = nodeChildren.begin(); childNodeItr != nodeChildren.end(); ++childNodeItr )
{
// Fetch child node.
const TamlCustomNode* pChildNode = *childNodeItr;
// Write the custom node.
writeCustomNode( stream, pChildNode );
}
}
}
//-----------------------------------------------------------------------------
void TamlBinaryWriter::writeCustomNode( Stream& stream, const TamlCustomNode* pCustomNode )
{
// Is the node a proxy object?
if ( pCustomNode->isProxyObject() )
{
// Yes, so flag as proxy object.
stream.write( true );
// Write the element.
writeElement( stream, pCustomNode->getProxyWriteNode() );
return;
}
// No, so flag as custom node.
stream.write( false );
// Write custom node name.
stream.writeString( pCustomNode->getNodeName() );
// Write custom node text.
stream.writeLongString(MAX_TAML_NODE_FIELDVALUE_LENGTH, pCustomNode->getNodeTextField().getFieldValue());
// Fetch node children.
const TamlCustomNodeVector& nodeChildren = pCustomNode->getChildren();
// Fetch child node count.
const U32 childNodeCount = (U32)nodeChildren.size();
// Write custom node count.
stream.write( childNodeCount );
// Do we have any children nodes.
if ( childNodeCount > 0 )
{
// Yes, so iterate children nodes.
for( TamlCustomNodeVector::const_iterator childNodeItr = nodeChildren.begin(); childNodeItr != nodeChildren.end(); ++childNodeItr )
{
// Fetch child node.
const TamlCustomNode* pChildNode = *childNodeItr;
// Write the custom node.
writeCustomNode( stream, pChildNode );
}
}
// Fetch fields.
const TamlCustomFieldVector& fields = pCustomNode->getFields();
// Fetch child field count.
const U32 childFieldCount = (U32)fields.size();
// Write custom field count.
stream.write( childFieldCount );
// Do we have any child fields?
if ( childFieldCount > 0 )
{
// Yes, so iterate fields.
for ( TamlCustomFieldVector::const_iterator fieldItr = fields.begin(); fieldItr != fields.end(); ++fieldItr )
{
// Fetch node field.
const TamlCustomField* pField = *fieldItr;
// Write the node field.
stream.writeString( pField->getFieldName() );
stream.writeLongString( MAX_TAML_NODE_FIELDVALUE_LENGTH, pField->getFieldValue() );
}
}
}

View file

@ -0,0 +1,59 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _TAML_BINARYWRITER_H_
#define _TAML_BINARYWRITER_H_
#ifndef _TAML_H_
#include "persistence/taml/taml.h"
#endif
//-----------------------------------------------------------------------------
/// @ingroup tamlGroup
/// @see tamlGroup
class TamlBinaryWriter
{
public:
TamlBinaryWriter( Taml* pTaml ) :
mpTaml( pTaml ),
mVersionId(2)
{
}
virtual ~TamlBinaryWriter() {}
/// Write.
bool write( FileStream& stream, const TamlWriteNode* pTamlWriteNode, const bool compressed );
private:
Taml* mpTaml;
const U32 mVersionId;
private:
void writeElement( Stream& stream, const TamlWriteNode* pTamlWriteNode );
void writeAttributes( Stream& stream, const TamlWriteNode* pTamlWriteNode );
void writeChildren( Stream& stream, const TamlWriteNode* pTamlWriteNode );
void writeCustomElements( Stream& stream, const TamlWriteNode* pTamlWriteNode );
void writeCustomNode( Stream& stream, const TamlCustomNode* pCustomNode );
};
#endif // _TAML_BINARYWRITER_H_

View file

@ -0,0 +1,747 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "fsTinyXml.h"
#include "console/console.h"
bool fsTiXmlDocument::LoadFile( const char * pFilename, TiXmlEncoding encoding )
{
// Expand the file-path.
char filenameBuffer[1024];
Con::expandToolScriptFilename( filenameBuffer, sizeof(filenameBuffer), pFilename );
FileStream stream;
#ifdef TORQUE_OS_ANDROID
if (strlen(pFilename) > strlen(filenameBuffer)) {
strcpy(filenameBuffer, pFilename);
}
#endif
// File open for read?
if ( !stream.open( filenameBuffer, Torque::FS::File::AccessMode::Read ) )
{
// No, so warn.
Con::warnf("TamlXmlParser::parse() - Could not open filename '%s' for parse.", filenameBuffer );
return false;
}
// Load document from stream.
if ( !LoadFile( stream ) )
{
// Warn!
Con::warnf("TamlXmlParser: Could not load Taml XML file from stream.");
return false;
}
// Close the stream.
stream.close();
return true;
}
bool fsTiXmlDocument::SaveFile( const char * pFilename ) const
{
// Expand the file-name into the file-path buffer.
char filenameBuffer[1024];
Con::expandToolScriptFilename( filenameBuffer, sizeof(filenameBuffer), pFilename );
FileStream stream;
// File opened?
if ( !stream.open( filenameBuffer, Torque::FS::File::AccessMode::Write ) )
{
// No, so warn.
Con::warnf("Taml::writeFile() - Could not open filename '%s' for write.", filenameBuffer );
return false;
}
bool ret = SaveFile(stream);
stream.close();
return ret;
}
bool fsTiXmlDocument::LoadFile( FileStream &stream, TiXmlEncoding encoding )
{
// Delete the existing data:
Clear();
//TODO: Can't clear location, investigate if this gives issues.
//doc.location.Clear();
// Get the file size, so we can pre-allocate the string. HUGE speed impact.
long length = stream.getStreamSize();
// Strange case, but good to handle up front.
if ( length <= 0 )
{
SetError( TiXmlDocument::TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN );
return false;
}
// Subtle bug here. TinyXml did use fgets. But from the XML spec:
// 2.11 End-of-Line Handling
// <snip>
// <quote>
// ...the XML processor MUST behave as if it normalized all line breaks in external
// parsed entities (including the document entity) on input, before parsing, by translating
// both the two-character sequence #xD #xA and any #xD that is not followed by #xA to
// a single #xA character.
// </quote>
//
// It is not clear fgets does that, and certainly isn't clear it works cross platform.
// Generally, you expect fgets to translate from the convention of the OS to the c/unix
// convention, and not work generally.
/*
while( fgets( buf, sizeof(buf), file ) )
{
data += buf;
}
*/
char* buf = new char[ length+1 ];
buf[0] = 0;
if ( !stream.read( length, buf ) ) {
delete [] buf;
SetError( TiXmlDocument::TIXML_ERROR_OPENING_FILE, 0, 0, TIXML_ENCODING_UNKNOWN );
return false;
}
// Process the buffer in place to normalize new lines. (See comment above.)
// Copies from the 'p' to 'q' pointer, where p can advance faster if
// a newline-carriage return is hit.
//
// Wikipedia:
// Systems based on ASCII or a compatible character set use either LF (Line feed, '\n', 0x0A, 10 in decimal) or
// CR (Carriage return, '\r', 0x0D, 13 in decimal) individually, or CR followed by LF (CR+LF, 0x0D 0x0A)...
// * LF: Multics, Unix and Unix-like systems (GNU/Linux, AIX, Xenix, Mac OS X, FreeBSD, etc.), BeOS, Amiga, RISC OS, and others
// * CR+LF: DEC RT-11 and most other early non-Unix, non-IBM OSes, CP/M, MP/M, DOS, OS/2, Microsoft Windows, Symbian OS
// * CR: Commodore 8-bit machines, Apple II family, Mac OS up to version 9 and OS-9
const char* p = buf; // the read head
char* q = buf; // the write head
const char CR = 0x0d;
const char LF = 0x0a;
buf[length] = 0;
while( *p ) {
assert( p < (buf+length) );
assert( q <= (buf+length) );
assert( q <= p );
if ( *p == CR ) {
*q++ = LF;
p++;
if ( *p == LF ) { // check for CR+LF (and skip LF)
p++;
}
}
else {
*q++ = *p++;
}
}
assert( q <= (buf+length) );
*q = 0;
Parse( buf, 0, encoding );
delete [] buf;
return !Error();
}
bool fsTiXmlDocument::SaveFile( FileStream &stream ) const
{
if ( useMicrosoftBOM )
{
const unsigned char TIXML_UTF_LEAD_0 = 0xefU;
const unsigned char TIXML_UTF_LEAD_1 = 0xbbU;
const unsigned char TIXML_UTF_LEAD_2 = 0xbfU;
stream.write( TIXML_UTF_LEAD_0 );
stream.write( TIXML_UTF_LEAD_1 );
stream.write( TIXML_UTF_LEAD_2 );
}
Print( stream, 0 );
return true;
}
void fsTiXmlDocument::Print( FileStream& stream, int depth ) const
{
for ( const TiXmlNode* node=FirstChild(); node; node=node->NextSibling() )
{
//AttemptPrintTiNode(const_cast<TiXmlNode*>(node), stream, depth);
dynamic_cast<const fsTiXmlNode*>(node)->Print( stream, depth );
stream.writeText( "\n" );
}
}
void fsTiXmlAttribute::Print( FileStream& stream, int depth, TIXML_STRING* str ) const
{
TIXML_STRING n, v;
TiXmlString value = TiXmlString(Value());
EncodeString( NameTStr(), &n );
EncodeString( value, &v );
for ( int i=0; i< depth; i++ ) {
stream.writeText( " " );
}
if (value.find ('\"') == TIXML_STRING::npos) {
const char* pValue = v.c_str();
char buffer[4096];
const S32 length = dSprintf(buffer, sizeof(buffer), "%s=\"%s\"", n.c_str(), pValue);
stream.write(length, buffer);
if ( str ) {
(*str) += n; (*str) += "=\""; (*str) += v; (*str) += "\"";
}
}
else {
char buffer[4096];
const S32 length = dSprintf(buffer, sizeof(buffer), "%s='%s'", n.c_str(), v.c_str());
stream.write(length, buffer);
if ( str ) {
(*str) += n; (*str) += "='"; (*str) += v; (*str) += "'";
}
}
}
void fsTiXmlDeclaration::Print(FileStream& stream, int depth, TiXmlString* str) const
{
stream.writeStringBuffer( "<?xml " );
if ( str ) (*str) += "<?xml ";
if ( !version.empty() ) {
stream.writeFormattedBuffer( "version=\"%s\" ", version.c_str ());
if ( str ) { (*str) += "version=\""; (*str) += version; (*str) += "\" "; }
}
if ( !encoding.empty() ) {
stream.writeFormattedBuffer( "encoding=\"%s\" ", encoding.c_str ());
if ( str ) { (*str) += "encoding=\""; (*str) += encoding; (*str) += "\" "; }
}
if ( !standalone.empty() ) {
stream.writeFormattedBuffer( "standalone=\"%s\" ", standalone.c_str ());
if ( str ) { (*str) += "standalone=\""; (*str) += standalone; (*str) += "\" "; }
}
stream.writeStringBuffer( "?>" );
if ( str ) (*str) += "?>";
}
void fsTiXmlElement::Print(FileStream& stream, int depth) const
{
int i;
for ( i=0; i<depth; i++ ) {
stream.writeStringBuffer( " " );
}
stream.writeFormattedBuffer( "<%s", value.c_str() );
const TiXmlAttribute* attrib;
for ( attrib = attributeSet.First(); attrib; attrib = attrib->Next() )
{
stream.writeStringBuffer( "\n" );
dynamic_cast<const fsTiXmlAttribute*>(attrib)->Print( stream, depth+1 );
}
// There are 3 different formatting approaches:
// 1) An element without children is printed as a <foo /> node
// 2) An element with only a text child is printed as <foo> text </foo>
// 3) An element with children is printed on multiple lines.
TiXmlNode* node;
if ( !firstChild )
{
stream.writeStringBuffer( " />" );
}
else if ( firstChild == lastChild && firstChild->ToText() )
{
stream.writeStringBuffer( ">" );
dynamic_cast<const fsTiXmlNode*>(firstChild)->Print( stream, depth + 1 );
stream.writeFormattedBuffer( "</%s>", value.c_str() );
}
else
{
stream.writeStringBuffer( ">" );
for ( node = firstChild; node; node=node->NextSibling() )
{
if ( !node->ToText() )
{
stream.writeStringBuffer( "\n" );
}
dynamic_cast<const fsTiXmlNode*>(node)->Print( stream, depth+1 );
}
stream.writeStringBuffer( "\n" );
for( i=0; i<depth; ++i ) {
stream.writeStringBuffer( " " );
}
stream.writeFormattedBuffer( "</%s>", value.c_str() );
}
}
void fsTiXmlComment::Print(FileStream& stream, int depth) const
{
for ( int i=0; i<depth; i++ )
{
stream.writeStringBuffer( " " );
}
stream.writeFormattedBuffer( "<!--%s-->", value.c_str() );
}
void fsTiXmlText::Print(FileStream& stream, int depth) const
{
if ( cdata )
{
int i;
stream.writeStringBuffer( "\n" );
for ( i=0; i<depth; i++ ) {
stream.writeStringBuffer( " " );
}
stream.writeFormattedBuffer( "<![CDATA[%s]]>\n", value.c_str() ); // unformatted output
}
else
{
TIXML_STRING buffer;
EncodeString( value, &buffer );
stream.writeFormattedBuffer( "%s", buffer.c_str() );
}
}
void fsTiXmlUnknown::Print(FileStream& stream, int depth) const
{
for ( int i=0; i<depth; i++ )
stream.writeStringBuffer( " " );
stream.writeFormattedBuffer( "<%s>", value.c_str() );
}
static TiXmlNode* TiNodeIdentify( TiXmlNode* parent, const char* p, TiXmlEncoding encoding )
{
TiXmlNode* returnNode = 0;
p = TiXmlNode::SkipWhiteSpace( p, encoding );
if( !p || !*p || *p != '<' )
{
return 0;
}
p = TiXmlNode::SkipWhiteSpace( p, encoding );
if ( !p || !*p )
{
return 0;
}
// What is this thing?
// - Elements start with a letter or underscore, but xml is reserved.
// - Comments: <!--
// - Decleration: <?xml
// - Everthing else is unknown to tinyxml.
//
const char* xmlHeader = { "<?xml" };
const char* commentHeader = { "<!--" };
const char* dtdHeader = { "<!" };
const char* cdataHeader = { "<![CDATA[" };
if ( TiXmlNode::StringEqual( p, xmlHeader, true, encoding ) )
{
#ifdef DEBUG_PARSER
TIXML_LOG( "XML parsing Declaration\n" );
#endif
returnNode = new fsTiXmlDeclaration();
}
else if ( TiXmlNode::StringEqual( p, commentHeader, false, encoding ) )
{
#ifdef DEBUG_PARSER
TIXML_LOG( "XML parsing Comment\n" );
#endif
returnNode = new fsTiXmlComment();
}
else if ( TiXmlNode::StringEqual( p, cdataHeader, false, encoding ) )
{
#ifdef DEBUG_PARSER
TIXML_LOG( "XML parsing CDATA\n" );
#endif
TiXmlText* text = new fsTiXmlText( "" );
text->SetCDATA( true );
returnNode = text;
}
else if ( TiXmlNode::StringEqual( p, dtdHeader, false, encoding ) )
{
#ifdef DEBUG_PARSER
TIXML_LOG( "XML parsing Unknown(1)\n" );
#endif
returnNode = new fsTiXmlUnknown();
}
else if ( TiXmlNode::IsAlpha( *(p+1), encoding )
|| *(p+1) == '_' )
{
#ifdef DEBUG_PARSER
TIXML_LOG( "XML parsing Element\n" );
#endif
returnNode = new fsTiXmlElement( "" );
}
else
{
#ifdef DEBUG_PARSER
TIXML_LOG( "XML parsing Unknown(2)\n" );
#endif
returnNode = new fsTiXmlUnknown();
}
if ( returnNode )
{
// Set the parent, so it can report errors
returnNode->parent = parent;
}
return returnNode;
}
TiXmlNode* fsTiXmlDocument::Identify( const char* p, TiXmlEncoding encoding )
{
return TiNodeIdentify(this, p, encoding);
}
TiXmlNode* fsTiXmlElement::Identify( const char* p, TiXmlEncoding encoding )
{
return TiNodeIdentify(this, p, encoding);
}
const char* fsTiXmlElement::Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding )
{
p = SkipWhiteSpace( p, encoding );
TiXmlDocument* document = GetDocument();
if ( !p || !*p )
{
if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, 0, 0, encoding );
return 0;
}
if ( data )
{
data->Stamp( p, encoding );
location = data->Cursor();
}
if ( *p != '<' )
{
if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, p, data, encoding );
return 0;
}
p = SkipWhiteSpace( p+1, encoding );
// Read the name.
const char* pErr = p;
p = ReadName( p, &value, encoding );
if ( !p || !*p )
{
if ( document ) document->SetError( TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME, pErr, data, encoding );
return 0;
}
TIXML_STRING endTag ("</");
endTag += value;
// Check for and read attributes. Also look for an empty
// tag or an end tag.
while ( p && *p )
{
pErr = p;
p = SkipWhiteSpace( p, encoding );
if ( !p || !*p )
{
if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES, pErr, data, encoding );
return 0;
}
if ( *p == '/' )
{
++p;
// Empty tag.
if ( *p != '>' )
{
if ( document ) document->SetError( TIXML_ERROR_PARSING_EMPTY, p, data, encoding );
return 0;
}
return (p+1);
}
else if ( *p == '>' )
{
// Done with attributes (if there were any.)
// Read the value -- which can include other
// elements -- read the end tag, and return.
++p;
p = ReadValue( p, data, encoding ); // Note this is an Element method, and will set the error if one happens.
if ( !p || !*p ) {
// We were looking for the end tag, but found nothing.
// Fix for [ 1663758 ] Failure to report error on bad XML
if ( document ) document->SetError( TIXML_ERROR_READING_END_TAG, p, data, encoding );
return 0;
}
// We should find the end tag now
// note that:
// </foo > and
// </foo>
// are both valid end tags.
if ( StringEqual( p, endTag.c_str(), false, encoding ) )
{
p += endTag.length();
p = SkipWhiteSpace( p, encoding );
if ( p && *p && *p == '>' ) {
++p;
return p;
}
if ( document ) document->SetError( TIXML_ERROR_READING_END_TAG, p, data, encoding );
return 0;
}
else
{
if ( document ) document->SetError( TIXML_ERROR_READING_END_TAG, p, data, encoding );
return 0;
}
}
else
{
// Try to read an attribute:
TiXmlAttribute* attrib = new fsTiXmlAttribute();
if ( !attrib )
{
return 0;
}
attrib->SetDocument( document );
pErr = p;
p = attrib->Parse( p, data, encoding );
if ( !p || !*p )
{
if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, pErr, data, encoding );
delete attrib;
return 0;
}
// Handle the strange case of double attributes:
#ifdef TIXML_USE_STL
TiXmlAttribute* node = attributeSet.Find( attrib->NameTStr() );
#else
TiXmlAttribute* node = attributeSet.Find( attrib->Name() );
#endif
if ( node )
{
if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT, pErr, data, encoding );
delete attrib;
return 0;
}
attributeSet.Add( attrib );
}
}
return p;
}
/*
TiXmlNode* fsTiXmlNode::Identify(char const* p, TiXmlEncoding encoding)
{
TiXmlNode* returnNode = 0;
p = TiXmlBase::SkipWhiteSpace( p, encoding );
if( !p || !*p || *p != '<' )
{
return 0;
}
p = TiXmlBase::SkipWhiteSpace( p, encoding );
if ( !p || !*p )
{
return 0;
}
// What is this thing?
// - Elements start with a letter or underscore, but xml is reserved.
// - Comments: <!--
// - Decleration: <?xml
// - Everthing else is unknown to tinyxml.
//
const char* xmlHeader = { "<?xml" };
const char* commentHeader = { "<!--" };
const char* dtdHeader = { "<!" };
const char* cdataHeader = { "<![CDATA[" };
if ( TiXmlBase::StringEqual( p, xmlHeader, true, encoding ) )
{
#ifdef DEBUG_PARSER
TIXML_LOG( "XML parsing Declaration\n" );
#endif
returnNode = new fsTiXmlDeclaration();
}
else if ( TiXmlBase::StringEqual( p, commentHeader, false, encoding ) )
{
#ifdef DEBUG_PARSER
TIXML_LOG( "XML parsing Comment\n" );
#endif
returnNode = new fsTiXmlComment();
}
else if ( TiXmlBase::StringEqual( p, cdataHeader, false, encoding ) )
{
#ifdef DEBUG_PARSER
TIXML_LOG( "XML parsing CDATA\n" );
#endif
fsTiXmlText* text = new fsTiXmlText( "" );
text->SetCDATA( true );
returnNode = text;
}
else if ( TiXmlBase::StringEqual( p, dtdHeader, false, encoding ) )
{
#ifdef DEBUG_PARSER
TIXML_LOG( "XML parsing Unknown(1)\n" );
#endif
returnNode = new fsTiXmlUnknown();
}
else if ( TiXmlBase::IsAlpha( *(p+1), encoding )
|| *(p+1) == '_' )
{
#ifdef DEBUG_PARSER
TIXML_LOG( "XML parsing Element\n" );
#endif
returnNode = new fsTiXmlElement( "" );
}
else
{
#ifdef DEBUG_PARSER
TIXML_LOG( "XML parsing Unknown(2)\n" );
#endif
returnNode = new fsTiXmlUnknown();
}
if ( returnNode )
{
// Set the parent, so it can report errors
returnNode->parent = this;
}
return returnNode;
}
const unsigned char TIXML_UTF_LEAD_0 = 0xefU;
const unsigned char TIXML_UTF_LEAD_1 = 0xbbU;
const unsigned char TIXML_UTF_LEAD_2 = 0xbfU;
char const* fsTiXmlDocument::Parse(char const* p, TiXmlParsingData* prevData, TiXmlEncoding encoding)
{
ClearError();
// Parse away, at the document level. Since a document
// contains nothing but other tags, most of what happens
// here is skipping white space.
if ( !p || !*p )
{
SetError( TiXmlBase::TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN );
return 0;
}
// Note that, for a document, this needs to come
// before the while space skip, so that parsing
// starts from the pointer we are given.
location.Clear();
if ( prevData )
{
location.row = prevData->Cursor().row;
location.col = prevData->Cursor().col;
}
else
{
location.row = 0;
location.col = 0;
}
TiXmlParsingData data( p, TabSize(), location.row, location.col );
location = data.Cursor();
if ( encoding == TIXML_ENCODING_UNKNOWN )
{
// Check for the Microsoft UTF-8 lead bytes.
const unsigned char* pU = (const unsigned char*)p;
if ( *(pU+0) && *(pU+0) == TIXML_UTF_LEAD_0
&& *(pU+1) && *(pU+1) == TIXML_UTF_LEAD_1
&& *(pU+2) && *(pU+2) == TIXML_UTF_LEAD_2 )
{
encoding = TIXML_ENCODING_UTF8;
useMicrosoftBOM = true;
}
}
p = TiXmlBase::SkipWhiteSpace( p, encoding );
if ( !p )
{
SetError( TiXmlBase::TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, TIXML_ENCODING_UNKNOWN );
return 0;
}
while ( p && *p )
{
TiXmlNode* node = fsTiXmlNode::Identify( p, encoding );
if ( node )
{
p = node->Parse( p, &data, encoding );
LinkEndChild( node );
}
else
{
break;
}
// Did we get encoding info?
if ( encoding == TIXML_ENCODING_UNKNOWN
&& node->ToDeclaration() )
{
TiXmlDeclaration* dec = node->ToDeclaration();
const char* enc = dec->Encoding();
assert( enc );
if ( *enc == 0 )
encoding = TIXML_ENCODING_UTF8;
else if ( TiXmlBase::StringEqual( enc, "UTF-8", true, TIXML_ENCODING_UNKNOWN ) )
encoding = TIXML_ENCODING_UTF8;
else if ( TiXmlBase::StringEqual( enc, "UTF8", true, TIXML_ENCODING_UNKNOWN ) )
encoding = TIXML_ENCODING_UTF8; // incorrect, but be nice
else
encoding = TIXML_ENCODING_LEGACY;
}
p = TiXmlBase::SkipWhiteSpace( p, encoding );
}
// Was this empty?
if ( !firstChild ) {
SetError( TiXmlBase::TIXML_ERROR_DOCUMENT_EMPTY, 0, 0, encoding );
return 0;
}
// All is well.
return p;
}
*/

View file

@ -0,0 +1,248 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _FSTINYXML_H_
#define _FSTINYXML_H_
#ifndef TINYXML_INCLUDED
#include "tinyXML/tinyxml.h"
#endif
#include "platform/platform.h"
#ifndef _FILESTREAM_H_
#include "core/stream/fileStream.h"
#endif
class fsTiXmlNode
{
public:
virtual void Print( FileStream& stream, int depth ) const = 0;
};
class fsTiXmlDocument : public TiXmlDocument, public fsTiXmlNode
{
public:
bool LoadFile( FileStream &stream, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
bool SaveFile( FileStream &stream ) const;
/// Load a file using the given filename. Returns true if successful.
bool LoadFile( const char * filename, TiXmlEncoding encoding = TIXML_DEFAULT_ENCODING );
/// Save a file using the given filename. Returns true if successful.
bool SaveFile( const char * filename ) const;
virtual void Print( FileStream& stream, int depth ) const;
virtual TiXmlNode* Clone() const
{
TiXmlDocument* clone = new fsTiXmlDocument();
if ( !clone )
return 0;
CopyTo( clone );
return clone;
}
TiXmlNode* Identify( const char* p, TiXmlEncoding encoding );
};
class fsTiXmlAttribute : public TiXmlAttribute, public fsTiXmlNode
{
public:
virtual void Print( FileStream& stream, int depth, TIXML_STRING* str ) const;
virtual void Print( FileStream& stream, int depth) const
{
Print(stream, depth, 0);
}
};
class fsTiXmlDeclaration : public TiXmlDeclaration, public fsTiXmlNode
{
public:
fsTiXmlDeclaration(){};
fsTiXmlDeclaration( const char* _version,
const char* _encoding,
const char* _standalone ) : TiXmlDeclaration(_version, _encoding, _standalone) { }
virtual void Print( FileStream& stream, int depth, TIXML_STRING* str ) const;
virtual void Print( FileStream& stream, int depth) const
{
Print(stream, depth, 0);
}
virtual TiXmlNode* Clone() const
{
fsTiXmlDeclaration* clone = new fsTiXmlDeclaration();
if ( !clone )
return 0;
CopyTo( clone );
return clone;
}
};
class fsTiXmlElement : public TiXmlElement, public fsTiXmlNode
{
public:
fsTiXmlElement(const char* in_value) : TiXmlElement(in_value) { }
virtual void Print( FileStream& stream, int depth ) const;
virtual TiXmlNode* Clone() const
{
TiXmlElement* clone = new fsTiXmlElement( Value() );
if ( !clone )
return 0;
CopyTo( clone );
return clone;
}
void SetAttribute( const char* name, const char * _value )
{
TiXmlAttribute* attrib = attributeSet.Find( name );
if(!attrib)
{
attrib = new fsTiXmlAttribute();
attributeSet.Add( attrib );
attrib->SetName( name );
}
if ( attrib ) {
attrib->SetValue( _value );
}
}
void SetAttribute( const char * name, int value )
{
TiXmlAttribute* attrib = attributeSet.Find( name );
if(!attrib)
{
attrib = new fsTiXmlAttribute();
attributeSet.Add( attrib );
attrib->SetName( name );
}
if ( attrib ) {
attrib->SetIntValue( value );
}
}
TiXmlNode* Identify( const char* p, TiXmlEncoding encoding );
virtual const char* Parse( const char* p, TiXmlParsingData* data, TiXmlEncoding encoding );
};
class fsTiXmlComment : public TiXmlComment, public fsTiXmlNode
{
public:
virtual void Print( FileStream& stream, int depth ) const;
virtual TiXmlNode* Clone() const
{
TiXmlComment* clone = new fsTiXmlComment();
if ( !clone )
return 0;
CopyTo( clone );
return clone;
}
};
class fsTiXmlText : public TiXmlText, public fsTiXmlNode
{
public:
fsTiXmlText (const char * initValue ) : TiXmlText(initValue) { }
virtual void Print( FileStream& stream, int depth ) const;
virtual TiXmlNode* Clone() const
{
TiXmlText* clone = 0;
clone = new fsTiXmlText( "" );
if ( !clone )
return 0;
CopyTo( clone );
return clone;
}
};
class fsTiXmlUnknown : public TiXmlUnknown, public fsTiXmlNode
{
public:
virtual void Print( FileStream& stream, int depth ) const;
virtual TiXmlNode* Clone() const
{
TiXmlUnknown* clone = new fsTiXmlUnknown();
if ( !clone )
return 0;
CopyTo( clone );
return clone;
}
};
static bool AttemptPrintTiNode(class fsTiXmlDocument* node, FileStream& stream, int depth)
{
fsTiXmlDocument* fsDoc = dynamic_cast<fsTiXmlDocument*>(node);
if(fsDoc != NULL)
{
fsDoc->Print(stream, depth);
return true;
}
fsTiXmlUnknown* fsUnk = dynamic_cast<fsTiXmlUnknown*>(node);
if(fsUnk != NULL)
{
fsUnk->Print(stream, depth);
return true;
}
fsTiXmlText* fsTxt = dynamic_cast<fsTiXmlText*>(node);
if(fsTxt != NULL)
{
fsTxt->Print(stream, depth);
return true;
}
fsTiXmlComment* fsCom = dynamic_cast<fsTiXmlComment*>(node);
if(fsCom != NULL)
{
fsCom->Print(stream, depth);
return true;
}
fsTiXmlElement* fsElm = dynamic_cast<fsTiXmlElement*>(node);
if(fsElm != NULL)
{
fsElm->Print(stream, depth);
return true;
}
fsTiXmlDeclaration* fsDec = dynamic_cast<fsTiXmlDeclaration*>(node);
if(fsDec != NULL)
{
fsDec->Print(stream, depth);
return true;
}
fsTiXmlAttribute* fsAtt = dynamic_cast<fsTiXmlAttribute*>(node);
if(fsAtt != NULL)
{
fsAtt->Print(stream, depth);
return true;
}
return false;
}
#endif //_FSTINYXML_H_

View file

@ -0,0 +1,258 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "persistence/taml/json/tamlJSONParser.h"
#include "persistence/taml/tamlVisitor.h"
#include "console/console.h"
#include "core/stream/fileStream.h"
#include "core/frameAllocator.h"
// Debug Profiling.
#include "platform/profiler.h"
//-----------------------------------------------------------------------------
bool TamlJSONParser::accept( const char* pFilename, TamlVisitor& visitor )
{
// Debug Profiling.
PROFILE_SCOPE(TamlJSONParser_Accept);
// Sanity!
AssertFatal( pFilename != NULL, "Cannot parse a NULL filename." );
// Expand the file-path.
char filenameBuffer[1024];
Con::expandToolScriptFilename( filenameBuffer, sizeof(filenameBuffer), pFilename );
FileStream stream;
// File open for read?
if ( !stream.open( filenameBuffer, Torque::FS::File::Write ) )
{
// No, so warn.
Con::warnf("TamlJSONParser::parse() - Could not open filename '%s' for parse.", filenameBuffer );
return false;
}
// Read JSON file.
const U32 streamSize = stream.getStreamSize();
FrameTemp<char> jsonText( streamSize + 1 );
if ( !stream.read( streamSize, jsonText ) )
{
// Warn!
Con::warnf("TamlJSONParser::parse() - Could not load Taml JSON file from stream.");
return false;
}
// Create JSON document.
rapidjson::Document inputDocument;
inputDocument.Parse<0>( jsonText );
// Close the stream.
stream.close();
// Check the document is valid.
if ( inputDocument.GetType() != rapidjson::kObjectType )
{
// Warn!
Con::warnf("TamlJSONParser::parse() - Load Taml JSON file from stream but was invalid.");
return false;
}
// Set parsing filename.
setParsingFilename( filenameBuffer );
// Flag document as not dirty.
mDocumentDirty = false;
// Fetch the root.
rapidjson::Value::MemberIterator rootItr = inputDocument.MemberBegin();
// Parse root value.
parseType( rootItr, visitor, true );
// Reset parsing filename.
setParsingFilename( StringTable->EmptyString() );
// Finish if the document is not dirty.
if ( !mDocumentDirty )
return true;
// Open for write?
if ( !stream.open( filenameBuffer, Torque::FS::File::Write ) )
{
// No, so warn.
Con::warnf("TamlJSONParser::parse() - Could not open filename '%s' for write.", filenameBuffer );
return false;
}
// Create output document.
rapidjson::Document outputDocument;
outputDocument.AddMember( rootItr->name, rootItr->value, outputDocument.GetAllocator() );
// Write document to stream.
rapidjson::PrettyWriter<FileStream> jsonStreamWriter( stream );
outputDocument.Accept( jsonStreamWriter );
// Close the stream.
stream.close();
return true;
}
//-----------------------------------------------------------------------------
inline bool TamlJSONParser::parseType( rapidjson::Value::MemberIterator& memberItr, TamlVisitor& visitor, const bool isRoot )
{
// Debug Profiling.
PROFILE_SCOPE(TamlJSONParser_ParseType);
// Fetch name and value.
const rapidjson::Value& typeName = memberItr->name;
rapidjson::Value& typeValue = memberItr->value;
// Create a visitor property state.
TamlVisitor::PropertyState propertyState;
propertyState.setObjectName( typeName.GetString(), isRoot );
// Parse field members.
for( rapidjson::Value::MemberIterator fieldMemberItr = typeValue.MemberBegin(); fieldMemberItr != typeValue.MemberEnd(); ++fieldMemberItr )
{
// Fetch value.
const rapidjson::Value& fieldName = fieldMemberItr->name;
rapidjson::Value& fieldValue = fieldMemberItr->value;
// Skip if not a field.
if ( fieldValue.IsObject() )
continue;
char valueBuffer[4096];
if ( !parseStringValue( valueBuffer, sizeof(valueBuffer), fieldValue, fieldName.GetString() ) )
{
// Warn.
Con::warnf( "TamlJSONParser::parseTyoe() - Could not interpret value for field '%s'", fieldName.GetString() );
continue;
}
// Configure property state.
propertyState.setProperty( fieldName.GetString(), valueBuffer );
// Visit this attribute.
const bool visitStatus = visitor.visit( *this, propertyState );
// Was the property value changed?
if ( propertyState.getPropertyValueDirty() )
{
// Yes, so update the attribute.
fieldValue.SetString( propertyState.getPropertyValue() );
// Flag the document as dirty.
mDocumentDirty = true;
}
// Finish if requested.
if ( !visitStatus )
return false;
}
// Finish if only the root is needed.
if ( visitor.wantsRootOnly() )
return false;
// Parse children and custom node members.
for( rapidjson::Value::MemberIterator objectMemberItr = typeValue.MemberBegin(); objectMemberItr != typeValue.MemberEnd(); ++objectMemberItr )
{
// Fetch name and value.
const rapidjson::Value& objectValue = objectMemberItr->value;
// Skip if not an object.
if ( !objectValue.IsObject() )
continue;
// Parse the type.
if ( !parseType( objectMemberItr, visitor, false ) )
return false;
}
return true;
}
//-----------------------------------------------------------------------------
inline bool TamlJSONParser::parseStringValue( char* pBuffer, const S32 bufferSize, const rapidjson::Value& value, const char* pName )
{
// Debug Profiling.
PROFILE_SCOPE(TamlJSONParser_ParseStringValue);
// Handle field value appropriately.
if ( value.IsString() )
{
dSprintf( pBuffer, bufferSize, "%s", value.GetString() );
return true;
}
if ( value.IsNumber() )
{
if ( value.IsInt() )
{
dSprintf( pBuffer, bufferSize, "%d", value.GetInt() );
return true;
}
if ( value.IsUint() )
{
dSprintf( pBuffer, bufferSize, "%d", value.GetUint() );
return true;
}
if ( value.IsInt64() )
{
dSprintf( pBuffer, bufferSize, "%d", value.GetInt64() );
return true;
}
if ( value.IsUint64() )
{
dSprintf( pBuffer, bufferSize, "%d", value.GetUint64() );
return true;
}
if ( value.IsDouble() )
{
dSprintf( pBuffer, bufferSize, "%f", value.GetDouble() );
return true;
}
}
if ( value.IsBool() )
{
dSprintf( pBuffer, bufferSize, "%d", value.GetBool() );
return true;
}
// Failed to get value type.
Con::warnf( "Taml: Encountered a field '%s' but its value is an unknown type.", pName );
return false;
}

View file

@ -0,0 +1,57 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _TAML_JSONPARSER_H_
#define _TAML_JSONPARSER_H_
#ifndef _TAML_PARSER_H_
#include "persistence/taml/tamlParser.h"
#endif
/// RapidJson.
#include "persistence/rapidjson/document.h"
#include "persistence/rapidjson/prettywriter.h"
//-----------------------------------------------------------------------------
/// @ingroup tamlGroup
/// @see tamlGroup
class TamlJSONParser : public TamlParser
{
public:
TamlJSONParser() {}
virtual ~TamlJSONParser() {}
/// Whether the parser can change a property or not.
virtual bool canChangeProperty( void ) { return true; }
/// Accept visitor.
virtual bool accept( const char* pFilename, TamlVisitor& visitor );
private:
inline bool parseType( rapidjson::Value::MemberIterator& memberItr, TamlVisitor& visitor, const bool isRoot );
inline bool parseStringValue( char* pBuffer, const S32 bufferSize, const rapidjson::Value& value, const char* pName );
bool mDocumentDirty;
};
#endif // _TAML_JSONPARSER_H_

View file

@ -0,0 +1,686 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "persistence/taml/json/tamlJSONReader.h"
#include "persistence/taml/json/tamlJSONWriter.h"
#include "core/stream/fileStream.h"
#include "core/strings/stringUnit.h"
#include "core/frameAllocator.h"
// Debug Profiling.
#include "platform/profiler.h"
//-----------------------------------------------------------------------------
SimObject* TamlJSONReader::read( FileStream& stream )
{
// Debug Profiling.
PROFILE_SCOPE(TamlJSONReader_Read);
// Read JSON file.
const U32 streamSize = stream.getStreamSize();
FrameTemp<char> jsonText( streamSize + 1 );
if ( !stream.read( streamSize, jsonText ) )
{
// Warn!
Con::warnf("TamlJSONReader::read() - Could not load Taml JSON file from stream.");
return NULL;
}
jsonText[streamSize] = '\0';
// Create JSON document.
rapidjson::Document document;
document.Parse<0>( jsonText );
// Check the document is valid.
if ( document.GetType() != rapidjson::kObjectType )
{
// Warn!
Con::warnf("TamlJSONReader::read() - Load Taml JSON file from stream but was invalid.");
return NULL;
}
// Parse root value.
SimObject* pSimObject = parseType( document.MemberBegin() );
// Reset parse.
resetParse();
return pSimObject;
}
//-----------------------------------------------------------------------------
void TamlJSONReader::resetParse( void )
{
// Debug Profiling.
PROFILE_SCOPE(TamlJSONReader_ResetParse);
// Clear object reference map.
mObjectReferenceMap.clear();
}
//-----------------------------------------------------------------------------
SimObject* TamlJSONReader::parseType( const rapidjson::Value::ConstMemberIterator& memberItr )
{
// Debug Profiling.
PROFILE_SCOPE(TamlJSONReader_ParseType);
// Fetch name and value.
const rapidjson::Value& typeName = memberItr->name;
const rapidjson::Value& typeValue = memberItr->value;
// Is value an object?
if ( !typeValue.IsObject() )
{
// No, so warn.
Con::warnf( "TamlJSONReader::parseType() - Cannot process type '%s' as it is not an object.", typeName.GetString() );
return NULL;
}
// Fetch engine type name (demangled).
StringTableEntry engineTypeName = getDemangledName( typeName.GetString() );
// Fetch reference to Id.
const U32 tamlRefToId = getTamlRefToId( typeValue );
// Do we have a reference to Id?
if ( tamlRefToId != 0 )
{
// Yes, so fetch reference.
typeObjectReferenceHash::Iterator referenceItr = mObjectReferenceMap.find( tamlRefToId );
// Did we find the reference?
if ( referenceItr == mObjectReferenceMap.end() )
{
// No, so warn.
Con::warnf( "TamlJSONReader::parseType() - Could not find a reference Id of '%d'", tamlRefToId );
return NULL;
}
// Return object.
return referenceItr->value;
}
// No, so fetch reference Id.
const U32 tamlRefId = getTamlRefId( typeValue );
// Create type.
SimObject* pSimObject = Taml::createType( engineTypeName, mpTaml );
// Finish if we couldn't create the type.
if ( pSimObject == NULL )
return NULL;
// Find Taml callbacks.
TamlCallbacks* pCallbacks = dynamic_cast<TamlCallbacks*>( pSimObject );
TamlCustomNodes customNodes;
// Are there any Taml callbacks?
if ( pCallbacks != NULL )
{
// Yes, so call it.
mpTaml->tamlPreRead( pCallbacks );
}
// Parse field members.
for( rapidjson::Value::ConstMemberIterator fieldMemberItr = typeValue.MemberBegin(); fieldMemberItr != typeValue.MemberEnd(); ++fieldMemberItr )
{
// Fetch value.
const rapidjson::Value& fieldValue = fieldMemberItr->value;
// Skip if not a field.
if ( fieldValue.IsObject() )
continue;
// Parse as field.
parseField( fieldMemberItr, pSimObject );
}
// Fetch object name.
StringTableEntry objectName = StringTable->insert( getTamlObjectName( typeValue ) );
// Does the object require a name?
if ( objectName == StringTable->EmptyString() )
{
// No, so just register anonymously.
pSimObject->registerObject();
}
else
{
// Yes, so register a named object.
pSimObject->registerObject( objectName );
// Was the name assigned?
if ( pSimObject->getName() != objectName )
{
// No, so warn that the name was rejected.
Con::warnf( "Taml::parseType() - Registered an instance of type '%s' but a request to name it '%s' was rejected. This is typically because an object of that name already exists.",
engineTypeName, objectName );
}
}
// Do we have a reference Id?
if ( tamlRefId != 0 )
{
// Yes, so insert reference.
mObjectReferenceMap.insertUnique( tamlRefId, pSimObject );
}
// Parse children and custom node members.
for( rapidjson::Value::ConstMemberIterator objectMemberItr = typeValue.MemberBegin(); objectMemberItr != typeValue.MemberEnd(); ++objectMemberItr )
{
// Fetch name and value.
const rapidjson::Value& objectName = objectMemberItr->name;
const rapidjson::Value& objectValue = objectMemberItr->value;
// Skip if not an object.
if ( !objectValue.IsObject() )
continue;
// Find the period character in the name.
const char* pPeriod = dStrchr( objectName.GetString(), '.' );
// Did we find the period?
if ( pPeriod == NULL )
{
// No, so parse child object.
parseChild( objectMemberItr, pSimObject );
continue;
}
// Yes, so parse custom object.
parseCustom( objectMemberItr, pSimObject, pPeriod+1, customNodes );
}
// Call custom read.
if ( pCallbacks )
{
mpTaml->tamlCustomRead( pCallbacks, customNodes );
mpTaml->tamlPostRead( pCallbacks, customNodes );
}
// Return object.
return pSimObject;
}
//-----------------------------------------------------------------------------
inline void TamlJSONReader::parseField( rapidjson::Value::ConstMemberIterator& memberItr, SimObject* pSimObject )
{
// Debug Profiling.
PROFILE_SCOPE(TamlJSONReader_ParseField);
// Fetch name and value.
const rapidjson::Value& name = memberItr->name;
const rapidjson::Value& value = memberItr->value;
// Insert the field name.
StringTableEntry fieldName = StringTable->insert( name.GetString() );
// Ignore if this is a Taml attribute.
if ( fieldName == tamlRefIdName ||
fieldName == tamlRefToIdName ||
fieldName == tamlNamedObjectName )
return;
// Get field value.
char valueBuffer[4096];
if ( !parseStringValue( valueBuffer, sizeof(valueBuffer), value, fieldName ) )
{
// Warn.
Con::warnf( "Taml::parseField() Could not interpret value for field '%s'", fieldName );
return;
}
// Set field.
pSimObject->setPrefixedDataField(fieldName, NULL, valueBuffer);
}
//-----------------------------------------------------------------------------
inline void TamlJSONReader::parseChild( rapidjson::Value::ConstMemberIterator& memberItr, SimObject* pSimObject )
{
// Debug Profiling.
PROFILE_SCOPE(TamlJSONReader_ParseChild);
// Fetch name.
const rapidjson::Value& name = memberItr->name;
// Fetch the Taml children.
TamlChildren* pChildren = dynamic_cast<TamlChildren*>( pSimObject );
// Is this a Taml child?
if ( pChildren == NULL )
{
// No, so warn.
Con::warnf("Taml::parseChild() - Child member '%s' found under parent '%s' but object cannot have children.",
name.GetString(),
pSimObject->getClassName() );
return;
}
// Fetch any container child class specifier.
AbstractClassRep* pContainerChildClass = pSimObject->getClassRep()->getContainerChildClass( true );
// Parse child member.
SimObject* pChildSimObject = parseType( memberItr );
// Finish if the child was not created.
if ( pChildSimObject == NULL )
return;
// Do we have a container child class?
if ( pContainerChildClass != NULL )
{
// Yes, so is the child object the correctly derived type?
if ( !pChildSimObject->getClassRep()->isClass( pContainerChildClass ) )
{
// No, so warn.
Con::warnf("Taml::parseChild() - Child element '%s' found under parent '%s' but object is restricted to children of type '%s'.",
pChildSimObject->getClassName(),
pSimObject->getClassName(),
pContainerChildClass->getClassName() );
// NOTE: We can't delete the object as it may be referenced elsewhere!
pChildSimObject = NULL;
return;
}
}
// Add child.
pChildren->addTamlChild( pChildSimObject );
// Find Taml callbacks for child.
TamlCallbacks* pChildCallbacks = dynamic_cast<TamlCallbacks*>( pChildSimObject );
// Do we have callbacks on the child?
if ( pChildCallbacks != NULL )
{
// Yes, so perform callback.
mpTaml->tamlAddParent( pChildCallbacks, pSimObject );
}
}
//-----------------------------------------------------------------------------
inline void TamlJSONReader::parseCustom( rapidjson::Value::ConstMemberIterator& memberItr, SimObject* pSimObject, const char* pCustomNodeName, TamlCustomNodes& customNodes )
{
// Debug Profiling.
PROFILE_SCOPE(TamlJSONReader_ParseCustom);
// Fetch value.
const rapidjson::Value& value = memberItr->value;
// Add custom node.
TamlCustomNode* pCustomNode = customNodes.addNode( pCustomNodeName );
// Iterate members.
for( rapidjson::Value::ConstMemberIterator customMemberItr = value.MemberBegin(); customMemberItr != value.MemberEnd(); ++customMemberItr )
{
// Fetch value.
const rapidjson::Value& customValue = customMemberItr->value;
// Is the member an object?
if ( !customValue.IsObject() && !customValue.IsArray() )
{
// No, so warn.
Con::warnf( "Taml::parseCustom() - Cannot process custom node name '%s' member as child value is not an object or array.", pCustomNodeName );
return;
}
// Parse custom node.
parseCustomNode( customMemberItr, pCustomNode );
}
}
//-----------------------------------------------------------------------------
inline void TamlJSONReader::parseCustomNode( rapidjson::Value::ConstMemberIterator& memberItr, TamlCustomNode* pCustomNode )
{
// Debug Profiling.
PROFILE_SCOPE(TamlJSONReader_ParseCustomNode);
// Fetch name and value.
const rapidjson::Value& name = memberItr->name;
const rapidjson::Value& value = memberItr->value;
// Is the value an object?
if ( value.IsObject() )
{
// Yes, so is the node a proxy object?
if ( getTamlRefId( value ) != 0 || getTamlRefToId( value ) != 0 )
{
// Yes, so parse proxy object.
SimObject* pProxyObject = parseType( memberItr );
// Add child node.
pCustomNode->addNode( pProxyObject );
return;
}
}
char valueBuffer[4096];
// Fetch the node name.
StringTableEntry nodeName = getDemangledName( name.GetString() );
// Yes, so add child node.
TamlCustomNode* pChildNode = pCustomNode->addNode( nodeName );
// Is the value an array?
if ( value.IsArray() )
{
// Yes, so does it have a single entry?
if ( value.Size() == 1 )
{
// Yes, so parse the node text.
if ( parseStringValue( valueBuffer, sizeof(valueBuffer), value.Begin(), nodeName ) )
{
pChildNode->setNodeText( valueBuffer );
}
else
{
// Warn.
Con::warnf( "Taml::parseCustomNode() - Encountered text in the custom node '%s' but could not interpret the value.", nodeName );
}
}
else
{
// No, so warn.
Con::warnf( "Taml::parseCustomNode() - Encountered text in the custom node '%s' but more than a single element was found in the array.", nodeName );
}
return;
}
// Iterate child members.
for( rapidjson::Value::ConstMemberIterator childMemberItr = value.MemberBegin(); childMemberItr != value.MemberEnd(); ++childMemberItr )
{
// Fetch name and value.
const rapidjson::Value& childName = childMemberItr->name;
const rapidjson::Value& childValue = childMemberItr->value;
// Fetch the field name.
StringTableEntry fieldName = StringTable->insert( childName.GetString() );
// Is the value an array?
if ( childValue.IsArray() )
{
// Yes, so does it have a single entry?
if ( childValue.Size() == 1 )
{
// Yes, so parse the node text.
if ( parseStringValue( valueBuffer, sizeof(valueBuffer), *childValue.Begin(), fieldName ) )
{
// Yes, so add sub-child node.
TamlCustomNode* pSubChildNode = pChildNode->addNode( fieldName );
// Set sub-child text.
pSubChildNode->setNodeText( valueBuffer );
continue;
}
// Warn.
Con::warnf( "Taml::parseCustomNode() - Encountered text in the custom node '%s' but could not interpret the value.", fieldName );
return;
}
// No, so warn.
Con::warnf( "Taml::parseCustomNode() - Encountered text in the custom node '%s' but more than a single element was found in the array.", fieldName );
return;
}
// Is the member an object?
if ( childValue.IsObject() )
{
// Yes, so parse custom node.
parseCustomNode( childMemberItr, pChildNode );
continue;
}
// Ignore if this is a Taml attribute.
if ( fieldName == tamlRefIdName ||
fieldName == tamlRefToIdName ||
fieldName == tamlNamedObjectName )
continue;
// Parse string value.
if ( !parseStringValue( valueBuffer, sizeof(valueBuffer), childValue, childName.GetString() ) )
{
// Warn.
Con::warnf( "Taml::parseCustomNode() - Could not interpret value for field '%s'", fieldName );
continue;
}
// Add node field.
pChildNode->addField( fieldName, valueBuffer );
}
}
//-----------------------------------------------------------------------------
inline StringTableEntry TamlJSONReader::getDemangledName( const char* pMangledName )
{
// Debug Profiling.
PROFILE_SCOPE(TamlJSONReader_GetDemangledName);
// Is the type name mangled?
if ( StringUnit::getUnitCount( pMangledName, JSON_RFC4627_NAME_MANGLING_CHARACTERS ) > 1 )
{
// Yes, so fetch type name portion.
return StringTable->insert( StringUnit::getUnit( pMangledName, 0, JSON_RFC4627_NAME_MANGLING_CHARACTERS ) );
}
// No, so use all the type name.
return StringTable->insert( pMangledName );
}
//-----------------------------------------------------------------------------
inline bool TamlJSONReader::parseStringValue( char* pBuffer, const S32 bufferSize, const rapidjson::Value& value, const char* pName )
{
// Debug Profiling.
PROFILE_SCOPE(TamlJSONReader_ParseStringValue);
// Handle field value appropriately.
if ( value.IsString() )
{
dSprintf( pBuffer, bufferSize, "%s", value.GetString() );
return true;
}
if ( value.IsNumber() )
{
if ( value.IsInt() )
{
dSprintf( pBuffer, bufferSize, "%d", value.GetInt() );
return true;
}
if ( value.IsUint() )
{
dSprintf( pBuffer, bufferSize, "%d", value.GetUint() );
return true;
}
if ( value.IsInt64() )
{
dSprintf( pBuffer, bufferSize, "%d", value.GetInt64() );
return true;
}
if ( value.IsUint64() )
{
dSprintf( pBuffer, bufferSize, "%d", value.GetUint64() );
return true;
}
if ( value.IsDouble() )
{
dSprintf( pBuffer, bufferSize, "%f", value.GetDouble() );
return true;
}
}
if ( value.IsBool() )
{
dSprintf( pBuffer, bufferSize, "%d", value.GetBool() );
return true;
}
// Failed to get value type.
Con::warnf( "Taml: Encountered a field '%s' but its value is an unknown type.", pName );
return false;
}
//-----------------------------------------------------------------------------
inline U32 TamlJSONReader::getTamlRefId( const rapidjson::Value& value )
{
// Debug Profiling.
PROFILE_SCOPE(TamlJSONReader_GetTamlRefId);
// Is the value an object?
if ( !value.IsObject() )
{
// No, so warn.
Con::warnf( "Taml::getTamlRefId() - Cannot get '%s' member as value is not an object.", tamlRefIdName );
return 0;
}
// Iterate members.
for( rapidjson::Value::ConstMemberIterator memberItr = value.MemberBegin(); memberItr != value.MemberEnd(); ++memberItr )
{
// Insert member name.
StringTableEntry attributeName = StringTable->insert( memberItr->name.GetString() );
// Skip if not the correct attribute.
if ( attributeName != tamlRefIdName )
continue;
// Is the value an integer?
if ( !memberItr->value.IsInt() )
{
// No, so warn.
Con::warnf( "Taml::getTamlRefId() - Found '%s' member but it is not an integer.", tamlRefIdName );
return 0;
}
// Return it.
return (U32)memberItr->value.GetInt();
}
// Not found.
return 0;
}
//-----------------------------------------------------------------------------
inline U32 TamlJSONReader::getTamlRefToId( const rapidjson::Value& value )
{
// Debug Profiling.
PROFILE_SCOPE(TamlJSONReader_GetTamlRefToId);
// Is the value an object?
if ( !value.IsObject() )
{
// No, so warn.
Con::warnf( "Taml::getTamlRefToId() - Cannot get '%s' member as value is not an object.", tamlRefToIdName );
return 0;
}
// Iterate members.
for( rapidjson::Value::ConstMemberIterator memberItr = value.MemberBegin(); memberItr != value.MemberEnd(); ++memberItr )
{
// Insert member name.
StringTableEntry attributeName = StringTable->insert( memberItr->name.GetString() );
// Skip if not the correct attribute.
if ( attributeName != tamlRefToIdName )
continue;
// Is the value an integer?
if ( !memberItr->value.IsInt() )
{
// No, so warn.
Con::warnf( "Taml::getTamlRefToId() - Found '%s' member but it is not an integer.", tamlRefToIdName );
return 0;
}
// Return it.
return (U32)memberItr->value.GetInt();
}
// Not found.
return 0;
}
//-----------------------------------------------------------------------------
inline const char* TamlJSONReader::getTamlObjectName( const rapidjson::Value& value )
{
// Debug Profiling.
PROFILE_SCOPE(TamlJSONReader_GetTamlObjectName);
// Is the value an object?
if ( !value.IsObject() )
{
// No, so warn.
Con::warnf( "Taml::getTamlObjectName() - Cannot get '%s' member as value is not an object.", tamlNamedObjectName );
return 0;
}
// Iterate members.
for( rapidjson::Value::ConstMemberIterator memberItr = value.MemberBegin(); memberItr != value.MemberEnd(); ++memberItr )
{
// Insert member name.
StringTableEntry attributeName = StringTable->insert( memberItr->name.GetString() );
// Skip if not the correct attribute.
if ( attributeName != tamlNamedObjectName )
continue;
// Is the value an integer?
if ( !memberItr->value.IsString() )
{
// No, so warn.
Con::warnf( "Taml::getTamlObjectName() - Found '%s' member but it is not a string.", tamlNamedObjectName );
return NULL;
}
// Return it.
return memberItr->value.GetString();
}
// Not found.
return NULL;
}

View file

@ -0,0 +1,76 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _TAML_JSONREADER_H_
#define _TAML_JSONREADER_H_
#ifndef _TDICTIONARY_H_
#include "core/util/tDictionary.h"
#endif
#ifndef _TAML_H_
#include "persistence/taml/taml.h"
#endif
/// RapidJson.
#include "persistence/rapidjson/document.h"
#include "persistence/rapidjson/prettywriter.h"
//-----------------------------------------------------------------------------
/// @ingroup tamlGroup
/// @see tamlGroup
class TamlJSONReader
{
public:
TamlJSONReader( Taml* pTaml ) :
mpTaml( pTaml )
{}
virtual ~TamlJSONReader() {}
/// Read.
SimObject* read( FileStream& stream );
private:
Taml* mpTaml;
typedef HashTable<SimObjectId, SimObject*> typeObjectReferenceHash;
typeObjectReferenceHash mObjectReferenceMap;
private:
void resetParse( void );
SimObject* parseType( const rapidjson::Value::ConstMemberIterator& memberItr );
inline void parseField( rapidjson::Value::ConstMemberIterator& memberItr, SimObject* pSimObject );
inline void parseChild( rapidjson::Value::ConstMemberIterator& memberItr, SimObject* pSimObject );
inline void parseCustom( rapidjson::Value::ConstMemberIterator& memberItr, SimObject* pSimObject, const char* pCustomNodeName, TamlCustomNodes& customNodes );
inline void parseCustomNode( rapidjson::Value::ConstMemberIterator& memberItr, TamlCustomNode* pCustomNode );
inline StringTableEntry getDemangledName( const char* pMangledName );
inline bool parseStringValue( char* pBuffer, const S32 bufferSize, const rapidjson::Value& value, const char* pName );
inline U32 getTamlRefId( const rapidjson::Value& value );
inline U32 getTamlRefToId( const rapidjson::Value& value );
inline const char* getTamlObjectName( const rapidjson::Value& value );
};
#endif // _TAML_JSONREADER_H_

View file

@ -0,0 +1,367 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "persistence/taml/json/tamlJSONWriter.h"
#include "core/stringTable.h"
#include "core/stream/fileStream.h"
// Debug Profiling.
#include "platform/profiler.h"
//-----------------------------------------------------------------------------
// These are the characters allowed that separate the type-name from the type.
// These separators can be used to ensure that each member in an object has
// a unique name.
//
// It is important to understand that TAML does not require entries to be unique
// but technically the RFC4627 spec states it as "should" be seems to be taken
// as MUST. See here: http://www.ietf.org/rfc/rfc4627.txt
//
// They can be placed as a suffix to the type-name. The very first occurance
// is used to split the type-name from the suffix so you can form whatever
// suffix you like to make entries unique.
// Examples are "Sprite 0", "Sprite*0", "Sprite[0]", "Sprite,0" etc.
//
// Type-names can legally consist of a-z, A-Z, 0-9 and "_" (underscore) so these
// characters cannot be used for mangling. Feel free to add any characters you
// require to this list.
StringTableEntry JSON_RFC4627_NAME_MANGLING_CHARACTERS = StringTable->insert(" !$%^&*()-+{}[]@:~#|\\/?<>,.\n\r\t");
// This is the "dSprintf" format that the JSON writer uses to encode each
// member if JSON_RFC4627 mode is on. You are free to change this as long as
// you ensure that it starts with the "%s" character (which represents the type name)
// and is immediately followed by at least a single mangling character and that the
// "%d" is present as that represents the automatically-added member index.
StringTableEntry JSON_RFC4627_NAME_MANGLING_FORMAT = StringTable->insert( "%s[%d]" );
//-----------------------------------------------------------------------------
bool TamlJSONWriter::write( FileStream& stream, const TamlWriteNode* pTamlWriteNode )
{
// Debug Profiling.
PROFILE_SCOPE(TamlJSONWriter_Write);
// Create document.
rapidjson::Document document;
document.SetObject();
// Compile the root type.
rapidjson::Value rootValue(rapidjson::kObjectType);
compileType( document, &rootValue, NULL, pTamlWriteNode, -1 );
// Write document to stream.
rapidjson::PrettyWriter<FileStream> jsonStreamWriter( stream );
document.Accept( jsonStreamWriter );
return true;
}
//-----------------------------------------------------------------------------
void TamlJSONWriter::compileType( rapidjson::Document& document, rapidjson::Value* pTypeValue, rapidjson::Value* pParentValue, const TamlWriteNode* pTamlWriteNode, const S32 memberIndex )
{
// Debug Profiling.
PROFILE_SCOPE(TamlJSONWriter_CompileType);
// Fetch the json document allocator.
rapidjson::Document::AllocatorType& allocator = document.GetAllocator();
// Fetch object.
SimObject* pSimObject = pTamlWriteNode->mpSimObject;
// Fetch JSON strict flag (don't use it if member index is set to not use it).
const bool jsonStrict = memberIndex == -1 ? false : mpTaml->getJSONStrict();
// Fetch element name (mangled or not).
StringTableEntry elementName = jsonStrict ? getManagedName( pSimObject->getClassName(), memberIndex ) : pSimObject->getClassName();
// Is there a parent value?
if ( pParentValue == NULL )
{
// No, so add as document root value member.
pTypeValue = &((document.AddMember( elementName, *pTypeValue, allocator ).MemberEnd()-1)->value);
}
else
{
// Yes, so add as a parent value member.
pTypeValue = &((pParentValue->AddMember( elementName, *pTypeValue, allocator ).MemberEnd()-1)->value);
}
// Fetch reference Id.
const U32 referenceId = pTamlWriteNode->mRefId;
// Do we have a reference Id?
if ( referenceId != 0 )
{
// Yes, so set reference Id.
rapidjson::Value value;
value.SetInt( referenceId );
pTypeValue->AddMember( tamlRefIdName, value, allocator );
}
// Do we have a reference to node?
else if ( pTamlWriteNode->mRefToNode != NULL )
{
// Yes, so fetch reference to Id.
const U32 referenceToId = pTamlWriteNode->mRefToNode->mRefId;
// Sanity!
AssertFatal( referenceToId != 0, "Taml: Invalid reference to Id." );
// Set reference to Id.
rapidjson::Value value;
value.SetInt( referenceToId );
pTypeValue->AddMember( tamlRefToIdName, value, allocator );
// Finish because we're a reference to another object.
return;
}
// Fetch object name.
const char* pObjectName = pTamlWriteNode->mpObjectName;
// Do we have a name?
if ( pObjectName != NULL )
{
// Yes, so set name.
rapidjson::Value value;
value.SetString( pObjectName, dStrlen(pObjectName), allocator );
pTypeValue->AddMember( tamlNamedObjectName, value, allocator );
}
// Compile field.
compileFields( document, pTypeValue, pTamlWriteNode );
// Fetch children.
Vector<TamlWriteNode*>* pChildren = pTamlWriteNode->mChildren;
// Do we have any children?
if ( pChildren )
{
S32 childMemberIndex = 0;
// Yes, so iterate children.
for( Vector<TamlWriteNode*>::iterator itr = pChildren->begin(); itr != pChildren->end(); ++itr )
{
// Compile child type.
rapidjson::Value childValue(rapidjson::kObjectType);
compileType( document, &childValue, pTypeValue, (*itr), childMemberIndex++ );
}
}
// Compile custom.
compileCustom( document, pTypeValue, pTamlWriteNode );
}
//-----------------------------------------------------------------------------
void TamlJSONWriter::compileFields( rapidjson::Document& document, rapidjson::Value* pTypeValue, const TamlWriteNode* pTamlWriteNode )
{
// Debug Profiling.
PROFILE_SCOPE(TamlJSONWriter_CompileFields);
// Fetch fields.
const Vector<TamlWriteNode::FieldValuePair*>& fields = pTamlWriteNode->mFields;
// Ignore if no fields.
if ( fields.size() == 0 )
return;
// Fetch the json document allocator.
rapidjson::Document::AllocatorType& allocator = document.GetAllocator();
// Iterate fields.
for( Vector<TamlWriteNode::FieldValuePair*>::const_iterator itr = fields.begin(); itr != fields.end(); ++itr )
{
// Fetch field/value pair.
TamlWriteNode::FieldValuePair* pFieldValue = (*itr);
// Set field attribute.
rapidjson::Value value;
value.SetString( pFieldValue->mpValue, dStrlen(pFieldValue->mpValue), allocator );
pTypeValue->AddMember( pFieldValue->mName, value, allocator );
}
}
//-----------------------------------------------------------------------------
void TamlJSONWriter::compileCustom( rapidjson::Document& document, rapidjson::Value* pTypeValue, const TamlWriteNode* pTamlWriteNode )
{
// Debug Profiling.
PROFILE_SCOPE(TamlJSONWriter_CompileCustom);
// Fetch custom nodes.
const TamlCustomNodes& customNodes = pTamlWriteNode->mCustomNodes;
// Fetch custom nodes.
const TamlCustomNodeVector& nodes = customNodes.getNodes();
// Finish if no custom nodes to process.
if ( nodes.size() == 0 )
return;
// Fetch the json document allocator.
rapidjson::Document::AllocatorType& allocator = document.GetAllocator();
// Fetch object.
SimObject* pSimObject = pTamlWriteNode->mpSimObject;
// Fetch element name.
const char* pElementName = pSimObject->getClassName();
// Iterate custom nodes.
for( TamlCustomNodeVector::const_iterator customNodesItr = nodes.begin(); customNodesItr != nodes.end(); ++customNodesItr )
{
// Fetch the custom node.
TamlCustomNode* pCustomNode = *customNodesItr;
// Format extended element name.
char extendedElementNameBuffer[256];
dSprintf( extendedElementNameBuffer, sizeof(extendedElementNameBuffer), "%s.%s", pElementName, pCustomNode->getNodeName() );
StringTableEntry elementNameEntry = StringTable->insert( extendedElementNameBuffer );
rapidjson::Value elementValue(rapidjson::kObjectType);
rapidjson::Value* pElementValue = &((pTypeValue->AddMember( elementNameEntry, elementValue, allocator ).MemberEnd()-1)->value);
// Fetch node children.
const TamlCustomNodeVector& nodeChildren = pCustomNode->getChildren();
S32 childMemberIndex = 0;
// Iterate children nodes.
for( TamlCustomNodeVector::const_iterator childNodeItr = nodeChildren.begin(); childNodeItr != nodeChildren.end(); ++childNodeItr )
{
// Fetch child node.
const TamlCustomNode* pChildNode = *childNodeItr;
// Compile the custom node.
compileCustomNode( document, pElementValue, pChildNode, childMemberIndex++ );
}
// Finish if the node is set to ignore if empty and it is empty.
if ( pCustomNode->getIgnoreEmpty() && pTypeValue->MemberBegin() == pTypeValue->MemberEnd() )
{
// Yes, so delete the member.
pElementValue->SetNull();
}
}
}
//-----------------------------------------------------------------------------
void TamlJSONWriter::compileCustomNode( rapidjson::Document& document, rapidjson::Value* pParentValue, const TamlCustomNode* pCustomNode, const S32 memberIndex )
{
// Debug Profiling.
PROFILE_SCOPE(TamlJSONWriter_CompileCustomNode);
// Finish if the node is set to ignore if empty and it is empty.
if ( pCustomNode->getIgnoreEmpty() && pCustomNode->isEmpty() )
return;
// Is the node a proxy object?
if ( pCustomNode->isProxyObject() )
{
// Yes, so write the proxy object.
rapidjson::Value proxyValue(rapidjson::kObjectType);
compileType( document, &proxyValue, pParentValue, pCustomNode->getProxyWriteNode(), memberIndex );
return;
}
// Fetch the json document allocator.
rapidjson::Document::AllocatorType& allocator = document.GetAllocator();
// Fetch fields.
const TamlCustomFieldVector& fields = pCustomNode->getFields();
// Fetch JSON strict flag (don't use it if member index is set to not use it).
const bool jsonStrict = memberIndex == -1 ? false : mpTaml->getJSONStrict();
// Fetch element name (mangled or not).
StringTableEntry nodeName = jsonStrict ? getManagedName( pCustomNode->getNodeName(), memberIndex ) : pCustomNode->getNodeName();
// Is there any node text?
if ( !pCustomNode->getNodeTextField().isValueEmpty() )
{
// Yes, so fetch text.
const char* pNodeText = pCustomNode->getNodeTextField().getFieldValue();
// Create custom value.
rapidjson::Value customTextValue(rapidjson::kArrayType);
customTextValue.PushBack( pNodeText, allocator );
pParentValue->AddMember( nodeName, customTextValue, allocator );
return;
}
// Create custom value.
rapidjson::Value customValue(rapidjson::kObjectType);
rapidjson::Value* pCustomValue = &((pParentValue->AddMember( nodeName, customValue, allocator ).MemberEnd()-1)->value);
// Iterate fields.
for ( TamlCustomFieldVector::const_iterator fieldItr = fields.begin(); fieldItr != fields.end(); ++fieldItr )
{
// Fetch field.
const TamlCustomField* pField = *fieldItr;
// Add a field.
rapidjson::Value fieldValue;
fieldValue.SetString( pField->getFieldValue(), dStrlen(pField->getFieldValue()), allocator );
pCustomValue->AddMember( pField->getFieldName(), fieldValue, allocator );
}
// Fetch node children.
const TamlCustomNodeVector& nodeChildren = pCustomNode->getChildren();
S32 childMemberIndex = 0;
// Iterate children nodes.
for( TamlCustomNodeVector::const_iterator childNodeItr = nodeChildren.begin(); childNodeItr != nodeChildren.end(); ++childNodeItr )
{
// Fetch child node.
const TamlCustomNode* pChildNode = *childNodeItr;
// Compile the child node.
compileCustomNode( document, pCustomValue, pChildNode, childMemberIndex++ );
}
// Finish if the node is set to ignore if empty and it is empty (including fields).
if ( pCustomNode->getIgnoreEmpty() && fields.size() == 0 && pCustomValue->MemberBegin() == pCustomValue->MemberEnd() )
{
// Yes, so delete the member.
pCustomValue->SetNull();
}
}
//-----------------------------------------------------------------------------
inline StringTableEntry TamlJSONWriter::getManagedName( const char* pName, const S32 memberIndex )
{
// Debug Profiling.
PROFILE_SCOPE(TamlJSONWriter_getManagedName);
char nameBuffer[1024];
// Format mangled name.
dSprintf( nameBuffer, sizeof(nameBuffer), JSON_RFC4627_NAME_MANGLING_FORMAT, pName, memberIndex );
return StringTable->insert( nameBuffer );
}

View file

@ -0,0 +1,66 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _TAML_JSONWRITER_H_
#define _TAML_JSONWRITER_H_
#ifndef _TAML_H_
#include "persistence/taml/taml.h"
#endif
/// RapidJson.
#include "persistence/rapidjson/document.h"
#include "persistence/rapidjson/prettywriter.h"
//-----------------------------------------------------------------------------
extern StringTableEntry JSON_RFC4627_NAME_MANGLING_CHARACTERS;
extern StringTableEntry JSON_RFC4627_NAME_MANGLING_FORMAT;
//-----------------------------------------------------------------------------
/// @ingroup tamlGroup
/// @see tamlGroup
class TamlJSONWriter
{
public:
TamlJSONWriter( Taml* pTaml ) :
mpTaml( pTaml )
{}
virtual ~TamlJSONWriter() {}
/// Write.
bool write( FileStream& stream, const TamlWriteNode* pTamlWriteNode );
private:
Taml* mpTaml;
private:
void compileType( rapidjson::Document& document, rapidjson::Value* pTypeValue, rapidjson::Value* pParentValue, const TamlWriteNode* pTamlWriteNode, const S32 memberIndex );
void compileFields( rapidjson::Document& document, rapidjson::Value* pTypeValue, const TamlWriteNode* pTamlWriteNode );
void compileCustom( rapidjson::Document& document, rapidjson::Value* pTypeValue, const TamlWriteNode* pTamlWriteNode );
void compileCustomNode( rapidjson::Document& document, rapidjson::Value* pParentValue, const TamlCustomNode* pCustomNode, const S32 memberIndex );
inline StringTableEntry getManagedName(const char* pName, const S32 memberIndex );
};
#endif // _TAML_JSONWRITER_H_

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,218 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _TAML_H_
#define _TAML_H_
#ifndef _TAML_CALLBACKS_H_
#include "persistence/taml/tamlCallbacks.h"
#endif
#ifndef _TAML_CUSTOM_H_
#include "persistence/taml/tamlCustom.h"
#endif
#ifndef _TAML_CHILDREN_H_
#include "persistence/taml/tamlChildren.h"
#endif
#ifndef _TAML_WRITE_NODE_H_
#include "persistence/taml/tamlWriteNode.h"
#endif
#ifndef _TAML_VISITOR_H_
#include "persistence/taml/tamlVisitor.h"
#endif
#ifndef _SIMBASE_H_
#include "console/simBase.h"
#endif
#ifndef _TDICTIONARY_H_
#include "core/util/tDictionary.h"
#endif
#ifndef _FILESTREAM_H_
#include "core/stream/fileStream.h"
#endif
//-----------------------------------------------------------------------------
extern StringTableEntry tamlRefIdName;
extern StringTableEntry tamlRefToIdName;
extern StringTableEntry tamlNamedObjectName;
//-----------------------------------------------------------------------------
#define TAML_SIGNATURE "Taml"
#define TAML_SCHEMA_VARIABLE "$pref::T2D::TAMLSchema"
#define TAML_JSON_STRICT_VARIBLE "$pref::T2D::JSONStrict"
class TiXmlElement;
//-----------------------------------------------------------------------------
/// @ingroup tamlGroup
/// @see tamlGroup
class Taml : public SimObject
{
public:
enum TamlFormatMode
{
InvalidFormat = 0,
XmlFormat,
BinaryFormat,
JSONFormat,
};
private:
typedef SimObject Parent;
typedef Vector<TamlWriteNode*> typeNodeVector;
typedef HashTable<SimObjectId, TamlWriteNode*> typeCompiledHash;
typeNodeVector mCompiledNodes;
typeCompiledHash mCompiledObjects;
U32 mMasterNodeId;
TamlFormatMode mFormatMode;
StringTableEntry mAutoFormatXmlExtension;
StringTableEntry mAutoFormatBinaryExtension;
StringTableEntry mAutoFormatJSONExtension;
bool mJSONStrict;
bool mBinaryCompression;
bool mAutoFormat;
bool mWriteDefaults;
bool mProgenitorUpdate;
char mFilePathBuffer[1024];
private:
void resetCompilation( void );
TamlWriteNode* compileObject( SimObject* pSimObject, const bool forceId = false );
void compileStaticFields( TamlWriteNode* pTamlWriteNode );
void compileDynamicFields( TamlWriteNode* pTamlWriteNode );
void compileChildren( TamlWriteNode* pTamlWriteNode );
void compileCustomState( TamlWriteNode* pTamlWriteNode );
void compileCustomNodeState( TamlCustomNode* pCustomNode );
bool write( FileStream& stream, SimObject* pSimObject, const TamlFormatMode formatMode );
SimObject* read( FileStream& stream, const TamlFormatMode formatMode );
template<typename T> inline T* read( FileStream& stream, const TamlFormatMode formatMode )
{
SimObject* pSimObject = read( stream, formatMode );
if ( pSimObject == NULL )
return NULL;
T* pObj = dynamic_cast<T*>( pSimObject );
if ( pObj != NULL )
return pObj;
pSimObject->deleteObject();
return NULL;
}
public:
Taml();
virtual ~Taml() {}
virtual bool onAdd();
virtual void onRemove();
static void initPersistFields();
/// Format mode.
inline void setFormatMode( const TamlFormatMode formatMode ) { mFormatMode = formatMode != Taml::InvalidFormat ? formatMode : Taml::XmlFormat; }
inline TamlFormatMode getFormatMode( void ) const { return mFormatMode; }
/// Auto-Format mode.
inline void setAutoFormat( const bool autoFormat ) { mAutoFormat = autoFormat; }
inline bool getAutoFormat( void ) const { return mAutoFormat; }
/// Write defaults.
inline void setWriteDefaults( const bool writeDefaults ) { mWriteDefaults = writeDefaults; }
inline bool getWriteDefaults( void ) const { return mWriteDefaults; }
/// Progenitor.
inline void setProgenitorUpdate( const bool progenitorUpdate ) { mProgenitorUpdate = progenitorUpdate; }
inline bool getProgenitorUpdate( void ) const { return mProgenitorUpdate; }
/// Auto-format extensions.
inline void setAutoFormatXmlExtension( const char* pExtension ) { mAutoFormatXmlExtension = StringTable->insert( pExtension ); }
inline StringTableEntry getAutoFormatXmlExtension( void ) const { return mAutoFormatXmlExtension; }
inline void setAutoFormatBinaryExtension( const char* pExtension ) { mAutoFormatBinaryExtension = StringTable->insert( pExtension ); }
inline StringTableEntry getAutoFormatBinaryExtension( void ) const { return mAutoFormatBinaryExtension; }
/// Compression.
inline void setBinaryCompression( const bool compressed ) { mBinaryCompression = compressed; }
inline bool getBinaryCompression( void ) const { return mBinaryCompression; }
/// JSON Strict RFC4627 mode.
inline void setJSONStrict( const bool jsonStrict ) { mJSONStrict = jsonStrict; }
inline bool getJSONStrict( void ) const { return mJSONStrict; }
TamlFormatMode getFileAutoFormatMode( const char* pFilename );
const char* getFilePathBuffer( void ) const { return mFilePathBuffer; }
/// Write.
bool write( SimObject* pSimObject, const char* pFilename );
/// Read.
template<typename T> inline T* read( const char* pFilename )
{
SimObject* pSimObject = read( pFilename );
if ( pSimObject == NULL )
return NULL;
T* pObj = dynamic_cast<T*>( pSimObject );
if ( pObj != NULL )
return pObj;
pSimObject->deleteObject();
return NULL;
}
SimObject* read( const char* pFilename );
/// Parse.
bool parse( const char* pFilename, TamlVisitor& visitor );
/// Create type.
static SimObject* createType( StringTableEntry typeName, const Taml* pTaml, const char* pProgenitorSuffix = NULL );
/// Schema generation.
static bool generateTamlSchema();
/// Write a unrestricted custom Taml schema.
static void WriteUnrestrictedCustomTamlSchema( const char* pCustomNodeName, const AbstractClassRep* pClassRep, TiXmlElement* pParentElement );
/// Get format mode info.
static TamlFormatMode getFormatModeEnum( const char* label );
static const char* getFormatModeDescription( const TamlFormatMode formatMode );
/// Taml callbacks.
inline void tamlPreWrite( TamlCallbacks* pCallbacks ) { pCallbacks->onTamlPreWrite(); }
inline void tamlPostWrite( TamlCallbacks* pCallbacks ) { pCallbacks->onTamlPostWrite(); }
inline void tamlPreRead( TamlCallbacks* pCallbacks ) { pCallbacks->onTamlPreRead(); }
inline void tamlPostRead( TamlCallbacks* pCallbacks, const TamlCustomNodes& customNodes ) { pCallbacks->onTamlPostRead( customNodes ); }
inline void tamlAddParent( TamlCallbacks* pCallbacks, SimObject* pParentObject ) { pCallbacks->onTamlAddParent( pParentObject ); }
inline void tamlCustomWrite( TamlCallbacks* pCallbacks, TamlCustomNodes& customNodes ) { pCallbacks->onTamlCustomWrite( customNodes ); }
inline void tamlCustomRead( TamlCallbacks* pCallbacks, const TamlCustomNodes& customNodes ) { pCallbacks->onTamlCustomRead( customNodes ); }
/// Declare Console Object.
DECLARE_CONOBJECT( Taml );
};
#endif // _TAML_H_

View file

@ -0,0 +1,61 @@
//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _TAML_CALLBACKS_H_
#define _TAML_CALLBACKS_H_
//-----------------------------------------------------------------------------
class TamlCustomNodes;
class SimObject;
//-----------------------------------------------------------------------------
class TamlCallbacks
{
friend class Taml;
private:
/// Called prior to Taml writing the object.
virtual void onTamlPreWrite( void ) = 0;
/// Called after Taml has finished writing the object.
virtual void onTamlPostWrite( void ) = 0;
/// Called prior to Taml reading the object.
virtual void onTamlPreRead( void ) = 0;
/// Called after Taml has finished reading the object.
/// The custom properties is additionally passed here for object who want to process it at the end of reading.
virtual void onTamlPostRead( const TamlCustomNodes& customNodes ) = 0;
/// Called after Taml has finished reading the object and has added the object to any parent.
virtual void onTamlAddParent( SimObject* pParentObject ) = 0;
/// Called during the writing of the object to allow custom properties to be written.
virtual void onTamlCustomWrite( TamlCustomNodes& customNodes ) = 0;
/// Called during the reading of the object to allow custom properties to be read.
virtual void onTamlCustomRead( const TamlCustomNodes& customNodes ) = 0;
};
#endif // _TAML_CALLBACKS_H_

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