ImageAsset.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  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 IMAGE_ASSET_H
  23. #include "ImageAsset.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 "gfx/gfxStringEnumTranslate.h"
  38. #include "ImageAssetInspectors.h"
  39. // Debug Profiling.
  40. #include "platform/profiler.h"
  41. #include "T3D/assets/assetImporter.h"
  42. #include "gfx/gfxDrawUtil.h"
  43. #include "gfx/bitmap/ddsFile.h"
  44. #ifdef __clang__
  45. #define STBIWDEF static inline
  46. #endif
  47. #pragma warning( push )
  48. #pragma warning( disable : 4505 ) // unreferenced function removed.
  49. #ifndef STB_IMAGE_IMPLEMENTATION
  50. #define STB_IMAGE_IMPLEMENTATION
  51. #define STB_IMAGE_STATIC
  52. #include "stb_image.h"
  53. #endif
  54. #pragma warning(pop)
  55. //-----------------------------------------------------------------------------
  56. StringTableEntry ImageAsset::smNoImageAssetFallback = NULL;
  57. StringTableEntry ImageAsset::smNamedTargetAssetFallback = NULL;
  58. //-----------------------------------------------------------------------------
  59. IMPLEMENT_CONOBJECT(ImageAsset);
  60. //-----------------------------------------------------------------------------
  61. // REFACTOR
  62. //-----------------------------------------------------------------------------
  63. IMPLEMENT_STRUCT(AssetPtr<ImageAsset>, AssetPtrImageAsset,, "")
  64. END_IMPLEMENT_STRUCT
  65. ConsoleType(ImageAssetPtr, TypeImageAssetPtr, AssetPtr<ImageAsset>, ASSET_ID_FIELD_PREFIX)
  66. ConsoleGetType(TypeImageAssetPtr)
  67. {
  68. // Fetch asset Id.
  69. return (*((AssetPtr<ImageAsset>*)dptr)).getAssetId();
  70. }
  71. ConsoleSetType(TypeImageAssetPtr)
  72. {
  73. // Was a single argument specified?
  74. if (argc == 1)
  75. {
  76. // Yes, so fetch field value.
  77. const char* pFieldValue = argv[0];
  78. // Fetch asset pointer.
  79. AssetPtr<ImageAsset>* pAssetPtr = dynamic_cast<AssetPtr<ImageAsset>*>((AssetPtrBase*)(dptr));
  80. // Is the asset pointer the correct type?
  81. if (pAssetPtr == NULL)
  82. {
  83. Con::warnf("(TypeImageAssetPtr) - Failed to set asset Id '%d'.", pFieldValue);
  84. return;
  85. }
  86. // Set asset.
  87. pAssetPtr->setAssetId(pFieldValue);
  88. return;
  89. }
  90. // Warn.
  91. Con::warnf("(TypeImageAssetPtr) - Cannot set multiple args to a single asset.");
  92. }
  93. //-----------------------------------------------------------------------------
  94. // REFACTOR END
  95. //-----------------------------------------------------------------------------
  96. ImplementEnumType(ImageAssetType,
  97. "Type of mesh data available in a shape.\n"
  98. "@ingroup gameObjects")
  99. { ImageAsset::Albedo, "Albedo", "" },
  100. { ImageAsset::Normal, "Normal", "" },
  101. { ImageAsset::ORMConfig, "ORMConfig", "" },
  102. { ImageAsset::GUI, "GUI", "" },
  103. { ImageAsset::Roughness, "Roughness", "" },
  104. { ImageAsset::AO, "AO", "" },
  105. { ImageAsset::Metalness, "Metalness", "" },
  106. { ImageAsset::Glow, "Glow", "" },
  107. { ImageAsset::Particle, "Particle", "" },
  108. { ImageAsset::Decal, "Decal", "" },
  109. { ImageAsset::Cubemap, "Cubemap", "" },
  110. EndImplementEnumType;
  111. const String ImageAsset::mErrCodeStrings[] =
  112. {
  113. "TooManyMips",
  114. "UnKnown"
  115. };
  116. //-----------------------------------------------------------------------------
  117. ImageAsset::ImageAsset() :
  118. mImageFile(StringTable->EmptyString()),
  119. mUseMips(true),
  120. mIsHDRImage(false),
  121. mImageType(Albedo),
  122. mTextureHandle(NULL),
  123. mIsNamedTarget(false),
  124. mImageWidth(-1),
  125. mImageHeight(-1),
  126. mImageDepth(-1),
  127. mImageChannels(-1)
  128. {
  129. mLoadedState = AssetErrCode::NotLoaded;
  130. }
  131. //-----------------------------------------------------------------------------
  132. ImageAsset::~ImageAsset()
  133. {
  134. ImageTextureMap::iterator resIter = mResourceMap.begin();
  135. for (; resIter != mResourceMap.end(); ++resIter)
  136. {
  137. resIter->value.free();
  138. }
  139. mResourceMap.clear();
  140. }
  141. void ImageAsset::consoleInit()
  142. {
  143. Parent::consoleInit();
  144. Con::addVariable("$Core::NoImageAssetFallback", TypeString, &smNoImageAssetFallback,
  145. "The assetId of the texture to display when the requested image asset is missing.\n"
  146. "@ingroup GFX\n");
  147. Con::addVariable("$Core::NamedTargetFallback", TypeString, &smNamedTargetAssetFallback,
  148. "The assetId of the texture to display when the requested image asset is named target.\n"
  149. "@ingroup GFX\n");
  150. smNoImageAssetFallback = StringTable->insert(Con::getVariable("$Core::NoImageAssetFallback"));
  151. smNamedTargetAssetFallback = StringTable->insert(Con::getVariable("$Core::NamedTargetFallback"));
  152. }
  153. //-----------------------------------------------------------------------------
  154. void ImageAsset::initPersistFields()
  155. {
  156. docsURL;
  157. // Call parent.
  158. Parent::initPersistFields();
  159. addProtectedField("imageFile", TypeAssetLooseFilePath, Offset(mImageFile, ImageAsset), &setImageFile, &getImageFile, &writeImageFile, "Path to the image file.");
  160. addProtectedField("useMips", TypeBool, Offset(mUseMips, ImageAsset), &setGenMips, &defaultProtectedGetFn, &writeGenMips, "Generate mip maps?");
  161. addProtectedField("isHDRImage", TypeBool, Offset(mIsHDRImage, ImageAsset), &setTextureHDR, &defaultProtectedGetFn, &writeTextureHDR, "HDR Image?");
  162. addField("imageType", TypeImageAssetType, Offset(mImageType, ImageAsset), "What the main use-case for the image is for.");
  163. }
  164. bool ImageAsset::onAdd()
  165. {
  166. // Call Parent.
  167. if (!Parent::onAdd())
  168. return false;
  169. return true;
  170. }
  171. void ImageAsset::onRemove()
  172. {
  173. // Call Parent.
  174. Parent::onRemove();
  175. }
  176. U32 ImageAsset::getAssetByFilename(StringTableEntry fileName, AssetPtr<ImageAsset>* imageAsset)
  177. {
  178. AssetQuery query;
  179. S32 foundAssetcount = AssetDatabase.findAssetLooseFile(&query, fileName);
  180. if (foundAssetcount == 0)
  181. {
  182. //Didn't work, so have us fall back to a placeholder asset
  183. imageAsset->setAssetId(ImageAsset::smNoImageAssetFallback);
  184. if (imageAsset->isNull())
  185. {
  186. //Well that's bad, loading the fallback failed.
  187. Con::warnf("ImageAsset::getAssetByFilename - Finding of asset associated with file %s failed with no fallback asset", fileName);
  188. return AssetErrCode::Failed;
  189. }
  190. //handle noshape not being loaded itself
  191. if ((*imageAsset)->mLoadedState == BadFileReference)
  192. {
  193. Con::warnf("ImageAsset::getAssetByFilename - Finding of associated with file %s failed, and fallback asset reported error of Bad File Reference.", fileName);
  194. return AssetErrCode::BadFileReference;
  195. }
  196. Con::warnf("ImageAsset::getAssetByFilename - Finding of associated with file %s failed, utilizing fallback asset", fileName);
  197. (*imageAsset)->mLoadedState = AssetErrCode::UsingFallback;
  198. return AssetErrCode::UsingFallback;
  199. }
  200. else
  201. {
  202. //acquire and bind the asset, and return it out
  203. imageAsset->setAssetId(query.mAssetList[0]);
  204. return (*imageAsset)->load();
  205. }
  206. }
  207. StringTableEntry ImageAsset::getAssetIdByFilename(StringTableEntry fileName)
  208. {
  209. if (fileName == StringTable->EmptyString())
  210. return StringTable->EmptyString();
  211. StringTableEntry imageAssetId = ImageAsset::smNoImageAssetFallback;
  212. AssetQuery query;
  213. S32 foundAssetcount = AssetDatabase.findAssetLooseFile(&query, fileName);
  214. if (foundAssetcount != 0)
  215. {
  216. //acquire and bind the asset, and return it out
  217. imageAssetId = query.mAssetList[0];
  218. }
  219. else
  220. {
  221. foundAssetcount = AssetDatabase.findAssetType(&query, "ImageAsset");
  222. if (foundAssetcount != 0)
  223. {
  224. // loop all image assets and see if we can find one
  225. // using the same image file/named target.
  226. for (auto imgAsset : query.mAssetList)
  227. {
  228. AssetPtr<ImageAsset> temp = imgAsset;
  229. if (temp.notNull())
  230. {
  231. if (temp->getImageFile() == fileName)
  232. {
  233. return imgAsset;
  234. }
  235. else
  236. {
  237. Torque::Path temp1 = temp->getImageFile();
  238. Torque::Path temp2 = fileName;
  239. if (temp1.getFileName() == temp2.getFileName())
  240. {
  241. return imgAsset;
  242. }
  243. }
  244. }
  245. }
  246. }
  247. else
  248. {
  249. AssetPtr<ImageAsset> imageAsset = imageAssetId; //ensures the fallback is loaded
  250. }
  251. }
  252. return imageAssetId;
  253. }
  254. U32 ImageAsset::getAssetById(StringTableEntry assetId, AssetPtr<ImageAsset>* imageAsset)
  255. {
  256. (*imageAsset) = assetId;
  257. if (imageAsset->notNull())
  258. {
  259. return (*imageAsset)->load();
  260. }
  261. else
  262. {
  263. if (imageAsset->isNull())
  264. {
  265. return AssetErrCode::Failed;
  266. }
  267. //handle fallback not being loaded itself
  268. if ((*imageAsset)->mLoadedState == BadFileReference)
  269. {
  270. Con::warnf("ImageAsset::getAssetById - Finding of asset with id %s failed, and fallback asset reported error of Bad File Reference.", assetId);
  271. return AssetErrCode::BadFileReference;
  272. }
  273. Con::warnf("ImageAsset::getAssetById - Finding of asset with id %s failed, utilizing fallback asset", assetId);
  274. (*imageAsset)->mLoadedState = AssetErrCode::UsingFallback;
  275. return AssetErrCode::UsingFallback;
  276. }
  277. }
  278. void ImageAsset::initializeAsset(void)
  279. {
  280. // Call parent.
  281. Parent::initializeAsset();
  282. // Ensure the image-file is expanded.
  283. if (isNamedTarget())
  284. return;
  285. mImageFile = expandAssetFilePath(mImageFile);
  286. }
  287. void ImageAsset::onAssetRefresh(void)
  288. {
  289. // Ignore if not yet added to the sim.
  290. if (!isProperlyAdded())
  291. return;
  292. // Call parent.
  293. Parent::onAssetRefresh();
  294. }
  295. //------------------------------------------------------------------------------
  296. void ImageAsset::copyTo(SimObject* object)
  297. {
  298. // Call to parent.
  299. Parent::copyTo(object);
  300. ImageAsset* pAsset = static_cast<ImageAsset*>(object);
  301. // Sanity!
  302. AssertFatal(pAsset != NULL, "ImageAsset::copyTo() - Object is not the correct type.");
  303. pAsset->setImageFile(getImageFile());
  304. pAsset->setGenMips(getGenMips());
  305. pAsset->setTextureHDR(getTextureHDR());
  306. }
  307. void ImageAsset::setImageFile(StringTableEntry pImageFile)
  308. {
  309. // Sanity!
  310. AssertFatal(pImageFile != NULL, "Cannot use a NULL image file.");
  311. pImageFile = StringTable->insert(pImageFile);
  312. if (pImageFile == mImageFile)
  313. return;
  314. if (String(pImageFile).startsWith("#") || String(pImageFile).startsWith("$"))
  315. {
  316. mImageFile = StringTable->insert(pImageFile);
  317. mIsNamedTarget = true;
  318. refreshAsset();
  319. return;
  320. }
  321. mImageFile = getOwned() ? expandAssetFilePath(pImageFile) : StringTable->insert(pImageFile);
  322. if (Torque::FS::IsFile(mImageFile))
  323. {
  324. if (dStrEndsWith(mImageFile, ".dds"))
  325. {
  326. DDSFile* tempFile = new DDSFile();
  327. FileStream* ddsFs;
  328. if ((ddsFs = FileStream::createAndOpen(mImageFile, Torque::FS::File::Read)) == NULL)
  329. {
  330. Con::errorf("ImageAsset::setImageFile Failed to open ddsfile: %s", mImageFile);
  331. }
  332. if (!tempFile->readHeader(*ddsFs))
  333. {
  334. Con::errorf("ImageAsset::setImageFile Failed to read header of ddsfile: %s", mImageFile);
  335. }
  336. else
  337. {
  338. mImageWidth = tempFile->mWidth;
  339. mImageHeight = tempFile->mHeight;
  340. }
  341. ddsFs->close();
  342. delete tempFile;
  343. }
  344. else
  345. {
  346. if (!stbi_info(mImageFile, &mImageWidth, &mImageHeight, &mImageChannels))
  347. {
  348. StringTableEntry stbErr = stbi_failure_reason();
  349. if (stbErr == StringTable->EmptyString())
  350. stbErr = "ImageAsset::Unkown Error!";
  351. Con::errorf("ImageAsset::setImageFile STB Get file info failed: %s", stbErr);
  352. }
  353. }
  354. // we only support 2d textures..... for no ;)
  355. mImageDepth = 1;
  356. }
  357. refreshAsset();
  358. }
  359. void ImageAsset::setGenMips(const bool pGenMips)
  360. {
  361. if (pGenMips == mUseMips)
  362. return;
  363. mUseMips = pGenMips;
  364. refreshAsset();
  365. }
  366. void ImageAsset::setTextureHDR(const bool pIsHDR)
  367. {
  368. if (pIsHDR == mIsHDRImage)
  369. return;
  370. mIsHDRImage = pIsHDR;
  371. refreshAsset();
  372. }
  373. U32 ImageAsset::load()
  374. {
  375. if (mLoadedState == Ok)
  376. return mLoadedState;
  377. if (!Torque::FS::IsFile(mImageFile))
  378. {
  379. if (isNamedTarget())
  380. {
  381. mLoadedState = Ok;
  382. return mLoadedState;
  383. }
  384. Con::errorf("ImageAsset::initializeAsset: Attempted to load file %s but it was not valid!", mImageFile);
  385. mLoadedState = BadFileReference;
  386. return mLoadedState;
  387. }
  388. else
  389. {
  390. mLoadedState = Ok;
  391. }
  392. return mLoadedState;
  393. }
  394. GFXTexHandle ImageAsset::getTexture(GFXTextureProfile* requestedProfile)
  395. {
  396. load();
  397. if (isNamedTarget())
  398. {
  399. GFXTexHandle tex;
  400. AssetPtr<ImageAsset> fallbackAsset;
  401. ImageAsset::getAssetById(smNamedTargetAssetFallback, &fallbackAsset);
  402. if (getNamedTarget().isValid())
  403. {
  404. tex = getNamedTarget()->getTexture();
  405. if (tex.isNull())
  406. {
  407. return fallbackAsset->getTexture();
  408. }
  409. return tex;
  410. }
  411. else
  412. {
  413. return fallbackAsset->getTexture();
  414. }
  415. }
  416. if (mLoadedState == Ok)
  417. {
  418. if (mResourceMap.contains(requestedProfile))
  419. {
  420. return mResourceMap.find(requestedProfile)->value;
  421. }
  422. else
  423. {
  424. //If we don't have an existing map case to the requested format, we'll just create it and insert it in
  425. GFXTexHandle newTex;
  426. newTex.set(mImageFile, requestedProfile, avar("%s %s() - mTextureObject (line %d)", mImageFile, __FUNCTION__, __LINE__));
  427. if (newTex)
  428. {
  429. mLoadedState = AssetErrCode::Ok;
  430. mResourceMap.insert(requestedProfile, newTex);
  431. return newTex;
  432. }
  433. }
  434. }
  435. mLoadedState = AssetErrCode::Failed;
  436. return nullptr;
  437. }
  438. void ImageAsset::generateTexture(void)
  439. {
  440. // already have a generated texture, get out.
  441. if (mTextureHandle.isValid())
  442. return;
  443. // implement some defaults, eventually SRGB should be optional.
  444. U32 flags = GFXTextureProfile::Static | GFXTextureProfile::SRGB;
  445. // dont want mips?
  446. if (!mUseMips)
  447. {
  448. flags |= GFXTextureProfile::NoMipmap;
  449. }
  450. GFXTextureProfile::Types type = GFXTextureProfile::Types::DiffuseMap;
  451. if (mImageType == ImageTypes::Normal) {
  452. type = GFXTextureProfile::Types::NormalMap;
  453. }
  454. GFXTextureProfile* genProfile = new GFXTextureProfile("ImageAssetGennedProfile", type, flags);
  455. mTextureHandle.set(mImageFile, genProfile, avar("%s() - mTextureObject (line %d)", __FUNCTION__, __LINE__));
  456. mResourceMap.insert(genProfile, mTextureHandle);
  457. if (mTextureHandle.isValid())
  458. mLoadedState = AssetErrCode::Ok;
  459. else
  460. mLoadedState = AssetErrCode::Failed;
  461. ResourceManager::get().getChangedSignal().notify(this, &ImageAsset::_onResourceChanged);
  462. }
  463. const char* ImageAsset::getImageTypeNameFromType(ImageAsset::ImageTypes type)
  464. {
  465. // must match ImageTypes order
  466. static const char* _names[] = {
  467. "Albedo",
  468. "Normal",
  469. "ORMConfig",
  470. "GUI",
  471. "Roughness",
  472. "AO",
  473. "Metalness",
  474. "Glow",
  475. "Particle",
  476. "Decal",
  477. "Cubemap"
  478. };
  479. if (type < 0 || type >= ImageTypeCount)
  480. {
  481. Con::errorf("ImageAsset::getAdapterNameFromType - Invalid ImageType, defaulting to Albedo");
  482. return _names[Albedo];
  483. }
  484. return _names[type];
  485. }
  486. ImageAsset::ImageTypes ImageAsset::getImageTypeFromName(StringTableEntry name)
  487. {
  488. if (dStrIsEmpty(name))
  489. {
  490. return (ImageTypes)Albedo;
  491. }
  492. S32 ret = -1;
  493. for (S32 i = 0; i < ImageTypeCount; i++)
  494. {
  495. if (!dStricmp(getImageTypeNameFromType((ImageTypes)i), name))
  496. ret = i;
  497. }
  498. if (ret == -1)
  499. {
  500. Con::errorf("ImageAsset::getImageTypeFromName - Invalid ImageType name, defaulting to Albedo");
  501. ret = Albedo;
  502. }
  503. return (ImageTypes)ret;
  504. }
  505. void ImageAsset::_onResourceChanged(const Torque::Path& path)
  506. {
  507. if (path != Torque::Path(mImageFile))
  508. return;
  509. refreshAsset();
  510. }
  511. void ImageAsset::onTamlPreWrite(void)
  512. {
  513. // Call parent.
  514. Parent::onTamlPreWrite();
  515. if (isNamedTarget())
  516. return;
  517. // Ensure the image-file is collapsed.
  518. mImageFile = collapseAssetFilePath(mImageFile);
  519. }
  520. void ImageAsset::onTamlPostWrite(void)
  521. {
  522. // Call parent.
  523. Parent::onTamlPostWrite();
  524. if (isNamedTarget())
  525. return;
  526. // Ensure the image-file is expanded.
  527. mImageFile = expandAssetFilePath(mImageFile);
  528. }
  529. void ImageAsset::onTamlCustomWrite(TamlCustomNodes& customNodes)
  530. {
  531. // Debug Profiling.
  532. PROFILE_SCOPE(ImageAsset_OnTamlCustomWrite);
  533. // Call parent.
  534. Parent::onTamlCustomWrite(customNodes);
  535. TamlCustomNode* pImageMetaData = customNodes.addNode(StringTable->insert("ImageMetadata"));
  536. TamlCustomNode* pImageInfoNode = pImageMetaData->addNode(StringTable->insert("ImageInfo"));
  537. pImageInfoNode->addField(StringTable->insert("ImageWidth"), mImageWidth);
  538. pImageInfoNode->addField(StringTable->insert("ImageHeight"), mImageHeight);
  539. pImageInfoNode->addField(StringTable->insert("ImageDepth"), mImageDepth);
  540. }
  541. void ImageAsset::onTamlCustomRead(const TamlCustomNodes& customNodes)
  542. {
  543. // Debug Profiling.
  544. PROFILE_SCOPE(ImageAsset_OnTamlCustomRead);
  545. // Call parent.
  546. Parent::onTamlCustomRead(customNodes);
  547. const TamlCustomNode* pImageMetaDataNode = customNodes.findNode(StringTable->insert("ImageMetadata"));
  548. if (pImageMetaDataNode != NULL)
  549. {
  550. const TamlCustomNode* pImageInfoNode = pImageMetaDataNode->findNode(StringTable->insert("ImageInfo"));
  551. // Fetch fields.
  552. const TamlCustomFieldVector& fields = pImageInfoNode->getFields();
  553. // Iterate property fields.
  554. for (TamlCustomFieldVector::const_iterator fieldItr = fields.begin(); fieldItr != fields.end(); ++fieldItr)
  555. {
  556. // Fetch field.
  557. const TamlCustomField* pField = *fieldItr;
  558. // Fetch field name.
  559. StringTableEntry fieldName = pField->getFieldName();
  560. if (fieldName == StringTable->insert("ImageWidth"))
  561. {
  562. pField->getFieldValue(mImageWidth);
  563. }
  564. else if (fieldName == StringTable->insert("ImageHeight"))
  565. {
  566. pField->getFieldValue(mImageHeight);
  567. }
  568. else if (fieldName == StringTable->insert("ImageDepth"))
  569. {
  570. pField->getFieldValue(mImageDepth);
  571. }
  572. else
  573. {
  574. // Unknown name so warn.
  575. Con::warnf("ImageAsset::onTamlCustomRead() - Encountered an unknown custom field name of '%s'.", fieldName);
  576. continue;
  577. }
  578. }
  579. }
  580. }
  581. const char* ImageAsset::getImageInfo()
  582. {
  583. if (isAssetValid())
  584. {
  585. static const U32 bufSize = 2048;
  586. char* returnBuffer = Con::getReturnBuffer(bufSize);
  587. GFXTexHandle newTex = TEXMGR->createTexture(mImageFile, &GFXStaticTextureSRGBProfile);
  588. if (newTex)
  589. {
  590. dSprintf(returnBuffer, bufSize, "%s %d %d %d", GFXStringTextureFormat[newTex->getFormat()], newTex->getHeight(), newTex->getWidth(), newTex->getDepth());
  591. newTex = nullptr;
  592. }
  593. else
  594. {
  595. dSprintf(returnBuffer, bufSize, "ImageAsset::getImageInfo() - Failed to get image info for %s", getAssetId());
  596. }
  597. return returnBuffer;
  598. }
  599. return "";
  600. }
  601. DefineEngineMethod(ImageAsset, getImagePath, const char*, (), ,
  602. "Gets the image filepath of this asset.\n"
  603. "@return File path of the image file.")
  604. {
  605. return object->getImageFile();
  606. }
  607. DefineEngineMethod(ImageAsset, getImageInfo, const char*, (), ,
  608. "Gets the info and properties of the image.\n"
  609. "@return The info/properties of the image.")
  610. {
  611. return object->getImageInfo();
  612. }
  613. DefineEngineMethod(ImageAsset, isNamedTarget, bool, (), ,
  614. "Gets whether this image is a named target.\n"
  615. "@return bool for isNamedTarget.")
  616. {
  617. return object->isNamedTarget();
  618. }
  619. #ifdef TORQUE_TOOLS
  620. DefineEngineStaticMethod(ImageAsset, getAssetIdByFilename, const char*, (const char* filePath), (""),
  621. "Queries the Asset Database to see if any asset exists that is associated with the provided file path.\n"
  622. "@return The AssetId of the associated asset, if any.")
  623. {
  624. return ImageAsset::getAssetIdByFilename(StringTable->insert(filePath));
  625. }
  626. #endif
  627. //-----------------------------------------------------------------------------
  628. // GuiInspectorTypeAssetId
  629. //-----------------------------------------------------------------------------
  630. IMPLEMENT_CONOBJECT(GuiInspectorTypeImageAssetPtr);
  631. ConsoleDocClass(GuiInspectorTypeImageAssetPtr,
  632. "@brief Inspector field type for Shapes\n\n"
  633. "Editor use only.\n\n"
  634. "@internal"
  635. );
  636. void GuiInspectorTypeImageAssetPtr::consoleInit()
  637. {
  638. Parent::consoleInit();
  639. ConsoleBaseType::getType(TypeImageAssetPtr)->setInspectorFieldType("GuiInspectorTypeImageAssetPtr");
  640. }
  641. GuiControl* GuiInspectorTypeImageAssetPtr::constructEditControl()
  642. {
  643. // Create base filename edit controls
  644. GuiControl* retCtrl = Parent::constructEditControl();
  645. if (retCtrl == NULL)
  646. return retCtrl;
  647. retCtrl->getRenderTooltipDelegate().bind(this, &GuiInspectorTypeImageAssetPtr::renderTooltip);
  648. // Change filespec
  649. char szBuffer[512];
  650. const char* previewImage;
  651. if (mInspector->getInspectObject() != nullptr)
  652. {
  653. dSprintf(szBuffer, sizeof(szBuffer), "AssetBrowser.showDialog(\"ImageAsset\", \"AssetBrowser.changeAsset\", %s);",
  654. getIdString());
  655. mBrowseButton->setField("Command", szBuffer);
  656. setDataField(StringTable->insert("targetObject"), NULL, mInspector->getInspectObject()->getIdString());
  657. previewImage = getData();
  658. }
  659. else
  660. {
  661. //if we don't have a target object, we'll be manipulating the desination value directly
  662. dSprintf(szBuffer, sizeof(szBuffer), "AssetBrowser.showDialog(\"ImageAsset\", \"AssetBrowser.changeAsset\", %s, \"%s\");",
  663. mInspector->getIdString(), mVariableName);
  664. mBrowseButton->setField("Command", szBuffer);
  665. previewImage = Con::getVariable(mVariableName);
  666. }
  667. mLabel = new GuiTextCtrl();
  668. mLabel->registerObject();
  669. mLabel->setControlProfile(mProfile);
  670. mLabel->setText(mCaption);
  671. addObject(mLabel);
  672. //
  673. GuiTextEditCtrl* editTextCtrl = static_cast<GuiTextEditCtrl*>(retCtrl);
  674. GuiControlProfile* toolEditProfile;
  675. if (Sim::findObject("ToolsGuiTextEditProfile", toolEditProfile))
  676. editTextCtrl->setControlProfile(toolEditProfile);
  677. GuiControlProfile* toolDefaultProfile = nullptr;
  678. Sim::findObject("ToolsGuiDefaultProfile", toolDefaultProfile);
  679. //
  680. mPreviewImage = new GuiBitmapCtrl();
  681. mPreviewImage->registerObject();
  682. if (toolDefaultProfile)
  683. mPreviewImage->setControlProfile(toolDefaultProfile);
  684. updatePreviewImage();
  685. addObject(mPreviewImage);
  686. //
  687. mPreviewBorderButton = new GuiBitmapButtonCtrl();
  688. mPreviewBorderButton->registerObject();
  689. if (toolDefaultProfile)
  690. mPreviewBorderButton->setControlProfile(toolDefaultProfile);
  691. mPreviewBorderButton->_setBitmap(StringTable->insert("ToolsModule:cubemapBtnBorder_n_image"));
  692. mPreviewBorderButton->setField("Command", szBuffer); //clicking the preview does the same thing as the edit button, for simplicity
  693. addObject(mPreviewBorderButton);
  694. //
  695. // Create "Open in Editor" button
  696. /*mEditButton = new GuiBitmapButtonCtrl();
  697. dSprintf(szBuffer, sizeof(szBuffer), "AssetBrowser.editAsset(%d.getText());", retCtrl->getId());
  698. mEditButton->setField("Command", szBuffer);
  699. mEditButton->setText("Edit");
  700. mEditButton->setSizing(horizResizeLeft, vertResizeAspectTop);
  701. mEditButton->setDataField(StringTable->insert("Profile"), NULL, "ToolsGuiButtonProfile");
  702. mEditButton->setDataField(StringTable->insert("tooltipprofile"), NULL, "GuiToolTipProfile");
  703. mEditButton->setDataField(StringTable->insert("hovertime"), NULL, "1000");
  704. mEditButton->setDataField(StringTable->insert("tooltip"), NULL, "Open this asset in the Image Editor");
  705. mEditButton->registerObject();
  706. addObject(mEditButton);*/
  707. //
  708. mUseHeightOverride = true;
  709. mHeightOverride = 72;
  710. return retCtrl;
  711. }
  712. bool GuiInspectorTypeImageAssetPtr::updateRects()
  713. {
  714. S32 rowSize = 18;
  715. S32 dividerPos, dividerMargin;
  716. mInspector->getDivider(dividerPos, dividerMargin);
  717. Point2I fieldExtent = getExtent();
  718. Point2I fieldPos = getPosition();
  719. mEditCtrlRect.set(0, 0, fieldExtent.x, fieldExtent.y);
  720. mLabel->resize(Point2I(mProfile->mTextOffset.x, 0), Point2I(fieldExtent.x, rowSize));
  721. RectI previewRect = RectI(Point2I(mProfile->mTextOffset.x, rowSize), Point2I(50, 50));
  722. mPreviewBorderButton->resize(previewRect.point, previewRect.extent);
  723. mPreviewImage->resize(previewRect.point, previewRect.extent);
  724. S32 editPos = previewRect.point.x + previewRect.extent.x + 10;
  725. mEdit->resize(Point2I(editPos, rowSize * 1.5), Point2I(fieldExtent.x - editPos - 5, rowSize));
  726. //mEditButton->resize(Point2I(fieldExtent.x - 105, previewRect.point.y + previewRect.extent.y - rowSize), Point2I(100, rowSize));
  727. mBrowseButton->setHidden(true);
  728. return true;
  729. }
  730. bool GuiInspectorTypeImageAssetPtr::renderTooltip(const Point2I& hoverPos, const Point2I& cursorPos, const char* tipText)
  731. {
  732. if (!mAwake)
  733. return false;
  734. GuiCanvas* root = getRoot();
  735. if (!root)
  736. return false;
  737. AssetPtr<ImageAsset> imgAsset;
  738. U32 assetState = ImageAsset::getAssetById(getData(), &imgAsset);
  739. if (imgAsset == NULL || assetState == ImageAsset::Failed)
  740. return false;
  741. StringTableEntry filename = imgAsset->getImageFile();
  742. if (!filename || !filename[0])
  743. return false;
  744. StringTableEntry previewFilename = filename;
  745. if (Con::isFunction("getAssetPreviewImage"))
  746. {
  747. ConsoleValue consoleRet = Con::executef("getAssetPreviewImage", filename);
  748. previewFilename = StringTable->insert(consoleRet.getString());
  749. if (AssetDatabase.isDeclaredAsset(previewFilename))
  750. {
  751. ImageAsset* previewAsset = AssetDatabase.acquireAsset<ImageAsset>(previewFilename);
  752. previewFilename = previewAsset->getImageFile();
  753. }
  754. }
  755. GFXTexHandle texture(previewFilename, &GFXStaticTextureSRGBProfile, avar("%s() - tooltip texture (line %d)", __FUNCTION__, __LINE__));
  756. if (texture.isNull())
  757. return false;
  758. // Render image at a reasonable screen size while
  759. // keeping its aspect ratio...
  760. Point2I screensize = getRoot()->getWindowSize();
  761. Point2I offset = hoverPos;
  762. Point2I tipBounds;
  763. U32 texWidth = texture.getWidth();
  764. U32 texHeight = texture.getHeight();
  765. F32 aspect = (F32)texHeight / (F32)texWidth;
  766. const F32 newWidth = 150.0f;
  767. F32 newHeight = aspect * newWidth;
  768. // Offset below cursor image
  769. offset.y += 20; // TODO: Attempt to fix?: root->getCursorExtent().y;
  770. tipBounds.x = newWidth;
  771. tipBounds.y = newHeight;
  772. // Make sure all of the tooltip will be rendered width the app window,
  773. // 5 is given as a buffer against the edge
  774. if (screensize.x < offset.x + tipBounds.x + 5)
  775. offset.x = screensize.x - tipBounds.x - 5;
  776. if (screensize.y < offset.y + tipBounds.y + 5)
  777. offset.y = hoverPos.y - tipBounds.y - 5;
  778. RectI oldClip = GFX->getClipRect();
  779. RectI rect(offset, tipBounds);
  780. GFX->setClipRect(rect);
  781. GFXDrawUtil* drawer = GFX->getDrawUtil();
  782. drawer->clearBitmapModulation();
  783. GFX->getDrawUtil()->drawBitmapStretch(texture, rect);
  784. GFX->setClipRect(oldClip);
  785. return true;
  786. }
  787. void GuiInspectorTypeImageAssetPtr::updateValue()
  788. {
  789. Parent::updateValue();
  790. updatePreviewImage();
  791. }
  792. void GuiInspectorTypeImageAssetPtr::updatePreviewImage()
  793. {
  794. const char* previewImage;
  795. if (mInspector->getInspectObject() != nullptr)
  796. previewImage = getData();
  797. else
  798. previewImage = Con::getVariable(mVariableName);
  799. //if what we're working with isn't even a valid asset, don't present like we found a good one
  800. if (!AssetDatabase.isDeclaredAsset(previewImage))
  801. {
  802. mPreviewImage->_setBitmap(StringTable->EmptyString());
  803. return;
  804. }
  805. String imgPreviewAssetId = String(previewImage) + "_PreviewImage";
  806. imgPreviewAssetId.replace(":", "_");
  807. imgPreviewAssetId = "ToolsModule:" + imgPreviewAssetId;
  808. if (AssetDatabase.isDeclaredAsset(imgPreviewAssetId.c_str()))
  809. {
  810. mPreviewImage->setBitmap(StringTable->insert(imgPreviewAssetId.c_str()));
  811. }
  812. else
  813. {
  814. if (AssetDatabase.isDeclaredAsset(previewImage))
  815. {
  816. mPreviewImage->_setBitmap(previewImage);
  817. }
  818. }
  819. if (mPreviewImage->getBitmapAsset().isNull())
  820. mPreviewImage->_setBitmap(StringTable->insert("ToolsModule:genericAssetIcon_image"));
  821. }
  822. void GuiInspectorTypeImageAssetPtr::setPreviewImage(StringTableEntry assetId)
  823. {
  824. //if what we're working with isn't even a valid asset, don't present like we found a good one
  825. if (!AssetDatabase.isDeclaredAsset(assetId))
  826. {
  827. mPreviewImage->_setBitmap(StringTable->EmptyString());
  828. return;
  829. }
  830. String imgPreviewAssetId = String(assetId) + "_PreviewImage";
  831. imgPreviewAssetId.replace(":", "_");
  832. imgPreviewAssetId = "ToolsModule:" + imgPreviewAssetId;
  833. if (AssetDatabase.isDeclaredAsset(imgPreviewAssetId.c_str()))
  834. {
  835. mPreviewImage->setBitmap(StringTable->insert(imgPreviewAssetId.c_str()));
  836. }
  837. else
  838. {
  839. if (AssetDatabase.isDeclaredAsset(assetId))
  840. {
  841. mPreviewImage->_setBitmap(assetId);
  842. }
  843. }
  844. if (mPreviewImage->getBitmapAsset().isNull())
  845. mPreviewImage->_setBitmap(StringTable->insert("ToolsModule:genericAssetIcon_image"));
  846. }