llpreviewmaterial.cpp 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225
  1. /**
  2. * @file llpreviewmaterial.cpp
  3. * @brief LLPreviewMaterial class implementation
  4. *
  5. * $LicenseInfo:firstyear=2022&license=viewergpl$
  6. *
  7. * Copyright (c) 2022, Linden Research, Inc., (c) 2023-2024 Henri Beauchamp
  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 "boost/signals2.hpp"
  35. #include "llpreviewmaterial.h"
  36. #include "llassetstorage.h"
  37. #include "llbutton.h"
  38. #include "llcheckboxctrl.h"
  39. #include "llcombobox.h"
  40. #include "llfilesystem.h"
  41. #include "llnotifications.h"
  42. #include "lleconomy.h"
  43. #include "llsdserialize.h"
  44. #include "llsdutil.h"
  45. #include "llspinctrl.h"
  46. #include "lltextbox.h"
  47. #include "lltrans.h"
  48. #include "lluictrlfactory.h"
  49. #include "llagent.h"
  50. #include "llcolorswatch.h"
  51. #include "llfloaterperms.h"
  52. #include "llfloatertools.h"
  53. #include "llinventorymodel.h"
  54. #include "lllocalbitmaps.h"
  55. #include "lllocalgltfmaterials.h"
  56. #include "hbobjectbackup.h" // For HBObjectBackup::validateAssetPerms()
  57. #include "llselectmgr.h"
  58. #include "llstatusbar.h" // For can_afford_transaction()
  59. #include "lltexturectrl.h"
  60. #include "lltinygltfhelper.h"
  61. #include "lltoolpie.h"
  62. #include "llviewerassetupload.h"
  63. #include "llviewercontrol.h"
  64. #include "llviewerinventory.h" // For move_or_copy_item_from_object()
  65. #include "llviewerobjectlist.h"
  66. #include "llviewerregion.h"
  67. #include "llviewerstats.h"
  68. #include "llviewertexturelist.h"
  69. #include "llvovolume.h"
  70. #include "roles_constants.h" // For GP_OBJECT_MANIPULATE
  71. // Holds all the pointers to material previews/editors instances. Used by
  72. // callbacks to verify that its parent instance has not vanished. HB
  73. static std::set<LLPreviewMaterial*> sEditorInstances;
  74. // Static variables for use only with the "singleton" live editor. They are not
  75. // static members of LLPreviewMaterial, because they are only used within this
  76. // module, and by various classes (which would have forced to use public static
  77. // members, or to make all these classes friends of LLPreviewMaterial, or to
  78. // add variable reference/pointer accessors). HB
  79. static LLPreviewMaterial* sLiveEditorInstance = NULL;
  80. static LLUUID sOverrideObjectId;
  81. static S32 sOverrideObjectTE = 0;
  82. static bool sOverrideInProgress = false;
  83. static bool sSelectionNeedsUpdate = true;
  84. static boost::signals2::connection sSelectionUpdateSlot;
  85. static const std::string MAT_BASE_COLOR_DEFAULT_NAME = "Base Color";
  86. static const std::string MAT_NORMAL_DEFAULT_NAME = "Normal";
  87. static const std::string MAT_METALLIC_DEFAULT_NAME = "Metallic Roughness";
  88. static const std::string MAT_EMISSIVE_DEFAULT_NAME = "Emissive";
  89. // WARNING: if you change this enum (including just the order of its values),
  90. // you must also revise LLSelectedMaterialChangeFunctor and onSelectCtrl()
  91. // accordinly. HB
  92. enum eDirtyFlags : U32
  93. {
  94. MAT_BASE_COLOR_TEX_DIRTY = 0x1 << 0,
  95. MAT_NORMAL_TEX_DIRTY = 0x1 << 1,
  96. MAT_ROUGHTNESS_TEX_DIRTY = 0x1 << 2,
  97. MAT_EMISIVE_TEX_DIRTY = 0x1 << 3,
  98. MAT_BASE_COLOR_DIRTY = 0x1 << 4,
  99. MAT_EMISIVE_COLOR_DIRTY = 0x1 << 5,
  100. MAT_TRANSPARENCY_DIRTY = 0x1 << 6,
  101. MAT_ALPHA_MODE_DIRTY = 0x1 << 7,
  102. MAT_ALPHA_CUTOFF_DIRTY = 0x1 << 8,
  103. MAT_METALNESS_DIRTY = 0x1 << 9,
  104. MAT_ROUGHTNESS_DIRTY = 0x1 << 10,
  105. MAT_DOUBLE_SIDED_DIRTY = 0x1 << 11,
  106. };
  107. //static
  108. LLPreviewMaterial* LLPreviewMaterial::getLiveEditorInstance()
  109. {
  110. return sLiveEditorInstance;
  111. }
  112. //static
  113. void LLPreviewMaterial::closeLiveEditorInstance()
  114. {
  115. if (sLiveEditorInstance)
  116. {
  117. sLiveEditorInstance->close();
  118. sLiveEditorInstance = NULL;
  119. sOverrideInProgress = sSelectionNeedsUpdate = false;
  120. }
  121. }
  122. // Constructor used internally only, for the live editor and uploads.
  123. LLPreviewMaterial::LLPreviewMaterial(const std::string& name, bool live_editor)
  124. : LLPreview(name),
  125. mUnsavedChanges(0),
  126. mRevertedChanges(0),
  127. mUploadingTexturesCount(0),
  128. mExpectedUploadCost(0),
  129. mIsOverride(live_editor),
  130. mCanCopy(false),
  131. mCanModify(false),
  132. mHasSelection(false),
  133. mUploadingTexturesFailure(false)
  134. {
  135. if (live_editor)
  136. {
  137. llassert_always(!sLiveEditorInstance);
  138. sLiveEditorInstance = this;
  139. }
  140. sEditorInstances.insert(this);
  141. LLUICtrlFactory* factoryp = LLUICtrlFactory::getInstance();
  142. factoryp->buildFloater(this, "floater_preview_material.xml");
  143. }
  144. // Constructor used to preview/edit inventory items.
  145. LLPreviewMaterial::LLPreviewMaterial(const std::string& name,
  146. const LLRect& rect,
  147. const std::string& title,
  148. const LLUUID& item_id,
  149. const LLUUID& object_id)
  150. : LLPreview(name, rect, title, item_id, object_id),
  151. mUnsavedChanges(0),
  152. mRevertedChanges(0),
  153. mUploadingTexturesCount(0),
  154. mExpectedUploadCost(0),
  155. mIsOverride(false),
  156. mCanCopy(false),
  157. mCanModify(false),
  158. mHasSelection(false),
  159. mUploadingTexturesFailure(false)
  160. {
  161. sEditorInstances.insert(this);
  162. const LLViewerInventoryItem* itemp = getItem();
  163. if (itemp)
  164. {
  165. mAssetID = itemp->getAssetUUID();
  166. }
  167. LLUICtrlFactory* factoryp = LLUICtrlFactory::getInstance();
  168. factoryp->buildFloater(this, "floater_preview_material.xml");
  169. setTitle(title);
  170. loadAsset();
  171. }
  172. //virtual
  173. LLPreviewMaterial::~LLPreviewMaterial()
  174. {
  175. for (connection_map_t::iterator it = mTextureChangesUpdates.begin(),
  176. end = mTextureChangesUpdates.end();
  177. it != end; ++it)
  178. {
  179. it->second.mConnection.disconnect();
  180. }
  181. if (this == sLiveEditorInstance)
  182. {
  183. if (sSelectionUpdateSlot.connected())
  184. {
  185. sSelectionUpdateSlot.disconnect();
  186. }
  187. sLiveEditorInstance = NULL;
  188. }
  189. sEditorInstances.erase(this);
  190. }
  191. //virtual
  192. bool LLPreviewMaterial::postBuild()
  193. {
  194. mDoubleSidedCheck = getChild<LLCheckBoxCtrl>("double_sided_check");
  195. mDoubleSidedCheck->setCommitCallback(onSelectCtrl);
  196. mDoubleSidedCheck->setCallbackUserData(this);
  197. mUploadFeeText = getChild<LLTextBox>("upload_fee");
  198. mUploadFeeText->setVisible(!mIsOverride);
  199. mBaseColorTexCtrl = getChild<LLTextureCtrl>("base_color_texture");
  200. mBaseColorTexCtrl->setCommitCallback(onTextureCtrl);
  201. mBaseColorTexCtrl->setCallbackUserData(this);
  202. mMetallicTexCtrl = getChild<LLTextureCtrl>("roughness_texture");
  203. mMetallicTexCtrl->setCommitCallback(onTextureCtrl);
  204. mMetallicTexCtrl->setCallbackUserData(this);
  205. mEmissiveTexCtrl = getChild<LLTextureCtrl>("emissive_texture");
  206. mEmissiveTexCtrl->setCommitCallback(onTextureCtrl);
  207. mEmissiveTexCtrl->setCallbackUserData(this);
  208. mNormalTexCtrl = getChild<LLTextureCtrl>("normal_texture");
  209. mNormalTexCtrl->setCommitCallback(onTextureCtrl);
  210. mNormalTexCtrl->setCallbackUserData(this);
  211. std::string tex_id = gSavedSettings.getString("DefaultNormalTexture");
  212. mNormalTexCtrl->setDefaultImageAssetID(LLUUID(tex_id));
  213. tex_id = gSavedSettings.getString("BlankNormalTexture");
  214. mNormalTexCtrl->setBlankImageAssetID(LLUUID(tex_id));
  215. if (!gAgent.isGodlike())
  216. {
  217. constexpr PermissionMask full_perm_mask = PERM_COPY | PERM_TRANSFER;
  218. mBaseColorTexCtrl->setImmediateFilterPermMask(full_perm_mask);
  219. mMetallicTexCtrl->setImmediateFilterPermMask(full_perm_mask);
  220. mEmissiveTexCtrl->setImmediateFilterPermMask(full_perm_mask);
  221. mNormalTexCtrl->setImmediateFilterPermMask(full_perm_mask);
  222. }
  223. mBaseColorCtrl = getChild<LLColorSwatchCtrl>("base_color");
  224. mBaseColorCtrl->setCommitCallback(onSelectCtrl);
  225. mBaseColorCtrl->setCallbackUserData(this);
  226. mEmissiveColorCtrl = getChild<LLColorSwatchCtrl>("emissive_color");
  227. mEmissiveColorCtrl->setCommitCallback(onSelectCtrl);
  228. mEmissiveColorCtrl->setCallbackUserData(this);
  229. if (mIsOverride)
  230. {
  231. // Material override change success callback
  232. LLGLTFMaterialList::addSelectionUpdateCallback(&updateLive);
  233. // Live editing needs a recovery mechanism on cancel
  234. mBaseColorTexCtrl->setOnCancelCallback(onCancelCtrl);
  235. mMetallicTexCtrl->setOnCancelCallback(onCancelCtrl);
  236. mEmissiveTexCtrl->setOnCancelCallback(onCancelCtrl);
  237. mNormalTexCtrl->setOnCancelCallback(onCancelCtrl);
  238. mBaseColorCtrl->setOnCancelCallback(onCancelCtrl);
  239. mEmissiveColorCtrl->setOnCancelCallback(onCancelCtrl);
  240. // Save applied changes on 'OK' to our recovery mechanism.
  241. mBaseColorTexCtrl->setOnSelectCallback(onSelectCtrl);
  242. mMetallicTexCtrl->setOnSelectCallback(onSelectCtrl);
  243. mEmissiveTexCtrl->setOnSelectCallback(onSelectCtrl);
  244. mNormalTexCtrl->setOnSelectCallback(onSelectCtrl);
  245. mBaseColorCtrl->setOnSelectCallback(onCancelCtrl);
  246. mEmissiveColorCtrl->setOnSelectCallback(onCancelCtrl);
  247. }
  248. else
  249. {
  250. mBaseColorTexCtrl->setCanApplyImmediately(false);
  251. mMetallicTexCtrl->setCanApplyImmediately(false);
  252. mEmissiveTexCtrl->setCanApplyImmediately(false);
  253. mNormalTexCtrl->setCanApplyImmediately(false);
  254. mBaseColorCtrl->setCanApplyImmediately(false);
  255. mEmissiveColorCtrl->setCanApplyImmediately(false);
  256. }
  257. mTransparencyCtrl = getChild<LLSpinCtrl>("transparency");
  258. mTransparencyCtrl->setCommitCallback(onSelectCtrl);
  259. mTransparencyCtrl->setCallbackUserData(this);
  260. mAlphaModeCombo = getChild<LLComboBox>("alpha_mode");
  261. mAlphaModeCombo->setCommitCallback(onSelectCtrl);
  262. mAlphaModeCombo->setCallbackUserData(this);
  263. mAlphaCutoffCtrl = getChild<LLSpinCtrl>("alpha_cutoff");
  264. mAlphaCutoffCtrl->setCommitCallback(onSelectCtrl);
  265. mAlphaCutoffCtrl->setCallbackUserData(this);
  266. mMetalnessCtrl = getChild<LLSpinCtrl>("metalness");
  267. mMetalnessCtrl->setCommitCallback(onSelectCtrl);
  268. mMetalnessCtrl->setCallbackUserData(this);
  269. mRoughnessCtrl = getChild<LLSpinCtrl>("roughness");
  270. mRoughnessCtrl->setCommitCallback(onSelectCtrl);
  271. mRoughnessCtrl->setCallbackUserData(this);
  272. mCancelButton = getChild<LLButton>("cancel_btn");
  273. mCancelButton->setClickedCallback(onClickCancel, this);
  274. mSaveButton = getChild<LLButton>("save_btn");
  275. mSaveAsButton = getChild<LLButton>("save_as_btn");
  276. if (mIsOverride)
  277. {
  278. mCancelButton->setLabel(getString("close"));
  279. mSaveButton->setVisible(false);
  280. mSaveAsButton->setVisible(false);
  281. }
  282. else
  283. {
  284. mSaveButton->setClickedCallback(onClickSave, this);
  285. mSaveAsButton->setClickedCallback(onClickSaveAs, this);
  286. }
  287. // Sync Save button state and cost.
  288. markChangesUnsaved(0);
  289. if (!mIsOverride)
  290. {
  291. setRectControl("PreviewMaterialRect");
  292. applyRectControl();
  293. }
  294. else if (LLFloaterTools::isVisible())
  295. {
  296. gFloaterToolsp->addDependentFloater(this);
  297. }
  298. else
  299. {
  300. center();
  301. }
  302. return LLPreview::postBuild();
  303. }
  304. //virtual
  305. void LLPreviewMaterial::setItemID(const LLUUID& item_id)
  306. {
  307. LLPreview::setItemID(item_id);
  308. const LLViewerInventoryItem* itemp = getItem();
  309. if (itemp)
  310. {
  311. mAssetID = itemp->getAssetUUID();
  312. }
  313. }
  314. //virtual
  315. void LLPreviewMaterial::setAuxItem(const LLInventoryItem* itemp)
  316. {
  317. LLPreview::setAuxItem(itemp);
  318. if (itemp)
  319. {
  320. mAssetID = itemp->getAssetUUID();
  321. }
  322. }
  323. //virtual
  324. void LLPreviewMaterial::inventoryChanged(LLViewerObject*,
  325. LLInventoryObject::object_list_t*,
  326. S32, void*)
  327. {
  328. removeVOInventoryListener();
  329. loadAsset();
  330. }
  331. //virtual
  332. void LLPreviewMaterial::draw()
  333. {
  334. if (mIsOverride)
  335. {
  336. if (sSelectionNeedsUpdate ||
  337. (mHasSelection && gSelectMgr.getSelection()->isEmpty()))
  338. {
  339. LL_DEBUGS("GLTF") << "Reloading live material from selection"
  340. << LL_ENDL;
  341. sSelectionNeedsUpdate = false;
  342. clearTextures();
  343. setFromSelection();
  344. }
  345. }
  346. else
  347. {
  348. bool loaded = mAssetStatus == PREVIEW_ASSET_LOADED;
  349. mSaveButton->setEnabled(loaded && mCanModify &&
  350. (mUnsavedChanges || mRevertedChanges));
  351. mSaveAsButton->setEnabled(loaded && mCanCopy);
  352. }
  353. LLPreview::draw();
  354. }
  355. void LLPreviewMaterial::setMaterialName(const std::string& name)
  356. {
  357. setTitle(name);
  358. mMaterialName = name;
  359. }
  360. void LLPreviewMaterial::refreshFromInventory(const LLUUID& new_item_id)
  361. {
  362. if (mIsOverride) // Should never happen.
  363. {
  364. llassert(false);
  365. return;
  366. }
  367. if (new_item_id.notNull())
  368. {
  369. setItemID(new_item_id);
  370. }
  371. loadAsset();
  372. }
  373. struct LLPreviewMaterialInfo
  374. {
  375. LLPreviewMaterial* mPreviewp;
  376. LLUUID mAssetUUID;
  377. LLUUID mItemUUID;
  378. LLUUID mObjectUUID;
  379. };
  380. //virtual
  381. void LLPreviewMaterial::loadAsset()
  382. {
  383. if (mIsOverride)
  384. {
  385. // Overrides do not have an asset... HB
  386. return;
  387. }
  388. const LLInventoryItem* itemp = getItem();
  389. if (!itemp)
  390. {
  391. if (mObjectUUID.isNull() || mItemUUID.isNull())
  392. {
  393. llwarns << "Cannot load asset: no object or no inventory item set."
  394. << llendl;
  395. return;
  396. }
  397. LLViewerObject* objectp = gObjectList.findObject(mObjectUUID);
  398. if (!objectp)
  399. {
  400. llwarns << "Cannot load asset: object gone ?" << llendl;
  401. return;
  402. }
  403. bool inv_dirty = objectp->isInventoryDirty();
  404. if (inv_dirty || objectp->isInventoryPending())
  405. {
  406. registerVOInventoryListener(objectp, NULL);
  407. if (inv_dirty)
  408. {
  409. objectp->requestInventory();
  410. }
  411. }
  412. return;
  413. }
  414. setMaterialName(itemp->getName());
  415. // Set permissions
  416. LLPermissions perm = itemp->getPermissions();
  417. mCanCopy = mObjectUUID.isNull() &&
  418. gAgent.allowOperation(PERM_COPY, perm, GP_OBJECT_MANIPULATE);
  419. mCanModify = canModify(mObjectUUID, itemp);
  420. if (mCanModify)
  421. {
  422. const LLUUID& lib_id = gInventory.getLibraryRootFolderID();
  423. if (mObjectUUID.isNull() &&
  424. gInventory.isObjectDescendentOf(mItemUUID, lib_id))
  425. {
  426. mCanModify = false;
  427. }
  428. }
  429. mAssetID = itemp->getAssetUUID();
  430. if (mAssetID.isNull())
  431. {
  432. mAssetStatus = PREVIEW_ASSET_LOADED;
  433. loadDefaults();
  434. resetUnsavedChanges();
  435. setEnableEditing(mCanModify);
  436. return;
  437. }
  438. setEnableEditing(false); // Wait for it to load
  439. mAssetStatus = PREVIEW_ASSET_LOADING;
  440. if (!gAssetStoragep)
  441. {
  442. return;
  443. }
  444. LLPreviewMaterialInfo* infop = new LLPreviewMaterialInfo;
  445. infop->mPreviewp = this;
  446. infop->mAssetUUID = itemp->getAssetUUID();
  447. if (mObjectUUID.notNull())
  448. {
  449. LLViewerObject* objectp = gObjectList.findObject(mObjectUUID);
  450. if (!objectp)
  451. {
  452. llwarns << "Cannot load asset: object gone ?" << llendl;
  453. mAssetID.setNull();
  454. mAssetStatus = PREVIEW_ASSET_LOADED;
  455. resetUnsavedChanges();
  456. setEnableEditing(mCanModify);
  457. delete infop;
  458. return;
  459. }
  460. infop->mItemUUID = mItemUUID;
  461. infop->mObjectUUID = mObjectUUID;
  462. }
  463. else
  464. {
  465. infop->mItemUUID = mItemUUID;
  466. }
  467. gAssetStoragep->getAssetData(infop->mAssetUUID, LLAssetType::AT_MATERIAL,
  468. onLoadComplete, (void*)infop, true);
  469. }
  470. //static
  471. void LLPreviewMaterial::onLoadComplete(const LLUUID& asset_id,
  472. LLAssetType::EType type, void* userdata,
  473. S32 status, LLExtStat)
  474. {
  475. LLPreviewMaterialInfo* infop = (LLPreviewMaterialInfo*)userdata;
  476. if (!infop) // Should never happen.
  477. {
  478. llassert(false);
  479. return;
  480. }
  481. LLPreviewMaterial* self = infop->mPreviewp;
  482. if (!self || !sEditorInstances.count(self) || asset_id != self->mAssetID)
  483. {
  484. // Floater already gone.
  485. delete infop;
  486. return;
  487. }
  488. // Check for any error
  489. if (status)
  490. {
  491. gViewerStats.incStat(LLViewerStats::ST_DOWNLOAD_FAILED);
  492. if (status == LL_ERR_ASSET_REQUEST_NOT_IN_DATABASE ||
  493. status == LL_ERR_FILE_EMPTY)
  494. {
  495. gNotifications.add("MaterialMissing");
  496. }
  497. else if (status == LL_ERR_INSUFFICIENT_PERMISSIONS)
  498. {
  499. gNotifications.add("MaterialNoPermissions");
  500. }
  501. else
  502. {
  503. gNotifications.add("UnableToLoadMaterial");
  504. }
  505. self->setEnableEditing(false);
  506. self->mAssetStatus = PREVIEW_ASSET_ERROR;
  507. delete infop;
  508. return;
  509. }
  510. LLFileSystem file(asset_id);
  511. S32 file_length = file.getSize();
  512. std::string buffer(file_length + 1, '\0');
  513. file.read((U8*)&buffer[0], file_length);
  514. self->decodeAsset(buffer);
  515. bool can_modify = LLPreview::canModify(self->mObjectUUID, self->getItem());
  516. if (can_modify && self->mObjectUUID.isNull())
  517. {
  518. const LLUUID& lib_id = gInventory.getLibraryRootFolderID();
  519. can_modify = !gInventory.isObjectDescendentOf(self->mItemUUID, lib_id);
  520. }
  521. self->setEnableEditing(can_modify);
  522. self->resetUnsavedChanges();
  523. self->mAssetStatus = PREVIEW_ASSET_LOADED;
  524. self->setEnabled(true); // Ready for use
  525. delete infop;
  526. }
  527. LLUUID LLPreviewMaterial::getTextureId(LLTextureCtrl* ctrlp) const
  528. {
  529. return ctrlp->getValue().asUUID();
  530. }
  531. void LLPreviewMaterial::setTextureId(LLTextureCtrl* ctrlp, const LLUUID& id)
  532. {
  533. ctrlp->setValue(id);
  534. ctrlp->setDefaultImageAssetID(id);
  535. ctrlp->setTentative(false);
  536. }
  537. F32 LLPreviewMaterial::getCtrlValue(LLSpinCtrl* ctrlp) const
  538. {
  539. return ctrlp->getValue().asReal();
  540. }
  541. void LLPreviewMaterial::setCtrlValue(LLSpinCtrl* ctrlp, F32 value)
  542. {
  543. ctrlp->setValue(value);
  544. }
  545. LLColor4 LLPreviewMaterial::getBaseColor() const
  546. {
  547. LLColor4 color = linearColor4(LLColor4(mBaseColorCtrl->getValue()));
  548. color.mV[3] = getTransparency();
  549. return color;
  550. }
  551. void LLPreviewMaterial::setBaseColor(const LLColor4& color)
  552. {
  553. mBaseColorCtrl->setValue(srgbColor4(color).getValue());
  554. setTransparency(color.mV[3]);
  555. }
  556. LLColor4 LLPreviewMaterial::getEmissiveColor() const
  557. {
  558. return linearColor4(LLColor4(mEmissiveColorCtrl->getValue()));
  559. }
  560. void LLPreviewMaterial::setEmissiveColor(const LLColor4& color)
  561. {
  562. mEmissiveColorCtrl->setValue(srgbColor4(color).getValue());
  563. }
  564. std::string LLPreviewMaterial::getAlphaMode() const
  565. {
  566. return mAlphaModeCombo->getValue().asString();
  567. }
  568. void LLPreviewMaterial::setAlphaMode(const std::string& alpha_mode)
  569. {
  570. mAlphaModeCombo->setValue(alpha_mode);
  571. }
  572. bool LLPreviewMaterial::getDoubleSided() const
  573. {
  574. return mDoubleSidedCheck->get();
  575. }
  576. void LLPreviewMaterial::setDoubleSided(bool double_sided)
  577. {
  578. mDoubleSidedCheck->set(double_sided);
  579. }
  580. void LLPreviewMaterial::resetUnsavedChanges()
  581. {
  582. mUnsavedChanges = mRevertedChanges = 0;
  583. if (!mIsOverride)
  584. {
  585. mExpectedUploadCost = 0;
  586. mUploadFeeText->setTextArg("[COST]", "0");
  587. mUploadFeeText->setVisible(false);
  588. }
  589. }
  590. static S32 get_texture_cost(LLViewerFetchedTexture* texp)
  591. {
  592. if (!texp)
  593. {
  594. return 0;
  595. }
  596. return LLEconomy::getInstance()->getTextureUploadCost(texp->getWidth(),
  597. texp->getHeight());
  598. }
  599. void LLPreviewMaterial::markChangesUnsaved(U32 dirty_flag)
  600. {
  601. mUnsavedChanges |= dirty_flag;
  602. if (mIsOverride)
  603. {
  604. return;
  605. }
  606. if (mUnsavedChanges)
  607. {
  608. const LLInventoryItem* itemp = getItem();
  609. if (itemp)
  610. {
  611. mCanModify = canModify(mObjectUUID, itemp);
  612. if (mCanModify && mObjectUUID.isNull())
  613. {
  614. const LLUUID& lib_id = gInventory.getLibraryRootFolderID();
  615. mCanModify = !gInventory.isObjectDescendentOf(mItemUUID,
  616. lib_id);
  617. }
  618. }
  619. }
  620. mExpectedUploadCost = 0;
  621. if (mBaseColorTextureUploadId.notNull() &&
  622. mBaseColorTextureUploadId == getBaseColorId())
  623. {
  624. mExpectedUploadCost = get_texture_cost(mBaseColorFetched.get());
  625. }
  626. if (mMetallicTextureUploadId.notNull() &&
  627. mMetallicTextureUploadId == getMetallicRoughnessId())
  628. {
  629. mExpectedUploadCost +=
  630. get_texture_cost(mMetallicRoughnessFetched.get());
  631. }
  632. if (mEmissiveTextureUploadId.notNull() &&
  633. mEmissiveTextureUploadId == getEmissiveId())
  634. {
  635. mExpectedUploadCost += get_texture_cost(mEmissiveFetched.get());
  636. }
  637. if (mNormalTextureUploadId.notNull() &&
  638. mNormalTextureUploadId == getNormalId())
  639. {
  640. mExpectedUploadCost += get_texture_cost(mNormalFetched.get());
  641. }
  642. mUploadFeeText->setTextArg("[COST]", llformat("%d", mExpectedUploadCost));
  643. mUploadFeeText->setVisible(mExpectedUploadCost > 0);
  644. }
  645. void LLPreviewMaterial::setEnableEditing(bool can_modify)
  646. {
  647. mDoubleSidedCheck->setEnabled(can_modify);
  648. mBaseColorTexCtrl->setEnabled(can_modify);
  649. mMetallicTexCtrl->setEnabled(can_modify);
  650. mEmissiveTexCtrl->setEnabled(can_modify);
  651. mNormalTexCtrl->setEnabled(can_modify);
  652. mBaseColorCtrl->setEnabled(can_modify);
  653. mEmissiveColorCtrl->setEnabled(can_modify);
  654. mAlphaModeCombo->setEnabled(can_modify);
  655. mTransparencyCtrl->setEnabled(can_modify);
  656. mAlphaCutoffCtrl->setEnabled(can_modify);
  657. mMetalnessCtrl->setEnabled(can_modify);
  658. mRoughnessCtrl->setEnabled(can_modify);
  659. }
  660. void LLPreviewMaterial::clearTextures()
  661. {
  662. mBaseColorJ2C = mNormalJ2C = mMetallicRoughnessJ2C = mEmissiveJ2C = NULL;
  663. mBaseColorFetched = mNormalFetched = mMetallicRoughnessFetched =
  664. mEmissiveFetched = NULL;
  665. mBaseColorTextureUploadId.setNull();
  666. mMetallicTextureUploadId.setNull();
  667. mEmissiveTextureUploadId.setNull();
  668. mNormalTextureUploadId.setNull();
  669. }
  670. void LLPreviewMaterial::subscribeToLocalTexture(U32 flag, const LLUUID& t_id)
  671. {
  672. LocalTexConnection& connection = mTextureChangesUpdates[flag];
  673. if (connection.mTrackingId == t_id)
  674. {
  675. return; // Already registered with us...
  676. }
  677. connection.mConnection.disconnect();
  678. connection.mTrackingId = t_id;
  679. connection.mConnection =
  680. LLLocalBitmap::setOnChangedCallback(t_id,
  681. [this, flag](const LLUUID& tid,
  682. const LLUUID& oid,
  683. const LLUUID& nid)
  684. {
  685. if (nid.notNull())
  686. {
  687. replaceLocalTexture(oid,
  688. nid);
  689. return;
  690. }
  691. mTextureChangesUpdates[flag].mConnection.disconnect();
  692. });
  693. }
  694. const LLUUID& LLPreviewMaterial::getLocalTexTrackingIdFromFlag(U32 flag) const
  695. {
  696. connection_map_t::const_iterator it = mTextureChangesUpdates.find(flag);
  697. return it != mTextureChangesUpdates.end() ? it->second.mTrackingId
  698. : LLUUID::null;
  699. }
  700. bool LLPreviewMaterial::updateMaterialLocalSubscription(LLGLTFMaterial* matp)
  701. {
  702. if (!matp)
  703. {
  704. return false;
  705. }
  706. bool seen = false;
  707. for (connection_map_t::const_iterator it = mTextureChangesUpdates.begin(),
  708. end = mTextureChangesUpdates.end();
  709. it != end; ++it)
  710. {
  711. const LLUUID& tracking_id = it->second.mTrackingId;
  712. const LLUUID& world_id = LLLocalBitmap::getWorldID(tracking_id);
  713. if (matp->mTextureId[BASECOLIDX] == world_id ||
  714. matp->mTextureId[NORMALIDX] == world_id ||
  715. matp->mTextureId[MROUGHIDX] == world_id ||
  716. matp->mTextureId[EMISSIVEIDX] == world_id)
  717. {
  718. LLLocalBitmap::associateGLTFMaterial(tracking_id, matp);
  719. seen = true;
  720. }
  721. }
  722. return seen;
  723. }
  724. void LLPreviewMaterial::replaceLocalTexture(const LLUUID& old_id,
  725. const LLUUID& new_id)
  726. {
  727. if (old_id == new_id)
  728. {
  729. return; // Nothing to do...
  730. }
  731. if (getBaseColorId() == old_id)
  732. {
  733. setBaseColorId(new_id);
  734. }
  735. if (mBaseColorTexCtrl->getDefaultImageAssetID() == old_id)
  736. {
  737. mBaseColorTexCtrl->setDefaultImageAssetID(new_id);
  738. }
  739. if (getMetallicRoughnessId() == old_id)
  740. {
  741. setMetallicRoughnessId(new_id);
  742. }
  743. if (mMetallicTexCtrl->getDefaultImageAssetID() == old_id)
  744. {
  745. mMetallicTexCtrl->setDefaultImageAssetID(new_id);
  746. }
  747. if (getEmissiveId() == old_id)
  748. {
  749. setEmissiveId(new_id);
  750. }
  751. if (mEmissiveTexCtrl->getDefaultImageAssetID() == old_id)
  752. {
  753. mEmissiveTexCtrl->setDefaultImageAssetID(new_id);
  754. }
  755. if (getNormalId() == old_id)
  756. {
  757. setNormalId(new_id);
  758. }
  759. if (mNormalTexCtrl->getDefaultImageAssetID() == old_id)
  760. {
  761. mNormalTexCtrl->setDefaultImageAssetID(new_id);
  762. }
  763. }
  764. void LLPreviewMaterial::loadDefaults()
  765. {
  766. tinygltf::Model model_in;
  767. model_in.materials.resize(1);
  768. setFromGltfModel(model_in, 0, true);
  769. }
  770. void LLPreviewMaterial::setTextureUploadId(LLTextureCtrl* ctrlp,
  771. const LLUUID& id)
  772. {
  773. U32 dirty_flag = getDirtyFlagFromCtrl(ctrlp);
  774. // If HBObjectBackup::validateAssetPerms() returns true, then we do have
  775. // an inventory item bearing the proper texture Id and suitable permissions
  776. // for reuse by this material. HB
  777. if (id.notNull() && !HBObjectBackup::validateAssetPerms(id, true))
  778. {
  779. switch (dirty_flag)
  780. {
  781. case MAT_BASE_COLOR_TEX_DIRTY:
  782. mBaseColorTextureUploadId = id;
  783. break;
  784. case MAT_NORMAL_TEX_DIRTY:
  785. mNormalTextureUploadId = id;
  786. break;
  787. case MAT_ROUGHTNESS_TEX_DIRTY:
  788. mMetallicTextureUploadId = id;
  789. break;
  790. case MAT_EMISIVE_TEX_DIRTY:
  791. mEmissiveTextureUploadId = id;
  792. default:
  793. break;
  794. }
  795. }
  796. markChangesUnsaved(dirty_flag);
  797. }
  798. struct LLRenderMaterialFunctor final : public LLSelectedTEFunctor
  799. {
  800. LLRenderMaterialFunctor(const LLUUID& id)
  801. : mMatId(id)
  802. {
  803. }
  804. bool apply(LLViewerObject* objectp, S32 te) override
  805. {
  806. if (objectp && objectp->permModify() && objectp->getVolume())
  807. {
  808. LLVOVolume* vobjp = (LLVOVolume*)objectp;
  809. // Note: false = preview only
  810. vobjp->setRenderMaterialID(te, mMatId, false);
  811. vobjp->updateTEMaterialTextures(te);
  812. }
  813. return true;
  814. }
  815. LLUUID mMatId;
  816. };
  817. class LLRenderMatOverrider final : public LLSelectedNodeFunctor
  818. {
  819. protected:
  820. LOG_CLASS(LLRenderMatOverrider);
  821. public:
  822. LLRenderMatOverrider(const LLUUID& object_id, S32 te)
  823. : mObjectId(object_id),
  824. mObjectTE(te),
  825. mSuccess(false)
  826. {
  827. }
  828. bool apply(LLSelectNode* nodep) override
  829. {
  830. LLPreviewMaterial* editorp =
  831. LLPreviewMaterial::getLiveEditorInstance();
  832. if (!editorp) // Check in case the live preview has gone... HB
  833. {
  834. return false;
  835. }
  836. LLViewerObject* objectp = nodep->getObject();
  837. if (!objectp || !objectp->permModify() || !objectp->getVolume())
  838. {
  839. return false;
  840. }
  841. // Avatars have TEs but no faces.
  842. U8 num_tes = llmin(objectp->getNumTEs(), objectp->getNumFaces());
  843. for (U8 te = 0; te < num_tes; ++te)
  844. {
  845. if (!nodep->isTESelected(te))
  846. {
  847. continue;
  848. }
  849. LLTextureEntry* tep = objectp->getTE(te);
  850. if (!tep || !tep->getGLTFMaterial())
  851. {
  852. // Overrides are not supposed to work or apply if there is no
  853. // base material to work from.
  854. continue;
  855. }
  856. LLPointer<LLGLTFMaterial> matp = tep->getGLTFMaterialOverride();
  857. if (matp.isNull())
  858. {
  859. // Start with a material override which does not make any
  860. // changes
  861. matp = new LLGLTFMaterial();
  862. }
  863. else
  864. {
  865. matp = new LLGLTFMaterial(*matp);
  866. }
  867. U32 changed_flags = editorp->getUnsavedChangesFlags();
  868. U32 reverted_flags = editorp->getRevertedChangesFlags();
  869. LLPointer<LLGLTFMaterial> revmatp;
  870. if (nodep->mSavedGLTFOverrideMaterials.size() > te)
  871. {
  872. if (nodep->mSavedGLTFOverrideMaterials[te].notNull())
  873. {
  874. revmatp = nodep->mSavedGLTFOverrideMaterials[te];
  875. }
  876. else
  877. {
  878. // mSavedGLTFOverrideMaterials[te] being present but null
  879. // means we need to use a default value.
  880. revmatp = new LLGLTFMaterial();
  881. }
  882. }
  883. bool has_revert = revmatp.notNull();
  884. bool check_local_tex = false;
  885. // Override the object values with values from editor where
  886. // appropriate
  887. if (changed_flags & MAT_BASE_COLOR_TEX_DIRTY)
  888. {
  889. matp->setBaseColorId(editorp->getBaseColorId(), true);
  890. check_local_tex = true;
  891. }
  892. else if (has_revert && (reverted_flags & MAT_BASE_COLOR_TEX_DIRTY))
  893. {
  894. matp->setBaseColorId(revmatp->mTextureId[BASECOLIDX]);
  895. check_local_tex = true;
  896. }
  897. if (check_local_tex)
  898. {
  899. check_local_tex = false;
  900. const LLUUID& tracking_id =
  901. editorp->getLocalTexTrackingIdFromFlag(BASECOLIDX);
  902. if (tracking_id.notNull())
  903. {
  904. LLLocalBitmap::associateGLTFMaterial(tracking_id, matp);
  905. }
  906. }
  907. if (changed_flags & MAT_NORMAL_TEX_DIRTY)
  908. {
  909. matp->setNormalId(editorp->getNormalId(), true);
  910. check_local_tex = true;
  911. }
  912. else if (has_revert && (reverted_flags & MAT_NORMAL_TEX_DIRTY))
  913. {
  914. matp->setNormalId(revmatp->mTextureId[NORMALIDX]);
  915. check_local_tex = true;
  916. }
  917. if (check_local_tex)
  918. {
  919. check_local_tex = false;
  920. const LLUUID& tracking_id =
  921. editorp->getLocalTexTrackingIdFromFlag(NORMALIDX);
  922. if (tracking_id.notNull())
  923. {
  924. LLLocalBitmap::associateGLTFMaterial(tracking_id, matp);
  925. }
  926. }
  927. if (changed_flags & MAT_ROUGHTNESS_TEX_DIRTY)
  928. {
  929. matp->setMetallicRoughnessId(editorp->getMetallicRoughnessId(),
  930. true);
  931. }
  932. else if (has_revert && (reverted_flags & MAT_ROUGHTNESS_TEX_DIRTY))
  933. {
  934. matp->setMetallicRoughnessId(revmatp->mTextureId[MROUGHIDX],
  935. false);
  936. }
  937. if (check_local_tex)
  938. {
  939. check_local_tex = false;
  940. const LLUUID& tracking_id =
  941. editorp->getLocalTexTrackingIdFromFlag(MROUGHIDX);
  942. if (tracking_id.notNull())
  943. {
  944. LLLocalBitmap::associateGLTFMaterial(tracking_id, matp);
  945. }
  946. }
  947. if (changed_flags & MAT_EMISIVE_TEX_DIRTY)
  948. {
  949. matp->setEmissiveId(editorp->getEmissiveId(), true);
  950. }
  951. else if (has_revert && (reverted_flags & MAT_EMISIVE_TEX_DIRTY))
  952. {
  953. matp->setEmissiveId(revmatp->mTextureId[EMISSIVEIDX]);
  954. }
  955. if (check_local_tex)
  956. {
  957. check_local_tex = false;
  958. const LLUUID& tracking_id =
  959. editorp->getLocalTexTrackingIdFromFlag(EMISSIVEIDX);
  960. if (tracking_id.notNull())
  961. {
  962. LLLocalBitmap::associateGLTFMaterial(tracking_id, matp);
  963. }
  964. }
  965. constexpr U32 COLOR_FLAGS = MAT_TRANSPARENCY_DIRTY |
  966. MAT_BASE_COLOR_DIRTY;
  967. if (changed_flags & COLOR_FLAGS)
  968. {
  969. matp->setBaseColorFactor(editorp->getBaseColor(), true);
  970. }
  971. else if (has_revert && (reverted_flags & COLOR_FLAGS))
  972. {
  973. matp->setBaseColorFactor(revmatp->mBaseColor);
  974. }
  975. if (changed_flags & MAT_EMISIVE_COLOR_DIRTY)
  976. {
  977. LLColor3 color(editorp->getEmissiveColor());
  978. matp->setEmissiveColorFactor(color, true);
  979. }
  980. else if (has_revert && (reverted_flags & MAT_EMISIVE_COLOR_DIRTY))
  981. {
  982. matp->setEmissiveColorFactor(revmatp->mEmissiveColor);
  983. }
  984. if (changed_flags & MAT_ALPHA_MODE_DIRTY)
  985. {
  986. matp->setAlphaMode(editorp->getAlphaMode(), true);
  987. }
  988. else if (has_revert && (reverted_flags & MAT_ALPHA_MODE_DIRTY))
  989. {
  990. matp->setAlphaMode(revmatp->mAlphaMode);
  991. }
  992. if (changed_flags & MAT_ALPHA_CUTOFF_DIRTY)
  993. {
  994. matp->setAlphaCutoff(editorp->getAlphaCutoff(), true);
  995. }
  996. else if (has_revert && (reverted_flags & MAT_ALPHA_CUTOFF_DIRTY))
  997. {
  998. matp->setAlphaCutoff(revmatp->mAlphaCutoff);
  999. }
  1000. if (changed_flags & MAT_METALNESS_DIRTY)
  1001. {
  1002. matp->setMetallicFactor(editorp->getMetalnessFactor(), true);
  1003. }
  1004. else if (has_revert && (reverted_flags & MAT_METALNESS_DIRTY))
  1005. {
  1006. matp->setMetallicFactor(revmatp->mMetallicFactor);
  1007. }
  1008. if (changed_flags & MAT_ROUGHTNESS_DIRTY)
  1009. {
  1010. matp->setRoughnessFactor(editorp->getRoughnessFactor(), true);
  1011. }
  1012. else if (has_revert && (reverted_flags & MAT_ROUGHTNESS_DIRTY))
  1013. {
  1014. matp->setRoughnessFactor(revmatp->mRoughnessFactor);
  1015. }
  1016. if (changed_flags & MAT_DOUBLE_SIDED_DIRTY)
  1017. {
  1018. matp->setDoubleSided(editorp->getDoubleSided(), true);
  1019. }
  1020. else if (has_revert && (reverted_flags & MAT_DOUBLE_SIDED_DIRTY))
  1021. {
  1022. matp->setDoubleSided(revmatp->mDoubleSided);
  1023. }
  1024. if (te == mObjectTE && objectp->getID() == mObjectId)
  1025. {
  1026. mSuccess = true;
  1027. }
  1028. LLGLTFMaterialList::queueModify(objectp, te, matp.get());
  1029. }
  1030. return true;
  1031. }
  1032. bool getResult() const { return mSuccess; }
  1033. static void modifyCallback(bool success)
  1034. {
  1035. if (!success)
  1036. {
  1037. // Something went wrong update selection
  1038. llwarns << "Failed to update material" << llendl;
  1039. LLPreviewMaterial::markForLiveUpdate();
  1040. }
  1041. // Else we will get a call to updateLive() from LLGLTFMaterialList
  1042. }
  1043. private:
  1044. LLUUID mObjectId;
  1045. S32 mObjectTE;
  1046. bool mSuccess;
  1047. };
  1048. void LLPreviewMaterial::applyToSelection()
  1049. {
  1050. if (!mIsOverride || (!mUnsavedChanges && !mRevertedChanges))
  1051. {
  1052. return;
  1053. }
  1054. const std::string& url =
  1055. gAgent.getRegionCapability("ModifyMaterialParams");
  1056. if (url.empty())
  1057. {
  1058. llwarns << "Missing ModifyMaterialParams capability in this region"
  1059. << llendl;
  1060. LLPointer<LLFetchedGLTFMaterial> matp(new LLFetchedGLTFMaterial());
  1061. getGLTFMaterial(matp);
  1062. static const LLUUID dummy("984e183e-7811-4b05-a502-d79c6f978a98");
  1063. gGLTFMaterialList.addMaterial(dummy, matp);
  1064. LLRenderMaterialFunctor mat_func(dummy);
  1065. gSelectMgr.getSelection()->applyToTEs(&mat_func);
  1066. return;
  1067. }
  1068. sOverrideInProgress = true;
  1069. LLRenderMatOverrider func(sOverrideObjectId, sOverrideObjectTE);
  1070. gSelectMgr.getSelection()->applyToNodes(&func);
  1071. LLGLTFMaterialList::flushUpdates(&LLRenderMatOverrider::modifyCallback);
  1072. if (!func.getResult())
  1073. {
  1074. sOverrideInProgress = false;
  1075. }
  1076. mUnsavedChanges = mRevertedChanges = 0;
  1077. if (gFloaterToolsp)
  1078. {
  1079. gFloaterToolsp->dirty();
  1080. }
  1081. }
  1082. void LLPreviewMaterial::getGLTFMaterial(LLGLTFMaterial* matp)
  1083. {
  1084. if (!matp) return; // Paranoia
  1085. matp->mTextureId[BASECOLIDX] = getBaseColorId();
  1086. matp->mTextureId[NORMALIDX] = getNormalId();
  1087. matp->mTextureId[MROUGHIDX] = getMetallicRoughnessId();
  1088. matp->mTextureId[EMISSIVEIDX] = getEmissiveId();
  1089. matp->mBaseColor = getBaseColor();
  1090. matp->mBaseColor.mV[3] = getTransparency();
  1091. matp->mEmissiveColor = getEmissiveColor();
  1092. matp->setAlphaMode(getAlphaMode());
  1093. matp->mAlphaCutoff = getAlphaCutoff();
  1094. matp->mMetallicFactor = getMetalnessFactor();
  1095. matp->mRoughnessFactor = getRoughnessFactor();
  1096. matp->mAlphaCutoff = getAlphaCutoff();
  1097. }
  1098. void LLPreviewMaterial::setFromGLTFMaterial(LLGLTFMaterial* matp)
  1099. {
  1100. if (!matp) return; // Paranoia
  1101. setBaseColorId(matp->mTextureId[BASECOLIDX]);
  1102. setNormalId(matp->mTextureId[NORMALIDX]);
  1103. setMetallicRoughnessId(matp->mTextureId[MROUGHIDX]);
  1104. setEmissiveId(matp->mTextureId[EMISSIVEIDX]);
  1105. setBaseColor(matp->mBaseColor);
  1106. setAlphaMode(matp->getAlphaMode());
  1107. setAlphaCutoff(matp->mAlphaCutoff);
  1108. setMetalnessFactor(matp->mMetallicFactor);
  1109. setRoughnessFactor(matp->mRoughnessFactor);
  1110. setEmissiveColor(matp->mEmissiveColor);
  1111. setDoubleSided(matp->mDoubleSided);
  1112. if (!matp->hasLocalTextures())
  1113. {
  1114. return;
  1115. }
  1116. for (LLGLTFMaterial::local_tex_map_t::const_iterator
  1117. it = matp->mTrackingIdToLocalTexture.begin(),
  1118. end = matp->mTrackingIdToLocalTexture.end();
  1119. it != end; ++it)
  1120. {
  1121. const LLUUID& tracking_id = it->first;
  1122. const LLUUID& world_id = LLLocalBitmap::getWorldID(tracking_id);
  1123. if (it->second != world_id)
  1124. {
  1125. llwarns << "World Id for local texture " << tracking_id
  1126. << " does not match." << llendl;
  1127. }
  1128. if (matp->mTextureId[BASECOLIDX] == world_id)
  1129. {
  1130. subscribeToLocalTexture(MAT_BASE_COLOR_TEX_DIRTY, tracking_id);
  1131. }
  1132. if (matp->mTextureId[NORMALIDX] == world_id)
  1133. {
  1134. subscribeToLocalTexture(MAT_NORMAL_TEX_DIRTY, tracking_id);
  1135. }
  1136. if (matp->mTextureId[MROUGHIDX] == world_id)
  1137. {
  1138. subscribeToLocalTexture(MAT_ROUGHTNESS_TEX_DIRTY, tracking_id);
  1139. }
  1140. if (matp->mTextureId[EMISSIVEIDX] == world_id)
  1141. {
  1142. subscribeToLocalTexture(MAT_EMISIVE_TEX_DIRTY, tracking_id);
  1143. }
  1144. }
  1145. }
  1146. class LLSelectedTEGetMatData final : public LLSelectedTEFunctor
  1147. {
  1148. protected:
  1149. LOG_CLASS(LLSelectedTEGetMatData);
  1150. public:
  1151. LLSelectedTEGetMatData(bool for_override)
  1152. : mIsOverride(for_override),
  1153. mObject(NULL),
  1154. mObjectTE(-1),
  1155. mFirst(true),
  1156. mIdenticalTexColor(true),
  1157. mIdenticalTexMetal(true),
  1158. mIdenticalTexEmissive(true),
  1159. mIdenticalTexNormal(true)
  1160. {
  1161. }
  1162. bool apply(LLViewerObject* objectp, S32 te_index) override
  1163. {
  1164. if (!objectp)
  1165. {
  1166. return false;
  1167. }
  1168. mMaterialId = objectp->getRenderMaterialID(te_index);
  1169. if (mMaterialId.isNull())
  1170. {
  1171. return false;
  1172. }
  1173. bool can_use = mIsOverride ? objectp->permModify()
  1174. : objectp->permCopy();
  1175. if (!can_use)
  1176. {
  1177. return false;
  1178. }
  1179. LLTextureEntry* tep = objectp->getTE(te_index);
  1180. if (!tep)
  1181. {
  1182. return false;
  1183. }
  1184. if (!mIsOverride)
  1185. {
  1186. LLLocalGLTFMaterial* matp =
  1187. dynamic_cast<LLLocalGLTFMaterial*>(tep->getGLTFMaterial());
  1188. if (matp)
  1189. {
  1190. mLocalMaterial = matp;
  1191. }
  1192. mMaterial = tep->getGLTFRenderMaterial();
  1193. if (mMaterial.isNull())
  1194. {
  1195. llwarns << "Object " << objectp->getID()
  1196. << " has material Id " << mMaterialId
  1197. << " but no render material." << llendl;
  1198. mMaterial = gGLTFMaterialList.getMaterial(mMaterialId);
  1199. }
  1200. return true;
  1201. }
  1202. LLUUID tex_color_id, tex_metal_id, tex_emissive_id, tex_normal_id;
  1203. LLPointer<LLGLTFMaterial> matp = tep->getGLTFRenderMaterial();
  1204. if (matp.notNull())
  1205. {
  1206. tex_color_id = matp->mTextureId[BASECOLIDX];
  1207. tex_metal_id = matp->mTextureId[MROUGHIDX];
  1208. tex_emissive_id = matp->mTextureId[EMISSIVEIDX];
  1209. tex_normal_id = matp->mTextureId[NORMALIDX];
  1210. }
  1211. if (mFirst)
  1212. {
  1213. mFirst = false;
  1214. mObject = objectp;
  1215. mObjectTE = te_index;
  1216. mObjectId = objectp->getID();
  1217. mMaterial = matp;
  1218. mTexColorId = tex_color_id;
  1219. mTexMetalId = tex_metal_id;
  1220. mTexEmissiveId = tex_emissive_id;
  1221. mTexNormalId = tex_normal_id;
  1222. }
  1223. else
  1224. {
  1225. if (mTexColorId != tex_color_id)
  1226. {
  1227. mIdenticalTexColor = false;
  1228. }
  1229. if (mTexMetalId != tex_metal_id)
  1230. {
  1231. mIdenticalTexMetal = false;
  1232. }
  1233. if (mTexEmissiveId != tex_emissive_id)
  1234. {
  1235. mIdenticalTexEmissive = false;
  1236. }
  1237. if (mTexNormalId != tex_normal_id)
  1238. {
  1239. mIdenticalTexNormal = false;
  1240. }
  1241. }
  1242. return true;
  1243. }
  1244. public:
  1245. LLUUID mObjectId;
  1246. LLUUID mMaterialId;
  1247. LLUUID mTexColorId;
  1248. LLUUID mTexMetalId;
  1249. LLUUID mTexEmissiveId;
  1250. LLUUID mTexNormalId;
  1251. // Used by can_use_objects_material() to pass any found inv item Id for
  1252. // this material. HB
  1253. LLUUID mInvItemId;
  1254. LLViewerObject* mObject;
  1255. LLPointer<LLGLTFMaterial> mMaterial;
  1256. LLPointer<LLLocalGLTFMaterial> mLocalMaterial;
  1257. S32 mObjectTE;
  1258. bool mIdenticalTexColor;
  1259. bool mIdenticalTexMetal;
  1260. bool mIdenticalTexEmissive;
  1261. bool mIdenticalTexNormal;
  1262. private:
  1263. bool mIsOverride;
  1264. bool mFirst;
  1265. };
  1266. struct LLSelectedTEUpdateOverrides final : public LLSelectedNodeFunctor
  1267. {
  1268. LLSelectedTEUpdateOverrides(LLPreviewMaterial* editorp)
  1269. : mEditor(editorp)
  1270. {
  1271. }
  1272. bool apply(LLSelectNode* nodep) override
  1273. {
  1274. LLViewerObject* objectp = nodep->getObject();
  1275. if (!objectp)
  1276. {
  1277. return false;
  1278. }
  1279. // Avatars have TEs but no faces.
  1280. U8 num_tes = llmin(objectp->getNumTEs(), objectp->getNumFaces());
  1281. for (U8 te = 0; te < num_tes; ++te)
  1282. {
  1283. LLTextureEntry* tep = objectp->getTE(te);
  1284. if (!tep)
  1285. {
  1286. return false;
  1287. }
  1288. LLGLTFMaterial* omatp = tep->getGLTFMaterialOverride();
  1289. if (mEditor->updateMaterialLocalSubscription(omatp))
  1290. {
  1291. LLGLTFMaterial* rmatp = tep->getGLTFRenderMaterial();
  1292. mEditor->updateMaterialLocalSubscription(rmatp);
  1293. }
  1294. }
  1295. return true;
  1296. }
  1297. LLPreviewMaterial* mEditor;
  1298. };
  1299. bool LLPreviewMaterial::setFromSelection()
  1300. {
  1301. sSelectionNeedsUpdate = false;
  1302. LLObjectSelectionHandle selectionp = gSelectMgr.getSelection();
  1303. mHasSelection = !selectionp->isEmpty();
  1304. LLSelectedTEGetMatData func(mIsOverride);
  1305. selectionp->applyToTEs(&func);
  1306. if (func.mMaterial.notNull())
  1307. {
  1308. setFromGLTFMaterial(func.mMaterial);
  1309. setEnableEditing(true);
  1310. // *TODO: apply local texture data to all materials in selection.
  1311. }
  1312. else
  1313. {
  1314. // Pick defaults from a blank material;
  1315. LLGLTFMaterial blank_mat;
  1316. setFromGLTFMaterial(&blank_mat);
  1317. if (mIsOverride)
  1318. {
  1319. setEnableEditing(false);
  1320. }
  1321. }
  1322. if (mIsOverride)
  1323. {
  1324. mBaseColorTexCtrl->setTentative(!func.mIdenticalTexColor);
  1325. mMetallicTexCtrl->setTentative(!func.mIdenticalTexMetal);
  1326. mEmissiveTexCtrl->setTentative(!func.mIdenticalTexEmissive);
  1327. mNormalTexCtrl->setTentative(!func.mIdenticalTexNormal);
  1328. // Memorize selection data for filtering further updates
  1329. sOverrideObjectId = func.mObjectId;
  1330. sOverrideObjectTE = func.mObjectTE;
  1331. // Overrides might have been updated: refresh state of local textures.
  1332. LLSelectedTEUpdateOverrides local_tex_func(this);
  1333. selectionp->applyToNodes(&local_tex_func);
  1334. }
  1335. return func.mMaterial.notNull();
  1336. }
  1337. bool LLPreviewMaterial::setFromGltfModel(const tinygltf::Model& model, S32 idx,
  1338. bool set_textures)
  1339. {
  1340. if (idx >= (S32)model.materials.size())
  1341. {
  1342. return false;
  1343. }
  1344. const tinygltf::Material& mat = model.materials[idx];
  1345. if (set_textures)
  1346. {
  1347. LLUUID id;
  1348. S32 i = mat.pbrMetallicRoughness.baseColorTexture.index;
  1349. if (i >= 0)
  1350. {
  1351. id.set(model.images[i].uri);
  1352. setBaseColorId(id);
  1353. }
  1354. else
  1355. {
  1356. setBaseColorId(LLUUID::null);
  1357. }
  1358. i = mat.normalTexture.index;
  1359. if (i >= 0)
  1360. {
  1361. id.set(model.images[i].uri);
  1362. setNormalId(id);
  1363. }
  1364. else
  1365. {
  1366. setNormalId(LLUUID::null);
  1367. }
  1368. i = mat.pbrMetallicRoughness.metallicRoughnessTexture.index;
  1369. if (i >= 0)
  1370. {
  1371. id.set(model.images[i].uri);
  1372. setMetallicRoughnessId(id);
  1373. }
  1374. else
  1375. {
  1376. setMetallicRoughnessId(LLUUID::null);
  1377. }
  1378. i = mat.emissiveTexture.index;
  1379. if (i >= 0)
  1380. {
  1381. id.set(model.images[i].uri);
  1382. setEmissiveId(id);
  1383. }
  1384. else
  1385. {
  1386. setEmissiveId(LLUUID::null);
  1387. }
  1388. }
  1389. setAlphaMode(mat.alphaMode);
  1390. setAlphaCutoff(mat.alphaCutoff);
  1391. setBaseColor(LLTinyGLTFHelper::getColor(mat.pbrMetallicRoughness.baseColorFactor));
  1392. setEmissiveColor(LLTinyGLTFHelper::getColor(mat.emissiveFactor));
  1393. setMetalnessFactor(mat.pbrMetallicRoughness.metallicFactor);
  1394. setRoughnessFactor(mat.pbrMetallicRoughness.roughnessFactor);
  1395. setDoubleSided(mat.doubleSided);
  1396. return true;
  1397. }
  1398. std::string LLPreviewMaterial::getImageNameFromUri(std::string image_uri,
  1399. std::string texture_type)
  1400. {
  1401. // Make the texture type all lower case. HB
  1402. LLStringUtil::toLower(texture_type);
  1403. // Replace alien directory limiters so that getBaseFileName() works.
  1404. #if LL_WINDOWS
  1405. LLStringUtil::replaceChar(image_uri, '/', LL_DIR_DELIM_CHR);
  1406. #else
  1407. LLStringUtil::replaceChar(image_uri, '\\', LL_DIR_DELIM_CHR);
  1408. #endif
  1409. // Use the base file name, limited to 64 characters as the image URI.
  1410. image_uri = gDirUtil.getBaseFileName(image_uri, true);
  1411. if (image_uri.size() > 64)
  1412. {
  1413. image_uri.resize(64);
  1414. }
  1415. std::string uri = image_uri;
  1416. // Lower-case it for comparison
  1417. LLStringUtil::toLower(uri);
  1418. // Remove spacing characters from URI
  1419. uri.erase(std::remove_if(uri.begin(), uri.end(), isspace), uri.end());
  1420. if (uri.empty())
  1421. {
  1422. // URI is empty, so we must reorganize the string a bit to include the
  1423. // name and an explicit name type. E.g. "DamagedHelmet: (emissive)".
  1424. return llformat("%s (%s)", mMaterialNameShort.c_str(),
  1425. texture_type.c_str());
  1426. }
  1427. // Remove spacing characters from texture type
  1428. std::string type = texture_type;
  1429. type.erase(std::remove_if(type.begin(), type.end(), isspace), type.end());
  1430. // Let's see if texture_type is already part of the URI.
  1431. if (uri.find(type) != std::string::npos)
  1432. {
  1433. // It is indeed part of it, so just use it directly with the name of
  1434. // the material. E.g. AlienBust: normal_layer
  1435. return llformat("%s: %s", mMaterialNameShort.c_str(),
  1436. image_uri.c_str());
  1437. }
  1438. // URI does not include the type and is not empty, so we can include
  1439. // everything. E.g. "DamagedHelmet: base layer (base color)"
  1440. return llformat("%s: %s (%s)", mMaterialNameShort.c_str(),
  1441. image_uri.c_str(), texture_type.c_str());
  1442. }
  1443. void LLPreviewMaterial::setFromGltfMetaData(const std::string& filename,
  1444. const tinygltf::Model& model,
  1445. S32 index)
  1446. {
  1447. mMaterialNameShort = gDirUtil.getBaseFileName(filename, true);
  1448. LLInventoryObject::correctInventoryName(mMaterialNameShort);
  1449. S32 count = model.materials.size();
  1450. std::string material_name;
  1451. if (count > index && !model.materials[index].name.empty())
  1452. {
  1453. material_name = model.materials[index].name;
  1454. }
  1455. else if (model.scenes.size())
  1456. {
  1457. const tinygltf::Scene& scene_in = model.scenes[0];
  1458. if (scene_in.name.size())
  1459. {
  1460. material_name = scene_in.name;
  1461. }
  1462. }
  1463. if (material_name.empty())
  1464. {
  1465. mMaterialName = mMaterialNameShort;
  1466. }
  1467. else
  1468. {
  1469. mMaterialName = llformat("%s (%s)", mMaterialNameShort.c_str(),
  1470. material_name.c_str());
  1471. LLInventoryObject::correctInventoryName(mMaterialName);
  1472. }
  1473. setTitle(mMaterialName);
  1474. // For ease of inventory management, we prepend the material name.
  1475. std::string base_name = mMaterialName + ": ";
  1476. mBaseColorName = base_name + MAT_BASE_COLOR_DEFAULT_NAME;
  1477. mNormalName = base_name + MAT_NORMAL_DEFAULT_NAME;
  1478. mMetallicRoughnessName = base_name + MAT_METALLIC_DEFAULT_NAME;
  1479. mEmissiveName = base_name + MAT_EMISSIVE_DEFAULT_NAME;
  1480. if (index < 0 || index >= count)
  1481. {
  1482. return;
  1483. }
  1484. S32 images = model.images.size();
  1485. const tinygltf::Material& first_mat = model.materials[index];
  1486. S32 i = first_mat.pbrMetallicRoughness.baseColorTexture.index;
  1487. if (i >= 0 && i < images)
  1488. {
  1489. mBaseColorName = getImageNameFromUri(model.images[i].uri,
  1490. MAT_BASE_COLOR_DEFAULT_NAME);
  1491. LLInventoryObject::correctInventoryName(mBaseColorName);
  1492. }
  1493. i = first_mat.normalTexture.index;
  1494. if (i >= 0 && i < images)
  1495. {
  1496. mNormalName = getImageNameFromUri(model.images[i].uri,
  1497. MAT_NORMAL_DEFAULT_NAME);
  1498. LLInventoryObject::correctInventoryName(mNormalName);
  1499. }
  1500. i = first_mat.pbrMetallicRoughness.metallicRoughnessTexture.index;
  1501. if (i >= 0 && i < images)
  1502. {
  1503. mMetallicRoughnessName =
  1504. getImageNameFromUri(model.images[i].uri,
  1505. MAT_METALLIC_DEFAULT_NAME);
  1506. LLInventoryObject::correctInventoryName(mMetallicRoughnessName);
  1507. }
  1508. i = first_mat.emissiveTexture.index;
  1509. if (i >= 0 && i < images)
  1510. {
  1511. mEmissiveName = getImageNameFromUri(model.images[i].uri,
  1512. MAT_EMISSIVE_DEFAULT_NAME);
  1513. LLInventoryObject::correctInventoryName(mEmissiveName);
  1514. }
  1515. }
  1516. void LLPreviewMaterial::loadMaterial(const tinygltf::Model& model,
  1517. const std::string& filename, S32 index)
  1518. {
  1519. S32 count = model.materials.size();
  1520. if (index < 0 || index >= count)
  1521. {
  1522. llwarns << "Material index (" << index << ") out of range for file: "
  1523. << filename << " - Max index is: " << count - 1 << llendl;
  1524. return;
  1525. }
  1526. std::string folder = gDirUtil.getDirName(filename);
  1527. tinygltf::Material mat = model.materials[index];
  1528. tinygltf::Model model_out;
  1529. model_out.asset.version = "2.0";
  1530. model_out.materials.resize(1);
  1531. // Get base color texture
  1532. LLPointer<LLImageRaw> base_imgp =
  1533. LLTinyGLTFHelper::getTexture(folder, model,
  1534. mat.pbrMetallicRoughness.baseColorTexture.index,
  1535. mBaseColorName);
  1536. // Get normal texture
  1537. LLPointer<LLImageRaw> norm_imgp =
  1538. LLTinyGLTFHelper::getTexture(folder, model, mat.normalTexture.index,
  1539. mNormalName);
  1540. // Get metallic-roughness texture
  1541. LLPointer<LLImageRaw> mr_imgp =
  1542. LLTinyGLTFHelper::getTexture(folder, model,
  1543. mat.pbrMetallicRoughness.metallicRoughnessTexture.index,
  1544. mMetallicRoughnessName);
  1545. // Get emissive texture
  1546. LLPointer<LLImageRaw> em_imgp =
  1547. LLTinyGLTFHelper::getTexture(folder, model, mat.emissiveTexture.index,
  1548. mNormalName);
  1549. // Get occlusion map if needed
  1550. LLPointer<LLImageRaw> occl_imgp;
  1551. if (mat.occlusionTexture.index !=
  1552. mat.pbrMetallicRoughness.metallicRoughnessTexture.index)
  1553. {
  1554. std::string tmp;
  1555. occl_imgp = LLTinyGLTFHelper::getTexture(folder, model,
  1556. mat.occlusionTexture.index,
  1557. tmp);
  1558. }
  1559. LLTinyGLTFHelper::initFetchedTextures(mat, base_imgp, norm_imgp, mr_imgp,
  1560. em_imgp, occl_imgp,
  1561. mBaseColorFetched, mNormalFetched,
  1562. mMetallicRoughnessFetched,
  1563. mEmissiveFetched);
  1564. if (base_imgp.notNull())
  1565. {
  1566. mBaseColorJ2C = LLViewerTextureList::convertToUploadFile(base_imgp);
  1567. }
  1568. if (norm_imgp.notNull())
  1569. {
  1570. mNormalJ2C = LLViewerTextureList::convertToUploadFile(norm_imgp,
  1571. gMaxImageSizeDefault,
  1572. true);
  1573. }
  1574. if (mr_imgp.notNull())
  1575. {
  1576. mMetallicRoughnessJ2C =
  1577. LLViewerTextureList::convertToUploadFile(mr_imgp);
  1578. }
  1579. if (em_imgp.notNull())
  1580. {
  1581. mEmissiveJ2C = LLViewerTextureList::convertToUploadFile(em_imgp);
  1582. }
  1583. LLUUID base_color_id;
  1584. if (mBaseColorFetched.notNull())
  1585. {
  1586. mBaseColorFetched->setBoostLevel(LLGLTexture::BOOST_PREVIEW);
  1587. mBaseColorFetched->forceToSaveRawImage(0, F32_MAX);
  1588. base_color_id = mBaseColorFetched->getID();
  1589. if (mBaseColorName.empty())
  1590. {
  1591. mBaseColorName = MAT_BASE_COLOR_DEFAULT_NAME;
  1592. }
  1593. }
  1594. setBaseColorId(base_color_id);
  1595. setBaseColorUploadId(base_color_id);
  1596. LLUUID normal_id;
  1597. if (mNormalFetched.notNull())
  1598. {
  1599. mNormalFetched->setBoostLevel(LLGLTexture::BOOST_PREVIEW);
  1600. mNormalFetched->forceToSaveRawImage(0, F32_MAX);
  1601. normal_id = mNormalFetched->getID();
  1602. if (mNormalName.empty())
  1603. {
  1604. mNormalName = MAT_NORMAL_DEFAULT_NAME;
  1605. }
  1606. }
  1607. setNormalId(normal_id);
  1608. setNormalUploadId(normal_id);
  1609. LLUUID mr_id;
  1610. if (mMetallicRoughnessFetched.notNull())
  1611. {
  1612. mMetallicRoughnessFetched->setBoostLevel(LLGLTexture::BOOST_PREVIEW);
  1613. mMetallicRoughnessFetched->forceToSaveRawImage(0, F32_MAX);
  1614. mr_id = mMetallicRoughnessFetched->getID();
  1615. if (mMetallicRoughnessName.empty())
  1616. {
  1617. mMetallicRoughnessName = MAT_METALLIC_DEFAULT_NAME;
  1618. }
  1619. }
  1620. setMetallicRoughnessId(mr_id);
  1621. setMetallicRoughnessUploadId(mr_id);
  1622. LLUUID emissive_id;
  1623. if (mEmissiveFetched.notNull())
  1624. {
  1625. mEmissiveFetched->setBoostLevel(LLGLTexture::BOOST_PREVIEW);
  1626. mEmissiveFetched->forceToSaveRawImage(0, F32_MAX);
  1627. emissive_id = mEmissiveFetched->getID();
  1628. if (mEmissiveName.empty())
  1629. {
  1630. mEmissiveName = MAT_EMISSIVE_DEFAULT_NAME;
  1631. }
  1632. }
  1633. setEmissiveId(emissive_id);
  1634. setEmissiveUploadId(emissive_id);
  1635. setFromGltfModel(model, index);
  1636. setFromGltfMetaData(filename, model, index);
  1637. // SL-19392: double sided materials double the number of pixels that must
  1638. // be rasterized,and a great many tools that export GLTF simply leave
  1639. // double sided enabled whether or not it is necessary.
  1640. if (getDoubleSided())
  1641. {
  1642. setDoubleSided(false);
  1643. }
  1644. mCanCopy = true;
  1645. mAssetStatus = PREVIEW_ASSET_LOADED;
  1646. markChangesUnsaved(U32_MAX);
  1647. setFocus(true);
  1648. applyToSelection();
  1649. }
  1650. //static
  1651. void LLPreviewMaterial::onSelectionChanged()
  1652. {
  1653. // Drop selection updates if we are waiting for overrides to finish
  1654. // applying to not reset values (might need a timeout).
  1655. if (!sOverrideInProgress)
  1656. {
  1657. sSelectionNeedsUpdate = true;
  1658. }
  1659. }
  1660. //static
  1661. void LLPreviewMaterial::markForLiveUpdate()
  1662. {
  1663. if (sOverrideInProgress)
  1664. {
  1665. LL_DEBUGS("GLTF") << "Updating live material from selection"
  1666. << LL_ENDL;
  1667. }
  1668. sSelectionNeedsUpdate = true;
  1669. sOverrideInProgress = false;
  1670. }
  1671. //static
  1672. void LLPreviewMaterial::updateLive(const LLUUID& object_id, S32 te)
  1673. {
  1674. if (object_id != sOverrideObjectId || te != sOverrideObjectTE)
  1675. {
  1676. // Ignore if waiting for override, but if not waiting, mark selection
  1677. // dirty.
  1678. LL_DEBUGS("GLTF") << "Received a stale object update. Ignoring."
  1679. << LL_ENDL;
  1680. sSelectionNeedsUpdate = !sOverrideInProgress;
  1681. return;
  1682. }
  1683. LL_DEBUGS("GLTF") << "Updating live material from selection"
  1684. << LL_ENDL;
  1685. // Mark object for rebuild. HB
  1686. LLViewerObject* objectp = gObjectList.findObject(sOverrideObjectId);
  1687. if (objectp)
  1688. {
  1689. objectp->refreshMaterials();
  1690. }
  1691. sSelectionNeedsUpdate = true;
  1692. sOverrideInProgress = false;
  1693. }
  1694. //static
  1695. void LLPreviewMaterial::loadLive()
  1696. {
  1697. if (!sLiveEditorInstance)
  1698. {
  1699. LL_DEBUGS("GLTF") << "Creating a new live editor instance..."
  1700. << LL_ENDL;
  1701. sLiveEditorInstance = new LLPreviewMaterial("live editor", true);
  1702. }
  1703. LL_DEBUGS("GLTF") << "Loading live material from selection" << LL_ENDL;
  1704. sOverrideInProgress = false;
  1705. sLiveEditorInstance->setFromSelection();
  1706. if (!sSelectionUpdateSlot.connected())
  1707. {
  1708. sSelectionUpdateSlot =
  1709. gSelectMgr.mUpdateSignal.connect(boost::bind(&onSelectionChanged));
  1710. }
  1711. sLiveEditorInstance->open();
  1712. sLiveEditorInstance->setFocus(true);
  1713. }
  1714. //static
  1715. LLPreviewMaterial* LLPreviewMaterial::loadFromFile(const std::string& filename,
  1716. S32 index)
  1717. {
  1718. std::string error_msg, warn_msg;
  1719. tinygltf::TinyGLTF loader;
  1720. tinygltf::Model model;
  1721. bool loaded = false;
  1722. std::string exten = gDirUtil.getExtension(filename);
  1723. if (exten == "gltf")
  1724. {
  1725. loaded = loader.LoadASCIIFromFile(&model, &error_msg, &warn_msg,
  1726. filename);
  1727. }
  1728. else
  1729. {
  1730. loaded = loader.LoadBinaryFromFile(&model, &error_msg, &warn_msg,
  1731. filename);
  1732. }
  1733. if (!loaded || model.materials.empty())
  1734. {
  1735. gNotifications.add("CannotUploadMaterial");
  1736. return NULL;
  1737. }
  1738. S32 count = model.materials.size();
  1739. LLPreviewMaterial* self = NULL;
  1740. if (index >= 0)
  1741. {
  1742. if (index < count)
  1743. {
  1744. self = new LLPreviewMaterial("material_preview");
  1745. self->loadMaterial(model, filename, index);
  1746. }
  1747. else
  1748. {
  1749. gNotifications.add("CannotUploadMaterialIndex");
  1750. }
  1751. return self;
  1752. }
  1753. // Open as many material previews as there are materials in the file. HB
  1754. for (S32 i = 0; i < count; ++i)
  1755. {
  1756. LLPreviewMaterial* self = new LLPreviewMaterial("material_preview");
  1757. self->loadMaterial(model, filename, i);
  1758. }
  1759. // Return a pointer on the last opened preview floater.
  1760. return self;
  1761. }
  1762. U32 LLPreviewMaterial::getDirtyFlagFromCtrl(LLUICtrl* ctrlp)
  1763. {
  1764. // Spinners first, as they are high frequency events. HB
  1765. if (ctrlp == (LLUICtrl*)mTransparencyCtrl)
  1766. {
  1767. return MAT_TRANSPARENCY_DIRTY;
  1768. }
  1769. if (ctrlp == (LLUICtrl*)mAlphaCutoffCtrl)
  1770. {
  1771. return MAT_ALPHA_CUTOFF_DIRTY;
  1772. }
  1773. if (ctrlp == (LLUICtrl*)mMetalnessCtrl)
  1774. {
  1775. return MAT_METALNESS_DIRTY;
  1776. }
  1777. if (ctrlp == (LLUICtrl*)mRoughnessCtrl)
  1778. {
  1779. return MAT_ROUGHTNESS_DIRTY;
  1780. }
  1781. // Texture and color controls, combo and check box last, as they are low
  1782. // frequency events. HB
  1783. if (ctrlp == (LLUICtrl*)mBaseColorCtrl)
  1784. {
  1785. return MAT_BASE_COLOR_DIRTY;
  1786. }
  1787. if (ctrlp == (LLUICtrl*)mBaseColorTexCtrl)
  1788. {
  1789. return MAT_BASE_COLOR_TEX_DIRTY;
  1790. }
  1791. if (ctrlp == (LLUICtrl*)mNormalTexCtrl)
  1792. {
  1793. return MAT_NORMAL_TEX_DIRTY;
  1794. }
  1795. if (ctrlp == (LLUICtrl*)mMetallicTexCtrl)
  1796. {
  1797. return MAT_ROUGHTNESS_TEX_DIRTY;
  1798. }
  1799. if (ctrlp == (LLUICtrl*)mEmissiveTexCtrl)
  1800. {
  1801. return MAT_EMISIVE_TEX_DIRTY;
  1802. }
  1803. if (ctrlp == (LLUICtrl*)mEmissiveColorCtrl)
  1804. {
  1805. return MAT_EMISIVE_COLOR_DIRTY;
  1806. }
  1807. if (ctrlp == (LLUICtrl*)mAlphaModeCombo)
  1808. {
  1809. return MAT_ALPHA_MODE_DIRTY;
  1810. }
  1811. if (ctrlp == (LLUICtrl*)mDoubleSidedCheck)
  1812. {
  1813. return MAT_DOUBLE_SIDED_DIRTY;
  1814. }
  1815. return 0;
  1816. }
  1817. static void check_for_local_texture(LLUICtrl* ctrlp, LLGLTFMaterial* matp)
  1818. {
  1819. LLTextureCtrl* texctrlp = (LLTextureCtrl*)ctrlp;
  1820. if (texctrlp->isImageLocal())
  1821. {
  1822. // Subscribe material to updates of local textures
  1823. LLLocalBitmap::associateGLTFMaterial(texctrlp->getLocalTrackingID(),
  1824. matp);
  1825. }
  1826. }
  1827. struct LLSelectedMaterialChangeFunctor final : public LLSelectedNodeFunctor
  1828. {
  1829. LLSelectedMaterialChangeFunctor(LLUICtrl* ctrlp, U32 dirty_flag)
  1830. : mCtrl(ctrlp),
  1831. mDirtyFlag(dirty_flag)
  1832. {
  1833. if (!dirty_flag)
  1834. {
  1835. return;
  1836. }
  1837. if (dirty_flag <= MAT_EMISIVE_TEX_DIRTY)
  1838. {
  1839. mTextureId = ctrlp->getValue().asUUID();
  1840. }
  1841. else if (dirty_flag <= MAT_EMISIVE_COLOR_DIRTY)
  1842. {
  1843. mColor = LLColor4(ctrlp->getValue());
  1844. }
  1845. else if (dirty_flag == MAT_ALPHA_MODE_DIRTY)
  1846. {
  1847. mValue = F32(ctrlp->getValue().asInteger());
  1848. }
  1849. else if (dirty_flag == MAT_DOUBLE_SIDED_DIRTY)
  1850. {
  1851. mValue = ctrlp->getValue().asBoolean() ? 1.f : 0.f;
  1852. }
  1853. else
  1854. {
  1855. mValue = ctrlp->getValue().asReal();
  1856. }
  1857. }
  1858. bool apply(LLSelectNode* nodep) override
  1859. {
  1860. LLViewerObject* objectp = nodep->getObject();
  1861. if (!objectp)
  1862. {
  1863. return false;
  1864. }
  1865. // Avatars have TEs but no faces.
  1866. U8 num_tes = llmin(objectp->getNumTEs(), objectp->getNumFaces());
  1867. for (U8 te = 0; te < num_tes; ++te)
  1868. {
  1869. if (!nodep->isTESelected(te) ||
  1870. te >= nodep->mSavedGLTFOverrideMaterials.size())
  1871. {
  1872. continue;
  1873. }
  1874. LLPointer<LLGLTFMaterial>& matp =
  1875. nodep->mSavedGLTFOverrideMaterials[te];
  1876. if (matp.isNull())
  1877. {
  1878. // Populate with default values, default values basically mean
  1879. // 'not in use'.
  1880. matp = new LLGLTFMaterial();
  1881. }
  1882. switch (mDirtyFlag)
  1883. {
  1884. case MAT_BASE_COLOR_TEX_DIRTY:
  1885. matp->setBaseColorId(mTextureId, true);
  1886. check_for_local_texture(mCtrl, matp);
  1887. break;
  1888. case MAT_NORMAL_TEX_DIRTY:
  1889. matp->setNormalId(mTextureId, true);
  1890. check_for_local_texture(mCtrl, matp);
  1891. break;
  1892. case MAT_ROUGHTNESS_TEX_DIRTY:
  1893. matp->setMetallicRoughnessId(mTextureId, true);
  1894. check_for_local_texture(mCtrl, matp);
  1895. break;
  1896. case MAT_EMISIVE_TEX_DIRTY:
  1897. matp->setEmissiveId(mTextureId, true);
  1898. check_for_local_texture(mCtrl, matp);
  1899. break;
  1900. case MAT_BASE_COLOR_DIRTY:
  1901. {
  1902. LLColor4 color = linearColor4(mColor);
  1903. // Do not touch the transparency value
  1904. color.mV[3] = matp->mBaseColor.mV[3];
  1905. matp->setBaseColorFactor(color, true);
  1906. break;
  1907. }
  1908. case MAT_EMISIVE_COLOR_DIRTY:
  1909. matp->setEmissiveColorFactor(LLColor3(mColor), true);
  1910. break;
  1911. case MAT_TRANSPARENCY_DIRTY:
  1912. {
  1913. LLColor4 color = matp->mBaseColor;
  1914. // Only touch the transparency value
  1915. color.mV[3] = mValue;
  1916. matp->setBaseColorFactor(color, true);
  1917. break;
  1918. }
  1919. case MAT_ALPHA_MODE_DIRTY:
  1920. matp->setAlphaMode(U32(mValue), true);
  1921. break;
  1922. case MAT_ALPHA_CUTOFF_DIRTY:
  1923. matp->setAlphaCutoff(mValue, true);
  1924. break;
  1925. case MAT_METALNESS_DIRTY:
  1926. matp->setMetallicFactor(mValue, true);
  1927. break;
  1928. case MAT_ROUGHTNESS_DIRTY:
  1929. matp->setRoughnessFactor(mValue, true);
  1930. break;
  1931. case MAT_DOUBLE_SIDED_DIRTY:
  1932. matp->setDoubleSided(mValue != 0.f, true);
  1933. default:
  1934. break;
  1935. }
  1936. }
  1937. return true;
  1938. }
  1939. LLUICtrl* mCtrl;
  1940. LLUUID mTextureId;
  1941. LLColor4 mColor;
  1942. U32 mDirtyFlag;
  1943. F32 mValue;
  1944. };
  1945. //static
  1946. void LLPreviewMaterial::onSelectCtrl(LLUICtrl* ctrlp, void* userdata)
  1947. {
  1948. LLPreviewMaterial* self = (LLPreviewMaterial*)userdata;
  1949. if (!self || !ctrlp)
  1950. {
  1951. return;
  1952. }
  1953. U32 dirty_flag = self->getDirtyFlagFromCtrl(ctrlp);
  1954. self->mUnsavedChanges |= dirty_flag;
  1955. self->applyToSelection();
  1956. // If needed, propagate any change in textures or colors
  1957. if (self->mIsOverride)
  1958. {
  1959. LLSelectedMaterialChangeFunctor func(ctrlp, dirty_flag);
  1960. gSelectMgr.getSelection()->applyToNodes(&func);
  1961. if (gFloaterToolsp)
  1962. {
  1963. gFloaterToolsp->dirty();
  1964. }
  1965. }
  1966. }
  1967. //static
  1968. void LLPreviewMaterial::onTextureCtrl(LLUICtrl* ctrlp, void* userdata)
  1969. {
  1970. LLPreviewMaterial* self = (LLPreviewMaterial*)userdata;
  1971. if (self && ctrlp)
  1972. {
  1973. U32 dirty_flag = self->getDirtyFlagFromCtrl(ctrlp);
  1974. // Note: as long as onTextureCtrl() is only used with an LLTextureCtrl,
  1975. // the static cast is valid. HB
  1976. LLTextureCtrl* tctrlp = (LLTextureCtrl*)ctrlp;
  1977. if (tctrlp->isImageLocal())
  1978. {
  1979. self->subscribeToLocalTexture(dirty_flag,
  1980. tctrlp->getLocalTrackingID());
  1981. }
  1982. else
  1983. {
  1984. // Unsubcribe potential old callback
  1985. connection_map_t::iterator it =
  1986. self->mTextureChangesUpdates.find(dirty_flag);
  1987. if (it != self->mTextureChangesUpdates.end())
  1988. {
  1989. it->second.mConnection.disconnect();
  1990. }
  1991. }
  1992. self->markChangesUnsaved(dirty_flag);
  1993. self->applyToSelection();
  1994. }
  1995. }
  1996. //static
  1997. void LLPreviewMaterial::onCancelCtrl(LLUICtrl* ctrlp, void* userdata)
  1998. {
  1999. LLPreviewMaterial* self = (LLPreviewMaterial*)userdata;
  2000. if (self && ctrlp)
  2001. {
  2002. self->mRevertedChanges |= self->getDirtyFlagFromCtrl(ctrlp);
  2003. self->applyToSelection();
  2004. }
  2005. }
  2006. bool LLPreviewMaterial::onCancelMsgCallback(const LLSD& notification,
  2007. const LLSD& response)
  2008. {
  2009. if (LLNotification::getSelectedOption(notification, response) == 0)
  2010. {
  2011. close();
  2012. }
  2013. return false;
  2014. }
  2015. //static
  2016. void LLPreviewMaterial::onClickCancel(void* userdata)
  2017. {
  2018. LLPreviewMaterial* self = (LLPreviewMaterial*)userdata;
  2019. if (!self)
  2020. {
  2021. return;
  2022. }
  2023. if (self->mIsOverride || !self->mUnsavedChanges)
  2024. {
  2025. if (self->mIsOverride && gFloaterToolsp)
  2026. {
  2027. gFloaterToolsp->dirty();
  2028. }
  2029. self->close();
  2030. return;
  2031. }
  2032. gNotifications.add("UnsavedMaterialChanges", LLSD(), LLSD(),
  2033. boost::bind(&LLPreviewMaterial::onCancelMsgCallback,
  2034. self, _1, _2));
  2035. }
  2036. //static
  2037. void LLPreviewMaterial::onClickSave(void* userdata)
  2038. {
  2039. LLPreviewMaterial* self = (LLPreviewMaterial*)userdata;
  2040. if (!self)
  2041. {
  2042. return;
  2043. }
  2044. if (!gAgent.hasInventoryMaterial())
  2045. {
  2046. gNotifications.add("MissingMaterialCaps");
  2047. return;
  2048. }
  2049. if (!can_afford_transaction(self->mExpectedUploadCost))
  2050. {
  2051. LLSD args;
  2052. args["COST"] = llformat("%d", self->mExpectedUploadCost);
  2053. gNotifications.add("ErrorCannotAffordUpload", args);
  2054. return;
  2055. }
  2056. self->applyToSelection();
  2057. self->saveIfNeeded();
  2058. }
  2059. //static
  2060. void LLPreviewMaterial::onClickSaveAs(void* userdata)
  2061. {
  2062. LLPreviewMaterial* self = (LLPreviewMaterial*)userdata;
  2063. if (!self)
  2064. {
  2065. return;
  2066. }
  2067. if (!gAgent.hasInventoryMaterial())
  2068. {
  2069. gNotifications.add("MissingMaterialCaps");
  2070. return;
  2071. }
  2072. if (!can_afford_transaction(self->mExpectedUploadCost))
  2073. {
  2074. LLSD args;
  2075. args["COST"] = llformat("%d", self->mExpectedUploadCost);
  2076. gNotifications.add("ErrorCannotAffordUpload", args);
  2077. return;
  2078. }
  2079. LLSD args;
  2080. args["DESC"] = self->mMaterialName;
  2081. gNotifications.add("SaveMaterialAs", args, LLSD(),
  2082. boost::bind(&LLPreviewMaterial::onSaveAsMsgCallback,
  2083. self, _1, _2));
  2084. }
  2085. class LLMaterialCopiedCB final : public LLInventoryCallback
  2086. {
  2087. protected:
  2088. LOG_CLASS(LLMaterialCopiedCB);
  2089. public:
  2090. LLMaterialCopiedCB(LLPreviewMaterial* previewp,
  2091. const std::string& buffer)
  2092. : mPreviewp(previewp),
  2093. mBuffer(buffer)
  2094. {
  2095. }
  2096. void fire(const LLUUID& inv_item_id) override
  2097. {
  2098. if (mPreviewp && sEditorInstances.count(mPreviewp)) // Still around ?
  2099. {
  2100. mPreviewp->finishSaveAs(inv_item_id, mBuffer);
  2101. }
  2102. }
  2103. private:
  2104. LLPreviewMaterial* mPreviewp;
  2105. std::string mBuffer;
  2106. };
  2107. void LLPreviewMaterial::finishSaveAs(const LLUUID& new_item_id,
  2108. const std::string& buffer)
  2109. {
  2110. LLViewerInventoryItem* itemp = gInventory.getItem(new_item_id);
  2111. if (!itemp)
  2112. {
  2113. llwarns << "Cannot find the inventory item " << new_item_id << llendl;
  2114. setEnabled(true);
  2115. return;
  2116. }
  2117. setItemID(new_item_id);
  2118. mObjectUUID.setNull();
  2119. mAuxItem = NULL;
  2120. setMaterialName(itemp->getName());
  2121. if (!mUnsavedChanges)
  2122. {
  2123. loadAsset();
  2124. setEnabled(true);
  2125. if (mTextureChangesUpdates.empty())
  2126. {
  2127. return;
  2128. }
  2129. LLGLTFMaterial* matp =
  2130. gGLTFMaterialList.getMaterial(itemp->getAssetUUID());
  2131. if (!matp)
  2132. {
  2133. return;
  2134. }
  2135. // Local textures were assigned, force load material and init tracking
  2136. for (connection_map_t::iterator it = mTextureChangesUpdates.begin(),
  2137. end = mTextureChangesUpdates.end();
  2138. it != end; ++it)
  2139. {
  2140. LLLocalBitmap::associateGLTFMaterial(it->second.mTrackingId, matp);
  2141. }
  2142. }
  2143. else if (!updateInventoryItem(buffer, new_item_id, LLUUID::null))
  2144. {
  2145. setEnabled(true);
  2146. }
  2147. }
  2148. bool LLPreviewMaterial::onSaveAsMsgCallback(const LLSD& notification,
  2149. const LLSD& response)
  2150. {
  2151. if (LLNotification::getSelectedOption(notification, response) == 0) // Yes
  2152. {
  2153. std::string new_name = response["message"].asString();
  2154. LLInventoryObject::correctInventoryName(new_name);
  2155. if (new_name.empty())
  2156. {
  2157. gNotifications.add("InvalidMaterialName");
  2158. return false;
  2159. }
  2160. const LLInventoryItem* itemp = getItem();
  2161. if (!itemp)
  2162. {
  2163. setMaterialName(new_name);
  2164. onClickSave(this);
  2165. return false;
  2166. }
  2167. LLPointer<LLInventoryCallback> cb =
  2168. new LLMaterialCopiedCB(this, getEncodedAsset());
  2169. copy_inventory_item(itemp->getPermissions().getOwner(),
  2170. itemp->getUUID(), itemp->getParentUUID(), new_name,
  2171. cb);
  2172. mAssetStatus = PREVIEW_ASSET_LOADING;
  2173. setEnabled(false);
  2174. }
  2175. return false;
  2176. }
  2177. static bool can_use_objects_material(LLSelectedTEGetMatData& func,
  2178. const std::vector<U32>& ops,
  2179. LLPermissions& permissions)
  2180. {
  2181. if (!gAgent.hasInventoryMaterial())
  2182. {
  2183. return false;
  2184. }
  2185. gSelectMgr.getSelection()->applyToTEs(&func, true);
  2186. LLViewerObject* objectp = func.mObject;
  2187. if (!objectp || objectp->isInventoryPending())
  2188. {
  2189. return false;
  2190. }
  2191. if (objectp->isPermanentEnforced())
  2192. {
  2193. for (U32 i = 0, count = ops.size(); i < count; ++i)
  2194. {
  2195. if (ops[i] == PERM_MODIFY)
  2196. {
  2197. return false;
  2198. }
  2199. }
  2200. }
  2201. LLPermissions item_perms;
  2202. LLViewerInventoryItem* itemp =
  2203. objectp->getInventoryItemByAsset(func.mMaterialId);
  2204. if (itemp)
  2205. {
  2206. item_perms.set(itemp->getPermissions());
  2207. for (U32 i = 0, count = ops.size(); i < count; ++i)
  2208. {
  2209. if (!gAgent.allowOperation(ops[i], item_perms,
  2210. GP_OBJECT_MANIPULATE))
  2211. {
  2212. return false;
  2213. }
  2214. }
  2215. // Update flags for new owner
  2216. if (!item_perms.setOwnerAndGroup(LLUUID::null, gAgentID,
  2217. LLUUID::null, true))
  2218. {
  2219. return false;
  2220. }
  2221. }
  2222. else
  2223. {
  2224. item_perms.init(gAgentID, gAgentID, LLUUID::null, LLUUID::null);
  2225. }
  2226. // Use the root object for permissions checking
  2227. LLViewerObject* rootp = objectp->getRootEdit();
  2228. LLPermissions obj_perms;
  2229. LLPermissions* permsp = gSelectMgr.findObjectPermissions(rootp);
  2230. if (permsp)
  2231. {
  2232. obj_perms.set(*permsp);
  2233. for (U32 i = 0, count = ops.size(); i < count; ++i)
  2234. {
  2235. if (!gAgent.allowOperation(ops[i], obj_perms,
  2236. GP_OBJECT_MANIPULATE))
  2237. {
  2238. return false;
  2239. }
  2240. }
  2241. // Update flags for new owner
  2242. if (!obj_perms.setOwnerAndGroup(LLUUID::null, gAgentID,
  2243. LLUUID::null, true))
  2244. {
  2245. return false;
  2246. }
  2247. }
  2248. else
  2249. {
  2250. obj_perms.init(gAgentID, gAgentID, LLUUID::null, LLUUID::null);
  2251. }
  2252. LLPermissions default_perms;
  2253. default_perms.setMaskEveryone(LLFloaterPerms::getEveryonePerms());
  2254. default_perms.setMaskGroup(LLFloaterPerms::getGroupPerms());
  2255. default_perms.setMaskNext(LLFloaterPerms::getNextOwnerPerms());
  2256. // Note: a close inspection of LLPermissions::accumulate shows that
  2257. // conflicting UUIDs will be unset. This is acceptable behavior for now.
  2258. // The server will populate creator info based on the item creation method
  2259. // used. There is currently no good way to preserve creation history when
  2260. // there is no material item present. In that case, the agent who saved the
  2261. // material will be considered the creator.
  2262. if (itemp)
  2263. {
  2264. func.mInvItemId = itemp->getUUID();
  2265. permissions.set(item_perms);
  2266. }
  2267. else
  2268. {
  2269. permissions.set(obj_perms);
  2270. }
  2271. permissions.accumulate(default_perms);
  2272. return true;
  2273. }
  2274. //static
  2275. bool LLPreviewMaterial::canModifyObjectsMaterial()
  2276. {
  2277. static const std::vector<U32> perm_mod({ PERM_MODIFY });
  2278. LLSelectedTEGetMatData func(true);
  2279. LLPermissions permissions;
  2280. return can_use_objects_material(func, perm_mod, permissions);
  2281. }
  2282. //static
  2283. bool LLPreviewMaterial::canSaveObjectsMaterial()
  2284. {
  2285. static const std::vector<U32> perm_copy_mod({ PERM_COPY, PERM_MODIFY });
  2286. LLSelectedTEGetMatData func(true);
  2287. LLPermissions permissions;
  2288. return can_use_objects_material(func, perm_copy_mod, permissions);
  2289. }
  2290. //static
  2291. void LLPreviewMaterial::saveObjectsMaterial()
  2292. {
  2293. static const std::vector<U32> perm_copy_mod({ PERM_COPY, PERM_MODIFY });
  2294. LLSelectedTEGetMatData func(true);
  2295. LLPermissions permissions;
  2296. if (!can_use_objects_material(func, perm_copy_mod, permissions))
  2297. {
  2298. return;
  2299. }
  2300. const LLPointer<LLLocalGLTFMaterial>& localmatp = func.mLocalMaterial;
  2301. const LLPointer<LLGLTFMaterial>& matp = func.mMaterial;
  2302. if (localmatp.notNull() && matp.notNull())
  2303. {
  2304. // This is a local material, reload it from file so that the user would
  2305. // not end up with grey textures on next login.
  2306. LLPreviewMaterial* self = loadFromFile(localmatp->getFilename(),
  2307. localmatp->getIndexInFile());
  2308. if (!self)
  2309. {
  2310. return; // Failed !
  2311. }
  2312. // Do not use override material here, it has 'hacked ids' and values;
  2313. // use end result, apply it on top of local.
  2314. const LLColor4& base_color = matp->mBaseColor;
  2315. self->setBaseColor(LLColor3(base_color));
  2316. self->setTransparency(base_color[VW]);
  2317. self->setAlphaMode(matp->getAlphaMode());
  2318. self->setAlphaCutoff(matp->mAlphaCutoff);
  2319. self->setMetalnessFactor(matp->mMetallicFactor);
  2320. self->setRoughnessFactor(matp->mRoughnessFactor);
  2321. self->setDoubleSided(matp->mDoubleSided);
  2322. // Most things like colors we can apply without verifying, but textures
  2323. // Ids are going to be different from both, base and override, so only
  2324. // apply override Id if there is actually a difference.
  2325. if (localmatp->mTextureId[BASECOLIDX] != matp->mTextureId[BASECOLIDX])
  2326. {
  2327. self->setBaseColorId(matp->mTextureId[BASECOLIDX]);
  2328. }
  2329. if (localmatp->mTextureId[NORMALIDX] != matp->mTextureId[NORMALIDX])
  2330. {
  2331. self->setNormalId(matp->mTextureId[NORMALIDX]);
  2332. }
  2333. if (localmatp->mTextureId[MROUGHIDX] != matp->mTextureId[MROUGHIDX])
  2334. {
  2335. self->setMetallicRoughnessId(matp->mTextureId[MROUGHIDX]);
  2336. }
  2337. if (localmatp->mTextureId[EMISSIVEIDX] !=
  2338. matp->mTextureId[EMISSIVEIDX])
  2339. {
  2340. self->setEmissiveId(matp->mTextureId[EMISSIVEIDX]);
  2341. }
  2342. // Recalculate upload cost.
  2343. self->markChangesUnsaved(0);
  2344. }
  2345. LLSD payload;
  2346. if (matp.notNull())
  2347. {
  2348. // Make a copy of the render material with unsupported transforms
  2349. // removed
  2350. LLGLTFMaterial asset_mat = *matp;
  2351. asset_mat.sanitizeAssetMaterial();
  2352. payload["data"] = asset_mat.asJSON();
  2353. }
  2354. else
  2355. {
  2356. // This should not happen, but just in case, use a blank material.
  2357. LLGLTFMaterial blank_mat;
  2358. payload["data"] = blank_mat.asJSON();
  2359. llwarns << "Got no material when trying to save selected faces material"
  2360. << llendl;
  2361. }
  2362. LLSD args;
  2363. args["DESC"] = LLTrans::getString("New Material");
  2364. if (localmatp.isNull() && func.mInvItemId.notNull())
  2365. {
  2366. payload["object_id"] = func.mObjectId;
  2367. payload["item_id"] = func.mInvItemId;
  2368. permissions.init(gAgentID, gAgentID, LLUUID::null, LLUUID::null);
  2369. }
  2370. gNotifications.add("SaveMaterialAs", args, payload,
  2371. boost::bind(&LLPreviewMaterial::onSaveObjectsMaterialCB,
  2372. _1, _2, permissions));
  2373. }
  2374. class LLMaterialInventoryCB final : public LLInventoryCallback
  2375. {
  2376. protected:
  2377. LOG_CLASS(LLMaterialInventoryCB);
  2378. public:
  2379. LLMaterialInventoryCB(const LLPermissions& permissions,
  2380. const std::string& buffer,
  2381. const std::string& item_name)
  2382. : mPermissions(permissions),
  2383. mBuffer(buffer),
  2384. mItemName(item_name)
  2385. {
  2386. }
  2387. void fire(const LLUUID& inv_item_id) override
  2388. {
  2389. LLViewerInventoryItem* itemp = gInventory.getItem(inv_item_id);
  2390. if (!itemp) return;
  2391. // create_inventory_item() does not allow presetting some permissions;
  2392. // fix it now.
  2393. itemp->setPermissions(mPermissions);
  2394. itemp->updateServer(false);
  2395. gInventory.updateItem(itemp);
  2396. gInventory.notifyObservers();
  2397. if (itemp->getName() != mItemName)
  2398. {
  2399. LLSD updates;
  2400. updates["name"] = mItemName;
  2401. update_inventory_item(inv_item_id, updates, NULL);
  2402. }
  2403. LLResourceUploadInfo::ptr_t infop =
  2404. std::make_shared<LLBufferedAssetUploadInfo>(
  2405. inv_item_id, LLAssetType::AT_MATERIAL, mBuffer, uploadDone);
  2406. const std::string& cap_url =
  2407. gAgent.getRegionCapability("UpdateMaterialAgentInventory");
  2408. LLViewerAssetUpload::enqueueInventoryUpload(cap_url, infop);
  2409. }
  2410. static void uploadDone(LLUUID, LLUUID, LLUUID, LLSD)
  2411. {
  2412. gNotifications.add("MaterialCreated");
  2413. }
  2414. private:
  2415. std::string mBuffer;
  2416. std::string mItemName;
  2417. LLPermissions mPermissions;
  2418. };
  2419. //static
  2420. bool LLPreviewMaterial::onSaveObjectsMaterialCB(const LLSD& notification,
  2421. const LLSD& response,
  2422. const LLPermissions& perms)
  2423. {
  2424. if (LLNotification::getSelectedOption(notification, response) == 0)
  2425. {
  2426. LLSD asset;
  2427. asset["version"] = LLGLTFMaterial::ASSET_VERSION;
  2428. asset["type"] = LLGLTFMaterial::ASSET_TYPE;
  2429. // This is the string serialized from LLGLTFMaterial::asJSON
  2430. asset["data"] = notification["payload"]["data"];
  2431. std::stringstream buffer;
  2432. LLSDSerialize::serialize(asset, buffer, LLSDSerialize::LLSD_BINARY);
  2433. std::string new_name = response["message"].asString();
  2434. if (notification["payload"].has("item_id"))
  2435. {
  2436. LLUUID object_id = notification["payload"]["object_id"];
  2437. LLViewerObject* objectp = gObjectList.findObject(object_id);
  2438. if (!objectp) return false;
  2439. LLUUID item_id = notification["payload"]["item_id"];
  2440. const LLInventoryItem* itemp = objectp->getInventoryItem(item_id);
  2441. if (!itemp) return false;
  2442. const LLUUID& mat_cat_id =
  2443. gInventory.findCategoryUUIDForType(LLFolderType::FT_MATERIAL);
  2444. LLPointer<LLInventoryCallback> cb =
  2445. new LLMaterialInventoryCB(perms, buffer.str(), new_name);
  2446. move_or_copy_item_from_object(mat_cat_id, object_id, item_id, cb);
  2447. }
  2448. else
  2449. {
  2450. createInventoryItem(buffer.str(), new_name, LLStringUtil::null,
  2451. perms);
  2452. }
  2453. }
  2454. return false;
  2455. }
  2456. std::string LLPreviewMaterial::getEncodedAsset()
  2457. {
  2458. LLSD asset;
  2459. asset["version"] = LLGLTFMaterial::ASSET_VERSION;
  2460. asset["type"] = LLGLTFMaterial::ASSET_TYPE;
  2461. LLGLTFMaterial mat;
  2462. getGLTFMaterial(&mat);
  2463. asset["data"] = mat.asJSON();
  2464. std::stringstream buffer;
  2465. LLSDSerialize::serialize(asset, buffer, LLSDSerialize::LLSD_BINARY);
  2466. return buffer.str();
  2467. }
  2468. bool LLPreviewMaterial::decodeAsset(const std::string& buffer)
  2469. {
  2470. std::stringstream llsdstream(buffer);
  2471. LLSD asset;
  2472. if (!LLSDSerialize::deserialize(asset, llsdstream, buffer.size()))
  2473. {
  2474. llwarns << "Failed to deserialize material data." << llendl;
  2475. return false;
  2476. }
  2477. if (!asset.has("version") ||
  2478. !LLGLTFMaterial::isAcceptedVersion(asset["version"].asString()))
  2479. {
  2480. llwarns << "Invalid or missing material data version." << llendl;
  2481. return false;
  2482. }
  2483. static const std::string asset_type(LLGLTFMaterial::ASSET_TYPE);
  2484. if (!asset.has("type") || asset["type"].asString() != asset_type)
  2485. {
  2486. llwarns << "Not a " << asset_type << " asset." << llendl;
  2487. return false;
  2488. }
  2489. if (!asset.has("data") || !asset["data"].isString())
  2490. {
  2491. llwarns << "Material asset has no data." << llendl;
  2492. return false;
  2493. }
  2494. std::string data = asset["data"];
  2495. std::string error_msg, warn_msg;
  2496. tinygltf::TinyGLTF gltf;
  2497. tinygltf::TinyGLTF loader;
  2498. tinygltf::Model model_in;
  2499. if (!loader.LoadASCIIFromString(&model_in, &error_msg, &warn_msg,
  2500. data.c_str(), data.size(), ""))
  2501. {
  2502. llwarns << "Failed to decode GLTF material data: "
  2503. << (error_msg.empty() ? warn_msg : error_msg) << llendl;
  2504. return false;
  2505. }
  2506. // Assets are only supposed to have one item. This duplicates some
  2507. // functionality from LLGLTFMaterial::fromJSON, but currently does the job
  2508. // better for the material preview use case. However LLGLTFMaterial::asJSON
  2509. // should always be used when uploading materials, to ensure the asset is
  2510. // valid.
  2511. return setFromGltfModel(model_in, 0, true);
  2512. }
  2513. std::string LLPreviewMaterial::buildMaterialDescription()
  2514. {
  2515. static const char* separator = ", ";
  2516. bool needs_separator = false;
  2517. std::string desc = getString("mat_desc");
  2518. if (mBaseColorTexCtrl->getValue().asUUID().notNull() &&
  2519. !mBaseColorName.empty())
  2520. {
  2521. desc += mBaseColorName;
  2522. needs_separator = true;
  2523. }
  2524. if (mMetallicTexCtrl->getValue().asUUID().notNull() &&
  2525. !mMetallicRoughnessName.empty())
  2526. {
  2527. if (needs_separator)
  2528. {
  2529. desc.append(separator);
  2530. }
  2531. desc += mMetallicRoughnessName;
  2532. needs_separator = true;
  2533. }
  2534. if (mEmissiveTexCtrl->getValue().asUUID().notNull() &&
  2535. !mEmissiveName.empty())
  2536. {
  2537. if (needs_separator)
  2538. {
  2539. desc.append(separator);
  2540. }
  2541. desc += mEmissiveName;
  2542. needs_separator = true;
  2543. }
  2544. if (mNormalTexCtrl->getValue().asUUID().notNull() && !mNormalName.empty())
  2545. {
  2546. if (needs_separator)
  2547. {
  2548. desc.append(separator);
  2549. }
  2550. desc += mNormalName;
  2551. }
  2552. LLInventoryObject::correctInventoryName(desc);
  2553. return desc;
  2554. }
  2555. void LLPreviewMaterial::saveIfNeeded()
  2556. {
  2557. if (mUploadingTexturesCount > 0)
  2558. {
  2559. // An upload is already in progress; wait until textures upload will
  2560. // retry saving on callback. Also should prevent some failure
  2561. // callbacks.
  2562. return;
  2563. }
  2564. if (saveTextures())
  2565. {
  2566. // Started texture upload
  2567. setEnabled(false);
  2568. return;
  2569. }
  2570. std::string buffer = getEncodedAsset();
  2571. const LLInventoryItem* itemp = getItem();
  2572. if (!itemp)
  2573. {
  2574. // Create an new inventory item
  2575. LLPermissions perms;
  2576. perms.init(gAgentID, gAgentID, LLUUID::null, LLUUID::null);
  2577. createInventoryItem(buffer, mMaterialName, buildMaterialDescription(),
  2578. perms);
  2579. // We do not update floater with uploaded asset yet, so just close it.
  2580. close();
  2581. return;
  2582. }
  2583. if (!updateInventoryItem(buffer, mItemUUID, mObjectUUID))
  2584. {
  2585. return;
  2586. }
  2587. if (mCloseAfterSave)
  2588. {
  2589. close();
  2590. return;
  2591. }
  2592. mAssetStatus = PREVIEW_ASSET_LOADING;
  2593. setEnabled(false);
  2594. }
  2595. //static
  2596. void LLPreviewMaterial::uploadFailure(void* userdata)
  2597. {
  2598. LLPreviewMaterial* self = (LLPreviewMaterial*)userdata;
  2599. if (self && sEditorInstances.count(self)) // Floater still there ?
  2600. {
  2601. // Stop upload if possible, unblock and let user decide
  2602. self->setFailedToUploadTexture();
  2603. }
  2604. }
  2605. //static
  2606. void LLPreviewMaterial::finishInventoryUpload(const LLUUID& item_id,
  2607. const LLUUID& new_asset_id,
  2608. const LLUUID& new_item_id,
  2609. void* userdata)
  2610. {
  2611. LLPreviewMaterial* self = (LLPreviewMaterial*)userdata;
  2612. if (!self || !sEditorInstances.count(self))
  2613. {
  2614. return; // Floater already gone.
  2615. }
  2616. if (new_asset_id.notNull())
  2617. {
  2618. self->setAssetId(new_asset_id);
  2619. }
  2620. self->refreshFromInventory(new_item_id.notNull() ? new_item_id : item_id);
  2621. if (self->mTextureChangesUpdates.empty())
  2622. {
  2623. return;
  2624. }
  2625. const LLViewerInventoryItem* itemp = self->getItem();
  2626. if (!itemp)
  2627. {
  2628. return;
  2629. }
  2630. LLGLTFMaterial* matp =
  2631. gGLTFMaterialList.getMaterial(itemp->getAssetUUID());
  2632. if (!matp)
  2633. {
  2634. return;
  2635. }
  2636. // Local textures were assigned, force load material and init tracking
  2637. for (connection_map_t::iterator it = self->mTextureChangesUpdates.begin(),
  2638. end = self->mTextureChangesUpdates.end();
  2639. it != end; ++it)
  2640. {
  2641. LLLocalBitmap::associateGLTFMaterial(it->second.mTrackingId, matp);
  2642. }
  2643. }
  2644. //static
  2645. void LLPreviewMaterial::finishTaskUpload(const LLUUID& item_id,
  2646. const LLUUID& new_asset_id,
  2647. const LLUUID& task_id, void* userdata)
  2648. {
  2649. LLPreviewMaterial* self = (LLPreviewMaterial*)userdata;
  2650. if (self && sEditorInstances.count(self)) // Floater still there ?
  2651. {
  2652. #if 1 // Refreshing from an object inventory does not properly work because
  2653. // it takes an indeterminate amount of time for the object inventory to
  2654. // get refreshed, so just close the floater... HB
  2655. self->close();
  2656. #else
  2657. self->setAssetId(new_asset_id);
  2658. self->refreshFromInventory();
  2659. self->setEnabled(true);
  2660. if (self->mTextureChangesUpdates.empty())
  2661. {
  2662. return;
  2663. }
  2664. // Local textures were assigned, force load material and init tracking
  2665. LLGLTFMaterial* matp = gGLTFMaterialList.getMaterial(new_asset_id);
  2666. if (!matp)
  2667. {
  2668. return;
  2669. }
  2670. for (connection_map_t::iterator it = mTextureChangesUpdates.begin(),
  2671. end = mTextureChangesUpdates.end();
  2672. it != end; ++it)
  2673. {
  2674. LLLocalBitmap::associateGLTFMaterial(it->second.mTrackingId, matp);
  2675. }
  2676. #endif
  2677. }
  2678. }
  2679. bool LLPreviewMaterial::updateInventoryItem(const std::string& buffer,
  2680. const LLUUID& item_id,
  2681. const LLUUID& task_id)
  2682. {
  2683. if (!gAgent.hasInventoryMaterial())
  2684. {
  2685. llwarns << "Not connected to a GLTF material capable region, cannot save material."
  2686. << llendl;
  2687. return false;
  2688. }
  2689. const std::string* urlp = NULL;
  2690. LLResourceUploadInfo::ptr_t infop;
  2691. if (task_id.notNull())
  2692. {
  2693. const std::string& task_url =
  2694. gAgent.getRegionCapability("UpdateMaterialTaskInventory");
  2695. if (!task_url.empty())
  2696. {
  2697. // Saving into task inventory
  2698. urlp = &task_url;
  2699. infop = std::make_shared<LLBufferedAssetUploadInfo>(
  2700. task_id, item_id, LLAssetType::AT_MATERIAL, buffer,
  2701. boost::bind(finishTaskUpload, _1, _2, _3, (void*)this),
  2702. boost::bind(uploadFailure, (void*)this));
  2703. }
  2704. }
  2705. else
  2706. {
  2707. const std::string& inv_url =
  2708. gAgent.getRegionCapability("UpdateMaterialAgentInventory");
  2709. if (!inv_url.empty())
  2710. {
  2711. // Saving into agent inventory
  2712. urlp = &inv_url;
  2713. infop = std::make_shared<LLBufferedAssetUploadInfo>(
  2714. item_id, LLAssetType::AT_MATERIAL, buffer,
  2715. boost::bind(finishInventoryUpload, _1, _2, _3,
  2716. (void*)this),
  2717. boost::bind(uploadFailure, (void*)this));
  2718. }
  2719. }
  2720. if (urlp && infop)
  2721. {
  2722. LLViewerAssetUpload::enqueueInventoryUpload(*urlp, infop);
  2723. return true;
  2724. }
  2725. return false;
  2726. }
  2727. //static
  2728. void LLPreviewMaterial::createInventoryItem(const std::string& buffer,
  2729. const std::string& name,
  2730. const std::string& desc,
  2731. const LLPermissions& permissions)
  2732. {
  2733. if (!gAgent.hasInventoryMaterial())
  2734. {
  2735. gNotifications.add("MissingMaterialCaps");
  2736. return;
  2737. }
  2738. LLTransactionID tid;
  2739. tid.generate();
  2740. LLUUID parent_id =
  2741. gInventory.findChoosenCategoryUUIDForType(LLFolderType::FT_MATERIAL);
  2742. LLPointer<LLInventoryCallback> cb = new LLMaterialInventoryCB(permissions,
  2743. buffer,
  2744. name);
  2745. create_inventory_item(parent_id, tid, name, desc, LLAssetType::AT_MATERIAL,
  2746. LLInventoryType::IT_MATERIAL, NO_INV_SUBTYPE,
  2747. permissions.getMaskNextOwner(), cb);
  2748. }
  2749. //static
  2750. void LLPreviewMaterial::uploadSuccess(const LLUUID& asset_id,
  2751. const LLSD& response,
  2752. U32 tex_type, void* userdata)
  2753. {
  2754. LLPreviewMaterial* self = (LLPreviewMaterial*)userdata;
  2755. if (!self || !sEditorInstances.count(self))
  2756. {
  2757. return; // Floater already gone !
  2758. }
  2759. if (!response["success"].asBoolean())
  2760. {
  2761. // Stop upload if possible, unblock and let user decide
  2762. self->setFailedToUploadTexture();
  2763. return;
  2764. }
  2765. switch (tex_type)
  2766. {
  2767. case MAT_BASE_COLOR_TEX_DIRTY:
  2768. self->setBaseColorId(asset_id);
  2769. self->mBaseColorJ2C = NULL;
  2770. self->mBaseColorFetched = NULL;
  2771. self->mBaseColorTextureUploadId.setNull();
  2772. break;
  2773. case MAT_NORMAL_TEX_DIRTY:
  2774. self->setNormalId(asset_id);
  2775. self->mNormalJ2C = NULL;
  2776. self->mNormalFetched = NULL;
  2777. self->mNormalTextureUploadId.setNull();
  2778. break;
  2779. case MAT_ROUGHTNESS_TEX_DIRTY:
  2780. self->setMetallicRoughnessId(asset_id);
  2781. self->mMetallicRoughnessJ2C = NULL;
  2782. self->mMetallicRoughnessFetched = NULL;
  2783. self->mMetallicTextureUploadId.setNull();
  2784. break;
  2785. case MAT_EMISIVE_TEX_DIRTY:
  2786. self->setEmissiveId(asset_id);
  2787. self->mEmissiveJ2C = NULL;
  2788. self->mEmissiveFetched = NULL;
  2789. self->mEmissiveTextureUploadId.setNull();
  2790. default:
  2791. break;
  2792. }
  2793. --self->mUploadingTexturesCount;
  2794. if (!self->mUploadingTexturesFailure)
  2795. {
  2796. // Try saving
  2797. self->saveIfNeeded();
  2798. }
  2799. else if (!self->mUploadingTexturesCount)
  2800. {
  2801. self->setEnabled(true);
  2802. }
  2803. }
  2804. bool LLPreviewMaterial::saveTexture(LLImageJ2C* imgp, U32 tex_type,
  2805. const std::string& name,
  2806. const LLUUID& asset_id)
  2807. {
  2808. if (asset_id.isNull() || !imgp || !imgp->getDataSize())
  2809. {
  2810. return false;
  2811. }
  2812. ++mUploadingTexturesCount;
  2813. // Copy image bytes into a string buffer
  2814. std::string buffer;
  2815. buffer.assign((const char*)imgp->getData(), imgp->getDataSize());
  2816. LLResourceUploadInfo::ptr_t info =
  2817. std::make_shared<LLNewBufferedResourceUploadInfo>(
  2818. buffer, asset_id, name, name, 0, LLFolderType::FT_TEXTURE,
  2819. LLInventoryType::IT_TEXTURE, LLAssetType::AT_TEXTURE,
  2820. LLFloaterPerms::getNextOwnerPerms(),
  2821. LLFloaterPerms::getGroupPerms(),
  2822. LLFloaterPerms::getEveryonePerms(),
  2823. LLEconomy::getInstance()->getTextureUploadCost(imgp->getWidth(),
  2824. imgp->getHeight()),
  2825. boost::bind(uploadSuccess, _1, _2, tex_type, (void*)this),
  2826. boost::bind(uploadFailure, (void*)this));
  2827. upload_new_resource(info);
  2828. return true;
  2829. }
  2830. void LLPreviewMaterial::setFailedToUploadTexture()
  2831. {
  2832. mUploadingTexturesFailure = true;
  2833. if (--mUploadingTexturesCount == 0)
  2834. {
  2835. setEnabled(true);
  2836. }
  2837. }
  2838. U32 LLPreviewMaterial::saveTextures()
  2839. {
  2840. mUploadingTexturesFailure = false;
  2841. U32 work_count = 0;
  2842. if (!mUploadingTexturesCount && // Only 1 texture uploaded at a time ! HB
  2843. mBaseColorTextureUploadId.notNull() &&
  2844. mBaseColorTextureUploadId == getBaseColorId())
  2845. {
  2846. if (saveTexture(mBaseColorJ2C, MAT_BASE_COLOR_TEX_DIRTY,
  2847. mBaseColorName, mBaseColorTextureUploadId))
  2848. {
  2849. ++work_count;
  2850. }
  2851. }
  2852. if (!mUploadingTexturesCount && // Only 1 texture uploaded at a time ! HB
  2853. mNormalTextureUploadId.notNull() &&
  2854. mNormalTextureUploadId == getNormalId())
  2855. {
  2856. if (saveTexture(mNormalJ2C, MAT_NORMAL_TEX_DIRTY, mNormalName,
  2857. mNormalTextureUploadId))
  2858. {
  2859. ++work_count;
  2860. }
  2861. }
  2862. if (!mUploadingTexturesCount && // Only 1 texture uploaded at a time ! HB
  2863. mMetallicTextureUploadId.notNull() &&
  2864. mMetallicTextureUploadId == getMetallicRoughnessId())
  2865. {
  2866. if (saveTexture(mMetallicRoughnessJ2C, MAT_ROUGHTNESS_TEX_DIRTY,
  2867. mMetallicRoughnessName, mMetallicTextureUploadId))
  2868. {
  2869. ++work_count;
  2870. }
  2871. }
  2872. if (!mUploadingTexturesCount && // Only 1 texture uploaded at a time ! HB
  2873. mEmissiveTextureUploadId.notNull() &&
  2874. mEmissiveTextureUploadId == getEmissiveId())
  2875. {
  2876. if (saveTexture(mEmissiveJ2C, MAT_EMISIVE_TEX_DIRTY,
  2877. mEmissiveName, mEmissiveTextureUploadId))
  2878. {
  2879. ++work_count;
  2880. }
  2881. }
  2882. if (!mUploadingTexturesCount && !work_count)
  2883. {
  2884. // Discard upload buffers once textures have been confirmed as saved.
  2885. // Otherwise we keep buffers for potential upload failure recovery.
  2886. clearTextures();
  2887. }
  2888. // Asset storage can callback immediately, causing a decrease of
  2889. // mUploadingTexturesCount, so report the amount of work scheduled, not the
  2890. // amount of work remaining.
  2891. return work_count;
  2892. }