ShapeAsset.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2013 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #ifndef _SHAPE_ASSET_H_
  23. #include "ShapeAsset.h"
  24. #endif
  25. #ifndef _ASSET_MANAGER_H_
  26. #include "assets/assetManager.h"
  27. #endif
  28. #ifndef _CONSOLETYPES_H_
  29. #include "console/consoleTypes.h"
  30. #endif
  31. #ifndef _TAML_
  32. #include "persistence/taml/taml.h"
  33. #endif
  34. #ifndef _ASSET_PTR_H_
  35. #include "assets/assetPtr.h"
  36. #endif
  37. #include "core/resourceManager.h"
  38. // Debug Profiling.
  39. #include "platform/profiler.h"
  40. #include "T3D/assets/assetImporter.h"
  41. #ifdef TORQUE_TOOLS
  42. #include "ts/tsLastDetail.h"
  43. #endif
  44. #include "util/imposterCapture.h"
  45. #include "ts/tsShapeInstance.h"
  46. #include "gfx/bitmap/imageUtils.h"
  47. StringTableEntry ShapeAsset::smNoShapeAssetFallback = NULL;
  48. //-----------------------------------------------------------------------------
  49. IMPLEMENT_CONOBJECT(ShapeAsset);
  50. ConsoleType(assetIdString, TypeShapeAssetPtr, String, ASSET_ID_FIELD_PREFIX)
  51. ConsoleGetType(TypeShapeAssetPtr)
  52. {
  53. // Fetch asset Id.
  54. //return *((StringTableEntry*)dptr);
  55. return (*((AssetPtr<ShapeAsset>*)dptr)).getAssetId();
  56. }
  57. ConsoleSetType(TypeShapeAssetPtr)
  58. {
  59. // Was a single argument specified?
  60. if (argc == 1)
  61. {
  62. // Yes, so fetch field value.
  63. const char* pFieldValue = argv[0];
  64. // Fetch asset Id.
  65. StringTableEntry* assetId = (StringTableEntry*)(dptr);
  66. // Update asset value.
  67. *assetId = StringTable->insert(pFieldValue);
  68. return;
  69. }
  70. // Warn.
  71. Con::warnf("(TypeAssetId) - Cannot set multiple args to a single asset.");
  72. }
  73. //-----------------------------------------------------------------------------
  74. ConsoleType(assetIdString, TypeShapeAssetId, const char*, ASSET_ID_FIELD_PREFIX)
  75. ConsoleGetType(TypeShapeAssetId)
  76. {
  77. // Fetch asset Id.
  78. return *((const char**)(dptr));
  79. }
  80. ConsoleSetType(TypeShapeAssetId)
  81. {
  82. // Was a single argument specified?
  83. if (argc == 1)
  84. {
  85. // Yes, so fetch field value.
  86. *((const char**)dptr) = StringTable->insert(argv[0]);
  87. return;
  88. }
  89. // Warn.
  90. Con::warnf("(TypeAssetId) - Cannot set multiple args to a single asset.");
  91. }
  92. //-----------------------------------------------------------------------------
  93. const String ShapeAsset::mErrCodeStrings[] =
  94. {
  95. "TooManyVerts",
  96. "TooManyBones",
  97. "MissingAnimatons",
  98. "UnKnown"
  99. };
  100. //-----------------------------------------------------------------------------
  101. ShapeAsset::ShapeAsset()
  102. {
  103. mFileName = StringTable->EmptyString();
  104. mConstructorFileName = StringTable->EmptyString();
  105. mFilePath = StringTable->EmptyString();
  106. mConstructorFilePath = StringTable->EmptyString();
  107. mDiffuseImposterFileName = StringTable->EmptyString();
  108. mDiffuseImposterPath = StringTable->EmptyString();
  109. mNormalImposterFileName = StringTable->EmptyString();
  110. mNormalImposterPath = StringTable->EmptyString();
  111. mLoadedState = AssetErrCode::NotLoaded;
  112. }
  113. //-----------------------------------------------------------------------------
  114. ShapeAsset::~ShapeAsset()
  115. {
  116. }
  117. //-----------------------------------------------------------------------------
  118. void ShapeAsset::consoleInit()
  119. {
  120. Parent::consoleInit();
  121. Con::addVariable("$Core::NoShapeAssetFallback", TypeString, &smNoShapeAssetFallback,
  122. "The assetId of the shape to display when the requested shape asset is missing.\n"
  123. "@ingroup GFX\n");
  124. smNoShapeAssetFallback = StringTable->insert(Con::getVariable("$Core::NoShapeAssetFallback"));
  125. }
  126. //-----------------------------------------------------------------------------
  127. void ShapeAsset::initPersistFields()
  128. {
  129. docsURL;
  130. // Call parent.
  131. Parent::initPersistFields();
  132. addProtectedField("fileName", TypeAssetLooseFilePath, Offset(mFileName, ShapeAsset),
  133. &setShapeFile, &getShapeFile, "Path to the shape file we want to render");
  134. addProtectedField("constuctorFileName", TypeAssetLooseFilePath, Offset(mConstructorFileName, ShapeAsset),
  135. &setShapeConstructorFile, &getShapeConstructorFile, "Path to the shape file we want to render");
  136. addProtectedField("diffuseImposterFileName", TypeAssetLooseFilePath, Offset(mDiffuseImposterFileName, ShapeAsset),
  137. &setDiffuseImposterFile, &getDiffuseImposterFile, "Path to the diffuse imposter file we want to render");
  138. addProtectedField("normalImposterFileName", TypeAssetLooseFilePath, Offset(mNormalImposterFileName, ShapeAsset),
  139. &setNormalImposterFile, &getNormalImposterFile, "Path to the normal imposter file we want to render");
  140. }
  141. void ShapeAsset::setDataField(StringTableEntry slotName, StringTableEntry array, StringTableEntry value)
  142. {
  143. Parent::setDataField(slotName, array, value);
  144. //Now, if it's a material slot of some fashion, set it up
  145. StringTableEntry matSlotName = StringTable->insert("materialAsset");
  146. if (String(slotName).startsWith(matSlotName))
  147. {
  148. StringTableEntry matId = StringTable->insert(value);
  149. mMaterialAssetIds.push_back(matId);
  150. }
  151. }
  152. void ShapeAsset::initializeAsset()
  153. {
  154. // Call parent.
  155. Parent::initializeAsset();
  156. if (mFileName == StringTable->EmptyString())
  157. return;
  158. ResourceManager::get().getChangedSignal().notify(this, &ShapeAsset::_onResourceChanged);
  159. //Ensure our path is expando'd if it isn't already
  160. mFilePath = getOwned() ? expandAssetFilePath(mFileName) : mFilePath;
  161. mConstructorFilePath = getOwned() ? expandAssetFilePath(mConstructorFileName) : mConstructorFilePath;
  162. if (!Torque::FS::IsFile(mConstructorFilePath))
  163. Con::errorf("ShapeAsset::initializeAsset (%s) could not find %s!", getAssetName(), mConstructorFilePath);
  164. mDiffuseImposterPath = getOwned() ? expandAssetFilePath(mDiffuseImposterFileName) : mDiffuseImposterFileName;
  165. if (mDiffuseImposterPath == StringTable->EmptyString())
  166. {
  167. String diffusePath = String(mFilePath) + "_imposter.dds";
  168. mDiffuseImposterPath = StringTable->insert(diffusePath.c_str());
  169. }
  170. mNormalImposterPath = getOwned() ? expandAssetFilePath(mNormalImposterFileName) : mNormalImposterFileName;
  171. if (mNormalImposterPath == StringTable->EmptyString())
  172. {
  173. String normalPath = String(mFilePath) + "_imposter_normals.dds";
  174. mNormalImposterPath = StringTable->insert(normalPath.c_str());
  175. }
  176. }
  177. void ShapeAsset::setShapeFile(const char* pShapeFile)
  178. {
  179. // Sanity!
  180. AssertFatal(pShapeFile != NULL, "Cannot use a NULL shape file.");
  181. // Fetch image file.
  182. pShapeFile = StringTable->insert(pShapeFile, true);
  183. // Ignore no change,
  184. if (pShapeFile == mFileName)
  185. return;
  186. mFileName = getOwned() ? expandAssetFilePath(pShapeFile) : pShapeFile;
  187. // Refresh the asset.
  188. refreshAsset();
  189. }
  190. void ShapeAsset::setShapeConstructorFile(const char* pShapeConstructorFile)
  191. {
  192. // Sanity!
  193. AssertFatal(pShapeConstructorFile != NULL, "Cannot use a NULL shape constructor file.");
  194. // Fetch image file.
  195. pShapeConstructorFile = StringTable->insert(pShapeConstructorFile, true);
  196. // Ignore no change,
  197. if (pShapeConstructorFile == mConstructorFileName)
  198. return;
  199. mConstructorFileName = getOwned() ? expandAssetFilePath(pShapeConstructorFile) : pShapeConstructorFile;
  200. // Refresh the asset.
  201. refreshAsset();
  202. }
  203. void ShapeAsset::setDiffuseImposterFile(const char* pImageFile)
  204. {
  205. // Sanity!
  206. AssertFatal(pImageFile != NULL, "Cannot use a NULL image file.");
  207. // Fetch image file.
  208. pImageFile = StringTable->insert(pImageFile, true);
  209. // Ignore no change,
  210. if (pImageFile == mDiffuseImposterFileName)
  211. return;
  212. mDiffuseImposterFileName = getOwned() ? expandAssetFilePath(pImageFile) : pImageFile;
  213. // Refresh the asset.
  214. refreshAsset();
  215. }
  216. void ShapeAsset::setNormalImposterFile(const char* pImageFile)
  217. {
  218. // Sanity!
  219. AssertFatal(pImageFile != NULL, "Cannot use a NULL image file.");
  220. // Fetch image file.
  221. pImageFile = StringTable->insert(pImageFile, true);
  222. // Ignore no change,
  223. if (pImageFile == mNormalImposterFileName)
  224. return;
  225. mNormalImposterFileName = getOwned() ? expandAssetFilePath(pImageFile) : pImageFile;
  226. // Refresh the asset.
  227. refreshAsset();
  228. }
  229. void ShapeAsset::_onResourceChanged(const Torque::Path &path)
  230. {
  231. if (path != Torque::Path(mFilePath) )
  232. return;
  233. refreshAsset();
  234. }
  235. U32 ShapeAsset::load()
  236. {
  237. if (mLoadedState == AssetErrCode::Ok) return mLoadedState;
  238. mMaterialAssets.clear();
  239. mMaterialAssetIds.clear();
  240. //First, load any material, animation, etc assets we may be referencing in our asset
  241. // Find any asset dependencies.
  242. AssetManager::typeAssetDependsOnHash::Iterator assetDependenciesItr = mpOwningAssetManager->getDependedOnAssets()->find(mpAssetDefinition->mAssetId);
  243. // Does the asset have any dependencies?
  244. if (assetDependenciesItr != mpOwningAssetManager->getDependedOnAssets()->end())
  245. {
  246. // Iterate all dependencies.
  247. while (assetDependenciesItr != mpOwningAssetManager->getDependedOnAssets()->end() && assetDependenciesItr->key == mpAssetDefinition->mAssetId)
  248. {
  249. StringTableEntry assetType = mpOwningAssetManager->getAssetType(assetDependenciesItr->value);
  250. if (assetType == StringTable->insert("MaterialAsset"))
  251. {
  252. mMaterialAssetIds.push_front(assetDependenciesItr->value);
  253. //Force the asset to become initialized if it hasn't been already
  254. AssetPtr<MaterialAsset> matAsset = assetDependenciesItr->value;
  255. mMaterialAssets.push_front(matAsset);
  256. }
  257. else if (assetType == StringTable->insert("ShapeAnimationAsset"))
  258. {
  259. mAnimationAssetIds.push_back(assetDependenciesItr->value);
  260. //Force the asset to become initialized if it hasn't been already
  261. AssetPtr<ShapeAnimationAsset> animAsset = assetDependenciesItr->value;
  262. mAnimationAssets.push_back(animAsset);
  263. }
  264. // Next dependency.
  265. assetDependenciesItr++;
  266. }
  267. }
  268. mShape = ResourceManager::get().load(mFilePath);
  269. if (!mShape)
  270. {
  271. Con::errorf("ShapeAsset::loadShape : failed to load shape file %s (%s)!", getAssetName(), mFilePath);
  272. mLoadedState = BadFileReference;
  273. return mLoadedState; //if it failed to load, bail out
  274. }
  275. // Construct billboards if not done already
  276. if (GFXDevice::devicePresent())
  277. mShape->setupBillboardDetails(mFilePath, mDiffuseImposterPath, mNormalImposterPath);
  278. //If they exist, grab our imposters here and bind them to our shapeAsset
  279. bool hasBlends = false;
  280. //Now that we've successfully loaded our shape and have any materials and animations loaded
  281. //we need to set up the animations we're using on our shape
  282. for (S32 i = mAnimationAssets.size()-1; i >= 0; --i)
  283. {
  284. String srcName = mAnimationAssets[i]->getAnimationName();
  285. String srcPath(mAnimationAssets[i]->getAnimationFilename());
  286. //SplitSequencePathAndName(srcPath, srcName);
  287. if (!mShape->addSequence(srcPath, srcName, srcName,
  288. mAnimationAssets[i]->getStartFrame(), mAnimationAssets[i]->getEndFrame(), mAnimationAssets[i]->getPadRotation(), mAnimationAssets[i]->getPadTransforms()))
  289. {
  290. mLoadedState = MissingAnimatons;
  291. return mLoadedState;
  292. }
  293. if (mAnimationAssets[i]->isBlend())
  294. hasBlends = true;
  295. }
  296. //if any of our animations are blends, set those up now
  297. if (hasBlends)
  298. {
  299. for (U32 i=0; i < mAnimationAssets.size(); ++i)
  300. {
  301. if (mAnimationAssets[i]->isBlend() && mAnimationAssets[i]->getBlendAnimationName() != StringTable->EmptyString())
  302. {
  303. //gotta do a bit of logic here.
  304. //First, we need to make sure the anim asset we depend on for our blend is loaded
  305. AssetPtr<ShapeAnimationAsset> blendAnimAsset = mAnimationAssets[i]->getBlendAnimationName();
  306. U32 assetStatus = ShapeAnimationAsset::getAssetErrCode(blendAnimAsset);
  307. if (assetStatus != AssetBase::Ok)
  308. {
  309. Con::errorf("ShapeAsset::initializeAsset - Unable to acquire reference animation asset %s for asset %s to blend!", mAnimationAssets[i]->getBlendAnimationName(), mAnimationAssets[i]->getAssetName());
  310. {
  311. mLoadedState = MissingAnimatons;
  312. return mLoadedState;
  313. }
  314. }
  315. String refAnimName = blendAnimAsset->getAnimationName();
  316. if (!mShape->setSequenceBlend(mAnimationAssets[i]->getAnimationName(), true, blendAnimAsset->getAnimationName(), mAnimationAssets[i]->getBlendFrame()))
  317. {
  318. Con::errorf("ShapeAnimationAsset::initializeAsset - Unable to set animation clip %s for asset %s to blend!", mAnimationAssets[i]->getAnimationName(), mAnimationAssets[i]->getAssetName());
  319. {
  320. mLoadedState = MissingAnimatons;
  321. return mLoadedState;
  322. }
  323. }
  324. }
  325. }
  326. }
  327. mLoadedState = Ok;
  328. mChangeSignal.trigger();
  329. return mLoadedState;
  330. }
  331. //------------------------------------------------------------------------------
  332. //Utility function to 'fill out' bindings and resources with a matching asset if one exists
  333. U32 ShapeAsset::getAssetByFilename(StringTableEntry fileName, AssetPtr<ShapeAsset>* shapeAsset)
  334. {
  335. AssetQuery query;
  336. S32 foundAssetcount = AssetDatabase.findAssetLooseFile(&query, fileName);
  337. if (foundAssetcount == 0)
  338. {
  339. //Didn't work, so have us fall back to a placeholder asset
  340. shapeAsset->setAssetId(ShapeAsset::smNoShapeAssetFallback);
  341. if (shapeAsset->isNull())
  342. {
  343. //Well that's bad, loading the fallback failed.
  344. Con::warnf("ShapeAsset::getAssetByFilename - Finding of asset associated with file %s failed with no fallback asset", fileName);
  345. return AssetErrCode::Failed;
  346. }
  347. //handle noshape not being loaded itself
  348. if ((*shapeAsset)->mLoadedState == BadFileReference)
  349. {
  350. Con::warnf("ShapeAsset::getAssetByFilename - Finding of associated with file %s failed, and fallback asset reported error of Bad File Reference.", fileName);
  351. return AssetErrCode::BadFileReference;
  352. }
  353. Con::warnf("ShapeAsset::getAssetByFilename - Finding of associated with file %s failed, utilizing fallback asset", fileName);
  354. (*shapeAsset)->mLoadedState = AssetErrCode::UsingFallback;
  355. return AssetErrCode::UsingFallback;
  356. }
  357. else
  358. {
  359. //acquire and bind the asset, and return it out
  360. shapeAsset->setAssetId(query.mAssetList[0]);
  361. return (*shapeAsset)->mLoadedState;
  362. }
  363. }
  364. StringTableEntry ShapeAsset::getAssetIdByFilename(StringTableEntry fileName)
  365. {
  366. if (fileName == StringTable->EmptyString())
  367. return StringTable->EmptyString();
  368. StringTableEntry shapeAssetId = ShapeAsset::smNoShapeAssetFallback;
  369. AssetQuery query;
  370. S32 foundAssetcount = AssetDatabase.findAssetLooseFile(&query, fileName);
  371. if (foundAssetcount != 0)
  372. {
  373. //acquire and bind the asset, and return it out
  374. shapeAssetId = query.mAssetList[0];
  375. }
  376. else
  377. {
  378. AssetPtr<ShapeAsset> shapeAsset = shapeAssetId; //ensures the fallback is loaded
  379. }
  380. return shapeAssetId;
  381. }
  382. U32 ShapeAsset::getAssetById(StringTableEntry assetId, AssetPtr<ShapeAsset>* shapeAsset)
  383. {
  384. (*shapeAsset) = assetId;
  385. if (shapeAsset->notNull())
  386. {
  387. return (*shapeAsset)->mLoadedState;
  388. }
  389. else
  390. {
  391. //Didn't work, so have us fall back to a placeholder asset
  392. shapeAsset->setAssetId(ShapeAsset::smNoShapeAssetFallback);
  393. if (shapeAsset->isNull())
  394. {
  395. //Well that's bad, loading the fallback failed.
  396. Con::warnf("ShapeAsset::getAssetById - Finding of asset with id %s failed with no fallback asset", assetId);
  397. return AssetErrCode::Failed;
  398. }
  399. //handle noshape not being loaded itself
  400. if ((*shapeAsset)->mLoadedState == BadFileReference)
  401. {
  402. Con::warnf("ShapeAsset::getAssetById - Finding of asset with id %s failed, and fallback asset reported error of Bad File Reference.", assetId);
  403. return AssetErrCode::BadFileReference;
  404. }
  405. Con::warnf("ShapeAsset::getAssetById - Finding of asset with id %s failed, utilizing fallback asset", assetId);
  406. (*shapeAsset)->mLoadedState = AssetErrCode::UsingFallback;
  407. return AssetErrCode::UsingFallback;
  408. }
  409. }
  410. //------------------------------------------------------------------------------
  411. void ShapeAsset::copyTo(SimObject* object)
  412. {
  413. // Call to parent.
  414. Parent::copyTo(object);
  415. }
  416. void ShapeAsset::onAssetRefresh(void)
  417. {
  418. if (mFileName == StringTable->EmptyString())
  419. return;
  420. // Update.
  421. if(!Platform::isFullPath(mFileName))
  422. mFilePath = getOwned() ? expandAssetFilePath(mFileName) : mFilePath;
  423. load();
  424. }
  425. void ShapeAsset::SplitSequencePathAndName(String& srcPath, String& srcName)
  426. {
  427. srcName = "";
  428. // Determine if there is a sequence name at the end of the source string, and
  429. // if so, split the filename from the sequence name
  430. S32 split = srcPath.find(' ', 0, String::Right);
  431. S32 split2 = srcPath.find('\t', 0, String::Right);
  432. if ((split == String::NPos) || (split2 > split))
  433. split = split2;
  434. if (split != String::NPos)
  435. {
  436. split2 = split + 1;
  437. while ((srcPath[split2] != '\0') && dIsspace(srcPath[split2]))
  438. split2++;
  439. // now 'split' is at the end of the path, and 'split2' is at the start of the sequence name
  440. srcName = srcPath.substr(split2);
  441. srcPath = srcPath.erase(split, srcPath.length() - split);
  442. }
  443. }
  444. ShapeAnimationAsset* ShapeAsset::getAnimation(S32 index)
  445. {
  446. if (index < mAnimationAssets.size())
  447. {
  448. return mAnimationAssets[index];
  449. }
  450. return nullptr;
  451. }
  452. #ifdef TORQUE_TOOLS
  453. const char* ShapeAsset::generateCachedPreviewImage(S32 resolution, String overrideMaterial)
  454. {
  455. if (!mShape)
  456. return "";
  457. // We're gonna render... make sure we can.
  458. bool sceneBegun = GFX->canCurrentlyRender();
  459. if (!sceneBegun)
  460. GFX->beginScene();
  461. // We need to create our own instance to render with.
  462. TSShapeInstance* shape = new TSShapeInstance(mShape, true);
  463. if (overrideMaterial.isNotEmpty())
  464. {
  465. Material *tMat = dynamic_cast<Material*>(Sim::findObject(overrideMaterial));
  466. if (tMat)
  467. shape->reSkin(tMat->mMapTo, mShape->materialList->getMaterialName(0));
  468. }
  469. // Animate the shape once.
  470. shape->animate(0);
  471. GBitmap* imposter = NULL;
  472. GBitmap* imposterNrml = NULL;
  473. ImposterCapture* imposterCap = new ImposterCapture();
  474. static const MatrixF topXfm(EulerF(-M_PI_F / 2.0f, 0, 0));
  475. static const MatrixF bottomXfm(EulerF(M_PI_F / 2.0f, 0, 0));
  476. MatrixF angMat;
  477. PROFILE_START(ShapeAsset_generateCachedPreviewImage);
  478. //dMemset(destBmp.getWritableBits(mip), 0, destBmp.getWidth(mip) * destBmp.getHeight(mip) * GFXFormat_getByteSize(format));
  479. F32 rotX = -(mDegToRad(60.0) - 0.5f * M_PI_F);
  480. F32 rotZ = -(mDegToRad(45.0) - 0.5f * M_PI_F);
  481. // We capture the images in a particular order which must
  482. // match the order expected by the imposter renderer.
  483. imposterCap->begin(shape, 0, resolution, mShape->mRadius, mShape->center);
  484. angMat.mul(MatrixF(EulerF(rotX, 0, 0)),
  485. MatrixF(EulerF(0, 0, rotZ)));
  486. imposterCap->capture(angMat, &imposter, &imposterNrml);
  487. imposterCap->end();
  488. PROFILE_END(); // ShapeAsset_generateCachedPreviewImage
  489. delete imposterCap;
  490. delete shape;
  491. String dumpPath = String(mFilePath) + "_Preview.dds";
  492. char* returnBuffer = Con::getReturnBuffer(128);
  493. dSprintf(returnBuffer, 128, "%s", dumpPath.c_str());
  494. /*FileStream stream;
  495. if (stream.open(dumpPath, Torque::FS::File::Write))
  496. destBmp.writeBitmap("png", stream);
  497. stream.close();*/
  498. DDSFile* ddsDest = DDSFile::createDDSFileFromGBitmap(imposter);
  499. ImageUtil::ddsCompress(ddsDest, GFXFormatBC2);
  500. // Finally save the imposters to disk.
  501. FileStream fs;
  502. if (fs.open(returnBuffer, Torque::FS::File::Write))
  503. {
  504. ddsDest->write(fs);
  505. fs.close();
  506. }
  507. delete ddsDest;
  508. delete imposter;
  509. delete imposterNrml;
  510. // If we did a begin then end it now.
  511. if (!sceneBegun)
  512. GFX->endScene();
  513. return returnBuffer;
  514. }
  515. #endif
  516. DefineEngineMethod(ShapeAsset, getMaterialCount, S32, (), ,
  517. "Gets the number of materials for this shape asset.\n"
  518. "@return Material count.\n")
  519. {
  520. return object->getMaterialCount();
  521. }
  522. DefineEngineMethod(ShapeAsset, getAnimationCount, S32, (), ,
  523. "Gets the number of animations for this shape asset.\n"
  524. "@return Animation count.\n")
  525. {
  526. return object->getAnimationCount();
  527. }
  528. DefineEngineMethod(ShapeAsset, getAnimation, ShapeAnimationAsset*, (S32 index), (0),
  529. "Gets a particular shape animation asset for this shape.\n"
  530. "@param animation asset index.\n"
  531. "@return Shape Animation Asset.\n")
  532. {
  533. return object->getAnimation(index);
  534. }
  535. DefineEngineMethod(ShapeAsset, getShapePath, const char*, (), ,
  536. "Gets the shape's file path\n"
  537. "@return The filename of the shape file")
  538. {
  539. return object->getShapeFilePath();
  540. }
  541. DefineEngineMethod(ShapeAsset, getShapeConstructorFilePath, const char*, (), ,
  542. "Gets the shape's constructor file.\n"
  543. "@return The filename of the shape constructor file")
  544. {
  545. return object->getShapeConstructorFilePath();
  546. }
  547. DefineEngineMethod(ShapeAsset, getStatusString, String, (), , "get status string")\
  548. {
  549. return ShapeAsset::getAssetErrstrn(object->getStatus());
  550. }
  551. #ifdef TORQUE_TOOLS
  552. DefineEngineMethod(ShapeAsset, generateCachedPreviewImage, const char*, (S32 resolution, const char* overrideMaterialName), (256, ""),
  553. "Generates a baked preview image of the given shapeAsset. Only really used for generating Asset Browser icons.\n"
  554. "@param resolution Optional field for what resolution to bake the preview image at. Must be pow2\n"
  555. "@param overrideMaterialName Optional field for overriding the material used when rendering the shape for the bake.")
  556. {
  557. object->load();
  558. return object->generateCachedPreviewImage(resolution, overrideMaterialName);
  559. }
  560. DefineEngineStaticMethod(ShapeAsset, getAssetIdByFilename, const char*, (const char* filePath), (""),
  561. "Queries the Asset Database to see if any asset exists that is associated with the provided file path.\n"
  562. "@return The AssetId of the associated asset, if any.")
  563. {
  564. return ShapeAsset::getAssetIdByFilename(StringTable->insert(filePath));
  565. }
  566. #endif
  567. #ifdef TORQUE_TOOLS
  568. //-----------------------------------------------------------------------------
  569. // GuiInspectorTypeAssetId
  570. //-----------------------------------------------------------------------------
  571. IMPLEMENT_CONOBJECT(GuiInspectorTypeShapeAssetPtr);
  572. ConsoleDocClass(GuiInspectorTypeShapeAssetPtr,
  573. "@brief Inspector field type for Shapes\n\n"
  574. "Editor use only.\n\n"
  575. "@internal"
  576. );
  577. void GuiInspectorTypeShapeAssetPtr::consoleInit()
  578. {
  579. Parent::consoleInit();
  580. ConsoleBaseType::getType(TypeShapeAssetPtr)->setInspectorFieldType("GuiInspectorTypeShapeAssetPtr");
  581. }
  582. GuiControl* GuiInspectorTypeShapeAssetPtr::constructEditControl()
  583. {
  584. // Create base filename edit controls
  585. GuiControl* retCtrl = Parent::constructEditControl();
  586. if (retCtrl == NULL)
  587. return retCtrl;
  588. // Change filespec
  589. char szBuffer[512];
  590. const char* previewImage;
  591. if (mInspector->getInspectObject() != nullptr)
  592. {
  593. dSprintf(szBuffer, sizeof(szBuffer), "AssetBrowser.showDialog(\"ShapeAsset\", \"AssetBrowser.changeAsset\", %s, %s);",
  594. mInspector->getIdString(), mCaption);
  595. mBrowseButton->setField("Command", szBuffer);
  596. setDataField(StringTable->insert("targetObject"), NULL, mInspector->getInspectObject()->getIdString());
  597. previewImage = mInspector->getInspectObject()->getDataField(mCaption, NULL);
  598. }
  599. else
  600. {
  601. //if we don't have a target object, we'll be manipulating the desination value directly
  602. dSprintf(szBuffer, sizeof(szBuffer), "AssetBrowser.showDialog(\"ShapeAsset\", \"AssetBrowser.changeAsset\", %s, \"%s\");",
  603. mInspector->getIdString(), mVariableName);
  604. mBrowseButton->setField("Command", szBuffer);
  605. previewImage = Con::getVariable(mVariableName);
  606. }
  607. mLabel = new GuiTextCtrl();
  608. mLabel->registerObject();
  609. mLabel->setControlProfile(mProfile);
  610. mLabel->setText(mCaption);
  611. addObject(mLabel);
  612. //
  613. GuiTextEditCtrl* editTextCtrl = static_cast<GuiTextEditCtrl*>(retCtrl);
  614. GuiControlProfile* toolEditProfile;
  615. if (Sim::findObject("ToolsGuiTextEditProfile", toolEditProfile))
  616. editTextCtrl->setControlProfile(toolEditProfile);
  617. GuiControlProfile* toolDefaultProfile = nullptr;
  618. Sim::findObject("ToolsGuiDefaultProfile", toolDefaultProfile);
  619. //
  620. mPreviewImage = new GuiBitmapCtrl();
  621. mPreviewImage->registerObject();
  622. if (toolDefaultProfile)
  623. mPreviewImage->setControlProfile(toolDefaultProfile);
  624. updatePreviewImage();
  625. addObject(mPreviewImage);
  626. //
  627. mPreviewBorderButton = new GuiBitmapButtonCtrl();
  628. mPreviewBorderButton->registerObject();
  629. if (toolDefaultProfile)
  630. mPreviewBorderButton->setControlProfile(toolDefaultProfile);
  631. mPreviewBorderButton->_setBitmap(StringTable->insert("ToolsModule:cubemapBtnBorder_n_image"));
  632. mPreviewBorderButton->setField("Command", szBuffer); //clicking the preview does the same thing as the edit button, for simplicity
  633. addObject(mPreviewBorderButton);
  634. //
  635. // Create "Open in Editor" button
  636. mEditButton = new GuiBitmapButtonCtrl();
  637. dSprintf(szBuffer, sizeof(szBuffer), "ShapeEditorPlugin.openShapeAssetId(%d.getText());", retCtrl->getId());
  638. mEditButton->setField("Command", szBuffer);
  639. mEditButton->setText("Edit");
  640. mEditButton->setSizing(horizResizeLeft, vertResizeAspectTop);
  641. mEditButton->setDataField(StringTable->insert("Profile"), NULL, "ToolsGuiButtonProfile");
  642. mEditButton->setDataField(StringTable->insert("tooltipprofile"), NULL, "GuiToolTipProfile");
  643. mEditButton->setDataField(StringTable->insert("hovertime"), NULL, "1000");
  644. mEditButton->setDataField(StringTable->insert("tooltip"), NULL, "Open this asset in the Shape Editor");
  645. mEditButton->registerObject();
  646. addObject(mEditButton);
  647. //
  648. mUseHeightOverride = true;
  649. mHeightOverride = 72;
  650. return retCtrl;
  651. }
  652. bool GuiInspectorTypeShapeAssetPtr::updateRects()
  653. {
  654. S32 rowSize = 18;
  655. S32 dividerPos, dividerMargin;
  656. mInspector->getDivider(dividerPos, dividerMargin);
  657. Point2I fieldExtent = getExtent();
  658. Point2I fieldPos = getPosition();
  659. mEditCtrlRect.set(0, 0, fieldExtent.x, fieldExtent.y);
  660. mLabel->resize(Point2I(mProfile->mTextOffset.x, 0), Point2I(fieldExtent.x, rowSize));
  661. RectI previewRect = RectI(Point2I(mProfile->mTextOffset.x, rowSize), Point2I(50, 50));
  662. mPreviewBorderButton->resize(previewRect.point, previewRect.extent);
  663. mPreviewImage->resize(previewRect.point, previewRect.extent);
  664. S32 editPos = previewRect.point.x + previewRect.extent.x + 10;
  665. mEdit->resize(Point2I(editPos, rowSize * 1.5), Point2I(fieldExtent.x - editPos - 5, rowSize));
  666. mEditButton->resize(Point2I(fieldExtent.x - 105, previewRect.point.y + previewRect.extent.y - rowSize), Point2I(100, rowSize));
  667. mBrowseButton->setHidden(true);
  668. return true;
  669. }
  670. void GuiInspectorTypeShapeAssetPtr::updateValue()
  671. {
  672. Parent::updateValue();
  673. updatePreviewImage();
  674. }
  675. void GuiInspectorTypeShapeAssetPtr::updatePreviewImage()
  676. {
  677. const char* previewImage;
  678. if (mInspector->getInspectObject() != nullptr)
  679. previewImage = mInspector->getInspectObject()->getDataField(mCaption, NULL);
  680. else
  681. previewImage = Con::getVariable(mVariableName);
  682. //if what we're working with isn't even a valid asset, don't present like we found a good one
  683. if (!AssetDatabase.isDeclaredAsset(previewImage))
  684. {
  685. mPreviewImage->_setBitmap(StringTable->EmptyString());
  686. return;
  687. }
  688. String shpPreviewAssetId = String(previewImage) + "_PreviewImage";
  689. shpPreviewAssetId.replace(":", "_");
  690. shpPreviewAssetId = "ToolsModule:" + shpPreviewAssetId;
  691. if (AssetDatabase.isDeclaredAsset(shpPreviewAssetId.c_str()))
  692. {
  693. mPreviewImage->setBitmap(StringTable->insert(shpPreviewAssetId.c_str()));
  694. }
  695. if (mPreviewImage->getBitmapAsset().isNull())
  696. mPreviewImage->_setBitmap(StringTable->insert("ToolsModule:genericAssetIcon_image"));
  697. }
  698. void GuiInspectorTypeShapeAssetPtr::setPreviewImage(StringTableEntry assetId)
  699. {
  700. //if what we're working with isn't even a valid asset, don't present like we found a good one
  701. if (!AssetDatabase.isDeclaredAsset(assetId))
  702. {
  703. mPreviewImage->_setBitmap(StringTable->EmptyString());
  704. return;
  705. }
  706. String shpPreviewAssetId = String(assetId) + "_PreviewImage";
  707. shpPreviewAssetId.replace(":", "_");
  708. shpPreviewAssetId = "ToolsModule:" + shpPreviewAssetId;
  709. if (AssetDatabase.isDeclaredAsset(shpPreviewAssetId.c_str()))
  710. {
  711. mPreviewImage->setBitmap(StringTable->insert(shpPreviewAssetId.c_str()));
  712. }
  713. if (mPreviewImage->getBitmapAsset().isNull())
  714. mPreviewImage->_setBitmap(StringTable->insert("ToolsModule:genericAssetIcon_image"));
  715. }
  716. IMPLEMENT_CONOBJECT(GuiInspectorTypeShapeAssetId);
  717. ConsoleDocClass(GuiInspectorTypeShapeAssetId,
  718. "@brief Inspector field type for Shapes\n\n"
  719. "Editor use only.\n\n"
  720. "@internal"
  721. );
  722. void GuiInspectorTypeShapeAssetId::consoleInit()
  723. {
  724. Parent::consoleInit();
  725. ConsoleBaseType::getType(TypeShapeAssetId)->setInspectorFieldType("GuiInspectorTypeShapeAssetId");
  726. }
  727. #endif