ImageAsset.cpp 24 KB

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