Torque3D/Engine/source/T3D/assets/ShapeAsset.cpp
JeffR c96d58ae34 - Updates the material and terrain material assets to utilize AssetRef and drop the old macros like how Image and ShapeAssets have been updated.
- Updates the various classes using materials to comply to the change.
- Also standardizes some getter names to follow the general convention image and shape used to keep things more consistent across the board to minimize usage friction.
- Shifts handling of fallback asset lookups for the thus-far converted classes to have them be loaded during core initialization rather than being loaded as part of other asset loading as that sometimes lead to nesting execution/stability errors. Explicit call now ensures the fallbacks are loaded before any other asset tries to load, so there's no room for confounding or having no fallback to work with.
2026-07-03 23:38:43 -05:00

1224 lines
37 KiB
C++

//-----------------------------------------------------------------------------
// 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"
#include "T3D/assets/assetImporter.h"
#ifdef TORQUE_TOOLS
#include "ts/tsLastDetail.h"
#endif
#include "util/imposterCapture.h"
#include "ts/tsShapeInstance.h"
#include "gfx/bitmap/imageUtils.h"
StringTableEntry ShapeAsset::smNoShapeAssetFallback = NULL;
AssetPtr<ShapeAsset> ShapeAsset::smNoShapeAssetFallbackAssetPtr = NULL;
//-----------------------------------------------------------------------------
IMPLEMENT_CONOBJECT(ShapeAsset);
IMPLEMENT_STRUCT(AssetPtr<ShapeAsset>, AssetPtrShapeAsset, , "")
END_IMPLEMENT_STRUCT
ConsoleType(ShapeAssetPtr, TypeShapeAssetPtr, AssetPtr<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)
{
Con::warnf("(TypeShapeAssetPtr) - Failed to set asset Id '%d'.", pFieldValue);
return;
}
// Set asset.
pAssetPtr->setAssetId(pFieldValue);
return;
}
// Warn.
Con::warnf("(TypeShapeAssetPtr) - Cannot set multiple args to a single asset.");
}
//-----------------------------------------------------------------------------
ConsoleType(assetIdString, TypeShapeAssetId, const char*, ASSET_ID_FIELD_PREFIX)
ConsoleGetType(TypeShapeAssetId)
{
// Fetch asset Id.
return *((const char**)(dptr));
}
ConsoleSetType(TypeShapeAssetId)
{
// Was a single argument specified?
if (argc == 1)
{
// Yes, so fetch field value.
*((const char**)dptr) = StringTable->insert(argv[0]);
return;
}
// Warn.
Con::warnf("(TypeAssetId) - Cannot set multiple args to a single asset.");
}
//-----------------------------------------------------------------------------
IMPLEMENT_STRUCT(AssetRef<ShapeAsset>, AssetRefShapeAsset, , "")
END_IMPLEMENT_STRUCT
ConsoleType(ShapeAssetRef, TypeShapeAssetRef, AssetRef<ShapeAsset>, ASSET_ID_FIELD_PREFIX)
ConsoleGetType(TypeShapeAssetRef)
{
AssetRef<ShapeAsset>& ref = *((AssetRef<ShapeAsset>*)dptr);
if (ref.assetPtr.isNull())
return ref.assetId;
else
return ref.assetPtr.getAssetId();
}
ConsoleSetType(TypeShapeAssetRef)
{
// Was a single argument specified?
if (argc == 1)
{
// Yes, so fetch field value.
const char* pFieldValue = argv[0];
// Fetch asset pointer.
AssetRef<ShapeAsset>* pAssetRef = (AssetRef<ShapeAsset>*)(dptr);
// Is the asset pointer the correct type?
if (pAssetRef == NULL)
{
Con::warnf("(TypeShapeAssetRef) - Failed to set asset Id '%d'.", pFieldValue);
return;
}
// Set asset.
*pAssetRef = pFieldValue;
return;
}
// Warn.
Con::warnf("(TypeShapeAssetRef) - Cannot set multiple args to a single asset.");
}
const String ShapeAsset::mErrCodeStrings[] =
{
"TooManyVerts",
"TooManyBones",
"MissingAnimatons",
"UnKnown"
};
//-----------------------------------------------------------------------------
ShapeAsset::ShapeAsset()
{
mShapeFile = StringTable->EmptyString();
mConstructorFileName = StringTable->EmptyString();
mDiffuseImposterFileName = StringTable->EmptyString();
mNormalImposterFileName = StringTable->EmptyString();
mLoadedState = AssetErrCode::NotLoaded;
}
//-----------------------------------------------------------------------------
ShapeAsset::~ShapeAsset()
{
}
//-----------------------------------------------------------------------------
void ShapeAsset::consoleInit()
{
Parent::consoleInit();
Con::addVariable("$Core::NoShapeAssetFallback", TypeString, &smNoShapeAssetFallback,
"The assetId of the shape to display when the requested shape asset is missing.\n"
"@ingroup GFX\n");
smNoShapeAssetFallback = StringTable->insert(Con::getVariable("$Core::NoShapeAssetFallback"));
}
//-----------------------------------------------------------------------------
void ShapeAsset::initPersistFields()
{
docsURL;
// Call parent.
Parent::initPersistFields();
addProtectedField("fileName", TypeAssetLooseFilePath, Offset(mShapeFile, ShapeAsset),
&setShapeFile, &getShapeFile, "Path to the shape file we want to render");
addProtectedField("constuctorFileName", TypeAssetLooseFilePath, Offset(mConstructorFileName, ShapeAsset),
&setShapeConstructorFile, &getShapeConstructorFile, "Path to the shape file we want to render");
addProtectedField("diffuseImposterFileName", TypeAssetLooseFilePath, Offset(mDiffuseImposterFileName, ShapeAsset),
&setDiffuseImposterFile, &getDiffuseImposterFile, "Path to the diffuse imposter file we want to render");
addProtectedField("normalImposterFileName", TypeAssetLooseFilePath, Offset(mNormalImposterFileName, ShapeAsset),
&setNormalImposterFile, &getNormalImposterFile, "Path to the normal imposter file we want to render");
}
void ShapeAsset::initializeAsset()
{
// Call parent.
Parent::initializeAsset();
if (mShapeFile == StringTable->EmptyString())
return;
ResourceManager::get().getChangedSignal().notify(this, &ShapeAsset::_onResourceChanged);
//Ensure our path is expando'd if it isn't already
mShapeFile = getOwned() ? expandAssetFilePath(mShapeFile) : mShapeFile;
mConstructorFileName = getOwned() ? expandAssetFilePath(mConstructorFileName) : mConstructorFileName;
if (!Torque::FS::IsFile(mConstructorFileName))
Con::errorf("ShapeAsset::initializeAsset (%s) could not find %s!", getAssetName(), mConstructorFileName);
mDiffuseImposterFileName = getOwned() ? expandAssetFilePath(mDiffuseImposterFileName) : mDiffuseImposterFileName;
if (mDiffuseImposterFileName == StringTable->EmptyString())
{
String diffusePath = String(mShapeFile) + "_imposter.dds";
mDiffuseImposterFileName = StringTable->insert(diffusePath.c_str());
}
mNormalImposterFileName = getOwned() ? expandAssetFilePath(mNormalImposterFileName) : mNormalImposterFileName;
if (mNormalImposterFileName == StringTable->EmptyString())
{
String normalPath = String(mShapeFile) + "_imposter_normals.dds";
mNormalImposterFileName = StringTable->insert(normalPath.c_str());
}
}
void ShapeAsset::setShapeFile(const char* pShapeFile)
{
// Sanity!
AssertFatal(pShapeFile != NULL, "Cannot use a NULL shape file.");
// Fetch image file.
pShapeFile = StringTable->insert(pShapeFile, true);
// Ignore no change,
if (pShapeFile == mShapeFile)
return;
mShapeFile = getOwned() ? expandAssetFilePath(pShapeFile) : pShapeFile;
// Refresh the asset.
refreshAsset();
}
void ShapeAsset::setShapeConstructorFile(const char* pShapeConstructorFile)
{
// Sanity!
AssertFatal(pShapeConstructorFile != NULL, "Cannot use a NULL shape constructor file.");
// Fetch image file.
pShapeConstructorFile = StringTable->insert(pShapeConstructorFile, true);
// Ignore no change,
if (pShapeConstructorFile == mConstructorFileName)
return;
mConstructorFileName = getOwned() ? expandAssetFilePath(pShapeConstructorFile) : pShapeConstructorFile;
// Refresh the asset.
refreshAsset();
}
void ShapeAsset::setDiffuseImposterFile(const char* pImageFile)
{
// Sanity!
AssertFatal(pImageFile != NULL, "Cannot use a NULL image file.");
// Fetch image file.
pImageFile = StringTable->insert(pImageFile, true);
// Ignore no change,
if (pImageFile == mDiffuseImposterFileName)
return;
mDiffuseImposterFileName = getOwned() ? expandAssetFilePath(pImageFile) : pImageFile;
// Refresh the asset.
refreshAsset();
}
void ShapeAsset::setNormalImposterFile(const char* pImageFile)
{
// Sanity!
AssertFatal(pImageFile != NULL, "Cannot use a NULL image file.");
// Fetch image file.
pImageFile = StringTable->insert(pImageFile, true);
// Ignore no change,
if (pImageFile == mNormalImposterFileName)
return;
mNormalImposterFileName = getOwned() ? expandAssetFilePath(pImageFile) : pImageFile;
// Refresh the asset.
refreshAsset();
}
void ShapeAsset::_onResourceChanged(const Torque::Path& path)
{
if (path != Torque::Path(mShapeFile))
return;
refreshAsset();
}
U32 ShapeAsset::load()
{
if (mLoadedState == AssetErrCode::Ok) return mLoadedState;
mShape = ResourceManager::get().load(mShapeFile);
if (!mShape)
{
mLoadedState = BadFileReference;
return mLoadedState; //if it failed to load, bail out
}
// Construct billboards if not done already
if (GFXDevice::devicePresent())
mShape->setupBillboardDetails(mShapeFile, mDiffuseImposterFileName, mNormalImposterFileName);
mLoadedState = Ok;
return mLoadedState;
}
bool ShapeAsset::preloadMaterialList()
{
if (!mShape)
return false;
return mShape->preloadMaterialList(getShapeFile());
}
TSShape* ShapeAsset::getShape()
{
AssetErrCode result = static_cast<AssetErrCode>(load());
if (mShape)
{
return mShape;
}
else if (smNoShapeAssetFallbackAssetPtr.notNull())
{
return smNoShapeAssetFallbackAssetPtr->getShape();
}
return NULL;
}
Resource<TSShape> ShapeAsset::getShapeResource()
{
AssetErrCode result = static_cast<AssetErrCode>(load());
if (mShape)
{
return mShape;
}
else if (smNoShapeAssetFallbackAssetPtr.notNull())
{
return smNoShapeAssetFallbackAssetPtr->getShapeResource();
}
return Resource<TSShape>(NULL);
}
//------------------------------------------------------------------------------
//Utility function to 'fill out' bindings and resources with a matching asset if one exists
U32 ShapeAsset::getAssetByFilename(StringTableEntry fileName, AssetPtr<ShapeAsset>* shapeAsset)
{
AssetQuery query;
S32 foundAssetcount = AssetDatabase.findAssetLooseFile(&query, fileName);
if (foundAssetcount == 0)
{
//Didn't work, so have us fall back to a placeholder asset
shapeAsset->setAssetId(ShapeAsset::smNoShapeAssetFallback);
if (shapeAsset->isNull())
{
//Well that's bad, loading the fallback failed.
Con::warnf("ShapeAsset::getAssetByFilename - Finding of asset associated with file %s failed with no fallback asset", fileName);
return AssetErrCode::Failed;
}
//handle noshape not being loaded itself
if ((*shapeAsset)->mLoadedState == BadFileReference)
{
Con::warnf("ShapeAsset::getAssetByFilename - Finding of associated with file %s failed, and fallback asset reported error of Bad File Reference.", fileName);
return AssetErrCode::BadFileReference;
}
Con::warnf("ShapeAsset::getAssetByFilename - Finding of associated with file %s failed, utilizing fallback asset", fileName);
(*shapeAsset)->mLoadedState = AssetErrCode::UsingFallback;
return AssetErrCode::UsingFallback;
}
else
{
//acquire and bind the asset, and return it out
shapeAsset->setAssetId(query.mAssetList[0]);
return (*shapeAsset)->mLoadedState;
}
}
StringTableEntry ShapeAsset::getAssetIdByFilename(StringTableEntry fileName)
{
if (fileName == StringTable->EmptyString())
return StringTable->EmptyString();
StringTableEntry shapeAssetId = ShapeAsset::smNoShapeAssetFallback;
AssetQuery query;
S32 foundAssetcount = AssetDatabase.findAssetLooseFile(&query, fileName);
if (foundAssetcount != 0)
{
//acquire and bind the asset, and return it out
shapeAssetId = query.mAssetList[0];
}
else
{
foundAssetcount = AssetDatabase.findAssetType(&query, "ShapeAsset");
if (foundAssetcount != 0)
{
// loop all image assets and see if we can find one
// using the same image file/named target.
for (auto shapeAsset : query.mAssetList)
{
AssetPtr<ShapeAsset> temp = shapeAsset;
if (temp.notNull())
{
if (temp->getShapeFile() == fileName)
{
return shapeAsset;
}
else
{
Torque::Path temp1 = temp->getShapeFile();
Torque::Path temp2 = fileName;
if (temp1.getPath() == temp2.getPath() && temp1.getFileName() == temp2.getFileName())
{
return shapeAsset;
}
}
}
}
}
else
{
AssetPtr<ShapeAsset> shapeAsset = shapeAssetId; //ensures the fallback is loaded
}
}
return shapeAssetId;
}
U32 ShapeAsset::getAssetById(StringTableEntry assetId, AssetPtr<ShapeAsset>* shapeAsset)
{
(*shapeAsset) = assetId;
if (shapeAsset->notNull())
{
return (*shapeAsset)->mLoadedState;
}
else
{
//Didn't work, so have us fall back to a placeholder asset
shapeAsset->setAssetId(ShapeAsset::smNoShapeAssetFallback);
if (shapeAsset->isNull())
{
//Well that's bad, loading the fallback failed.
Con::warnf("ShapeAsset::getAssetById - Finding of asset with id %s failed with no fallback asset", assetId);
return AssetErrCode::Failed;
}
//handle noshape not being loaded itself
if ((*shapeAsset)->mLoadedState == BadFileReference)
{
Con::warnf("ShapeAsset::getAssetById - Finding of asset with id %s failed, and fallback asset reported error of Bad File Reference.", assetId);
return AssetErrCode::BadFileReference;
}
Con::warnf("ShapeAsset::getAssetById - Finding of asset with id %s failed, utilizing fallback asset", assetId);
(*shapeAsset)->mLoadedState = AssetErrCode::UsingFallback;
return AssetErrCode::UsingFallback;
}
}
StringTableEntry ShapeAsset::getMaterial(const S32& index)
{
if (!mShape)
return StringTable->EmptyString();
if (index < 0 || index >= mShape->materialList->size())
return StringTable->EmptyString();
return mShape->materialList->getMaterialName(index);
}
U32 ShapeAsset::getMaterialCount()
{
if (!mShape)
return 0;
return mShape->materialList->size();
}
StringTableEntry ShapeAsset::getAnimation(const S32& index)
{
if (!mShape)
return StringTable->EmptyString();
if (index < 0 || index >= mShape->sequences.size())
return StringTable->EmptyString();
return mShape->getName(mShape->sequences[index].nameIndex);
}
U32 ShapeAsset::getAnimationCount()
{
if (!mShape)
return 0;
return mShape->sequences.size();
}
//------------------------------------------------------------------------------
void ShapeAsset::copyTo(SimObject* object)
{
// Call to parent.
Parent::copyTo(object);
}
void ShapeAsset::onAssetRefresh(void)
{
// Ignore if not yet added to the sim.
if (!isProperlyAdded())
return;
if (mShapeFile == StringTable->EmptyString())
return;
// Call parent.
Parent::onAssetRefresh();
load();
}
void ShapeAsset::onTamlPreWrite(void)
{
// Call parent.
Parent::onTamlPreWrite();
// ensure paths are collapsed.
mShapeFile = collapseAssetFilePath(mShapeFile);
mConstructorFileName = collapseAssetFilePath(mConstructorFileName);
mDiffuseImposterFileName = collapseAssetFilePath(mDiffuseImposterFileName);
mNormalImposterFileName = collapseAssetFilePath(mNormalImposterFileName);
}
void ShapeAsset::onTamlPostWrite(void)
{
// Call parent.
Parent::onTamlPostWrite();
// ensure paths are expanded.
mShapeFile = expandAssetFilePath(mShapeFile);
mConstructorFileName = expandAssetFilePath(mConstructorFileName);
mDiffuseImposterFileName = expandAssetFilePath(mDiffuseImposterFileName);
mNormalImposterFileName = expandAssetFilePath(mNormalImposterFileName);
}
void ShapeAsset::onTamlCustomWrite(TamlCustomNodes& customNodes)
{
// Debug Profiling.
PROFILE_SCOPE(ShapeAsset_OnTamlCustomWrite);
// Call parent.
Parent::onTamlCustomWrite(customNodes);
if (!mShape)
return;
TamlCustomNode* materialsData = customNodes.addNode(StringTable->insert("Materials"));
U32 matCount = mShape->materialList->size();
Vector<String>& mat_names = const_cast<Vector<String>&>(mShape->materialList->getMaterialNameList());
for (U32 i=0; i < mat_names.size(); i++)
{
StringTableEntry matAssetId = MaterialAsset::getAssetIdByMaterialName(StringTable->insert(mat_names[i].c_str()));
if (matAssetId != StringTable->EmptyString())
{
String fieldName = String::ToString("materialSlot%d", i);
String fieldData = String::ToString("%s%s", ASSET_ID_FIELD_PREFIX, matAssetId);
materialsData->addField(fieldName.c_str(), matAssetId);
}
}
}
#ifdef TORQUE_TOOLS
const char* ShapeAsset::generateCachedPreviewImage(S32 resolution, String overrideMaterial)
{
if (!mShape)
return "";
// We're gonna render... make sure we can.
bool sceneBegun = GFX->canCurrentlyRender();
if (!sceneBegun)
GFX->beginScene();
// We need to create our own instance to render with.
TSShapeInstance* shape = new TSShapeInstance(mShape, true);
if (overrideMaterial.isNotEmpty())
{
Material* tMat = dynamic_cast<Material*>(Sim::findObject(overrideMaterial));
if (tMat)
shape->reSkin(tMat->mMapTo, mShape->materialList->getMaterialName(0));
}
// Animate the shape once.
shape->animate(0);
GBitmap* imposter = NULL;
GBitmap* imposterNrml = NULL;
ImposterCapture* imposterCap = new ImposterCapture();
static const MatrixF topXfm(EulerF(-M_PI_F / 2.0f, 0, 0));
static const MatrixF bottomXfm(EulerF(M_PI_F / 2.0f, 0, 0));
MatrixF angMat;
PROFILE_START(ShapeAsset_generateCachedPreviewImage);
//dMemset(destBmp.getWritableBits(mip), 0, destBmp.getWidth(mip) * destBmp.getHeight(mip) * GFXFormat_getByteSize(format));
F32 rotX = -(mDegToRad(60.0) - 0.5f * M_PI_F);
F32 rotZ = -(mDegToRad(45.0) - 0.5f * M_PI_F);
// We capture the images in a particular order which must
// match the order expected by the imposter renderer.
imposterCap->begin(shape, 0, resolution, mShape->mRadius, mShape->center);
angMat.mul(MatrixF(EulerF(rotX, 0, 0)),
MatrixF(EulerF(0, 0, rotZ)));
imposterCap->capture(angMat, &imposter, &imposterNrml);
imposterCap->end();
PROFILE_END(); // ShapeAsset_generateCachedPreviewImage
delete imposterCap;
delete shape;
String dumpPath = String(mShapeFile) + ".png";
char* returnBuffer = Con::getReturnBuffer(128);
dSprintf(returnBuffer, 128, "%s", dumpPath.c_str());
imposter->writeBitmap("png", dumpPath);
delete imposter;
delete imposterNrml;
// If we did a begin then end it now.
if (!sceneBegun)
GFX->endScene();
return returnBuffer;
}
#endif
DefineEngineMethod(ShapeAsset, getMaterial, const char*, (S32 index), (0),
"Gets the number of materials for this shape asset.\n"
"@return Material count.\n")
{
return object->getMaterial(index);
}
DefineEngineMethod(ShapeAsset, getMaterialCount, S32, (), ,
"Gets the number of materials for this shape asset.\n"
"@return Material count.\n")
{
return object->getMaterialCount();
}
DefineEngineMethod(ShapeAsset, getAnimation, const char*, (S32 index), (0),
"Gets a particular shape animation asset for this shape.\n"
"@param animation asset index.\n"
"@return Shape Animation Asset.\n")
{
return object->getAnimation(index);
}
DefineEngineMethod(ShapeAsset, getAnimationCount, S32, (), ,
"Gets the number of animations for this shape asset.\n"
"@return Animation count.\n")
{
return object->getAnimationCount();
}
DefineEngineMethod(ShapeAsset, getShapePath, const char*, (), ,
"Gets the shape's file path\n"
"@return The filename of the shape file")
{
return object->getShapeFile();
}
DefineEngineMethod(ShapeAsset, getShapeConstructorFilePath, const char*, (), ,
"Gets the shape's constructor file.\n"
"@return The filename of the shape constructor file")
{
return object->getShapeConstructorFile();
}
DefineEngineMethod(ShapeAsset, getStatusString, String, (), , "get status string")\
{
return ShapeAsset::getAssetErrstrn(object->getStatus());
}
DefineEngineFunction(loadShapeAssetFallback, S32, (), ,
"Forces the loading of the ShapeAsset fallback asset.\n"
"@return Load status code.")
{
if (ShapeAsset::smNoShapeAssetFallbackAssetPtr.isNull())
{
ShapeAsset::smNoShapeAssetFallbackAssetPtr = ShapeAsset::smNoShapeAssetFallback;
if (ShapeAsset::smNoShapeAssetFallbackAssetPtr.isNull())
Con::errorf("loadShapeAssetFallback could not find fallback asset %s!", ShapeAsset::smNoShapeAssetFallback);
else
return (S32)ShapeAsset::smNoShapeAssetFallbackAssetPtr->load();
}
else
{
return (S32)ShapeAsset::smNoShapeAssetFallbackAssetPtr->getStatus();
}
return AssetBase::Failed;
}
#ifdef TORQUE_TOOLS
DefineEngineMethod(ShapeAsset, generateCachedPreviewImage, const char*, (S32 resolution, const char* overrideMaterialName), (256, ""),
"Generates a baked preview image of the given shapeAsset. Only really used for generating Asset Browser icons.\n"
"@param resolution Optional field for what resolution to bake the preview image at. Must be pow2\n"
"@param overrideMaterialName Optional field for overriding the material used when rendering the shape for the bake.")
{
object->load();
return object->generateCachedPreviewImage(resolution, overrideMaterialName);
}
DefineEngineStaticMethod(ShapeAsset, getAssetIdByFilename, const char*, (const char* filePath), (""),
"Queries the Asset Database to see if any asset exists that is associated with the provided file path.\n"
"@return The AssetId of the associated asset, if any.")
{
return ShapeAsset::getAssetIdByFilename(StringTable->insert(filePath));
}
#endif
#ifdef TORQUE_TOOLS
//-----------------------------------------------------------------------------
// GuiInspectorTypeAssetId
//-----------------------------------------------------------------------------
IMPLEMENT_CONOBJECT(GuiInspectorTypeShapeAssetPtr);
ConsoleDocClass(GuiInspectorTypeShapeAssetPtr,
"@brief Inspector field type for Shapes\n\n"
"Editor use only.\n\n"
"@internal"
);
void GuiInspectorTypeShapeAssetPtr::consoleInit()
{
Parent::consoleInit();
ConsoleBaseType::getType(TypeShapeAssetPtr)->setInspectorFieldType("GuiInspectorTypeShapeAssetPtr");
}
GuiControl* GuiInspectorTypeShapeAssetPtr::constructEditControl()
{
// Create base filename edit controls
GuiControl* retCtrl = Parent::constructEditControl();
if (retCtrl == NULL)
return retCtrl;
// Change filespec
char szBuffer[512];
const char* previewImage;
if (mInspector->getInspectObject() != NULL)
{
StringBuilder varNameStr;
varNameStr.append(mCaption);
if (mFieldArrayIndex != NULL)
{
varNameStr.append("[");
varNameStr.append(mFieldArrayIndex);
varNameStr.append("]");
}
dSprintf(szBuffer, sizeof(szBuffer), "AssetBrowser.showDialog(\"ShapeAsset\", \"AssetBrowser.changeAsset\", %s, \"%s\");",
mInspector->getIdString(), varNameStr.end().c_str());
mBrowseButton->setField("Command", szBuffer);
setDataField(StringTable->insert("targetObject"), NULL, mInspector->getInspectObject()->getIdString());
previewImage = mInspector->getInspectObject()->getDataField(varNameStr.end().c_str(), NULL);
}
else
{
//if we don't have a target object, we'll be manipulating the desination value directly
dSprintf(szBuffer, sizeof(szBuffer), "AssetBrowser.showDialog(\"ShapeAsset\", \"AssetBrowser.changeAsset\", %s, \"%s\");",
mInspector->getIdString(), mVariableName);
mBrowseButton->setField("Command", szBuffer);
previewImage = Con::getVariable(mVariableName);
}
mLabel = new GuiTextCtrl();
mLabel->registerObject();
mLabel->setControlProfile(mProfile);
mLabel->setText(mCaption);
addObject(mLabel);
//
GuiTextEditCtrl* editTextCtrl = static_cast<GuiTextEditCtrl*>(retCtrl);
GuiControlProfile* toolEditProfile;
if (Sim::findObject("ToolsGuiTextEditProfile", toolEditProfile))
editTextCtrl->setControlProfile(toolEditProfile);
GuiControlProfile* toolDefaultProfile = NULL;
Sim::findObject("ToolsGuiDefaultProfile", toolDefaultProfile);
//
mPreviewImage = new GuiBitmapCtrl();
mPreviewImage->registerObject();
if (toolDefaultProfile)
mPreviewImage->setControlProfile(toolDefaultProfile);
updatePreviewImage();
addObject(mPreviewImage);
//
mPreviewBorderButton = new GuiBitmapButtonCtrl();
mPreviewBorderButton->registerObject();
if (toolDefaultProfile)
mPreviewBorderButton->setControlProfile(toolDefaultProfile);
mPreviewBorderButton->_setBitmap(StringTable->insert("ToolsModule:cubemapBtnBorder_n_image"));
mPreviewBorderButton->setField("Command", szBuffer); //clicking the preview does the same thing as the edit button, for simplicity
addObject(mPreviewBorderButton);
//
// Create "Open in Editor" button
mEditButton = new GuiBitmapButtonCtrl();
dSprintf(szBuffer, sizeof(szBuffer), "ShapeEditorPlugin.openShapeAssetId(%d.getText());", retCtrl->getId());
mEditButton->setField("Command", szBuffer);
mEditButton->setText("Edit");
mEditButton->setSizing(horizResizeLeft, vertResizeAspectTop);
mEditButton->setDataField(StringTable->insert("Profile"), NULL, "ToolsGuiButtonProfile");
mEditButton->setDataField(StringTable->insert("tooltipprofile"), NULL, "GuiToolTipProfile");
mEditButton->setDataField(StringTable->insert("hovertime"), NULL, "1000");
mEditButton->setDataField(StringTable->insert("tooltip"), NULL, "Open this asset in the Shape Editor");
mEditButton->registerObject();
addObject(mEditButton);
//
mUseHeightOverride = true;
mHeightOverride = 72;
return retCtrl;
}
bool GuiInspectorTypeShapeAssetPtr::updateRects()
{
S32 rowSize = 18;
S32 dividerPos, dividerMargin;
mInspector->getDivider(dividerPos, dividerMargin);
Point2I fieldExtent = getExtent();
Point2I fieldPos = getPosition();
mEditCtrlRect.set(0, 0, fieldExtent.x, fieldExtent.y);
mLabel->resize(Point2I(mProfile->mTextOffset.x, 0), Point2I(fieldExtent.x, rowSize));
RectI previewRect = RectI(Point2I(mProfile->mTextOffset.x, rowSize), Point2I(50, 50));
mPreviewBorderButton->resize(previewRect.point, previewRect.extent);
mPreviewImage->resize(previewRect.point, previewRect.extent);
S32 editPos = previewRect.point.x + previewRect.extent.x + 10;
mEdit->resize(Point2I(editPos, rowSize * 1.5), Point2I(fieldExtent.x - editPos - 5, rowSize));
mEditButton->resize(Point2I(fieldExtent.x - 105, previewRect.point.y + previewRect.extent.y - rowSize), Point2I(100, rowSize));
mBrowseButton->setHidden(true);
return true;
}
void GuiInspectorTypeShapeAssetPtr::updateValue()
{
Parent::updateValue();
updatePreviewImage();
}
void GuiInspectorTypeShapeAssetPtr::updatePreviewImage()
{
const char* previewImage;
if (mInspector->getInspectObject() != NULL)
previewImage = mInspector->getInspectObject()->getDataField(mCaption, NULL);
else
previewImage = Con::getVariable(mVariableName);
//if what we're working with isn't even a valid asset, don't present like we found a good one
if (!AssetDatabase.isDeclaredAsset(previewImage))
{
mPreviewImage->setBitmap(StringTable->EmptyString());
return;
}
String shpPreviewAssetId = String(previewImage) + "_PreviewImage";
shpPreviewAssetId.replace(":", "_");
shpPreviewAssetId = "ToolsModule:" + shpPreviewAssetId;
if (AssetDatabase.isDeclaredAsset(shpPreviewAssetId.c_str()))
{
mPreviewImage->setBitmap(StringTable->insert(shpPreviewAssetId.c_str()));
}
if (mPreviewImage->getBitmapAsset().isNull())
mPreviewImage->setBitmap(StringTable->insert("ToolsModule:genericAssetIcon_image"));
}
void GuiInspectorTypeShapeAssetPtr::setPreviewImage(StringTableEntry assetId)
{
//if what we're working with isn't even a valid asset, don't present like we found a good one
if (!AssetDatabase.isDeclaredAsset(assetId))
{
mPreviewImage->setBitmap(StringTable->EmptyString());
return;
}
String shpPreviewAssetId = String(assetId) + "_PreviewImage";
shpPreviewAssetId.replace(":", "_");
shpPreviewAssetId = "ToolsModule:" + shpPreviewAssetId;
if (AssetDatabase.isDeclaredAsset(shpPreviewAssetId.c_str()))
{
mPreviewImage->setBitmap(StringTable->insert(shpPreviewAssetId.c_str()));
}
if (mPreviewImage->getBitmapAsset().isNull())
mPreviewImage->setBitmap(StringTable->insert("ToolsModule:genericAssetIcon_image"));
}
IMPLEMENT_CONOBJECT(GuiInspectorTypeShapeAssetId);
ConsoleDocClass(GuiInspectorTypeShapeAssetId,
"@brief Inspector field type for Shapes\n\n"
"Editor use only.\n\n"
"@internal"
);
void GuiInspectorTypeShapeAssetId::consoleInit()
{
Parent::consoleInit();
ConsoleBaseType::getType(TypeShapeAssetId)->setInspectorFieldType("GuiInspectorTypeShapeAssetId");
}
//-----------------------------------------------------------------------------
IMPLEMENT_CONOBJECT(GuiInspectorTypeShapeAssetRef);
ConsoleDocClass(GuiInspectorTypeShapeAssetRef,
"@brief Inspector field type for Shapes\n\n"
"Editor use only.\n\n"
"@internal"
);
void GuiInspectorTypeShapeAssetRef::consoleInit()
{
Parent::consoleInit();
ConsoleBaseType::getType(TypeShapeAssetRef)->setInspectorFieldType("GuiInspectorTypeShapeAssetRef");
}
GuiControl* GuiInspectorTypeShapeAssetRef::constructEditControl()
{
// Create base filename edit controls
GuiControl* retCtrl = Parent::constructEditControl();
if (retCtrl == NULL)
return retCtrl;
// Change filespec
char szBuffer[512];
const char* previewImage;
if (mInspector->getInspectObject() != NULL)
{
StringBuilder varNameStr;
varNameStr.append(mCaption);
if (mFieldArrayIndex != NULL)
{
varNameStr.append("[");
varNameStr.append(mFieldArrayIndex);
varNameStr.append("]");
}
dSprintf(szBuffer, sizeof(szBuffer), "AssetBrowser.showDialog(\"ShapeAsset\", \"AssetBrowser.changeAsset\", %s, \"%s\");",
mInspector->getIdString(), varNameStr.end().c_str());
mBrowseButton->setField("Command", szBuffer);
setDataField(StringTable->insert("targetObject"), NULL, mInspector->getInspectObject()->getIdString());
previewImage = mInspector->getInspectObject()->getDataField(varNameStr.end().c_str(), NULL);
}
else
{
//if we don't have a target object, we'll be manipulating the desination value directly
dSprintf(szBuffer, sizeof(szBuffer), "AssetBrowser.showDialog(\"ShapeAsset\", \"AssetBrowser.changeAsset\", %s, \"%s\");",
mInspector->getIdString(), mVariableName);
mBrowseButton->setField("Command", szBuffer);
previewImage = Con::getVariable(mVariableName);
}
mLabel = new GuiTextCtrl();
mLabel->registerObject();
mLabel->setControlProfile(mProfile);
mLabel->setText(mCaption);
addObject(mLabel);
//
GuiTextEditCtrl* editTextCtrl = static_cast<GuiTextEditCtrl*>(retCtrl);
GuiControlProfile* toolEditProfile;
if (Sim::findObject("ToolsGuiTextEditProfile", toolEditProfile))
editTextCtrl->setControlProfile(toolEditProfile);
GuiControlProfile* toolDefaultProfile = NULL;
Sim::findObject("ToolsGuiDefaultProfile", toolDefaultProfile);
//
mPreviewImage = new GuiBitmapCtrl();
mPreviewImage->registerObject();
if (toolDefaultProfile)
mPreviewImage->setControlProfile(toolDefaultProfile);
updatePreviewImage();
addObject(mPreviewImage);
//
mPreviewBorderButton = new GuiBitmapButtonCtrl();
mPreviewBorderButton->registerObject();
if (toolDefaultProfile)
mPreviewBorderButton->setControlProfile(toolDefaultProfile);
mPreviewBorderButton->_setBitmap(StringTable->insert("ToolsModule:cubemapBtnBorder_n_image"));
mPreviewBorderButton->setField("Command", szBuffer); //clicking the preview does the same thing as the edit button, for simplicity
addObject(mPreviewBorderButton);
//
// Create "Open in Editor" button
mEditButton = new GuiBitmapButtonCtrl();
dSprintf(szBuffer, sizeof(szBuffer), "ShapeEditorPlugin.openShapeAssetId(%d.getText());", retCtrl->getId());
mEditButton->setField("Command", szBuffer);
mEditButton->setText("Edit");
mEditButton->setSizing(horizResizeLeft, vertResizeAspectTop);
mEditButton->setDataField(StringTable->insert("Profile"), NULL, "ToolsGuiButtonProfile");
mEditButton->setDataField(StringTable->insert("tooltipprofile"), NULL, "GuiToolTipProfile");
mEditButton->setDataField(StringTable->insert("hovertime"), NULL, "1000");
mEditButton->setDataField(StringTable->insert("tooltip"), NULL, "Open this asset in the Shape Editor");
mEditButton->registerObject();
addObject(mEditButton);
//
mUseHeightOverride = true;
mHeightOverride = 72;
return retCtrl;
}
bool GuiInspectorTypeShapeAssetRef::updateRects()
{
S32 rowSize = 18;
S32 dividerPos, dividerMargin;
mInspector->getDivider(dividerPos, dividerMargin);
Point2I fieldExtent = getExtent();
Point2I fieldPos = getPosition();
mEditCtrlRect.set(0, 0, fieldExtent.x, fieldExtent.y);
mLabel->resize(Point2I(mProfile->mTextOffset.x, 0), Point2I(fieldExtent.x, rowSize));
RectI previewRect = RectI(Point2I(mProfile->mTextOffset.x, rowSize), Point2I(50, 50));
mPreviewBorderButton->resize(previewRect.point, previewRect.extent);
mPreviewImage->resize(previewRect.point, previewRect.extent);
S32 editPos = previewRect.point.x + previewRect.extent.x + 10;
mEdit->resize(Point2I(editPos, rowSize * 1.5), Point2I(fieldExtent.x - editPos - 5, rowSize));
mEditButton->resize(Point2I(fieldExtent.x - 105, previewRect.point.y + previewRect.extent.y - rowSize), Point2I(100, rowSize));
mBrowseButton->setHidden(true);
return true;
}
void GuiInspectorTypeShapeAssetRef::updateValue()
{
Parent::updateValue();
updatePreviewImage();
}
void GuiInspectorTypeShapeAssetRef::updatePreviewImage()
{
const char* previewImage;
if (mInspector->getInspectObject() != NULL)
previewImage = mInspector->getInspectObject()->getDataField(mCaption, NULL);
else
previewImage = Con::getVariable(mVariableName);
//if what we're working with isn't even a valid asset, don't present like we found a good one
if (!AssetDatabase.isDeclaredAsset(previewImage))
{
mPreviewImage->setBitmap(StringTable->EmptyString());
return;
}
String shpPreviewAssetId = String(previewImage) + "_PreviewImage";
shpPreviewAssetId.replace(":", "_");
shpPreviewAssetId = "ToolsModule:" + shpPreviewAssetId;
if (AssetDatabase.isDeclaredAsset(shpPreviewAssetId.c_str()))
{
mPreviewImage->setBitmap(StringTable->insert(shpPreviewAssetId.c_str()));
}
if (mPreviewImage->getBitmapAsset().isNull())
mPreviewImage->setBitmap(StringTable->insert("ToolsModule:genericAssetIcon_image"));
}
void GuiInspectorTypeShapeAssetRef::setPreviewImage(StringTableEntry assetId)
{
//if what we're working with isn't even a valid asset, don't present like we found a good one
if (!AssetDatabase.isDeclaredAsset(assetId))
{
mPreviewImage->setBitmap(StringTable->EmptyString());
return;
}
String shpPreviewAssetId = String(assetId) + "_PreviewImage";
shpPreviewAssetId.replace(":", "_");
shpPreviewAssetId = "ToolsModule:" + shpPreviewAssetId;
if (AssetDatabase.isDeclaredAsset(shpPreviewAssetId.c_str()))
{
mPreviewImage->setBitmap(StringTable->insert(shpPreviewAssetId.c_str()));
}
if (mPreviewImage->getBitmapAsset().isNull())
mPreviewImage->setBitmap(StringTable->insert("ToolsModule:genericAssetIcon_image"));
}
#endif