ImageAsset.cpp 27 KB

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