ImageAsset.cpp 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  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.getPath() == temp2.getPath() && 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. //-----------------------------------------------------------------------------
  627. // GuiInspectorTypeAssetId
  628. //-----------------------------------------------------------------------------
  629. IMPLEMENT_CONOBJECT(GuiInspectorTypeImageAssetPtr);
  630. ConsoleDocClass(GuiInspectorTypeImageAssetPtr,
  631. "@brief Inspector field type for Shapes\n\n"
  632. "Editor use only.\n\n"
  633. "@internal"
  634. );
  635. void GuiInspectorTypeImageAssetPtr::consoleInit()
  636. {
  637. Parent::consoleInit();
  638. ConsoleBaseType::getType(TypeImageAssetPtr)->setInspectorFieldType("GuiInspectorTypeImageAssetPtr");
  639. }
  640. GuiControl* GuiInspectorTypeImageAssetPtr::constructEditControl()
  641. {
  642. // Create base filename edit controls
  643. GuiControl* retCtrl = Parent::constructEditControl();
  644. if (retCtrl == NULL)
  645. return retCtrl;
  646. retCtrl->getRenderTooltipDelegate().bind(this, &GuiInspectorTypeImageAssetPtr::renderTooltip);
  647. // Change filespec
  648. char szBuffer[512];
  649. const char* previewImage;
  650. if (mInspector->getInspectObject() != nullptr)
  651. {
  652. dSprintf(szBuffer, sizeof(szBuffer), "AssetBrowser.showDialog(\"ImageAsset\", \"AssetBrowser.changeAsset\", %s);",
  653. getIdString());
  654. mBrowseButton->setField("Command", szBuffer);
  655. setDataField(StringTable->insert("targetObject"), NULL, mInspector->getInspectObject()->getIdString());
  656. previewImage = getData();
  657. }
  658. else
  659. {
  660. //if we don't have a target object, we'll be manipulating the desination value directly
  661. dSprintf(szBuffer, sizeof(szBuffer), "AssetBrowser.showDialog(\"ImageAsset\", \"AssetBrowser.changeAsset\", %s, \"%s\");",
  662. mInspector->getIdString(), mVariableName);
  663. mBrowseButton->setField("Command", szBuffer);
  664. previewImage = Con::getVariable(mVariableName);
  665. }
  666. mLabel = new GuiTextCtrl();
  667. mLabel->registerObject();
  668. mLabel->setControlProfile(mProfile);
  669. mLabel->setText(mCaption);
  670. addObject(mLabel);
  671. //
  672. GuiTextEditCtrl* editTextCtrl = static_cast<GuiTextEditCtrl*>(retCtrl);
  673. GuiControlProfile* toolEditProfile;
  674. if (Sim::findObject("ToolsGuiTextEditProfile", toolEditProfile))
  675. editTextCtrl->setControlProfile(toolEditProfile);
  676. GuiControlProfile* toolDefaultProfile = nullptr;
  677. Sim::findObject("ToolsGuiDefaultProfile", toolDefaultProfile);
  678. //
  679. mPreviewImage = new GuiBitmapCtrl();
  680. mPreviewImage->registerObject();
  681. if (toolDefaultProfile)
  682. mPreviewImage->setControlProfile(toolDefaultProfile);
  683. updatePreviewImage();
  684. addObject(mPreviewImage);
  685. //
  686. mPreviewBorderButton = new GuiBitmapButtonCtrl();
  687. mPreviewBorderButton->registerObject();
  688. if (toolDefaultProfile)
  689. mPreviewBorderButton->setControlProfile(toolDefaultProfile);
  690. mPreviewBorderButton->_setBitmap(StringTable->insert("ToolsModule:cubemapBtnBorder_n_image"));
  691. mPreviewBorderButton->setField("Command", szBuffer); //clicking the preview does the same thing as the edit button, for simplicity
  692. addObject(mPreviewBorderButton);
  693. //
  694. // Create "Open in Editor" button
  695. /*mEditButton = new GuiBitmapButtonCtrl();
  696. dSprintf(szBuffer, sizeof(szBuffer), "AssetBrowser.editAsset(%d.getText());", retCtrl->getId());
  697. mEditButton->setField("Command", szBuffer);
  698. mEditButton->setText("Edit");
  699. mEditButton->setSizing(horizResizeLeft, vertResizeAspectTop);
  700. mEditButton->setDataField(StringTable->insert("Profile"), NULL, "ToolsGuiButtonProfile");
  701. mEditButton->setDataField(StringTable->insert("tooltipprofile"), NULL, "GuiToolTipProfile");
  702. mEditButton->setDataField(StringTable->insert("hovertime"), NULL, "1000");
  703. mEditButton->setDataField(StringTable->insert("tooltip"), NULL, "Open this asset in the Image Editor");
  704. mEditButton->registerObject();
  705. addObject(mEditButton);*/
  706. //
  707. mUseHeightOverride = true;
  708. mHeightOverride = 72;
  709. return retCtrl;
  710. }
  711. bool GuiInspectorTypeImageAssetPtr::updateRects()
  712. {
  713. S32 rowSize = 18;
  714. S32 dividerPos, dividerMargin;
  715. mInspector->getDivider(dividerPos, dividerMargin);
  716. Point2I fieldExtent = getExtent();
  717. Point2I fieldPos = getPosition();
  718. mEditCtrlRect.set(0, 0, fieldExtent.x, fieldExtent.y);
  719. mLabel->resize(Point2I(mProfile->mTextOffset.x, 0), Point2I(fieldExtent.x, rowSize));
  720. RectI previewRect = RectI(Point2I(mProfile->mTextOffset.x, rowSize), Point2I(50, 50));
  721. mPreviewBorderButton->resize(previewRect.point, previewRect.extent);
  722. mPreviewImage->resize(previewRect.point, previewRect.extent);
  723. S32 editPos = previewRect.point.x + previewRect.extent.x + 10;
  724. mEdit->resize(Point2I(editPos, rowSize * 1.5), Point2I(fieldExtent.x - editPos - 5, rowSize));
  725. //mEditButton->resize(Point2I(fieldExtent.x - 105, previewRect.point.y + previewRect.extent.y - rowSize), Point2I(100, rowSize));
  726. mBrowseButton->setHidden(true);
  727. return true;
  728. }
  729. bool GuiInspectorTypeImageAssetPtr::renderTooltip(const Point2I& hoverPos, const Point2I& cursorPos, const char* tipText)
  730. {
  731. if (!mAwake)
  732. return false;
  733. GuiCanvas* root = getRoot();
  734. if (!root)
  735. return false;
  736. AssetPtr<ImageAsset> imgAsset;
  737. U32 assetState = ImageAsset::getAssetById(getData(), &imgAsset);
  738. if (imgAsset == NULL || assetState == ImageAsset::Failed)
  739. return false;
  740. StringTableEntry filename = imgAsset->getImageFile();
  741. if (!filename || !filename[0])
  742. return false;
  743. StringTableEntry previewFilename = filename;
  744. if (Con::isFunction("getAssetPreviewImage"))
  745. {
  746. ConsoleValue consoleRet = Con::executef("getAssetPreviewImage", filename);
  747. previewFilename = StringTable->insert(consoleRet.getString());
  748. if (AssetDatabase.isDeclaredAsset(previewFilename))
  749. {
  750. ImageAsset* previewAsset = AssetDatabase.acquireAsset<ImageAsset>(previewFilename);
  751. previewFilename = previewAsset->getImageFile();
  752. }
  753. }
  754. GFXTexHandle texture(previewFilename, &GFXStaticTextureSRGBProfile, avar("%s() - tooltip texture (line %d)", __FUNCTION__, __LINE__));
  755. if (texture.isNull())
  756. return false;
  757. // Render image at a reasonable screen size while
  758. // keeping its aspect ratio...
  759. Point2I screensize = getRoot()->getWindowSize();
  760. Point2I offset = hoverPos;
  761. Point2I tipBounds;
  762. U32 texWidth = texture.getWidth();
  763. U32 texHeight = texture.getHeight();
  764. F32 aspect = (F32)texHeight / (F32)texWidth;
  765. const F32 newWidth = 150.0f;
  766. F32 newHeight = aspect * newWidth;
  767. // Offset below cursor image
  768. offset.y += 20; // TODO: Attempt to fix?: root->getCursorExtent().y;
  769. tipBounds.x = newWidth;
  770. tipBounds.y = newHeight;
  771. // Make sure all of the tooltip will be rendered width the app window,
  772. // 5 is given as a buffer against the edge
  773. if (screensize.x < offset.x + tipBounds.x + 5)
  774. offset.x = screensize.x - tipBounds.x - 5;
  775. if (screensize.y < offset.y + tipBounds.y + 5)
  776. offset.y = hoverPos.y - tipBounds.y - 5;
  777. RectI oldClip = GFX->getClipRect();
  778. RectI rect(offset, tipBounds);
  779. GFX->setClipRect(rect);
  780. GFXDrawUtil* drawer = GFX->getDrawUtil();
  781. drawer->clearBitmapModulation();
  782. GFX->getDrawUtil()->drawBitmapStretch(texture, rect);
  783. GFX->setClipRect(oldClip);
  784. return true;
  785. }
  786. void GuiInspectorTypeImageAssetPtr::updateValue()
  787. {
  788. Parent::updateValue();
  789. updatePreviewImage();
  790. }
  791. void GuiInspectorTypeImageAssetPtr::updatePreviewImage()
  792. {
  793. const char* previewImage;
  794. if (mInspector->getInspectObject() != nullptr)
  795. previewImage = getData();
  796. else
  797. previewImage = Con::getVariable(mVariableName);
  798. //if what we're working with isn't even a valid asset, don't present like we found a good one
  799. if (!AssetDatabase.isDeclaredAsset(previewImage))
  800. {
  801. mPreviewImage->_setBitmap(StringTable->EmptyString());
  802. return;
  803. }
  804. String imgPreviewAssetId = String(previewImage) + "_PreviewImage";
  805. imgPreviewAssetId.replace(":", "_");
  806. imgPreviewAssetId = "ToolsModule:" + imgPreviewAssetId;
  807. if (AssetDatabase.isDeclaredAsset(imgPreviewAssetId.c_str()))
  808. {
  809. mPreviewImage->setBitmap(StringTable->insert(imgPreviewAssetId.c_str()));
  810. }
  811. else
  812. {
  813. if (AssetDatabase.isDeclaredAsset(previewImage))
  814. {
  815. mPreviewImage->_setBitmap(previewImage);
  816. }
  817. }
  818. if (mPreviewImage->getBitmapAsset().isNull())
  819. mPreviewImage->_setBitmap(StringTable->insert("ToolsModule:genericAssetIcon_image"));
  820. }
  821. void GuiInspectorTypeImageAssetPtr::setPreviewImage(StringTableEntry assetId)
  822. {
  823. //if what we're working with isn't even a valid asset, don't present like we found a good one
  824. if (!AssetDatabase.isDeclaredAsset(assetId))
  825. {
  826. mPreviewImage->_setBitmap(StringTable->EmptyString());
  827. return;
  828. }
  829. String imgPreviewAssetId = String(assetId) + "_PreviewImage";
  830. imgPreviewAssetId.replace(":", "_");
  831. imgPreviewAssetId = "ToolsModule:" + imgPreviewAssetId;
  832. if (AssetDatabase.isDeclaredAsset(imgPreviewAssetId.c_str()))
  833. {
  834. mPreviewImage->setBitmap(StringTable->insert(imgPreviewAssetId.c_str()));
  835. }
  836. else
  837. {
  838. if (AssetDatabase.isDeclaredAsset(assetId))
  839. {
  840. mPreviewImage->_setBitmap(assetId);
  841. }
  842. }
  843. if (mPreviewImage->getBitmapAsset().isNull())
  844. mPreviewImage->_setBitmap(StringTable->insert("ToolsModule:genericAssetIcon_image"));
  845. }
  846. #endif