MaterialAsset.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. #pragma once
  23. #ifndef MATERIALASSET_H
  24. #include "MaterialAsset.h"
  25. #endif
  26. #ifndef _ASSET_MANAGER_H_
  27. #include "assets/assetManager.h"
  28. #endif
  29. #ifndef _CONSOLETYPES_H_
  30. #include "console/consoleTypes.h"
  31. #endif
  32. #ifndef _TAML_
  33. #include "persistence/taml/taml.h"
  34. #endif
  35. #ifndef _ASSET_PTR_H_
  36. #include "assets/assetPtr.h"
  37. #endif
  38. #include "T3D/assets/assetImporter.h"
  39. StringTableEntry MaterialAsset::smNoMaterialAssetFallback = NULL;
  40. //-----------------------------------------------------------------------------
  41. IMPLEMENT_CONOBJECT(MaterialAsset);
  42. ConsoleType(MaterialAssetPtr, TypeMaterialAssetPtr, MaterialAsset, ASSET_ID_FIELD_PREFIX)
  43. //-----------------------------------------------------------------------------
  44. ConsoleGetType(TypeMaterialAssetPtr)
  45. {
  46. // Fetch asset Id.
  47. return (*((AssetPtr<MaterialAsset>*)dptr)).getAssetId();
  48. }
  49. //-----------------------------------------------------------------------------
  50. ConsoleSetType(TypeMaterialAssetPtr)
  51. {
  52. // Was a single argument specified?
  53. if (argc == 1)
  54. {
  55. // Yes, so fetch field value.
  56. const char* pFieldValue = argv[0];
  57. // Fetch asset pointer.
  58. AssetPtr<MaterialAsset>* pAssetPtr = dynamic_cast<AssetPtr<MaterialAsset>*>((AssetPtrBase*)(dptr));
  59. // Is the asset pointer the correct type?
  60. if (pAssetPtr == NULL)
  61. {
  62. // No, so fail.
  63. //Con::warnf("(TypeMaterialAssetPtr) - Failed to set asset Id '%d'.", pFieldValue);
  64. return;
  65. }
  66. // Set asset.
  67. pAssetPtr->setAssetId(pFieldValue);
  68. return;
  69. }
  70. // Warn.
  71. Con::warnf("(TypeMaterialAssetPtr) - Cannot set multiple args to a single asset.");
  72. }
  73. ConsoleType(assetIdString, TypeMaterialAssetId, const char*, ASSET_ID_FIELD_PREFIX)
  74. ConsoleGetType(TypeMaterialAssetId)
  75. {
  76. // Fetch asset Id.
  77. return *((const char**)(dptr));
  78. }
  79. ConsoleSetType(TypeMaterialAssetId)
  80. {
  81. // Was a single argument specified?
  82. if (argc == 1)
  83. {
  84. // Yes, so fetch field value.
  85. const char* pFieldValue = argv[0];
  86. // Fetch asset Id.
  87. StringTableEntry* assetId = (StringTableEntry*)(dptr);
  88. // Update asset value.
  89. *assetId = StringTable->insert(pFieldValue);
  90. return;
  91. }
  92. // Warn.
  93. Con::warnf("(TypeMaterialAssetId) - Cannot set multiple args to a single asset.");
  94. }
  95. //-----------------------------------------------------------------------------
  96. MaterialAsset::MaterialAsset()
  97. {
  98. mShaderGraphFile = "";
  99. mScriptFile = StringTable->EmptyString();
  100. mScriptPath = StringTable->EmptyString();
  101. mMatDefinitionName = StringTable->EmptyString();
  102. mMaterialDefinition = nullptr;
  103. }
  104. //-----------------------------------------------------------------------------
  105. MaterialAsset::~MaterialAsset()
  106. {
  107. //SAFE_DELETE(mMaterialDefinition);
  108. }
  109. //-----------------------------------------------------------------------------
  110. void MaterialAsset::consoleInit()
  111. {
  112. Parent::consoleInit();
  113. Con::addVariable("$Core::NoMaterialAssetFallback", TypeString, &smNoMaterialAssetFallback,
  114. "The assetId of the material to display when the requested material asset is missing.\n"
  115. "@ingroup GFX\n");
  116. smNoMaterialAssetFallback = StringTable->insert(Con::getVariable("$Core::NoMaterialAssetFallback"));
  117. }
  118. void MaterialAsset::initPersistFields()
  119. {
  120. // Call parent.
  121. Parent::initPersistFields();
  122. //addField("shaderGraph", TypeRealString, Offset(mShaderGraphFile, MaterialAsset), "");
  123. addProtectedField("scriptFile", TypeAssetLooseFilePath, Offset(mScriptFile, MaterialAsset),
  124. &setScriptFile, &getScriptFile, "Path to the file containing the material definition.");
  125. addField("materialDefinitionName", TypeString, Offset(mMatDefinitionName, MaterialAsset), "Name of the material definition this asset is for.");
  126. }
  127. void MaterialAsset::initializeAsset()
  128. {
  129. // Call parent.
  130. Parent::initializeAsset();
  131. mScriptPath = getOwned() ? expandAssetFilePath(mScriptFile) : mScriptPath;
  132. if (Torque::FS::IsScriptFile(mScriptPath))
  133. {
  134. if (!Sim::findObject(mMatDefinitionName))
  135. if (Con::executeFile(mScriptPath, false, false))
  136. mLoadedState = ScriptLoaded;
  137. else
  138. mLoadedState = Failed;
  139. }
  140. loadMaterial();
  141. }
  142. void MaterialAsset::onAssetRefresh()
  143. {
  144. mScriptPath = getOwned() ? expandAssetFilePath(mScriptFile) : mScriptPath;
  145. if (Torque::FS::IsScriptFile(mScriptPath))
  146. {
  147. //Since we're refreshing, we can assume that the file we're executing WILL have an existing definition.
  148. //But that definition, whatever it is, is the 'correct' one, so we enable the Replace Existing behavior
  149. //when the engine encounters a named object conflict.
  150. String redefineBehaviorPrev = Con::getVariable("$Con::redefineBehavior");
  151. Con::setVariable("$Con::redefineBehavior", "replaceExisting");
  152. if (Con::executeFile(mScriptPath, false, false))
  153. mLoadedState = ScriptLoaded;
  154. else
  155. mLoadedState = Failed;
  156. //And now that we've executed, switch back to the prior behavior
  157. Con::setVariable("$Con::redefineBehavior", redefineBehaviorPrev.c_str());
  158. }
  159. loadMaterial();
  160. }
  161. void MaterialAsset::setScriptFile(const char* pScriptFile)
  162. {
  163. // Sanity!
  164. AssertFatal(pScriptFile != NULL, "Cannot use a NULL script file.");
  165. // Fetch image file.
  166. pScriptFile = StringTable->insert(pScriptFile, true);
  167. // Update.
  168. mScriptFile = getOwned() ? expandAssetFilePath(pScriptFile) : pScriptFile;
  169. // Refresh the asset.
  170. refreshAsset();
  171. }
  172. //------------------------------------------------------------------------------
  173. void MaterialAsset::loadMaterial()
  174. {
  175. if (mMaterialDefinition)
  176. SAFE_DELETE(mMaterialDefinition);
  177. if (mLoadedState == ScriptLoaded && mMatDefinitionName != StringTable->EmptyString())
  178. {
  179. Material* matDef;
  180. if (!Sim::findObject(mMatDefinitionName, matDef))
  181. {
  182. Con::errorf("MaterialAsset: Unable to find the Material %s", mMatDefinitionName);
  183. mLoadedState = BadFileReference;
  184. return;
  185. }
  186. mMaterialDefinition = matDef;
  187. mLoadedState = Ok;
  188. mMaterialDefinition->reload();
  189. return;
  190. }
  191. mLoadedState = Failed;
  192. }
  193. //------------------------------------------------------------------------------
  194. void MaterialAsset::copyTo(SimObject* object)
  195. {
  196. // Call to parent.
  197. Parent::copyTo(object);
  198. }
  199. //------------------------------------------------------------------------------
  200. U32 MaterialAsset::getAssetByMaterialName(StringTableEntry matName, AssetPtr<MaterialAsset>* matAsset)
  201. {
  202. AssetQuery query;
  203. U32 foundAssetcount = AssetDatabase.findAssetType(&query, "MaterialAsset");
  204. if (foundAssetcount == 0)
  205. {
  206. //Didn't work, so have us fall back to a placeholder asset
  207. matAsset->setAssetId(MaterialAsset::smNoMaterialAssetFallback);
  208. if (matAsset->isNull())
  209. {
  210. //Well that's bad, loading the fallback failed.
  211. Con::warnf("MaterialAsset::getAssetByMaterialName - Finding of asset associated with material name %s failed with no fallback asset", matName);
  212. return AssetErrCode::Failed;
  213. }
  214. //handle noshape not being loaded itself
  215. if ((*matAsset)->mLoadedState == BadFileReference)
  216. {
  217. Con::warnf("ShapeAsset::getAssetByMaterialName - Finding of associated with aterial name %s failed, and fallback asset reported error of Bad File Reference.", matName);
  218. return AssetErrCode::BadFileReference;
  219. }
  220. Con::warnf("ShapeAsset::getAssetByMaterialName - Finding of associated with aterial name %s failed, utilizing fallback asset", matName);
  221. (*matAsset)->mLoadedState = AssetErrCode::UsingFallback;
  222. return AssetErrCode::UsingFallback;
  223. }
  224. else
  225. {
  226. for (U32 i = 0; i < foundAssetcount; i++)
  227. {
  228. MaterialAsset* tMatAsset = AssetDatabase.acquireAsset<MaterialAsset>(query.mAssetList[i]);
  229. if (tMatAsset && tMatAsset->getMaterialDefinitionName() == matName)
  230. {
  231. matAsset->setAssetId(query.mAssetList[i]);
  232. AssetDatabase.releaseAsset(query.mAssetList[i]);
  233. return (*matAsset)->mLoadedState;
  234. }
  235. AssetDatabase.releaseAsset(query.mAssetList[i]); //cleanup if that's not the one we needed
  236. }
  237. }
  238. }
  239. StringTableEntry MaterialAsset::getAssetIdByMaterialName(StringTableEntry matName)
  240. {
  241. if (matName == StringTable->EmptyString())
  242. return StringTable->EmptyString();
  243. StringTableEntry materialAssetId = MaterialAsset::smNoMaterialAssetFallback;
  244. AssetQuery query;
  245. U32 foundCount = AssetDatabase.findAssetType(&query, "MaterialAsset");
  246. if (foundCount != 0)
  247. {
  248. for (U32 i = 0; i < foundCount; i++)
  249. {
  250. MaterialAsset* matAsset = AssetDatabase.acquireAsset<MaterialAsset>(query.mAssetList[i]);
  251. if (matAsset && matAsset->getMaterialDefinitionName() == matName)
  252. {
  253. materialAssetId = matAsset->getAssetId();
  254. AssetDatabase.releaseAsset(query.mAssetList[i]);
  255. break;
  256. }
  257. AssetDatabase.releaseAsset(query.mAssetList[i]);
  258. }
  259. }
  260. return materialAssetId;
  261. }
  262. U32 MaterialAsset::getAssetById(StringTableEntry assetId, AssetPtr<MaterialAsset>* materialAsset)
  263. {
  264. (*materialAsset) = assetId;
  265. if (materialAsset->notNull())
  266. {
  267. return (*materialAsset)->mLoadedState;
  268. }
  269. else
  270. {
  271. //Didn't work, so have us fall back to a placeholder asset
  272. materialAsset->setAssetId(MaterialAsset::smNoMaterialAssetFallback);
  273. if (materialAsset->isNull())
  274. {
  275. //Well that's bad, loading the fallback failed.
  276. Con::warnf("MaterialAsset::getAssetById - Finding of asset with id %s failed with no fallback asset", assetId);
  277. return AssetErrCode::Failed;
  278. }
  279. //handle noshape not being loaded itself
  280. if ((*materialAsset)->mLoadedState == BadFileReference)
  281. {
  282. Con::warnf("MaterialAsset::getAssetById - Finding of asset with id %s failed, and fallback asset reported error of Bad File Reference.", assetId);
  283. return AssetErrCode::BadFileReference;
  284. }
  285. Con::warnf("MaterialAsset::getAssetById - Finding of asset with id %s failed, utilizing fallback asset", assetId);
  286. (*materialAsset)->mLoadedState = AssetErrCode::UsingFallback;
  287. return AssetErrCode::UsingFallback;
  288. }
  289. }
  290. #ifdef TORQUE_TOOLS
  291. DefineEngineStaticMethod(MaterialAsset, getAssetIdByMaterialName, const char*, (const char* materialName), (""),
  292. "Queries the Asset Database to see if any asset exists that is associated with the provided material name.\n"
  293. "@return The AssetId of the associated asset, if any.")
  294. {
  295. return MaterialAsset::getAssetIdByMaterialName(StringTable->insert(materialName));
  296. }
  297. DefineEngineMethod(MaterialAsset, getScriptPath, const char*, (), ,
  298. "Queries the Asset Database to see if any asset exists that is associated with the provided material name.\n"
  299. "@return The AssetId of the associated asset, if any.")
  300. {
  301. return object->getScriptPath();
  302. }
  303. #endif
  304. //-----------------------------------------------------------------------------
  305. // GuiInspectorTypeAssetId
  306. //-----------------------------------------------------------------------------
  307. IMPLEMENT_CONOBJECT(GuiInspectorTypeMaterialAssetPtr);
  308. ConsoleDocClass(GuiInspectorTypeMaterialAssetPtr,
  309. "@brief Inspector field type for Shapes\n\n"
  310. "Editor use only.\n\n"
  311. "@internal"
  312. );
  313. void GuiInspectorTypeMaterialAssetPtr::consoleInit()
  314. {
  315. Parent::consoleInit();
  316. ConsoleBaseType::getType(TypeMaterialAssetPtr)->setInspectorFieldType("GuiInspectorTypeMaterialAssetPtr");
  317. }
  318. GuiControl* GuiInspectorTypeMaterialAssetPtr::constructEditControl()
  319. {
  320. // Create base filename edit controls
  321. GuiControl* retCtrl = Parent::constructEditControl();
  322. if (retCtrl == NULL)
  323. return retCtrl;
  324. // Change filespec
  325. char szBuffer[512];
  326. dSprintf(szBuffer, sizeof(szBuffer), "AssetBrowser.showDialog(\"MaterialAsset\", \"AssetBrowser.changeAsset\", %s, \"\");",
  327. getIdString());
  328. mBrowseButton->setField("Command", szBuffer);
  329. setDataField(StringTable->insert("targetObject"), NULL, mInspector->getInspectObject()->getIdString());
  330. // Create "Open in Editor" button
  331. mEditButton = new GuiBitmapButtonCtrl();
  332. dSprintf(szBuffer, sizeof(szBuffer), "AssetBrowser.editAsset(%d.getText());", retCtrl->getId());
  333. mEditButton->setField("Command", szBuffer);
  334. char bitmapName[512] = "ToolsModule:material_editor_n_image";
  335. mEditButton->setBitmap(StringTable->insert(bitmapName));
  336. mEditButton->setDataField(StringTable->insert("Profile"), NULL, "GuiButtonProfile");
  337. mEditButton->setDataField(StringTable->insert("tooltipprofile"), NULL, "GuiToolTipProfile");
  338. mEditButton->setDataField(StringTable->insert("hovertime"), NULL, "1000");
  339. mEditButton->setDataField(StringTable->insert("tooltip"), NULL, "Open this asset in the Material Editor");
  340. mEditButton->registerObject();
  341. addObject(mEditButton);
  342. return retCtrl;
  343. }
  344. bool GuiInspectorTypeMaterialAssetPtr::updateRects()
  345. {
  346. S32 dividerPos, dividerMargin;
  347. mInspector->getDivider(dividerPos, dividerMargin);
  348. Point2I fieldExtent = getExtent();
  349. Point2I fieldPos = getPosition();
  350. mCaptionRect.set(0, 0, fieldExtent.x - dividerPos - dividerMargin, fieldExtent.y);
  351. mEditCtrlRect.set(fieldExtent.x - dividerPos + dividerMargin, 1, dividerPos - dividerMargin - 34, fieldExtent.y);
  352. bool resized = mEdit->resize(mEditCtrlRect.point, mEditCtrlRect.extent);
  353. if (mBrowseButton != NULL)
  354. {
  355. mBrowseRect.set(fieldExtent.x - 32, 2, 14, fieldExtent.y - 4);
  356. resized |= mBrowseButton->resize(mBrowseRect.point, mBrowseRect.extent);
  357. }
  358. if (mEditButton != NULL)
  359. {
  360. RectI shapeEdRect(fieldExtent.x - 16, 2, 14, fieldExtent.y - 4);
  361. resized |= mEditButton->resize(shapeEdRect.point, shapeEdRect.extent);
  362. }
  363. return resized;
  364. }
  365. IMPLEMENT_CONOBJECT(GuiInspectorTypeMaterialAssetId);
  366. ConsoleDocClass(GuiInspectorTypeMaterialAssetId,
  367. "@brief Inspector field type for Material Assets\n\n"
  368. "Editor use only.\n\n"
  369. "@internal"
  370. );
  371. void GuiInspectorTypeMaterialAssetId::consoleInit()
  372. {
  373. Parent::consoleInit();
  374. ConsoleBaseType::getType(TypeMaterialAssetId)->setInspectorFieldType("GuiInspectorTypeMaterialAssetId");
  375. }