MaterialAsset.cpp 16 KB

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