llmeshrepository.cpp 141 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403
  1. /**
  2. * @file llmeshrepository.cpp
  3. * @brief Mesh repository implementation.
  4. *
  5. * $LicenseInfo:firstyear=2004&license=viewergpl$
  6. *
  7. * Copyright (c) 2010, Linden Research, Inc.
  8. *
  9. * Second Life Viewer Source Code
  10. * The source code in this file ("Source Code") is provided by Linden Lab
  11. * to you under the terms of the GNU General Public License, version 2.0
  12. * ("GPL"), unless you have obtained a separate licensing agreement
  13. * ("Other License"), formally executed by you and Linden Lab. Terms of
  14. * the GPL can be found in doc/GPL-license.txt in this distribution, or
  15. * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
  16. *
  17. * There are special exceptions to the terms and conditions of the GPL as
  18. * it is applied to this Source Code. View the full text of the exception
  19. * in the file doc/FLOSS-exception.txt in this software distribution, or
  20. * online at
  21. * http://secondlifegrid.net/programs/open_source/licensing/flossexception
  22. *
  23. * By copying, modifying or distributing this software, you acknowledge
  24. * that you have read and understood your obligations described above,
  25. * and agree to abide by those obligations.
  26. *
  27. * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
  28. * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
  29. * COMPLETENESS OR PERFORMANCE.
  30. * $/LicenseInfo$
  31. */
  32. #include "llviewerprecompiledheaders.h"
  33. #ifndef LL_WINDOWS
  34. # include <netdb.h>
  35. #endif
  36. #include <utility>
  37. #include "boost/iostreams/device/array.hpp"
  38. #include "boost/iostreams/stream.hpp"
  39. #include "boost/lexical_cast.hpp"
  40. #include "llmeshrepository.h"
  41. #include "imageids.h"
  42. #include "llapp.h"
  43. #include "llcallbacklist.h"
  44. #include "llcorebufferarray.h"
  45. #include "llcorebufferstream.h"
  46. #include "llcorehttputil.h"
  47. #include "lldatapacker.h"
  48. #include "lleconomy.h"
  49. #include "llfilesystem.h"
  50. #include "llfoldertype.h"
  51. #include "llhttpconstants.h"
  52. #include "llhost.h"
  53. #include "llimagej2c.h"
  54. #include "llnotifications.h"
  55. #include "llsd.h"
  56. #include "llsdserialize.h"
  57. #include "llsdutil_math.h"
  58. #include "llthread.h"
  59. #include "hbtracy.h"
  60. #include "lltrans.h"
  61. #include "llvolumemgr.h"
  62. #include "llagent.h"
  63. #include "llfloaterperms.h"
  64. #include "llinventorymodel.h"
  65. #include "llpipeline.h"
  66. #include "llviewerassetupload.h"
  67. #include "llviewercontrol.h"
  68. #include "llviewerinventory.h"
  69. #include "llviewermenu.h"
  70. #include "llviewerobject.h"
  71. #include "llviewerparcelmgr.h"
  72. #include "llviewerregion.h"
  73. #include "llviewertexturelist.h"
  74. #include "llvovolume.h"
  75. #include "llworld.h"
  76. // Purpose
  77. //
  78. // The purpose of this module is to provide access between the viewer and the
  79. // asset system as regards to mesh objects.
  80. // (for structural details, see:
  81. // http://wiki.secondlife.com/wiki/Mesh/Mesh_Asset_Format)
  82. //
  83. // * High-throughput download of mesh assets from servers while following
  84. // best industry practices for network profile.
  85. // * Reliable expensing and upload of new mesh assets.
  86. // * Recovery and retry from errors when appropriate.
  87. // * Decomposition of mesh assets for preview and uploads.
  88. // * And most important: all of the above without exposing the main thread to
  89. // stalls due to deep processing or thread locking actions. In particular,
  90. // the following operations on LLMeshRepository are very averse to any
  91. // stalls:
  92. // * loadMesh
  93. // * notifyLoadedMeshes
  94. // * getSkinInfo
  95. //
  96. // Threads
  97. //
  98. // main Main rendering thread, very sensitive to locking and other stalls
  99. // repo Overseeing worker thread associated with the LLMeshRepoThread
  100. // class
  101. // decom Worker thread for mesh decomposition requests
  102. // core HTTP worker thread: does the work but doesn't intrude here
  103. // uploadN 0-N temporary mesh upload threads (0-1 in practice)
  104. //
  105. // Sequence of Operations
  106. //
  107. // What follows is a description of the retrieval of one LOD for a new mesh
  108. // object. Work is performed by a series of short, quick actions distributed
  109. // over a number of threads. Each is meant to proceed without stalling and the
  110. // whole forms a deep request pipeline to achieve throughput. Ellipsis
  111. // indicates a return or break in processing which is resumed elsewhere.
  112. //
  113. // main thread repo thread (run() method)
  114. //
  115. // loadMesh() invoked to request LOD
  116. // append LODRequest to mPendingRequests
  117. // ...
  118. // other mesh requests may be made
  119. // ...
  120. // notifyLoadedMeshes() invoked to stage work
  121. // append HeaderRequest to mHeaderReqQ
  122. // ...
  123. // scan mHeaderReqQ
  124. // issue 4096-byte GET for header
  125. // ...
  126. // onCompleted() invoked for GET
  127. // data copied
  128. // headerReceived() invoked
  129. // LLSD parsed
  130. // mMeshHeaders updated
  131. // scan mPendingLOD for LOD request
  132. // push LODRequest to mLODReqQ
  133. // ...
  134. // scan mLODReqQ
  135. // fetchMeshLOD() invoked
  136. // issue Byte-Range GET for LOD
  137. // ...
  138. // onCompleted() invoked for GET
  139. // data copied
  140. // lodReceived() invoked
  141. // unpack data into LLVolume
  142. // append LoadedMesh to mLoadedMeshes
  143. // ...
  144. // notifyLoadedMeshes() invoked again
  145. // scan mLoadedMeshes
  146. // notifyMeshLoaded() for LOD
  147. // setMeshAssetLoaded() invoked for system volume
  148. // notifyMeshLoaded() invoked for each interested object
  149. // ...
  150. //
  151. // Mutexes
  152. //
  153. // LLMeshRepository::mMeshMutex
  154. // LLMeshRepoThread::mMutex
  155. // LLMeshRepoThread::mHeaderMutex
  156. // LLMeshRepoThread::mSignal (LLCondition)
  157. // LLPhysicsDecomp::mSignal (LLCondition)
  158. // LLPhysicsDecomp::mMutex
  159. // LLMeshUploadThread::mMutex
  160. //
  161. // Mutex Order Rules
  162. //
  163. // 1. LLMeshRepoThread::mMutex before LLMeshRepoThread::mHeaderMutex
  164. // 2. LLMeshRepository::mMeshMutex before LLMeshRepoThread::mMutex
  165. // (there are more rules, have not been extracted)
  166. //
  167. // Data Member Access/Locking
  168. //
  169. // Description of how shared access to static and instance data members is
  170. // performed. Each member is followed by the name of the mutex, if any,
  171. // covering the data and then a list of data access models each of which is a
  172. // triplet of the following form:
  173. //
  174. // {ro, wo, rw}.{main, repo, any}.{mutex, none}
  175. // Type of access: read-only, write-only, read-write.
  176. // Accessing thread or 'any'
  177. // Relevant mutex held during access (several may be held) or 'none'
  178. //
  179. // A careful eye will notice some unsafe operations. Many of these have an
  180. // alibi of some form. Several types of alibi are identified and listed here:
  181. //
  182. // [1] Single-writer, self-consistent readers. Old data must be tolerated
  183. // by any reader but data will come true eventually.
  184. // [2] Like [1] but provides a hint about thread state. These may be
  185. // unsafe.
  186. // [3] empty() check outside of lock. Can me made safish when done in
  187. // double-check lock style. But this depends on std:: implementation
  188. // and memory model.
  189. // [4] Appears to be covered by a mutex but does not need one.
  190. // [5] Read of a double-checked lock.
  191. //
  192. // So, in addition to documentation, take this as a to-do/review list and see
  193. // if you can improve things. For porters to non-x86 architectures, the weaker
  194. // memory models will make these platforms probabilistically more susceptible
  195. // to hitting race conditions. True here and in other multi-thread code such as
  196. // texture fetching.
  197. //
  198. // LLMeshRepository:
  199. //
  200. // sBytesReceived none rw.repo.none, ro.main.none [1]
  201. // sMeshRequestCount "
  202. // sHTTPRequestCount "
  203. // sHTTPLargeRequestCount "
  204. // sHTTPRetryCount "
  205. // sHTTPErrorCount "
  206. // sLODPending atomic
  207. // sLODProcessing atomic
  208. // sCacheBytesRead none rw.repo.none, ro.main.none [1]
  209. // sCacheBytesWritten "
  210. // sCacheReads "
  211. // sCacheWrites "
  212. // mLoadingMeshes mMeshMutex [4] rw.main.none, rw.any.mMeshMutex
  213. // mSkinMap none rw.main.none
  214. // mDecompositionMap none rw.main.none
  215. // mPendingRequests mMeshMutex [4] rw.main.mMeshMutex
  216. // mLoadingSkins mMeshMutex [4] rw.main.mMeshMutex
  217. // mPendingSkinRequests mMeshMutex [4] rw.main.mMeshMutex
  218. // mLoadingDecompositions mMeshMutex [4] rw.main.mMeshMutex
  219. // mPendingDecompositionRequests mMeshMutex [4] rw.main.mMeshMutex
  220. // mLoadingPhysicsShapes mMeshMutex [4] rw.main.mMeshMutex
  221. // mPendingPhysicsShapeRequests mMeshMutex [4] rw.main.mMeshMutex
  222. // mUploads none rw.main.none (upload thread accessing objects)
  223. // mUploadWaitList none rw.main.none (upload thread accessing objects)
  224. // mInventoryQ mMeshMutex [4] rw.main.mMeshMutex, ro.main.none [5]
  225. // mUploadErrorQ mMeshMutex rw.main.mMeshMutex, rw.any.mMeshMutex
  226. //
  227. // LLMeshRepoThread:
  228. //
  229. // sActiveHeaderRequests atomic
  230. // sActiveLODRequests atomic
  231. // sMaxConcurrentRequests mMutex wo.main.none, ro.repo.none, ro.main.mMutex
  232. // mMeshHeaders mHeaderMutex rw.repo.mHeaderMutex, ro.main.mHeaderMutex
  233. // mSkinRequests mMutex rw.repo.mMutex, ro.repo.none [5]
  234. // mSkinInfos mMutex rw.repo.mMutex, rw.main.mMutex [5]
  235. // mDecompositionRequests mMutex rw.repo.mMutex, ro.repo.none [5]
  236. // mPhysicsShapeRequests mMutex rw.repo.mMutex, ro.repo.none [5]
  237. // mDecompositions mMutex rw.repo.mMutex, rw.main.mMutex [5]
  238. // mHeaderReqQ mMutex ro.repo.none [5], rw.repo.mMutex, rw.any.mMutex
  239. // mLODReqQ mMutex ro.repo.none [5], rw.repo.mMutex, rw.any.mMutex
  240. // mUnavailableLODs mMutex rw.repo.mMutex, ro.main.none [5], rw.main.mMutex
  241. // mLoadedMeshes mMutex rw.repo.mMutex, ro.main.none [5], rw.main.mMutex
  242. // mPendingLOD mMutex rw.repo.mMutex, rw.any.mMutex
  243. // mGetMeshCapability mMutex rw.main.mMutex, ro.repo.mMutex
  244. // mGetMeshVersion mMutex rw.main.mMutex, ro.repo.mMutex
  245. // mHttp* none rw.repo.none
  246. //
  247. // LLMeshUploadThread:
  248. //
  249. // mDiscarded mMutex rw.main.mMutex, ro.uploadN.none [1]
  250. // ... more ...
  251. //
  252. // *TODO: work list for followup actions:
  253. // * Review anything marked as unsafe above, verify if there are real issues.
  254. // * See if we can put ::run() into a hard sleep. May not actually perform
  255. // better than the current scheme so be prepared for disappointment. You
  256. // will likely need to introduce a condition variable class that references
  257. // a mutex in methods rather than derives from mutex which is not correct.
  258. // * On upload failures, make more information available to the alerting
  259. // dialog. Get the structured information going into the log into a tree
  260. // there.
  261. // * Header parse failures come without much explanation. Elaborate.
  262. // * Work queue for uploads ? Any need for this or is the current scheme
  263. // good enough ?
  264. // * Move data structures holding mesh data used by main thread into main-
  265. // thread-only access so that no locking is needed. May require duplication
  266. // of some data so that worker thread has a minimal data set to guide
  267. // operations.
  268. LLMeshRepository gMeshRepo;
  269. // Important: assumption is that headers fit in this space
  270. constexpr S32 MESH_HEADER_SIZE = 4096;
  271. // Limits for GetMesh regions
  272. constexpr S32 REQUEST_HIGH_WATER_MIN = 32;
  273. constexpr S32 REQUEST_HIGH_WATER_MAX = 150; // Should remain under 2X throttle
  274. constexpr S32 REQUEST_LOW_WATER_MIN = 16;
  275. constexpr S32 REQUEST_LOW_WATER_MAX = 75;
  276. // Limits for GetMesh2 regions
  277. constexpr S32 REQUEST2_HIGH_WATER_MIN = 32;
  278. constexpr S32 REQUEST2_HIGH_WATER_MAX = 100;
  279. constexpr S32 REQUEST2_LOW_WATER_MIN = 16;
  280. constexpr S32 REQUEST2_LOW_WATER_MAX = 50;
  281. // Size at which requests goes to narrow/slow queue
  282. constexpr U32 LARGE_MESH_FETCH_THRESHOLD = 1U << 21;
  283. // Seconds to complete xfer, small mesh downloads
  284. constexpr long SMALL_MESH_XFER_TIMEOUT = 120L;
  285. // Seconds to complete xfer, large downloads
  286. constexpr long LARGE_MESH_XFER_TIMEOUT = 600L;
  287. // Would normally like to retry on uploads as some retryable failures would be
  288. // recoverable. Unfortunately, the mesh service is using 500 (retryable) rather
  289. // than 400/bad request (permanent) for a bad payload and retrying that just
  290. // leads to revocation of the one-shot cap which then produces a 404 on retry
  291. // destroying some (occasionally) useful error information. We'll leave upload
  292. // retries to the user as in the past. SH-4667.
  293. constexpr long UPLOAD_RETRY_LIMIT = 0L;
  294. // Maximum mesh version to support. Three least significant digits are reserved
  295. // for the minor version, with major version changes indicating a format change
  296. // that is not backwards compatible and should not be parsed by viewers that
  297. // don't specifically support that version. For example, if the integer "1" is
  298. // present, the version is 0.001. A viewer that can parse version 0.001 can
  299. // also parse versions up to 0.999, but not 1.0 (integer 1000).
  300. // See the wiki at https://wiki.secondlife.com/wiki/Mesh/Mesh_Asset_Format
  301. constexpr S32 MAX_MESH_VERSION = 999;
  302. U32 LLMeshRepository::sBytesReceived = 0;
  303. U32 LLMeshRepository::sMeshRequestCount = 0;
  304. U32 LLMeshRepository::sHTTPRequestCount = 0;
  305. U32 LLMeshRepository::sHTTPLargeRequestCount = 0;
  306. U32 LLMeshRepository::sHTTPRetryCount = 0;
  307. U32 LLMeshRepository::sHTTPErrorCount = 0;
  308. LLAtomicU32 LLMeshRepository::sLODProcessing(0);
  309. LLAtomicU32 LLMeshRepository::sLODPending(0);
  310. U32 LLMeshRepository::sCacheBytesRead = 0;
  311. U32 LLMeshRepository::sCacheBytesWritten = 0;
  312. U32 LLMeshRepository::sCacheReads = 0;
  313. U32 LLMeshRepository::sCacheWrites = 0;
  314. U32 LLMeshRepository::sMaxLockHoldoffs = 0;
  315. LLAtomicS32 LLMeshRepoThread::sActiveHeaderRequests(0);
  316. LLAtomicS32 LLMeshRepoThread::sActiveLODRequests(0);
  317. U32 LLMeshRepoThread::sMaxConcurrentRequests = 1;
  318. S32 LLMeshRepoThread::sRequestLowWater = REQUEST2_LOW_WATER_MIN;
  319. S32 LLMeshRepoThread::sRequestHighWater = REQUEST2_HIGH_WATER_MIN;
  320. S32 LLMeshRepoThread::sRequestWaterLevel = 0;
  321. namespace {
  322. // The NoOpDeletor is used when passing certain objects (generally the
  323. // LLMeshUploadThread) in a smart pointer below for passage into the
  324. // LLCore::Http libararies. When the smart pointer is destroyed, no action
  325. // will be taken since we do not in these cases want the object to be
  326. // destroyed at the end of the call.
  327. void NoOpDeletor(LLCore::HttpHandler*) {}
  328. }
  329. // Helper functions
  330. static S32 sDumpNum = 0;
  331. static std::string make_dump_name(const std::string& prefix, S32 num)
  332. {
  333. return prefix + boost::lexical_cast<std::string>(num) + ".xml";
  334. }
  335. // Also used by llfloatermodelpreview.cpp, therefore not static
  336. void dump_llsd_to_file(const LLSD& content, const std::string& filename)
  337. {
  338. if (gSavedSettings.getBool("MeshUploadLogXML"))
  339. {
  340. std::ofstream of(filename.c_str());
  341. LLSDSerialize::toPrettyXML(content, of);
  342. }
  343. }
  344. #if 0 // Not used
  345. static LLSD llsd_from_file(const std::string& filename)
  346. {
  347. std::ifstream ifs(filename.c_str());
  348. LLSD result;
  349. LLSDSerialize::fromXML(result, ifs);
  350. return result;
  351. }
  352. // Returns the number of bytes resident in memory for given volume
  353. static U32 get_volume_memory_size(const LLVolume* volume)
  354. {
  355. U32 indices = 0;
  356. U32 vertices = 0;
  357. for (S32 i = 0, count = volume->getNumVolumeFaces(); i < count; ++i)
  358. {
  359. const LLVolumeFace& face = volume->getVolumeFace(i);
  360. indices += face.mNumIndices;
  361. vertices += face.mNumVertices;
  362. }
  363. return indices * 2 + vertices * 11 + sizeof(LLVolume) +
  364. sizeof(LLVolumeFace) * volume->getNumVolumeFaces();
  365. }
  366. #endif
  367. static void get_vertex_buffer_from_mesh(LLCDMeshData& mesh,
  368. LLModel::PhysicsMesh& res,
  369. F32 scale = 1.f)
  370. {
  371. res.mPositions.clear();
  372. res.mNormals.clear();
  373. const F32* v = mesh.mVertexBase;
  374. if (mesh.mIndexType == LLCDMeshData::INT_16)
  375. {
  376. U16* idx = (U16*) mesh.mIndexBase;
  377. for (S32 j = 0; j < mesh.mNumTriangles; ++j)
  378. {
  379. F32* mp0 = (F32*)((U8*)v + idx[0] * mesh.mVertexStrideBytes);
  380. F32* mp1 = (F32*)((U8*)v + idx[1] * mesh.mVertexStrideBytes);
  381. F32* mp2 = (F32*)((U8*)v + idx[2] * mesh.mVertexStrideBytes);
  382. idx = (U16*)(((U8*)idx) + mesh.mIndexStrideBytes);
  383. LLVector3 v0(mp0);
  384. LLVector3 v1(mp1);
  385. LLVector3 v2(mp2);
  386. LLVector3 n = (v1 - v0) % (v2 - v0);
  387. n.normalize();
  388. res.mPositions.emplace_back(v0 * scale);
  389. res.mPositions.emplace_back(v1 * scale);
  390. res.mPositions.emplace_back(v2 * scale);
  391. res.mNormals.emplace_back(n);
  392. res.mNormals.emplace_back(n);
  393. res.mNormals.emplace_back(n);
  394. }
  395. }
  396. else
  397. {
  398. U32* idx = (U32*)mesh.mIndexBase;
  399. for (S32 j = 0; j < mesh.mNumTriangles; ++j)
  400. {
  401. F32* mp0 = (F32*)((U8*)v + idx[0] * mesh.mVertexStrideBytes);
  402. F32* mp1 = (F32*)((U8*)v + idx[1] * mesh.mVertexStrideBytes);
  403. F32* mp2 = (F32*)((U8*)v + idx[2] * mesh.mVertexStrideBytes);
  404. idx = (U32*)(((U8*)idx) + mesh.mIndexStrideBytes);
  405. LLVector3 v0(mp0);
  406. LLVector3 v1(mp1);
  407. LLVector3 v2(mp2);
  408. LLVector3 n = (v1 - v0) % (v2 - v0);
  409. n.normalize();
  410. res.mPositions.emplace_back(v0 * scale);
  411. res.mPositions.emplace_back(v1 * scale);
  412. res.mPositions.emplace_back(v2 * scale);
  413. res.mNormals.emplace_back(n);
  414. res.mNormals.emplace_back(n);
  415. res.mNormals.emplace_back(n);
  416. }
  417. }
  418. }
  419. ///////////////////////////////////////////////////////////////////////////////
  420. // LLMeshHeader class
  421. ///////////////////////////////////////////////////////////////////////////////
  422. LLMeshHeader::LLMeshHeader() noexcept
  423. {
  424. reset();
  425. }
  426. void LLMeshHeader::reset()
  427. {
  428. mValid = false;
  429. mHeaderSize = 0;
  430. mLodOffset[0] = mLodOffset[1] = mLodOffset[2] = mLodOffset[3] = 0;
  431. mLodSize[0] = mLodSize[1] = mLodSize[2] = mLodSize[3] = 0;
  432. mSkinOffset = mSkinSize = 0;
  433. mPhysicsConvexOffset = mPhysicsConvexSize = 0;
  434. mPhysicsMeshOffset = mPhysicsMeshSize = 0;
  435. }
  436. void LLMeshHeader::init(const LLSD& header, U32 size)
  437. {
  438. LL_TRACY_TIMER(TRC_MESH_HEADER_INIT);
  439. mHeaderSize = size;
  440. mValid = size && !header.has("404");
  441. if (!mValid)
  442. {
  443. // Invalid mesh header
  444. return;
  445. }
  446. if (header.has("version"))
  447. {
  448. mValid = header["version"].asInteger() <= MAX_MESH_VERSION;
  449. if (!mValid)
  450. {
  451. // Invalid mesh header
  452. return;
  453. }
  454. }
  455. if (header.has("lowest_lod"))
  456. {
  457. const LLSD& lod = header["lowest_lod"];
  458. if (lod.has("offset"))
  459. {
  460. mLodOffset[0] = lod["offset"].asInteger();
  461. }
  462. mLodOffset[0] += size;
  463. if (lod.has("size"))
  464. {
  465. mLodSize[0] = lod["size"].asInteger();
  466. }
  467. }
  468. if (header.has("low_lod"))
  469. {
  470. const LLSD& lod = header["low_lod"];
  471. if (lod.has("offset"))
  472. {
  473. mLodOffset[1] = lod["offset"].asInteger();
  474. }
  475. mLodOffset[1] += size;
  476. if (lod.has("size"))
  477. {
  478. mLodSize[1] = lod["size"].asInteger();
  479. }
  480. }
  481. if (header.has("medium_lod"))
  482. {
  483. const LLSD& lod = header["medium_lod"];
  484. if (lod.has("offset"))
  485. {
  486. mLodOffset[2] = lod["offset"].asInteger();
  487. }
  488. mLodOffset[2] += size;
  489. if (lod.has("size"))
  490. {
  491. mLodSize[2] = lod["size"].asInteger();
  492. }
  493. }
  494. if (header.has("high_lod"))
  495. {
  496. const LLSD& lod = header["high_lod"];
  497. if (lod.has("offset"))
  498. {
  499. mLodOffset[3] = lod["offset"].asInteger();
  500. }
  501. mLodOffset[3] += size;
  502. if (lod.has("size"))
  503. {
  504. mLodSize[3] = lod["size"].asInteger();
  505. }
  506. }
  507. if (header.has("skin"))
  508. {
  509. const LLSD& lod = header["skin"];
  510. if (lod.has("offset"))
  511. {
  512. mSkinOffset = lod["offset"].asInteger();
  513. }
  514. mSkinOffset += size;
  515. if (lod.has("size"))
  516. {
  517. mSkinSize = lod["size"].asInteger();
  518. }
  519. }
  520. if (header.has("physics_convex"))
  521. {
  522. const LLSD& lod = header["physics_convex"];
  523. if (lod.has("offset"))
  524. {
  525. mPhysicsConvexOffset = lod["offset"].asInteger();
  526. }
  527. mPhysicsConvexOffset += size;
  528. if (lod.has("size"))
  529. {
  530. mPhysicsConvexSize = lod["size"].asInteger();
  531. }
  532. }
  533. if (header.has("physics_mesh"))
  534. {
  535. const LLSD& lod = header["physics_mesh"];
  536. if (lod.has("offset"))
  537. {
  538. mPhysicsMeshOffset = lod["offset"].asInteger();
  539. }
  540. mPhysicsMeshOffset += size;
  541. if (lod.has("size"))
  542. {
  543. mPhysicsMeshSize = lod["size"].asInteger();
  544. }
  545. }
  546. // Header is valid if we found at least one valid LOD in it
  547. mValid = mLodSize[0] || mLodSize[1] || mLodSize[2] || mLodSize[3];
  548. }
  549. ///////////////////////////////////////////////////////////////////////////////
  550. // LLMeshCostData class
  551. ///////////////////////////////////////////////////////////////////////////////
  552. LLMeshCostData::LLMeshCostData() noexcept
  553. : mSizeTotal(0),
  554. mEstTrisMax(0.f),
  555. mChargedTris(-1.f)
  556. {
  557. mSizeByLOD.resize(4, 0);
  558. mEstTrisByLOD.resize(4, 0.f);
  559. }
  560. bool LLMeshCostData::init(LLMeshHeader* header)
  561. {
  562. return header &&
  563. init(header->mLodSize[0], header->mLodSize[1], header->mLodSize[2],
  564. header->mLodSize[3]);
  565. }
  566. bool LLMeshCostData::init(const LLSD& header)
  567. {
  568. LL_TRACY_TIMER(TRC_MESH_COST_INIT);
  569. S32 bytes_lowest = 0;
  570. if (header.has("lowest_lod"))
  571. {
  572. bytes_lowest = header["lowest_lod"]["size"].asInteger();
  573. }
  574. S32 bytes_low = 0;
  575. if (header.has("low_lod"))
  576. {
  577. bytes_low = header["low_lod"]["size"].asInteger();
  578. }
  579. S32 bytes_med = 0;
  580. if (header.has("medium_lod"))
  581. {
  582. bytes_med = header["medium_lod"]["size"].asInteger();
  583. }
  584. S32 bytes_high = 0;
  585. if (header.has("high_lod"))
  586. {
  587. bytes_high = header["high_lod"]["size"].asInteger();
  588. }
  589. return init(bytes_lowest, bytes_low, bytes_med, bytes_high);
  590. }
  591. bool LLMeshCostData::init(S32 bytes_lowest, S32 bytes_low, S32 bytes_med,
  592. S32 bytes_high)
  593. {
  594. if (bytes_high <= 0)
  595. {
  596. bytes_high = llmax(0, bytes_med, bytes_low, bytes_lowest);
  597. }
  598. if (bytes_high == 0)
  599. {
  600. return false;
  601. }
  602. mSizeByLOD[3] = bytes_high;
  603. if (bytes_med <= 0)
  604. {
  605. bytes_med = bytes_high;
  606. }
  607. mSizeByLOD[2] = bytes_med;
  608. if (bytes_low <= 0)
  609. {
  610. bytes_low = bytes_med;
  611. }
  612. mSizeByLOD[1] = bytes_low;
  613. if (bytes_lowest <= 0)
  614. {
  615. bytes_lowest = bytes_low;
  616. }
  617. mSizeByLOD[0] = bytes_lowest;
  618. mSizeTotal = bytes_high + bytes_med + bytes_low + bytes_lowest;
  619. static LLCachedControl<U32> discount(gSavedSettings,
  620. "MeshMetaDataDiscount");
  621. static LLCachedControl<U32> min_size(gSavedSettings,
  622. "MeshMinimumByteSize");
  623. static LLCachedControl<U32> tri_bytes(gSavedSettings,
  624. "MeshBytesPerTriangle");
  625. F32 max = 0.f;
  626. F32 bytes_per_tri = (F32)tri_bytes;
  627. for (S32 i = 0; i < 4; ++i)
  628. {
  629. S32 size = mSizeByLOD[i] - discount;
  630. if (size < (S32)min_size)
  631. {
  632. size = min_size;
  633. }
  634. F32 tris = (F32)size / bytes_per_tri;
  635. if (tris > max)
  636. {
  637. max = tris;
  638. }
  639. mEstTrisByLOD[i] = tris;
  640. }
  641. mEstTrisMax = max;
  642. mChargedTris = -1.f;
  643. return true;
  644. }
  645. F32 LLMeshCostData::getRadiusWeightedTris(F32 radius)
  646. {
  647. constexpr F32 MAX_DISTANCE = 512.f;
  648. constexpr F32 K1 = 1.f / 0.03f;
  649. constexpr F32 K2 = 1.f / 0.06f;
  650. constexpr F32 K3 = 1.f / 0.24f;
  651. F32 dlowest = llmin(radius * K1, MAX_DISTANCE);
  652. F32 dlow = llmin(radius * K2, MAX_DISTANCE);
  653. F32 dmid = llmin(radius * K3, MAX_DISTANCE);
  654. // Area of a circle that encompasses region (see MAINT-6559):
  655. constexpr F32 MAX_AREA = 102944.f;
  656. constexpr F32 MIN_AREA = 1.f;
  657. F32 high_area = llmin(F_PI * dmid * dmid, MAX_AREA);
  658. F32 mid_area = llmin(F_PI * dlow * dlow, MAX_AREA);
  659. F32 low_area = llmin(F_PI * dlowest * dlowest, MAX_AREA);
  660. F32 lowest_area = MAX_AREA;
  661. lowest_area -= low_area;
  662. low_area -= mid_area;
  663. mid_area -= high_area;
  664. high_area = llclamp(high_area, MIN_AREA, MAX_AREA);
  665. mid_area = llclamp(mid_area, MIN_AREA, MAX_AREA);
  666. low_area = llclamp(low_area, MIN_AREA, MAX_AREA);
  667. lowest_area = llclamp(lowest_area, MIN_AREA, MAX_AREA);
  668. F32 inv_total_area = 1.f / (high_area + mid_area + low_area + lowest_area);
  669. high_area *= inv_total_area;
  670. mid_area *= inv_total_area;
  671. low_area *= inv_total_area;
  672. lowest_area *= inv_total_area;
  673. return mEstTrisByLOD[3] * high_area + mEstTrisByLOD[2] * mid_area +
  674. mEstTrisByLOD[1] * low_area + mEstTrisByLOD[0] * lowest_area;
  675. }
  676. F32 LLMeshCostData::getEstTrisForStreamingCost()
  677. {
  678. if (mChargedTris < 0.f)
  679. {
  680. mChargedTris = mEstTrisByLOD[3];
  681. F32 allowed_tris = mChargedTris;
  682. constexpr F32 ENFORCE_FLOOR = 64.f;
  683. for (S32 i = 2; i >= 0; --i)
  684. {
  685. // How many tris can we have in this LOD without affecting land
  686. // impact ?
  687. // - normally a LOD should be at most half the size of the previous
  688. // one
  689. // - once we reach a floor of ENFORCE_FLOOR, do not require LODs to
  690. // get any smaller.
  691. allowed_tris = llclamp(allowed_tris * 0.5f, ENFORCE_FLOOR,
  692. mEstTrisByLOD[i]);
  693. F32 excess_tris = mEstTrisByLOD[i] - allowed_tris;
  694. if (excess_tris > 0.f)
  695. {
  696. mChargedTris += excess_tris;
  697. }
  698. }
  699. }
  700. return mChargedTris;
  701. }
  702. F32 LLMeshCostData::getRadiusBasedStreamingCost(F32 radius)
  703. {
  704. LL_TRACY_TIMER(TRC_MESH_COST_RADIUS);
  705. static LLCachedControl<U32> budget(gSavedSettings, "MeshTriangleBudget");
  706. F32 triangle_budget = budget > 0 ? (F32)budget : 250000.f;
  707. return getRadiusWeightedTris(radius) * 15000.f / triangle_budget;
  708. }
  709. F32 LLMeshCostData::getTriangleBasedStreamingCost()
  710. {
  711. LL_TRACY_TIMER(TRC_MESH_COST_TRI);
  712. return ANIMATED_OBJECT_COST_PER_KTRI * 0.001f *
  713. getEstTrisForStreamingCost();
  714. }
  715. ///////////////////////////////////////////////////////////////////////////////
  716. // LLMeshHandlerBase class
  717. //
  718. // Base handler class for all mesh users of llcorehttp. This is roughly
  719. // equivalent to a Responder class in traditional LL code. The base is going to
  720. // perform common response/data handling in the inherited onCompleted() method.
  721. // Derived classes, one for each type of HTTP action, define processData() and
  722. // processFailure() methods to customize handling and error messages.
  723. //
  724. // LLCore::HttpHandler
  725. // LLMeshHandlerBase
  726. // LLMeshHeaderHandler
  727. // LLMeshLODHandler
  728. // LLMeshSkinInfoHandler
  729. // LLMeshDecompositionHandler
  730. // LLMeshPhysicsShapeHandler
  731. // LLMeshUploadThread
  732. class LLMeshHandlerBase : public LLCore::HttpHandler,
  733. public std::enable_shared_from_this<LLMeshHandlerBase>
  734. {
  735. protected:
  736. LOG_CLASS(LLMeshHandlerBase);
  737. public:
  738. typedef std::shared_ptr<LLMeshHandlerBase> ptr_t;
  739. LLMeshHandlerBase(U32 offset, U32 requested_bytes)
  740. : LLCore::HttpHandler(),
  741. mMeshParams(),
  742. mProcessed(false),
  743. mHttpHandle(LLCORE_HTTP_HANDLE_INVALID),
  744. mOffset(offset),
  745. mRequestedBytes(requested_bytes)
  746. {
  747. }
  748. ~LLMeshHandlerBase() override
  749. {
  750. }
  751. LLMeshHandlerBase(const LLMeshHandlerBase&) = delete;
  752. void operator=(const LLMeshHandlerBase&) = delete;
  753. public:
  754. void onCompleted(LLCore::HttpHandle handle,
  755. LLCore::HttpResponse* response) override;
  756. // New virtual methods
  757. virtual void processData(LLCore::BufferArray* body, S32 body_offset,
  758. U8* data, S32 data_size) = 0;
  759. virtual void processFailure(LLCore::HttpStatus status) = 0;
  760. public:
  761. LLCore::HttpHandle mHttpHandle;
  762. S32 mOffset;
  763. U32 mRequestedBytes;
  764. LLVolumeParams mMeshParams;
  765. bool mProcessed;
  766. };
  767. // Subclass for header fetches.
  768. //
  769. // Thread: repo
  770. class LLMeshHeaderHandler final : public LLMeshHandlerBase
  771. {
  772. protected:
  773. LOG_CLASS(LLMeshHeaderHandler);
  774. public:
  775. LLMeshHeaderHandler(const LLVolumeParams& mesh_params, U32 offset,
  776. U32 requested_bytes)
  777. : LLMeshHandlerBase(offset, requested_bytes)
  778. {
  779. mMeshParams = mesh_params;
  780. ++LLMeshRepoThread::sActiveHeaderRequests;
  781. }
  782. ~LLMeshHeaderHandler() override;
  783. LLMeshHeaderHandler(const LLMeshHeaderHandler&) = delete;
  784. void operator=(const LLMeshHeaderHandler&) = delete;
  785. void processData(LLCore::BufferArray* body, S32 body_offset, U8* data,
  786. S32 data_size) override;
  787. void processFailure(LLCore::HttpStatus status) override;
  788. };
  789. // Subclass for LOD fetches.
  790. //
  791. // Thread: repo
  792. class LLMeshLODHandler final : public LLMeshHandlerBase
  793. {
  794. protected:
  795. LOG_CLASS(LLMeshLODHandler);
  796. public:
  797. LLMeshLODHandler(const LLVolumeParams & mesh_params, S32 lod, U32 offset,
  798. U32 requested_bytes)
  799. : LLMeshHandlerBase(offset, requested_bytes),
  800. mLOD(lod)
  801. {
  802. mMeshParams = mesh_params;
  803. ++LLMeshRepoThread::sActiveLODRequests;
  804. }
  805. ~LLMeshLODHandler() override;
  806. LLMeshLODHandler(const LLMeshLODHandler&) = delete;
  807. void operator=(const LLMeshLODHandler&) = delete;
  808. void processData(LLCore::BufferArray* body, S32 body_offset, U8* data,
  809. S32 data_size) override;
  810. void processFailure(LLCore::HttpStatus status) override;
  811. public:
  812. S32 mLOD;
  813. };
  814. // Subclass for skin info fetches.
  815. //
  816. // Thread: repo
  817. class LLMeshSkinInfoHandler final : public LLMeshHandlerBase
  818. {
  819. protected:
  820. LOG_CLASS(LLMeshSkinInfoHandler);
  821. public:
  822. LLMeshSkinInfoHandler(const LLUUID& id, U32 offset, U32 requested_bytes)
  823. : LLMeshHandlerBase(offset, requested_bytes),
  824. mMeshID(id)
  825. {
  826. }
  827. ~LLMeshSkinInfoHandler() override;
  828. LLMeshSkinInfoHandler(const LLMeshSkinInfoHandler&) = delete;
  829. void operator=(const LLMeshSkinInfoHandler&) = delete;
  830. void processData(LLCore::BufferArray* body, S32 body_offset, U8* data,
  831. S32 data_size) override;
  832. void processFailure(LLCore::HttpStatus status) override;
  833. public:
  834. LLUUID mMeshID;
  835. };
  836. // Subclass for decomposition fetches.
  837. //
  838. // Thread: repo
  839. class LLMeshDecompositionHandler final : public LLMeshHandlerBase
  840. {
  841. protected:
  842. LOG_CLASS(LLMeshDecompositionHandler);
  843. public:
  844. LLMeshDecompositionHandler(const LLUUID& id, U32 offset,
  845. U32 requested_bytes)
  846. : LLMeshHandlerBase(offset, requested_bytes),
  847. mMeshID(id)
  848. {
  849. }
  850. ~LLMeshDecompositionHandler() override;
  851. LLMeshDecompositionHandler(const LLMeshDecompositionHandler&) = delete;
  852. void operator=(const LLMeshDecompositionHandler&) = delete;
  853. void processData(LLCore::BufferArray* body, S32 body_offset, U8* data,
  854. S32 data_size) override;
  855. void processFailure(LLCore::HttpStatus status) override;
  856. public:
  857. LLUUID mMeshID;
  858. };
  859. // Subclass for physics shape fetches.
  860. //
  861. // Thread: repo
  862. class LLMeshPhysicsShapeHandler final : public LLMeshHandlerBase
  863. {
  864. protected:
  865. LOG_CLASS(LLMeshPhysicsShapeHandler);
  866. public:
  867. LLMeshPhysicsShapeHandler(const LLUUID& id, U32 offset,
  868. U32 requested_bytes)
  869. : LLMeshHandlerBase(offset, requested_bytes),
  870. mMeshID(id)
  871. {
  872. }
  873. ~LLMeshPhysicsShapeHandler() override;
  874. LLMeshPhysicsShapeHandler(const LLMeshPhysicsShapeHandler&) = delete;
  875. void operator=(const LLMeshPhysicsShapeHandler&) = delete;
  876. void processData(LLCore::BufferArray* body, S32 body_offset, U8* data,
  877. S32 data_size) override;
  878. void processFailure(LLCore::HttpStatus status) override;
  879. public:
  880. LLUUID mMeshID;
  881. };
  882. LLMeshRepoThread::LLMeshRepoThread()
  883. : LLThread("Mesh repository"),
  884. mHttpPolicyClass(LLCore::HttpRequest::DEFAULT_POLICY_ID),
  885. mHttpLegacyPolicyClass(LLCore::HttpRequest::DEFAULT_POLICY_ID),
  886. mHttpLargePolicyClass(LLCore::HttpRequest::DEFAULT_POLICY_ID),
  887. mGetMeshVersion(2)
  888. {
  889. mHttpRequest = new LLCore::HttpRequest;
  890. mHttpOptions = DEFAULT_HTTP_OPTIONS;
  891. mHttpOptions->setTransferTimeout(SMALL_MESH_XFER_TIMEOUT);
  892. bool use_retyr_after = gSavedSettings.getBool("MeshUseHttpRetryAfter");
  893. mHttpOptions->setUseRetryAfter(use_retyr_after);
  894. mHttpLargeOptions = DEFAULT_HTTP_OPTIONS;
  895. mHttpLargeOptions->setTransferTimeout(LARGE_MESH_XFER_TIMEOUT);
  896. mHttpLargeOptions->setUseRetryAfter(use_retyr_after);
  897. mHttpHeaders = DEFAULT_HTTP_HEADERS;
  898. mHttpHeaders->append(HTTP_OUT_HEADER_ACCEPT, HTTP_CONTENT_VND_LL_MESH);
  899. LLAppCoreHttp& app_core_http= gAppViewerp->getAppCoreHttp();
  900. mHttpPolicyClass = app_core_http.getPolicy(LLAppCoreHttp::AP_MESH2);
  901. mHttpLegacyPolicyClass = app_core_http.getPolicy(LLAppCoreHttp::AP_MESH1);
  902. mHttpLargePolicyClass =
  903. app_core_http.getPolicy(LLAppCoreHttp::AP_LARGE_MESH);
  904. }
  905. LLMeshRepoThread::~LLMeshRepoThread()
  906. {
  907. llinfos << "Small GETs issued: " << LLMeshRepository::sHTTPRequestCount
  908. << " - Large GETs issued: "
  909. << LLMeshRepository::sHTTPLargeRequestCount
  910. << " - Max lock holdoffs: " << LLMeshRepository::sMaxLockHoldoffs
  911. << " - Total mesh headers stored: " << mMeshHeaders.size()
  912. << llendl;
  913. mHttpRequestSet.clear();
  914. mHttpHeaders.reset();
  915. for (skin_info_list_t::iterator it = mSkinInfos.begin(),
  916. end = mSkinInfos.end();
  917. it != end; ++it)
  918. {
  919. delete *it;
  920. }
  921. mSkinInfos.clear();
  922. for (decomp_list_t::iterator it = mDecompositions.begin(),
  923. end = mDecompositions.end();
  924. it != end; ++it)
  925. {
  926. delete *it;
  927. }
  928. mDecompositions.clear();
  929. delete mHttpRequest;
  930. mHttpRequest = NULL;
  931. for (auto it = mMeshHeaders.begin(), end = mMeshHeaders.end(); it != end;
  932. ++it)
  933. {
  934. delete it->second;
  935. }
  936. mMeshHeaders.clear();
  937. }
  938. // Note: this method is written in such a way that it holds mMutex for the
  939. // shortest possible amount of time. HB
  940. void LLMeshRepoThread::insertRequests(base_requests_set_t& dest,
  941. base_requests_set_t& remaining,
  942. base_requests_set_t& incomplete)
  943. {
  944. if (!remaining.empty())
  945. {
  946. if (incomplete.empty())
  947. {
  948. incomplete.swap(remaining); // Fastest !
  949. }
  950. else
  951. {
  952. // No range-emplacing: iterate so to use emplace()
  953. for (base_requests_set_t::iterator it = remaining.begin(),
  954. end = remaining.end();
  955. it != end; ++it)
  956. {
  957. incomplete.emplace(*it);
  958. }
  959. remaining.clear();
  960. }
  961. }
  962. if (incomplete.empty())
  963. {
  964. return;
  965. }
  966. mMutex.lock();
  967. if (dest.empty())
  968. {
  969. dest.swap(incomplete); // Fastest !
  970. mMutex.unlock();
  971. }
  972. else
  973. {
  974. // No range-emplacing: iterate so to use emplace()
  975. for (base_requests_set_t::iterator it = incomplete.begin(),
  976. end = incomplete.end();
  977. it != end; ++it)
  978. {
  979. dest.emplace(*it);
  980. }
  981. mMutex.unlock();
  982. incomplete.clear();
  983. }
  984. }
  985. void LLMeshRepoThread::run()
  986. {
  987. if (LLConvexDecomposition::initThread() != LLCD_OK)
  988. {
  989. llwarns << "Unable to start the convex decomposition thread" << llendl;
  990. }
  991. lod_req_queue_t incomplete_lod, lodq_copy;
  992. header_req_queue_t incomplete_hdr, hdrq_copy;
  993. base_requests_set_t incomplete_req, requests_copy;
  994. bool can_req;
  995. while (!LLApp::isExiting())
  996. {
  997. // *TODO: Revise sleep/wake strategy and try to move away from polling
  998. // operations in this thread. We can sleep this thread hard when:
  999. // * All Http requests are serviced
  1000. // * LOD request queue empty
  1001. // * Header request queue empty
  1002. // * Skin info request queue empty
  1003. // * Decomposition request queue empty
  1004. // * Physics shape request queue empty
  1005. // We wake the thread when any of the above become untrue. Will likely
  1006. // need a correctly-implemented condition variable to do this. On the
  1007. // other hand, this may actually be an effective and efficient scheme.
  1008. mSignal.wait();
  1009. if (LLApp::isExiting())
  1010. {
  1011. break;
  1012. }
  1013. {
  1014. LL_TRACY_TIMER(TRC_MESH_THREAD_UDPATE);
  1015. if (!mHttpRequestSet.empty())
  1016. {
  1017. // Dispatch all HttpHandler notifications
  1018. mHttpRequest->update(0L);
  1019. }
  1020. // Stats data update
  1021. sRequestWaterLevel = mHttpRequestSet.size();
  1022. can_req = sRequestWaterLevel < sRequestHighWater;
  1023. }
  1024. // NOTE: order of queue processing intentionally favors skin requests
  1025. // over LOD requests, so to avoid as much as possible the "floating
  1026. // body parts" during rigged meshes rezzing. HB
  1027. if (can_req && !mSkinRequests.empty())
  1028. {
  1029. LL_TRACY_TIMER(TRC_MESH_THREAD_SKIN);
  1030. // Swap the container with an empty local copy to avoid locking at
  1031. // each iteration and slowing down the main thread as a result. HB
  1032. mMutex.lock();
  1033. requests_copy.swap(mSkinRequests);
  1034. mMutex.unlock();
  1035. do
  1036. {
  1037. base_requests_set_t::iterator iter = requests_copy.begin();
  1038. UUIDBasedRequest req = *iter;
  1039. if (req.isDelayed())
  1040. {
  1041. incomplete_req.insert(req);
  1042. }
  1043. else
  1044. {
  1045. bool can_retry = req.canRetry();
  1046. if (!fetchMeshSkinInfo(req.mId, can_retry))
  1047. {
  1048. if (can_retry)
  1049. {
  1050. req.updateTime();
  1051. incomplete_req.insert(req);
  1052. }
  1053. else
  1054. {
  1055. // Note: at this point, the skin UUID has already
  1056. // been added to mUnavailableSkins during the above
  1057. // fetchMeshSkinInfo() call. HB
  1058. llwarns << "Skin request failed for " << req.mId
  1059. << llendl;
  1060. }
  1061. }
  1062. }
  1063. can_req = (S32)mHttpRequestSet.size() < sRequestHighWater;
  1064. requests_copy.erase(iter);
  1065. }
  1066. while (can_req && !requests_copy.empty());
  1067. // Note: this always leaves requests_copy and incomplete_req empty
  1068. insertRequests(mSkinRequests, requests_copy, incomplete_req);
  1069. }
  1070. // NOTE: order of queue processing intentionally favors LOD requests
  1071. // over header requests
  1072. if (can_req && !mLODReqQ.empty())
  1073. {
  1074. LL_TRACY_TIMER(TRC_MESH_THREAD_LOD);
  1075. // Swap the container with an empty local copy to avoid locking at
  1076. // each iteration and slowing down the main thread as a result. HB
  1077. mMutex.lock();
  1078. lodq_copy.swap(mLODReqQ);
  1079. mMutex.unlock();
  1080. do
  1081. {
  1082. LODRequest& req = lodq_copy.front();
  1083. if (req.isDelayed())
  1084. {
  1085. // Still need to wait a bit before retrying
  1086. incomplete_lod.emplace_back(req);
  1087. }
  1088. else
  1089. {
  1090. --LLMeshRepository::sLODProcessing;
  1091. bool can_retry = req.canRetry();
  1092. if (!fetchMeshLOD(req.mMeshParams, req.mLOD, can_retry))
  1093. {
  1094. if (can_retry)
  1095. {
  1096. // Failed, resubmit
  1097. req.updateTime();
  1098. incomplete_lod.emplace_back(req);
  1099. ++LLMeshRepository::sLODProcessing;
  1100. }
  1101. else
  1102. {
  1103. // Note: at this point, the request has already
  1104. // been added to mUnavailableLODs during the above
  1105. // fetchMeshLOD() call. HB
  1106. llwarns << "Failed to load " << req.mMeshParams
  1107. << ", skipping." << llendl;
  1108. }
  1109. }
  1110. }
  1111. lodq_copy.pop_front();
  1112. can_req = (S32)mHttpRequestSet.size() < sRequestHighWater;
  1113. }
  1114. while (can_req && !lodq_copy.empty());
  1115. // If we could not process all the requests; push them into the
  1116. // incomplete queue.
  1117. if (!lodq_copy.empty())
  1118. {
  1119. if (incomplete_lod.empty())
  1120. {
  1121. incomplete_lod.swap(lodq_copy); // Fastest !
  1122. }
  1123. else
  1124. {
  1125. // Note: there is no range-emplacing for deque, so let's
  1126. // iterate to emplace_front()
  1127. for (lod_req_queue_t::reverse_iterator
  1128. rit = lodq_copy.rend(),
  1129. begin = lodq_copy.rbegin();
  1130. rit != begin; --rit)
  1131. {
  1132. incomplete_lod.emplace_front(*rit);
  1133. }
  1134. lodq_copy.clear();
  1135. }
  1136. }
  1137. if (!incomplete_lod.empty())
  1138. {
  1139. mMutex.lock();
  1140. if (mLODReqQ.empty())
  1141. {
  1142. mLODReqQ.swap(incomplete_lod); // Fastest !
  1143. mMutex.unlock();
  1144. }
  1145. else
  1146. {
  1147. // Note: there is no range-emplacing for deque, so let's
  1148. // iterate to emplace_front()
  1149. for (lod_req_queue_t::reverse_iterator
  1150. rit = incomplete_lod.rend(),
  1151. begin = incomplete_lod.rbegin();
  1152. rit != begin; --rit)
  1153. {
  1154. mLODReqQ.emplace_front(*rit);
  1155. }
  1156. mMutex.unlock();
  1157. incomplete_lod.clear();
  1158. }
  1159. }
  1160. }
  1161. if (can_req && !mHeaderReqQ.empty())
  1162. {
  1163. LL_TRACY_TIMER(TRC_MESH_THREAD_HEADER);
  1164. // Swap the container with an empty local copy to avoid locking at
  1165. // each iteration and slowing down the main thread as a result. HB
  1166. mMutex.lock();
  1167. hdrq_copy.swap(mHeaderReqQ);
  1168. mMutex.unlock();
  1169. do
  1170. {
  1171. HeaderRequest& req = hdrq_copy.front();
  1172. if (req.isDelayed())
  1173. {
  1174. // Still need to wait a bit before retrying
  1175. incomplete_hdr.emplace_back(req);
  1176. }
  1177. else
  1178. {
  1179. bool can_retry = req.canRetry();
  1180. if (!fetchMeshHeader(req.mMeshParams, can_retry))
  1181. {
  1182. if (can_retry)
  1183. {
  1184. // Failed, resubmit
  1185. req.updateTime();
  1186. incomplete_hdr.emplace_back(req);
  1187. }
  1188. else
  1189. {
  1190. llwarns << "Failed to load header "
  1191. << req.mMeshParams << ", skipping."
  1192. << llendl;
  1193. }
  1194. }
  1195. }
  1196. hdrq_copy.pop_front();
  1197. can_req = (S32)mHttpRequestSet.size() < sRequestHighWater;
  1198. }
  1199. while (can_req && !hdrq_copy.empty());
  1200. // If we could not process all the requests; push them into the
  1201. // incomplete queue.
  1202. if (!hdrq_copy.empty())
  1203. {
  1204. if (incomplete_hdr.empty())
  1205. {
  1206. incomplete_hdr.swap(hdrq_copy); // Fastest !
  1207. }
  1208. else
  1209. {
  1210. // Note: there is no range-emplacing for deque, so let's
  1211. // iterate to emplace_front()
  1212. for (header_req_queue_t::reverse_iterator
  1213. rit = hdrq_copy.rend(),
  1214. begin = hdrq_copy.rbegin();
  1215. rit != begin; --rit)
  1216. {
  1217. incomplete_hdr.emplace_front(*rit);
  1218. }
  1219. hdrq_copy.clear();
  1220. }
  1221. }
  1222. if (!incomplete_hdr.empty())
  1223. {
  1224. mMutex.lock();
  1225. if (mHeaderReqQ.empty())
  1226. {
  1227. mHeaderReqQ.swap(incomplete_hdr); // Fastest !
  1228. mMutex.unlock();
  1229. }
  1230. else
  1231. {
  1232. // Note: there is no range-emplacing for deque, so let's
  1233. // iterate to emplace_front()
  1234. for (header_req_queue_t::reverse_iterator
  1235. rit = incomplete_hdr.rend(),
  1236. begin = incomplete_hdr.rbegin();
  1237. rit != begin; --rit)
  1238. {
  1239. mHeaderReqQ.emplace_front(*rit);
  1240. }
  1241. mMutex.unlock();
  1242. incomplete_hdr.clear();
  1243. }
  1244. }
  1245. }
  1246. // For the final two request sets, similar goal to above but slightly
  1247. // different queue structures. Stay off the mutex when performing long
  1248. // duration actions.
  1249. if (can_req && !mDecompositionRequests.empty())
  1250. {
  1251. LL_TRACY_TIMER(TRC_MESH_THREAD_DECOMP);
  1252. // Swap the container with an empty local copy to avoid locking at
  1253. // each iteration and slowing down the main thread as a result. HB
  1254. mMutex.lock();
  1255. requests_copy.swap(mDecompositionRequests);
  1256. mMutex.unlock();
  1257. do
  1258. {
  1259. base_requests_set_t::iterator iter = requests_copy.begin();
  1260. UUIDBasedRequest req = *iter;
  1261. if (req.isDelayed())
  1262. {
  1263. incomplete_req.insert(req);
  1264. }
  1265. else if (!fetchMeshDecomposition(req.mId))
  1266. {
  1267. if (req.canRetry())
  1268. {
  1269. req.updateTime();
  1270. incomplete_req.insert(req);
  1271. }
  1272. else
  1273. {
  1274. llwarns << "Decomp request failed for " << req.mId
  1275. << llendl;
  1276. }
  1277. }
  1278. requests_copy.erase(iter);
  1279. can_req = (S32)mHttpRequestSet.size() < sRequestHighWater;
  1280. }
  1281. while (can_req && !requests_copy.empty());
  1282. // Note: this always leaves requests_copy and incomplete_req empty
  1283. insertRequests(mDecompositionRequests, requests_copy,
  1284. incomplete_req);
  1285. }
  1286. if (can_req && !mPhysicsShapeRequests.empty())
  1287. {
  1288. LL_TRACY_TIMER(TRC_MESH_THREAD_PHYSICS);
  1289. // Swap the container with an empty local copy to avoid locking at
  1290. // each iteration and slowing down the main thread as a result. HB
  1291. mMutex.lock();
  1292. requests_copy.swap(mPhysicsShapeRequests);
  1293. mMutex.unlock();
  1294. do
  1295. {
  1296. base_requests_set_t::iterator iter = requests_copy.begin();
  1297. UUIDBasedRequest req = *iter;
  1298. if (req.isDelayed())
  1299. {
  1300. incomplete_req.insert(req);
  1301. }
  1302. else if (!fetchMeshPhysicsShape(req.mId))
  1303. {
  1304. if (req.canRetry())
  1305. {
  1306. req.updateTime();
  1307. incomplete_req.insert(req);
  1308. }
  1309. else
  1310. {
  1311. llwarns << "Physics shape request failed for "
  1312. << req.mId << llendl;
  1313. }
  1314. }
  1315. requests_copy.erase(iter);
  1316. can_req = (S32)mHttpRequestSet.size() < sRequestHighWater;
  1317. }
  1318. while (can_req && !requests_copy.empty());
  1319. // Note: this always leaves requests_copy and incomplete_req empty
  1320. insertRequests(mPhysicsShapeRequests, requests_copy,
  1321. incomplete_req);
  1322. }
  1323. }
  1324. if (mSignal.isLocked())
  1325. {
  1326. // Make sure to let go off the mutex associated with the given signal
  1327. // before shutting down
  1328. mSignal.unlock();
  1329. }
  1330. if (LLConvexDecomposition::quitThread() != LLCD_OK)
  1331. {
  1332. llwarns << "Unable to quit convex decomposition thread" << llendl;
  1333. }
  1334. }
  1335. void LLMeshRepoThread::loadMeshSkinInfo(const LLUUID& mesh_id)
  1336. {
  1337. mSkinRequests.emplace(mesh_id);
  1338. }
  1339. void LLMeshRepoThread::loadMeshDecomposition(const LLUUID& mesh_id)
  1340. {
  1341. mDecompositionRequests.emplace(mesh_id);
  1342. }
  1343. void LLMeshRepoThread::loadMeshPhysicsShape(const LLUUID& mesh_id)
  1344. {
  1345. mPhysicsShapeRequests.emplace(mesh_id);
  1346. }
  1347. void LLMeshRepoThread::lockAndLoadMeshLOD(const LLVolumeParams& mesh_params,
  1348. S32 lod)
  1349. {
  1350. if (!LLAppViewer::isExiting())
  1351. {
  1352. // Could be called from any thread
  1353. mMutex.lock();
  1354. loadMeshLOD(mesh_params, lod);
  1355. mMutex.unlock();
  1356. }
  1357. }
  1358. void LLMeshRepoThread::loadMeshLOD(const LLVolumeParams& mesh_params, S32 lod)
  1359. {
  1360. const LLUUID& mesh_id = mesh_params.getSculptID();
  1361. mHeaderMutex.lock();
  1362. bool exists = mMeshHeaders.count(mesh_id) > 0;
  1363. mHeaderMutex.unlock();
  1364. if (exists)
  1365. {
  1366. // If we have the header, request LOD byte range
  1367. mLODReqQ.emplace_back(mesh_params, lod);
  1368. ++LLMeshRepository::sLODProcessing;
  1369. }
  1370. else
  1371. {
  1372. HeaderRequest req(mesh_params);
  1373. pending_lod_map_t::iterator pending = mPendingLOD.find(mesh_id);
  1374. if (pending != mPendingLOD.end())
  1375. {
  1376. // Append this lod request to existing header request
  1377. pending->second.push_back(lod);
  1378. llassert(pending->second.size() <= LLModel::NUM_LODS);
  1379. }
  1380. else
  1381. {
  1382. // If no header request is pending, fetch header
  1383. mHeaderReqQ.emplace_back(req);
  1384. mPendingLOD[mesh_id].push_back(lod);
  1385. }
  1386. }
  1387. }
  1388. // Constructs a capability URL for the mesh.
  1389. // Mutex: acquires mMutex
  1390. std::string LLMeshRepoThread::constructUrl(const LLUUID& mesh_id, U32* version)
  1391. {
  1392. mMutex.lock();
  1393. const std::string& http_url = mGetMeshCapability;
  1394. *version = mGetMeshVersion;
  1395. mMutex.unlock();
  1396. if (http_url.empty())
  1397. {
  1398. llwarns << "Current region does not have GetMesh capability, cannot fetch mesh Id: "
  1399. << mesh_id << llendl;
  1400. return "";
  1401. }
  1402. return http_url + "?mesh_id=" + mesh_id.asString();
  1403. }
  1404. // Issue an HTTP GET request with byte range using the right policy class.
  1405. // Large requests go to the large request class. If the current region supports
  1406. // GetMesh2, we prefer that for smaller requests otherwise we try to use the
  1407. // traditional GetMesh capability and connection concurrency.
  1408. //
  1409. // @return Valid handle or LLCORE_HTTP_HANDLE_INVALID.
  1410. // If the latter, actual status is found in mHttpStatus member which
  1411. // is valid until the next call to this method.
  1412. //
  1413. // Thread: repo
  1414. LLCore::HttpHandle LLMeshRepoThread::getByteRange(const std::string& url,
  1415. U32 cap_version,
  1416. size_t offset, size_t len,
  1417. const LLCore::HttpHandler::ptr_t& handler)
  1418. {
  1419. static LLCachedControl<bool> disable_range_req(gSavedSettings,
  1420. "HttpRangeRequestsDisable");
  1421. size_t req_offset = disable_range_req ? 0 : offset;
  1422. size_t req_len = disable_range_req ? 0 : len;
  1423. LLCore::HttpHandle handle = LLCORE_HTTP_HANDLE_INVALID;
  1424. if (len < LARGE_MESH_FETCH_THRESHOLD)
  1425. {
  1426. handle = mHttpRequest->requestGetByteRange(cap_version == 2 ? mHttpPolicyClass
  1427. : mHttpLegacyPolicyClass,
  1428. url, req_offset, req_len,
  1429. mHttpOptions, mHttpHeaders,
  1430. handler);
  1431. if (handle != LLCORE_HTTP_HANDLE_INVALID)
  1432. {
  1433. ++LLMeshRepository::sHTTPRequestCount;
  1434. }
  1435. }
  1436. else
  1437. {
  1438. handle = mHttpRequest->requestGetByteRange(mHttpLargePolicyClass, url,
  1439. req_offset, req_len,
  1440. mHttpLargeOptions,
  1441. mHttpHeaders, handler);
  1442. if (handle != LLCORE_HTTP_HANDLE_INVALID)
  1443. {
  1444. ++LLMeshRepository::sHTTPLargeRequestCount;
  1445. }
  1446. }
  1447. if (handle != LLCORE_HTTP_HANDLE_INVALID)
  1448. {
  1449. // Something went wrong, capture the error code for caller.
  1450. mHttpStatus = mHttpRequest->getStatus();
  1451. }
  1452. return handle;
  1453. }
  1454. bool LLMeshRepoThread::fetchMeshSkinInfo(const LLUUID& mesh_id, bool can_retry)
  1455. {
  1456. mHeaderMutex.lock();
  1457. mesh_header_map_t::iterator iter = mMeshHeaders.find(mesh_id);
  1458. if (iter == mMeshHeaders.end())
  1459. {
  1460. // We have no header info for this mesh, do nothing
  1461. mHeaderMutex.unlock();
  1462. return false;
  1463. }
  1464. LLMeshHeader* header = iter->second;
  1465. ++LLMeshRepository::sMeshRequestCount;
  1466. if (!header->mHeaderSize)
  1467. {
  1468. mHeaderMutex.unlock();
  1469. // Early out was not hit, effectively fetched
  1470. return true;
  1471. }
  1472. bool valid = header->mValid;
  1473. S32 offset = header->mSkinOffset;
  1474. S32 size = header->mSkinSize;
  1475. mHeaderMutex.unlock();
  1476. if (valid && offset >= 0 && size > 0)
  1477. {
  1478. // Check cache for mesh skin info
  1479. LLFileSystem file(mesh_id);
  1480. if (file.getSize() >= offset + size)
  1481. {
  1482. U8* buffer = new(std::nothrow) U8[size];
  1483. if (!buffer)
  1484. {
  1485. LLMemory::allocationFailed(size);
  1486. llwarns << "Could not allocate enough memory. Aborted."
  1487. << llendl;
  1488. return false;
  1489. }
  1490. LLMeshRepository::sCacheBytesRead += size;
  1491. ++LLMeshRepository::sCacheReads;
  1492. file.seek(offset);
  1493. file.read(buffer, size);
  1494. // Make sure the buffer is not all zeros by checking the first 128
  1495. // bytes (reserved block but not written)
  1496. bool zero = true;
  1497. for (S32 i = 0, count = llmin(size, 128); i < count && zero; ++i)
  1498. {
  1499. zero = buffer[i] == 0;
  1500. }
  1501. if (!zero)
  1502. {
  1503. // Attempt to parse
  1504. if (skinInfoReceived(mesh_id, buffer, size))
  1505. {
  1506. delete[] buffer;
  1507. return true;
  1508. }
  1509. }
  1510. delete[] buffer;
  1511. }
  1512. // Reading from cache failed for whatever reason, fetch from server
  1513. U32 cap_version = 2;
  1514. std::string http_url = constructUrl(mesh_id, &cap_version);
  1515. if (http_url.empty())
  1516. {
  1517. mMutex.lock();
  1518. mUnavailableSkins.emplace_back(mesh_id);
  1519. mMutex.unlock();
  1520. }
  1521. else
  1522. {
  1523. LLMeshHandlerBase::ptr_t handler(new LLMeshSkinInfoHandler(mesh_id,
  1524. offset,
  1525. size));
  1526. LLCore::HttpHandle handle =
  1527. getByteRange(http_url, cap_version, offset, size, handler);
  1528. if (handle == LLCORE_HTTP_HANDLE_INVALID)
  1529. {
  1530. llwarns << "HTTP GET request failed for skin info on mesh "
  1531. << mID << ". Reason: " << mHttpStatus.toString()
  1532. << " (" << mHttpStatus.toTerseString() << ")"
  1533. << llendl;
  1534. if (!can_retry)
  1535. {
  1536. mMutex.lock();
  1537. mUnavailableSkins.emplace_back(mesh_id);
  1538. mMutex.unlock();
  1539. }
  1540. return false;
  1541. }
  1542. handler->mHttpHandle = handle;
  1543. // Do not use handler after this line !
  1544. mHttpRequestSet.emplace(std::move(handler));
  1545. }
  1546. }
  1547. return true;
  1548. }
  1549. bool LLMeshRepoThread::fetchMeshDecomposition(const LLUUID& mesh_id)
  1550. {
  1551. mHeaderMutex.lock();
  1552. mesh_header_map_t::iterator iter = mMeshHeaders.find(mesh_id);
  1553. if (iter == mMeshHeaders.end())
  1554. {
  1555. // We have no header info for this mesh, do nothing
  1556. mHeaderMutex.unlock();
  1557. return false;
  1558. }
  1559. LLMeshHeader* header = iter->second;
  1560. ++LLMeshRepository::sMeshRequestCount;
  1561. if (!header->mHeaderSize)
  1562. {
  1563. mHeaderMutex.unlock();
  1564. // Early out was not hit, effectively fetched
  1565. return true;
  1566. }
  1567. bool valid = header->mValid;
  1568. S32 offset = header->mPhysicsConvexOffset;
  1569. S32 size = header->mPhysicsConvexSize;
  1570. mHeaderMutex.unlock();
  1571. if (valid && offset >= 0 && size > 0)
  1572. {
  1573. // Check cache for mesh skin info
  1574. LLFileSystem file(mesh_id);
  1575. if (file.getSize() >= offset + size)
  1576. {
  1577. U8* buffer = new(std::nothrow) U8[size];
  1578. if (!buffer)
  1579. {
  1580. LLMemory::allocationFailed(size);
  1581. llwarns << "Could not allocate enough memory. Aborted."
  1582. << llendl;
  1583. return false;
  1584. }
  1585. LLMeshRepository::sCacheBytesRead += size;
  1586. ++LLMeshRepository::sCacheReads;
  1587. file.seek(offset);
  1588. file.read(buffer, size);
  1589. // Make sure the buffer is not all zeros by checking the first 128
  1590. // bytes (reserved block but not written)
  1591. bool zero = true;
  1592. for (S32 i = 0, count = llmin(size, 128); i < count && zero; ++i)
  1593. {
  1594. zero = buffer[i] == 0;
  1595. }
  1596. if (!zero)
  1597. {
  1598. // Attempt to parse
  1599. if (decompositionReceived(mesh_id, buffer, size))
  1600. {
  1601. delete[] buffer;
  1602. return true;
  1603. }
  1604. }
  1605. delete[] buffer;
  1606. }
  1607. // Reading from cache failed for whatever reason, fetch from sim
  1608. U32 cap_version = 2;
  1609. std::string http_url = constructUrl(mesh_id, &cap_version);
  1610. if (!http_url.empty())
  1611. {
  1612. LLMeshHandlerBase::ptr_t
  1613. handler(new LLMeshDecompositionHandler(mesh_id, offset, size));
  1614. LLCore::HttpHandle handle =
  1615. getByteRange(http_url, cap_version, offset, size, handler);
  1616. if (handle == LLCORE_HTTP_HANDLE_INVALID)
  1617. {
  1618. llwarns << "HTTP GET request failed for decomposition mesh "
  1619. << mID << " - Reason: " << mHttpStatus.toString()
  1620. << " (" << mHttpStatus.toTerseString() << ")"
  1621. << llendl;
  1622. return false;
  1623. }
  1624. handler->mHttpHandle = handle;
  1625. // Do not use handler after this line !
  1626. mHttpRequestSet.emplace(std::move(handler));
  1627. }
  1628. }
  1629. return true;
  1630. }
  1631. bool LLMeshRepoThread::fetchMeshPhysicsShape(const LLUUID& mesh_id)
  1632. {
  1633. mHeaderMutex.lock();
  1634. mesh_header_map_t::iterator iter = mMeshHeaders.find(mesh_id);
  1635. if (iter == mMeshHeaders.end())
  1636. {
  1637. // We have no header info for this mesh, do nothing
  1638. mHeaderMutex.unlock();
  1639. return false;
  1640. }
  1641. LLMeshHeader* header = iter->second;
  1642. ++LLMeshRepository::sMeshRequestCount;
  1643. if (!header->mHeaderSize)
  1644. {
  1645. mHeaderMutex.unlock();
  1646. // Early out was not hit, effectively fetched
  1647. return true;
  1648. }
  1649. bool valid = header->mValid;
  1650. S32 offset = header->mPhysicsMeshOffset;
  1651. S32 size = header->mPhysicsMeshSize;
  1652. mHeaderMutex.unlock();
  1653. if (valid && offset >= 0 && size > 0)
  1654. {
  1655. // Check cache for mesh physics shape info
  1656. LLFileSystem file(mesh_id);
  1657. if (file.getSize() >= offset + size)
  1658. {
  1659. U8* buffer = new(std::nothrow) U8[size];
  1660. if (!buffer)
  1661. {
  1662. LLMemory::allocationFailed(size);
  1663. llwarns << "Could not allocate enough memory. Aborted."
  1664. << llendl;
  1665. return false;
  1666. }
  1667. LLMeshRepository::sCacheBytesRead += size;
  1668. ++LLMeshRepository::sCacheReads;
  1669. file.seek(offset);
  1670. file.read(buffer, size);
  1671. // Make sure the buffer is not all zeros by checking the first 128
  1672. // bytes (reserved block but not written)
  1673. bool zero = true;
  1674. for (S32 i = 0, count = llmin(size, 128); i < count && zero; ++i)
  1675. {
  1676. zero = buffer[i] == 0;
  1677. }
  1678. if (!zero)
  1679. {
  1680. // Attempt to parse
  1681. if (physicsShapeReceived(mesh_id, buffer, size))
  1682. {
  1683. delete[] buffer;
  1684. return true;
  1685. }
  1686. }
  1687. delete[] buffer;
  1688. }
  1689. // Reading from cache failed for whatever reason, fetch from sim
  1690. U32 cap_version = 2;
  1691. std::string http_url = constructUrl(mesh_id, &cap_version);
  1692. if (!http_url.empty())
  1693. {
  1694. LLMeshHandlerBase::ptr_t
  1695. handler(new LLMeshPhysicsShapeHandler(mesh_id, offset, size));
  1696. LLCore::HttpHandle handle =
  1697. getByteRange(http_url, cap_version, offset, size, handler);
  1698. if (handle == LLCORE_HTTP_HANDLE_INVALID)
  1699. {
  1700. llwarns << "HTTP GET request failed for physics shape on mesh "
  1701. << mID << " - Reason: " << mHttpStatus.toString()
  1702. << " (" << mHttpStatus.toTerseString() << ")"
  1703. << llendl;
  1704. return false;
  1705. }
  1706. handler->mHttpHandle = handle;
  1707. // Do not use handler after this line !
  1708. mHttpRequestSet.emplace(std::move(handler));
  1709. }
  1710. }
  1711. else
  1712. {
  1713. // No physics shape whatsoever, report back NULL
  1714. physicsShapeReceived(mesh_id, NULL, 0);
  1715. }
  1716. return true;
  1717. }
  1718. // Returns false if failed to get header
  1719. bool LLMeshRepoThread::fetchMeshHeader(const LLVolumeParams& mesh_params,
  1720. bool can_retry)
  1721. {
  1722. ++LLMeshRepository::sMeshRequestCount;
  1723. // Look for mesh in asset in cache
  1724. LLFileSystem file(mesh_params.getSculptID());
  1725. S32 size = file.getSize();
  1726. if (size > 0)
  1727. {
  1728. // NOTE: if the header size is ever more than 4KB, this will break
  1729. U8 buffer[MESH_HEADER_SIZE];
  1730. S32 bytes = llmin(size, MESH_HEADER_SIZE);
  1731. LLMeshRepository::sCacheBytesRead += bytes;
  1732. ++LLMeshRepository::sCacheReads;
  1733. file.read(buffer, bytes);
  1734. if (headerReceived(mesh_params, buffer, bytes))
  1735. {
  1736. // Found mesh in cache
  1737. return true;
  1738. }
  1739. }
  1740. // Either cache entry does not exist or is corrupt, request header from
  1741. // simulator
  1742. U32 cap_version = 2;
  1743. std::string http_url = constructUrl(mesh_params.getSculptID(),
  1744. &cap_version);
  1745. if (!http_url.empty())
  1746. {
  1747. // Grab first 4KB if we are going to bother with a fetch. Cache will
  1748. // prevent future fetches if a full mesh fits within the first 4KB
  1749. // NOTE: this will break of headers ever exceed 4KB
  1750. LLMeshHandlerBase::ptr_t
  1751. handler(new LLMeshHeaderHandler(mesh_params, 0, MESH_HEADER_SIZE));
  1752. LLCore::HttpHandle handle =
  1753. getByteRange(http_url, cap_version, 0, MESH_HEADER_SIZE, handler);
  1754. if (handle == LLCORE_HTTP_HANDLE_INVALID)
  1755. {
  1756. llwarns << "HTTP GET request failed for mesh header " << mID
  1757. << " - Reason: " << mHttpStatus.toString() << " ("
  1758. << mHttpStatus.toTerseString() << ")" << llendl;
  1759. return false;
  1760. }
  1761. if (can_retry)
  1762. {
  1763. handler->mHttpHandle = handle;
  1764. // Do not use handler after this line !
  1765. mHttpRequestSet.emplace(std::move(handler));
  1766. }
  1767. }
  1768. return true;
  1769. }
  1770. // Returns false if failed to get mesh lod.
  1771. bool LLMeshRepoThread::fetchMeshLOD(const LLVolumeParams& mesh_params, S32 lod,
  1772. bool can_retry)
  1773. {
  1774. if (lod < 0)
  1775. {
  1776. return false;
  1777. }
  1778. mHeaderMutex.lock();
  1779. ++LLMeshRepository::sMeshRequestCount;
  1780. const LLUUID& mesh_id = mesh_params.getSculptID();
  1781. mesh_header_map_t::iterator iter = mMeshHeaders.find(mesh_id);
  1782. if (iter == mMeshHeaders.end())
  1783. {
  1784. // We have no header info for this mesh, do nothing
  1785. mHeaderMutex.unlock();
  1786. return false;
  1787. }
  1788. LLMeshHeader* header = iter->second;
  1789. if (!header->mHeaderSize)
  1790. {
  1791. mHeaderMutex.unlock();
  1792. // Early out was not hit, effectively fetched
  1793. return true;
  1794. }
  1795. bool valid = header->mValid;
  1796. S32 offset = header->mLodOffset[lod];
  1797. S32 size = header->mLodSize[lod];
  1798. mHeaderMutex.unlock();
  1799. bool available_lod = valid && offset >= 0 && size > 0;
  1800. if (available_lod)
  1801. {
  1802. // Check cache for mesh asset
  1803. LLFileSystem file(mesh_id);
  1804. if (file.getSize() >= offset + size)
  1805. {
  1806. U8* buffer = new(std::nothrow) U8[size];
  1807. if (!buffer)
  1808. {
  1809. LLMemory::allocationFailed(size);
  1810. llwarns << "Could not allocate enough memory. Aborted."
  1811. << llendl;
  1812. return false;
  1813. }
  1814. LLMeshRepository::sCacheBytesRead += size;
  1815. ++LLMeshRepository::sCacheReads;
  1816. file.seek(offset);
  1817. file.read(buffer, size);
  1818. // Make sure the buffer is not all zeros by checking the first 128
  1819. // bytes (reserved block but not written)
  1820. bool zero = true;
  1821. for (S32 i = 0, count = llmin(size, 128); i < count && zero; ++i)
  1822. {
  1823. zero = buffer[i] == 0;
  1824. }
  1825. if (!zero)
  1826. {
  1827. // Attempt to parse
  1828. if (lodReceived(mesh_params, lod, buffer, size))
  1829. {
  1830. delete[] buffer;
  1831. return true;
  1832. }
  1833. }
  1834. delete[] buffer;
  1835. }
  1836. // Reading from cache failed for whatever reason, fetch from sim
  1837. U32 cap_version = 2;
  1838. std::string http_url = constructUrl(mesh_id, &cap_version);
  1839. available_lod = !http_url.empty();
  1840. if (available_lod)
  1841. {
  1842. LLMeshHandlerBase::ptr_t handler(new LLMeshLODHandler(mesh_params,
  1843. lod, offset,
  1844. size));
  1845. LLCore::HttpHandle handle =
  1846. getByteRange(http_url, cap_version, offset, size, handler);
  1847. if (handle == LLCORE_HTTP_HANDLE_INVALID)
  1848. {
  1849. llwarns << "HTTP GET request failed for LOD on mesh " << mID
  1850. << " - Reason: " << mHttpStatus.toString() << " ("
  1851. << mHttpStatus.toTerseString() << ")" << llendl;
  1852. return false;
  1853. }
  1854. if (can_retry)
  1855. {
  1856. handler->mHttpHandle = handle;
  1857. // Do not use handler after this line !
  1858. mHttpRequestSet.emplace(std::move(handler));
  1859. }
  1860. else
  1861. {
  1862. available_lod = false;
  1863. }
  1864. }
  1865. }
  1866. if (!available_lod)
  1867. {
  1868. mMutex.lock();
  1869. mUnavailableLODs.emplace_back(mesh_params, lod);
  1870. mMutex.unlock();
  1871. }
  1872. return true;
  1873. }
  1874. bool LLMeshRepoThread::headerReceived(const LLVolumeParams& mesh_params,
  1875. U8* data, S32 data_size)
  1876. {
  1877. const LLUUID& mesh_id = mesh_params.getSculptID();
  1878. LLSD header;
  1879. U32 header_size = 0;
  1880. if (data && data_size > 0)
  1881. {
  1882. static char deprecated_header[] = "<? LLSD/Binary ?>";
  1883. static size_t deprecated_header_size = strlen(deprecated_header);
  1884. if (!strncmp((char*)data, deprecated_header, deprecated_header_size))
  1885. {
  1886. data += deprecated_header_size;
  1887. data_size -= deprecated_header_size;
  1888. }
  1889. boost::iostreams::stream<boost::iostreams::array_source>
  1890. stream((char*)data, data_size);
  1891. if (!LLSDSerialize::fromBinary(header, stream, data_size))
  1892. {
  1893. llwarns << "Parse error for header of mesh " << mesh_id
  1894. << ". Not a valid mesh asset !" << llendl;
  1895. return false;
  1896. }
  1897. #if 0 // OpenSIM servers do not serve a 'version' for meshes...
  1898. if (!header.isMap() || !header.has("version"))
  1899. #else
  1900. if (!header.isMap())
  1901. #endif
  1902. {
  1903. llwarns << "Mesh header is invalid for mesh: " << mesh_id
  1904. << llendl;
  1905. return false;
  1906. }
  1907. header_size += stream.tellg();
  1908. }
  1909. else
  1910. {
  1911. llwarns << "Marking header for mesh " << mesh_id
  1912. << " as non-existent, will not retry." << llendl;
  1913. header["404"] = 1;
  1914. }
  1915. mHeaderMutex.lock();
  1916. LLMeshHeader* mesh_header;
  1917. mesh_header_map_t::iterator it = mMeshHeaders.find(mesh_id);
  1918. if (it == mMeshHeaders.end())
  1919. {
  1920. mesh_header = new LLMeshHeader();
  1921. mMeshHeaders.emplace(mesh_id, mesh_header);
  1922. }
  1923. else // This should not happen, but just in case...
  1924. {
  1925. LL_DEBUGS("MeshCost") << "Refreshing mesh header data for mesh Id: "
  1926. << mesh_id << LL_ENDL;
  1927. mesh_header = it->second;
  1928. mesh_header->reset();
  1929. }
  1930. mesh_header->init(header, header_size);
  1931. LLMeshRepository::mesh_costs_map_t::iterator cit =
  1932. gMeshRepo.mCostsMap.find(mesh_id);
  1933. if (cit != gMeshRepo.mCostsMap.end())
  1934. {
  1935. // This should not happen, but just in case...
  1936. LL_DEBUGS("MeshCost") << "Refreshing mesh costs data for mesh Id: "
  1937. << mesh_id << LL_ENDL;
  1938. cit->second->init(header);
  1939. }
  1940. mHeaderMutex.unlock();
  1941. // Make sure only one thread access mPendingLOD at the same time:
  1942. mMutex.lock();
  1943. // Check for pending requests
  1944. pending_lod_map_t::iterator iter = mPendingLOD.find(mesh_id);
  1945. if (iter != mPendingLOD.end())
  1946. {
  1947. for (U32 i = 0; i < iter->second.size(); ++i)
  1948. {
  1949. mLODReqQ.emplace_back(mesh_params, iter->second[i]);
  1950. ++LLMeshRepository::sLODProcessing;
  1951. }
  1952. mPendingLOD.erase(iter);
  1953. }
  1954. mMutex.unlock();
  1955. return true;
  1956. }
  1957. // IMPORTANT: must be called with mHeaderMutex locked !
  1958. LLMeshHeader* LLMeshRepoThread::getMeshHeader(const LLUUID& mesh_id)
  1959. {
  1960. if (mesh_id.notNull())
  1961. {
  1962. mesh_header_map_t::iterator iter = mMeshHeaders.find(mesh_id);
  1963. if (iter != mMeshHeaders.end() && iter->second->mValid)
  1964. {
  1965. return iter->second;
  1966. }
  1967. }
  1968. return NULL;
  1969. }
  1970. bool LLMeshRepoThread::lodReceived(const LLVolumeParams& mesh_params,
  1971. S32 lod, U8* data, S32 data_size)
  1972. {
  1973. LL_DEBUGS("Mesh") << "Processing LOD " << lod << " for mesh Id: "
  1974. << mesh_params.getSculptID() << LL_ENDL;
  1975. if (!data || !data_size)
  1976. {
  1977. llwarns << "No data received for mesh Id: "
  1978. << mesh_params.getSculptID() << " - LOD: " << lod << llendl;
  1979. return false;
  1980. }
  1981. LLPointer<LLVolume> volume =
  1982. new LLVolume(mesh_params,
  1983. LLVolumeLODGroup::getVolumeScaleFromDetail(lod));
  1984. if (volume.notNull() && volume->unpackVolumeFaces(data, data_size))
  1985. {
  1986. if (volume->getNumFaces() > 0)
  1987. {
  1988. mMutex.lock();
  1989. mLoadedMeshes.emplace_back(std::move(volume), mesh_params, lod);
  1990. // NOTE: the std::move() above should ensure 'volume' got already
  1991. // dereferenced (via LLPointer move constructor), but make sure
  1992. // it is (in case the compiler would not obey us and perform a copy
  1993. // instead !) so that the reference counter on the LLPointer is
  1994. // decremented while mLoadedMeshes is still locked... HB
  1995. volume = NULL;
  1996. mMutex.unlock();
  1997. return true;
  1998. }
  1999. }
  2000. return false;
  2001. }
  2002. bool LLMeshRepoThread::skinInfoReceived(const LLUUID& mesh_id, U8* data,
  2003. S32 data_size)
  2004. {
  2005. LLSD skin;
  2006. if (data_size > 0)
  2007. {
  2008. if (!unzip_llsd(skin, data, data_size))
  2009. {
  2010. llwarns << "Mesh skin decompression error." << llendl;
  2011. return false;
  2012. }
  2013. }
  2014. mMutex.lock();
  2015. mSkinInfos.push_back(new LLMeshSkinInfo(skin, mesh_id));
  2016. mMutex.unlock();
  2017. return true;
  2018. }
  2019. bool LLMeshRepoThread::decompositionReceived(const LLUUID& mesh_id, U8* data,
  2020. S32 data_size)
  2021. {
  2022. LLSD decomp;
  2023. if (data_size > 0)
  2024. {
  2025. if (!unzip_llsd(decomp, data, data_size))
  2026. {
  2027. llwarns << "Mesh decomposition decompression error." << llendl;
  2028. return false;
  2029. }
  2030. }
  2031. LLModel::Decomposition* d = new LLModel::Decomposition(decomp, mesh_id);
  2032. mMutex.lock();
  2033. mDecompositions.push_back(d);
  2034. mMutex.unlock();
  2035. return true;
  2036. }
  2037. bool LLMeshRepoThread::physicsShapeReceived(const LLUUID& mesh_id, U8* data,
  2038. S32 data_size)
  2039. {
  2040. LLSD physics_shape;
  2041. LLModel::Decomposition* d = new LLModel::Decomposition();
  2042. d->mMeshID = mesh_id;
  2043. if (!data)
  2044. {
  2045. // No data, no physics shape exists
  2046. d->mPhysicsShapeMesh.clear();
  2047. }
  2048. else
  2049. {
  2050. LLVolumeParams volume_params;
  2051. volume_params.setType(LL_PCODE_PROFILE_SQUARE, LL_PCODE_PATH_LINE);
  2052. volume_params.setSculptID(mesh_id, LL_SCULPT_TYPE_MESH);
  2053. LLPointer<LLVolume> volume = new LLVolume(volume_params, 0);
  2054. if (volume->unpackVolumeFaces(data, data_size))
  2055. {
  2056. d->mPhysicsShapeMesh.clear();
  2057. // Load volume faces into decomposition buffer
  2058. std::vector<LLVector3>& pos = d->mPhysicsShapeMesh.mPositions;
  2059. std::vector<LLVector3>& norm = d->mPhysicsShapeMesh.mNormals;
  2060. for (S32 i = 0, count = volume->getNumVolumeFaces(); i < count;
  2061. i++)
  2062. {
  2063. const LLVolumeFace& face = volume->getVolumeFace(i);
  2064. for (S32 i = 0; i < face.mNumIndices; ++i)
  2065. {
  2066. U16 idx = face.mIndices[i];
  2067. pos.emplace_back(face.mPositions[idx].getF32ptr());
  2068. norm.emplace_back(face.mNormals[idx].getF32ptr());
  2069. }
  2070. }
  2071. }
  2072. }
  2073. mMutex.lock();
  2074. mDecompositions.push_back(d);
  2075. mMutex.unlock();
  2076. return true;
  2077. }
  2078. LLMeshUploadThread::LLMeshUploadThread(instance_list_t& data, LLVector3& scale,
  2079. bool upload_textures, bool upload_skin,
  2080. bool upload_joints,
  2081. bool lock_scale_if_joint_position,
  2082. const std::string& upload_url,
  2083. bool do_upload,
  2084. LLHandle<LLWholeModelFeeObserver> fee_observer,
  2085. LLHandle<LLWholeModelUploadObserver> upload_observer)
  2086. : LLThread("Mesh upload"),
  2087. LLCore::HttpHandler(),
  2088. mDiscarded(false),
  2089. mDoUpload(do_upload),
  2090. mWholeModelUploadURL(upload_url),
  2091. mFeeObserverHandle(fee_observer),
  2092. mUploadObserverHandle(upload_observer)
  2093. {
  2094. mInstanceList = data;
  2095. mUploadTextures = upload_textures;
  2096. mUploadSkin = upload_skin;
  2097. mUploadJoints = upload_joints;
  2098. mLockScaleIfJointPosition = lock_scale_if_joint_position;
  2099. mPendingUploads = 0;
  2100. mFinished = false;
  2101. mOrigin = gAgent.getPositionAgent();
  2102. mHost = gAgent.getRegionHost();
  2103. mOrigin += gAgent.getAtAxis() * scale.length();
  2104. mMeshUploadTimeOut = gSavedSettings.getS32("MeshUploadTimeOut");
  2105. mHttpRequest = new LLCore::HttpRequest;
  2106. mHttpOptions = DEFAULT_HTTP_OPTIONS;
  2107. mHttpOptions->setTransferTimeout(mMeshUploadTimeOut);
  2108. mHttpOptions->setUseRetryAfter(gSavedSettings.getBool("MeshUseHttpRetryAfter"));
  2109. mHttpOptions->setRetries(UPLOAD_RETRY_LIMIT);
  2110. mHttpHeaders = DEFAULT_HTTP_HEADERS;
  2111. mHttpHeaders->append(HTTP_OUT_HEADER_CONTENT_TYPE,
  2112. HTTP_CONTENT_LLSD_XML);
  2113. mHttpPolicyClass =
  2114. gAppViewerp->getAppCoreHttp().getPolicy(LLAppCoreHttp::AP_UPLOADS);
  2115. }
  2116. LLMeshUploadThread::~LLMeshUploadThread()
  2117. {
  2118. delete mHttpRequest;
  2119. mHttpRequest = NULL;
  2120. }
  2121. LLMeshUploadThread::DecompRequest::DecompRequest(LLModel* mdl,
  2122. LLModel* base_model,
  2123. LLMeshUploadThread* thread)
  2124. {
  2125. mStage = "single_hull";
  2126. mModel = mdl;
  2127. mDecompID = &mdl->mDecompID;
  2128. mBaseModel = base_model;
  2129. mThread = thread;
  2130. // Copy out positions and indices
  2131. assignData(mdl);
  2132. mThread->mFinalDecomp = this;
  2133. mThread->mPhysicsComplete = false;
  2134. }
  2135. void LLMeshUploadThread::DecompRequest::completed()
  2136. {
  2137. if (mThread->mFinalDecomp == this)
  2138. {
  2139. mThread->mPhysicsComplete = true;
  2140. }
  2141. llassert(mHull.size() == 1);
  2142. mThread->mHullMap[mBaseModel] = mHull[0];
  2143. LL_DEBUGS("MeshUpload") << "Decomposition request completed." << LL_ENDL;
  2144. }
  2145. // Called in the main thread.
  2146. void LLMeshUploadThread::preStart()
  2147. {
  2148. // Build map of LLModel refs to instances for callbacks
  2149. for (instance_list_t::iterator iter = mInstanceList.begin(),
  2150. end = mInstanceList.end();
  2151. iter != end; ++iter)
  2152. {
  2153. mInstance[iter->mModel].emplace_back(*iter);
  2154. }
  2155. }
  2156. void LLMeshUploadThread::discard()
  2157. {
  2158. mMutex.lock();
  2159. mDiscarded = true;
  2160. mMutex.unlock();
  2161. }
  2162. bool LLMeshUploadThread::isDiscarded()
  2163. {
  2164. mMutex.lock();
  2165. bool discarded = mDiscarded;
  2166. mMutex.unlock();
  2167. return discarded;
  2168. }
  2169. void LLMeshUploadThread::run()
  2170. {
  2171. if (mDoUpload)
  2172. {
  2173. doWholeModelUpload();
  2174. }
  2175. else
  2176. {
  2177. requestWholeModelFee();
  2178. }
  2179. }
  2180. LLViewerFetchedTexture* LLMeshUploadThread::findViewerTexture(const LLImportMaterial& mat)
  2181. {
  2182. LLPointer<LLViewerFetchedTexture>* tex =
  2183. (LLPointer<LLViewerFetchedTexture>*)mat.mUserData;
  2184. return tex ? (*tex).get() : NULL;
  2185. }
  2186. struct LLMeshUploadData
  2187. {
  2188. LLMeshUploadData()
  2189. : mRetries(0)
  2190. {
  2191. }
  2192. U32 mRetries;
  2193. LLPointer<LLModel> mBaseModel;
  2194. LLPointer<LLModel> mModel[5];
  2195. LLUUID mUUID;
  2196. std::string mRSVP;
  2197. std::string mAssetData;
  2198. LLSD mPostData;
  2199. };
  2200. void LLMeshUploadThread::wholeModelToLLSD(LLSD& dest, bool include_textures)
  2201. {
  2202. LLSD result;
  2203. LLSD res;
  2204. result["folder_id"] =
  2205. gInventory.findChoosenCategoryUUIDForType(LLFolderType::FT_OBJECT);
  2206. result["texture_folder_id"] =
  2207. gInventory.findChoosenCategoryUUIDForType(LLFolderType::FT_TEXTURE);
  2208. result["asset_type"] = "mesh";
  2209. result["inventory_type"] = "object";
  2210. result["description"] = "(No Description)";
  2211. result["next_owner_mask"] =
  2212. LLSD::Integer(LLFloaterPerms::getNextOwnerPerms());
  2213. result["group_mask"] = LLSD::Integer(LLFloaterPerms::getGroupPerms());
  2214. result["everyone_mask"] =
  2215. LLSD::Integer(LLFloaterPerms::getEveryonePerms());
  2216. res["mesh_list"] = LLSD::emptyArray();
  2217. res["texture_list"] = LLSD::emptyArray();
  2218. res["instance_list"] = LLSD::emptyArray();
  2219. S32 mesh_num = 0;
  2220. S32 texture_num = 0;
  2221. std::set<LLViewerTexture*> textures;
  2222. std::map<LLViewerTexture*, S32> texture_index;
  2223. std::map<LLModel*, S32> mesh_index;
  2224. std::string model_name;
  2225. S32 instance_num = 0;
  2226. for (instance_map_t::iterator iter = mInstance.begin(),
  2227. end = mInstance.end();
  2228. iter != end; ++iter)
  2229. {
  2230. LLMeshUploadData data;
  2231. data.mBaseModel = iter->first;
  2232. if (data.mBaseModel->mSubmodelID)
  2233. {
  2234. // These are handled below to insure correct parenting order on
  2235. // creation due to map walking being based on model address (aka
  2236. // random)
  2237. continue;
  2238. }
  2239. LLModelInstance& first_instance = *(iter->second.begin());
  2240. for (S32 i = 0; i < 5; ++i)
  2241. {
  2242. data.mModel[i] = first_instance.mLOD[i];
  2243. }
  2244. if (mesh_index.find(data.mBaseModel) == mesh_index.end())
  2245. {
  2246. // Have not seen this model before - create a new mesh_list entry
  2247. // for it.
  2248. if (model_name.empty())
  2249. {
  2250. model_name = data.mBaseModel->getName();
  2251. }
  2252. std::stringstream ostr;
  2253. LLModel::Decomposition& decomp =
  2254. data.mModel[LLModel::LOD_PHYSICS].notNull() ?
  2255. data.mModel[LLModel::LOD_PHYSICS]->mPhysics :
  2256. data.mBaseModel->mPhysics;
  2257. decomp.mBaseHull = mHullMap[data.mBaseModel];
  2258. LLSD mesh_header =
  2259. LLModel::writeModel(ostr, data.mModel[LLModel::LOD_PHYSICS],
  2260. data.mModel[LLModel::LOD_HIGH],
  2261. data.mModel[LLModel::LOD_MEDIUM],
  2262. data.mModel[LLModel::LOD_LOW],
  2263. data.mModel[LLModel::LOD_IMPOSTOR],
  2264. decomp, mUploadSkin, mUploadJoints,
  2265. mLockScaleIfJointPosition, false, false,
  2266. data.mBaseModel->mSubmodelID);
  2267. data.mAssetData = ostr.str();
  2268. std::string str = ostr.str();
  2269. res["mesh_list"][mesh_num] = LLSD::Binary(str.begin(), str.end());
  2270. mesh_index[data.mBaseModel] = mesh_num++;
  2271. }
  2272. // For all instances that use this model
  2273. for (instance_list_t::iterator instance_iter = iter->second.begin(),
  2274. instance_end = iter->second.end();
  2275. instance_iter != instance_end; ++instance_iter)
  2276. {
  2277. LLModelInstance& instance = *instance_iter;
  2278. LLSD instance_entry;
  2279. for (S32 i = 0; i < 5; ++i)
  2280. {
  2281. data.mModel[i] = instance.mLOD[i];
  2282. }
  2283. LLVector3 pos, scale;
  2284. LLQuaternion rot;
  2285. LLMatrix4 transformation = instance.mTransform;
  2286. decomposeMeshMatrix(transformation, pos, rot, scale);
  2287. instance_entry["position"] = ll_sd_from_vector3(pos);
  2288. instance_entry["rotation"] = ll_sd_from_quaternion(rot);
  2289. instance_entry["scale"] = ll_sd_from_vector3(scale);
  2290. instance_entry["material"] = LL_MCODE_WOOD;
  2291. U8 shape_type;
  2292. if (data.mModel[LLModel::LOD_PHYSICS].notNull())
  2293. {
  2294. shape_type = (U8)(LLViewerObject::PHYSICS_SHAPE_PRIM);
  2295. }
  2296. else
  2297. {
  2298. shape_type = (U8)(LLViewerObject::PHYSICS_SHAPE_CONVEX_HULL);
  2299. }
  2300. instance_entry["physics_shape_type"] = shape_type;
  2301. instance_entry["mesh"] = mesh_index[data.mBaseModel];
  2302. instance_entry["mesh_name"] = instance.mLabel;
  2303. instance_entry["face_list"] = LLSD::emptyArray();
  2304. // We want to be able to allow more than 8 materials...
  2305. S32 end = llmin((S32)instance.mMaterial.size(),
  2306. instance.mModel->getNumVolumeFaces());
  2307. for (S32 face_num = 0; face_num < end; ++face_num)
  2308. {
  2309. LLImportMaterial& material =
  2310. instance.mMaterial[data.mBaseModel->mMaterialList[face_num]];
  2311. LLSD face_entry = LLSD::emptyMap();
  2312. LLViewerFetchedTexture* texture = NULL;
  2313. if (material.mDiffuseMapFilename.size())
  2314. {
  2315. texture = findViewerTexture(material);
  2316. }
  2317. if (texture && textures.find(texture) == textures.end())
  2318. {
  2319. textures.insert(texture);
  2320. }
  2321. std::stringstream texture_str;
  2322. if (texture && include_textures && mUploadTextures)
  2323. {
  2324. if (texture->hasSavedRawImage())
  2325. {
  2326. LLPointer<LLImageJ2C> upload_file =
  2327. LLViewerTextureList::convertToUploadFile(texture->getSavedRawImage());
  2328. if (upload_file.notNull() &&
  2329. upload_file->getDataSize())
  2330. {
  2331. texture_str.write((const char*)upload_file->getData(),
  2332. upload_file->getDataSize());
  2333. }
  2334. }
  2335. }
  2336. if (texture && mUploadTextures &&
  2337. texture_index.find(texture) == texture_index.end())
  2338. {
  2339. texture_index[texture] = texture_num;
  2340. std::string str = texture_str.str();
  2341. res["texture_list"][texture_num++] = LLSD::Binary(str.begin(),
  2342. str.end());
  2343. }
  2344. // Subset of TextureEntry fields.
  2345. if (texture && mUploadTextures)
  2346. {
  2347. face_entry["image"] = texture_index[texture];
  2348. face_entry["scales"] = 1.0;
  2349. face_entry["scalet"] = 1.0;
  2350. face_entry["offsets"] = 0.0;
  2351. face_entry["offsett"] = 0.0;
  2352. face_entry["imagerot"] = 0.0;
  2353. }
  2354. face_entry["diffuse_color"] =
  2355. ll_sd_from_color4(material.mDiffuseColor);
  2356. face_entry["fullbright"] = material.mFullbright;
  2357. instance_entry["face_list"][face_num] = face_entry;
  2358. }
  2359. res["instance_list"][instance_num++] = instance_entry;
  2360. }
  2361. }
  2362. for (instance_map_t::iterator iter = mInstance.begin(),
  2363. the_end = mInstance.end();
  2364. iter != the_end; ++iter)
  2365. {
  2366. LLMeshUploadData data;
  2367. data.mBaseModel = iter->first;
  2368. if (!data.mBaseModel->mSubmodelID)
  2369. {
  2370. // These were handled above already...
  2371. continue;
  2372. }
  2373. LLModelInstance& first_instance = *(iter->second.begin());
  2374. for (S32 i = 0; i < 5; ++i)
  2375. {
  2376. data.mModel[i] = first_instance.mLOD[i];
  2377. }
  2378. if (mesh_index.find(data.mBaseModel) == mesh_index.end())
  2379. {
  2380. // Have not seen this model before; create a new mesh_list entry
  2381. // for it.
  2382. if (model_name.empty())
  2383. {
  2384. model_name = data.mBaseModel->getName();
  2385. }
  2386. std::stringstream ostr;
  2387. LLModel::Decomposition& decomp =
  2388. data.mModel[LLModel::LOD_PHYSICS].notNull() ?
  2389. data.mModel[LLModel::LOD_PHYSICS]->mPhysics :
  2390. data.mBaseModel->mPhysics;
  2391. decomp.mBaseHull = mHullMap[data.mBaseModel];
  2392. LLSD mesh_header =
  2393. LLModel::writeModel(ostr, data.mModel[LLModel::LOD_PHYSICS],
  2394. data.mModel[LLModel::LOD_HIGH],
  2395. data.mModel[LLModel::LOD_MEDIUM],
  2396. data.mModel[LLModel::LOD_LOW],
  2397. data.mModel[LLModel::LOD_IMPOSTOR],
  2398. decomp, mUploadSkin, mUploadJoints,
  2399. mLockScaleIfJointPosition, false, false,
  2400. data.mBaseModel->mSubmodelID);
  2401. data.mAssetData = ostr.str();
  2402. std::string str = ostr.str();
  2403. res["mesh_list"][mesh_num] = LLSD::Binary(str.begin(), str.end());
  2404. mesh_index[data.mBaseModel] = mesh_num++;
  2405. }
  2406. // For all instances that use this model
  2407. for (instance_list_t::iterator instance_iter = iter->second.begin(),
  2408. instance_end = iter->second.end();
  2409. instance_iter != instance_end; ++instance_iter)
  2410. {
  2411. LLModelInstance& instance = *instance_iter;
  2412. LLSD instance_entry;
  2413. for (S32 i = 0; i < 5; ++i)
  2414. {
  2415. data.mModel[i] = instance.mLOD[i];
  2416. }
  2417. LLVector3 pos, scale;
  2418. LLQuaternion rot;
  2419. LLMatrix4 transformation = instance.mTransform;
  2420. decomposeMeshMatrix(transformation,pos,rot,scale);
  2421. instance_entry["position"] = ll_sd_from_vector3(pos);
  2422. instance_entry["rotation"] = ll_sd_from_quaternion(rot);
  2423. instance_entry["scale"] = ll_sd_from_vector3(scale);
  2424. instance_entry["material"] = LL_MCODE_WOOD;
  2425. instance_entry["physics_shape_type"] =
  2426. (U8)(LLViewerObject::PHYSICS_SHAPE_NONE);
  2427. instance_entry["mesh"] = mesh_index[data.mBaseModel];
  2428. instance_entry["face_list"] = LLSD::emptyArray();
  2429. // We want to be able to allow more than 8 materials...
  2430. S32 end = llmin((S32)instance.mMaterial.size(),
  2431. instance.mModel->getNumVolumeFaces());
  2432. for (S32 face_num = 0; face_num < end; ++face_num)
  2433. {
  2434. LLImportMaterial& material =
  2435. instance.mMaterial[data.mBaseModel->mMaterialList[face_num]];
  2436. LLSD face_entry = LLSD::emptyMap();
  2437. LLViewerFetchedTexture* tex = NULL;
  2438. if (material.mDiffuseMapFilename.size())
  2439. {
  2440. tex = findViewerTexture(material);
  2441. }
  2442. if (tex && textures.find(tex) == textures.end())
  2443. {
  2444. textures.insert(tex);
  2445. }
  2446. std::stringstream tex_str;
  2447. if (tex && include_textures && mUploadTextures)
  2448. {
  2449. if (tex->hasSavedRawImage())
  2450. {
  2451. LLPointer<LLImageJ2C> upload_file =
  2452. LLViewerTextureList::convertToUploadFile(tex->getSavedRawImage());
  2453. if (!upload_file.isNull() &&
  2454. upload_file->getDataSize())
  2455. {
  2456. tex_str.write((const char*)upload_file->getData(),
  2457. upload_file->getDataSize());
  2458. }
  2459. }
  2460. }
  2461. if (tex && mUploadTextures &&
  2462. texture_index.find(tex) == texture_index.end())
  2463. {
  2464. texture_index[tex] = texture_num;
  2465. std::string str = tex_str.str();
  2466. res["texture_list"][texture_num++] =
  2467. LLSD::Binary(str.begin(), str.end());
  2468. }
  2469. // Subset of TextureEntry fields.
  2470. if (tex && mUploadTextures)
  2471. {
  2472. face_entry["image"] = texture_index[tex];
  2473. face_entry["scales"] = 1.0;
  2474. face_entry["scalet"] = 1.0;
  2475. face_entry["offsets"] = 0.0;
  2476. face_entry["offsett"] = 0.0;
  2477. face_entry["imagerot"] = 0.0;
  2478. }
  2479. face_entry["diffuse_color"] =
  2480. ll_sd_from_color4(material.mDiffuseColor);
  2481. face_entry["fullbright"] = material.mFullbright;
  2482. instance_entry["face_list"][face_num] = face_entry;
  2483. }
  2484. res["instance_list"][instance_num++] = instance_entry;
  2485. }
  2486. }
  2487. if (model_name.empty())
  2488. {
  2489. model_name = "mesh model";
  2490. }
  2491. result["name"] = model_name;
  2492. res["metric"] = "MUT_Unspecified";
  2493. result["asset_resources"] = res;
  2494. dump_llsd_to_file(result, make_dump_name("whole_model_", sDumpNum));
  2495. dest = result;
  2496. }
  2497. void LLMeshUploadThread::generateHulls()
  2498. {
  2499. bool no_valid_request = true;
  2500. for (instance_map_t::iterator iter = mInstance.begin(),
  2501. end = mInstance.end();
  2502. iter != end; ++iter)
  2503. {
  2504. LLMeshUploadData data;
  2505. data.mBaseModel = iter->first;
  2506. LLModelInstance& instance = *(iter->second.begin());
  2507. for (S32 i = 0; i < 5; ++i)
  2508. {
  2509. data.mModel[i] = instance.mLOD[i];
  2510. }
  2511. // Queue up models for hull generation
  2512. LLModel* physics = NULL;
  2513. if (data.mModel[LLModel::LOD_PHYSICS].notNull())
  2514. {
  2515. physics = data.mModel[LLModel::LOD_PHYSICS];
  2516. }
  2517. else if (data.mModel[LLModel::LOD_LOW].notNull())
  2518. {
  2519. physics = data.mModel[LLModel::LOD_LOW];
  2520. }
  2521. else if (data.mModel[LLModel::LOD_MEDIUM].notNull())
  2522. {
  2523. physics = data.mModel[LLModel::LOD_MEDIUM];
  2524. }
  2525. else
  2526. {
  2527. physics = data.mModel[LLModel::LOD_HIGH];
  2528. }
  2529. DecompRequest* request = new DecompRequest(physics, data.mBaseModel,
  2530. this);
  2531. if (request->isValid())
  2532. {
  2533. gMeshRepo.mDecompThread->submitRequest(request);
  2534. no_valid_request = false;
  2535. }
  2536. }
  2537. if (no_valid_request)
  2538. {
  2539. return;
  2540. }
  2541. // *NOTE: interesting live-lock condition on shutdown; if there is an
  2542. // upload request in generateHulls() when shutdown starts, the main thread
  2543. // is not available to manage communication between the decomposition
  2544. // thread and the upload thread and this loop would not complete in turn
  2545. // stalling the main thread. The check on isDiscarded() prevents that.
  2546. LL_DEBUGS("MeshUpload") << "Sleeping after hulls generation till the physics decomp request is honored."
  2547. << LL_ENDL;
  2548. while (!mPhysicsComplete && !isDiscarded())
  2549. {
  2550. ms_sleep(1);
  2551. }
  2552. LL_DEBUGS("MeshUpload") << "Physics decomp request is honored. Sleep state exited."
  2553. << LL_ENDL;
  2554. }
  2555. void LLMeshUploadThread::doWholeModelUpload()
  2556. {
  2557. LL_DEBUGS("MeshUpload") << "Starting model upload. Instances: "
  2558. << mInstance.size() << LL_ENDL;
  2559. if (mWholeModelUploadURL.empty())
  2560. {
  2561. llinfos << "Unable to upload, fee request failed" << llendl;
  2562. }
  2563. else
  2564. {
  2565. generateHulls();
  2566. LL_DEBUGS("MeshUpload") << "Hull generation completed." << LL_ENDL;
  2567. mModelData = LLSD::emptyMap();
  2568. wholeModelToLLSD(mModelData, true);
  2569. LLSD body = mModelData["asset_resources"];
  2570. dump_llsd_to_file(body, make_dump_name("whole_model_body_", sDumpNum));
  2571. LLCore::HttpHandle handle =
  2572. LLCoreHttpUtil::requestPostWithLLSD(mHttpRequest, mHttpPolicyClass,
  2573. mWholeModelUploadURL, body,
  2574. mHttpOptions, mHttpHeaders,
  2575. LLCore::HttpHandler::ptr_t(this,
  2576. &NoOpDeletor));
  2577. if (handle == LLCORE_HTTP_HANDLE_INVALID)
  2578. {
  2579. mHttpStatus = mHttpRequest->getStatus();
  2580. llwarns << "Could not issue request for full model upload. Reason: "
  2581. << mHttpStatus.toString() << " ("
  2582. << mHttpStatus.toTerseString() << ")" << llendl;
  2583. }
  2584. else
  2585. {
  2586. U32 sleep_time = 10;
  2587. LL_DEBUGS("MeshUpload") << "POST request issued." << LL_ENDL;
  2588. mHttpRequest->update(0);
  2589. while (!LLApp::isExiting() && !finished() && !isDiscarded())
  2590. {
  2591. ms_sleep(sleep_time);
  2592. sleep_time = llmin(250U, sleep_time + sleep_time);
  2593. mHttpRequest->update(0);
  2594. }
  2595. LL_DEBUGS("MeshUpload") << "Mesh upload operation "
  2596. << (isDiscarded() ? "discarded."
  2597. : "completed.")
  2598. << LL_ENDL;
  2599. }
  2600. }
  2601. }
  2602. void LLMeshUploadThread::requestWholeModelFee()
  2603. {
  2604. ++sDumpNum;
  2605. generateHulls();
  2606. mModelData = LLSD::emptyMap();
  2607. wholeModelToLLSD(mModelData, false);
  2608. dump_llsd_to_file(mModelData,
  2609. make_dump_name("whole_model_fee_request_", sDumpNum));
  2610. const std::string& whole_model_fee_cap_url =
  2611. gAgent.getRegionCapability("NewFileAgentInventory");
  2612. LLCore::HttpHandle handle =
  2613. LLCoreHttpUtil::requestPostWithLLSD(mHttpRequest, mHttpPolicyClass,
  2614. whole_model_fee_cap_url,
  2615. mModelData, mHttpOptions,
  2616. mHttpHeaders,
  2617. LLCore::HttpHandler::ptr_t(this,
  2618. &NoOpDeletor));
  2619. if (handle == LLCORE_HTTP_HANDLE_INVALID)
  2620. {
  2621. mHttpStatus = mHttpRequest->getStatus();
  2622. llwarns << "Could not issue request for model fee. Reason: "
  2623. << mHttpStatus.toString() << " ("
  2624. << mHttpStatus.toTerseString() << ")" << llendl;
  2625. }
  2626. else
  2627. {
  2628. U32 sleep_time = 10;
  2629. mHttpRequest->update(0);
  2630. while (!LLApp::isExiting() && !finished() && !isDiscarded())
  2631. {
  2632. ms_sleep(sleep_time);
  2633. sleep_time = llmin(250U, 2 * sleep_time);
  2634. mHttpRequest->update(0);
  2635. }
  2636. LL_DEBUGS("MeshUpload") << "Mesh fee query operation "
  2637. << (isDiscarded() ? "discarded" : "completed")
  2638. << LL_ENDL;
  2639. }
  2640. }
  2641. // Helper function
  2642. static void log_upload_error(LLCore::HttpStatus status, const LLSD& content,
  2643. const char* const stage,
  2644. const std::string& model_name)
  2645. {
  2646. // Add notification popup.
  2647. LLSD args;
  2648. std::string message = content["error"]["message"].asString();
  2649. std::string identifier = content["error"]["identifier"].asString();
  2650. args["MESSAGE"] = message;
  2651. args["IDENTIFIER"] = identifier;
  2652. args["LABEL"] = model_name;
  2653. // Log details.
  2654. llwarns << "Error in stage: " << stage << " - Reason: "
  2655. << status.toString() << " (" << status.toTerseString()<< ")"
  2656. << llendl;
  2657. std::ostringstream details;
  2658. typedef std::set<std::string> mav_errors_set_t;
  2659. mav_errors_set_t mav_errors;
  2660. if (content.has("error"))
  2661. {
  2662. const LLSD& err = content["error"];
  2663. llwarns << "Error: " << err << " - Mesh upload failed at stage "
  2664. << stage << " with error: " << err["error"].asString()
  2665. << " - Message: " << err["message"].asString() << " - Id: "
  2666. << err["identifier"].asString() << llendl;
  2667. if (err.has("errors"))
  2668. {
  2669. details << std::endl << std::endl;
  2670. S32 error_num = 0;
  2671. const LLSD& err_list = err["errors"];
  2672. for (LLSD::array_const_iterator it = err_list.beginArray();
  2673. it != err_list.endArray(); ++it)
  2674. {
  2675. const LLSD& err_entry = *it;
  2676. std::string message = err_entry["message"];
  2677. if (message.length() > 0)
  2678. {
  2679. mav_errors.emplace(message);
  2680. }
  2681. llwarns << "error[" << error_num << "]:" << llendl;
  2682. for (LLSD::map_const_iterator map_it = err_entry.beginMap();
  2683. map_it != err_entry.endMap(); ++map_it)
  2684. {
  2685. llwarns << " " << map_it->first << ": "
  2686. << map_it->second << llendl;
  2687. }
  2688. ++error_num;
  2689. }
  2690. }
  2691. }
  2692. else
  2693. {
  2694. llwarns << "Bad response to mesh, no error information available"
  2695. << llendl;
  2696. }
  2697. for (mav_errors_set_t::iterator it = mav_errors.begin(),
  2698. end = mav_errors.end();
  2699. it != end; ++it)
  2700. {
  2701. details << "Message: '" << *it << "': "
  2702. << LLTrans::getString("Mav_Details_" + *it)
  2703. << std::endl << std::endl;
  2704. }
  2705. args["DETAILS"] = details.str();
  2706. gMeshRepo.uploadError(args);
  2707. }
  2708. // Does completion duty for both fee queries and actual uploads.
  2709. void LLMeshUploadThread::onCompleted(LLCore::HttpHandle handle,
  2710. LLCore::HttpResponse* response)
  2711. {
  2712. LLCore::HttpStatus status = response->getStatus();
  2713. std::string reason = status.toString();
  2714. LLSD body;
  2715. mFinished = true;
  2716. if (mDoUpload) // Model upload case
  2717. {
  2718. LLWholeModelUploadObserver* observer(mUploadObserverHandle.get());
  2719. if (!status)
  2720. {
  2721. llwarns << "Upload failed. Reason: " << reason << " ("
  2722. << status.toTerseString() << ")" << llendl;
  2723. // Build a fake body for the alert generator
  2724. body["error"] = LLSD::emptyMap();
  2725. body["error"]["message"] = reason;
  2726. body["error"]["identifier"] = "NetworkError";
  2727. log_upload_error(status, body, "upload",
  2728. mModelData["name"].asString());
  2729. if (observer)
  2730. {
  2731. doOnIdleOneTime(boost::bind(&LLWholeModelUploadObserver::onModelUploadFailure,
  2732. observer));
  2733. }
  2734. }
  2735. else
  2736. {
  2737. // *TODO: handle error in conversion process
  2738. LLCoreHttpUtil::responseToLLSD(response, true, body);
  2739. dump_llsd_to_file(body,
  2740. make_dump_name("whole_model_upload_response_",
  2741. sDumpNum));
  2742. if (body["state"].asString() == "complete")
  2743. {
  2744. // Requested "mesh" asset type is not actually the type of the
  2745. // resultant object, fix it up here.
  2746. mModelData["asset_type"] = "object";
  2747. gMeshRepo.updateInventory(LLMeshRepository::InventoryData(mModelData,
  2748. body));
  2749. if (observer)
  2750. {
  2751. doOnIdleOneTime(boost::bind(&LLWholeModelUploadObserver::onModelUploadSuccess,
  2752. observer));
  2753. }
  2754. }
  2755. else
  2756. {
  2757. llwarns << "Upload failed. Not in expected 'complete' state."
  2758. << llendl;
  2759. log_upload_error(status, body, "upload",
  2760. mModelData["name"].asString());
  2761. if (observer)
  2762. {
  2763. doOnIdleOneTime(boost::bind(&LLWholeModelUploadObserver::onModelUploadFailure,
  2764. observer));
  2765. }
  2766. }
  2767. }
  2768. }
  2769. else // Model fee case
  2770. {
  2771. LLWholeModelFeeObserver* observer = mFeeObserverHandle.get();
  2772. mWholeModelUploadURL.clear();
  2773. if (!status)
  2774. {
  2775. llwarns << "Fee request failed. Reason: " << reason << " ("
  2776. << status.toTerseString() << ")" << llendl;
  2777. // Build a fake body for the alert generator
  2778. body["error"] = LLSD::emptyMap();
  2779. body["error"]["message"] = reason;
  2780. body["error"]["identifier"] = "NetworkError";
  2781. log_upload_error(status, body, "fee",
  2782. mModelData["name"].asString());
  2783. if (observer)
  2784. {
  2785. observer->setModelPhysicsFeeErrorStatus(status.toULong(),
  2786. reason, body["error"]);
  2787. }
  2788. }
  2789. else
  2790. {
  2791. // *TODO: handle error in conversion process
  2792. LLCoreHttpUtil::responseToLLSD(response, true, body);
  2793. dump_llsd_to_file(body, make_dump_name("whole_model_fee_response_",
  2794. sDumpNum));
  2795. if (body["state"].asString() == "upload")
  2796. {
  2797. mWholeModelUploadURL = body["uploader"].asString();
  2798. if (observer)
  2799. {
  2800. body["data"]["upload_price"] = body["upload_price"];
  2801. observer->onModelPhysicsFeeReceived(body["data"],
  2802. mWholeModelUploadURL);
  2803. }
  2804. }
  2805. else
  2806. {
  2807. llwarns << "Fee request failed. Not in expected 'upload' state."
  2808. << llendl;
  2809. log_upload_error(status, body, "fee",
  2810. mModelData["name"].asString());
  2811. if (observer)
  2812. {
  2813. observer->setModelPhysicsFeeErrorStatus(status.toULong(),
  2814. reason,
  2815. body["error"]);
  2816. }
  2817. }
  2818. }
  2819. }
  2820. }
  2821. void LLMeshRepoThread::notifyLoadedMeshes()
  2822. {
  2823. LL_TRACY_TIMER(TRC_MESH_THREAD_NOTIFY_LOADED);
  2824. if (!mLoadedMeshes.empty())
  2825. {
  2826. loaded_mesh_list_t list_copy;
  2827. mMutex.lock();
  2828. list_copy.swap(mLoadedMeshes);
  2829. mMutex.unlock();
  2830. for (loaded_mesh_list_t::iterator it = list_copy.begin(),
  2831. end = list_copy.end();
  2832. it != end; ++it)
  2833. {
  2834. const LoadedMesh& mesh = *it;
  2835. if (mesh.mVolume && mesh.mVolume->getNumVolumeFaces() > 0)
  2836. {
  2837. gMeshRepo.notifyMeshLoaded(mesh.mMeshParams, mesh.mVolume);
  2838. }
  2839. else
  2840. {
  2841. gMeshRepo.notifyMeshUnavailable(mesh.mMeshParams,
  2842. LLVolumeLODGroup::getVolumeDetailFromScale(mesh.mVolume->getDetail()));
  2843. }
  2844. }
  2845. }
  2846. if (!mUnavailableLODs.empty())
  2847. {
  2848. lod_req_list_t list_copy;
  2849. mMutex.lock();
  2850. list_copy.swap(mUnavailableLODs);
  2851. mMutex.unlock();
  2852. for (lod_req_list_t::iterator it = list_copy.begin(),
  2853. end = list_copy.end();
  2854. it != end; ++it)
  2855. {
  2856. const LODRequest& req = *it;
  2857. gMeshRepo.notifyMeshUnavailable(req.mMeshParams, req.mLOD);
  2858. }
  2859. }
  2860. bool no_skin = mSkinInfos.empty();
  2861. bool no_unavailable_skin = mUnavailableSkins.empty();
  2862. bool no_decomp = mDecompositions.empty();
  2863. if (no_skin && no_unavailable_skin && no_decomp)
  2864. {
  2865. return;
  2866. }
  2867. if (!mMutex.trylock())
  2868. {
  2869. return;
  2870. }
  2871. skin_info_list_t skin_info_list;
  2872. if (!no_skin)
  2873. {
  2874. skin_info_list.swap(mSkinInfos);
  2875. }
  2876. uuid_vec_t skin_info_vec;
  2877. if (!no_unavailable_skin)
  2878. {
  2879. skin_info_vec.swap(mUnavailableSkins);
  2880. }
  2881. decomp_list_t decomp_list;
  2882. if (!no_decomp)
  2883. {
  2884. decomp_list.swap(mDecompositions);
  2885. }
  2886. mMutex.unlock();
  2887. // Process the elements free of the lock
  2888. for (skin_info_list_t::iterator it = skin_info_list.begin(),
  2889. end = skin_info_list.end();
  2890. it != end; ++it)
  2891. {
  2892. gMeshRepo.notifySkinInfoReceived(*it);
  2893. }
  2894. for (U32 i = 0, count = skin_info_vec.size(); i < count; ++i)
  2895. {
  2896. gMeshRepo.notifySkinInfoUnavailable(skin_info_vec[i]);
  2897. }
  2898. for (decomp_list_t::iterator it = decomp_list.begin(),
  2899. end = decomp_list.end();
  2900. it != end; ++it)
  2901. {
  2902. gMeshRepo.notifyDecompositionReceived(*it);
  2903. }
  2904. }
  2905. // Only ever called from main thread
  2906. S32 LLMeshRepoThread::getActualMeshLOD(const LLVolumeParams& mesh_params,
  2907. S32 lod)
  2908. {
  2909. mHeaderMutex.lock();
  2910. mesh_header_map_t::iterator iter =
  2911. mMeshHeaders.find(mesh_params.getSculptID());
  2912. if (iter != mMeshHeaders.end())
  2913. {
  2914. lod = LLMeshRepository::getActualMeshLOD(iter->second, lod);
  2915. }
  2916. mHeaderMutex.unlock();
  2917. return lod;
  2918. }
  2919. //static
  2920. S32 LLMeshRepository::getActualMeshLOD(LLMeshHeader* header, S32 lod)
  2921. {
  2922. lod = llclamp(lod, 0, 3);
  2923. if (!header || !header->mValid)
  2924. {
  2925. return -1;
  2926. }
  2927. if (header->mLodSize[lod] > 0)
  2928. {
  2929. return lod;
  2930. }
  2931. static LLCachedControl<bool> higher_first(gSavedSettings,
  2932. "SearchHigherMeshLODFirst");
  2933. if (higher_first)
  2934. {
  2935. // Search up to find then next available higher lod
  2936. for (S32 i = lod + 1; i < 4; ++i)
  2937. {
  2938. if (header->mLodSize[i] > 0)
  2939. {
  2940. return i;
  2941. }
  2942. }
  2943. }
  2944. // Search down to find the next available lower lod
  2945. for (S32 i = lod - 1; i >= 0; --i)
  2946. {
  2947. if (header->mLodSize[i] > 0)
  2948. {
  2949. return i;
  2950. }
  2951. }
  2952. if (!higher_first)
  2953. {
  2954. // Search up to find then next available higher lod
  2955. for (S32 i = lod + 1; i < 4; ++i)
  2956. {
  2957. if (header->mLodSize[i] > 0)
  2958. {
  2959. return i;
  2960. }
  2961. }
  2962. }
  2963. // Should never get there... Header valid and no good LOD found.
  2964. llassert(false);
  2965. return -1;
  2966. }
  2967. // Handle failed or successful requests for mesh assets.
  2968. //
  2969. // Support for 200 responses was added for several reasons. One, a service or
  2970. // cache can ignore range headers and give us a 200 with full asset should it
  2971. // elect to. We also support a debug flag which disables range requests for
  2972. // those very few users that have some sort of problem with their networking
  2973. // services. But the 200 response handling is suboptimal: rather than cache the
  2974. // whole asset, we just extract the part that would have been sent in a 206 and
  2975. // process that. Inefficient but these are cases far off the norm.
  2976. void LLMeshHandlerBase::onCompleted(LLCore::HttpHandle handle,
  2977. LLCore::HttpResponse* response)
  2978. {
  2979. LL_TRACY_TIMER(TRC_MESH_HANDLER_COMPLETED);
  2980. // Thread could have already been destroyed during logout
  2981. if (!gMeshRepo.mThread)
  2982. {
  2983. return;
  2984. }
  2985. mProcessed = true;
  2986. do // Single-pass do-while used for common exit handling
  2987. {
  2988. LLCore::HttpStatus status = response->getStatus();
  2989. if (!status)
  2990. {
  2991. processFailure(status);
  2992. ++LLMeshRepository::sHTTPErrorCount;
  2993. break;
  2994. }
  2995. // From texture fetch code and may apply here:
  2996. //
  2997. // A warning about partial (HTTP 206) data. Some grid services do *not*
  2998. // return a 'Content-Range' header in the response to Range requests
  2999. // with a 206 status. We're forced to assume we get what we asked for
  3000. // in these cases until we can fix the services.
  3001. //
  3002. // May also need to deal with 200 status (full asset returned rather
  3003. // than partial) and 416 (request completely unsatisfyable). Always
  3004. // been exposed to these but are less likely here where speculative
  3005. // loads aren't done.
  3006. LLCore::BufferArray* body = response->getBody();
  3007. S32 body_offset = 0;
  3008. U8* data = NULL;
  3009. S32 data_size = body ? body->size() : 0;
  3010. if (data_size > 0)
  3011. {
  3012. unsigned int offset = 0;
  3013. unsigned int length = 0;
  3014. unsigned int full_length = 0;
  3015. if (status == gStatusPartialContent)
  3016. {
  3017. // 206 case
  3018. response->getRange(&offset, &length, &full_length);
  3019. if (!offset && !length)
  3020. {
  3021. // This is the case where we receive a 206 status but there
  3022. // was not a useful Content-Range header in the response.
  3023. // This could be because it was badly formatted but is more
  3024. // likely due to capabilities services which scrub headers
  3025. // from responses. Assume we got what we asked for...
  3026. offset = mOffset;
  3027. }
  3028. }
  3029. else
  3030. {
  3031. // 200 case, typically
  3032. offset = 0;
  3033. }
  3034. // Validate that what we think we received is consistent with
  3035. // what we've asked for. I.e. first byte we wanted lies somewhere
  3036. // in the response.
  3037. if ((S32)offset > mOffset || (S32)offset + data_size <= mOffset ||
  3038. mOffset - (S32)offset >= data_size)
  3039. {
  3040. // No overlap with requested range. Fail request with suitable
  3041. // error. Should not happen unless server/cache/ISP is doing
  3042. // something awful.
  3043. llwarns << "Mesh response (bytes [" << offset << ", "
  3044. << offset + length - 1
  3045. << "]) didn't overlap with request's origin (bytes ["
  3046. << mOffset << ", " << mOffset + mRequestedBytes - 1
  3047. << "])." << llendl;
  3048. processFailure(LLCore::HttpStatus(LLCore::HttpStatus::LLCORE,
  3049. LLCore::HE_INV_CONTENT_RANGE_HDR));
  3050. ++LLMeshRepository::sHTTPErrorCount;
  3051. break;
  3052. }
  3053. LLMeshRepository::sBytesReceived += data_size;
  3054. // *TODO: Try to get rid of data copying and add interfaces that
  3055. // support BufferArray directly. Introduce a two-phase handler,
  3056. // optional first that takes a body, fallback second that requires
  3057. // a temporary allocation and data copy.
  3058. body_offset = mOffset - offset;
  3059. data_size -= body_offset;
  3060. data = new(std::nothrow) U8[data_size];
  3061. if (!data)
  3062. {
  3063. LLMemory::allocationFailed(data_size);
  3064. llwarns << "Could not allocate enough memory. Aborted."
  3065. << llendl;
  3066. break;
  3067. }
  3068. body->read(body_offset, (char*)data, data_size);
  3069. }
  3070. processData(body, body_offset, data, data_size);
  3071. if (data)
  3072. {
  3073. delete[] data;
  3074. }
  3075. }
  3076. while (false);
  3077. // Release handler
  3078. gMeshRepo.mThread->mHttpRequestSet.erase(this->shared_from_this());
  3079. }
  3080. LLMeshHeaderHandler::~LLMeshHeaderHandler()
  3081. {
  3082. if (!LLApp::isExiting())
  3083. {
  3084. if (!mProcessed)
  3085. {
  3086. // Something went wrong, retry
  3087. llwarns << "Mesh header fetch cancelled unexpectedly, retrying."
  3088. << llendl;
  3089. LLMutex& mutex = gMeshRepo.mThread->mMutex;
  3090. mutex.lock();
  3091. gMeshRepo.mThread->mHeaderReqQ.emplace_back(mMeshParams);
  3092. mutex.unlock();
  3093. }
  3094. --LLMeshRepoThread::sActiveHeaderRequests;
  3095. }
  3096. }
  3097. void LLMeshHeaderHandler::processFailure(LLCore::HttpStatus status)
  3098. {
  3099. llwarns << "Error during mesh header handling. ID: "
  3100. << mMeshParams.getSculptID() << " - Reason: " << status.toString()
  3101. << " (" << status.toTerseString() << "). Not retrying." << llendl;
  3102. // Cannot get the header so none of the LODs will be available
  3103. LLMutex& mutex = gMeshRepo.mThread->mMutex;
  3104. mutex.lock();
  3105. for (S32 i = 0; i < 4; ++i)
  3106. {
  3107. gMeshRepo.mThread->mUnavailableLODs.emplace_back(mMeshParams, i);
  3108. }
  3109. mutex.unlock();
  3110. }
  3111. void LLMeshHeaderHandler::processData(LLCore::BufferArray*, S32, U8* data,
  3112. S32 data_size)
  3113. {
  3114. LL_TRACY_TIMER(TRC_MESH_PROCESS_HEADER);
  3115. const LLUUID& mesh_id = mMeshParams.getSculptID();
  3116. bool success = gMeshRepo.mThread->headerReceived(mMeshParams, data,
  3117. data_size);
  3118. if (!success)
  3119. {
  3120. // *TODO: Get real reason for parse failure here. Might we want to
  3121. // retry ?
  3122. llwarns << "Unable to parse mesh header. ID: " << mesh_id
  3123. << " - Unknown reason. Not retrying." << llendl;
  3124. // Cannot get the header, so none of the LODs will be available
  3125. LLMutex& mutex = gMeshRepo.mThread->mMutex;
  3126. mutex.lock();
  3127. for (S32 i = 0; i < 4; ++i)
  3128. {
  3129. gMeshRepo.mThread->mUnavailableLODs.emplace_back(mMeshParams, i);
  3130. }
  3131. mutex.unlock();
  3132. }
  3133. else if (data && data_size > 0)
  3134. {
  3135. // Header was successfully retrieved from sim, cache it
  3136. LLMeshHeader* header = NULL;
  3137. LLMutex& mutex = gMeshRepo.mThread->mHeaderMutex;
  3138. mutex.lock();
  3139. LLMeshRepoThread::mesh_header_map_t::iterator iter =
  3140. gMeshRepo.mThread->mMeshHeaders.find(mesh_id);
  3141. if (iter != gMeshRepo.mThread->mMeshHeaders.end())
  3142. {
  3143. header = iter->second;
  3144. }
  3145. mutex.unlock();
  3146. if (header && header->mValid)
  3147. {
  3148. U32 header_bytes = header->mHeaderSize;
  3149. U32 lod_bytes = 0;
  3150. U32 lod_size = 0;
  3151. for (U32 i = 0; i < 4; ++i)
  3152. {
  3153. // Figure out how many bytes we will need to reserve in the
  3154. // file
  3155. lod_size = header->mLodSize[i];
  3156. if (lod_size > 0)
  3157. {
  3158. lod_bytes = llmax(lod_bytes,
  3159. header->mLodOffset[i] + lod_size);
  3160. }
  3161. }
  3162. // Just in case skin info or decomposition is at the end of the
  3163. // file (which it should not be)
  3164. lod_size = header->mSkinSize;
  3165. if (lod_size > 0)
  3166. {
  3167. lod_bytes = llmax(lod_bytes,
  3168. header->mSkinOffset + lod_size);
  3169. }
  3170. lod_size = header->mPhysicsConvexSize;
  3171. if (lod_size > 0)
  3172. {
  3173. lod_bytes = llmax(lod_bytes,
  3174. header->mPhysicsConvexOffset + lod_size);
  3175. }
  3176. S32 bytes = llmax(lod_bytes, header_bytes);
  3177. // It is possible for the remote asset to have more data than is
  3178. // needed for the local cache; only allocate as much space in the
  3179. // cache as is needed for the local cache.
  3180. data_size = llmin(data_size, bytes);
  3181. LLMeshRepository::sCacheBytesWritten += data_size;
  3182. ++LLMeshRepository::sCacheWrites;
  3183. LLFileSystem file(mesh_id, LLFileSystem::OVERWRITE);
  3184. file.write(data, data_size);
  3185. }
  3186. else
  3187. {
  3188. llwarns << "Trying to cache nonexistent mesh, mesh id: " << mesh_id
  3189. << llendl;
  3190. // headerReceived() parsed the header, but its data is invalid so
  3191. // none of the LODs will be available
  3192. LLMutex& mutex = gMeshRepo.mThread->mMutex;
  3193. mutex.lock();
  3194. for (S32 i = 0; i < 4; ++i)
  3195. {
  3196. gMeshRepo.mThread->mUnavailableLODs.emplace_back(mMeshParams,
  3197. i);
  3198. }
  3199. mutex.unlock();
  3200. }
  3201. }
  3202. }
  3203. LLMeshLODHandler::~LLMeshLODHandler()
  3204. {
  3205. if (!LLApp::isExiting())
  3206. {
  3207. if (!mProcessed)
  3208. {
  3209. llwarns << "Mesh LOD fetch cancelled unexpectedly, retrying."
  3210. << llendl;
  3211. gMeshRepo.mThread->lockAndLoadMeshLOD(mMeshParams, mLOD);
  3212. }
  3213. --LLMeshRepoThread::sActiveLODRequests;
  3214. }
  3215. }
  3216. void LLMeshLODHandler::processFailure(LLCore::HttpStatus status)
  3217. {
  3218. llwarns << "Error during mesh LOD handling. ID: "
  3219. << mMeshParams.getSculptID() << " - Reason: "
  3220. << status.toString() << " (" << status.toTerseString()
  3221. << "). Not retrying." << llendl;
  3222. LLMutex& mutex = gMeshRepo.mThread->mMutex;
  3223. mutex.lock();
  3224. gMeshRepo.mThread->mUnavailableLODs.emplace_back(mMeshParams, mLOD);
  3225. mutex.unlock();
  3226. }
  3227. void LLMeshLODHandler::processData(LLCore::BufferArray*, S32, U8* data,
  3228. S32 data_size)
  3229. {
  3230. LL_TRACY_TIMER(TRC_MESH_PROCESS_LOD);
  3231. if (data && data_size > 0 &&
  3232. gMeshRepo.mThread->lodReceived(mMeshParams, mLOD, data, data_size))
  3233. {
  3234. // Good fetch from sim, write to cache
  3235. LLFileSystem file(mMeshParams.getSculptID(), LLFileSystem::WRITE);
  3236. S32 offset = mOffset;
  3237. S32 size = mRequestedBytes;
  3238. if (file.getSize() >= MESH_HEADER_SIZE)
  3239. {
  3240. file.seek(offset); // Note: pads data if necessary. HB
  3241. file.write(data, size);
  3242. LLMeshRepository::sCacheBytesWritten += size;
  3243. ++LLMeshRepository::sCacheWrites;
  3244. }
  3245. }
  3246. else
  3247. {
  3248. llwarns << "Failed to unpack volume faces for mesh Id: "
  3249. << mMeshParams.getSculptID() << " - LOD: " << mLOD
  3250. << ". Not retrying." << llendl;
  3251. LLMutex& mutex = gMeshRepo.mThread->mMutex;
  3252. mutex.lock();
  3253. gMeshRepo.mThread->mUnavailableLODs.emplace_back(mMeshParams, mLOD);
  3254. mutex.unlock();
  3255. }
  3256. }
  3257. LLMeshSkinInfoHandler::~LLMeshSkinInfoHandler()
  3258. {
  3259. llassert(mProcessed || LLApp::isExiting());
  3260. }
  3261. void LLMeshSkinInfoHandler::processFailure(LLCore::HttpStatus status)
  3262. {
  3263. llwarns << "Error during mesh skin info handling. ID: " << mMeshID
  3264. << " - Reason: " << status.toString() << " ("
  3265. << status.toTerseString() << "). Not retrying." << llendl;
  3266. LLMutex& mutex = gMeshRepo.mThread->mMutex;
  3267. mutex.lock();
  3268. gMeshRepo.mThread->mUnavailableSkins.emplace_back(mMeshID);
  3269. mutex.unlock();
  3270. }
  3271. void LLMeshSkinInfoHandler::processData(LLCore::BufferArray*, S32, U8* data,
  3272. S32 data_size)
  3273. {
  3274. LL_TRACY_TIMER(TRC_MESH_PROCESS_SKIN);
  3275. if (data && data_size > 0 &&
  3276. gMeshRepo.mThread->skinInfoReceived(mMeshID, data, data_size))
  3277. {
  3278. // Good fetch from sim, write to cache
  3279. LLFileSystem file(mMeshID, LLFileSystem::WRITE);
  3280. S32 offset = mOffset;
  3281. S32 size = mRequestedBytes;
  3282. if (file.getSize() >= MESH_HEADER_SIZE)
  3283. {
  3284. LLMeshRepository::sCacheBytesWritten += size;
  3285. ++LLMeshRepository::sCacheWrites;
  3286. file.seek(offset); // Note: pads data if necessary. HB
  3287. file.write(data, size);
  3288. }
  3289. }
  3290. else
  3291. {
  3292. llwarns << "Error during mesh skin info processing. ID: " << mMeshID
  3293. << " - Unknown reason. Not retrying." << llendl;
  3294. LLMutex& mutex = gMeshRepo.mThread->mMutex;
  3295. mutex.lock();
  3296. gMeshRepo.mThread->mUnavailableSkins.emplace_back(mMeshID);
  3297. mutex.unlock();
  3298. }
  3299. }
  3300. LLMeshDecompositionHandler::~LLMeshDecompositionHandler()
  3301. {
  3302. llassert(mProcessed || LLApp::isExiting());
  3303. }
  3304. void LLMeshDecompositionHandler::processFailure(LLCore::HttpStatus status)
  3305. {
  3306. llwarns << "Error during mesh decomposition handling. ID: " << mMeshID
  3307. << ", Reason: " << status.toString() << " ("
  3308. << status.toTerseString() << "). Not retrying." << llendl;
  3309. // *TODO: mark mesh unavailable on error. For now, simply leave the request
  3310. // unfulfilled rather than retrying forever.
  3311. }
  3312. void LLMeshDecompositionHandler::processData(LLCore::BufferArray*, S32,
  3313. U8* data, S32 data_size)
  3314. {
  3315. LL_TRACY_TIMER(TRC_MESH_PROCESS_DECOMP);
  3316. if (data && data_size > 0 &&
  3317. gMeshRepo.mThread->decompositionReceived(mMeshID, data, data_size))
  3318. {
  3319. // Good fetch from sim, write to cache
  3320. LLFileSystem file(mMeshID, LLFileSystem::WRITE);
  3321. S32 offset = mOffset;
  3322. S32 size = mRequestedBytes;
  3323. if (file.getSize() >= MESH_HEADER_SIZE)
  3324. {
  3325. LLMeshRepository::sCacheBytesWritten += size;
  3326. ++LLMeshRepository::sCacheWrites;
  3327. file.seek(offset); // Note: pads data if necessary. HB
  3328. file.write(data, size);
  3329. }
  3330. }
  3331. else
  3332. {
  3333. llwarns << "Error during mesh decomposition processing. ID: "
  3334. << mMeshID << " - Unknown reason. Not retrying." << llendl;
  3335. // *TODO: Mark mesh unavailable on error
  3336. }
  3337. }
  3338. LLMeshPhysicsShapeHandler::~LLMeshPhysicsShapeHandler()
  3339. {
  3340. llassert(mProcessed || LLApp::isExiting());
  3341. }
  3342. void LLMeshPhysicsShapeHandler::processFailure(LLCore::HttpStatus status)
  3343. {
  3344. llwarns << "Error during mesh physics shape handling. ID: " << mMeshID
  3345. << ", Reason: " << status.toString() << " ("
  3346. << status.toTerseString() << "). Not retrying." << llendl;
  3347. // *TODO: Mark mesh unavailable on error
  3348. }
  3349. void LLMeshPhysicsShapeHandler::processData(LLCore::BufferArray*, S32,
  3350. U8* data, S32 data_size)
  3351. {
  3352. LL_TRACY_TIMER(TRC_MESH_PROCESS_PHYSICS);
  3353. if (data && data_size > 0 &&
  3354. gMeshRepo.mThread->physicsShapeReceived(mMeshID, data, data_size))
  3355. {
  3356. // Good fetch from sim, write to cache
  3357. LLFileSystem file(mMeshID, LLFileSystem::WRITE);
  3358. S32 offset = mOffset;
  3359. S32 size = mRequestedBytes;
  3360. if (file.getSize() >= MESH_HEADER_SIZE)
  3361. {
  3362. LLMeshRepository::sCacheBytesWritten += size;
  3363. ++LLMeshRepository::sCacheWrites;
  3364. file.seek(offset); // Note: pads data if necessary. HB
  3365. file.write(data, size);
  3366. }
  3367. }
  3368. else
  3369. {
  3370. llwarns << "Error during mesh physics shape processing. ID: "
  3371. << mMeshID << " - Unknown reason. Not retrying." << llendl;
  3372. // *TODO: mark mesh unavailable on error
  3373. }
  3374. }
  3375. LLMeshRepository::LLMeshRepository()
  3376. : mDecompThread(NULL),
  3377. mThread(NULL)
  3378. {
  3379. }
  3380. void LLMeshRepository::init()
  3381. {
  3382. LLConvexDecomposition::getInstance()->initSystem();
  3383. mDecompThread = new LLPhysicsDecomp();
  3384. mDecompThread->start();
  3385. // Wait for physics decomp thread to init
  3386. while (!mDecompThread->mInited)
  3387. {
  3388. ms_sleep(1);
  3389. }
  3390. mThread = new LLMeshRepoThread();
  3391. mThread->start();
  3392. }
  3393. void LLMeshRepository::shutdown()
  3394. {
  3395. llinfos << "Shutting down mesh repository." << llendl;
  3396. if (!mThread)
  3397. {
  3398. llwarns << "NULL thread pointer: repository already shut down ?"
  3399. << llendl;
  3400. llassert(false);
  3401. return;
  3402. }
  3403. for (U32 i = 0; i < mUploads.size(); ++i)
  3404. {
  3405. llinfos << "Discard the pending mesh uploads " << llendl;
  3406. mUploads[i]->discard(); // discard the uploading requests.
  3407. }
  3408. mThread->mSignal.broadcast();
  3409. while (!mThread->isStopped())
  3410. {
  3411. ms_sleep(1);
  3412. }
  3413. delete mThread;
  3414. mThread = NULL;
  3415. for (U32 i = 0; i < mUploads.size(); ++i)
  3416. {
  3417. llinfos << "Waiting for pending mesh upload " << i + 1 << "/"
  3418. << mUploads.size() << llendl;
  3419. while (!mUploads[i]->isStopped())
  3420. {
  3421. ms_sleep(1);
  3422. }
  3423. delete mUploads[i];
  3424. }
  3425. mUploads.clear();
  3426. llinfos << "Shutting down decomposition system." << llendl;
  3427. if (mDecompThread)
  3428. {
  3429. mDecompThread->shutdown();
  3430. delete mDecompThread;
  3431. mDecompThread = NULL;
  3432. }
  3433. LLConvexDecomposition::quitSystem();
  3434. llinfos << "Clearing " << mSkinMap.size() << " cached skin info entries."
  3435. << llendl;
  3436. mSkinMap.clear();
  3437. llinfos << "Clearing " << mCostsMap.size() << " cached cost data entries."
  3438. << llendl;
  3439. mCostsMap.clear();
  3440. }
  3441. // Called in the main thread.
  3442. S32 LLMeshRepository::update()
  3443. {
  3444. if (mUploadWaitList.empty())
  3445. {
  3446. return 0;
  3447. }
  3448. S32 size = mUploadWaitList.size();
  3449. for (S32 i = 0; i < size; ++i)
  3450. {
  3451. mUploads.push_back(mUploadWaitList[i]);
  3452. mUploadWaitList[i]->preStart();
  3453. mUploadWaitList[i]->start();
  3454. }
  3455. mUploadWaitList.clear();
  3456. return size;
  3457. }
  3458. void LLMeshRepository::unregisterVolume(LLVOVolume* volp, bool has_mesh,
  3459. bool has_skin)
  3460. {
  3461. LL_TRACY_TIMER(TRC_MESH_UNREGISTER_VOLUME);
  3462. mMeshMutex.lock();
  3463. if (has_mesh)
  3464. {
  3465. for (U32 lod = 0; lod < 4; ++lod)
  3466. {
  3467. for (mesh_load_map_t::iterator it = mLoadingMeshes[lod].begin(),
  3468. end = mLoadingMeshes[lod].end();
  3469. it != end; )
  3470. {
  3471. it->second.erase(volp);
  3472. if (it->second.empty())
  3473. {
  3474. it = mLoadingMeshes[lod].erase(it);
  3475. }
  3476. else
  3477. {
  3478. ++it;
  3479. }
  3480. }
  3481. }
  3482. }
  3483. if (has_skin)
  3484. {
  3485. for (skin_load_map_t::iterator it = mLoadingSkins.begin(),
  3486. end = mLoadingSkins.end();
  3487. it != end; )
  3488. {
  3489. it->second.erase(volp);
  3490. if (it->second.empty())
  3491. {
  3492. it = mLoadingSkins.erase(it);
  3493. }
  3494. else
  3495. {
  3496. ++it;
  3497. }
  3498. }
  3499. }
  3500. mMeshMutex.unlock();
  3501. }
  3502. S32 LLMeshRepository::loadMesh(LLVOVolume* vobj,
  3503. const LLVolumeParams& mesh_params,
  3504. S32 detail, S32 last_lod)
  3505. {
  3506. detail = llclamp(detail, 0, 3);
  3507. LL_DEBUGS("MeshQueue") << "Requested LOD for mesh object "
  3508. << vobj->getID() << " = " << detail << LL_ENDL;
  3509. // Mark this object address as registered in the mesh repository. HB
  3510. vobj->setInMeshCache();
  3511. mMeshMutex.lock();
  3512. // Add volume to list of loading meshes
  3513. const LLUUID& mesh_id = mesh_params.getSculptID();
  3514. mesh_load_map_t::iterator iter = mLoadingMeshes[detail].find(mesh_id);
  3515. if (iter != mLoadingMeshes[detail].end())
  3516. {
  3517. // Request pending for this mesh, append volume id to list
  3518. LL_DEBUGS("MeshQueue") << "Adding object to pending requests for the associated mesh"
  3519. << LL_ENDL;
  3520. iter->second.insert(vobj);
  3521. }
  3522. else
  3523. {
  3524. // First request for this mesh
  3525. LL_DEBUGS("MeshQueue") << "Initiating request for the associated mesh"
  3526. << LL_ENDL;
  3527. mLoadingMeshes[detail][mesh_id].insert(vobj);
  3528. mPendingRequests.emplace_back(mesh_params, detail);
  3529. ++sLODPending;
  3530. }
  3531. mMeshMutex.unlock();
  3532. // Do a quick search to see if we cannot display something while we wait
  3533. // for this mesh to load
  3534. LLVolume* volume = vobj->getVolume();
  3535. if (volume)
  3536. {
  3537. LLVolumeParams params = volume->getParams();
  3538. LLVolumeLODGroup* group = gVolumeMgrp->getGroup(params);
  3539. if (group)
  3540. {
  3541. // First, see if last_lod is available (do not transition down to
  3542. // avoid funny popping à la SH-641)
  3543. if (last_lod >= 0 && last_lod <= LLModel::LOD_HIGH)
  3544. {
  3545. LLVolume* lod = group->refLOD(last_lod);
  3546. if (lod && lod->isMeshAssetLoaded() &&
  3547. lod->getNumVolumeFaces() > 0)
  3548. {
  3549. group->derefLOD(lod);
  3550. LL_DEBUGS("Mesh") << "Using last LOD (" << last_lod
  3551. << ") for mesh object" << vobj->getID()
  3552. << LL_ENDL;
  3553. return last_lod;
  3554. }
  3555. group->derefLOD(lod);
  3556. }
  3557. // Next, see what the next higher LOD available might be
  3558. for (S32 i = detail + 1; i <= LLModel::LOD_HIGH; ++i)
  3559. {
  3560. LLVolume* lod = group->refLOD(i);
  3561. if (lod && lod->isMeshAssetLoaded() &&
  3562. lod->getNumVolumeFaces() > 0)
  3563. {
  3564. group->derefLOD(lod);
  3565. LL_DEBUGS("Mesh") << "Using higher LOD = " << i
  3566. << " for mesh object" << vobj->getID()
  3567. << LL_ENDL;
  3568. return i;
  3569. }
  3570. group->derefLOD(lod);
  3571. }
  3572. // No higher LOD is a available, is a lower lod available ?
  3573. for (S32 i = detail - 1; i >= 0; --i)
  3574. {
  3575. LLVolume* lod = group->refLOD(i);
  3576. if (lod && lod->isMeshAssetLoaded() &&
  3577. lod->getNumVolumeFaces() > 0)
  3578. {
  3579. group->derefLOD(lod);
  3580. LL_DEBUGS("Mesh") << "Using lower LOD = " << i
  3581. << " for mesh object" << vobj->getID()
  3582. << LL_ENDL;
  3583. return i;
  3584. }
  3585. group->derefLOD(lod);
  3586. }
  3587. }
  3588. }
  3589. return detail;
  3590. }
  3591. // Called from main thread
  3592. void LLMeshRepository::notifyLoadedMeshes()
  3593. {
  3594. LL_TRACY_TIMER(TRC_MESH_NOTIFY_LOADED);
  3595. // Clean up completed upload threads
  3596. for (std::vector<LLMeshUploadThread*>::iterator iter = mUploads.begin();
  3597. iter != mUploads.end(); )
  3598. {
  3599. LLMeshUploadThread* thread = *iter;
  3600. if (thread->isStopped() && thread->finished())
  3601. {
  3602. iter = mUploads.erase(iter);
  3603. delete thread;
  3604. }
  3605. else
  3606. {
  3607. ++iter;
  3608. }
  3609. }
  3610. // Update inventory
  3611. if (!mInventoryQ.empty())
  3612. {
  3613. const LLUUID parent_id =
  3614. gInventory.findChoosenCategoryUUIDForType(LLFolderType::FT_TEXTURE);
  3615. mMeshMutex.lock();
  3616. while (!mInventoryQ.empty())
  3617. {
  3618. InventoryData& data = mInventoryQ.front();
  3619. LLAssetType::EType asset_type =
  3620. LLAssetType::lookup(data.mPostData["asset_type"].asString());
  3621. LLInventoryType::EType inventory_type =
  3622. LLInventoryType::lookup(data.mPostData["inventory_type"].asString());
  3623. // Handle addition of texture, if any.
  3624. if (data.mResponse.has("new_texture_folder_id"))
  3625. {
  3626. LLUUID folder_id =
  3627. data.mResponse["new_texture_folder_id"].asUUID();
  3628. if (folder_id.notNull())
  3629. {
  3630. std::string name;
  3631. // Check if the server built a different name for the
  3632. // texture folder
  3633. if (data.mResponse.has("new_texture_folder_name"))
  3634. {
  3635. name = data.mResponse["new_texture_folder_name"].asString();
  3636. }
  3637. else
  3638. {
  3639. name = data.mPostData["name"].asString();
  3640. }
  3641. // Add the category to the internal representation
  3642. LLPointer<LLViewerInventoryCategory> catp =
  3643. new LLViewerInventoryCategory(folder_id, parent_id,
  3644. LLFolderType::FT_NONE,
  3645. name, gAgentID);
  3646. catp->setVersionUnknown();
  3647. LLInventoryModel::LLCategoryUpdate u(catp->getParentUUID(),
  3648. 1);
  3649. gInventory.accountForUpdate(u);
  3650. gInventory.updateCategory(catp);
  3651. }
  3652. }
  3653. on_new_single_inventory_upload_complete(asset_type,
  3654. inventory_type,
  3655. data.mPostData["asset_type"].asString(),
  3656. data.mPostData["folder_id"].asUUID(),
  3657. data.mPostData["name"],
  3658. data.mPostData["description"],
  3659. data.mResponse,
  3660. data.mResponse["upload_price"]);
  3661. mInventoryQ.pop();
  3662. }
  3663. mMeshMutex.unlock();
  3664. }
  3665. // Call completed callbacks on finished decompositions
  3666. mDecompThread->notifyCompleted();
  3667. // For major operations, attempt to get the required locks without blocking
  3668. // and punt if they are not available. The longest run of holdoffs is kept
  3669. // in sMaxLockHoldoffs just to collect the data. In testing, I have never
  3670. // seen a value greater than 2 (written to log on exit).
  3671. {
  3672. LLMutexTrylock lock1(mMeshMutex);
  3673. LLMutexTrylock lock2(mThread->mMutex);
  3674. static U32 hold_offs = 0;
  3675. if (!lock1.isLocked() || !lock2.isLocked())
  3676. {
  3677. // If we cannot get the locks, skip and pick this up later.
  3678. ++hold_offs;
  3679. sMaxLockHoldoffs = llmax(sMaxLockHoldoffs, hold_offs);
  3680. return;
  3681. }
  3682. hold_offs = 0;
  3683. static LLUUID region_id;
  3684. LLViewerRegion* regionp = gAgent.getRegion();
  3685. if (regionp && regionp->getRegionID() != region_id &&
  3686. regionp->capabilitiesReceived())
  3687. {
  3688. // Update the mesh capability url
  3689. region_id = regionp->getRegionID();
  3690. bool is_v2 = false;
  3691. mThread->mGetMeshCapability = regionp->getMeshUrl(&is_v2);
  3692. mThread->mGetMeshVersion = is_v2 ? 2 : 1;
  3693. S32 scale = 5;
  3694. if (is_v2)
  3695. {
  3696. // GetMesh2 operation with keepalives, etc. With pipelining, we
  3697. // will increase this. See llappcorehttp and llcorehttp for
  3698. // discussion on connection strategies.
  3699. LLAppCoreHttp& app_core_http = gAppViewerp->getAppCoreHttp();
  3700. if (app_core_http.isPipelined(LLAppCoreHttp::AP_MESH2))
  3701. {
  3702. scale = 2 * LLAppCoreHttp::PIPELINING_DEPTH;
  3703. }
  3704. static LLCachedControl<U32> max_requests2(gSavedSettings,
  3705. "Mesh2MaxConcurrentRequests");
  3706. LLMeshRepoThread::sMaxConcurrentRequests = max_requests2;
  3707. LLMeshRepoThread::sRequestHighWater =
  3708. llclamp(scale * (S32)max_requests2,
  3709. REQUEST2_HIGH_WATER_MIN, REQUEST2_HIGH_WATER_MAX);
  3710. LLMeshRepoThread::sRequestLowWater =
  3711. llclamp(LLMeshRepoThread::sRequestHighWater / 2,
  3712. REQUEST2_LOW_WATER_MIN, REQUEST2_LOW_WATER_MAX);
  3713. }
  3714. else
  3715. {
  3716. static LLCachedControl<U32> max_requests(gSavedSettings,
  3717. "MeshMaxConcurrentRequests");
  3718. LLMeshRepoThread::sMaxConcurrentRequests = max_requests;
  3719. LLMeshRepoThread::sRequestHighWater =
  3720. llclamp(scale * (S32)max_requests,
  3721. REQUEST_HIGH_WATER_MIN, REQUEST_HIGH_WATER_MAX);
  3722. LLMeshRepoThread::sRequestLowWater =
  3723. llclamp(LLMeshRepoThread::sRequestHighWater / 2,
  3724. REQUEST_LOW_WATER_MIN, REQUEST_LOW_WATER_MAX);
  3725. }
  3726. }
  3727. // Popup queued error messages from background threads
  3728. while (!mUploadErrorQ.empty())
  3729. {
  3730. gNotifications.add("MeshUploadError", mUploadErrorQ.front());
  3731. mUploadErrorQ.pop();
  3732. }
  3733. S32 active_count = LLMeshRepoThread::sActiveHeaderRequests +
  3734. LLMeshRepoThread::sActiveLODRequests;
  3735. if (active_count < LLMeshRepoThread::sRequestLowWater)
  3736. {
  3737. S32 push_count = LLMeshRepoThread::sRequestHighWater -
  3738. active_count;
  3739. #if LL_PENDING_MESH_REQUEST_SORTING
  3740. if ((S32)mPendingRequests.size() > push_count)
  3741. {
  3742. // More requests than the high-water limit allows so sort and
  3743. // forward the most important. Calculate "score" for pending
  3744. // requests.
  3745. // Create score map
  3746. fast_hmap<LLUUID, F32> score_map;
  3747. for (U32 i = 0; i < 4; ++i)
  3748. {
  3749. for (mesh_load_map_t::iterator
  3750. iter = mLoadingMeshes[i].begin(),
  3751. end = mLoadingMeshes[i].end();
  3752. iter != end; ++iter)
  3753. {
  3754. F32 max_score = 0.f;
  3755. for (auto obj_iter = iter->second.begin(),
  3756. end2 = iter->second.end();
  3757. obj_iter != end2; ++obj_iter)
  3758. {
  3759. LLViewerObject* object = *obj_iter;
  3760. if (object)
  3761. {
  3762. LLDrawable* drawable = object->mDrawable;
  3763. if (drawable)
  3764. {
  3765. F32 cur_score =
  3766. drawable->getRadius() /
  3767. llmax(drawable->mDistanceWRTCamera,
  3768. 1.f);
  3769. max_score = llmax(max_score, cur_score);
  3770. }
  3771. }
  3772. }
  3773. score_map.emplace(iter->first, max_score);
  3774. }
  3775. }
  3776. // Set "score" for pending requests
  3777. for (std::vector<LLMeshRepoThread::LODRequest>::iterator
  3778. iter = mPendingRequests.begin(),
  3779. end = mPendingRequests.end();
  3780. iter != end; ++iter)
  3781. {
  3782. iter->mScore = score_map[iter->mMeshParams.getSculptID()];
  3783. }
  3784. // Sort by "score"
  3785. std::partial_sort(mPendingRequests.begin(),
  3786. mPendingRequests.begin() + push_count,
  3787. mPendingRequests.end(),
  3788. LLMeshRepoThread::CompareScoreGreater());
  3789. }
  3790. while (--push_count >= 0 && !mPendingRequests.empty())
  3791. {
  3792. LLMeshRepoThread::LODRequest& request =
  3793. mPendingRequests.front();
  3794. mThread->loadMeshLOD(request.mMeshParams, request.mLOD);
  3795. mPendingRequests.erase(mPendingRequests.begin());
  3796. --sLODPending;
  3797. }
  3798. #else
  3799. if (mPendingRequests.empty() && !mDelayedPendingRequests.empty())
  3800. {
  3801. // When all urgent requests have been processed, add back some
  3802. // of the delayed requests into the queue...
  3803. for (S32 i = 0;
  3804. i < LLMeshRepoThread::sRequestLowWater &&
  3805. !mDelayedPendingRequests.empty();
  3806. ++i)
  3807. {
  3808. mPendingRequests.emplace_back(mDelayedPendingRequests.front());
  3809. mDelayedPendingRequests.pop_front();
  3810. }
  3811. LL_DEBUGS("MeshQueue") << "Re-inserted "
  3812. << mPendingRequests.size()
  3813. << " delayed mesh requests into the queue."
  3814. << LL_ENDL;
  3815. }
  3816. while (--push_count >= 0 && !mPendingRequests.empty())
  3817. {
  3818. LLMeshRepoThread::LODRequest& request =
  3819. mPendingRequests.front();
  3820. mThread->loadMeshLOD(request.mMeshParams, request.mLOD);
  3821. mPendingRequests.pop_front();
  3822. --sLODPending;
  3823. }
  3824. #endif
  3825. }
  3826. // Send skin info requests
  3827. while (!mPendingSkinRequests.empty())
  3828. {
  3829. mThread->loadMeshSkinInfo(mPendingSkinRequests.front());
  3830. mPendingSkinRequests.pop();
  3831. }
  3832. // Send decomposition requests
  3833. while (!mPendingDecompositionRequests.empty())
  3834. {
  3835. mThread->loadMeshDecomposition(mPendingDecompositionRequests.front());
  3836. mPendingDecompositionRequests.pop();
  3837. }
  3838. // Send physics shapes decomposition requests
  3839. while (!mPendingPhysicsShapeRequests.empty())
  3840. {
  3841. mThread->loadMeshPhysicsShape(mPendingPhysicsShapeRequests.front());
  3842. mPendingPhysicsShapeRequests.pop();
  3843. }
  3844. mThread->notifyLoadedMeshes();
  3845. }
  3846. // Skins cache periodic culling, based on .
  3847. static F32 last_culling = 0.f;
  3848. constexpr F32 SKININFO_CULL_DELAY = 10.f; // In seconds
  3849. if (gFrameTimeSeconds - last_culling >= SKININFO_CULL_DELAY)
  3850. {
  3851. last_culling = gFrameTimeSeconds;
  3852. for (skin_map_t::iterator it = mSkinMap.begin(), end = mSkinMap.end();
  3853. it != end; )
  3854. {
  3855. if (it->second->getNumRefs() == 1) // Just one ref (in mSkinMap) ?
  3856. {
  3857. it = mSkinMap.erase(it);
  3858. }
  3859. else
  3860. {
  3861. ++it;
  3862. }
  3863. }
  3864. }
  3865. // There is only one wait(), but broadcast, just in case...
  3866. mThread->mSignal.broadcast();
  3867. }
  3868. void LLMeshRepository::notifySkinInfoReceived(LLMeshSkinInfo* info)
  3869. {
  3870. mSkinMap[info->mMeshID] = info;
  3871. mMeshMutex.lock();
  3872. skin_load_map_t::const_iterator iter = mLoadingSkins.find(info->mMeshID);
  3873. if (iter == mLoadingSkins.end())
  3874. {
  3875. // This may happen after far TPs, for example.
  3876. mMeshMutex.unlock();
  3877. LL_DEBUGS("MeshQueue") << "Received notification for a skin no more in the loading list: "
  3878. << info->mMeshID << LL_ENDL;
  3879. return;
  3880. }
  3881. for (auto oit = iter->second.begin(), end = iter->second.end();
  3882. oit != end; ++oit)
  3883. {
  3884. LLVOVolume* vobj = *oit;
  3885. if (vobj)
  3886. {
  3887. vobj->notifySkinInfoLoaded(info);
  3888. }
  3889. }
  3890. mLoadingSkins.erase(iter);
  3891. mMeshMutex.unlock();
  3892. }
  3893. void LLMeshRepository::notifySkinInfoUnavailable(const LLUUID& mesh_id)
  3894. {
  3895. mMeshMutex.lock();
  3896. skin_load_map_t::iterator iter = mLoadingSkins.find(mesh_id);
  3897. if (iter != mLoadingSkins.end())
  3898. {
  3899. for (auto oit = iter->second.begin(), end = iter->second.end();
  3900. oit != end; ++oit)
  3901. {
  3902. LLVOVolume* vobj = *oit;
  3903. if (vobj)
  3904. {
  3905. vobj->notifySkinInfoUnavailable();
  3906. }
  3907. }
  3908. mLoadingSkins.erase(iter);
  3909. }
  3910. mMeshMutex.unlock();
  3911. }
  3912. #if !LL_PENDING_MESH_REQUEST_SORTING
  3913. void LLMeshRepository::delayCurrentRequests()
  3914. {
  3915. mMeshMutex.lock();
  3916. if (!mPendingRequests.empty())
  3917. {
  3918. LL_DEBUGS("MeshQueue") << "Delaying " << mPendingRequests.size()
  3919. << " pending mesh requests." << LL_ENDL;
  3920. // Very likely (and super-fast) when we did not TP for a while...
  3921. if (mDelayedPendingRequests.empty())
  3922. {
  3923. mDelayedPendingRequests.swap(mPendingRequests);
  3924. }
  3925. // May happen (especially with a slow network) when TPing shortly after
  3926. // a previous TP has finished and meshes are still loading.
  3927. else
  3928. {
  3929. // NOTE: the current pending meshes are emplaced at the end of
  3930. // the queue of the delayed ones, in case we would be TPing back to
  3931. // the previous region where the already delayed meshes were queued
  3932. for (LLMeshRepoThread::lod_req_queue_t::iterator
  3933. it = mPendingRequests.begin(),
  3934. end = mPendingRequests.end();
  3935. it != end; ++it)
  3936. {
  3937. mDelayedPendingRequests.emplace_back(*it);
  3938. }
  3939. mPendingRequests.clear();
  3940. }
  3941. LL_DEBUGS("MeshQueue") << mDelayedPendingRequests.size()
  3942. << " pending mesh requests are in the delayed queue."
  3943. << LL_ENDL;
  3944. }
  3945. mMeshMutex.unlock();
  3946. }
  3947. #endif
  3948. void LLMeshRepository::notifyDecompositionReceived(LLModel::Decomposition* decomp)
  3949. {
  3950. const LLUUID& mesh_id = decomp->mMeshID;
  3951. decomp_map_t::iterator it = mDecompositionMap.find(mesh_id);
  3952. if (it == mDecompositionMap.end())
  3953. {
  3954. // Just insert decomp into map
  3955. mDecompositionMap.emplace(mesh_id, decomp);
  3956. mLoadingDecompositions.erase(mesh_id);
  3957. }
  3958. else
  3959. {
  3960. // Merge decomp with existing entry
  3961. it->second->merge(decomp);
  3962. mLoadingDecompositions.erase(mesh_id);
  3963. delete decomp;
  3964. }
  3965. }
  3966. // Called from main thread
  3967. void LLMeshRepository::notifyMeshLoaded(const LLVolumeParams& mesh_params,
  3968. LLVolume* volume)
  3969. {
  3970. LL_TRACY_TIMER(TRC_MESH_NOTIFY_LOADED);
  3971. if (!volume) return;
  3972. mMeshMutex.lock();
  3973. // Get the list of objects waiting to be notified this mesh is loaded
  3974. S32 lod = LLVolumeLODGroup::getVolumeDetailFromScale(volume->getDetail());
  3975. const LLUUID& mesh_id = mesh_params.getSculptID();
  3976. mesh_load_map_t::iterator obj_iter = mLoadingMeshes[lod].find(mesh_id);
  3977. if (obj_iter == mLoadingMeshes[lod].end())
  3978. {
  3979. mMeshMutex.unlock();
  3980. return;
  3981. }
  3982. // Make sure target volume is still valid
  3983. if (volume->getNumVolumeFaces() <= 0)
  3984. {
  3985. llwarns << "Mesh loading returned empty volume for mesh " << mesh_id
  3986. << llendl;
  3987. }
  3988. // Update system volume
  3989. LLVolume* sys_volume = gVolumeMgrp->refVolume(mesh_params, lod);
  3990. if (sys_volume)
  3991. {
  3992. sys_volume->copyVolumeFaces(volume);
  3993. sys_volume->setMeshAssetLoaded(true);
  3994. gVolumeMgrp->unrefVolume(sys_volume);
  3995. }
  3996. else
  3997. {
  3998. llwarns << "Could not find system volume for mesh " << mesh_id
  3999. << llendl;
  4000. }
  4001. // Notify waiting LLVOVolume instances that their requested mesh is
  4002. // available
  4003. for (auto it = obj_iter->second.begin(), end = obj_iter->second.end();
  4004. it != end; ++it)
  4005. {
  4006. LLVOVolume* vobj = *it;
  4007. if (vobj)
  4008. {
  4009. vobj->notifyMeshLoaded();
  4010. }
  4011. }
  4012. mLoadingMeshes[lod].erase(obj_iter);
  4013. mMeshMutex.unlock();
  4014. }
  4015. // Called from main thread
  4016. void LLMeshRepository::notifyMeshUnavailable(const LLVolumeParams& mesh_params,
  4017. S32 lod)
  4018. {
  4019. mMeshMutex.lock();
  4020. // Get the list of objects waiting to be notified this mesh is loaded
  4021. const LLUUID& mesh_id = mesh_params.getSculptID();
  4022. mesh_load_map_t::iterator it = mLoadingMeshes[lod].find(mesh_id);
  4023. if (it == mLoadingMeshes[lod].end())
  4024. {
  4025. mMeshMutex.unlock();
  4026. return;
  4027. }
  4028. F32 detail = LLVolumeLODGroup::getVolumeScaleFromDetail(lod);
  4029. for (auto oit = it->second.begin(), end = it->second.end();
  4030. oit != end; ++oit)
  4031. {
  4032. LLVOVolume* vobj = *oit;
  4033. if (vobj)
  4034. {
  4035. LLVolume* obj_volume = vobj->getVolume();
  4036. if (obj_volume && obj_volume->getDetail() == detail &&
  4037. obj_volume->getParams() == mesh_params)
  4038. {
  4039. // Should force volume to find most appropriate LOD
  4040. vobj->setVolume(obj_volume->getParams(), lod);
  4041. }
  4042. }
  4043. }
  4044. mLoadingMeshes[lod].erase(it);
  4045. mMeshMutex.unlock();
  4046. }
  4047. S32 LLMeshRepository::getActualMeshLOD(const LLVolumeParams& mesh_params,
  4048. S32 lod)
  4049. {
  4050. return mThread ? mThread->getActualMeshLOD(mesh_params, lod) : -1;
  4051. }
  4052. const LLMeshSkinInfo* LLMeshRepository::getSkinInfo(const LLUUID& mesh_id,
  4053. LLVOVolume* req_obj)
  4054. {
  4055. if (mesh_id.isNull())
  4056. {
  4057. return NULL;
  4058. }
  4059. skin_map_t::iterator iter = mSkinMap.find(mesh_id);
  4060. if (iter != mSkinMap.end())
  4061. {
  4062. return iter->second;
  4063. }
  4064. // Mark this object address as registered in the skin repository. HB
  4065. req_obj->setInSkinCache();
  4066. // No skin info known about given mesh, try to fetch it
  4067. mMeshMutex.lock();
  4068. // Add volume to list of loading meshes
  4069. if (!mLoadingSkins.count(mesh_id))
  4070. {
  4071. // No request pending for this skin info
  4072. mPendingSkinRequests.emplace(mesh_id);
  4073. }
  4074. auto& obj_set = mLoadingSkins[mesh_id];
  4075. obj_set.insert(req_obj);
  4076. mMeshMutex.unlock();
  4077. return NULL;
  4078. }
  4079. void LLMeshRepository::fetchPhysicsShape(const LLUUID& mesh_id)
  4080. {
  4081. if (mesh_id.notNull())
  4082. {
  4083. LLModel::Decomposition* decomp = NULL;
  4084. decomp_map_t::iterator iter = mDecompositionMap.find(mesh_id);
  4085. if (iter != mDecompositionMap.end())
  4086. {
  4087. decomp = iter->second;
  4088. }
  4089. // Decomposition block has not been fetched yet
  4090. if (!decomp || decomp->mPhysicsShapeMesh.empty())
  4091. {
  4092. mMeshMutex.lock();
  4093. // Add volume to list of loading meshes
  4094. if (!mLoadingPhysicsShapes.count(mesh_id))
  4095. {
  4096. // No request pending for this skin info
  4097. mLoadingPhysicsShapes.emplace(mesh_id);
  4098. mPendingPhysicsShapeRequests.emplace(mesh_id);
  4099. }
  4100. mMeshMutex.unlock();
  4101. }
  4102. }
  4103. }
  4104. LLModel::Decomposition* LLMeshRepository::getDecomposition(const LLUUID& mesh_id)
  4105. {
  4106. LLModel::Decomposition* ret = NULL;
  4107. if (mesh_id.notNull())
  4108. {
  4109. decomp_map_t::iterator iter = mDecompositionMap.find(mesh_id);
  4110. if (iter != mDecompositionMap.end())
  4111. {
  4112. ret = iter->second;
  4113. }
  4114. // Decomposition block has not been fetched yet
  4115. if (!ret || ret->mBaseHullMesh.empty())
  4116. {
  4117. mMeshMutex.lock();
  4118. // Add volume to list of loading meshes
  4119. if (!mLoadingDecompositions.count(mesh_id))
  4120. {
  4121. // No request pending for this skin info
  4122. mLoadingDecompositions.emplace(mesh_id);
  4123. mPendingDecompositionRequests.emplace(mesh_id);
  4124. }
  4125. mMeshMutex.unlock();
  4126. }
  4127. }
  4128. return ret;
  4129. }
  4130. void LLMeshRepository::buildHull(const LLVolumeParams& params, S32 detail)
  4131. {
  4132. LLVolume* volume = gVolumeMgrp->refVolume(params, detail);
  4133. #if 0
  4134. if (volume && !volume->mHullPoints)
  4135. {
  4136. // all default params
  4137. // execute first stage
  4138. // set simplify mode to retain
  4139. // set retain percentage to zero
  4140. // run second stage
  4141. }
  4142. #endif
  4143. if (volume)
  4144. {
  4145. gVolumeMgrp->unrefVolume(volume);
  4146. }
  4147. }
  4148. bool LLMeshRepository::hasPhysicsShape(const LLUUID& mesh_id)
  4149. {
  4150. bool physics_shape = false;
  4151. if (mThread)
  4152. {
  4153. mThread->mHeaderMutex.lock();
  4154. LLMeshHeader* header = mThread->getMeshHeader(mesh_id);
  4155. physics_shape = header && header->mPhysicsMeshSize > 0;
  4156. mThread->mHeaderMutex.unlock();
  4157. }
  4158. if (!physics_shape)
  4159. {
  4160. LLModel::Decomposition* decomp = getDecomposition(mesh_id);
  4161. physics_shape = decomp && !decomp->mHull.empty();
  4162. }
  4163. return physics_shape;
  4164. }
  4165. void LLMeshRepository::uploadModel(std::vector<LLModelInstance>& data,
  4166. LLVector3& scale, bool upload_textures,
  4167. bool upload_skin, bool upload_joints,
  4168. bool lock_scale_if_joint_position,
  4169. std::string upload_url, bool do_upload,
  4170. LLHandle<LLWholeModelFeeObserver> fee_observer,
  4171. LLHandle<LLWholeModelUploadObserver> upload_observer)
  4172. {
  4173. LLMeshUploadThread* thread =
  4174. new LLMeshUploadThread(data, scale, upload_textures, upload_skin,
  4175. upload_joints, lock_scale_if_joint_position,
  4176. upload_url, do_upload, fee_observer,
  4177. upload_observer);
  4178. mUploadWaitList.push_back(thread);
  4179. }
  4180. S32 LLMeshRepository::getMeshSize(const LLUUID& mesh_id, S32 lod)
  4181. {
  4182. S32 size = -1;
  4183. if (mThread && mesh_id.notNull() && lod >= 0 && lod < 4)
  4184. {
  4185. mThread->mHeaderMutex.lock();
  4186. LLMeshRepoThread::mesh_header_map_t::iterator iter =
  4187. mThread->mMeshHeaders.find(mesh_id);
  4188. if (iter != mThread->mMeshHeaders.end())
  4189. {
  4190. LLMeshHeader* header = iter->second;
  4191. if (header->mValid)
  4192. {
  4193. size = header->mLodSize[lod];
  4194. }
  4195. }
  4196. mThread->mHeaderMutex.unlock();
  4197. }
  4198. return size;
  4199. }
  4200. void LLMeshRepository::updateInventory(InventoryData data)
  4201. {
  4202. mMeshMutex.lock();
  4203. dump_llsd_to_file(data.mPostData,
  4204. make_dump_name("update_inventory_post_data_", sDumpNum));
  4205. dump_llsd_to_file(data.mResponse,
  4206. make_dump_name("update_inventory_response_", sDumpNum));
  4207. mInventoryQ.emplace(data);
  4208. mMeshMutex.unlock();
  4209. }
  4210. void LLMeshRepository::uploadError(const LLSD& args)
  4211. {
  4212. mMeshMutex.lock();
  4213. mUploadErrorQ.emplace(args);
  4214. mMeshMutex.unlock();
  4215. }
  4216. LLMeshCostData* LLMeshRepository::getCostData(const LLUUID& mesh_id)
  4217. {
  4218. if (!mThread || mesh_id.isNull())
  4219. {
  4220. return NULL;
  4221. }
  4222. mesh_costs_map_t::iterator it = mCostsMap.find(mesh_id);
  4223. if (it != mCostsMap.end())
  4224. {
  4225. LL_DEBUGS("MeshCost") << "Returning cached costs for mesh Id: "
  4226. << mesh_id << LL_ENDL;
  4227. return it->second.get();
  4228. }
  4229. LLMeshCostData* cost_data = NULL;
  4230. mThread->mHeaderMutex.lock();
  4231. LLMeshRepoThread::mesh_header_map_t::iterator iter =
  4232. mThread->mMeshHeaders.find(mesh_id);
  4233. if (iter != mThread->mMeshHeaders.end())
  4234. {
  4235. LLMeshHeader* header = iter->second;
  4236. if (header->mValid)
  4237. {
  4238. cost_data = new LLMeshCostData();
  4239. if (cost_data->init(header))
  4240. {
  4241. LL_DEBUGS("MeshCost") << "Caching costs for mesh Id: "
  4242. << mesh_id << LL_ENDL;
  4243. mCostsMap.emplace(mesh_id, cost_data);
  4244. }
  4245. else
  4246. {
  4247. llwarns << "Failed to compute costs for mesh Id: " << mesh_id
  4248. << llendl;
  4249. delete cost_data;
  4250. cost_data = NULL;
  4251. }
  4252. }
  4253. }
  4254. mThread->mHeaderMutex.unlock();
  4255. return cost_data;
  4256. }
  4257. F32 LLMeshRepository::getEstTrianglesMax(const LLUUID& mesh_id)
  4258. {
  4259. LLMeshCostData* cost_data = getCostData(mesh_id);
  4260. return cost_data ? cost_data->getEstTrisMax() : 0.f;
  4261. }
  4262. F32 LLMeshRepository::getEstTrianglesStreamingCost(const LLUUID& mesh_id)
  4263. {
  4264. LLMeshCostData* cost_data = getCostData(mesh_id);
  4265. return cost_data ? cost_data->getEstTrisForStreamingCost() : 0.f;
  4266. }
  4267. void LLMeshRepository::buildPhysicsMesh(LLModel::Decomposition& decomp)
  4268. {
  4269. decomp.mMesh.resize(decomp.mHull.size());
  4270. LLConvexDecomposition* decompinst = LLConvexDecomposition::getInstance();
  4271. for (U32 i = 0; i < decomp.mHull.size(); ++i)
  4272. {
  4273. LLCDHull hull;
  4274. hull.mNumVertices = decomp.mHull[i].size();
  4275. hull.mVertexBase = decomp.mHull[i][0].mV;
  4276. hull.mVertexStrideBytes = 12;
  4277. LLCDMeshData mesh;
  4278. LLCDResult res = LLCD_OK;
  4279. if (decompinst)
  4280. {
  4281. res = decompinst->getMeshFromHull(&hull, &mesh);
  4282. }
  4283. if (res == LLCD_OK)
  4284. {
  4285. get_vertex_buffer_from_mesh(mesh, decomp.mMesh[i]);
  4286. }
  4287. }
  4288. if (!decomp.mBaseHull.empty() && decomp.mBaseHullMesh.empty())
  4289. {
  4290. // Get mesh for base hull
  4291. LLCDHull hull;
  4292. hull.mNumVertices = decomp.mBaseHull.size();
  4293. hull.mVertexBase = decomp.mBaseHull[0].mV;
  4294. hull.mVertexStrideBytes = 12;
  4295. LLCDMeshData mesh;
  4296. LLCDResult res = LLCD_OK;
  4297. if (decompinst)
  4298. {
  4299. res = decompinst->getMeshFromHull(&hull, &mesh);
  4300. }
  4301. if (res == LLCD_OK)
  4302. {
  4303. get_vertex_buffer_from_mesh(mesh, decomp.mBaseHullMesh);
  4304. }
  4305. }
  4306. }
  4307. bool LLMeshRepository::meshUploadEnabled()
  4308. {
  4309. LLViewerRegion* region = gAgent.getRegion();
  4310. return region && region->meshUploadEnabled();
  4311. }
  4312. bool LLMeshRepository::meshRezEnabled()
  4313. {
  4314. LLViewerRegion* region = gAgent.getRegion();
  4315. return region && region->meshRezEnabled();
  4316. }
  4317. void LLMeshUploadThread::decomposeMeshMatrix(LLMatrix4& transformation,
  4318. LLVector3& result_pos,
  4319. LLQuaternion& result_rot,
  4320. LLVector3& result_scale)
  4321. {
  4322. // Check for reflection
  4323. bool reflected = transformation.determinant() < 0;
  4324. // Compute position
  4325. LLVector3 position = LLVector3::zero * transformation;
  4326. // Compute scale
  4327. LLVector3 x_transformed = LLVector3::x_axis * transformation - position;
  4328. LLVector3 y_transformed = LLVector3::y_axis * transformation - position;
  4329. LLVector3 z_transformed = LLVector3::z_axis * transformation - position;
  4330. F32 x_length = x_transformed.normalize();
  4331. F32 y_length = y_transformed.normalize();
  4332. F32 z_length = z_transformed.normalize();
  4333. LLVector3 scale = LLVector3(x_length, y_length, z_length);
  4334. // Adjust for "reflected" geometry
  4335. LLVector3 x_transformed_reflected = x_transformed;
  4336. if (reflected)
  4337. {
  4338. x_transformed_reflected *= -1.0;
  4339. }
  4340. // Compute rotation
  4341. LLMatrix3 rotation_matrix;
  4342. rotation_matrix.setRows(x_transformed_reflected, y_transformed,
  4343. z_transformed);
  4344. LLQuaternion quat_rotation = rotation_matrix.quaternion();
  4345. // The rotation_matrix might not have been orthoginal, make it so here:
  4346. quat_rotation.normalize();
  4347. LLVector3 euler_rotation;
  4348. quat_rotation.getEulerAngles(&euler_rotation.mV[VX],
  4349. &euler_rotation.mV[VY],
  4350. &euler_rotation.mV[VZ]);
  4351. result_pos = position + mOrigin;
  4352. result_scale = scale;
  4353. result_rot = quat_rotation;
  4354. LL_DEBUGS("MeshUpload") << "Mesh matrix decomposed." << LL_ENDL;
  4355. }
  4356. ///////////////////////////////////////////////////////////////////////////////
  4357. // LLPhysicsDecomp class
  4358. ///////////////////////////////////////////////////////////////////////////////
  4359. LLPhysicsDecomp::LLPhysicsDecomp()
  4360. : LLThread("Physics decomposition"),
  4361. mInited(false),
  4362. mQuitting(false),
  4363. mDone(false)
  4364. {
  4365. }
  4366. LLPhysicsDecomp::~LLPhysicsDecomp()
  4367. {
  4368. shutdown();
  4369. }
  4370. void LLPhysicsDecomp::shutdown()
  4371. {
  4372. mQuitting = true;
  4373. mSignal.signal();
  4374. while (!isStopped())
  4375. {
  4376. ms_sleep(1);
  4377. }
  4378. }
  4379. void LLPhysicsDecomp::submitRequest(LLPhysicsDecomp::Request* request)
  4380. {
  4381. mMutex.lock();
  4382. mRequestQ.push(request);
  4383. mSignal.signal();
  4384. mMutex.unlock();
  4385. }
  4386. //static
  4387. S32 LLPhysicsDecomp::llcdCallback(const char* status, S32 p1, S32 p2)
  4388. {
  4389. if (!gMeshRepo.mDecompThread ||
  4390. gMeshRepo.mDecompThread->mCurRequest.isNull())
  4391. {
  4392. return 1;
  4393. }
  4394. return gMeshRepo.mDecompThread->mCurRequest->statusCallback(status, p1,
  4395. p2);
  4396. }
  4397. // Helper function
  4398. static bool need_triangles(LLConvexDecomposition* decomp)
  4399. {
  4400. if (!decomp)
  4401. {
  4402. return false;
  4403. }
  4404. const LLCDParam* params = NULL;
  4405. S32 n_params = decomp->getParameters(&params);
  4406. if (n_params <= 0)
  4407. {
  4408. return false;
  4409. }
  4410. for (S32 i = 0; i < n_params; ++i)
  4411. {
  4412. if (params[i].mName &&
  4413. strcmp("nd_AlwaysNeedTriangles", params[i].mName) == 0)
  4414. {
  4415. return LLCDParam::LLCD_BOOLEAN == params[i].mType &&
  4416. params[i].mDefault.mBool;
  4417. }
  4418. }
  4419. return false;
  4420. }
  4421. void LLPhysicsDecomp::setMeshData(LLCDMeshData& mesh, bool vertex_based)
  4422. {
  4423. LLConvexDecomposition* decomp = LLConvexDecomposition::getInstance();
  4424. if (vertex_based)
  4425. {
  4426. vertex_based = !need_triangles(decomp);
  4427. }
  4428. mesh.mVertexBase = mCurRequest->mPositions[0].mV;
  4429. mesh.mVertexStrideBytes = 12;
  4430. mesh.mNumVertices = mCurRequest->mPositions.size();
  4431. if (!vertex_based)
  4432. {
  4433. mesh.mIndexType = LLCDMeshData::INT_16;
  4434. mesh.mIndexBase = &(mCurRequest->mIndices[0]);
  4435. mesh.mIndexStrideBytes = 6;
  4436. mesh.mNumTriangles = mCurRequest->mIndices.size() / 3;
  4437. }
  4438. if ((vertex_based || mesh.mNumTriangles > 0) && mesh.mNumVertices > 2)
  4439. {
  4440. LLCDResult ret = LLCD_OK;
  4441. if (decomp)
  4442. {
  4443. ret = decomp->setMeshData(&mesh, vertex_based);
  4444. }
  4445. if (ret)
  4446. {
  4447. llerrs << "Convex Decomposition thread valid but could not set mesh data"
  4448. << llendl;
  4449. }
  4450. }
  4451. }
  4452. void LLPhysicsDecomp::doDecomposition()
  4453. {
  4454. LLConvexDecomposition* decomp = LLConvexDecomposition::getInstance();
  4455. if (!decomp)
  4456. {
  4457. // Stub library, do nothing.
  4458. return;
  4459. }
  4460. LLCDMeshData mesh;
  4461. S32 stage = mStageID[mCurRequest->mStage];
  4462. // Load data into LLCD
  4463. if (stage == 0)
  4464. {
  4465. setMeshData(mesh, false);
  4466. }
  4467. // Build parameter map
  4468. std::map<std::string, const LLCDParam*> param_map;
  4469. static const LLCDParam* params = NULL;
  4470. static S32 param_count = 0;
  4471. if (!params)
  4472. {
  4473. param_count = decomp->getParameters(&params);
  4474. }
  4475. for (S32 i = 0; i < param_count; ++i)
  4476. {
  4477. param_map[params[i].mName] = params + i;
  4478. }
  4479. U32 ret = LLCD_OK;
  4480. // Set parameter values
  4481. for (decomp_params_t::iterator iter = mCurRequest->mParams.begin(),
  4482. end = mCurRequest->mParams.end();
  4483. iter != end; ++iter)
  4484. {
  4485. const std::string& name = iter->first;
  4486. const LLSD& value = iter->second;
  4487. const LLCDParam* param = param_map[name];
  4488. if (!param)
  4489. {
  4490. // Could not find a valid parameter
  4491. continue;
  4492. }
  4493. if (param->mType == LLCDParam::LLCD_FLOAT)
  4494. {
  4495. ret = decomp->setParam(param->mName, (F32)value.asReal());
  4496. }
  4497. else if (param->mType == LLCDParam::LLCD_INTEGER ||
  4498. param->mType == LLCDParam::LLCD_ENUM)
  4499. {
  4500. ret = decomp->setParam(param->mName, value.asInteger());
  4501. }
  4502. else if (param->mType == LLCDParam::LLCD_BOOLEAN)
  4503. {
  4504. ret = decomp->setParam(param->mName, value.asBoolean());
  4505. }
  4506. }
  4507. mCurRequest->setStatusMessage("Executing.");
  4508. ret = decomp->executeStage(stage);
  4509. if (ret)
  4510. {
  4511. llwarns << "Convex decomposition thread valid but could not execute stage "
  4512. << stage << llendl;
  4513. mMutex.lock();
  4514. mCurRequest->mHull.clear();
  4515. mCurRequest->mHullMesh.clear();
  4516. mCurRequest->setStatusMessage("FAIL");
  4517. mCompletedQ.push(std::move(mCurRequest));
  4518. mCurRequest = NULL;
  4519. mMutex.unlock();
  4520. }
  4521. else
  4522. {
  4523. mCurRequest->setStatusMessage("Reading results");
  4524. S32 num_hulls = decomp->getNumHullsFromStage(stage);
  4525. mMutex.lock();
  4526. mCurRequest->mHull.clear();
  4527. mCurRequest->mHull.resize(num_hulls);
  4528. mCurRequest->mHullMesh.clear();
  4529. mCurRequest->mHullMesh.resize(num_hulls);
  4530. mMutex.unlock();
  4531. for (S32 i = 0; i < num_hulls; ++i)
  4532. {
  4533. std::vector<LLVector3> p;
  4534. LLCDHull hull;
  4535. decomp->getHullFromStage(stage, i, &hull);
  4536. const F32* v = hull.mVertexBase;
  4537. for (S32 j = 0; j < hull.mNumVertices; ++j)
  4538. {
  4539. p.emplace_back(v[0], v[1], v[2]);
  4540. v = (F32*) (((U8*) v) + hull.mVertexStrideBytes);
  4541. }
  4542. LLCDMeshData mesh;
  4543. decomp->getMeshFromStage(stage, i, &mesh);
  4544. get_vertex_buffer_from_mesh(mesh, mCurRequest->mHullMesh[i]);
  4545. mMutex.lock();
  4546. mCurRequest->mHull[i] = std::move(p);
  4547. mMutex.unlock();
  4548. }
  4549. mMutex.lock();
  4550. mCurRequest->setStatusMessage("FAIL");
  4551. mCompletedQ.push(std::move(mCurRequest));
  4552. mCurRequest = NULL;
  4553. mMutex.unlock();
  4554. }
  4555. }
  4556. void LLPhysicsDecomp::notifyCompleted()
  4557. {
  4558. if (!mCompletedQ.empty())
  4559. {
  4560. mMutex.lock();
  4561. while (!mCompletedQ.empty())
  4562. {
  4563. Request* req = mCompletedQ.front();
  4564. req->completed();
  4565. mCompletedQ.pop();
  4566. }
  4567. mMutex.unlock();
  4568. }
  4569. }
  4570. void make_box(LLPhysicsDecomp::Request* request)
  4571. {
  4572. LLVector3 min = request->mPositions[0];
  4573. LLVector3 max(min);
  4574. for (U32 i = 0; i < request->mPositions.size(); ++i)
  4575. {
  4576. update_min_max(min, max, request->mPositions[i]);
  4577. }
  4578. request->mHull.clear();
  4579. LLModel::hull box;
  4580. box.emplace_back(min[0], min[1], min[2]);
  4581. box.emplace_back(max[0], min[1], min[2]);
  4582. box.emplace_back(min[0], max[1], min[2]);
  4583. box.emplace_back(max[0], max[1], min[2]);
  4584. box.emplace_back(min[0], min[1], max[2]);
  4585. box.emplace_back(max[0], min[1], max[2]);
  4586. box.emplace_back(min[0], max[1], max[2]);
  4587. box.emplace_back(max[0], max[1], max[2]);
  4588. request->mHull.emplace_back(box);
  4589. }
  4590. void LLPhysicsDecomp::doDecompositionSingleHull()
  4591. {
  4592. LLConvexDecomposition* decomp = LLConvexDecomposition::getInstance();
  4593. if (!decomp)
  4594. {
  4595. // Stub. Do nothing.
  4596. return;
  4597. }
  4598. LLCDMeshData mesh;
  4599. setMeshData(mesh, true);
  4600. LLCDResult ret = decomp->buildSingleHull();
  4601. if (ret)
  4602. {
  4603. llwarns << "Could not execute decomposition stage when attempting to create single hull."
  4604. << llendl;
  4605. make_box(mCurRequest);
  4606. }
  4607. else
  4608. {
  4609. mMutex.lock();
  4610. mCurRequest->mHull.clear();
  4611. mCurRequest->mHull.resize(1);
  4612. mCurRequest->mHullMesh.clear();
  4613. mMutex.unlock();
  4614. std::vector<LLVector3> p;
  4615. LLCDHull hull;
  4616. decomp->getSingleHull(&hull);
  4617. const F32* v = hull.mVertexBase;
  4618. for (S32 j = 0; j < hull.mNumVertices; ++j)
  4619. {
  4620. p.emplace_back(v[0], v[1], v[2]);
  4621. v = (F32*)(((U8*)v) + hull.mVertexStrideBytes);
  4622. }
  4623. mMutex.lock();
  4624. mCurRequest->mHull[0] = std::move(p);
  4625. mMutex.unlock();
  4626. }
  4627. mMutex.lock();
  4628. mCompletedQ.push(std::move(mCurRequest));
  4629. mCurRequest = NULL;
  4630. mMutex.unlock();
  4631. }
  4632. void LLPhysicsDecomp::run()
  4633. {
  4634. LLConvexDecomposition* decomp = LLConvexDecomposition::getInstance();
  4635. if (!decomp)
  4636. {
  4637. // Stub library. Set init to true so the main thread does not wait for
  4638. // this to finish.
  4639. mInited = true;
  4640. return;
  4641. }
  4642. decomp->initThread();
  4643. mInited = true;
  4644. static const LLCDStageData* stages = NULL;
  4645. static S32 num_stages = 0;
  4646. if (!stages)
  4647. {
  4648. num_stages = decomp->getStages(&stages);
  4649. }
  4650. for (S32 i = 0; i < num_stages; ++i)
  4651. {
  4652. mStageID[stages[i].mName] = i;
  4653. }
  4654. while (!mQuitting)
  4655. {
  4656. mSignal.wait();
  4657. while (!mQuitting && !mRequestQ.empty())
  4658. {
  4659. mMutex.lock();
  4660. mCurRequest = mRequestQ.front();
  4661. mRequestQ.pop();
  4662. mMutex.unlock();
  4663. S32& id = *(mCurRequest->mDecompID);
  4664. if (id == -1)
  4665. {
  4666. decomp->genDecomposition(id);
  4667. }
  4668. decomp->bindDecomposition(id);
  4669. if (mCurRequest->mStage == "single_hull")
  4670. {
  4671. doDecompositionSingleHull();
  4672. }
  4673. else
  4674. {
  4675. doDecomposition();
  4676. }
  4677. }
  4678. }
  4679. decomp->quitThread();
  4680. if (mSignal.isLocked())
  4681. {
  4682. // Let go of mSignal's associated mutex
  4683. mSignal.unlock();
  4684. }
  4685. mDone = true;
  4686. }
  4687. void LLPhysicsDecomp::Request::assignData(LLModel* mdl)
  4688. {
  4689. if (!mdl)
  4690. {
  4691. return;
  4692. }
  4693. U16 index_offset = 0;
  4694. U16 tri[3];
  4695. mPositions.clear();
  4696. mIndices.clear();
  4697. mBBox[1] = LLVector3(F32_MIN, F32_MIN, F32_MIN);
  4698. mBBox[0] = LLVector3(F32_MAX, F32_MAX, F32_MAX);
  4699. // Queue up vertex positions and indices
  4700. for (S32 i = 0, count = mdl->getNumVolumeFaces(); i < count; ++i)
  4701. {
  4702. const LLVolumeFace& face = mdl->getVolumeFace(i);
  4703. if (mPositions.size() + face.mNumVertices > 65535)
  4704. {
  4705. continue;
  4706. }
  4707. for (S32 j = 0; j < face.mNumVertices; ++j)
  4708. {
  4709. mPositions.emplace_back(face.mPositions[j].getF32ptr());
  4710. for (U32 k = 0; k < 3; ++k)
  4711. {
  4712. mBBox[0].mV[k] = llmin(mBBox[0].mV[k], mPositions[j].mV[k]);
  4713. mBBox[1].mV[k] = llmax(mBBox[1].mV[k], mPositions[j].mV[k]);
  4714. }
  4715. }
  4716. updateTriangleAreaThreshold();
  4717. for (S32 j = 0; j + 2 < face.mNumIndices; )
  4718. {
  4719. tri[0] = face.mIndices[j++] + index_offset;
  4720. tri[1] = face.mIndices[j++] + index_offset;
  4721. tri[2] = face.mIndices[j++] + index_offset;
  4722. if (isValidTriangle(tri[0], tri[1], tri[2]))
  4723. {
  4724. mIndices.push_back(tri[0]);
  4725. mIndices.push_back(tri[1]);
  4726. mIndices.push_back(tri[2]);
  4727. }
  4728. }
  4729. index_offset += face.mNumVertices;
  4730. }
  4731. }
  4732. void LLPhysicsDecomp::Request::updateTriangleAreaThreshold()
  4733. {
  4734. F32 range = mBBox[1].mV[0] - mBBox[0].mV[0];
  4735. range = llmin(range, mBBox[1].mV[1] - mBBox[0].mV[1]);
  4736. range = llmin(range, mBBox[1].mV[2] - mBBox[0].mV[2]);
  4737. mTriangleAreaThreshold = llmin(0.0002f, range * 0.000002f);
  4738. }
  4739. // Checks if the triangle area is large enough to qualify for a valid triangle
  4740. bool LLPhysicsDecomp::Request::isValidTriangle(U16 idx1, U16 idx2, U16 idx3)
  4741. {
  4742. LLVector3 a = mPositions[idx2] - mPositions[idx1];
  4743. LLVector3 b = mPositions[idx3] - mPositions[idx1];
  4744. F32 c = a * b;
  4745. return (a * a) * (b * b) - c * c > mTriangleAreaThreshold;
  4746. }
  4747. void LLPhysicsDecomp::Request::setStatusMessage(const std::string& msg)
  4748. {
  4749. mStatusMessage = msg;
  4750. }