llgltfmateriallist.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. /**
  2. * @file llgltfmateriallist.cpp
  3. * @brief The LLGLTFMaterialList class implementation
  4. *
  5. * $LicenseInfo:firstyear=2022&license=viewergpl$
  6. *
  7. * Copyright (c) 2022, Linden Research, Inc.
  8. *
  9. * Second Life Viewer Source Code
  10. * The source code in this file ("Source Code") is provided by Linden Lab
  11. * to you under the terms of the GNU General Public License, version 2.0
  12. * ("GPL"), unless you have obtained a separate licensing agreement
  13. * ("Other License"), formally executed by you and Linden Lab. Terms of
  14. * the GPL can be found in doc/GPL-license.txt in this distribution, or
  15. * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
  16. *
  17. * There are special exceptions to the terms and conditions of the GPL as
  18. * it is applied to this Source Code. View the full text of the exception
  19. * in the file doc/FLOSS-exception.txt in this software distribution, or
  20. * online at
  21. * http://secondlifegrid.net/programs/open_source/licensing/flossexception
  22. *
  23. * By copying, modifying or distributing this software, you acknowledge
  24. * that you have read and understood your obligations described above,
  25. * and agree to abide by those obligations.
  26. *
  27. * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
  28. * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
  29. * COMPLETENESS OR PERFORMANCE.
  30. * $/LicenseInfo$
  31. */
  32. #include "llviewerprecompiledheaders.h"
  33. #include <sstream>
  34. #include "tinygltf/tiny_gltf.h"
  35. #include "llgltfmateriallist.h"
  36. #include "indra_constants.h" // For BLANK_MATERIAL_ASSET_ID
  37. #include "llassetstorage.h"
  38. #include "llcorehttputil.h"
  39. #include "llfilesystem.h"
  40. #include "llsdserialize.h"
  41. #include "llworkqueue.h"
  42. #include "llagent.h"
  43. #include "llappviewer.h"
  44. #include "hbfloaterdebugtags.h"
  45. #include "llpipeline.h"
  46. #include "lltinygltfhelper.h"
  47. #include "llviewercontrol.h"
  48. #include "llviewerobjectlist.h"
  49. #include "llviewerregion.h"
  50. #include "llvlcomposition.h" // For LLTerrain::isAsset()
  51. #include "llvocache.h"
  52. #include "llworld.h"
  53. LLGLTFMaterialList gGLTFMaterialList;
  54. LLGLTFMaterialList::modify_queue_t LLGLTFMaterialList::sModifyQueue;
  55. LLGLTFMaterialList::apply_queue_t LLGLTFMaterialList::sApplyQueue;
  56. LLSD LLGLTFMaterialList::sUpdates;
  57. LLGLTFMaterialList::selection_cb_list_t LLGLTFMaterialList::sSelectionCallbacks;
  58. ///////////////////////////////////////////////////////////////////////////////
  59. // LLGLTFMaterialList class
  60. ///////////////////////////////////////////////////////////////////////////////
  61. void LLGLTFMaterialList::applyQueuedOverrides(LLViewerObject* objp)
  62. {
  63. if (objp)
  64. {
  65. // The override cache is the authoritative source of the most recent
  66. // override data
  67. LLViewerRegion* regionp = objp->getRegion();
  68. if (regionp)
  69. {
  70. regionp->applyCacheMiscExtras(objp);
  71. }
  72. }
  73. }
  74. void LLGLTFMaterialList::queueModify(const LLViewerObject* objp, S32 side,
  75. const LLGLTFMaterial* matp)
  76. {
  77. if (!objp || objp->getRenderMaterialID(side).isNull())
  78. {
  79. llwarns << "Cannot modify: NULL " << (objp ? "material" : "object")
  80. << llendl;
  81. return;
  82. }
  83. const LLUUID& obj_id = objp->getID();
  84. if (matp)
  85. {
  86. if (objp->getDebugUpdateMsg())
  87. {
  88. llinfos << "Queuing material modification for face " << side
  89. << " of object " << obj_id << llendl;
  90. }
  91. sModifyQueue.emplace_back(obj_id, *matp, side, true);
  92. return;
  93. }
  94. if (objp->getDebugUpdateMsg())
  95. {
  96. llinfos << "Queuing material reset for face " << side << " of object "
  97. << obj_id << llendl;
  98. }
  99. sModifyQueue.emplace_back(obj_id, LLGLTFMaterial(), side, false);
  100. }
  101. void LLGLTFMaterialList::queueApply(const LLViewerObject* objp, S32 side,
  102. const LLUUID& asset_id)
  103. {
  104. const LLUUID& obj_id = objp->getID();
  105. const LLGLTFMaterial* matp = objp->getTE(side)->getGLTFMaterialOverride();
  106. if (matp)
  107. {
  108. if (objp->getDebugUpdateMsg())
  109. {
  110. llinfos << "Queuing material applying for face " << side
  111. << " of object " << obj_id << llendl;
  112. }
  113. LLGLTFMaterial* cleared_matp = new LLGLTFMaterial(*matp);
  114. cleared_matp->setBaseMaterial();
  115. sApplyQueue.emplace_back(obj_id, asset_id, cleared_matp, side);
  116. return;
  117. }
  118. if (objp->getDebugUpdateMsg())
  119. {
  120. llinfos << "Queuing material reset for face " << side << " of object "
  121. << obj_id << llendl;
  122. }
  123. sApplyQueue.emplace_back(obj_id, asset_id, nullptr, side);
  124. }
  125. void LLGLTFMaterialList::queueApply(const LLViewerObject* objp, S32 side,
  126. const LLUUID& asset_id,
  127. const LLGLTFMaterial* matp)
  128. {
  129. if (!matp || asset_id.isNull())
  130. {
  131. queueApply(objp, side, asset_id);
  132. return;
  133. }
  134. sApplyQueue.emplace_back(objp->getID(), asset_id,
  135. new LLGLTFMaterial(*matp), side);
  136. }
  137. void LLGLTFMaterialList::queueUpdate(const LLSD& data)
  138. {
  139. if (!sUpdates.isArray())
  140. {
  141. sUpdates = LLSD::emptyArray();
  142. }
  143. sUpdates[sUpdates.size()] = data;
  144. }
  145. void LLGLTFMaterialList::flushUpdates(done_cb_t callback)
  146. {
  147. LLSD& data = sUpdates;
  148. S32 i = data.size();
  149. const LLUUID& debugged_id = LLViewerObject::getDebuggedObjectId();
  150. for (ModifyMaterialData& e : sModifyQueue)
  151. {
  152. data[i]["object_id"] = e.object_id;
  153. data[i]["side"] = e.side;
  154. if (e.has_override)
  155. {
  156. data[i]["gltf_json"] = e.override_data.asJSON();
  157. }
  158. else
  159. {
  160. // Clear all overrides
  161. data[i]["gltf_json"] = "";
  162. }
  163. if (e.object_id == debugged_id)
  164. {
  165. llinfos << "Sending modifications for object " << debugged_id
  166. << " on side " << e.side << ". JSON data: "
  167. << data[i]["gltf_json"] << llendl;
  168. }
  169. ++i;
  170. }
  171. sModifyQueue.clear();
  172. for (auto& e : sApplyQueue)
  173. {
  174. data[i]["object_id"] = e.object_id;
  175. data[i]["side"] = e.side;
  176. data[i]["asset_id"] = e.asset_id;
  177. if (e.override_data.notNull())
  178. {
  179. data[i]["gltf_json"] = e.override_data->asJSON();
  180. }
  181. else
  182. {
  183. // Clear all overrides
  184. data[i]["gltf_json"] = "";
  185. }
  186. if (e.object_id == debugged_id)
  187. {
  188. llinfos << "Applying material to object " << debugged_id
  189. << " on side " << e.side << " asset Id " << e.asset_id
  190. << ". JSON data: " << data[i]["gltf_json"] << llendl;
  191. }
  192. ++i;
  193. }
  194. sApplyQueue.clear();
  195. if (data.size() == 0)
  196. {
  197. return;
  198. }
  199. const std::string& cap_url =
  200. gAgent.getRegionCapability("ModifyMaterialParams");
  201. if (cap_url.empty())
  202. {
  203. LL_DEBUGS("GLTF") << "No ModifyMaterialParams capability. Aborted"
  204. << LL_ENDL;
  205. return;
  206. }
  207. gCoros.launch("modifyMaterialCoro",
  208. boost::bind(&LLGLTFMaterialList::modifyMaterialCoro, cap_url,
  209. data, callback));
  210. sUpdates = LLSD::emptyArray();
  211. }
  212. //static
  213. void LLGLTFMaterialList::addSelectionUpdateCallback(update_cb_t callback)
  214. {
  215. sSelectionCallbacks.insert(callback);
  216. }
  217. //static
  218. void LLGLTFMaterialList::doSelectionCallbacks(const LLUUID& obj_id, S32 side)
  219. {
  220. for (auto& callback : sSelectionCallbacks)
  221. {
  222. callback(obj_id, side);
  223. }
  224. }
  225. struct GLTFAssetLoadUserData
  226. {
  227. GLTFAssetLoadUserData() = default;
  228. LL_INLINE GLTFAssetLoadUserData(tinygltf::Model model,
  229. LLFetchedGLTFMaterial* matp)
  230. : mModelIn(model),
  231. mMaterial(matp)
  232. {
  233. }
  234. tinygltf::Model mModelIn;
  235. LLPointer<LLFetchedGLTFMaterial> mMaterial;
  236. };
  237. // Work done via the general queue thread pool.
  238. //static
  239. bool LLGLTFMaterialList::decodeAsset(const LLUUID& id,
  240. GLTFAssetLoadUserData* asset_data)
  241. {
  242. LLFileSystem file(id);
  243. S32 size = file.getSize();
  244. if (!size)
  245. {
  246. llwarns << "Cannot read asset cache file for " << id << llendl;
  247. return false;
  248. }
  249. std::string buffer(size + 1, '\0');
  250. file.read((U8*)buffer.data(), size);
  251. // Read file into buffer
  252. std::stringstream llsdstream(buffer);
  253. LLSD asset;
  254. if (!LLSDSerialize::deserialize(asset, llsdstream, -1))
  255. {
  256. llwarns << "Failed to deserialize material LLSD for " << id << llendl;
  257. return false;
  258. }
  259. if (!asset.has("version"))
  260. {
  261. llwarns << "Missing GLTF version in material LLSD for " << id
  262. << llendl;
  263. return false;
  264. }
  265. std::string data = asset["version"].asString();
  266. if (!LLGLTFMaterial::isAcceptedVersion(data))
  267. {
  268. llwarns << "Unsupported GLTF version " << data << " for " << id
  269. << llendl;
  270. return false;
  271. }
  272. if (!asset.has("type"))
  273. {
  274. llwarns << "Missing GLTF asset type in material LLSD for " << id
  275. << llendl;
  276. return false;
  277. }
  278. data = asset["type"].asString();
  279. if (data != LLGLTFMaterial::ASSET_TYPE)
  280. {
  281. llwarns << "Incorrect GLTF asset type '" << data << "' for " << id
  282. << llendl;
  283. return false;
  284. }
  285. if (!asset.has("data") || !asset["data"].isString())
  286. {
  287. llwarns << "Invalid GLTF asset data for " << id << llendl;
  288. return false;
  289. }
  290. data = asset["data"].asString();
  291. std::string warn_msg, error_msg;
  292. tinygltf::TinyGLTF gltf;
  293. if (!gltf.LoadASCIIFromString(&asset_data->mModelIn, &error_msg, &warn_msg,
  294. data.c_str(), data.length(), ""))
  295. {
  296. llwarns << "Failed to decode material asset " << id
  297. << ". tinygltf reports: \n" << warn_msg << "\n"
  298. << error_msg << llendl;
  299. return false;
  300. }
  301. return true;
  302. }
  303. // Work on the main thread via the main loop work queue.
  304. //static
  305. void LLGLTFMaterialList::decodeAssetCallback(const LLUUID& id,
  306. GLTFAssetLoadUserData* asset_data,
  307. bool result)
  308. {
  309. if (asset_data->mMaterial.isNull()) // Paranoia ? HB
  310. {
  311. LL_DEBUGS("GLTF") << "NULL material returned for " << id << LL_ENDL;
  312. return;
  313. }
  314. if (result)
  315. {
  316. asset_data->mMaterial->setFromModel(asset_data->mModelIn,
  317. 0/*only one index*/);
  318. }
  319. else
  320. {
  321. LL_DEBUGS("GLTF") << "Failed to get material " << id << LL_ENDL;
  322. }
  323. asset_data->mMaterial->materialComplete(true);
  324. delete asset_data;
  325. }
  326. void LLGLTFMaterialList::onAssetLoadComplete(const LLUUID& id,
  327. LLAssetType::EType asset_type,
  328. void* user_data, S32 status,
  329. LLExtStat ext_status)
  330. {
  331. GLTFAssetLoadUserData* asset_data = (GLTFAssetLoadUserData*)user_data;
  332. if (status != LL_ERR_NOERR)
  333. {
  334. // A failure is "normal" if that asset Id was actually a terrain
  335. // texture Id and not a PBR material, so do not log an error. HB
  336. if (!LLTerrain::isAsset(id))
  337. {
  338. llwarns << "Error getting material asset data: "
  339. << LLAssetStorage::getErrorString(status)
  340. << " (" << status << ")" << llendl;
  341. }
  342. asset_data->mMaterial->materialComplete(false);
  343. delete asset_data;
  344. return;
  345. }
  346. if (!gMainloopWorkp)
  347. {
  348. // We are likely shutting down... HB
  349. return;
  350. }
  351. static LLWorkQueue::weak_t general_queue =
  352. LLWorkQueue::getNamedInstance("General");
  353. gMainloopWorkp->postTo(general_queue,
  354. // Work done on general queue
  355. [id, asset_data]()
  356. {
  357. return decodeAsset(id, asset_data);
  358. },
  359. // Callback to main thread
  360. [id, asset_data](bool result)
  361. {
  362. decodeAssetCallback(id, asset_data, result);
  363. });
  364. }
  365. LLFetchedGLTFMaterial* LLGLTFMaterialList::getMaterial(const LLUUID& id)
  366. {
  367. id_mat_map_t::iterator iter = mList.find(id);
  368. if (iter != mList.end())
  369. {
  370. return iter->second;
  371. }
  372. LLFetchedGLTFMaterial* matp = new LLFetchedGLTFMaterial();
  373. mList[id] = matp;
  374. matp->materialBegin();
  375. GLTFAssetLoadUserData* datap = new GLTFAssetLoadUserData();
  376. datap->mMaterial = matp;
  377. if (gAssetStoragep) // In case this would trigger after logoff... HB
  378. {
  379. gAssetStoragep->getAssetData(id, LLAssetType::AT_MATERIAL,
  380. onAssetLoadComplete, (void*)datap);
  381. }
  382. return matp;
  383. }
  384. void LLGLTFMaterialList::flushMaterials()
  385. {
  386. // Similar variant to what textures use (TextureFetchUpdateMinCount in LL's
  387. // PBR viewer code).
  388. static LLCachedControl<U32> min_update_count(gSavedSettings,
  389. "TextureFetchUpdateMinMediumPriority");
  390. // Update min_update_count or 5% of materials, whichever is greater
  391. U32 update_count = llmax((U32)min_update_count, mList.size() / 20);
  392. update_count = llmin(update_count, (U32)mList.size());
  393. constexpr F32 TIMEOUT = 30.f;
  394. F32 cur_time = gFrameTimeSeconds;
  395. // Advance iter one past the last key we updated
  396. id_mat_map_t::iterator iter = mList.find(mLastUpdateKey);
  397. if (iter != mList.end())
  398. {
  399. ++iter;
  400. }
  401. while (update_count-- > 0)
  402. {
  403. if (iter == mList.end())
  404. {
  405. iter = mList.begin();
  406. }
  407. LLPointer<LLFetchedGLTFMaterial> material = iter->second;
  408. if (material->getNumRefs() == 2) // This one plus one from the list
  409. {
  410. if (!material->mActive && cur_time > material->mExpectedFlushTime)
  411. {
  412. iter = mList.erase(iter);
  413. }
  414. else
  415. {
  416. if (material->mActive)
  417. {
  418. material->mExpectedFlushTime = cur_time + TIMEOUT;
  419. material->mActive = false;
  420. }
  421. ++iter;
  422. }
  423. }
  424. else
  425. {
  426. material->mActive = true;
  427. ++iter;
  428. }
  429. }
  430. if (iter != mList.end())
  431. {
  432. mLastUpdateKey = iter->first;
  433. }
  434. else
  435. {
  436. mLastUpdateKey.setNull();
  437. }
  438. }
  439. //static
  440. void LLGLTFMaterialList::modifyMaterialCoro(const std::string& cap_url,
  441. LLSD overrides, done_cb_t callback)
  442. {
  443. LL_DEBUGS("GLTF") << "Applying override via ModifyMaterialParams cap: "
  444. << overrides << LL_ENDL;
  445. LLCore::HttpOptions::ptr_t options(new LLCore::HttpOptions);
  446. options->setFollowRedirects(true);
  447. LLCoreHttpUtil::HttpCoroutineAdapter adapter("modifyMaterialCoro");
  448. LLSD result = adapter.postAndSuspend(cap_url, overrides, options);
  449. LLCore::HttpStatus status =
  450. LLCoreHttpUtil::HttpCoroutineAdapter::getStatusFromLLSD(result);
  451. bool success = true;
  452. if (!status)
  453. {
  454. llwarns << "Failed to modify material." << llendl;
  455. success = false;
  456. }
  457. else if (!result["success"].asBoolean())
  458. {
  459. llwarns << "Failed to modify material: " << result["message"] << LL_ENDL;
  460. success = false;
  461. }
  462. if (callback)
  463. {
  464. callback(success);
  465. }
  466. }
  467. void LLGLTFMaterialList::applyOverrideMessage(LLMessageSystem* msg,
  468. const std::string& data_in)
  469. {
  470. if (!msg) return; // Paranoia
  471. const LLHost& host = msg->getSender();
  472. LLViewerRegion* regionp = gWorld.getRegion(host);
  473. if (!regionp)
  474. {
  475. return;
  476. }
  477. std::stringstream llsdstream(data_in);
  478. LLSD data;
  479. LLSDSerialize::fromNotation(data, llsdstream, data_in.size());
  480. const LLSD& tes = data["te"];
  481. if (!tes.isArray())
  482. {
  483. llwarns_once << "Malformed message: no 'te' array." << llendl;
  484. return;
  485. }
  486. U32 local_id = data.get("id").asInteger();
  487. LLUUID obj_id;
  488. gObjectList.getUUIDFromLocal(obj_id, local_id, host.getAddress(),
  489. host.getPort());
  490. LLViewerObject* objp = NULL;
  491. bool set_debug_tag = false;
  492. if (obj_id.notNull())
  493. {
  494. set_debug_tag = obj_id == LLViewerObject::getDebuggedObjectId() &&
  495. !HBFloaterDebugTags::debugTagActive("GLTF");
  496. if (set_debug_tag)
  497. {
  498. HBFloaterDebugTags::setTag("GLTF", true);
  499. }
  500. LL_DEBUGS("GLTF") << "Received PBR material data for object " << obj_id
  501. << ": " << data_in << LL_ENDL;
  502. objp = gObjectList.findObject(obj_id);
  503. // Note: objp may be NULL if the viewer has not heard about the object
  504. // yet...
  505. if (objp && gShowObjectUpdates)
  506. {
  507. // Display a cyan blip for override updates when "Show objects
  508. // updates" is enabled.
  509. gPipeline.addDebugBlip(objp->getPositionAgent(), LLColor4::cyan);
  510. }
  511. }
  512. bool has_te[MAX_TES] = { false };
  513. fast_hset<S32> selected_tes;
  514. LLGLTFOverrideCacheEntry entry;
  515. entry.mLocalId = local_id;
  516. entry.mRegionHandle = regionp->getHandle();
  517. const LLSD& od = data["od"];
  518. for (U32 i = 0, count = llmin(tes.size(), MAX_TES); i < count; ++i)
  519. {
  520. LL_DEBUGS("GLTF") << "Face " << i << ", material override: ";
  521. if (od[i].isDefined())
  522. {
  523. LL_CONT << od[i];
  524. }
  525. else
  526. {
  527. LL_CONT << "none.";
  528. }
  529. LL_CONT << LL_ENDL;
  530. // Note: setTEGLTFMaterialOverride() and cache will take ownership.
  531. LLGLTFMaterial* matp = new LLGLTFMaterial();
  532. matp->applyOverrideLLSD(od[i]);
  533. S32 te = tes[i].asInteger();
  534. has_te[te] = true;
  535. entry.mSides[te] = od[i];
  536. entry.mGLTFMaterial[te] = matp;
  537. if (objp)
  538. {
  539. objp->setTEGLTFMaterialOverride(te, matp);
  540. LLTextureEntry* tep = objp->getTE(te);
  541. if (tep && tep->isSelected())
  542. {
  543. selected_tes.insert(te);
  544. }
  545. }
  546. }
  547. if (objp)
  548. {
  549. // Null out overrides on TEs that should not have them
  550. for (U32 te = 0, count = llmin(objp->getNumTEs(), MAX_TES); te < count;
  551. ++te)
  552. {
  553. if (!has_te[te])
  554. {
  555. LLTextureEntry* tep = objp->getTE(te);
  556. if (tep && tep->getGLTFMaterialOverride())
  557. {
  558. objp->setTEGLTFMaterialOverride(te, NULL);
  559. selected_tes.insert(te);
  560. }
  561. }
  562. }
  563. }
  564. regionp->cacheFullUpdateGLTFOverride(entry);
  565. if (!selected_tes.empty())
  566. {
  567. for (fast_hset<S32>::iterator it = selected_tes.begin(),
  568. end = selected_tes.end();
  569. it != end; ++it)
  570. {
  571. doSelectionCallbacks(obj_id, *it);
  572. }
  573. }
  574. if (set_debug_tag)
  575. {
  576. HBFloaterDebugTags::setTag("GLTF", false);
  577. }
  578. }