ShapeAsset.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  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::mShapeErrCodeStrings[] =
  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. loadShape();
  177. }
  178. void ShapeAsset::setShapeFile(const char* pShapeFile)
  179. {
  180. // Sanity!
  181. AssertFatal(pShapeFile != NULL, "Cannot use a NULL shape file.");
  182. // Fetch image file.
  183. pShapeFile = StringTable->insert(pShapeFile, true);
  184. // Ignore no change,
  185. if (pShapeFile == mFileName)
  186. return;
  187. mFileName = getOwned() ? expandAssetFilePath(pShapeFile) : pShapeFile;
  188. // Refresh the asset.
  189. refreshAsset();
  190. }
  191. void ShapeAsset::setShapeConstructorFile(const char* pShapeConstructorFile)
  192. {
  193. // Sanity!
  194. AssertFatal(pShapeConstructorFile != NULL, "Cannot use a NULL shape constructor file.");
  195. // Fetch image file.
  196. pShapeConstructorFile = StringTable->insert(pShapeConstructorFile, true);
  197. // Ignore no change,
  198. if (pShapeConstructorFile == mConstructorFileName)
  199. return;
  200. mConstructorFileName = getOwned() ? expandAssetFilePath(pShapeConstructorFile) : pShapeConstructorFile;
  201. // Refresh the asset.
  202. refreshAsset();
  203. }
  204. void ShapeAsset::setDiffuseImposterFile(const char* pImageFile)
  205. {
  206. // Sanity!
  207. AssertFatal(pImageFile != NULL, "Cannot use a NULL image file.");
  208. // Fetch image file.
  209. pImageFile = StringTable->insert(pImageFile, true);
  210. // Ignore no change,
  211. if (pImageFile == mDiffuseImposterFileName)
  212. return;
  213. mDiffuseImposterFileName = getOwned() ? expandAssetFilePath(pImageFile) : pImageFile;
  214. // Refresh the asset.
  215. refreshAsset();
  216. }
  217. void ShapeAsset::setNormalImposterFile(const char* pImageFile)
  218. {
  219. // Sanity!
  220. AssertFatal(pImageFile != NULL, "Cannot use a NULL image file.");
  221. // Fetch image file.
  222. pImageFile = StringTable->insert(pImageFile, true);
  223. // Ignore no change,
  224. if (pImageFile == mNormalImposterFileName)
  225. return;
  226. mNormalImposterFileName = getOwned() ? expandAssetFilePath(pImageFile) : pImageFile;
  227. // Refresh the asset.
  228. refreshAsset();
  229. }
  230. void ShapeAsset::_onResourceChanged(const Torque::Path &path)
  231. {
  232. if (path != Torque::Path(mFilePath) )
  233. return;
  234. refreshAsset();
  235. loadShape();
  236. }
  237. bool ShapeAsset::loadShape()
  238. {
  239. mMaterialAssets.clear();
  240. mMaterialAssetIds.clear();
  241. //First, load any material, animation, etc assets we may be referencing in our asset
  242. // Find any asset dependencies.
  243. AssetManager::typeAssetDependsOnHash::Iterator assetDependenciesItr = mpOwningAssetManager->getDependedOnAssets()->find(mpAssetDefinition->mAssetId);
  244. // Does the asset have any dependencies?
  245. if (assetDependenciesItr != mpOwningAssetManager->getDependedOnAssets()->end())
  246. {
  247. // Iterate all dependencies.
  248. while (assetDependenciesItr != mpOwningAssetManager->getDependedOnAssets()->end() && assetDependenciesItr->key == mpAssetDefinition->mAssetId)
  249. {
  250. StringTableEntry assetType = mpOwningAssetManager->getAssetType(assetDependenciesItr->value);
  251. if (assetType == StringTable->insert("MaterialAsset"))
  252. {
  253. mMaterialAssetIds.push_front(assetDependenciesItr->value);
  254. //Force the asset to become initialized if it hasn't been already
  255. AssetPtr<MaterialAsset> matAsset = assetDependenciesItr->value;
  256. mMaterialAssets.push_front(matAsset);
  257. }
  258. else if (assetType == StringTable->insert("ShapeAnimationAsset"))
  259. {
  260. mAnimationAssetIds.push_back(assetDependenciesItr->value);
  261. //Force the asset to become initialized if it hasn't been already
  262. AssetPtr<ShapeAnimationAsset> animAsset = assetDependenciesItr->value;
  263. mAnimationAssets.push_back(animAsset);
  264. }
  265. // Next dependency.
  266. assetDependenciesItr++;
  267. }
  268. }
  269. mShape = ResourceManager::get().load(mFilePath);
  270. if (!mShape)
  271. {
  272. Con::errorf("ShapeAsset::loadShape : failed to load shape file %s (%s)!", getAssetName(), mFilePath);
  273. mLoadedState = BadFileReference;
  274. return false; //if it failed to load, bail out
  275. }
  276. // Construct billboards if not done already
  277. if (GFXDevice::devicePresent())
  278. mShape->setupBillboardDetails(mFilePath, mDiffuseImposterPath, mNormalImposterPath);
  279. //If they exist, grab our imposters here and bind them to our shapeAsset
  280. bool hasBlends = false;
  281. //Now that we've successfully loaded our shape and have any materials and animations loaded
  282. //we need to set up the animations we're using on our shape
  283. for (S32 i = mAnimationAssets.size()-1; i >= 0; --i)
  284. {
  285. String srcName = mAnimationAssets[i]->getAnimationName();
  286. String srcPath(mAnimationAssets[i]->getAnimationFilename());
  287. //SplitSequencePathAndName(srcPath, srcName);
  288. if (!mShape->addSequence(srcPath, srcName, srcName,
  289. mAnimationAssets[i]->getStartFrame(), mAnimationAssets[i]->getEndFrame(), mAnimationAssets[i]->getPadRotation(), mAnimationAssets[i]->getPadTransforms()))
  290. {
  291. mLoadedState = MissingAnimatons;
  292. return false;
  293. }
  294. if (mAnimationAssets[i]->isBlend())
  295. hasBlends = true;
  296. }
  297. //if any of our animations are blends, set those up now
  298. if (hasBlends)
  299. {
  300. for (U32 i=0; i < mAnimationAssets.size(); ++i)
  301. {
  302. if (mAnimationAssets[i]->isBlend() && mAnimationAssets[i]->getBlendAnimationName() != StringTable->EmptyString())
  303. {
  304. //gotta do a bit of logic here.
  305. //First, we need to make sure the anim asset we depend on for our blend is loaded
  306. AssetPtr<ShapeAnimationAsset> blendAnimAsset = mAnimationAssets[i]->getBlendAnimationName();
  307. if (blendAnimAsset.isNull())
  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 false;
  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 false;
  322. }
  323. }
  324. }
  325. }
  326. }
  327. mChangeSignal.trigger();
  328. mLoadedState = Ok;
  329. return true;
  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. loadShape();
  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. // So we don't have to change it everywhere.
  472. const GFXFormat format = GFXFormatR8G8B8A8;
  473. GBitmap* imposter = NULL;
  474. GBitmap* imposterNrml = NULL;
  475. ImposterCapture* imposterCap = new ImposterCapture();
  476. static const MatrixF topXfm(EulerF(-M_PI_F / 2.0f, 0, 0));
  477. static const MatrixF bottomXfm(EulerF(M_PI_F / 2.0f, 0, 0));
  478. MatrixF angMat;
  479. S32 mip = 0;
  480. PROFILE_START(ShapeAsset_generateCachedPreviewImage);
  481. //dMemset(destBmp.getWritableBits(mip), 0, destBmp.getWidth(mip) * destBmp.getHeight(mip) * GFXFormat_getByteSize(format));
  482. F32 rotX = -(mDegToRad(60.0) - 0.5f * M_PI_F);
  483. F32 rotZ = -(mDegToRad(45.0) - 0.5f * M_PI_F);
  484. // We capture the images in a particular order which must
  485. // match the order expected by the imposter renderer.
  486. imposterCap->begin(shape, 0, resolution, mShape->mRadius, mShape->center);
  487. angMat.mul(MatrixF(EulerF(rotX, 0, 0)),
  488. MatrixF(EulerF(0, 0, rotZ)));
  489. imposterCap->capture(angMat, &imposter, &imposterNrml);
  490. imposterCap->end();
  491. PROFILE_END(); // ShapeAsset_generateCachedPreviewImage
  492. delete imposterCap;
  493. delete shape;
  494. String dumpPath = String(mFilePath) + "_Preview.dds";
  495. char* returnBuffer = Con::getReturnBuffer(128);
  496. dSprintf(returnBuffer, 128, "%s", dumpPath.c_str());
  497. /*FileStream stream;
  498. if (stream.open(dumpPath, Torque::FS::File::Write))
  499. destBmp.writeBitmap("png", stream);
  500. stream.close();*/
  501. DDSFile* ddsDest = DDSFile::createDDSFileFromGBitmap(imposter);
  502. ImageUtil::ddsCompress(ddsDest, GFXFormatBC2);
  503. // Finally save the imposters to disk.
  504. FileStream fs;
  505. if (fs.open(returnBuffer, Torque::FS::File::Write))
  506. {
  507. ddsDest->write(fs);
  508. fs.close();
  509. }
  510. delete ddsDest;
  511. delete imposter;
  512. delete imposterNrml;
  513. // If we did a begin then end it now.
  514. if (!sceneBegun)
  515. GFX->endScene();
  516. return returnBuffer;
  517. }
  518. #endif
  519. DefineEngineMethod(ShapeAsset, getMaterialCount, S32, (), ,
  520. "Gets the number of materials for this shape asset.\n"
  521. "@return Material count.\n")
  522. {
  523. return object->getMaterialCount();
  524. }
  525. DefineEngineMethod(ShapeAsset, getAnimationCount, S32, (), ,
  526. "Gets the number of animations for this shape asset.\n"
  527. "@return Animation count.\n")
  528. {
  529. return object->getAnimationCount();
  530. }
  531. DefineEngineMethod(ShapeAsset, getAnimation, ShapeAnimationAsset*, (S32 index), (0),
  532. "Gets a particular shape animation asset for this shape.\n"
  533. "@param animation asset index.\n"
  534. "@return Shape Animation Asset.\n")
  535. {
  536. return object->getAnimation(index);
  537. }
  538. DefineEngineMethod(ShapeAsset, getShapePath, const char*, (), ,
  539. "Gets the shape's file path\n"
  540. "@return The filename of the shape file")
  541. {
  542. return object->getShapeFilePath();
  543. }
  544. DefineEngineMethod(ShapeAsset, getShapeConstructorFilePath, const char*, (), ,
  545. "Gets the shape's constructor file.\n"
  546. "@return The filename of the shape constructor file")
  547. {
  548. return object->getShapeConstructorFilePath();
  549. }
  550. DefineEngineMethod(ShapeAsset, getStatusString, String, (), , "get status string")\
  551. {
  552. return ShapeAsset::getAssetErrstrn(object->getStatus());
  553. }
  554. #ifdef TORQUE_TOOLS
  555. DefineEngineMethod(ShapeAsset, generateCachedPreviewImage, const char*, (S32 resolution, const char* overrideMaterialName), (256, ""),
  556. "Generates a baked preview image of the given shapeAsset. Only really used for generating Asset Browser icons.\n"
  557. "@param resolution Optional field for what resolution to bake the preview image at. Must be pow2\n"
  558. "@param overrideMaterialName Optional field for overriding the material used when rendering the shape for the bake.")
  559. {
  560. return object->generateCachedPreviewImage(resolution, overrideMaterialName);
  561. }
  562. DefineEngineStaticMethod(ShapeAsset, getAssetIdByFilename, const char*, (const char* filePath), (""),
  563. "Queries the Asset Database to see if any asset exists that is associated with the provided file path.\n"
  564. "@return The AssetId of the associated asset, if any.")
  565. {
  566. return ShapeAsset::getAssetIdByFilename(StringTable->insert(filePath));
  567. }
  568. #endif
  569. #ifdef TORQUE_TOOLS
  570. //-----------------------------------------------------------------------------
  571. // GuiInspectorTypeAssetId
  572. //-----------------------------------------------------------------------------
  573. IMPLEMENT_CONOBJECT(GuiInspectorTypeShapeAssetPtr);
  574. ConsoleDocClass(GuiInspectorTypeShapeAssetPtr,
  575. "@brief Inspector field type for Shapes\n\n"
  576. "Editor use only.\n\n"
  577. "@internal"
  578. );
  579. void GuiInspectorTypeShapeAssetPtr::consoleInit()
  580. {
  581. Parent::consoleInit();
  582. ConsoleBaseType::getType(TypeShapeAssetPtr)->setInspectorFieldType("GuiInspectorTypeShapeAssetPtr");
  583. }
  584. GuiControl* GuiInspectorTypeShapeAssetPtr::constructEditControl()
  585. {
  586. // Create base filename edit controls
  587. GuiControl* retCtrl = Parent::constructEditControl();
  588. if (retCtrl == NULL)
  589. return retCtrl;
  590. // Change filespec
  591. char szBuffer[512];
  592. const char* previewImage;
  593. if (mInspector->getInspectObject() != nullptr)
  594. {
  595. dSprintf(szBuffer, sizeof(szBuffer), "AssetBrowser.showDialog(\"ShapeAsset\", \"AssetBrowser.changeAsset\", %s, %s);",
  596. mInspector->getIdString(), mCaption);
  597. mBrowseButton->setField("Command", szBuffer);
  598. setDataField(StringTable->insert("targetObject"), NULL, mInspector->getInspectObject()->getIdString());
  599. previewImage = mInspector->getInspectObject()->getDataField(mCaption, NULL);
  600. }
  601. else
  602. {
  603. //if we don't have a target object, we'll be manipulating the desination value directly
  604. dSprintf(szBuffer, sizeof(szBuffer), "AssetBrowser.showDialog(\"ShapeAsset\", \"AssetBrowser.changeAsset\", %s, \"%s\");",
  605. mInspector->getIdString(), mVariableName);
  606. mBrowseButton->setField("Command", szBuffer);
  607. previewImage = Con::getVariable(mVariableName);
  608. }
  609. mLabel = new GuiTextCtrl();
  610. mLabel->registerObject();
  611. mLabel->setControlProfile(mProfile);
  612. mLabel->setText(mCaption);
  613. addObject(mLabel);
  614. //
  615. GuiTextEditCtrl* editTextCtrl = static_cast<GuiTextEditCtrl*>(retCtrl);
  616. GuiControlProfile* toolEditProfile;
  617. if (Sim::findObject("ToolsGuiTextEditProfile", toolEditProfile))
  618. editTextCtrl->setControlProfile(toolEditProfile);
  619. GuiControlProfile* toolDefaultProfile = nullptr;
  620. Sim::findObject("ToolsGuiDefaultProfile", toolDefaultProfile);
  621. //
  622. mPreviewImage = new GuiBitmapCtrl();
  623. mPreviewImage->registerObject();
  624. if (toolDefaultProfile)
  625. mPreviewImage->setControlProfile(toolDefaultProfile);
  626. updatePreviewImage();
  627. addObject(mPreviewImage);
  628. //
  629. mPreviewBorderButton = new GuiBitmapButtonCtrl();
  630. mPreviewBorderButton->registerObject();
  631. if (toolDefaultProfile)
  632. mPreviewBorderButton->setControlProfile(toolDefaultProfile);
  633. mPreviewBorderButton->_setBitmap(StringTable->insert("ToolsModule:cubemapBtnBorder_n_image"));
  634. mPreviewBorderButton->setField("Command", szBuffer); //clicking the preview does the same thing as the edit button, for simplicity
  635. addObject(mPreviewBorderButton);
  636. //
  637. // Create "Open in Editor" button
  638. mEditButton = new GuiBitmapButtonCtrl();
  639. dSprintf(szBuffer, sizeof(szBuffer), "ShapeEditorPlugin.openShapeAssetId(%d.getText());", retCtrl->getId());
  640. mEditButton->setField("Command", szBuffer);
  641. mEditButton->setText("Edit");
  642. mEditButton->setSizing(horizResizeLeft, vertResizeAspectTop);
  643. mEditButton->setDataField(StringTable->insert("Profile"), NULL, "ToolsGuiButtonProfile");
  644. mEditButton->setDataField(StringTable->insert("tooltipprofile"), NULL, "GuiToolTipProfile");
  645. mEditButton->setDataField(StringTable->insert("hovertime"), NULL, "1000");
  646. mEditButton->setDataField(StringTable->insert("tooltip"), NULL, "Open this asset in the Shape Editor");
  647. mEditButton->registerObject();
  648. addObject(mEditButton);
  649. //
  650. mUseHeightOverride = true;
  651. mHeightOverride = 72;
  652. return retCtrl;
  653. }
  654. bool GuiInspectorTypeShapeAssetPtr::updateRects()
  655. {
  656. S32 rowSize = 18;
  657. S32 dividerPos, dividerMargin;
  658. mInspector->getDivider(dividerPos, dividerMargin);
  659. Point2I fieldExtent = getExtent();
  660. Point2I fieldPos = getPosition();
  661. mEditCtrlRect.set(0, 0, fieldExtent.x, fieldExtent.y);
  662. mLabel->resize(Point2I(mProfile->mTextOffset.x, 0), Point2I(fieldExtent.x, rowSize));
  663. RectI previewRect = RectI(Point2I(mProfile->mTextOffset.x, rowSize), Point2I(50, 50));
  664. mPreviewBorderButton->resize(previewRect.point, previewRect.extent);
  665. mPreviewImage->resize(previewRect.point, previewRect.extent);
  666. S32 editPos = previewRect.point.x + previewRect.extent.x + 10;
  667. mEdit->resize(Point2I(editPos, rowSize * 1.5), Point2I(fieldExtent.x - editPos - 5, rowSize));
  668. mEditButton->resize(Point2I(fieldExtent.x - 105, previewRect.point.y + previewRect.extent.y - rowSize), Point2I(100, rowSize));
  669. mBrowseButton->setHidden(true);
  670. return true;
  671. }
  672. void GuiInspectorTypeShapeAssetPtr::updateValue()
  673. {
  674. Parent::updateValue();
  675. updatePreviewImage();
  676. }
  677. void GuiInspectorTypeShapeAssetPtr::updatePreviewImage()
  678. {
  679. const char* previewImage;
  680. if (mInspector->getInspectObject() != nullptr)
  681. previewImage = mInspector->getInspectObject()->getDataField(mCaption, NULL);
  682. else
  683. previewImage = Con::getVariable(mVariableName);
  684. //if what we're working with isn't even a valid asset, don't present like we found a good one
  685. if (!AssetDatabase.isDeclaredAsset(previewImage))
  686. {
  687. mPreviewImage->_setBitmap(StringTable->EmptyString());
  688. return;
  689. }
  690. String shpPreviewAssetId = String(previewImage) + "_PreviewImage";
  691. shpPreviewAssetId.replace(":", "_");
  692. shpPreviewAssetId = "ToolsModule:" + shpPreviewAssetId;
  693. if (AssetDatabase.isDeclaredAsset(shpPreviewAssetId.c_str()))
  694. {
  695. mPreviewImage->setBitmap(StringTable->insert(shpPreviewAssetId.c_str()));
  696. }
  697. if (mPreviewImage->getBitmapAsset().isNull())
  698. mPreviewImage->_setBitmap(StringTable->insert("ToolsModule:genericAssetIcon_image"));
  699. }
  700. void GuiInspectorTypeShapeAssetPtr::setPreviewImage(StringTableEntry assetId)
  701. {
  702. //if what we're working with isn't even a valid asset, don't present like we found a good one
  703. if (!AssetDatabase.isDeclaredAsset(assetId))
  704. {
  705. mPreviewImage->_setBitmap(StringTable->EmptyString());
  706. return;
  707. }
  708. String shpPreviewAssetId = String(assetId) + "_PreviewImage";
  709. shpPreviewAssetId.replace(":", "_");
  710. shpPreviewAssetId = "ToolsModule:" + shpPreviewAssetId;
  711. if (AssetDatabase.isDeclaredAsset(shpPreviewAssetId.c_str()))
  712. {
  713. mPreviewImage->setBitmap(StringTable->insert(shpPreviewAssetId.c_str()));
  714. }
  715. if (mPreviewImage->getBitmapAsset().isNull())
  716. mPreviewImage->_setBitmap(StringTable->insert("ToolsModule:genericAssetIcon_image"));
  717. }
  718. IMPLEMENT_CONOBJECT(GuiInspectorTypeShapeAssetId);
  719. ConsoleDocClass(GuiInspectorTypeShapeAssetId,
  720. "@brief Inspector field type for Shapes\n\n"
  721. "Editor use only.\n\n"
  722. "@internal"
  723. );
  724. void GuiInspectorTypeShapeAssetId::consoleInit()
  725. {
  726. Parent::consoleInit();
  727. ConsoleBaseType::getType(TypeShapeAssetId)->setInspectorFieldType("GuiInspectorTypeShapeAssetId");
  728. }
  729. #endif