gltf_document.cpp 236 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008
  1. /**************************************************************************/
  2. /* gltf_document.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "gltf_document.h"
  31. #include "extensions/gltf_spec_gloss.h"
  32. #include "gltf_state.h"
  33. #include "core/bind/core_bind.h" // FIXME: Shouldn't use _Directory but DirAccess.
  34. #include "core/crypto/crypto_core.h"
  35. #include "core/io/json.h"
  36. #include "core/math/disjoint_set.h"
  37. #include "core/os/file_access.h"
  38. #include "core/variant.h"
  39. #include "core/version.h"
  40. #include "drivers/png/png_driver_common.h"
  41. #include "scene/2d/node_2d.h"
  42. #include "scene/3d/bone_attachment.h"
  43. #include "scene/3d/mesh_instance.h"
  44. #include "scene/3d/multimesh_instance.h"
  45. #include "scene/3d/spatial.h"
  46. #include "scene/animation/animation_player.h"
  47. #include "scene/main/node.h"
  48. #include "scene/resources/surface_tool.h"
  49. #include "modules/modules_enabled.gen.h" // For csg, gridmap, regex.
  50. #ifdef MODULE_CSG_ENABLED
  51. #include "modules/csg/csg_shape.h"
  52. #endif // MODULE_CSG_ENABLED
  53. #ifdef MODULE_GRIDMAP_ENABLED
  54. #include "modules/gridmap/grid_map.h"
  55. #endif // MODULE_GRIDMAP_ENABLED
  56. #ifdef MODULE_REGEX_ENABLED
  57. #include "modules/regex/regex.h"
  58. #endif // MODULE_REGEX_ENABLED
  59. Ref<ArrayMesh> _mesh_to_array_mesh(Ref<Mesh> p_mesh) {
  60. Ref<ArrayMesh> array_mesh = p_mesh;
  61. if (array_mesh.is_valid()) {
  62. return array_mesh;
  63. }
  64. array_mesh.instance();
  65. if (p_mesh.is_null()) {
  66. return array_mesh;
  67. }
  68. for (int32_t surface_i = 0; surface_i < p_mesh->get_surface_count(); surface_i++) {
  69. Mesh::PrimitiveType primitive_type = p_mesh->surface_get_primitive_type(surface_i);
  70. Array arrays = p_mesh->surface_get_arrays(surface_i);
  71. Ref<Material> mat = p_mesh->surface_get_material(surface_i);
  72. int32_t mat_idx = array_mesh->get_surface_count();
  73. array_mesh->add_surface_from_arrays(primitive_type, arrays);
  74. array_mesh->surface_set_material(mat_idx, mat);
  75. }
  76. return array_mesh;
  77. }
  78. Error GLTFDocument::serialize(Ref<GLTFState> p_state, Node *p_root, const String &p_path) {
  79. uint64_t begin_time = OS::get_singleton()->get_ticks_usec();
  80. p_state->skeleton3d_to_gltf_skeleton.clear();
  81. p_state->skin_and_skeleton3d_to_gltf_skin.clear();
  82. document_extensions.clear();
  83. for (int ext_i = 0; ext_i < all_document_extensions.size(); ext_i++) {
  84. Ref<GLTFDocumentExtension> ext = all_document_extensions[ext_i];
  85. ERR_CONTINUE(ext.is_null());
  86. Error err = ext->export_preflight(p_state, p_root);
  87. if (err == OK) {
  88. document_extensions.push_back(ext);
  89. }
  90. }
  91. _convert_scene_node(p_state, p_root, -1, -1);
  92. if (!p_state->buffers.size()) {
  93. p_state->buffers.push_back(Vector<uint8_t>());
  94. }
  95. /* STEP 1 CONVERT MESH INSTANCES */
  96. _convert_mesh_instances(p_state);
  97. /* STEP 2 SERIALIZE CAMERAS */
  98. Error err = _serialize_cameras(p_state);
  99. if (err != OK) {
  100. return Error::FAILED;
  101. }
  102. /* STEP 3 CREATE SKINS */
  103. err = _serialize_skins(p_state);
  104. if (err != OK) {
  105. return Error::FAILED;
  106. }
  107. /* STEP 5 SERIALIZE MESHES (we have enough info now) */
  108. err = _serialize_meshes(p_state);
  109. if (err != OK) {
  110. return Error::FAILED;
  111. }
  112. /* STEP 6 SERIALIZE TEXTURES */
  113. err = _serialize_materials(p_state);
  114. if (err != OK) {
  115. return Error::FAILED;
  116. }
  117. /* STEP 7 SERIALIZE TEXTURE SAMPLERS */
  118. err = _serialize_texture_samplers(p_state);
  119. if (err != OK) {
  120. return Error::FAILED;
  121. }
  122. /* STEP 8 SERIALIZE ANIMATIONS */
  123. err = _serialize_animations(p_state);
  124. if (err != OK) {
  125. return Error::FAILED;
  126. }
  127. /* STEP 9 SERIALIZE ACCESSORS */
  128. err = _encode_accessors(p_state);
  129. if (err != OK) {
  130. return Error::FAILED;
  131. }
  132. /* STEP 10 SERIALIZE IMAGES */
  133. err = _serialize_images(p_state, p_path);
  134. if (err != OK) {
  135. return Error::FAILED;
  136. }
  137. for (GLTFBufferViewIndex i = 0; i < p_state->buffer_views.size(); i++) {
  138. p_state->buffer_views.write[i]->buffer = 0;
  139. }
  140. /* STEP 12 SERIALIZE BUFFER VIEWS */
  141. err = _encode_buffer_views(p_state);
  142. if (err != OK) {
  143. return Error::FAILED;
  144. }
  145. /* STEP 13 SERIALIZE NODES */
  146. err = _serialize_nodes(p_state);
  147. if (err != OK) {
  148. return Error::FAILED;
  149. }
  150. /* STEP 15 SERIALIZE SCENE */
  151. err = _serialize_scenes(p_state);
  152. if (err != OK) {
  153. return Error::FAILED;
  154. }
  155. /* STEP 16 SERIALIZE SCENE */
  156. err = _serialize_lights(p_state);
  157. if (err != OK) {
  158. return Error::FAILED;
  159. }
  160. /* STEP 17 SERIALIZE EXTENSIONS */
  161. err = _serialize_gltf_extensions(p_state);
  162. if (err != OK) {
  163. return Error::FAILED;
  164. }
  165. /* STEP 18 SERIALIZE VERSION */
  166. err = _serialize_version(p_state);
  167. if (err != OK) {
  168. return Error::FAILED;
  169. }
  170. /* STEP 19 SERIALIZE FILE */
  171. err = _serialize_file(p_state, p_path);
  172. if (err != OK) {
  173. return Error::FAILED;
  174. }
  175. for (int ext_i = 0; ext_i < document_extensions.size(); ext_i++) {
  176. Ref<GLTFDocumentExtension> ext = document_extensions[ext_i];
  177. ERR_CONTINUE(ext.is_null());
  178. err = ext->export_post(p_state);
  179. ERR_FAIL_COND_V(err != OK, err);
  180. }
  181. uint64_t elapsed = OS::get_singleton()->get_ticks_usec() - begin_time;
  182. float elapsed_sec = double(elapsed) / 1000000.0;
  183. elapsed_sec = Math::stepify(elapsed_sec, 0.01f);
  184. print_line("glTF: Export time elapsed seconds " + rtos(elapsed_sec).pad_decimals(2));
  185. return OK;
  186. }
  187. Error GLTFDocument::_serialize_gltf_extensions(Ref<GLTFState> p_state) const {
  188. Vector<String> extensions_used = p_state->extensions_used;
  189. Vector<String> extensions_required = p_state->extensions_required;
  190. if (!p_state->lights.empty()) {
  191. extensions_used.push_back("KHR_lights_punctual");
  192. }
  193. if (p_state->use_khr_texture_transform) {
  194. extensions_used.push_back("KHR_texture_transform");
  195. extensions_required.push_back("KHR_texture_transform");
  196. }
  197. if (!extensions_used.empty()) {
  198. extensions_used.sort();
  199. p_state->json["extensionsUsed"] = extensions_used;
  200. }
  201. if (!extensions_required.empty()) {
  202. extensions_required.sort();
  203. p_state->json["extensionsRequired"] = extensions_required;
  204. }
  205. return OK;
  206. }
  207. Error GLTFDocument::_serialize_scenes(Ref<GLTFState> p_state) {
  208. Array scenes;
  209. const int loaded_scene = 0;
  210. p_state->json["scene"] = loaded_scene;
  211. if (p_state->nodes.size()) {
  212. Dictionary s;
  213. if (!p_state->scene_name.empty()) {
  214. s["name"] = p_state->scene_name;
  215. }
  216. Array nodes;
  217. nodes.push_back(0);
  218. s["nodes"] = nodes;
  219. scenes.push_back(s);
  220. }
  221. p_state->json["scenes"] = scenes;
  222. return OK;
  223. }
  224. Error GLTFDocument::_parse_json(const String &p_path, Ref<GLTFState> p_state) {
  225. Error err;
  226. FileAccessRef file = FileAccess::open(p_path, FileAccess::READ, &err);
  227. if (!file) {
  228. return err;
  229. }
  230. Vector<uint8_t> array;
  231. array.resize(file->get_len());
  232. file->get_buffer(array.ptrw(), array.size());
  233. String text;
  234. text.parse_utf8((const char *)array.ptr(), array.size());
  235. String err_txt;
  236. int err_line;
  237. Variant v;
  238. err = JSON::parse(text, v, err_txt, err_line);
  239. if (err != OK) {
  240. _err_print_error("", p_path.utf8().get_data(), err_line, err_txt.utf8().get_data(), ERR_HANDLER_SCRIPT);
  241. return err;
  242. }
  243. p_state->json = v;
  244. return OK;
  245. }
  246. Error GLTFDocument::_parse_glb(const String &p_path, Ref<GLTFState> p_state) {
  247. Error err;
  248. FileAccessRef file = FileAccess::open(p_path, FileAccess::READ, &err);
  249. if (!file) {
  250. return err;
  251. }
  252. uint32_t magic = file->get_32();
  253. ERR_FAIL_COND_V(magic != 0x46546C67, ERR_FILE_UNRECOGNIZED); //glTF
  254. file->get_32(); // version
  255. file->get_32(); // length
  256. uint32_t chunk_length = file->get_32();
  257. uint32_t chunk_type = file->get_32();
  258. ERR_FAIL_COND_V(chunk_type != 0x4E4F534A, ERR_PARSE_ERROR); //JSON
  259. Vector<uint8_t> json_data;
  260. json_data.resize(chunk_length);
  261. uint32_t len = file->get_buffer(json_data.ptrw(), chunk_length);
  262. ERR_FAIL_COND_V(len != chunk_length, ERR_FILE_CORRUPT);
  263. String text;
  264. text.parse_utf8((const char *)json_data.ptr(), json_data.size());
  265. String err_txt;
  266. int err_line;
  267. Variant v;
  268. err = JSON::parse(text, v, err_txt, err_line);
  269. if (err != OK) {
  270. _err_print_error("", p_path.utf8().get_data(), err_line, err_txt.utf8().get_data(), ERR_HANDLER_SCRIPT);
  271. return err;
  272. }
  273. p_state->json = v;
  274. //data?
  275. chunk_length = file->get_32();
  276. chunk_type = file->get_32();
  277. if (file->eof_reached()) {
  278. return OK; //all good
  279. }
  280. ERR_FAIL_COND_V(chunk_type != 0x004E4942, ERR_PARSE_ERROR); //BIN
  281. p_state->glb_data.resize(chunk_length);
  282. len = file->get_buffer(p_state->glb_data.ptrw(), chunk_length);
  283. ERR_FAIL_COND_V(len != chunk_length, ERR_FILE_CORRUPT);
  284. return OK;
  285. }
  286. static Array _vec3_to_arr(const Vector3 &p_vec3) {
  287. Array array;
  288. array.resize(3);
  289. array[0] = p_vec3.x;
  290. array[1] = p_vec3.y;
  291. array[2] = p_vec3.z;
  292. return array;
  293. }
  294. static Vector3 _arr_to_vec3(const Array &p_array) {
  295. ERR_FAIL_COND_V(p_array.size() != 3, Vector3());
  296. return Vector3(p_array[0], p_array[1], p_array[2]);
  297. }
  298. static Array _quat_to_array(const Quat &p_quat) {
  299. Array array;
  300. array.resize(4);
  301. array[0] = p_quat.x;
  302. array[1] = p_quat.y;
  303. array[2] = p_quat.z;
  304. array[3] = p_quat.w;
  305. return array;
  306. }
  307. static Quat _arr_to_quat(const Array &p_array) {
  308. ERR_FAIL_COND_V(p_array.size() != 4, Quat());
  309. return Quat(p_array[0], p_array[1], p_array[2], p_array[3]);
  310. }
  311. static Transform _arr_to_xform(const Array &p_array) {
  312. ERR_FAIL_COND_V(p_array.size() != 16, Transform());
  313. Transform xform;
  314. xform.basis.set_axis(Vector3::AXIS_X, Vector3(p_array[0], p_array[1], p_array[2]));
  315. xform.basis.set_axis(Vector3::AXIS_Y, Vector3(p_array[4], p_array[5], p_array[6]));
  316. xform.basis.set_axis(Vector3::AXIS_Z, Vector3(p_array[8], p_array[9], p_array[10]));
  317. xform.set_origin(Vector3(p_array[12], p_array[13], p_array[14]));
  318. return xform;
  319. }
  320. static Vector<real_t> _xform_to_array(const Transform p_transform) {
  321. Vector<real_t> array;
  322. array.resize(16);
  323. Vector3 axis_x = p_transform.get_basis().get_axis(Vector3::AXIS_X);
  324. array.write[0] = axis_x.x;
  325. array.write[1] = axis_x.y;
  326. array.write[2] = axis_x.z;
  327. array.write[3] = 0.0f;
  328. Vector3 axis_y = p_transform.get_basis().get_axis(Vector3::AXIS_Y);
  329. array.write[4] = axis_y.x;
  330. array.write[5] = axis_y.y;
  331. array.write[6] = axis_y.z;
  332. array.write[7] = 0.0f;
  333. Vector3 axis_z = p_transform.get_basis().get_axis(Vector3::AXIS_Z);
  334. array.write[8] = axis_z.x;
  335. array.write[9] = axis_z.y;
  336. array.write[10] = axis_z.z;
  337. array.write[11] = 0.0f;
  338. Vector3 origin = p_transform.get_origin();
  339. array.write[12] = origin.x;
  340. array.write[13] = origin.y;
  341. array.write[14] = origin.z;
  342. array.write[15] = 1.0f;
  343. return array;
  344. }
  345. Error GLTFDocument::_serialize_nodes(Ref<GLTFState> p_state) {
  346. Array nodes;
  347. for (int i = 0; i < p_state->nodes.size(); i++) {
  348. Dictionary node;
  349. Ref<GLTFNode> gltf_node = p_state->nodes[i];
  350. Dictionary extensions;
  351. node["extensions"] = extensions;
  352. if (!gltf_node->get_name().empty()) {
  353. node["name"] = gltf_node->get_name();
  354. }
  355. if (gltf_node->camera != -1) {
  356. node["camera"] = gltf_node->camera;
  357. }
  358. if (gltf_node->light != -1) {
  359. Dictionary lights_punctual;
  360. extensions["KHR_lights_punctual"] = lights_punctual;
  361. lights_punctual["light"] = gltf_node->light;
  362. }
  363. if (gltf_node->mesh != -1) {
  364. node["mesh"] = gltf_node->mesh;
  365. }
  366. if (gltf_node->skin != -1) {
  367. node["skin"] = gltf_node->skin;
  368. }
  369. if (gltf_node->skeleton != -1 && gltf_node->skin < 0) {
  370. }
  371. if (gltf_node->xform != Transform()) {
  372. node["matrix"] = _xform_to_array(gltf_node->xform);
  373. }
  374. if (!gltf_node->rotation.is_equal_approx(Quat())) {
  375. node["rotation"] = _quat_to_array(gltf_node->rotation);
  376. }
  377. if (!gltf_node->scale.is_equal_approx(Vector3(1.0f, 1.0f, 1.0f))) {
  378. node["scale"] = _vec3_to_arr(gltf_node->scale);
  379. }
  380. if (!gltf_node->translation.is_zero_approx()) {
  381. node["translation"] = _vec3_to_arr(gltf_node->translation);
  382. }
  383. if (gltf_node->children.size()) {
  384. Array children;
  385. for (int j = 0; j < gltf_node->children.size(); j++) {
  386. children.push_back(gltf_node->children[j]);
  387. }
  388. node["children"] = children;
  389. }
  390. for (int ext_i = 0; ext_i < document_extensions.size(); ext_i++) {
  391. Ref<GLTFDocumentExtension> ext = document_extensions[ext_i];
  392. ERR_CONTINUE(ext.is_null());
  393. ERR_CONTINUE(!p_state->scene_nodes.find(i));
  394. Error err = ext->export_node(p_state, gltf_node, node, p_state->scene_nodes[i]);
  395. ERR_CONTINUE(err != OK);
  396. }
  397. nodes.push_back(node);
  398. }
  399. p_state->json["nodes"] = nodes;
  400. return OK;
  401. }
  402. String GLTFDocument::_sanitize_scene_name(Ref<GLTFState> p_state, const String &p_name) {
  403. if (p_state->use_legacy_names) {
  404. #ifdef MODULE_REGEX_ENABLED
  405. RegEx regex("([^a-zA-Z0-9_ -]+)");
  406. String s_name = regex.sub(p_name, "", true);
  407. return s_name;
  408. #else
  409. WARN_PRINT("GLTF: Legacy scene names are not supported without the RegEx module. Falling back to new names.");
  410. #endif // MODULE_REGEX_ENABLED
  411. }
  412. return p_name.validate_node_name();
  413. }
  414. String GLTFDocument::_legacy_validate_node_name(const String &p_name) {
  415. String invalid_character = ". : @ / \"";
  416. String name = p_name;
  417. Vector<String> chars = invalid_character.split(" ");
  418. for (int i = 0; i < chars.size(); i++) {
  419. name = name.replace(chars[i], "");
  420. }
  421. return name;
  422. }
  423. String GLTFDocument::_gen_unique_name(Ref<GLTFState> p_state, const String &p_name) {
  424. const String s_name = _sanitize_scene_name(p_state, p_name);
  425. String name;
  426. int index = 1;
  427. while (true) {
  428. name = s_name;
  429. if (index > 1) {
  430. if (p_state->use_legacy_names) {
  431. name += " ";
  432. }
  433. name += itos(index);
  434. }
  435. if (!p_state->unique_names.has(name)) {
  436. break;
  437. }
  438. index++;
  439. }
  440. p_state->unique_names.insert(name);
  441. return name;
  442. }
  443. String GLTFDocument::_sanitize_animation_name(const String &p_name) {
  444. // Animations disallow the normal node invalid characters as well as "," and "["
  445. // (See animation/animation_player.cpp::add_animation)
  446. // TODO: Consider adding invalid_characters or a validate_animation_name to animation_player to mirror Node.
  447. String name = p_name.validate_node_name();
  448. name = name.replace(",", "");
  449. name = name.replace("[", "");
  450. return name;
  451. }
  452. String GLTFDocument::_gen_unique_animation_name(Ref<GLTFState> p_state, const String &p_name) {
  453. const String s_name = _sanitize_animation_name(p_name);
  454. String name;
  455. int index = 1;
  456. while (true) {
  457. name = s_name;
  458. if (index > 1) {
  459. name += itos(index);
  460. }
  461. if (!p_state->unique_animation_names.has(name)) {
  462. break;
  463. }
  464. index++;
  465. }
  466. p_state->unique_animation_names.insert(name);
  467. return name;
  468. }
  469. String GLTFDocument::_sanitize_bone_name(Ref<GLTFState> p_state, const String &p_name) {
  470. if (p_state->use_legacy_names) {
  471. #ifdef MODULE_REGEX_ENABLED
  472. String name = p_name.camelcase_to_underscore(true);
  473. RegEx pattern_del("([^a-zA-Z0-9_ ])+");
  474. name = pattern_del.sub(name, "", true);
  475. RegEx pattern_nospace(" +");
  476. name = pattern_nospace.sub(name, "_", true);
  477. RegEx pattern_multiple("_+");
  478. name = pattern_multiple.sub(name, "_", true);
  479. RegEx pattern_padded("0+(\\d+)");
  480. name = pattern_padded.sub(name, "$1", true);
  481. return name;
  482. #else
  483. WARN_PRINT("GLTF: Legacy bone names are not supported without the RegEx module. Falling back to new names.");
  484. #endif // MODULE_REGEX_ENABLED
  485. }
  486. String name = p_name;
  487. name = name.replace(":", "_");
  488. name = name.replace("/", "_");
  489. if (name.empty()) {
  490. name = "bone";
  491. }
  492. return name;
  493. }
  494. String GLTFDocument::_gen_unique_bone_name(Ref<GLTFState> p_state, const GLTFSkeletonIndex p_skel_i, const String &p_name) {
  495. String s_name = _sanitize_bone_name(p_state, p_name);
  496. String name;
  497. int index = 1;
  498. while (true) {
  499. name = s_name;
  500. if (index > 1) {
  501. name += "_" + itos(index);
  502. }
  503. if (!p_state->skeletons[p_skel_i]->unique_names.has(name)) {
  504. break;
  505. }
  506. index++;
  507. }
  508. p_state->skeletons.write[p_skel_i]->unique_names.insert(name);
  509. return name;
  510. }
  511. Error GLTFDocument::_parse_scenes(Ref<GLTFState> p_state) {
  512. ERR_FAIL_COND_V(!p_state->json.has("scenes"), ERR_FILE_CORRUPT);
  513. const Array &scenes = p_state->json["scenes"];
  514. int loaded_scene = 0;
  515. if (p_state->json.has("scene")) {
  516. loaded_scene = p_state->json["scene"];
  517. } else {
  518. WARN_PRINT("The load-time scene is not defined in the glTF2 file. Picking the first scene.");
  519. }
  520. if (scenes.size()) {
  521. ERR_FAIL_COND_V(loaded_scene >= scenes.size(), ERR_FILE_CORRUPT);
  522. const Dictionary &s = scenes[loaded_scene];
  523. ERR_FAIL_COND_V(!s.has("nodes"), ERR_UNAVAILABLE);
  524. const Array &nodes = s["nodes"];
  525. for (int j = 0; j < nodes.size(); j++) {
  526. p_state->root_nodes.push_back(nodes[j]);
  527. }
  528. if (s.has("name") && !String(s["name"]).empty() && !((String)s["name"]).begins_with("Scene")) {
  529. p_state->scene_name = s["name"];
  530. } else {
  531. p_state->scene_name = p_state->filename;
  532. }
  533. }
  534. return OK;
  535. }
  536. Error GLTFDocument::_parse_nodes(Ref<GLTFState> p_state) {
  537. ERR_FAIL_COND_V(!p_state->json.has("nodes"), ERR_FILE_CORRUPT);
  538. const Array &nodes = p_state->json["nodes"];
  539. for (int i = 0; i < nodes.size(); i++) {
  540. Ref<GLTFNode> node;
  541. node.instance();
  542. const Dictionary &n = nodes[i];
  543. if (n.has("name")) {
  544. node->set_name(n["name"]);
  545. }
  546. if (n.has("camera")) {
  547. node->camera = n["camera"];
  548. }
  549. if (n.has("mesh")) {
  550. node->mesh = n["mesh"];
  551. }
  552. if (n.has("skin")) {
  553. node->skin = n["skin"];
  554. }
  555. if (n.has("matrix")) {
  556. node->xform = _arr_to_xform(n["matrix"]);
  557. } else {
  558. if (n.has("translation")) {
  559. node->translation = _arr_to_vec3(n["translation"]);
  560. }
  561. if (n.has("rotation")) {
  562. node->rotation = _arr_to_quat(n["rotation"]);
  563. }
  564. if (n.has("scale")) {
  565. node->scale = _arr_to_vec3(n["scale"]);
  566. }
  567. node->xform.basis.set_quat_scale(node->rotation, node->scale);
  568. node->xform.origin = node->translation;
  569. }
  570. if (n.has("extensions")) {
  571. Dictionary extensions = n["extensions"];
  572. if (extensions.has("KHR_lights_punctual")) {
  573. Dictionary lights_punctual = extensions["KHR_lights_punctual"];
  574. if (lights_punctual.has("light")) {
  575. GLTFLightIndex light = lights_punctual["light"];
  576. node->light = light;
  577. }
  578. }
  579. for (int ext_i = 0; ext_i < document_extensions.size(); ext_i++) {
  580. Ref<GLTFDocumentExtension> ext = document_extensions[ext_i];
  581. ERR_CONTINUE(ext.is_null());
  582. Error err = ext->parse_node_extensions(p_state, node, extensions);
  583. ERR_CONTINUE_MSG(err != OK, "GLTF: Encountered error " + itos(err) + " when parsing node extensions for node " + node->get_name() + " in file " + p_state->filename + ". Continuing.");
  584. }
  585. }
  586. if (n.has("children")) {
  587. const Array &children = n["children"];
  588. for (int j = 0; j < children.size(); j++) {
  589. node->children.push_back(children[j]);
  590. }
  591. }
  592. p_state->nodes.push_back(node);
  593. }
  594. // build the hierarchy
  595. for (GLTFNodeIndex node_i = 0; node_i < p_state->nodes.size(); node_i++) {
  596. for (int j = 0; j < p_state->nodes[node_i]->children.size(); j++) {
  597. GLTFNodeIndex child_i = p_state->nodes[node_i]->children[j];
  598. ERR_FAIL_INDEX_V(child_i, p_state->nodes.size(), ERR_FILE_CORRUPT);
  599. ERR_CONTINUE(p_state->nodes[child_i]->parent != -1); //node already has a parent, wtf.
  600. p_state->nodes.write[child_i]->parent = node_i;
  601. }
  602. }
  603. _compute_node_heights(p_state);
  604. return OK;
  605. }
  606. void GLTFDocument::_compute_node_heights(Ref<GLTFState> p_state) {
  607. p_state->root_nodes.clear();
  608. for (GLTFNodeIndex node_i = 0; node_i < p_state->nodes.size(); ++node_i) {
  609. Ref<GLTFNode> node = p_state->nodes[node_i];
  610. node->height = 0;
  611. GLTFNodeIndex current_i = node_i;
  612. while (current_i >= 0) {
  613. const GLTFNodeIndex parent_i = p_state->nodes[current_i]->parent;
  614. if (parent_i >= 0) {
  615. ++node->height;
  616. }
  617. current_i = parent_i;
  618. }
  619. if (node->height == 0) {
  620. p_state->root_nodes.push_back(node_i);
  621. }
  622. }
  623. }
  624. static Vector<uint8_t> _parse_base64_uri(const String &uri) {
  625. int start = uri.find(",");
  626. ERR_FAIL_COND_V(start == -1, Vector<uint8_t>());
  627. CharString substr = uri.right(start + 1).ascii();
  628. int strlen = substr.length();
  629. Vector<uint8_t> buf;
  630. buf.resize(strlen / 4 * 3 + 1 + 1);
  631. size_t len = 0;
  632. ERR_FAIL_COND_V(CryptoCore::b64_decode(buf.ptrw(), buf.size(), &len, (unsigned char *)substr.get_data(), strlen) != OK, Vector<uint8_t>());
  633. buf.resize(len);
  634. return buf;
  635. }
  636. Error GLTFDocument::_encode_buffer_glb(Ref<GLTFState> p_state, const String &p_path) {
  637. print_verbose("glTF: Total buffers: " + itos(p_state->buffers.size()));
  638. if (!p_state->buffers.size()) {
  639. return OK;
  640. }
  641. Array buffers;
  642. if (p_state->buffers.size()) {
  643. Vector<uint8_t> buffer_data = p_state->buffers[0];
  644. Dictionary gltf_buffer;
  645. gltf_buffer["byteLength"] = buffer_data.size();
  646. buffers.push_back(gltf_buffer);
  647. }
  648. for (GLTFBufferIndex i = 1; i < p_state->buffers.size() - 1; i++) {
  649. Vector<uint8_t> buffer_data = p_state->buffers[i];
  650. Dictionary gltf_buffer;
  651. String filename = p_path.get_basename().get_file() + itos(i) + ".bin";
  652. String path = p_path.get_base_dir() + "/" + filename;
  653. Error err;
  654. FileAccessRef file = FileAccess::open(path, FileAccess::WRITE, &err);
  655. if (!file) {
  656. return err;
  657. }
  658. if (buffer_data.size() == 0) {
  659. return OK;
  660. }
  661. file->create(FileAccess::ACCESS_RESOURCES);
  662. file->store_buffer(buffer_data.ptr(), buffer_data.size());
  663. file->close();
  664. gltf_buffer["uri"] = filename;
  665. gltf_buffer["byteLength"] = buffer_data.size();
  666. buffers.push_back(gltf_buffer);
  667. }
  668. if (!buffers.size()) {
  669. return OK;
  670. }
  671. p_state->json["buffers"] = buffers;
  672. return OK;
  673. }
  674. Error GLTFDocument::_encode_buffer_bins(Ref<GLTFState> p_state, const String &p_path) {
  675. print_verbose("glTF: Total buffers: " + itos(p_state->buffers.size()));
  676. if (!p_state->buffers.size()) {
  677. return OK;
  678. }
  679. Array buffers;
  680. for (GLTFBufferIndex i = 0; i < p_state->buffers.size(); i++) {
  681. Vector<uint8_t> buffer_data = p_state->buffers[i];
  682. Dictionary gltf_buffer;
  683. String filename = p_path.get_basename().get_file() + itos(i) + ".bin";
  684. String path = p_path.get_base_dir() + "/" + filename;
  685. Error err;
  686. FileAccessRef file = FileAccess::open(path, FileAccess::WRITE, &err);
  687. if (!file) {
  688. return err;
  689. }
  690. if (buffer_data.size() == 0) {
  691. return OK;
  692. }
  693. file->create(FileAccess::ACCESS_RESOURCES);
  694. file->store_buffer(buffer_data.ptr(), buffer_data.size());
  695. file->close();
  696. gltf_buffer["uri"] = filename;
  697. gltf_buffer["byteLength"] = buffer_data.size();
  698. buffers.push_back(gltf_buffer);
  699. }
  700. p_state->json["buffers"] = buffers;
  701. return OK;
  702. }
  703. Error GLTFDocument::_parse_buffers(Ref<GLTFState> p_state, const String &p_base_path) {
  704. if (!p_state->json.has("buffers")) {
  705. return OK;
  706. }
  707. const Array &buffers = p_state->json["buffers"];
  708. for (GLTFBufferIndex i = 0; i < buffers.size(); i++) {
  709. if (i == 0 && p_state->glb_data.size()) {
  710. p_state->buffers.push_back(p_state->glb_data);
  711. } else {
  712. const Dictionary &buffer = buffers[i];
  713. if (buffer.has("uri")) {
  714. Vector<uint8_t> buffer_data;
  715. String uri = buffer["uri"];
  716. if (uri.begins_with("data:")) { // Embedded data using base64.
  717. // Validate data MIME types and throw an error if it's one we don't know/support.
  718. if (!uri.begins_with("data:application/octet-stream;base64") &&
  719. !uri.begins_with("data:application/gltf-buffer;base64")) {
  720. ERR_PRINT("glTF: Got buffer with an unknown URI data type: " + uri);
  721. }
  722. buffer_data = _parse_base64_uri(uri);
  723. } else { // Relative path to an external image file.
  724. uri = uri.http_unescape();
  725. uri = p_base_path.plus_file(uri).replace("\\", "/"); // Fix for Windows.
  726. buffer_data = FileAccess::get_file_as_array(uri);
  727. ERR_FAIL_COND_V_MSG(buffer.size() == 0, ERR_PARSE_ERROR, "glTF: Couldn't load binary file as an array: " + uri);
  728. }
  729. ERR_FAIL_COND_V(!buffer.has("byteLength"), ERR_PARSE_ERROR);
  730. int byteLength = buffer["byteLength"];
  731. ERR_FAIL_COND_V(byteLength < buffer_data.size(), ERR_PARSE_ERROR);
  732. p_state->buffers.push_back(buffer_data);
  733. }
  734. }
  735. }
  736. print_verbose("glTF: Total buffers: " + itos(p_state->buffers.size()));
  737. return OK;
  738. }
  739. Error GLTFDocument::_encode_buffer_views(Ref<GLTFState> p_state) {
  740. Array buffers;
  741. for (GLTFBufferViewIndex i = 0; i < p_state->buffer_views.size(); i++) {
  742. Dictionary d;
  743. Ref<GLTFBufferView> buffer_view = p_state->buffer_views[i];
  744. d["buffer"] = buffer_view->buffer;
  745. d["byteLength"] = buffer_view->byte_length;
  746. d["byteOffset"] = buffer_view->byte_offset;
  747. if (buffer_view->byte_stride != -1) {
  748. d["byteStride"] = buffer_view->byte_stride;
  749. }
  750. // TODO Sparse
  751. // d["target"] = buffer_view->indices;
  752. ERR_FAIL_COND_V(!d.has("buffer"), ERR_INVALID_DATA);
  753. ERR_FAIL_COND_V(!d.has("byteLength"), ERR_INVALID_DATA);
  754. buffers.push_back(d);
  755. }
  756. print_verbose("glTF: Total buffer views: " + itos(p_state->buffer_views.size()));
  757. if (!buffers.size()) {
  758. return OK;
  759. }
  760. p_state->json["bufferViews"] = buffers;
  761. return OK;
  762. }
  763. Error GLTFDocument::_parse_buffer_views(Ref<GLTFState> p_state) {
  764. if (!p_state->json.has("bufferViews")) {
  765. return OK;
  766. }
  767. const Array &buffers = p_state->json["bufferViews"];
  768. for (GLTFBufferViewIndex i = 0; i < buffers.size(); i++) {
  769. const Dictionary &d = buffers[i];
  770. Ref<GLTFBufferView> buffer_view;
  771. buffer_view.instance();
  772. ERR_FAIL_COND_V(!d.has("buffer"), ERR_PARSE_ERROR);
  773. buffer_view->buffer = d["buffer"];
  774. ERR_FAIL_COND_V(!d.has("byteLength"), ERR_PARSE_ERROR);
  775. buffer_view->byte_length = d["byteLength"];
  776. if (d.has("byteOffset")) {
  777. buffer_view->byte_offset = d["byteOffset"];
  778. }
  779. if (d.has("byteStride")) {
  780. buffer_view->byte_stride = d["byteStride"];
  781. }
  782. if (d.has("target")) {
  783. const int target = d["target"];
  784. buffer_view->indices = target == GLTFDocument::ELEMENT_ARRAY_BUFFER;
  785. }
  786. p_state->buffer_views.push_back(buffer_view);
  787. }
  788. print_verbose("glTF: Total buffer views: " + itos(p_state->buffer_views.size()));
  789. return OK;
  790. }
  791. Error GLTFDocument::_encode_accessors(Ref<GLTFState> p_state) {
  792. Array accessors;
  793. for (GLTFAccessorIndex i = 0; i < p_state->accessors.size(); i++) {
  794. Dictionary d;
  795. Ref<GLTFAccessor> accessor = p_state->accessors[i];
  796. d["componentType"] = accessor->component_type;
  797. d["count"] = accessor->count;
  798. d["type"] = _get_accessor_type_name(accessor->type);
  799. d["byteOffset"] = accessor->byte_offset;
  800. d["normalized"] = accessor->normalized;
  801. Array max;
  802. max.resize(accessor->max.size());
  803. for (int32_t max_i = 0; max_i < max.size(); max_i++) {
  804. max[max_i] = accessor->max[max_i];
  805. }
  806. d["max"] = max;
  807. Array min;
  808. min.resize(accessor->min.size());
  809. for (int32_t min_i = 0; min_i < min.size(); min_i++) {
  810. min[min_i] = accessor->min[min_i];
  811. }
  812. d["min"] = min;
  813. d["bufferView"] = accessor->buffer_view; //optional because it may be sparse...
  814. // Dictionary s;
  815. // s["count"] = accessor->sparse_count;
  816. // ERR_FAIL_COND_V(!s.has("count"), ERR_PARSE_ERROR);
  817. // s["indices"] = accessor->sparse_accessors;
  818. // ERR_FAIL_COND_V(!s.has("indices"), ERR_PARSE_ERROR);
  819. // Dictionary si;
  820. // si["bufferView"] = accessor->sparse_indices_buffer_view;
  821. // ERR_FAIL_COND_V(!si.has("bufferView"), ERR_PARSE_ERROR);
  822. // si["componentType"] = accessor->sparse_indices_component_type;
  823. // if (si.has("byteOffset")) {
  824. // si["byteOffset"] = accessor->sparse_indices_byte_offset;
  825. // }
  826. // ERR_FAIL_COND_V(!si.has("componentType"), ERR_PARSE_ERROR);
  827. // s["indices"] = si;
  828. // Dictionary sv;
  829. // sv["bufferView"] = accessor->sparse_values_buffer_view;
  830. // if (sv.has("byteOffset")) {
  831. // sv["byteOffset"] = accessor->sparse_values_byte_offset;
  832. // }
  833. // ERR_FAIL_COND_V(!sv.has("bufferView"), ERR_PARSE_ERROR);
  834. // s["values"] = sv;
  835. // ERR_FAIL_COND_V(!s.has("values"), ERR_PARSE_ERROR);
  836. // d["sparse"] = s;
  837. accessors.push_back(d);
  838. }
  839. if (!accessors.size()) {
  840. return OK;
  841. }
  842. p_state->json["accessors"] = accessors;
  843. ERR_FAIL_COND_V(!p_state->json.has("accessors"), ERR_FILE_CORRUPT);
  844. print_verbose("glTF: Total accessors: " + itos(p_state->accessors.size()));
  845. return OK;
  846. }
  847. String GLTFDocument::_get_accessor_type_name(const GLTFType p_type) {
  848. if (p_type == GLTFType::TYPE_SCALAR) {
  849. return "SCALAR";
  850. }
  851. if (p_type == GLTFType::TYPE_VEC2) {
  852. return "VEC2";
  853. }
  854. if (p_type == GLTFType::TYPE_VEC3) {
  855. return "VEC3";
  856. }
  857. if (p_type == GLTFType::TYPE_VEC4) {
  858. return "VEC4";
  859. }
  860. if (p_type == GLTFType::TYPE_MAT2) {
  861. return "MAT2";
  862. }
  863. if (p_type == GLTFType::TYPE_MAT3) {
  864. return "MAT3";
  865. }
  866. if (p_type == GLTFType::TYPE_MAT4) {
  867. return "MAT4";
  868. }
  869. ERR_FAIL_V("SCALAR");
  870. }
  871. GLTFType GLTFDocument::_get_type_from_str(const String &p_string) {
  872. if (p_string == "SCALAR") {
  873. return GLTFType::TYPE_SCALAR;
  874. }
  875. if (p_string == "VEC2") {
  876. return GLTFType::TYPE_VEC2;
  877. }
  878. if (p_string == "VEC3") {
  879. return GLTFType::TYPE_VEC3;
  880. }
  881. if (p_string == "VEC4") {
  882. return GLTFType::TYPE_VEC4;
  883. }
  884. if (p_string == "MAT2") {
  885. return GLTFType::TYPE_MAT2;
  886. }
  887. if (p_string == "MAT3") {
  888. return GLTFType::TYPE_MAT3;
  889. }
  890. if (p_string == "MAT4") {
  891. return GLTFType::TYPE_MAT4;
  892. }
  893. ERR_FAIL_V(GLTFType::TYPE_SCALAR);
  894. }
  895. Error GLTFDocument::_parse_accessors(Ref<GLTFState> p_state) {
  896. if (!p_state->json.has("accessors")) {
  897. return OK;
  898. }
  899. const Array &accessors = p_state->json["accessors"];
  900. for (GLTFAccessorIndex i = 0; i < accessors.size(); i++) {
  901. const Dictionary &d = accessors[i];
  902. Ref<GLTFAccessor> accessor;
  903. accessor.instance();
  904. ERR_FAIL_COND_V(!d.has("componentType"), ERR_PARSE_ERROR);
  905. accessor->component_type = d["componentType"];
  906. ERR_FAIL_COND_V(!d.has("count"), ERR_PARSE_ERROR);
  907. accessor->count = d["count"];
  908. ERR_FAIL_COND_V(!d.has("type"), ERR_PARSE_ERROR);
  909. accessor->type = _get_type_from_str(d["type"]);
  910. if (d.has("bufferView")) {
  911. accessor->buffer_view = d["bufferView"]; //optional because it may be sparse...
  912. }
  913. if (d.has("byteOffset")) {
  914. accessor->byte_offset = d["byteOffset"];
  915. }
  916. if (d.has("normalized")) {
  917. accessor->normalized = d["normalized"];
  918. }
  919. if (d.has("max")) {
  920. Array max = d["max"];
  921. accessor->max.resize(max.size());
  922. PoolVector<float>::Write max_write = accessor->max.write();
  923. for (int32_t max_i = 0; max_i < accessor->max.size(); max_i++) {
  924. max_write[max_i] = max[max_i];
  925. }
  926. }
  927. if (d.has("min")) {
  928. Array min = d["min"];
  929. accessor->min.resize(min.size());
  930. PoolVector<float>::Write min_write = accessor->min.write();
  931. for (int32_t min_i = 0; min_i < accessor->min.size(); min_i++) {
  932. min_write[min_i] = min[min_i];
  933. }
  934. }
  935. if (d.has("sparse")) {
  936. //eeh..
  937. const Dictionary &s = d["sparse"];
  938. ERR_FAIL_COND_V(!s.has("count"), ERR_PARSE_ERROR);
  939. accessor->sparse_count = s["count"];
  940. ERR_FAIL_COND_V(!s.has("indices"), ERR_PARSE_ERROR);
  941. const Dictionary &si = s["indices"];
  942. ERR_FAIL_COND_V(!si.has("bufferView"), ERR_PARSE_ERROR);
  943. accessor->sparse_indices_buffer_view = si["bufferView"];
  944. ERR_FAIL_COND_V(!si.has("componentType"), ERR_PARSE_ERROR);
  945. accessor->sparse_indices_component_type = si["componentType"];
  946. if (si.has("byteOffset")) {
  947. accessor->sparse_indices_byte_offset = si["byteOffset"];
  948. }
  949. ERR_FAIL_COND_V(!s.has("values"), ERR_PARSE_ERROR);
  950. const Dictionary &sv = s["values"];
  951. ERR_FAIL_COND_V(!sv.has("bufferView"), ERR_PARSE_ERROR);
  952. accessor->sparse_values_buffer_view = sv["bufferView"];
  953. if (sv.has("byteOffset")) {
  954. accessor->sparse_values_byte_offset = sv["byteOffset"];
  955. }
  956. }
  957. p_state->accessors.push_back(accessor);
  958. }
  959. print_verbose("glTF: Total accessors: " + itos(p_state->accessors.size()));
  960. return OK;
  961. }
  962. double GLTFDocument::_filter_number(double p_float) {
  963. if (Math::is_nan(p_float)) {
  964. return 0.0f;
  965. }
  966. return p_float;
  967. }
  968. String GLTFDocument::_get_component_type_name(const uint32_t p_component) {
  969. switch (p_component) {
  970. case GLTFDocument::COMPONENT_TYPE_BYTE:
  971. return "Byte";
  972. case GLTFDocument::COMPONENT_TYPE_UNSIGNED_BYTE:
  973. return "UByte";
  974. case GLTFDocument::COMPONENT_TYPE_SHORT:
  975. return "Short";
  976. case GLTFDocument::COMPONENT_TYPE_UNSIGNED_SHORT:
  977. return "UShort";
  978. case GLTFDocument::COMPONENT_TYPE_INT:
  979. return "Int";
  980. case GLTFDocument::COMPONENT_TYPE_FLOAT:
  981. return "Float";
  982. }
  983. return "<Error>";
  984. }
  985. String GLTFDocument::_get_type_name(const GLTFType p_component) {
  986. static const char *names[] = {
  987. "float",
  988. "vec2",
  989. "vec3",
  990. "vec4",
  991. "mat2",
  992. "mat3",
  993. "mat4"
  994. };
  995. return names[p_component];
  996. }
  997. Error GLTFDocument::_encode_buffer_view(Ref<GLTFState> p_state, const double *p_src, const int p_count, const GLTFType p_type, const int p_component_type, const bool p_normalized, const int p_byte_offset, const bool p_for_vertex, GLTFBufferViewIndex &r_accessor) {
  998. const int component_count_for_type[7] = {
  999. 1, 2, 3, 4, 4, 9, 16
  1000. };
  1001. const int component_count = component_count_for_type[p_type];
  1002. const int component_size = _get_component_type_size(p_component_type);
  1003. ERR_FAIL_COND_V(component_size == 0, FAILED);
  1004. int skip_every = 0;
  1005. int skip_bytes = 0;
  1006. //special case of alignments, as described in spec
  1007. switch (p_component_type) {
  1008. case COMPONENT_TYPE_BYTE:
  1009. case COMPONENT_TYPE_UNSIGNED_BYTE: {
  1010. if (p_type == TYPE_MAT2) {
  1011. skip_every = 2;
  1012. skip_bytes = 2;
  1013. }
  1014. if (p_type == TYPE_MAT3) {
  1015. skip_every = 3;
  1016. skip_bytes = 1;
  1017. }
  1018. } break;
  1019. case COMPONENT_TYPE_SHORT:
  1020. case COMPONENT_TYPE_UNSIGNED_SHORT: {
  1021. if (p_type == TYPE_MAT3) {
  1022. skip_every = 6;
  1023. skip_bytes = 4;
  1024. }
  1025. } break;
  1026. default: {
  1027. }
  1028. }
  1029. Ref<GLTFBufferView> bv;
  1030. bv.instance();
  1031. const uint32_t offset = bv->byte_offset = p_byte_offset;
  1032. Vector<uint8_t> &gltf_buffer = p_state->buffers.write[0];
  1033. int stride = _get_component_type_size(p_component_type);
  1034. if (p_for_vertex && stride % 4) {
  1035. stride += 4 - (stride % 4); //according to spec must be multiple of 4
  1036. }
  1037. //use to debug
  1038. print_verbose("glTF: encoding type " + _get_type_name(p_type) + " component type: " + _get_component_type_name(p_component_type) + " stride: " + itos(stride) + " amount " + itos(p_count));
  1039. print_verbose("glTF: encoding accessor offset " + itos(p_byte_offset) + " view offset: " + itos(bv->byte_offset) + " total buffer len: " + itos(gltf_buffer.size()) + " view len " + itos(bv->byte_length));
  1040. const int buffer_end = (stride * (p_count - 1)) + _get_component_type_size(p_component_type);
  1041. // TODO define bv->byte_stride
  1042. bv->byte_offset = gltf_buffer.size();
  1043. switch (p_component_type) {
  1044. case COMPONENT_TYPE_BYTE: {
  1045. Vector<int8_t> buffer;
  1046. buffer.resize(p_count * component_count);
  1047. int32_t dst_i = 0;
  1048. for (int i = 0; i < p_count; i++) {
  1049. for (int j = 0; j < component_count; j++) {
  1050. if (skip_every && j > 0 && (j % skip_every) == 0) {
  1051. dst_i += skip_bytes;
  1052. }
  1053. double d = *p_src;
  1054. if (p_normalized) {
  1055. buffer.write[dst_i] = d * 128.0;
  1056. } else {
  1057. buffer.write[dst_i] = d;
  1058. }
  1059. p_src++;
  1060. dst_i++;
  1061. }
  1062. }
  1063. int64_t old_size = gltf_buffer.size();
  1064. gltf_buffer.resize(old_size + (buffer.size() * sizeof(int8_t)));
  1065. memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(int8_t));
  1066. bv->byte_length = buffer.size() * sizeof(int8_t);
  1067. } break;
  1068. case COMPONENT_TYPE_UNSIGNED_BYTE: {
  1069. Vector<uint8_t> buffer;
  1070. buffer.resize(p_count * component_count);
  1071. int32_t dst_i = 0;
  1072. for (int i = 0; i < p_count; i++) {
  1073. for (int j = 0; j < component_count; j++) {
  1074. if (skip_every && j > 0 && (j % skip_every) == 0) {
  1075. dst_i += skip_bytes;
  1076. }
  1077. double d = *p_src;
  1078. if (p_normalized) {
  1079. buffer.write[dst_i] = d * 255.0;
  1080. } else {
  1081. buffer.write[dst_i] = d;
  1082. }
  1083. p_src++;
  1084. dst_i++;
  1085. }
  1086. }
  1087. gltf_buffer.append_array(buffer);
  1088. bv->byte_length = buffer.size() * sizeof(uint8_t);
  1089. } break;
  1090. case COMPONENT_TYPE_SHORT: {
  1091. Vector<int16_t> buffer;
  1092. buffer.resize(p_count * component_count);
  1093. int32_t dst_i = 0;
  1094. for (int i = 0; i < p_count; i++) {
  1095. for (int j = 0; j < component_count; j++) {
  1096. if (skip_every && j > 0 && (j % skip_every) == 0) {
  1097. dst_i += skip_bytes;
  1098. }
  1099. double d = *p_src;
  1100. if (p_normalized) {
  1101. buffer.write[dst_i] = d * 32768.0;
  1102. } else {
  1103. buffer.write[dst_i] = d;
  1104. }
  1105. p_src++;
  1106. dst_i++;
  1107. }
  1108. }
  1109. int64_t old_size = gltf_buffer.size();
  1110. gltf_buffer.resize(old_size + (buffer.size() * sizeof(int16_t)));
  1111. memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(int16_t));
  1112. bv->byte_length = buffer.size() * sizeof(int16_t);
  1113. } break;
  1114. case COMPONENT_TYPE_UNSIGNED_SHORT: {
  1115. Vector<uint16_t> buffer;
  1116. buffer.resize(p_count * component_count);
  1117. int32_t dst_i = 0;
  1118. for (int i = 0; i < p_count; i++) {
  1119. for (int j = 0; j < component_count; j++) {
  1120. if (skip_every && j > 0 && (j % skip_every) == 0) {
  1121. dst_i += skip_bytes;
  1122. }
  1123. double d = *p_src;
  1124. if (p_normalized) {
  1125. buffer.write[dst_i] = d * 65535.0;
  1126. } else {
  1127. buffer.write[dst_i] = d;
  1128. }
  1129. p_src++;
  1130. dst_i++;
  1131. }
  1132. }
  1133. int64_t old_size = gltf_buffer.size();
  1134. gltf_buffer.resize(old_size + (buffer.size() * sizeof(uint16_t)));
  1135. memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(uint16_t));
  1136. bv->byte_length = buffer.size() * sizeof(uint16_t);
  1137. } break;
  1138. case COMPONENT_TYPE_INT: {
  1139. Vector<int> buffer;
  1140. buffer.resize(p_count * component_count);
  1141. int32_t dst_i = 0;
  1142. for (int i = 0; i < p_count; i++) {
  1143. for (int j = 0; j < component_count; j++) {
  1144. if (skip_every && j > 0 && (j % skip_every) == 0) {
  1145. dst_i += skip_bytes;
  1146. }
  1147. double d = *p_src;
  1148. buffer.write[dst_i] = d;
  1149. p_src++;
  1150. dst_i++;
  1151. }
  1152. }
  1153. int64_t old_size = gltf_buffer.size();
  1154. gltf_buffer.resize(old_size + (buffer.size() * sizeof(int32_t)));
  1155. memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(int32_t));
  1156. bv->byte_length = buffer.size() * sizeof(int32_t);
  1157. } break;
  1158. case COMPONENT_TYPE_FLOAT: {
  1159. Vector<float> buffer;
  1160. buffer.resize(p_count * component_count);
  1161. int32_t dst_i = 0;
  1162. for (int i = 0; i < p_count; i++) {
  1163. for (int j = 0; j < component_count; j++) {
  1164. if (skip_every && j > 0 && (j % skip_every) == 0) {
  1165. dst_i += skip_bytes;
  1166. }
  1167. double d = *p_src;
  1168. buffer.write[dst_i] = d;
  1169. p_src++;
  1170. dst_i++;
  1171. }
  1172. }
  1173. int64_t old_size = gltf_buffer.size();
  1174. gltf_buffer.resize(old_size + (buffer.size() * sizeof(float)));
  1175. memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(float));
  1176. bv->byte_length = buffer.size() * sizeof(float);
  1177. } break;
  1178. }
  1179. ERR_FAIL_COND_V(buffer_end > bv->byte_length, ERR_INVALID_DATA);
  1180. ERR_FAIL_COND_V((int)(offset + buffer_end) > gltf_buffer.size(), ERR_INVALID_DATA);
  1181. r_accessor = bv->buffer = p_state->buffer_views.size();
  1182. p_state->buffer_views.push_back(bv);
  1183. return OK;
  1184. }
  1185. Error GLTFDocument::_decode_buffer_view(Ref<GLTFState> p_state, double *p_dst, const GLTFBufferViewIndex p_buffer_view, const int p_skip_every, const int p_skip_bytes, const int p_element_size, const int p_count, const GLTFType p_type, const int p_component_count, const int p_component_type, const int p_component_size, const bool p_normalized, const int p_byte_offset, const bool p_for_vertex) {
  1186. const Ref<GLTFBufferView> bv = p_state->buffer_views[p_buffer_view];
  1187. int stride = p_element_size;
  1188. if (bv->byte_stride != -1) {
  1189. stride = bv->byte_stride;
  1190. }
  1191. if (p_for_vertex && stride % 4) {
  1192. stride += 4 - (stride % 4); //according to spec must be multiple of 4
  1193. }
  1194. ERR_FAIL_INDEX_V(bv->buffer, p_state->buffers.size(), ERR_PARSE_ERROR);
  1195. const uint32_t offset = bv->byte_offset + p_byte_offset;
  1196. Vector<uint8_t> buffer = p_state->buffers[bv->buffer]; //copy on write, so no performance hit
  1197. const uint8_t *bufptr = buffer.ptr();
  1198. //use to debug
  1199. print_verbose("glTF: type " + _get_type_name(p_type) + " component type: " + _get_component_type_name(p_component_type) + " stride: " + itos(stride) + " amount " + itos(p_count));
  1200. print_verbose("glTF: accessor offset " + itos(p_byte_offset) + " view offset: " + itos(bv->byte_offset) + " total buffer len: " + itos(buffer.size()) + " view len " + itos(bv->byte_length));
  1201. const int buffer_end = (stride * (p_count - 1)) + p_element_size;
  1202. ERR_FAIL_COND_V(buffer_end > bv->byte_length, ERR_PARSE_ERROR);
  1203. ERR_FAIL_COND_V((int)(offset + buffer_end) > buffer.size(), ERR_PARSE_ERROR);
  1204. //fill everything as doubles
  1205. for (int i = 0; i < p_count; i++) {
  1206. const uint8_t *src = &bufptr[offset + i * stride];
  1207. for (int j = 0; j < p_component_count; j++) {
  1208. if (p_skip_every && j > 0 && (j % p_skip_every) == 0) {
  1209. src += p_skip_bytes;
  1210. }
  1211. double d = 0;
  1212. switch (p_component_type) {
  1213. case COMPONENT_TYPE_BYTE: {
  1214. int8_t b = int8_t(*src);
  1215. if (p_normalized) {
  1216. d = (double(b) / 128.0);
  1217. } else {
  1218. d = double(b);
  1219. }
  1220. } break;
  1221. case COMPONENT_TYPE_UNSIGNED_BYTE: {
  1222. uint8_t b = *src;
  1223. if (p_normalized) {
  1224. d = (double(b) / 255.0);
  1225. } else {
  1226. d = double(b);
  1227. }
  1228. } break;
  1229. case COMPONENT_TYPE_SHORT: {
  1230. int16_t s = *(int16_t *)src;
  1231. if (p_normalized) {
  1232. d = (double(s) / 32768.0);
  1233. } else {
  1234. d = double(s);
  1235. }
  1236. } break;
  1237. case COMPONENT_TYPE_UNSIGNED_SHORT: {
  1238. uint16_t s = *(uint16_t *)src;
  1239. if (p_normalized) {
  1240. d = (double(s) / 65535.0);
  1241. } else {
  1242. d = double(s);
  1243. }
  1244. } break;
  1245. case COMPONENT_TYPE_INT: {
  1246. d = *(int *)src;
  1247. } break;
  1248. case COMPONENT_TYPE_FLOAT: {
  1249. d = *(float *)src;
  1250. } break;
  1251. }
  1252. *p_dst++ = d;
  1253. src += p_component_size;
  1254. }
  1255. }
  1256. return OK;
  1257. }
  1258. int GLTFDocument::_get_component_type_size(const int p_component_type) {
  1259. switch (p_component_type) {
  1260. case COMPONENT_TYPE_BYTE:
  1261. case COMPONENT_TYPE_UNSIGNED_BYTE:
  1262. return 1;
  1263. break;
  1264. case COMPONENT_TYPE_SHORT:
  1265. case COMPONENT_TYPE_UNSIGNED_SHORT:
  1266. return 2;
  1267. break;
  1268. case COMPONENT_TYPE_INT:
  1269. case COMPONENT_TYPE_FLOAT:
  1270. return 4;
  1271. break;
  1272. default: {
  1273. ERR_FAIL_V(0);
  1274. }
  1275. }
  1276. return 0;
  1277. }
  1278. Vector<double> GLTFDocument::_decode_accessor(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  1279. //spec, for reference:
  1280. //https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
  1281. ERR_FAIL_INDEX_V(p_accessor, p_state->accessors.size(), Vector<double>());
  1282. const Ref<GLTFAccessor> a = p_state->accessors[p_accessor];
  1283. const int component_count_for_type[7] = {
  1284. 1, 2, 3, 4, 4, 9, 16
  1285. };
  1286. const int component_count = component_count_for_type[a->type];
  1287. const int component_size = _get_component_type_size(a->component_type);
  1288. ERR_FAIL_COND_V(component_size == 0, Vector<double>());
  1289. int element_size = component_count * component_size;
  1290. int skip_every = 0;
  1291. int skip_bytes = 0;
  1292. //special case of alignments, as described in spec
  1293. switch (a->component_type) {
  1294. case COMPONENT_TYPE_BYTE:
  1295. case COMPONENT_TYPE_UNSIGNED_BYTE: {
  1296. if (a->type == TYPE_MAT2) {
  1297. skip_every = 2;
  1298. skip_bytes = 2;
  1299. element_size = 8; //override for this case
  1300. }
  1301. if (a->type == TYPE_MAT3) {
  1302. skip_every = 3;
  1303. skip_bytes = 1;
  1304. element_size = 12; //override for this case
  1305. }
  1306. } break;
  1307. case COMPONENT_TYPE_SHORT:
  1308. case COMPONENT_TYPE_UNSIGNED_SHORT: {
  1309. if (a->type == TYPE_MAT3) {
  1310. skip_every = 6;
  1311. skip_bytes = 4;
  1312. element_size = 16; //override for this case
  1313. }
  1314. } break;
  1315. default: {
  1316. }
  1317. }
  1318. Vector<double> dst_buffer;
  1319. dst_buffer.resize(component_count * a->count);
  1320. double *dst = dst_buffer.ptrw();
  1321. if (a->buffer_view >= 0) {
  1322. ERR_FAIL_INDEX_V(a->buffer_view, p_state->buffer_views.size(), Vector<double>());
  1323. const Error err = _decode_buffer_view(p_state, dst, a->buffer_view, skip_every, skip_bytes, element_size, a->count, a->type, component_count, a->component_type, component_size, a->normalized, a->byte_offset, p_for_vertex);
  1324. if (err != OK) {
  1325. return Vector<double>();
  1326. }
  1327. } else {
  1328. //fill with zeros, as bufferview is not defined.
  1329. for (int i = 0; i < (a->count * component_count); i++) {
  1330. dst_buffer.write[i] = 0;
  1331. }
  1332. }
  1333. if (a->sparse_count > 0) {
  1334. // I could not find any file using this, so this code is so far untested
  1335. Vector<double> indices;
  1336. indices.resize(a->sparse_count);
  1337. const int indices_component_size = _get_component_type_size(a->sparse_indices_component_type);
  1338. Error err = _decode_buffer_view(p_state, indices.ptrw(), a->sparse_indices_buffer_view, 0, 0, indices_component_size, a->sparse_count, TYPE_SCALAR, 1, a->sparse_indices_component_type, indices_component_size, false, a->sparse_indices_byte_offset, false);
  1339. if (err != OK) {
  1340. return Vector<double>();
  1341. }
  1342. Vector<double> data;
  1343. data.resize(component_count * a->sparse_count);
  1344. err = _decode_buffer_view(p_state, data.ptrw(), a->sparse_values_buffer_view, skip_every, skip_bytes, element_size, a->sparse_count, a->type, component_count, a->component_type, component_size, a->normalized, a->sparse_values_byte_offset, p_for_vertex);
  1345. if (err != OK) {
  1346. return Vector<double>();
  1347. }
  1348. for (int i = 0; i < indices.size(); i++) {
  1349. const int write_offset = int(indices[i]) * component_count;
  1350. for (int j = 0; j < component_count; j++) {
  1351. dst[write_offset + j] = data[i * component_count + j];
  1352. }
  1353. }
  1354. }
  1355. return dst_buffer;
  1356. }
  1357. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_ints(Ref<GLTFState> p_state, const Vector<int32_t> p_attribs, const bool p_for_vertex) {
  1358. if (p_attribs.size() == 0) {
  1359. return -1;
  1360. }
  1361. const int element_count = 1;
  1362. const int ret_size = p_attribs.size();
  1363. Vector<double> attribs;
  1364. attribs.resize(ret_size);
  1365. Vector<double> type_max;
  1366. type_max.resize(element_count);
  1367. Vector<double> type_min;
  1368. type_min.resize(element_count);
  1369. for (int i = 0; i < p_attribs.size(); i++) {
  1370. attribs.write[i] = Math::stepify(p_attribs[i], 1.0);
  1371. if (i == 0) {
  1372. for (int32_t type_i = 0; type_i < element_count; type_i++) {
  1373. type_max.write[type_i] = attribs[(i * element_count) + type_i];
  1374. type_min.write[type_i] = attribs[(i * element_count) + type_i];
  1375. }
  1376. }
  1377. for (int32_t type_i = 0; type_i < element_count; type_i++) {
  1378. type_max.write[type_i] = MAX(attribs[(i * element_count) + type_i], type_max[type_i]);
  1379. type_min.write[type_i] = MIN(attribs[(i * element_count) + type_i], type_min[type_i]);
  1380. type_max.write[type_i] = _filter_number(type_max.write[type_i]);
  1381. type_min.write[type_i] = _filter_number(type_min.write[type_i]);
  1382. }
  1383. }
  1384. ERR_FAIL_COND_V(attribs.size() == 0, -1);
  1385. Ref<GLTFAccessor> accessor;
  1386. accessor.instance();
  1387. GLTFBufferIndex buffer_view_i;
  1388. int64_t size = p_state->buffers[0].size();
  1389. const GLTFType type = GLTFType::TYPE_SCALAR;
  1390. const int component_type = GLTFDocument::COMPONENT_TYPE_INT;
  1391. PoolVector<float> max;
  1392. max.resize(type_max.size());
  1393. PoolVector<float>::Write write_max = max.write();
  1394. for (int32_t max_i = 0; max_i < max.size(); max_i++) {
  1395. write_max[max_i] = type_max[max_i];
  1396. }
  1397. accessor->max = max;
  1398. PoolVector<float> min;
  1399. min.resize(type_min.size());
  1400. PoolVector<float>::Write write_min = min.write();
  1401. for (int32_t min_i = 0; min_i < min.size(); min_i++) {
  1402. write_min[min_i] = type_min[min_i];
  1403. }
  1404. accessor->min = min;
  1405. accessor->normalized = false;
  1406. accessor->count = ret_size;
  1407. accessor->type = type;
  1408. accessor->component_type = component_type;
  1409. accessor->byte_offset = 0;
  1410. Error err = _encode_buffer_view(p_state, attribs.ptr(), attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1411. if (err != OK) {
  1412. return -1;
  1413. }
  1414. accessor->buffer_view = buffer_view_i;
  1415. p_state->accessors.push_back(accessor);
  1416. return p_state->accessors.size() - 1;
  1417. }
  1418. Vector<int> GLTFDocument::_decode_accessor_as_ints(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  1419. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  1420. Vector<int> ret;
  1421. if (attribs.size() == 0) {
  1422. return ret;
  1423. }
  1424. const double *attribs_ptr = attribs.ptr();
  1425. const int ret_size = attribs.size();
  1426. ret.resize(ret_size);
  1427. {
  1428. for (int i = 0; i < ret_size; i++) {
  1429. ret.write[i] = int(attribs_ptr[i]);
  1430. }
  1431. }
  1432. return ret;
  1433. }
  1434. Vector<float> GLTFDocument::_decode_accessor_as_floats(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  1435. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  1436. Vector<float> ret;
  1437. if (attribs.size() == 0) {
  1438. return ret;
  1439. }
  1440. const double *attribs_ptr = attribs.ptr();
  1441. const int ret_size = attribs.size();
  1442. ret.resize(ret_size);
  1443. {
  1444. for (int i = 0; i < ret_size; i++) {
  1445. ret.write[i] = float(attribs_ptr[i]);
  1446. }
  1447. }
  1448. return ret;
  1449. }
  1450. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_vec2(Ref<GLTFState> p_state, const Vector<Vector2> p_attribs, const bool p_for_vertex) {
  1451. if (p_attribs.size() == 0) {
  1452. return -1;
  1453. }
  1454. const int element_count = 2;
  1455. const int ret_size = p_attribs.size() * element_count;
  1456. Vector<double> attribs;
  1457. attribs.resize(ret_size);
  1458. Vector<double> type_max;
  1459. type_max.resize(element_count);
  1460. Vector<double> type_min;
  1461. type_min.resize(element_count);
  1462. for (int i = 0; i < p_attribs.size(); i++) {
  1463. Vector2 attrib = p_attribs[i];
  1464. attribs.write[(i * element_count) + 0] = Math::stepify(attrib.x, CMP_NORMALIZE_TOLERANCE);
  1465. attribs.write[(i * element_count) + 1] = Math::stepify(attrib.y, CMP_NORMALIZE_TOLERANCE);
  1466. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1467. }
  1468. ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
  1469. Ref<GLTFAccessor> accessor;
  1470. accessor.instance();
  1471. GLTFBufferIndex buffer_view_i;
  1472. int64_t size = p_state->buffers[0].size();
  1473. const GLTFType type = GLTFType::TYPE_VEC2;
  1474. const int component_type = GLTFDocument::COMPONENT_TYPE_FLOAT;
  1475. PoolVector<float> max;
  1476. max.resize(type_max.size());
  1477. PoolVector<float>::Write write_max = max.write();
  1478. for (int32_t max_i = 0; max_i < max.size(); max_i++) {
  1479. write_max[max_i] = type_max[max_i];
  1480. }
  1481. accessor->max = max;
  1482. PoolVector<float> min;
  1483. min.resize(type_min.size());
  1484. PoolVector<float>::Write write_min = min.write();
  1485. for (int32_t min_i = 0; min_i < min.size(); min_i++) {
  1486. write_min[min_i] = type_min[min_i];
  1487. }
  1488. accessor->min = min;
  1489. accessor->normalized = false;
  1490. accessor->count = p_attribs.size();
  1491. accessor->type = type;
  1492. accessor->component_type = component_type;
  1493. accessor->byte_offset = 0;
  1494. Error err = _encode_buffer_view(p_state, attribs.ptr(), p_attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1495. if (err != OK) {
  1496. return -1;
  1497. }
  1498. accessor->buffer_view = buffer_view_i;
  1499. p_state->accessors.push_back(accessor);
  1500. return p_state->accessors.size() - 1;
  1501. }
  1502. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_color(Ref<GLTFState> p_state, const Vector<Color> p_attribs, const bool p_for_vertex) {
  1503. if (p_attribs.size() == 0) {
  1504. return -1;
  1505. }
  1506. const int ret_size = p_attribs.size() * 4;
  1507. Vector<double> attribs;
  1508. attribs.resize(ret_size);
  1509. const int element_count = 4;
  1510. Vector<double> type_max;
  1511. type_max.resize(element_count);
  1512. Vector<double> type_min;
  1513. type_min.resize(element_count);
  1514. for (int i = 0; i < p_attribs.size(); i++) {
  1515. Color attrib = p_attribs[i];
  1516. attribs.write[(i * element_count) + 0] = Math::stepify(attrib.r, CMP_NORMALIZE_TOLERANCE);
  1517. attribs.write[(i * element_count) + 1] = Math::stepify(attrib.g, CMP_NORMALIZE_TOLERANCE);
  1518. attribs.write[(i * element_count) + 2] = Math::stepify(attrib.b, CMP_NORMALIZE_TOLERANCE);
  1519. attribs.write[(i * element_count) + 3] = Math::stepify(attrib.a, CMP_NORMALIZE_TOLERANCE);
  1520. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1521. }
  1522. ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
  1523. Ref<GLTFAccessor> accessor;
  1524. accessor.instance();
  1525. GLTFBufferIndex buffer_view_i;
  1526. int64_t size = p_state->buffers[0].size();
  1527. const GLTFType type = GLTFType::TYPE_VEC4;
  1528. const int component_type = GLTFDocument::COMPONENT_TYPE_FLOAT;
  1529. PoolVector<float> max;
  1530. max.resize(type_max.size());
  1531. PoolVector<float>::Write write_max = max.write();
  1532. for (int32_t max_i = 0; max_i < max.size(); max_i++) {
  1533. write_max[max_i] = type_max[max_i];
  1534. }
  1535. accessor->max = max;
  1536. PoolVector<float> min;
  1537. min.resize(type_min.size());
  1538. PoolVector<float>::Write write_min = min.write();
  1539. for (int32_t min_i = 0; min_i < min.size(); min_i++) {
  1540. write_min[min_i] = type_min[min_i];
  1541. }
  1542. accessor->min = min;
  1543. accessor->normalized = false;
  1544. accessor->count = p_attribs.size();
  1545. accessor->type = type;
  1546. accessor->component_type = component_type;
  1547. accessor->byte_offset = 0;
  1548. Error err = _encode_buffer_view(p_state, attribs.ptr(), p_attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1549. if (err != OK) {
  1550. return -1;
  1551. }
  1552. accessor->buffer_view = buffer_view_i;
  1553. p_state->accessors.push_back(accessor);
  1554. return p_state->accessors.size() - 1;
  1555. }
  1556. void GLTFDocument::_calc_accessor_min_max(int p_i, const int p_element_count, Vector<double> &p_type_max, Vector<double> p_attribs, Vector<double> &p_type_min) {
  1557. if (p_i == 0) {
  1558. for (int32_t type_i = 0; type_i < p_element_count; type_i++) {
  1559. p_type_max.write[type_i] = p_attribs[(p_i * p_element_count) + type_i];
  1560. p_type_min.write[type_i] = p_attribs[(p_i * p_element_count) + type_i];
  1561. }
  1562. }
  1563. for (int32_t type_i = 0; type_i < p_element_count; type_i++) {
  1564. p_type_max.write[type_i] = MAX(p_attribs[(p_i * p_element_count) + type_i], p_type_max[type_i]);
  1565. p_type_min.write[type_i] = MIN(p_attribs[(p_i * p_element_count) + type_i], p_type_min[type_i]);
  1566. p_type_max.write[type_i] = _filter_number(p_type_max.write[type_i]);
  1567. p_type_min.write[type_i] = _filter_number(p_type_min.write[type_i]);
  1568. }
  1569. }
  1570. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_weights(Ref<GLTFState> p_state, const Vector<Color> p_attribs, const bool p_for_vertex) {
  1571. if (p_attribs.size() == 0) {
  1572. return -1;
  1573. }
  1574. const int ret_size = p_attribs.size() * 4;
  1575. Vector<double> attribs;
  1576. attribs.resize(ret_size);
  1577. const int element_count = 4;
  1578. Vector<double> type_max;
  1579. type_max.resize(element_count);
  1580. Vector<double> type_min;
  1581. type_min.resize(element_count);
  1582. for (int i = 0; i < p_attribs.size(); i++) {
  1583. Color attrib = p_attribs[i];
  1584. attribs.write[(i * element_count) + 0] = Math::stepify(attrib.r, CMP_NORMALIZE_TOLERANCE);
  1585. attribs.write[(i * element_count) + 1] = Math::stepify(attrib.g, CMP_NORMALIZE_TOLERANCE);
  1586. attribs.write[(i * element_count) + 2] = Math::stepify(attrib.b, CMP_NORMALIZE_TOLERANCE);
  1587. attribs.write[(i * element_count) + 3] = Math::stepify(attrib.a, CMP_NORMALIZE_TOLERANCE);
  1588. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1589. }
  1590. ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
  1591. Ref<GLTFAccessor> accessor;
  1592. accessor.instance();
  1593. GLTFBufferIndex buffer_view_i;
  1594. int64_t size = p_state->buffers[0].size();
  1595. const GLTFType type = GLTFType::TYPE_VEC4;
  1596. const int component_type = GLTFDocument::COMPONENT_TYPE_FLOAT;
  1597. PoolVector<float> max;
  1598. max.resize(type_max.size());
  1599. PoolVector<float>::Write write_max = max.write();
  1600. for (int32_t max_i = 0; max_i < max.size(); max_i++) {
  1601. write_max[max_i] = type_max[max_i];
  1602. }
  1603. accessor->max = max;
  1604. PoolVector<float> min;
  1605. min.resize(type_min.size());
  1606. PoolVector<float>::Write write_min = min.write();
  1607. for (int32_t min_i = 0; min_i < min.size(); min_i++) {
  1608. write_min[min_i] = type_min[min_i];
  1609. }
  1610. accessor->min = min;
  1611. accessor->normalized = false;
  1612. accessor->count = p_attribs.size();
  1613. accessor->type = type;
  1614. accessor->component_type = component_type;
  1615. accessor->byte_offset = 0;
  1616. Error err = _encode_buffer_view(p_state, attribs.ptr(), p_attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1617. if (err != OK) {
  1618. return -1;
  1619. }
  1620. accessor->buffer_view = buffer_view_i;
  1621. p_state->accessors.push_back(accessor);
  1622. return p_state->accessors.size() - 1;
  1623. }
  1624. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_joints(Ref<GLTFState> p_state, const Vector<Color> p_attribs, const bool p_for_vertex) {
  1625. if (p_attribs.size() == 0) {
  1626. return -1;
  1627. }
  1628. const int element_count = 4;
  1629. const int ret_size = p_attribs.size() * element_count;
  1630. Vector<double> attribs;
  1631. attribs.resize(ret_size);
  1632. Vector<double> type_max;
  1633. type_max.resize(element_count);
  1634. Vector<double> type_min;
  1635. type_min.resize(element_count);
  1636. for (int i = 0; i < p_attribs.size(); i++) {
  1637. Color attrib = p_attribs[i];
  1638. attribs.write[(i * element_count) + 0] = Math::stepify(attrib.r, CMP_NORMALIZE_TOLERANCE);
  1639. attribs.write[(i * element_count) + 1] = Math::stepify(attrib.g, CMP_NORMALIZE_TOLERANCE);
  1640. attribs.write[(i * element_count) + 2] = Math::stepify(attrib.b, CMP_NORMALIZE_TOLERANCE);
  1641. attribs.write[(i * element_count) + 3] = Math::stepify(attrib.a, CMP_NORMALIZE_TOLERANCE);
  1642. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1643. }
  1644. ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
  1645. Ref<GLTFAccessor> accessor;
  1646. accessor.instance();
  1647. GLTFBufferIndex buffer_view_i;
  1648. int64_t size = p_state->buffers[0].size();
  1649. const GLTFType type = GLTFType::TYPE_VEC4;
  1650. const int component_type = GLTFDocument::COMPONENT_TYPE_UNSIGNED_SHORT;
  1651. PoolVector<float> max;
  1652. max.resize(type_max.size());
  1653. PoolVector<float>::Write write_max = max.write();
  1654. for (int32_t max_i = 0; max_i < max.size(); max_i++) {
  1655. write_max[max_i] = type_max[max_i];
  1656. }
  1657. accessor->max = max;
  1658. PoolVector<float> min;
  1659. min.resize(type_min.size());
  1660. PoolVector<float>::Write write_min = min.write();
  1661. for (int32_t min_i = 0; min_i < min.size(); min_i++) {
  1662. write_min[min_i] = type_min[min_i];
  1663. }
  1664. accessor->min = min;
  1665. accessor->normalized = false;
  1666. accessor->count = p_attribs.size();
  1667. accessor->type = type;
  1668. accessor->component_type = component_type;
  1669. accessor->byte_offset = 0;
  1670. Error err = _encode_buffer_view(p_state, attribs.ptr(), p_attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1671. if (err != OK) {
  1672. return -1;
  1673. }
  1674. accessor->buffer_view = buffer_view_i;
  1675. p_state->accessors.push_back(accessor);
  1676. return p_state->accessors.size() - 1;
  1677. }
  1678. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_quats(Ref<GLTFState> p_state, const Vector<Quat> p_attribs, const bool p_for_vertex) {
  1679. if (p_attribs.size() == 0) {
  1680. return -1;
  1681. }
  1682. const int element_count = 4;
  1683. const int ret_size = p_attribs.size() * element_count;
  1684. Vector<double> attribs;
  1685. attribs.resize(ret_size);
  1686. Vector<double> type_max;
  1687. type_max.resize(element_count);
  1688. Vector<double> type_min;
  1689. type_min.resize(element_count);
  1690. for (int i = 0; i < p_attribs.size(); i++) {
  1691. Quat quat = p_attribs[i];
  1692. attribs.write[(i * element_count) + 0] = Math::stepify(quat.x, CMP_NORMALIZE_TOLERANCE);
  1693. attribs.write[(i * element_count) + 1] = Math::stepify(quat.y, CMP_NORMALIZE_TOLERANCE);
  1694. attribs.write[(i * element_count) + 2] = Math::stepify(quat.z, CMP_NORMALIZE_TOLERANCE);
  1695. attribs.write[(i * element_count) + 3] = Math::stepify(quat.w, CMP_NORMALIZE_TOLERANCE);
  1696. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1697. }
  1698. ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
  1699. Ref<GLTFAccessor> accessor;
  1700. accessor.instance();
  1701. GLTFBufferIndex buffer_view_i;
  1702. int64_t size = p_state->buffers[0].size();
  1703. const GLTFType type = GLTFType::TYPE_VEC4;
  1704. const int component_type = GLTFDocument::COMPONENT_TYPE_FLOAT;
  1705. PoolVector<float> max;
  1706. max.resize(type_max.size());
  1707. PoolVector<float>::Write write_max = max.write();
  1708. for (int32_t max_i = 0; max_i < max.size(); max_i++) {
  1709. write_max[max_i] = type_max[max_i];
  1710. }
  1711. accessor->max = max;
  1712. PoolVector<float> min;
  1713. min.resize(type_min.size());
  1714. PoolVector<float>::Write write_min = min.write();
  1715. for (int32_t min_i = 0; min_i < min.size(); min_i++) {
  1716. write_min[min_i] = type_min[min_i];
  1717. }
  1718. accessor->min = min;
  1719. accessor->normalized = false;
  1720. accessor->count = p_attribs.size();
  1721. accessor->type = type;
  1722. accessor->component_type = component_type;
  1723. accessor->byte_offset = 0;
  1724. Error err = _encode_buffer_view(p_state, attribs.ptr(), p_attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1725. if (err != OK) {
  1726. return -1;
  1727. }
  1728. accessor->buffer_view = buffer_view_i;
  1729. p_state->accessors.push_back(accessor);
  1730. return p_state->accessors.size() - 1;
  1731. }
  1732. Vector<Vector2> GLTFDocument::_decode_accessor_as_vec2(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  1733. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  1734. Vector<Vector2> ret;
  1735. if (attribs.size() == 0) {
  1736. return ret;
  1737. }
  1738. ERR_FAIL_COND_V(attribs.size() % 2 != 0, ret);
  1739. const double *attribs_ptr = attribs.ptr();
  1740. const int ret_size = attribs.size() / 2;
  1741. ret.resize(ret_size);
  1742. {
  1743. for (int i = 0; i < ret_size; i++) {
  1744. ret.write[i] = Vector2(attribs_ptr[i * 2 + 0], attribs_ptr[i * 2 + 1]);
  1745. }
  1746. }
  1747. return ret;
  1748. }
  1749. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_floats(Ref<GLTFState> p_state, const Vector<real_t> p_attribs, const bool p_for_vertex) {
  1750. if (p_attribs.size() == 0) {
  1751. return -1;
  1752. }
  1753. const int element_count = 1;
  1754. const int ret_size = p_attribs.size();
  1755. Vector<double> attribs;
  1756. attribs.resize(ret_size);
  1757. Vector<double> type_max;
  1758. type_max.resize(element_count);
  1759. Vector<double> type_min;
  1760. type_min.resize(element_count);
  1761. for (int i = 0; i < p_attribs.size(); i++) {
  1762. attribs.write[i] = Math::stepify(p_attribs[i], CMP_NORMALIZE_TOLERANCE);
  1763. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1764. }
  1765. ERR_FAIL_COND_V(!attribs.size(), -1);
  1766. Ref<GLTFAccessor> accessor;
  1767. accessor.instance();
  1768. GLTFBufferIndex buffer_view_i;
  1769. int64_t size = p_state->buffers[0].size();
  1770. const GLTFType type = GLTFType::TYPE_SCALAR;
  1771. const int component_type = GLTFDocument::COMPONENT_TYPE_FLOAT;
  1772. PoolVector<float> max;
  1773. max.resize(type_max.size());
  1774. PoolVector<float>::Write write_max = max.write();
  1775. for (int32_t max_i = 0; max_i < max.size(); max_i++) {
  1776. write_max[max_i] = type_max[max_i];
  1777. }
  1778. accessor->max = max;
  1779. PoolVector<float> min;
  1780. min.resize(type_min.size());
  1781. PoolVector<float>::Write write_min = min.write();
  1782. for (int32_t min_i = 0; min_i < min.size(); min_i++) {
  1783. write_min[min_i] = type_min[min_i];
  1784. }
  1785. accessor->min = min;
  1786. accessor->normalized = false;
  1787. accessor->count = ret_size;
  1788. accessor->type = type;
  1789. accessor->component_type = component_type;
  1790. accessor->byte_offset = 0;
  1791. Error err = _encode_buffer_view(p_state, attribs.ptr(), attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1792. if (err != OK) {
  1793. return -1;
  1794. }
  1795. accessor->buffer_view = buffer_view_i;
  1796. p_state->accessors.push_back(accessor);
  1797. return p_state->accessors.size() - 1;
  1798. }
  1799. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_vec3(Ref<GLTFState> p_state, const Vector<Vector3> p_attribs, const bool p_for_vertex) {
  1800. if (p_attribs.size() == 0) {
  1801. return -1;
  1802. }
  1803. const int element_count = 3;
  1804. const int ret_size = p_attribs.size() * element_count;
  1805. Vector<double> attribs;
  1806. attribs.resize(ret_size);
  1807. Vector<double> type_max;
  1808. type_max.resize(element_count);
  1809. Vector<double> type_min;
  1810. type_min.resize(element_count);
  1811. for (int i = 0; i < p_attribs.size(); i++) {
  1812. Vector3 attrib = p_attribs[i];
  1813. attribs.write[(i * element_count) + 0] = Math::stepify(attrib.x, CMP_NORMALIZE_TOLERANCE);
  1814. attribs.write[(i * element_count) + 1] = Math::stepify(attrib.y, CMP_NORMALIZE_TOLERANCE);
  1815. attribs.write[(i * element_count) + 2] = Math::stepify(attrib.z, CMP_NORMALIZE_TOLERANCE);
  1816. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1817. }
  1818. ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
  1819. Ref<GLTFAccessor> accessor;
  1820. accessor.instance();
  1821. GLTFBufferIndex buffer_view_i;
  1822. int64_t size = p_state->buffers[0].size();
  1823. const GLTFType type = GLTFType::TYPE_VEC3;
  1824. const int component_type = GLTFDocument::COMPONENT_TYPE_FLOAT;
  1825. PoolVector<float> max;
  1826. max.resize(type_max.size());
  1827. PoolVector<float>::Write write_max = max.write();
  1828. for (int32_t max_i = 0; max_i < max.size(); max_i++) {
  1829. write_max[max_i] = type_max[max_i];
  1830. }
  1831. accessor->max = max;
  1832. PoolVector<float> min;
  1833. min.resize(type_min.size());
  1834. PoolVector<float>::Write write_min = min.write();
  1835. for (int32_t min_i = 0; min_i < min.size(); min_i++) {
  1836. write_min[min_i] = type_min[min_i];
  1837. }
  1838. accessor->min = min;
  1839. accessor->normalized = false;
  1840. accessor->count = p_attribs.size();
  1841. accessor->type = type;
  1842. accessor->component_type = component_type;
  1843. accessor->byte_offset = 0;
  1844. Error err = _encode_buffer_view(p_state, attribs.ptr(), p_attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1845. if (err != OK) {
  1846. return -1;
  1847. }
  1848. accessor->buffer_view = buffer_view_i;
  1849. p_state->accessors.push_back(accessor);
  1850. return p_state->accessors.size() - 1;
  1851. }
  1852. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_xform(Ref<GLTFState> p_state, const Vector<Transform> p_attribs, const bool p_for_vertex) {
  1853. if (p_attribs.size() == 0) {
  1854. return -1;
  1855. }
  1856. const int element_count = 16;
  1857. const int ret_size = p_attribs.size() * element_count;
  1858. Vector<double> attribs;
  1859. attribs.resize(ret_size);
  1860. Vector<double> type_max;
  1861. type_max.resize(element_count);
  1862. Vector<double> type_min;
  1863. type_min.resize(element_count);
  1864. for (int i = 0; i < p_attribs.size(); i++) {
  1865. Transform attrib = p_attribs[i];
  1866. Basis basis = attrib.get_basis();
  1867. Vector3 axis_0 = basis.get_axis(Vector3::AXIS_X);
  1868. attribs.write[i * element_count + 0] = Math::stepify(axis_0.x, CMP_NORMALIZE_TOLERANCE);
  1869. attribs.write[i * element_count + 1] = Math::stepify(axis_0.y, CMP_NORMALIZE_TOLERANCE);
  1870. attribs.write[i * element_count + 2] = Math::stepify(axis_0.z, CMP_NORMALIZE_TOLERANCE);
  1871. attribs.write[i * element_count + 3] = 0.0;
  1872. Vector3 axis_1 = basis.get_axis(Vector3::AXIS_Y);
  1873. attribs.write[i * element_count + 4] = Math::stepify(axis_1.x, CMP_NORMALIZE_TOLERANCE);
  1874. attribs.write[i * element_count + 5] = Math::stepify(axis_1.y, CMP_NORMALIZE_TOLERANCE);
  1875. attribs.write[i * element_count + 6] = Math::stepify(axis_1.z, CMP_NORMALIZE_TOLERANCE);
  1876. attribs.write[i * element_count + 7] = 0.0;
  1877. Vector3 axis_2 = basis.get_axis(Vector3::AXIS_Z);
  1878. attribs.write[i * element_count + 8] = Math::stepify(axis_2.x, CMP_NORMALIZE_TOLERANCE);
  1879. attribs.write[i * element_count + 9] = Math::stepify(axis_2.y, CMP_NORMALIZE_TOLERANCE);
  1880. attribs.write[i * element_count + 10] = Math::stepify(axis_2.z, CMP_NORMALIZE_TOLERANCE);
  1881. attribs.write[i * element_count + 11] = 0.0;
  1882. Vector3 origin = attrib.get_origin();
  1883. attribs.write[i * element_count + 12] = Math::stepify(origin.x, CMP_NORMALIZE_TOLERANCE);
  1884. attribs.write[i * element_count + 13] = Math::stepify(origin.y, CMP_NORMALIZE_TOLERANCE);
  1885. attribs.write[i * element_count + 14] = Math::stepify(origin.z, CMP_NORMALIZE_TOLERANCE);
  1886. attribs.write[i * element_count + 15] = 1.0;
  1887. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1888. }
  1889. ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
  1890. Ref<GLTFAccessor> accessor;
  1891. accessor.instance();
  1892. GLTFBufferIndex buffer_view_i;
  1893. int64_t size = p_state->buffers[0].size();
  1894. const GLTFType type = GLTFType::TYPE_MAT4;
  1895. const int component_type = GLTFDocument::COMPONENT_TYPE_FLOAT;
  1896. PoolVector<float> max;
  1897. max.resize(type_max.size());
  1898. PoolVector<float>::Write write_max = max.write();
  1899. for (int32_t max_i = 0; max_i < max.size(); max_i++) {
  1900. write_max[max_i] = type_max[max_i];
  1901. }
  1902. accessor->max = max;
  1903. PoolVector<float> min;
  1904. min.resize(type_min.size());
  1905. PoolVector<float>::Write write_min = min.write();
  1906. for (int32_t min_i = 0; min_i < min.size(); min_i++) {
  1907. write_min[min_i] = type_min[min_i];
  1908. }
  1909. accessor->min = min;
  1910. accessor->normalized = false;
  1911. accessor->count = p_attribs.size();
  1912. accessor->type = type;
  1913. accessor->component_type = component_type;
  1914. accessor->byte_offset = 0;
  1915. Error err = _encode_buffer_view(p_state, attribs.ptr(), p_attribs.size(), type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1916. if (err != OK) {
  1917. return -1;
  1918. }
  1919. accessor->buffer_view = buffer_view_i;
  1920. p_state->accessors.push_back(accessor);
  1921. return p_state->accessors.size() - 1;
  1922. }
  1923. Vector<Vector3> GLTFDocument::_decode_accessor_as_vec3(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  1924. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  1925. Vector<Vector3> ret;
  1926. if (attribs.size() == 0) {
  1927. return ret;
  1928. }
  1929. ERR_FAIL_COND_V(attribs.size() % 3 != 0, ret);
  1930. const double *attribs_ptr = attribs.ptr();
  1931. const int ret_size = attribs.size() / 3;
  1932. ret.resize(ret_size);
  1933. {
  1934. for (int i = 0; i < ret_size; i++) {
  1935. ret.write[i] = Vector3(attribs_ptr[i * 3 + 0], attribs_ptr[i * 3 + 1], attribs_ptr[i * 3 + 2]);
  1936. }
  1937. }
  1938. return ret;
  1939. }
  1940. Vector<Color> GLTFDocument::_decode_accessor_as_color(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  1941. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  1942. Vector<Color> ret;
  1943. if (attribs.size() == 0) {
  1944. return ret;
  1945. }
  1946. const int type = p_state->accessors[p_accessor]->type;
  1947. ERR_FAIL_COND_V(!(type == TYPE_VEC3 || type == TYPE_VEC4), ret);
  1948. int vec_len = 3;
  1949. if (type == TYPE_VEC4) {
  1950. vec_len = 4;
  1951. }
  1952. ERR_FAIL_COND_V(attribs.size() % vec_len != 0, ret);
  1953. const double *attribs_ptr = attribs.ptr();
  1954. const int ret_size = attribs.size() / vec_len;
  1955. ret.resize(ret_size);
  1956. {
  1957. for (int i = 0; i < ret_size; i++) {
  1958. ret.write[i] = Color(attribs_ptr[i * vec_len + 0], attribs_ptr[i * vec_len + 1], attribs_ptr[i * vec_len + 2], vec_len == 4 ? attribs_ptr[i * 4 + 3] : 1.0);
  1959. }
  1960. }
  1961. return ret;
  1962. }
  1963. Vector<Quat> GLTFDocument::_decode_accessor_as_quat(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  1964. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  1965. Vector<Quat> ret;
  1966. if (attribs.size() == 0) {
  1967. return ret;
  1968. }
  1969. ERR_FAIL_COND_V(attribs.size() % 4 != 0, ret);
  1970. const double *attribs_ptr = attribs.ptr();
  1971. const int ret_size = attribs.size() / 4;
  1972. ret.resize(ret_size);
  1973. {
  1974. for (int i = 0; i < ret_size; i++) {
  1975. ret.write[i] = Quat(attribs_ptr[i * 4 + 0], attribs_ptr[i * 4 + 1], attribs_ptr[i * 4 + 2], attribs_ptr[i * 4 + 3]).normalized();
  1976. }
  1977. }
  1978. return ret;
  1979. }
  1980. Vector<Transform2D> GLTFDocument::_decode_accessor_as_xform2d(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  1981. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  1982. Vector<Transform2D> ret;
  1983. if (attribs.size() == 0) {
  1984. return ret;
  1985. }
  1986. ERR_FAIL_COND_V(attribs.size() % 4 != 0, ret);
  1987. ret.resize(attribs.size() / 4);
  1988. for (int i = 0; i < ret.size(); i++) {
  1989. ret.write[i][0] = Vector2(attribs[i * 4 + 0], attribs[i * 4 + 1]);
  1990. ret.write[i][1] = Vector2(attribs[i * 4 + 2], attribs[i * 4 + 3]);
  1991. }
  1992. return ret;
  1993. }
  1994. Vector<Basis> GLTFDocument::_decode_accessor_as_basis(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  1995. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  1996. Vector<Basis> ret;
  1997. if (attribs.size() == 0) {
  1998. return ret;
  1999. }
  2000. ERR_FAIL_COND_V(attribs.size() % 9 != 0, ret);
  2001. ret.resize(attribs.size() / 9);
  2002. for (int i = 0; i < ret.size(); i++) {
  2003. ret.write[i].set_axis(0, Vector3(attribs[i * 9 + 0], attribs[i * 9 + 1], attribs[i * 9 + 2]));
  2004. ret.write[i].set_axis(1, Vector3(attribs[i * 9 + 3], attribs[i * 9 + 4], attribs[i * 9 + 5]));
  2005. ret.write[i].set_axis(2, Vector3(attribs[i * 9 + 6], attribs[i * 9 + 7], attribs[i * 9 + 8]));
  2006. }
  2007. return ret;
  2008. }
  2009. Vector<Transform> GLTFDocument::_decode_accessor_as_xform(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  2010. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  2011. Vector<Transform> ret;
  2012. if (attribs.size() == 0) {
  2013. return ret;
  2014. }
  2015. ERR_FAIL_COND_V(attribs.size() % 16 != 0, ret);
  2016. ret.resize(attribs.size() / 16);
  2017. for (int i = 0; i < ret.size(); i++) {
  2018. ret.write[i].basis.set_axis(0, Vector3(attribs[i * 16 + 0], attribs[i * 16 + 1], attribs[i * 16 + 2]));
  2019. ret.write[i].basis.set_axis(1, Vector3(attribs[i * 16 + 4], attribs[i * 16 + 5], attribs[i * 16 + 6]));
  2020. ret.write[i].basis.set_axis(2, Vector3(attribs[i * 16 + 8], attribs[i * 16 + 9], attribs[i * 16 + 10]));
  2021. ret.write[i].set_origin(Vector3(attribs[i * 16 + 12], attribs[i * 16 + 13], attribs[i * 16 + 14]));
  2022. }
  2023. return ret;
  2024. }
  2025. Error GLTFDocument::_serialize_meshes(Ref<GLTFState> p_state) {
  2026. Array meshes;
  2027. for (GLTFMeshIndex gltf_mesh_i = 0; gltf_mesh_i < p_state->meshes.size(); gltf_mesh_i++) {
  2028. print_verbose("glTF: Serializing mesh: " + itos(gltf_mesh_i));
  2029. Ref<ArrayMesh> import_mesh = p_state->meshes.write[gltf_mesh_i]->get_mesh();
  2030. if (import_mesh.is_null()) {
  2031. continue;
  2032. }
  2033. Array instance_materials = p_state->meshes.write[gltf_mesh_i]->get_instance_materials();
  2034. Array primitives;
  2035. Dictionary gltf_mesh;
  2036. Array target_names;
  2037. Array weights;
  2038. for (int morph_i = 0; morph_i < import_mesh->get_blend_shape_count(); morph_i++) {
  2039. target_names.push_back(import_mesh->get_blend_shape_name(morph_i));
  2040. }
  2041. for (int surface_i = 0; surface_i < import_mesh->get_surface_count(); surface_i++) {
  2042. Array targets;
  2043. Dictionary primitive;
  2044. Mesh::PrimitiveType primitive_type = import_mesh->surface_get_primitive_type(surface_i);
  2045. switch (primitive_type) {
  2046. case Mesh::PRIMITIVE_POINTS: {
  2047. primitive["mode"] = 0;
  2048. break;
  2049. }
  2050. case Mesh::PRIMITIVE_LINES: {
  2051. primitive["mode"] = 1;
  2052. break;
  2053. }
  2054. // case Mesh::PRIMITIVE_LINE_LOOP: {
  2055. // primitive["mode"] = 2;
  2056. // break;
  2057. // }
  2058. case Mesh::PRIMITIVE_LINE_STRIP: {
  2059. primitive["mode"] = 3;
  2060. break;
  2061. }
  2062. case Mesh::PRIMITIVE_TRIANGLES: {
  2063. primitive["mode"] = 4;
  2064. break;
  2065. }
  2066. case Mesh::PRIMITIVE_TRIANGLE_STRIP: {
  2067. primitive["mode"] = 5;
  2068. break;
  2069. }
  2070. // case Mesh::PRIMITIVE_TRIANGLE_FAN: {
  2071. // primitive["mode"] = 6;
  2072. // break;
  2073. // }
  2074. default: {
  2075. ERR_FAIL_V(FAILED);
  2076. }
  2077. }
  2078. Array array = import_mesh->surface_get_arrays(surface_i);
  2079. Dictionary attributes;
  2080. {
  2081. Vector<Vector3> a = array[Mesh::ARRAY_VERTEX];
  2082. ERR_FAIL_COND_V(!a.size(), ERR_INVALID_DATA);
  2083. attributes["POSITION"] = _encode_accessor_as_vec3(p_state, a, true);
  2084. }
  2085. {
  2086. Vector<real_t> a = array[Mesh::ARRAY_TANGENT];
  2087. if (a.size()) {
  2088. const int ret_size = a.size() / 4;
  2089. Vector<Color> attribs;
  2090. attribs.resize(ret_size);
  2091. for (int i = 0; i < ret_size; i++) {
  2092. Color out;
  2093. out.r = a[(i * 4) + 0];
  2094. out.g = a[(i * 4) + 1];
  2095. out.b = a[(i * 4) + 2];
  2096. out.a = a[(i * 4) + 3];
  2097. attribs.write[i] = out;
  2098. }
  2099. attributes["TANGENT"] = _encode_accessor_as_color(p_state, attribs, true);
  2100. }
  2101. }
  2102. {
  2103. Vector<Vector3> a = array[Mesh::ARRAY_NORMAL];
  2104. if (a.size()) {
  2105. const int ret_size = a.size();
  2106. Vector<Vector3> attribs;
  2107. attribs.resize(ret_size);
  2108. for (int i = 0; i < ret_size; i++) {
  2109. attribs.write[i] = Vector3(a[i]).normalized();
  2110. }
  2111. attributes["NORMAL"] = _encode_accessor_as_vec3(p_state, attribs, true);
  2112. }
  2113. }
  2114. {
  2115. Vector<Vector2> a = array[Mesh::ARRAY_TEX_UV];
  2116. if (a.size()) {
  2117. attributes["TEXCOORD_0"] = _encode_accessor_as_vec2(p_state, a, true);
  2118. }
  2119. }
  2120. {
  2121. Vector<Vector2> a = array[Mesh::ARRAY_TEX_UV2];
  2122. if (a.size()) {
  2123. attributes["TEXCOORD_1"] = _encode_accessor_as_vec2(p_state, a, true);
  2124. }
  2125. }
  2126. {
  2127. Vector<Color> a = array[Mesh::ARRAY_COLOR];
  2128. if (a.size()) {
  2129. attributes["COLOR_0"] = _encode_accessor_as_color(p_state, a, true);
  2130. }
  2131. }
  2132. Map<int, int> joint_i_to_bone_i;
  2133. for (GLTFNodeIndex node_i = 0; node_i < p_state->nodes.size(); node_i++) {
  2134. GLTFSkinIndex skin_i = -1;
  2135. if (p_state->nodes[node_i]->mesh == gltf_mesh_i) {
  2136. skin_i = p_state->nodes[node_i]->skin;
  2137. }
  2138. if (skin_i != -1) {
  2139. joint_i_to_bone_i = p_state->skins[skin_i]->joint_i_to_bone_i;
  2140. break;
  2141. }
  2142. }
  2143. {
  2144. const Array &a = array[Mesh::ARRAY_BONES];
  2145. const Vector<Vector3> &vertex_array = array[Mesh::ARRAY_VERTEX];
  2146. if ((a.size() / JOINT_GROUP_SIZE) == vertex_array.size()) {
  2147. const int ret_size = a.size() / JOINT_GROUP_SIZE;
  2148. Vector<Color> attribs;
  2149. attribs.resize(ret_size);
  2150. {
  2151. for (int array_i = 0; array_i < attribs.size(); array_i++) {
  2152. int32_t joint_0 = a[(array_i * JOINT_GROUP_SIZE) + 0];
  2153. int32_t joint_1 = a[(array_i * JOINT_GROUP_SIZE) + 1];
  2154. int32_t joint_2 = a[(array_i * JOINT_GROUP_SIZE) + 2];
  2155. int32_t joint_3 = a[(array_i * JOINT_GROUP_SIZE) + 3];
  2156. attribs.write[array_i] = Color(joint_0, joint_1, joint_2, joint_3);
  2157. }
  2158. }
  2159. attributes["JOINTS_0"] = _encode_accessor_as_joints(p_state, attribs, true);
  2160. }
  2161. ERR_FAIL_COND_V((a.size() / (JOINT_GROUP_SIZE * 2)) >= vertex_array.size(), FAILED);
  2162. }
  2163. {
  2164. const Array &a = array[Mesh::ARRAY_WEIGHTS];
  2165. const Vector<Vector3> &vertex_array = array[Mesh::ARRAY_VERTEX];
  2166. if ((a.size() / JOINT_GROUP_SIZE) == vertex_array.size()) {
  2167. int32_t vertex_count = vertex_array.size();
  2168. Vector<Color> attribs;
  2169. attribs.resize(vertex_count);
  2170. for (int i = 0; i < vertex_count; i++) {
  2171. attribs.write[i] = Color(a[(i * JOINT_GROUP_SIZE) + 0], a[(i * JOINT_GROUP_SIZE) + 1], a[(i * JOINT_GROUP_SIZE) + 2], a[(i * JOINT_GROUP_SIZE) + 3]);
  2172. }
  2173. attributes["WEIGHTS_0"] = _encode_accessor_as_weights(p_state, attribs, true);
  2174. } else if ((a.size() / (JOINT_GROUP_SIZE * 2)) >= vertex_array.size()) {
  2175. int32_t vertex_count = vertex_array.size();
  2176. Vector<Color> weights_0;
  2177. weights_0.resize(vertex_count);
  2178. Vector<Color> weights_1;
  2179. weights_1.resize(vertex_count);
  2180. int32_t weights_8_count = JOINT_GROUP_SIZE * 2;
  2181. for (int32_t vertex_i = 0; vertex_i < vertex_count; vertex_i++) {
  2182. Color weight_0;
  2183. weight_0.r = a[vertex_i * weights_8_count + 0];
  2184. weight_0.g = a[vertex_i * weights_8_count + 1];
  2185. weight_0.b = a[vertex_i * weights_8_count + 2];
  2186. weight_0.a = a[vertex_i * weights_8_count + 3];
  2187. weights_0.write[vertex_i] = weight_0;
  2188. Color weight_1;
  2189. weight_1.r = a[vertex_i * weights_8_count + 4];
  2190. weight_1.g = a[vertex_i * weights_8_count + 5];
  2191. weight_1.b = a[vertex_i * weights_8_count + 6];
  2192. weight_1.a = a[vertex_i * weights_8_count + 7];
  2193. weights_1.write[vertex_i] = weight_1;
  2194. }
  2195. attributes["WEIGHTS_0"] = _encode_accessor_as_weights(p_state, weights_0, true);
  2196. attributes["WEIGHTS_1"] = _encode_accessor_as_weights(p_state, weights_1, true);
  2197. }
  2198. }
  2199. {
  2200. Vector<int32_t> mesh_indices = array[Mesh::ARRAY_INDEX];
  2201. if (mesh_indices.size()) {
  2202. if (primitive_type == Mesh::PRIMITIVE_TRIANGLES) {
  2203. //swap around indices, convert ccw to cw for front face
  2204. const int is = mesh_indices.size();
  2205. for (int k = 0; k < is; k += 3) {
  2206. SWAP(mesh_indices.write[k + 0], mesh_indices.write[k + 2]);
  2207. }
  2208. }
  2209. primitive["indices"] = _encode_accessor_as_ints(p_state, mesh_indices, true);
  2210. } else {
  2211. if (primitive_type == Mesh::PRIMITIVE_TRIANGLES) {
  2212. //generate indices because they need to be swapped for CW/CCW
  2213. const Vector<Vector3> &vertices = array[Mesh::ARRAY_VERTEX];
  2214. Ref<SurfaceTool> st;
  2215. st.instance();
  2216. st->create_from_triangle_arrays(array);
  2217. st->index();
  2218. Vector<int32_t> generated_indices = st->commit_to_arrays()[Mesh::ARRAY_INDEX];
  2219. const int vs = vertices.size();
  2220. generated_indices.resize(vs);
  2221. {
  2222. for (int k = 0; k < vs; k += 3) {
  2223. generated_indices.write[k] = k;
  2224. generated_indices.write[k + 1] = k + 2;
  2225. generated_indices.write[k + 2] = k + 1;
  2226. }
  2227. }
  2228. primitive["indices"] = _encode_accessor_as_ints(p_state, generated_indices, true);
  2229. }
  2230. }
  2231. }
  2232. primitive["attributes"] = attributes;
  2233. //blend shapes
  2234. print_verbose("glTF: Mesh has targets");
  2235. if (import_mesh->get_blend_shape_count()) {
  2236. ArrayMesh::BlendShapeMode shape_mode = import_mesh->get_blend_shape_mode();
  2237. Array array_morphs = import_mesh->surface_get_blend_shape_arrays(surface_i);
  2238. for (int morph_i = 0; morph_i < array_morphs.size(); morph_i++) {
  2239. Array array_morph = array_morphs[morph_i];
  2240. Dictionary t;
  2241. Vector<Vector3> varr = array_morph[Mesh::ARRAY_VERTEX];
  2242. Array mesh_arrays = import_mesh->surface_get_arrays(surface_i);
  2243. if (varr.size()) {
  2244. Vector<Vector3> src_varr = array[Mesh::ARRAY_VERTEX];
  2245. if (shape_mode == ArrayMesh::BlendShapeMode::BLEND_SHAPE_MODE_NORMALIZED) {
  2246. const int max_idx = src_varr.size();
  2247. for (int blend_i = 0; blend_i < max_idx; blend_i++) {
  2248. varr.write[blend_i] = Vector3(varr[blend_i]) - src_varr[blend_i];
  2249. }
  2250. }
  2251. t["POSITION"] = _encode_accessor_as_vec3(p_state, varr, true);
  2252. }
  2253. Vector<Vector3> narr = array_morph[Mesh::ARRAY_NORMAL];
  2254. if (narr.size()) {
  2255. t["NORMAL"] = _encode_accessor_as_vec3(p_state, narr, true);
  2256. }
  2257. Vector<real_t> tarr = array_morph[Mesh::ARRAY_TANGENT];
  2258. if (tarr.size()) {
  2259. const int ret_size = tarr.size() / 4;
  2260. Vector<Vector3> attribs;
  2261. attribs.resize(ret_size);
  2262. for (int i = 0; i < ret_size; i++) {
  2263. Vector3 vec3;
  2264. vec3.x = tarr[(i * 4) + 0];
  2265. vec3.y = tarr[(i * 4) + 1];
  2266. vec3.z = tarr[(i * 4) + 2];
  2267. }
  2268. t["TANGENT"] = _encode_accessor_as_vec3(p_state, attribs, true);
  2269. }
  2270. targets.push_back(t);
  2271. }
  2272. }
  2273. Variant v;
  2274. if (surface_i < instance_materials.size()) {
  2275. v = instance_materials.get(surface_i);
  2276. }
  2277. Ref<Material3D> mat = v;
  2278. if (!mat.is_valid()) {
  2279. mat = import_mesh->surface_get_material(surface_i);
  2280. }
  2281. if (mat.is_valid()) {
  2282. Map<Ref<Material>, GLTFMaterialIndex>::Element *material_cache_i = p_state->material_cache.find(mat);
  2283. if (material_cache_i && material_cache_i->get() != -1) {
  2284. primitive["material"] = material_cache_i->get();
  2285. } else {
  2286. GLTFMaterialIndex mat_i = p_state->materials.size();
  2287. p_state->materials.push_back(mat);
  2288. primitive["material"] = mat_i;
  2289. p_state->material_cache.insert(mat, mat_i);
  2290. }
  2291. }
  2292. if (targets.size()) {
  2293. primitive["targets"] = targets;
  2294. }
  2295. primitives.push_back(primitive);
  2296. }
  2297. Dictionary e;
  2298. e["targetNames"] = target_names;
  2299. weights.resize(target_names.size());
  2300. for (int name_i = 0; name_i < target_names.size(); name_i++) {
  2301. real_t weight = 0.0;
  2302. if (name_i < p_state->meshes.write[gltf_mesh_i]->get_blend_weights().size()) {
  2303. weight = p_state->meshes.write[gltf_mesh_i]->get_blend_weights()[name_i];
  2304. }
  2305. weights[name_i] = weight;
  2306. }
  2307. if (weights.size()) {
  2308. gltf_mesh["weights"] = weights;
  2309. }
  2310. ERR_FAIL_COND_V(target_names.size() != weights.size(), FAILED);
  2311. gltf_mesh["extras"] = e;
  2312. gltf_mesh["primitives"] = primitives;
  2313. meshes.push_back(gltf_mesh);
  2314. }
  2315. if (!meshes.size()) {
  2316. return OK;
  2317. }
  2318. p_state->json["meshes"] = meshes;
  2319. print_verbose("glTF: Total meshes: " + itos(meshes.size()));
  2320. return OK;
  2321. }
  2322. Error GLTFDocument::_parse_meshes(Ref<GLTFState> p_state) {
  2323. if (!p_state->json.has("meshes")) {
  2324. return OK;
  2325. }
  2326. bool has_warned = false;
  2327. Array meshes = p_state->json["meshes"];
  2328. for (GLTFMeshIndex i = 0; i < meshes.size(); i++) {
  2329. print_verbose("glTF: Parsing mesh: " + itos(i));
  2330. Dictionary d = meshes[i];
  2331. Ref<GLTFMesh> mesh;
  2332. mesh.instance();
  2333. bool has_vertex_color = false;
  2334. ERR_FAIL_COND_V(!d.has("primitives"), ERR_PARSE_ERROR);
  2335. Array primitives = d["primitives"];
  2336. const Dictionary &extras = d.has("extras") ? (Dictionary)d["extras"] : Dictionary();
  2337. Ref<ArrayMesh> import_mesh;
  2338. import_mesh.instance();
  2339. String mesh_name = "mesh";
  2340. if (d.has("name") && !String(d["name"]).empty()) {
  2341. mesh_name = d["name"];
  2342. }
  2343. import_mesh->set_name(_gen_unique_name(p_state, vformat("%s_%s", p_state->scene_name, mesh_name)));
  2344. for (int j = 0; j < primitives.size(); j++) {
  2345. Dictionary p = primitives[j];
  2346. Array array;
  2347. array.resize(Mesh::ARRAY_MAX);
  2348. ERR_FAIL_COND_V(!p.has("attributes"), ERR_PARSE_ERROR);
  2349. Dictionary a = p["attributes"];
  2350. Mesh::PrimitiveType primitive = Mesh::PRIMITIVE_TRIANGLES;
  2351. if (p.has("mode")) {
  2352. const int mode = p["mode"];
  2353. ERR_FAIL_INDEX_V(mode, 7, ERR_FILE_CORRUPT);
  2354. static const Mesh::PrimitiveType primitives2[7] = {
  2355. Mesh::PRIMITIVE_POINTS,
  2356. Mesh::PRIMITIVE_LINES,
  2357. Mesh::PRIMITIVE_LINES, //loop not supported, should ce converted
  2358. Mesh::PRIMITIVE_LINES,
  2359. Mesh::PRIMITIVE_TRIANGLES,
  2360. Mesh::PRIMITIVE_TRIANGLE_STRIP,
  2361. Mesh::PRIMITIVE_TRIANGLES, //fan not supported, should be converted
  2362. #ifndef _MSC_VER
  2363. // #warning line loop and triangle fan are not supported and need to be converted to lines and triangles
  2364. #endif
  2365. };
  2366. primitive = primitives2[mode];
  2367. }
  2368. ERR_FAIL_COND_V(!a.has("POSITION"), ERR_PARSE_ERROR);
  2369. if (a.has("POSITION")) {
  2370. array[Mesh::ARRAY_VERTEX] = _decode_accessor_as_vec3(p_state, a["POSITION"], true);
  2371. }
  2372. if (a.has("NORMAL")) {
  2373. array[Mesh::ARRAY_NORMAL] = _decode_accessor_as_vec3(p_state, a["NORMAL"], true);
  2374. }
  2375. if (a.has("TANGENT")) {
  2376. array[Mesh::ARRAY_TANGENT] = _decode_accessor_as_floats(p_state, a["TANGENT"], true);
  2377. }
  2378. if (a.has("TEXCOORD_0")) {
  2379. array[Mesh::ARRAY_TEX_UV] = _decode_accessor_as_vec2(p_state, a["TEXCOORD_0"], true);
  2380. }
  2381. if (a.has("TEXCOORD_1")) {
  2382. array[Mesh::ARRAY_TEX_UV2] = _decode_accessor_as_vec2(p_state, a["TEXCOORD_1"], true);
  2383. }
  2384. if (a.has("COLOR_0")) {
  2385. array[Mesh::ARRAY_COLOR] = _decode_accessor_as_color(p_state, a["COLOR_0"], true);
  2386. has_vertex_color = true;
  2387. }
  2388. if (a.has("JOINTS_0")) {
  2389. array[Mesh::ARRAY_BONES] = _decode_accessor_as_ints(p_state, a["JOINTS_0"], true);
  2390. }
  2391. if (a.has("WEIGHTS_1") && a.has("JOINTS_1")) {
  2392. if (!has_warned) {
  2393. WARN_PRINT("glTF: Meshes use more than 4 bone joints");
  2394. has_warned = true;
  2395. }
  2396. }
  2397. if (a.has("WEIGHTS_0")) {
  2398. Vector<float> weights = _decode_accessor_as_floats(p_state, a["WEIGHTS_0"], true);
  2399. { //gltf does not seem to normalize the weights for some reason..
  2400. int wc = weights.size();
  2401. float *w = weights.ptrw();
  2402. for (int k = 0; k < wc; k += 4) {
  2403. float total = 0.0;
  2404. total += w[k + 0];
  2405. total += w[k + 1];
  2406. total += w[k + 2];
  2407. total += w[k + 3];
  2408. if (total > 0.0) {
  2409. w[k + 0] /= total;
  2410. w[k + 1] /= total;
  2411. w[k + 2] /= total;
  2412. w[k + 3] /= total;
  2413. }
  2414. }
  2415. }
  2416. array[Mesh::ARRAY_WEIGHTS] = weights;
  2417. }
  2418. if (p.has("indices")) {
  2419. Vector<int> indices = _decode_accessor_as_ints(p_state, p["indices"], false);
  2420. if (primitive == Mesh::PRIMITIVE_TRIANGLES) {
  2421. //swap around indices, convert ccw to cw for front face
  2422. const int is = indices.size();
  2423. int *w = indices.ptrw();
  2424. for (int k = 0; k < is; k += 3) {
  2425. SWAP(w[k + 1], w[k + 2]);
  2426. }
  2427. }
  2428. array[Mesh::ARRAY_INDEX] = indices;
  2429. } else if (primitive == Mesh::PRIMITIVE_TRIANGLES) {
  2430. //generate indices because they need to be swapped for CW/CCW
  2431. const Vector<Vector3> &vertices = array[Mesh::ARRAY_VERTEX];
  2432. ERR_FAIL_COND_V(vertices.size() == 0, ERR_PARSE_ERROR);
  2433. Vector<int> indices;
  2434. const int vs = vertices.size();
  2435. indices.resize(vs);
  2436. {
  2437. int *w = indices.ptrw();
  2438. for (int k = 0; k < vs; k += 3) {
  2439. w[k] = k;
  2440. w[k + 1] = k + 2;
  2441. w[k + 2] = k + 1;
  2442. }
  2443. }
  2444. array[Mesh::ARRAY_INDEX] = indices;
  2445. }
  2446. bool generate_tangents = (primitive == Mesh::PRIMITIVE_TRIANGLES && !a.has("TANGENT") && a.has("TEXCOORD_0") && a.has("NORMAL"));
  2447. if (generate_tangents) {
  2448. //must generate mikktspace tangents.. ergh..
  2449. Ref<SurfaceTool> st;
  2450. st.instance();
  2451. st->create_from_triangle_arrays(array);
  2452. st->generate_tangents();
  2453. array = st->commit_to_arrays();
  2454. }
  2455. Array morphs;
  2456. //blend shapes
  2457. if (p.has("targets")) {
  2458. print_verbose("glTF: Mesh has targets");
  2459. const Array &targets = p["targets"];
  2460. //ideally BLEND_SHAPE_MODE_RELATIVE since gltf2 stores in displacement
  2461. //but it could require a larger refactor?
  2462. import_mesh->set_blend_shape_mode(Mesh::BLEND_SHAPE_MODE_NORMALIZED);
  2463. if (j == 0) {
  2464. const Array &target_names = extras.has("targetNames") ? (Array)extras["targetNames"] : Array();
  2465. for (int k = 0; k < targets.size(); k++) {
  2466. const String name = k < target_names.size() ? (String)target_names[k] : String("morph_") + itos(k);
  2467. import_mesh->add_blend_shape(name);
  2468. }
  2469. }
  2470. for (int k = 0; k < targets.size(); k++) {
  2471. const Dictionary &t = targets[k];
  2472. Array array_copy;
  2473. array_copy.resize(Mesh::ARRAY_MAX);
  2474. for (int l = 0; l < Mesh::ARRAY_MAX; l++) {
  2475. array_copy[l] = array[l];
  2476. }
  2477. array_copy[Mesh::ARRAY_INDEX] = Variant();
  2478. if (t.has("POSITION")) {
  2479. Vector<Vector3> varr = _decode_accessor_as_vec3(p_state, t["POSITION"], true);
  2480. const Vector<Vector3> src_varr = array[Mesh::ARRAY_VERTEX];
  2481. const int size = src_varr.size();
  2482. ERR_FAIL_COND_V(size == 0, ERR_PARSE_ERROR);
  2483. {
  2484. const int max_idx = varr.size();
  2485. varr.resize(size);
  2486. Vector3 *w_varr = varr.ptrw();
  2487. const Vector3 *r_varr = varr.ptr();
  2488. const Vector3 *r_src_varr = src_varr.ptr();
  2489. for (int l = 0; l < size; l++) {
  2490. if (l < max_idx) {
  2491. w_varr[l] = r_varr[l] + r_src_varr[l];
  2492. } else {
  2493. w_varr[l] = r_src_varr[l];
  2494. }
  2495. }
  2496. }
  2497. array_copy[Mesh::ARRAY_VERTEX] = varr;
  2498. }
  2499. if (t.has("NORMAL")) {
  2500. Vector<Vector3> narr = _decode_accessor_as_vec3(p_state, t["NORMAL"], true);
  2501. const Vector<Vector3> src_narr = array[Mesh::ARRAY_NORMAL];
  2502. int size = src_narr.size();
  2503. ERR_FAIL_COND_V(size == 0, ERR_PARSE_ERROR);
  2504. {
  2505. int max_idx = narr.size();
  2506. narr.resize(size);
  2507. Vector3 *w_narr = narr.ptrw();
  2508. const Vector3 *r_narr = narr.ptr();
  2509. const Vector3 *r_src_narr = src_narr.ptr();
  2510. for (int l = 0; l < size; l++) {
  2511. if (l < max_idx) {
  2512. w_narr[l] = r_narr[l] + r_src_narr[l];
  2513. } else {
  2514. w_narr[l] = r_src_narr[l];
  2515. }
  2516. }
  2517. }
  2518. array_copy[Mesh::ARRAY_NORMAL] = narr;
  2519. }
  2520. if (t.has("TANGENT")) {
  2521. const Vector<Vector3> tangents_v3 = _decode_accessor_as_vec3(p_state, t["TANGENT"], true);
  2522. const Vector<float> src_tangents = array[Mesh::ARRAY_TANGENT];
  2523. ERR_FAIL_COND_V(src_tangents.size() == 0, ERR_PARSE_ERROR);
  2524. Vector<float> tangents_v4;
  2525. {
  2526. int max_idx = tangents_v3.size();
  2527. int size4 = src_tangents.size();
  2528. tangents_v4.resize(size4);
  2529. float *w4 = tangents_v4.ptrw();
  2530. const Vector3 *r3 = tangents_v3.ptr();
  2531. const float *r4 = src_tangents.ptr();
  2532. for (int l = 0; l < size4 / 4; l++) {
  2533. if (l < max_idx) {
  2534. w4[l * 4 + 0] = r3[l].x + r4[l * 4 + 0];
  2535. w4[l * 4 + 1] = r3[l].y + r4[l * 4 + 1];
  2536. w4[l * 4 + 2] = r3[l].z + r4[l * 4 + 2];
  2537. } else {
  2538. w4[l * 4 + 0] = r4[l * 4 + 0];
  2539. w4[l * 4 + 1] = r4[l * 4 + 1];
  2540. w4[l * 4 + 2] = r4[l * 4 + 2];
  2541. }
  2542. w4[l * 4 + 3] = r4[l * 4 + 3]; //copy flip value
  2543. }
  2544. }
  2545. array_copy[Mesh::ARRAY_TANGENT] = tangents_v4;
  2546. }
  2547. if (generate_tangents) {
  2548. Ref<SurfaceTool> st;
  2549. st.instance();
  2550. st->create_from_triangle_arrays(array_copy);
  2551. st->deindex();
  2552. st->generate_tangents();
  2553. array_copy = st->commit_to_arrays();
  2554. }
  2555. morphs.push_back(array_copy);
  2556. }
  2557. }
  2558. //just add it
  2559. Ref<Material> mat;
  2560. if (p.has("material")) {
  2561. const int material = p["material"];
  2562. ERR_FAIL_INDEX_V(material, p_state->materials.size(), ERR_FILE_CORRUPT);
  2563. Ref<Material3D> mat3d = p_state->materials[material];
  2564. if (has_vertex_color) {
  2565. mat3d->set_flag(Material3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  2566. }
  2567. mat = mat3d;
  2568. } else if (has_vertex_color) {
  2569. Ref<SpatialMaterial> mat3d;
  2570. mat3d.instance();
  2571. mat3d->set_flag(Material3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  2572. mat = mat3d;
  2573. }
  2574. int32_t mat_idx = import_mesh->get_surface_count();
  2575. // Check for invalid indices.
  2576. if (array[Mesh::ARRAY_INDEX] && array[Mesh::ARRAY_INDEX] != Variant()) {
  2577. const Vector<int> &inds = array[Mesh::ARRAY_INDEX];
  2578. if (array[Mesh::ARRAY_VERTEX] && array[Mesh::ARRAY_VERTEX] != Variant()) {
  2579. const Vector<Vector3> &vertices = array[Mesh::ARRAY_VERTEX];
  2580. int num_verts = vertices.size();
  2581. // The mesh contains invalid indices, abort.
  2582. ERR_FAIL_COND_V(!Geometry::verify_indices(inds.ptr(), inds.size(), num_verts), ERR_FILE_CORRUPT);
  2583. }
  2584. }
  2585. import_mesh->add_surface_from_arrays(primitive, array, morphs, p_state->compress_flags);
  2586. import_mesh->surface_set_material(mat_idx, mat);
  2587. }
  2588. Vector<float> blend_weights;
  2589. blend_weights.resize(import_mesh->get_blend_shape_count());
  2590. for (int32_t weight_i = 0; weight_i < blend_weights.size(); weight_i++) {
  2591. blend_weights.write[weight_i] = 0.0f;
  2592. }
  2593. if (d.has("weights")) {
  2594. const Array &weights = d["weights"];
  2595. for (int j = 0; j < weights.size(); j++) {
  2596. if (j >= blend_weights.size()) {
  2597. break;
  2598. }
  2599. blend_weights.write[j] = weights[j];
  2600. }
  2601. }
  2602. mesh->set_blend_weights(blend_weights);
  2603. mesh->set_mesh(import_mesh);
  2604. p_state->meshes.push_back(mesh);
  2605. }
  2606. print_verbose("glTF: Total meshes: " + itos(p_state->meshes.size()));
  2607. return OK;
  2608. }
  2609. Error GLTFDocument::_serialize_images(Ref<GLTFState> p_state, const String &p_path) {
  2610. Array images;
  2611. for (int i = 0; i < p_state->images.size(); i++) {
  2612. Dictionary d;
  2613. ERR_CONTINUE(p_state->images[i].is_null());
  2614. Ref<Image> image = p_state->images[i];
  2615. ERR_CONTINUE(image.is_null());
  2616. if (p_path.to_lower().ends_with("glb")) {
  2617. GLTFBufferViewIndex bvi;
  2618. Ref<GLTFBufferView> bv;
  2619. bv.instance();
  2620. const GLTFBufferIndex bi = 0;
  2621. bv->buffer = bi;
  2622. bv->byte_offset = p_state->buffers[bi].size();
  2623. ERR_FAIL_INDEX_V(bi, p_state->buffers.size(), ERR_PARAMETER_RANGE_ERROR);
  2624. PoolVector<uint8_t> buffer;
  2625. Ref<ImageTexture> img_tex = image;
  2626. if (img_tex.is_valid()) {
  2627. image = img_tex->get_data();
  2628. }
  2629. Error err = PNGDriverCommon::image_to_png(image, buffer);
  2630. ERR_FAIL_COND_V_MSG(err, err, "Can't convert image to PNG.");
  2631. bv->byte_length = buffer.size();
  2632. p_state->buffers.write[bi].resize(p_state->buffers[bi].size() + bv->byte_length);
  2633. memcpy(&p_state->buffers.write[bi].write[bv->byte_offset], buffer.read().ptr(), buffer.size());
  2634. ERR_FAIL_COND_V(bv->byte_offset + bv->byte_length > p_state->buffers[bi].size(), ERR_FILE_CORRUPT);
  2635. p_state->buffer_views.push_back(bv);
  2636. bvi = p_state->buffer_views.size() - 1;
  2637. d["bufferView"] = bvi;
  2638. d["mimeType"] = "image/png";
  2639. } else {
  2640. String name = p_state->images[i]->get_name();
  2641. if (name.empty()) {
  2642. name = itos(i);
  2643. }
  2644. name = _gen_unique_name(p_state, name);
  2645. name = name.pad_zeros(3);
  2646. Ref<_Directory> dir;
  2647. dir.instance();
  2648. String texture_dir = "textures";
  2649. String new_texture_dir = p_path.get_base_dir() + "/" + texture_dir;
  2650. dir->open(p_path.get_base_dir());
  2651. if (!dir->dir_exists(new_texture_dir)) {
  2652. dir->make_dir(new_texture_dir);
  2653. }
  2654. name = name + ".png";
  2655. image->save_png(new_texture_dir.plus_file(name));
  2656. d["uri"] = texture_dir.plus_file(name);
  2657. }
  2658. images.push_back(d);
  2659. }
  2660. print_verbose("Total images: " + itos(p_state->images.size()));
  2661. if (!images.size()) {
  2662. return OK;
  2663. }
  2664. p_state->json["images"] = images;
  2665. return OK;
  2666. }
  2667. Error GLTFDocument::_parse_images(Ref<GLTFState> p_state, const String &p_base_path) {
  2668. if (!p_state->json.has("images")) {
  2669. return OK;
  2670. }
  2671. // Ref: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#images
  2672. const Array &images = p_state->json["images"];
  2673. for (int i = 0; i < images.size(); i++) {
  2674. const Dictionary &d = images[i];
  2675. // glTF 2.0 supports PNG and JPEG types, which can be specified as (from spec):
  2676. // "- a URI to an external file in one of the supported images formats, or
  2677. // - a URI with embedded base64-encoded data, or
  2678. // - a reference to a bufferView; in that case mimeType must be defined."
  2679. // Since mimeType is optional for external files and base64 data, we'll have to
  2680. // fall back on letting Godot parse the data to figure out if it's PNG or JPEG.
  2681. // We'll assume that we use either URI or bufferView, so let's warn the user
  2682. // if their image somehow uses both. And fail if it has neither.
  2683. ERR_CONTINUE_MSG(!d.has("uri") && !d.has("bufferView"), "Invalid image definition in glTF file, it should specify an 'uri' or 'bufferView'.");
  2684. if (d.has("uri") && d.has("bufferView")) {
  2685. WARN_PRINT("Invalid image definition in glTF file using both 'uri' and 'bufferView'. 'uri' will take precedence.");
  2686. }
  2687. String mimetype;
  2688. if (d.has("mimeType")) { // Should be "image/png" or "image/jpeg".
  2689. mimetype = d["mimeType"];
  2690. }
  2691. Vector<uint8_t> data;
  2692. const uint8_t *data_ptr = nullptr;
  2693. int data_size = 0;
  2694. if (d.has("uri")) {
  2695. // Handles the first two bullet points from the spec (embedded data, or external file).
  2696. String uri = d["uri"];
  2697. if (uri.begins_with("data:")) { // Embedded data using base64.
  2698. // Validate data MIME types and throw a warning if it's one we don't know/support.
  2699. if (!uri.begins_with("data:application/octet-stream;base64") &&
  2700. !uri.begins_with("data:application/gltf-buffer;base64") &&
  2701. !uri.begins_with("data:image/png;base64") &&
  2702. !uri.begins_with("data:image/jpeg;base64")) {
  2703. WARN_PRINT(vformat("glTF: Image index '%d' uses an unsupported URI data type: %s. Skipping it.", i, uri));
  2704. p_state->images.push_back(Ref<Image>()); // Placeholder to keep count.
  2705. continue;
  2706. }
  2707. data = _parse_base64_uri(uri);
  2708. data_ptr = data.ptr();
  2709. data_size = data.size();
  2710. // mimeType is optional, but if we have it defined in the URI, let's use it.
  2711. if (mimetype.empty()) {
  2712. if (uri.begins_with("data:image/png;base64")) {
  2713. mimetype = "image/png";
  2714. } else if (uri.begins_with("data:image/jpeg;base64")) {
  2715. mimetype = "image/jpeg";
  2716. }
  2717. }
  2718. } else { // Relative path to an external image file.
  2719. uri = uri.http_unescape();
  2720. uri = p_base_path.plus_file(uri).replace("\\", "/"); // Fix for Windows.
  2721. // ResourceLoader will rely on the file extension to use the relevant loader.
  2722. // The spec says that if mimeType is defined, it should take precedence (e.g.
  2723. // there could be a `.png` image which is actually JPEG), but there's no easy
  2724. // API for that in Godot, so we'd have to load as a buffer (i.e. embedded in
  2725. // the material), so we do this only as fallback.
  2726. Ref<Texture> texture = ResourceLoader::load(uri);
  2727. if (texture.is_valid()) {
  2728. p_state->images.push_back(texture->get_data());
  2729. p_state->external_images_paths.insert(i, uri);
  2730. continue;
  2731. } else if (mimetype == "image/png" || mimetype == "image/jpeg") {
  2732. // Fallback to loading as byte array.
  2733. // This enables us to support the spec's requirement that we honor mimetype
  2734. // regardless of file URI.
  2735. data = FileAccess::get_file_as_array(uri);
  2736. if (data.size() == 0) {
  2737. WARN_PRINT(vformat("glTF: Image index '%d' couldn't be loaded as a buffer of MIME type '%s' from URI: %s. Skipping it.", i, mimetype, uri));
  2738. p_state->images.push_back(Ref<Image>()); // Placeholder to keep count.
  2739. continue;
  2740. }
  2741. data_ptr = data.ptr();
  2742. data_size = data.size();
  2743. } else {
  2744. WARN_PRINT(vformat("glTF: Image index '%d' couldn't be loaded from URI: %s. Skipping it.", i, uri));
  2745. p_state->images.push_back(Ref<Image>()); // Placeholder to keep count.
  2746. continue;
  2747. }
  2748. }
  2749. } else if (d.has("bufferView")) {
  2750. // Handles the third bullet point from the spec (bufferView).
  2751. ERR_FAIL_COND_V_MSG(mimetype.empty(), ERR_FILE_CORRUPT,
  2752. vformat("glTF: Image index '%d' specifies 'bufferView' but no 'mimeType', which is invalid.", i));
  2753. const GLTFBufferViewIndex bvi = d["bufferView"];
  2754. ERR_FAIL_INDEX_V(bvi, p_state->buffer_views.size(), ERR_PARAMETER_RANGE_ERROR);
  2755. Ref<GLTFBufferView> bv = p_state->buffer_views[bvi];
  2756. const GLTFBufferIndex bi = bv->buffer;
  2757. ERR_FAIL_INDEX_V(bi, p_state->buffers.size(), ERR_PARAMETER_RANGE_ERROR);
  2758. ERR_FAIL_COND_V(bv->byte_offset + bv->byte_length > p_state->buffers[bi].size(), ERR_FILE_CORRUPT);
  2759. data_ptr = &p_state->buffers[bi][bv->byte_offset];
  2760. data_size = bv->byte_length;
  2761. }
  2762. Ref<Image> img;
  2763. // First we honor the mime types if they were defined.
  2764. if (mimetype == "image/png") { // Load buffer as PNG.
  2765. ERR_FAIL_COND_V(Image::_png_mem_loader_func == nullptr, ERR_UNAVAILABLE);
  2766. img = Image::_png_mem_loader_func(data_ptr, data_size);
  2767. } else if (mimetype == "image/jpeg") { // Loader buffer as JPEG.
  2768. ERR_FAIL_COND_V(Image::_jpg_mem_loader_func == nullptr, ERR_UNAVAILABLE);
  2769. img = Image::_jpg_mem_loader_func(data_ptr, data_size);
  2770. }
  2771. // If we didn't pass the above tests, we attempt loading as PNG and then
  2772. // JPEG directly.
  2773. // This covers URIs with base64-encoded data with application/* type but
  2774. // no optional mimeType property, or bufferViews with a bogus mimeType
  2775. // (e.g. `image/jpeg` but the data is actually PNG).
  2776. // That's not *exactly* what the spec mandates but this lets us be
  2777. // lenient with bogus glb files which do exist in production.
  2778. if (img.is_null()) { // Try PNG first.
  2779. ERR_FAIL_COND_V(Image::_png_mem_loader_func == nullptr, ERR_UNAVAILABLE);
  2780. img = Image::_png_mem_loader_func(data_ptr, data_size);
  2781. }
  2782. if (img.is_null()) { // And then JPEG.
  2783. ERR_FAIL_COND_V(Image::_jpg_mem_loader_func == nullptr, ERR_UNAVAILABLE);
  2784. img = Image::_jpg_mem_loader_func(data_ptr, data_size);
  2785. }
  2786. // Now we've done our best, fix your scenes.
  2787. if (img.is_null()) {
  2788. ERR_PRINT(vformat("glTF: Couldn't load image index '%d' with its given mimetype: %s.", i, mimetype));
  2789. p_state->images.push_back(Ref<Image>());
  2790. continue;
  2791. }
  2792. p_state->images.push_back(img);
  2793. }
  2794. print_verbose("glTF: Total images: " + itos(p_state->images.size()));
  2795. return OK;
  2796. }
  2797. Error GLTFDocument::_serialize_textures(Ref<GLTFState> p_state) {
  2798. if (!p_state->textures.size()) {
  2799. return OK;
  2800. }
  2801. Array textures;
  2802. for (int32_t i = 0; i < p_state->textures.size(); i++) {
  2803. Dictionary d;
  2804. Ref<GLTFTexture> t = p_state->textures[i];
  2805. ERR_CONTINUE(t->get_src_image() == -1);
  2806. d["source"] = t->get_src_image();
  2807. GLTFTextureSamplerIndex sampler_index = t->get_sampler();
  2808. if (sampler_index != -1) {
  2809. d["sampler"] = sampler_index;
  2810. }
  2811. textures.push_back(d);
  2812. }
  2813. p_state->json["textures"] = textures;
  2814. return OK;
  2815. }
  2816. Error GLTFDocument::_parse_textures(Ref<GLTFState> p_state) {
  2817. if (!p_state->json.has("textures")) {
  2818. return OK;
  2819. }
  2820. const Array &textures = p_state->json["textures"];
  2821. for (GLTFTextureIndex i = 0; i < textures.size(); i++) {
  2822. const Dictionary &d = textures[i];
  2823. ERR_FAIL_COND_V(!d.has("source"), ERR_PARSE_ERROR);
  2824. Ref<GLTFTexture> t;
  2825. t.instance();
  2826. GLTFImageIndex gltf_src_image_i = d["source"];
  2827. ERR_FAIL_INDEX_V(gltf_src_image_i, p_state->images.size(), ERR_PARSE_ERROR);
  2828. t->set_src_image(gltf_src_image_i);
  2829. if (d.has("sampler")) {
  2830. t->set_sampler(d["sampler"]);
  2831. } else {
  2832. t->set_sampler(-1);
  2833. }
  2834. p_state->textures.push_back(t);
  2835. Ref<Texture> tex;
  2836. // Create and cache the texture used in the engine
  2837. if (p_state->external_images_paths.has(t->get_src_image())) {
  2838. tex = ResourceLoader::load(p_state->external_images_paths[t->get_src_image()]);
  2839. } else {
  2840. Ref<ImageTexture> img_tex;
  2841. img_tex.instance();
  2842. img_tex->create_from_image(p_state->images[t->get_src_image()]);
  2843. // Set texture filter and repeat based on sampler settings. Only supported for embedded textures
  2844. const Ref<GLTFTextureSampler> sampler = _get_sampler_for_texture(p_state, i);
  2845. Texture::Flags flags = sampler->get_texture_flags();
  2846. img_tex->set_flags(flags);
  2847. tex = img_tex;
  2848. }
  2849. p_state->texture_cache.insert(i, tex);
  2850. }
  2851. return OK;
  2852. }
  2853. GLTFTextureIndex GLTFDocument::_set_texture(Ref<GLTFState> p_state, Ref<Texture> p_texture) {
  2854. ERR_FAIL_COND_V(p_texture.is_null(), -1);
  2855. ERR_FAIL_COND_V(p_texture->get_data().is_null(), -1);
  2856. // Create GLTF data structures for the new texture
  2857. Ref<GLTFTexture> gltf_texture;
  2858. gltf_texture.instance();
  2859. GLTFImageIndex gltf_src_image_i = p_state->images.size();
  2860. p_state->images.push_back(p_texture->get_data());
  2861. GLTFTextureSamplerIndex gltf_sampler_i = _set_sampler_for_mode(p_state, p_texture->get_flags());
  2862. gltf_texture->set_src_image(gltf_src_image_i);
  2863. gltf_texture->set_sampler(gltf_sampler_i);
  2864. GLTFTextureIndex gltf_texture_i = p_state->textures.size();
  2865. p_state->textures.push_back(gltf_texture);
  2866. p_state->texture_cache[gltf_texture_i] = p_texture;
  2867. return gltf_texture_i;
  2868. }
  2869. Ref<Texture> GLTFDocument::_get_texture(Ref<GLTFState> p_state, const GLTFTextureIndex p_texture) {
  2870. ERR_FAIL_INDEX_V(p_texture, p_state->textures.size(), Ref<Texture>());
  2871. return p_state->texture_cache[p_texture];
  2872. }
  2873. GLTFTextureSamplerIndex GLTFDocument::_set_sampler_for_mode(Ref<GLTFState> p_state, uint32_t p_mode) {
  2874. for (int i = 0; i < p_state->texture_samplers.size(); ++i) {
  2875. if (p_state->texture_samplers[i]->get_texture_flags() == p_mode) {
  2876. return i;
  2877. }
  2878. }
  2879. GLTFTextureSamplerIndex gltf_sampler_i = p_state->texture_samplers.size();
  2880. Ref<GLTFTextureSampler> gltf_sampler;
  2881. gltf_sampler.instance();
  2882. gltf_sampler->set_texture_flags(p_mode);
  2883. p_state->texture_samplers.push_back(gltf_sampler);
  2884. return gltf_sampler_i;
  2885. }
  2886. Ref<GLTFTextureSampler> GLTFDocument::_get_sampler_for_texture(Ref<GLTFState> p_state, const GLTFTextureIndex p_texture) {
  2887. ERR_FAIL_INDEX_V(p_texture, p_state->textures.size(), p_state->default_texture_sampler);
  2888. const GLTFTextureSamplerIndex sampler = p_state->textures[p_texture]->get_sampler();
  2889. if (sampler == -1) {
  2890. return p_state->default_texture_sampler;
  2891. } else {
  2892. ERR_FAIL_INDEX_V(sampler, p_state->texture_samplers.size(), p_state->default_texture_sampler);
  2893. return p_state->texture_samplers[sampler];
  2894. }
  2895. }
  2896. Error GLTFDocument::_serialize_texture_samplers(Ref<GLTFState> p_state) {
  2897. if (!p_state->texture_samplers.size()) {
  2898. return OK;
  2899. }
  2900. Array samplers;
  2901. for (int32_t i = 0; i < p_state->texture_samplers.size(); ++i) {
  2902. Dictionary d;
  2903. Ref<GLTFTextureSampler> s = p_state->texture_samplers[i];
  2904. d["magFilter"] = s->get_mag_filter();
  2905. d["minFilter"] = s->get_min_filter();
  2906. d["wrapS"] = s->get_wrap_s();
  2907. d["wrapT"] = s->get_wrap_t();
  2908. samplers.push_back(d);
  2909. }
  2910. p_state->json["samplers"] = samplers;
  2911. return OK;
  2912. }
  2913. Error GLTFDocument::_parse_texture_samplers(Ref<GLTFState> p_state) {
  2914. p_state->default_texture_sampler.instance();
  2915. p_state->default_texture_sampler->set_min_filter(GLTFTextureSampler::FilterMode::LINEAR_MIPMAP_LINEAR);
  2916. p_state->default_texture_sampler->set_mag_filter(GLTFTextureSampler::FilterMode::LINEAR);
  2917. p_state->default_texture_sampler->set_wrap_s(GLTFTextureSampler::WrapMode::REPEAT);
  2918. p_state->default_texture_sampler->set_wrap_t(GLTFTextureSampler::WrapMode::REPEAT);
  2919. if (!p_state->json.has("samplers")) {
  2920. return OK;
  2921. }
  2922. const Array &samplers = p_state->json["samplers"];
  2923. for (int i = 0; i < samplers.size(); ++i) {
  2924. const Dictionary &d = samplers[i];
  2925. Ref<GLTFTextureSampler> sampler;
  2926. sampler.instance();
  2927. if (d.has("minFilter")) {
  2928. sampler->set_min_filter(d["minFilter"]);
  2929. } else {
  2930. sampler->set_min_filter(GLTFTextureSampler::FilterMode::LINEAR_MIPMAP_LINEAR);
  2931. }
  2932. if (d.has("magFilter")) {
  2933. sampler->set_mag_filter(d["magFilter"]);
  2934. } else {
  2935. sampler->set_mag_filter(GLTFTextureSampler::FilterMode::LINEAR);
  2936. }
  2937. if (d.has("wrapS")) {
  2938. sampler->set_wrap_s(d["wrapS"]);
  2939. } else {
  2940. sampler->set_wrap_s(GLTFTextureSampler::WrapMode::REPEAT);
  2941. }
  2942. if (d.has("wrapT")) {
  2943. sampler->set_wrap_t(d["wrapT"]);
  2944. } else {
  2945. sampler->set_wrap_t(GLTFTextureSampler::WrapMode::REPEAT);
  2946. }
  2947. p_state->texture_samplers.push_back(sampler);
  2948. }
  2949. return OK;
  2950. }
  2951. Error GLTFDocument::_serialize_materials(Ref<GLTFState> p_state) {
  2952. Array materials;
  2953. for (int32_t i = 0; i < p_state->materials.size(); i++) {
  2954. Dictionary d;
  2955. Ref<Material3D> material = p_state->materials[i];
  2956. if (material.is_null()) {
  2957. materials.push_back(d);
  2958. continue;
  2959. }
  2960. if (!material->get_name().empty()) {
  2961. d["name"] = _gen_unique_name(p_state, material->get_name());
  2962. }
  2963. {
  2964. Dictionary mr;
  2965. {
  2966. Array arr;
  2967. const Color c = material->get_albedo().to_linear();
  2968. arr.push_back(c.r);
  2969. arr.push_back(c.g);
  2970. arr.push_back(c.b);
  2971. arr.push_back(c.a);
  2972. mr["baseColorFactor"] = arr;
  2973. }
  2974. {
  2975. Dictionary bct;
  2976. Ref<Texture> albedo_texture = material->get_texture(Material3D::TEXTURE_ALBEDO);
  2977. GLTFTextureIndex gltf_texture_index = -1;
  2978. if (albedo_texture.is_valid() && albedo_texture->get_data().is_valid()) {
  2979. albedo_texture->set_name(material->get_name() + "_albedo");
  2980. gltf_texture_index = _set_texture(p_state, albedo_texture);
  2981. }
  2982. if (gltf_texture_index != -1) {
  2983. bct["index"] = gltf_texture_index;
  2984. Dictionary extensions = _serialize_texture_transform_uv1(material);
  2985. if (!extensions.empty()) {
  2986. bct["extensions"] = extensions;
  2987. p_state->use_khr_texture_transform = true;
  2988. }
  2989. mr["baseColorTexture"] = bct;
  2990. }
  2991. }
  2992. mr["metallicFactor"] = material->get_metallic();
  2993. mr["roughnessFactor"] = material->get_roughness();
  2994. bool has_roughness = material->get_texture(Material3D::TEXTURE_ROUGHNESS).is_valid() && material->get_texture(Material3D::TEXTURE_ROUGHNESS)->get_data().is_valid();
  2995. bool has_ao = material->get_feature(Material3D::FEATURE_AMBIENT_OCCLUSION) && material->get_texture(Material3D::TEXTURE_AMBIENT_OCCLUSION).is_valid();
  2996. bool has_metalness = material->get_texture(Material3D::TEXTURE_METALLIC).is_valid() && material->get_texture(Material3D::TEXTURE_METALLIC)->get_data().is_valid();
  2997. if (has_ao || has_roughness || has_metalness) {
  2998. Dictionary mrt;
  2999. Ref<Texture> roughness_texture = material->get_texture(Material3D::TEXTURE_ROUGHNESS);
  3000. Material3D::TextureChannel roughness_channel = material->get_roughness_texture_channel();
  3001. Ref<Texture> metallic_texture = material->get_texture(Material3D::TEXTURE_METALLIC);
  3002. Material3D::TextureChannel metalness_channel = material->get_metallic_texture_channel();
  3003. Ref<Texture> ao_texture = material->get_texture(Material3D::TEXTURE_AMBIENT_OCCLUSION);
  3004. Material3D::TextureChannel ao_channel = material->get_ao_texture_channel();
  3005. Ref<ImageTexture> orm_texture;
  3006. orm_texture.instance();
  3007. Ref<Image> orm_image;
  3008. orm_image.instance();
  3009. int32_t height = 0;
  3010. int32_t width = 0;
  3011. Ref<Image> ao_image;
  3012. if (has_ao) {
  3013. height = ao_texture->get_height();
  3014. width = ao_texture->get_width();
  3015. ao_image = ao_texture->get_data();
  3016. Ref<ImageTexture> img_tex = ao_image;
  3017. if (img_tex.is_valid()) {
  3018. ao_image = img_tex->get_data();
  3019. }
  3020. if (ao_image->is_compressed()) {
  3021. ao_image->decompress();
  3022. }
  3023. }
  3024. Ref<Image> roughness_image;
  3025. if (has_roughness) {
  3026. height = roughness_texture->get_height();
  3027. width = roughness_texture->get_width();
  3028. roughness_image = roughness_texture->get_data();
  3029. Ref<ImageTexture> img_tex = roughness_image;
  3030. if (img_tex.is_valid()) {
  3031. roughness_image = img_tex->get_data();
  3032. }
  3033. if (roughness_image->is_compressed()) {
  3034. roughness_image->decompress();
  3035. }
  3036. }
  3037. Ref<Image> metallness_image;
  3038. if (has_metalness) {
  3039. height = metallic_texture->get_height();
  3040. width = metallic_texture->get_width();
  3041. metallness_image = metallic_texture->get_data();
  3042. Ref<ImageTexture> img_tex = metallness_image;
  3043. if (img_tex.is_valid()) {
  3044. metallness_image = img_tex->get_data();
  3045. }
  3046. if (metallness_image->is_compressed()) {
  3047. metallness_image->decompress();
  3048. }
  3049. }
  3050. Ref<Texture> albedo_texture = material->get_texture(Material3D::TEXTURE_ALBEDO);
  3051. if (albedo_texture.is_valid() && albedo_texture->get_data().is_valid()) {
  3052. height = albedo_texture->get_height();
  3053. width = albedo_texture->get_width();
  3054. }
  3055. orm_image->create(width, height, false, Image::FORMAT_RGBA8);
  3056. if (ao_image.is_valid() && ao_image->get_size() != Vector2(width, height)) {
  3057. ao_image->resize(width, height, Image::INTERPOLATE_LANCZOS);
  3058. }
  3059. if (roughness_image.is_valid() && roughness_image->get_size() != Vector2(width, height)) {
  3060. roughness_image->resize(width, height, Image::INTERPOLATE_LANCZOS);
  3061. }
  3062. if (metallness_image.is_valid() && metallness_image->get_size() != Vector2(width, height)) {
  3063. metallness_image->resize(width, height, Image::INTERPOLATE_LANCZOS);
  3064. }
  3065. orm_image->lock();
  3066. for (int32_t h = 0; h < height; h++) {
  3067. for (int32_t w = 0; w < width; w++) {
  3068. Color c = Color(1.0f, 1.0f, 1.0f);
  3069. if (has_ao) {
  3070. ao_image->lock();
  3071. if (Material3D::TextureChannel::TEXTURE_CHANNEL_RED == ao_channel) {
  3072. c.r = ao_image->get_pixel(w, h).r;
  3073. } else if (Material3D::TextureChannel::TEXTURE_CHANNEL_GREEN == ao_channel) {
  3074. c.r = ao_image->get_pixel(w, h).g;
  3075. } else if (Material3D::TextureChannel::TEXTURE_CHANNEL_BLUE == ao_channel) {
  3076. c.r = ao_image->get_pixel(w, h).b;
  3077. } else if (Material3D::TextureChannel::TEXTURE_CHANNEL_ALPHA == ao_channel) {
  3078. c.r = ao_image->get_pixel(w, h).a;
  3079. }
  3080. ao_image->lock();
  3081. }
  3082. if (has_roughness) {
  3083. roughness_image->lock();
  3084. if (Material3D::TextureChannel::TEXTURE_CHANNEL_RED == roughness_channel) {
  3085. c.g = roughness_image->get_pixel(w, h).r;
  3086. } else if (Material3D::TextureChannel::TEXTURE_CHANNEL_GREEN == roughness_channel) {
  3087. c.g = roughness_image->get_pixel(w, h).g;
  3088. } else if (Material3D::TextureChannel::TEXTURE_CHANNEL_BLUE == roughness_channel) {
  3089. c.g = roughness_image->get_pixel(w, h).b;
  3090. } else if (Material3D::TextureChannel::TEXTURE_CHANNEL_ALPHA == roughness_channel) {
  3091. c.g = roughness_image->get_pixel(w, h).a;
  3092. }
  3093. roughness_image->unlock();
  3094. }
  3095. if (has_metalness) {
  3096. metallness_image->lock();
  3097. if (Material3D::TextureChannel::TEXTURE_CHANNEL_RED == metalness_channel) {
  3098. c.b = metallness_image->get_pixel(w, h).r;
  3099. } else if (Material3D::TextureChannel::TEXTURE_CHANNEL_GREEN == metalness_channel) {
  3100. c.b = metallness_image->get_pixel(w, h).g;
  3101. } else if (Material3D::TextureChannel::TEXTURE_CHANNEL_BLUE == metalness_channel) {
  3102. c.b = metallness_image->get_pixel(w, h).b;
  3103. } else if (Material3D::TextureChannel::TEXTURE_CHANNEL_ALPHA == metalness_channel) {
  3104. c.b = metallness_image->get_pixel(w, h).a;
  3105. }
  3106. metallness_image->unlock();
  3107. }
  3108. orm_image->set_pixel(w, h, c);
  3109. }
  3110. }
  3111. orm_image->unlock();
  3112. orm_image->generate_mipmaps();
  3113. orm_texture->create_from_image(orm_image);
  3114. GLTFTextureIndex orm_texture_index = -1;
  3115. if (has_ao || has_roughness || has_metalness) {
  3116. orm_texture->set_name(material->get_name() + "_orm");
  3117. orm_texture_index = _set_texture(p_state, orm_texture);
  3118. }
  3119. if (has_ao) {
  3120. Dictionary ot;
  3121. ot["index"] = orm_texture_index;
  3122. d["occlusionTexture"] = ot;
  3123. }
  3124. if (has_roughness || has_metalness) {
  3125. mrt["index"] = orm_texture_index;
  3126. Dictionary extensions = _serialize_texture_transform_uv1(material);
  3127. if (!extensions.empty()) {
  3128. mrt["extensions"] = extensions;
  3129. p_state->use_khr_texture_transform = true;
  3130. }
  3131. mr["metallicRoughnessTexture"] = mrt;
  3132. }
  3133. }
  3134. d["pbrMetallicRoughness"] = mr;
  3135. }
  3136. if (material->get_feature(Material3D::FEATURE_NORMAL_MAPPING)) {
  3137. Dictionary nt;
  3138. Ref<ImageTexture> tex;
  3139. tex.instance();
  3140. {
  3141. Ref<Texture> normal_texture = material->get_texture(Material3D::TEXTURE_NORMAL);
  3142. if (normal_texture.is_valid()) {
  3143. // Code for uncompressing RG normal maps
  3144. Ref<Image> img = normal_texture->get_data();
  3145. if (img.is_valid()) {
  3146. Ref<ImageTexture> img_tex = img;
  3147. if (img_tex.is_valid()) {
  3148. img = img_tex->get_data();
  3149. }
  3150. img->decompress();
  3151. img->convert(Image::FORMAT_RGBA8);
  3152. img->lock();
  3153. for (int32_t y = 0; y < img->get_height(); y++) {
  3154. for (int32_t x = 0; x < img->get_width(); x++) {
  3155. Color c = img->get_pixel(x, y);
  3156. Vector2 red_green = Vector2(c.r, c.g);
  3157. red_green = red_green * Vector2(2.0f, 2.0f) - Vector2(1.0f, 1.0f);
  3158. float blue = 1.0f - red_green.dot(red_green);
  3159. blue = MAX(0.0f, blue);
  3160. c.b = Math::sqrt(blue);
  3161. img->set_pixel(x, y, c);
  3162. }
  3163. }
  3164. img->unlock();
  3165. tex->create_from_image(img);
  3166. }
  3167. }
  3168. }
  3169. GLTFTextureIndex gltf_texture_index = -1;
  3170. if (tex.is_valid() && tex->get_data().is_valid()) {
  3171. tex->set_name(material->get_name() + "_normal");
  3172. gltf_texture_index = _set_texture(p_state, tex);
  3173. }
  3174. nt["scale"] = material->get_normal_scale();
  3175. if (gltf_texture_index != -1) {
  3176. nt["index"] = gltf_texture_index;
  3177. d["normalTexture"] = nt;
  3178. }
  3179. }
  3180. if (material->get_feature(Material3D::FEATURE_EMISSION)) {
  3181. const Color c = material->get_emission().to_srgb();
  3182. Array arr;
  3183. arr.push_back(c.r);
  3184. arr.push_back(c.g);
  3185. arr.push_back(c.b);
  3186. d["emissiveFactor"] = arr;
  3187. }
  3188. if (material->get_feature(Material3D::FEATURE_EMISSION)) {
  3189. Dictionary et;
  3190. Ref<Texture> emission_texture = material->get_texture(Material3D::TEXTURE_EMISSION);
  3191. GLTFTextureIndex gltf_texture_index = -1;
  3192. if (emission_texture.is_valid() && emission_texture->get_data().is_valid()) {
  3193. emission_texture->set_name(material->get_name() + "_emission");
  3194. gltf_texture_index = _set_texture(p_state, emission_texture);
  3195. }
  3196. if (gltf_texture_index != -1) {
  3197. et["index"] = gltf_texture_index;
  3198. d["emissiveTexture"] = et;
  3199. }
  3200. }
  3201. const bool ds = material->get_cull_mode() == Material3D::CULL_DISABLED;
  3202. if (ds) {
  3203. d["doubleSided"] = ds;
  3204. }
  3205. if (material->get_feature(Material3D::FEATURE_TRANSPARENT)) {
  3206. if (material->get_flag(Material3D::FLAG_USE_ALPHA_SCISSOR)) {
  3207. d["alphaMode"] = "MASK";
  3208. d["alphaCutoff"] = material->get_alpha_scissor_threshold();
  3209. } else {
  3210. d["alphaMode"] = "BLEND";
  3211. }
  3212. }
  3213. Dictionary extensions;
  3214. if (material->get_flag(Material3D::FLAG_UNSHADED)) {
  3215. Dictionary mat_unlit;
  3216. extensions["KHR_materials_unlit"] = mat_unlit;
  3217. p_state->add_used_extension("KHR_materials_unlit");
  3218. }
  3219. d["extensions"] = extensions;
  3220. materials.push_back(d);
  3221. }
  3222. if (!materials.size()) {
  3223. return OK;
  3224. }
  3225. p_state->json["materials"] = materials;
  3226. print_verbose("Total materials: " + itos(p_state->materials.size()));
  3227. return OK;
  3228. }
  3229. Error GLTFDocument::_parse_materials(Ref<GLTFState> p_state) {
  3230. if (!p_state->json.has("materials")) {
  3231. return OK;
  3232. }
  3233. const Array &materials = p_state->json["materials"];
  3234. for (GLTFMaterialIndex i = 0; i < materials.size(); i++) {
  3235. const Dictionary &d = materials[i];
  3236. Ref<SpatialMaterial> material;
  3237. material.instance();
  3238. if (d.has("name") && !String(d["name"]).empty()) {
  3239. material->set_name(d["name"]);
  3240. } else {
  3241. material->set_name(vformat("material_%s", itos(i)));
  3242. }
  3243. material->set_flag(Material3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  3244. Dictionary pbr_spec_gloss_extensions;
  3245. if (d.has("extensions")) {
  3246. pbr_spec_gloss_extensions = d["extensions"];
  3247. }
  3248. if (pbr_spec_gloss_extensions.has("KHR_materials_unlit")) {
  3249. material->set_flag(Material3D::FLAG_UNSHADED, true);
  3250. }
  3251. if (pbr_spec_gloss_extensions.has("KHR_materials_pbrSpecularGlossiness")) {
  3252. WARN_PRINT("Material uses a specular and glossiness workflow. Textures will be converted to roughness and metallic workflow, which may not be 100% accurate.");
  3253. Dictionary sgm = pbr_spec_gloss_extensions["KHR_materials_pbrSpecularGlossiness"];
  3254. Ref<GLTFSpecGloss> spec_gloss;
  3255. spec_gloss.instance();
  3256. if (sgm.has("diffuseTexture")) {
  3257. const Dictionary &diffuse_texture_dict = sgm["diffuseTexture"];
  3258. if (diffuse_texture_dict.has("index")) {
  3259. Ref<Texture> diffuse_texture = _get_texture(p_state, diffuse_texture_dict["index"]);
  3260. if (diffuse_texture.is_valid()) {
  3261. spec_gloss->diffuse_img = diffuse_texture->get_data();
  3262. material->set_texture(Material3D::TEXTURE_ALBEDO, diffuse_texture);
  3263. }
  3264. }
  3265. }
  3266. if (sgm.has("diffuseFactor")) {
  3267. const Array &arr = sgm["diffuseFactor"];
  3268. ERR_FAIL_COND_V(arr.size() != 4, ERR_PARSE_ERROR);
  3269. const Color c = Color(arr[0], arr[1], arr[2], arr[3]).to_srgb();
  3270. spec_gloss->diffuse_factor = c;
  3271. material->set_albedo(spec_gloss->diffuse_factor);
  3272. }
  3273. if (sgm.has("specularFactor")) {
  3274. const Array &arr = sgm["specularFactor"];
  3275. ERR_FAIL_COND_V(arr.size() != 3, ERR_PARSE_ERROR);
  3276. spec_gloss->specular_factor = Color(arr[0], arr[1], arr[2]);
  3277. }
  3278. if (sgm.has("glossinessFactor")) {
  3279. spec_gloss->gloss_factor = sgm["glossinessFactor"];
  3280. material->set_roughness(1.0f - CLAMP(spec_gloss->gloss_factor, 0.0f, 1.0f));
  3281. }
  3282. if (sgm.has("specularGlossinessTexture")) {
  3283. const Dictionary &spec_gloss_texture = sgm["specularGlossinessTexture"];
  3284. if (spec_gloss_texture.has("index")) {
  3285. const Ref<Texture> orig_texture = _get_texture(p_state, spec_gloss_texture["index"]);
  3286. if (orig_texture.is_valid()) {
  3287. spec_gloss->spec_gloss_img = orig_texture->get_data();
  3288. }
  3289. }
  3290. }
  3291. spec_gloss_to_rough_metal(spec_gloss, material);
  3292. } else if (d.has("pbrMetallicRoughness")) {
  3293. const Dictionary &mr = d["pbrMetallicRoughness"];
  3294. if (mr.has("baseColorFactor")) {
  3295. const Array &arr = mr["baseColorFactor"];
  3296. ERR_FAIL_COND_V(arr.size() != 4, ERR_PARSE_ERROR);
  3297. const Color c = Color(arr[0], arr[1], arr[2], arr[3]).to_srgb();
  3298. material->set_albedo(c);
  3299. }
  3300. if (mr.has("baseColorTexture")) {
  3301. const Dictionary &bct = mr["baseColorTexture"];
  3302. if (bct.has("index")) {
  3303. material->set_texture(Material3D::TEXTURE_ALBEDO, _get_texture(p_state, bct["index"]));
  3304. }
  3305. if (!mr.has("baseColorFactor")) {
  3306. material->set_albedo(Color(1, 1, 1));
  3307. }
  3308. _set_texture_transform_uv1(bct, material);
  3309. }
  3310. if (mr.has("metallicFactor")) {
  3311. material->set_metallic(mr["metallicFactor"]);
  3312. } else {
  3313. material->set_metallic(1.0);
  3314. }
  3315. if (mr.has("roughnessFactor")) {
  3316. material->set_roughness(mr["roughnessFactor"]);
  3317. } else {
  3318. material->set_roughness(1.0);
  3319. }
  3320. if (mr.has("metallicRoughnessTexture")) {
  3321. const Dictionary &bct = mr["metallicRoughnessTexture"];
  3322. if (bct.has("index")) {
  3323. const Ref<Texture> t = _get_texture(p_state, bct["index"]);
  3324. material->set_texture(Material3D::TEXTURE_METALLIC, t);
  3325. material->set_metallic_texture_channel(Material3D::TEXTURE_CHANNEL_BLUE);
  3326. material->set_texture(Material3D::TEXTURE_ROUGHNESS, t);
  3327. material->set_roughness_texture_channel(Material3D::TEXTURE_CHANNEL_GREEN);
  3328. if (!mr.has("metallicFactor")) {
  3329. material->set_metallic(1);
  3330. }
  3331. if (!mr.has("roughnessFactor")) {
  3332. material->set_roughness(1);
  3333. }
  3334. }
  3335. }
  3336. }
  3337. if (d.has("normalTexture")) {
  3338. const Dictionary &bct = d["normalTexture"];
  3339. if (bct.has("index")) {
  3340. material->set_texture(Material3D::TEXTURE_NORMAL, _get_texture(p_state, bct["index"]));
  3341. material->set_feature(Material3D::FEATURE_NORMAL_MAPPING, true);
  3342. }
  3343. if (bct.has("scale")) {
  3344. material->set_normal_scale(bct["scale"]);
  3345. }
  3346. }
  3347. if (d.has("occlusionTexture")) {
  3348. const Dictionary &bct = d["occlusionTexture"];
  3349. if (bct.has("index")) {
  3350. material->set_texture(Material3D::TEXTURE_AMBIENT_OCCLUSION, _get_texture(p_state, bct["index"]));
  3351. material->set_ao_texture_channel(Material3D::TEXTURE_CHANNEL_RED);
  3352. material->set_feature(Material3D::FEATURE_AMBIENT_OCCLUSION, true);
  3353. }
  3354. }
  3355. if (d.has("emissiveFactor")) {
  3356. const Array &arr = d["emissiveFactor"];
  3357. ERR_FAIL_COND_V(arr.size() != 3, ERR_PARSE_ERROR);
  3358. const Color c = Color(arr[0], arr[1], arr[2]).to_srgb();
  3359. material->set_feature(Material3D::FEATURE_EMISSION, true);
  3360. material->set_emission(c);
  3361. }
  3362. if (d.has("emissiveTexture")) {
  3363. const Dictionary &bct = d["emissiveTexture"];
  3364. if (bct.has("index")) {
  3365. material->set_texture(Material3D::TEXTURE_EMISSION, _get_texture(p_state, bct["index"]));
  3366. material->set_feature(Material3D::FEATURE_EMISSION, true);
  3367. material->set_emission(Color(0, 0, 0));
  3368. }
  3369. }
  3370. if (d.has("doubleSided")) {
  3371. const bool ds = d["doubleSided"];
  3372. if (ds) {
  3373. material->set_cull_mode(Material3D::CULL_DISABLED);
  3374. }
  3375. }
  3376. if (d.has("alphaMode")) {
  3377. const String &am = d["alphaMode"];
  3378. if (am == "BLEND") {
  3379. material->set_feature(Material3D::FEATURE_TRANSPARENT, true);
  3380. material->set_depth_draw_mode(Material3D::DEPTH_DRAW_ALPHA_OPAQUE_PREPASS);
  3381. } else if (am == "MASK") {
  3382. material->set_flag(Material3D::FLAG_USE_ALPHA_SCISSOR, true);
  3383. if (d.has("alphaCutoff")) {
  3384. material->set_alpha_scissor_threshold(d["alphaCutoff"]);
  3385. } else {
  3386. material->set_alpha_scissor_threshold(0.5f);
  3387. }
  3388. }
  3389. }
  3390. p_state->materials.push_back(material);
  3391. }
  3392. print_verbose("Total materials: " + itos(p_state->materials.size()));
  3393. return OK;
  3394. }
  3395. void GLTFDocument::_set_texture_transform_uv1(const Dictionary &p_dict, Ref<Material3D> p_material) {
  3396. if (p_dict.has("extensions")) {
  3397. const Dictionary &extensions = p_dict["extensions"];
  3398. if (extensions.has("KHR_texture_transform")) {
  3399. const Dictionary &texture_transform = extensions["KHR_texture_transform"];
  3400. const Array &offset_arr = texture_transform["offset"];
  3401. if (offset_arr.size() == 2) {
  3402. const Vector3 offset_vector3 = Vector3(offset_arr[0], offset_arr[1], 0.0f);
  3403. p_material->set_uv1_offset(offset_vector3);
  3404. }
  3405. const Array &scale_arr = texture_transform["scale"];
  3406. if (scale_arr.size() == 2) {
  3407. const Vector3 scale_vector3 = Vector3(scale_arr[0], scale_arr[1], 1.0f);
  3408. p_material->set_uv1_scale(scale_vector3);
  3409. }
  3410. }
  3411. }
  3412. }
  3413. void GLTFDocument::spec_gloss_to_rough_metal(Ref<GLTFSpecGloss> r_spec_gloss, Ref<Material3D> p_material) {
  3414. if (r_spec_gloss->spec_gloss_img.is_null()) {
  3415. return;
  3416. }
  3417. if (r_spec_gloss->diffuse_img.is_null()) {
  3418. return;
  3419. }
  3420. Ref<Image> rm_img;
  3421. rm_img.instance();
  3422. bool has_roughness = false;
  3423. bool has_metal = false;
  3424. p_material->set_roughness(1.0f);
  3425. p_material->set_metallic(1.0f);
  3426. rm_img->create(r_spec_gloss->spec_gloss_img->get_width(), r_spec_gloss->spec_gloss_img->get_height(), false, Image::FORMAT_RGBA8);
  3427. rm_img->lock();
  3428. r_spec_gloss->spec_gloss_img->decompress();
  3429. if (r_spec_gloss->diffuse_img.is_valid()) {
  3430. r_spec_gloss->diffuse_img->decompress();
  3431. r_spec_gloss->diffuse_img->resize(r_spec_gloss->spec_gloss_img->get_width(), r_spec_gloss->spec_gloss_img->get_height(), Image::INTERPOLATE_LANCZOS);
  3432. r_spec_gloss->spec_gloss_img->resize(r_spec_gloss->diffuse_img->get_width(), r_spec_gloss->diffuse_img->get_height(), Image::INTERPOLATE_LANCZOS);
  3433. }
  3434. for (int32_t y = 0; y < r_spec_gloss->spec_gloss_img->get_height(); y++) {
  3435. for (int32_t x = 0; x < r_spec_gloss->spec_gloss_img->get_width(); x++) {
  3436. const Color specular_pixel = r_spec_gloss->spec_gloss_img->get_pixel(x, y).to_linear();
  3437. Color specular = Color(specular_pixel.r, specular_pixel.g, specular_pixel.b);
  3438. specular *= r_spec_gloss->specular_factor;
  3439. Color diffuse = Color(1.0f, 1.0f, 1.0f);
  3440. r_spec_gloss->diffuse_img->lock();
  3441. diffuse *= r_spec_gloss->diffuse_img->get_pixel(x, y).to_linear();
  3442. float metallic = 0.0f;
  3443. Color base_color;
  3444. spec_gloss_to_metal_base_color(specular, diffuse, base_color, metallic);
  3445. Color mr = Color(1.0f, 1.0f, 1.0f);
  3446. mr.g = specular_pixel.a;
  3447. mr.b = metallic;
  3448. if (!Math::is_equal_approx(mr.g, 1.0f)) {
  3449. has_roughness = true;
  3450. }
  3451. if (!Math::is_equal_approx(mr.b, 0.0f)) {
  3452. has_metal = true;
  3453. }
  3454. mr.g *= r_spec_gloss->gloss_factor;
  3455. mr.g = 1.0f - mr.g;
  3456. rm_img->set_pixel(x, y, mr);
  3457. r_spec_gloss->diffuse_img->set_pixel(x, y, base_color.to_srgb());
  3458. r_spec_gloss->diffuse_img->unlock();
  3459. }
  3460. }
  3461. rm_img->unlock();
  3462. rm_img->generate_mipmaps();
  3463. r_spec_gloss->diffuse_img->generate_mipmaps();
  3464. Ref<ImageTexture> diffuse_image_texture;
  3465. diffuse_image_texture.instance();
  3466. diffuse_image_texture->create_from_image(r_spec_gloss->diffuse_img);
  3467. p_material->set_texture(Material3D::TEXTURE_ALBEDO, diffuse_image_texture);
  3468. Ref<ImageTexture> rm_image_texture;
  3469. rm_image_texture.instance();
  3470. rm_image_texture->create_from_image(rm_img);
  3471. if (has_roughness) {
  3472. p_material->set_texture(Material3D::TEXTURE_ROUGHNESS, rm_image_texture);
  3473. p_material->set_roughness_texture_channel(Material3D::TEXTURE_CHANNEL_GREEN);
  3474. }
  3475. if (has_metal) {
  3476. p_material->set_texture(Material3D::TEXTURE_METALLIC, rm_image_texture);
  3477. p_material->set_metallic_texture_channel(Material3D::TEXTURE_CHANNEL_BLUE);
  3478. }
  3479. }
  3480. void GLTFDocument::spec_gloss_to_metal_base_color(const Color &p_specular_factor, const Color &p_diffuse, Color &r_base_color, float &r_metallic) {
  3481. const Color DIELECTRIC_SPECULAR = Color(0.04f, 0.04f, 0.04f);
  3482. Color specular = Color(p_specular_factor.r, p_specular_factor.g, p_specular_factor.b);
  3483. const float one_minus_specular_strength = 1.0f - get_max_component(specular);
  3484. const float dielectric_specular_red = DIELECTRIC_SPECULAR.r;
  3485. float brightness_diffuse = get_perceived_brightness(p_diffuse);
  3486. const float brightness_specular = get_perceived_brightness(specular);
  3487. r_metallic = solve_metallic(dielectric_specular_red, brightness_diffuse, brightness_specular, one_minus_specular_strength);
  3488. const float one_minus_metallic = 1.0f - r_metallic;
  3489. const Color base_color_from_diffuse = p_diffuse * (one_minus_specular_strength / (1.0f - dielectric_specular_red) / MAX(one_minus_metallic, CMP_EPSILON));
  3490. const Color base_color_from_specular = (specular - (DIELECTRIC_SPECULAR * (one_minus_metallic))) * (1.0f / MAX(r_metallic, CMP_EPSILON));
  3491. r_base_color.r = Math::lerp(base_color_from_diffuse.r, base_color_from_specular.r, r_metallic * r_metallic);
  3492. r_base_color.g = Math::lerp(base_color_from_diffuse.g, base_color_from_specular.g, r_metallic * r_metallic);
  3493. r_base_color.b = Math::lerp(base_color_from_diffuse.b, base_color_from_specular.b, r_metallic * r_metallic);
  3494. r_base_color.a = p_diffuse.a;
  3495. r_base_color.r = CLAMP(r_base_color.r, 0.0f, 1.0f);
  3496. r_base_color.g = CLAMP(r_base_color.g, 0.0f, 1.0f);
  3497. r_base_color.b = CLAMP(r_base_color.b, 0.0f, 1.0f);
  3498. r_base_color.a = CLAMP(r_base_color.a, 0.0f, 1.0f);
  3499. }
  3500. GLTFNodeIndex GLTFDocument::_find_highest_node(Ref<GLTFState> p_state, const Vector<GLTFNodeIndex> &p_subset) {
  3501. int highest = -1;
  3502. GLTFNodeIndex best_node = -1;
  3503. for (int i = 0; i < p_subset.size(); ++i) {
  3504. const GLTFNodeIndex node_i = p_subset[i];
  3505. const Ref<GLTFNode> node = p_state->nodes[node_i];
  3506. if (highest == -1 || node->height < highest) {
  3507. highest = node->height;
  3508. best_node = node_i;
  3509. }
  3510. }
  3511. return best_node;
  3512. }
  3513. bool GLTFDocument::_capture_nodes_in_skin(Ref<GLTFState> p_state, Ref<GLTFSkin> p_skin, const GLTFNodeIndex p_node_index) {
  3514. bool found_joint = false;
  3515. for (int i = 0; i < p_state->nodes[p_node_index]->children.size(); ++i) {
  3516. found_joint |= _capture_nodes_in_skin(p_state, p_skin, p_state->nodes[p_node_index]->children[i]);
  3517. }
  3518. if (found_joint) {
  3519. // Mark it if we happen to find another skins joint...
  3520. if (p_state->nodes[p_node_index]->joint && p_skin->joints.find(p_node_index) < 0) {
  3521. p_skin->joints.push_back(p_node_index);
  3522. } else if (p_skin->non_joints.find(p_node_index) < 0) {
  3523. p_skin->non_joints.push_back(p_node_index);
  3524. }
  3525. }
  3526. if (p_skin->joints.find(p_node_index) > 0) {
  3527. return true;
  3528. }
  3529. return false;
  3530. }
  3531. void GLTFDocument::_capture_nodes_for_multirooted_skin(Ref<GLTFState> p_state, Ref<GLTFSkin> p_skin) {
  3532. DisjointSet<GLTFNodeIndex> disjoint_set;
  3533. for (int i = 0; i < p_skin->joints.size(); ++i) {
  3534. const GLTFNodeIndex node_index = p_skin->joints[i];
  3535. const GLTFNodeIndex parent = p_state->nodes[node_index]->parent;
  3536. disjoint_set.insert(node_index);
  3537. if (p_skin->joints.find(parent) >= 0) {
  3538. disjoint_set.create_union(parent, node_index);
  3539. }
  3540. }
  3541. Vector<GLTFNodeIndex> roots;
  3542. disjoint_set.get_representatives(roots);
  3543. if (roots.size() <= 1) {
  3544. return;
  3545. }
  3546. int maxHeight = -1;
  3547. // Determine the max height rooted tree
  3548. for (int i = 0; i < roots.size(); ++i) {
  3549. const GLTFNodeIndex root = roots[i];
  3550. if (maxHeight == -1 || p_state->nodes[root]->height < maxHeight) {
  3551. maxHeight = p_state->nodes[root]->height;
  3552. }
  3553. }
  3554. // Go up the tree till all of the multiple roots of the skin are at the same hierarchy level.
  3555. // This sucks, but 99% of all game engines (not just Godot) would have this same issue.
  3556. for (int i = 0; i < roots.size(); ++i) {
  3557. GLTFNodeIndex current_node = roots[i];
  3558. while (p_state->nodes[current_node]->height > maxHeight) {
  3559. GLTFNodeIndex parent = p_state->nodes[current_node]->parent;
  3560. if (p_state->nodes[parent]->joint && p_skin->joints.find(parent) < 0) {
  3561. p_skin->joints.push_back(parent);
  3562. } else if (p_skin->non_joints.find(parent) < 0) {
  3563. p_skin->non_joints.push_back(parent);
  3564. }
  3565. current_node = parent;
  3566. }
  3567. // replace the roots
  3568. roots.write[i] = current_node;
  3569. }
  3570. // Climb up the tree until they all have the same parent
  3571. bool all_same;
  3572. do {
  3573. all_same = true;
  3574. const GLTFNodeIndex first_parent = p_state->nodes[roots[0]]->parent;
  3575. for (int i = 1; i < roots.size(); ++i) {
  3576. all_same &= (first_parent == p_state->nodes[roots[i]]->parent);
  3577. }
  3578. if (!all_same) {
  3579. for (int i = 0; i < roots.size(); ++i) {
  3580. const GLTFNodeIndex current_node = roots[i];
  3581. const GLTFNodeIndex parent = p_state->nodes[current_node]->parent;
  3582. if (p_state->nodes[parent]->joint && p_skin->joints.find(parent) < 0) {
  3583. p_skin->joints.push_back(parent);
  3584. } else if (p_skin->non_joints.find(parent) < 0) {
  3585. p_skin->non_joints.push_back(parent);
  3586. }
  3587. roots.write[i] = parent;
  3588. }
  3589. }
  3590. } while (!all_same);
  3591. }
  3592. Error GLTFDocument::_expand_skin(Ref<GLTFState> p_state, Ref<GLTFSkin> p_skin) {
  3593. _capture_nodes_for_multirooted_skin(p_state, p_skin);
  3594. // Grab all nodes that lay in between skin joints/nodes
  3595. DisjointSet<GLTFNodeIndex> disjoint_set;
  3596. Vector<GLTFNodeIndex> all_skin_nodes;
  3597. all_skin_nodes.append_array(p_skin->joints);
  3598. all_skin_nodes.append_array(p_skin->non_joints);
  3599. for (int i = 0; i < all_skin_nodes.size(); ++i) {
  3600. const GLTFNodeIndex node_index = all_skin_nodes[i];
  3601. const GLTFNodeIndex parent = p_state->nodes[node_index]->parent;
  3602. disjoint_set.insert(node_index);
  3603. if (all_skin_nodes.find(parent) >= 0) {
  3604. disjoint_set.create_union(parent, node_index);
  3605. }
  3606. }
  3607. Vector<GLTFNodeIndex> out_owners;
  3608. disjoint_set.get_representatives(out_owners);
  3609. Vector<GLTFNodeIndex> out_roots;
  3610. for (int i = 0; i < out_owners.size(); ++i) {
  3611. Vector<GLTFNodeIndex> set;
  3612. disjoint_set.get_members(set, out_owners[i]);
  3613. const GLTFNodeIndex root = _find_highest_node(p_state, set);
  3614. ERR_FAIL_COND_V(root < 0, FAILED);
  3615. out_roots.push_back(root);
  3616. }
  3617. out_roots.sort();
  3618. for (int i = 0; i < out_roots.size(); ++i) {
  3619. _capture_nodes_in_skin(p_state, p_skin, out_roots[i]);
  3620. }
  3621. p_skin->roots = out_roots;
  3622. return OK;
  3623. }
  3624. Error GLTFDocument::_verify_skin(Ref<GLTFState> p_state, Ref<GLTFSkin> p_skin) {
  3625. // This may seem duplicated from expand_skins, but this is really a sanity check! (so it kinda is)
  3626. // In case additional interpolating logic is added to the skins, this will help ensure that you
  3627. // do not cause it to self implode into a fiery blaze
  3628. // We are going to re-calculate the root nodes and compare them to the ones saved in the skin,
  3629. // then ensure the multiple trees (if they exist) are on the same sublevel
  3630. // Grab all nodes that lay in between skin joints/nodes
  3631. DisjointSet<GLTFNodeIndex> disjoint_set;
  3632. Vector<GLTFNodeIndex> all_skin_nodes;
  3633. all_skin_nodes.append_array(p_skin->joints);
  3634. all_skin_nodes.append_array(p_skin->non_joints);
  3635. for (int i = 0; i < all_skin_nodes.size(); ++i) {
  3636. const GLTFNodeIndex node_index = all_skin_nodes[i];
  3637. const GLTFNodeIndex parent = p_state->nodes[node_index]->parent;
  3638. disjoint_set.insert(node_index);
  3639. if (all_skin_nodes.find(parent) >= 0) {
  3640. disjoint_set.create_union(parent, node_index);
  3641. }
  3642. }
  3643. Vector<GLTFNodeIndex> out_owners;
  3644. disjoint_set.get_representatives(out_owners);
  3645. Vector<GLTFNodeIndex> out_roots;
  3646. for (int i = 0; i < out_owners.size(); ++i) {
  3647. Vector<GLTFNodeIndex> set;
  3648. disjoint_set.get_members(set, out_owners[i]);
  3649. const GLTFNodeIndex root = _find_highest_node(p_state, set);
  3650. ERR_FAIL_COND_V(root < 0, FAILED);
  3651. out_roots.push_back(root);
  3652. }
  3653. out_roots.sort();
  3654. ERR_FAIL_COND_V(out_roots.size() == 0, FAILED);
  3655. // Make sure the roots are the exact same (they better be)
  3656. ERR_FAIL_COND_V(out_roots.size() != p_skin->roots.size(), FAILED);
  3657. for (int i = 0; i < out_roots.size(); ++i) {
  3658. ERR_FAIL_COND_V(out_roots[i] != p_skin->roots[i], FAILED);
  3659. }
  3660. // Single rooted skin? Perfectly ok!
  3661. if (out_roots.size() == 1) {
  3662. return OK;
  3663. }
  3664. // Make sure all parents of a multi-rooted skin are the SAME
  3665. const GLTFNodeIndex parent = p_state->nodes[out_roots[0]]->parent;
  3666. for (int i = 1; i < out_roots.size(); ++i) {
  3667. if (p_state->nodes[out_roots[i]]->parent != parent) {
  3668. return FAILED;
  3669. }
  3670. }
  3671. return OK;
  3672. }
  3673. Error GLTFDocument::_parse_skins(Ref<GLTFState> p_state) {
  3674. if (!p_state->json.has("skins")) {
  3675. return OK;
  3676. }
  3677. const Array &skins = p_state->json["skins"];
  3678. // Create the base skins, and mark nodes that are joints
  3679. for (int i = 0; i < skins.size(); i++) {
  3680. const Dictionary &d = skins[i];
  3681. Ref<GLTFSkin> skin;
  3682. skin.instance();
  3683. ERR_FAIL_COND_V(!d.has("joints"), ERR_PARSE_ERROR);
  3684. const Array &joints = d["joints"];
  3685. if (d.has("inverseBindMatrices")) {
  3686. skin->inverse_binds = _decode_accessor_as_xform(p_state, d["inverseBindMatrices"], false);
  3687. ERR_FAIL_COND_V(skin->inverse_binds.size() != joints.size(), ERR_PARSE_ERROR);
  3688. }
  3689. for (int j = 0; j < joints.size(); j++) {
  3690. const GLTFNodeIndex node = joints[j];
  3691. ERR_FAIL_INDEX_V(node, p_state->nodes.size(), ERR_PARSE_ERROR);
  3692. skin->joints.push_back(node);
  3693. skin->joints_original.push_back(node);
  3694. p_state->nodes.write[node]->joint = true;
  3695. }
  3696. if (d.has("name") && !String(d["name"]).empty()) {
  3697. skin->set_name(d["name"]);
  3698. } else {
  3699. skin->set_name(vformat("skin_%s", itos(i)));
  3700. }
  3701. if (d.has("skeleton")) {
  3702. skin->skin_root = d["skeleton"];
  3703. }
  3704. p_state->skins.push_back(skin);
  3705. }
  3706. for (GLTFSkinIndex i = 0; i < p_state->skins.size(); ++i) {
  3707. Ref<GLTFSkin> skin = p_state->skins.write[i];
  3708. // Expand the skin to capture all the extra non-joints that lie in between the actual joints,
  3709. // and expand the hierarchy to ensure multi-rooted trees lie on the same height level
  3710. ERR_FAIL_COND_V(_expand_skin(p_state, skin), ERR_PARSE_ERROR);
  3711. ERR_FAIL_COND_V(_verify_skin(p_state, skin), ERR_PARSE_ERROR);
  3712. }
  3713. print_verbose("glTF: Total skins: " + itos(p_state->skins.size()));
  3714. return OK;
  3715. }
  3716. Error GLTFDocument::_determine_skeletons(Ref<GLTFState> p_state) {
  3717. // Using a disjoint set, we are going to potentially combine all skins that are actually branches
  3718. // of a main skeleton, or treat skins defining the same set of nodes as ONE skeleton.
  3719. // This is another unclear issue caused by the current glTF specification.
  3720. DisjointSet<GLTFNodeIndex> skeleton_sets;
  3721. for (GLTFSkinIndex skin_i = 0; skin_i < p_state->skins.size(); ++skin_i) {
  3722. const Ref<GLTFSkin> skin = p_state->skins[skin_i];
  3723. Vector<GLTFNodeIndex> all_skin_nodes;
  3724. all_skin_nodes.append_array(skin->joints);
  3725. all_skin_nodes.append_array(skin->non_joints);
  3726. for (int i = 0; i < all_skin_nodes.size(); ++i) {
  3727. const GLTFNodeIndex node_index = all_skin_nodes[i];
  3728. const GLTFNodeIndex parent = p_state->nodes[node_index]->parent;
  3729. skeleton_sets.insert(node_index);
  3730. if (all_skin_nodes.find(parent) >= 0) {
  3731. skeleton_sets.create_union(parent, node_index);
  3732. }
  3733. }
  3734. // We are going to connect the separate skin subtrees in each skin together
  3735. // so that the final roots are entire sets of valid skin trees
  3736. for (int i = 1; i < skin->roots.size(); ++i) {
  3737. skeleton_sets.create_union(skin->roots[0], skin->roots[i]);
  3738. }
  3739. }
  3740. { // attempt to joint all touching subsets (siblings/parent are part of another skin)
  3741. Vector<GLTFNodeIndex> groups_representatives;
  3742. skeleton_sets.get_representatives(groups_representatives);
  3743. Vector<GLTFNodeIndex> highest_group_members;
  3744. Vector<Vector<GLTFNodeIndex>> groups;
  3745. for (int i = 0; i < groups_representatives.size(); ++i) {
  3746. Vector<GLTFNodeIndex> group;
  3747. skeleton_sets.get_members(group, groups_representatives[i]);
  3748. highest_group_members.push_back(_find_highest_node(p_state, group));
  3749. groups.push_back(group);
  3750. }
  3751. for (int i = 0; i < highest_group_members.size(); ++i) {
  3752. const GLTFNodeIndex node_i = highest_group_members[i];
  3753. // Attach any siblings together (this needs to be done n^2/2 times)
  3754. for (int j = i + 1; j < highest_group_members.size(); ++j) {
  3755. const GLTFNodeIndex node_j = highest_group_members[j];
  3756. // Even if they are siblings under the root! :)
  3757. if (p_state->nodes[node_i]->parent == p_state->nodes[node_j]->parent) {
  3758. skeleton_sets.create_union(node_i, node_j);
  3759. }
  3760. }
  3761. // Attach any parenting going on together (we need to do this n^2 times)
  3762. const GLTFNodeIndex node_i_parent = p_state->nodes[node_i]->parent;
  3763. if (node_i_parent >= 0) {
  3764. for (int j = 0; j < groups.size() && i != j; ++j) {
  3765. const Vector<GLTFNodeIndex> &group = groups[j];
  3766. if (group.find(node_i_parent) >= 0) {
  3767. const GLTFNodeIndex node_j = highest_group_members[j];
  3768. skeleton_sets.create_union(node_i, node_j);
  3769. }
  3770. }
  3771. }
  3772. }
  3773. }
  3774. // At this point, the skeleton groups should be finalized
  3775. Vector<GLTFNodeIndex> skeleton_owners;
  3776. skeleton_sets.get_representatives(skeleton_owners);
  3777. // Mark all the skins actual skeletons, after we have merged them
  3778. for (GLTFSkeletonIndex skel_i = 0; skel_i < skeleton_owners.size(); ++skel_i) {
  3779. const GLTFNodeIndex skeleton_owner = skeleton_owners[skel_i];
  3780. Ref<GLTFSkeleton> skeleton;
  3781. skeleton.instance();
  3782. Vector<GLTFNodeIndex> skeleton_nodes;
  3783. skeleton_sets.get_members(skeleton_nodes, skeleton_owner);
  3784. for (GLTFSkinIndex skin_i = 0; skin_i < p_state->skins.size(); ++skin_i) {
  3785. Ref<GLTFSkin> skin = p_state->skins.write[skin_i];
  3786. // If any of the the skeletons nodes exist in a skin, that skin now maps to the skeleton
  3787. for (int i = 0; i < skeleton_nodes.size(); ++i) {
  3788. GLTFNodeIndex skel_node_i = skeleton_nodes[i];
  3789. if (skin->joints.find(skel_node_i) >= 0 || skin->non_joints.find(skel_node_i) >= 0) {
  3790. skin->skeleton = skel_i;
  3791. continue;
  3792. }
  3793. }
  3794. }
  3795. Vector<GLTFNodeIndex> non_joints;
  3796. for (int i = 0; i < skeleton_nodes.size(); ++i) {
  3797. const GLTFNodeIndex node_i = skeleton_nodes[i];
  3798. if (p_state->nodes[node_i]->joint) {
  3799. skeleton->joints.push_back(node_i);
  3800. } else {
  3801. non_joints.push_back(node_i);
  3802. }
  3803. }
  3804. p_state->skeletons.push_back(skeleton);
  3805. _reparent_non_joint_skeleton_subtrees(p_state, p_state->skeletons.write[skel_i], non_joints);
  3806. }
  3807. for (GLTFSkeletonIndex skel_i = 0; skel_i < p_state->skeletons.size(); ++skel_i) {
  3808. Ref<GLTFSkeleton> skeleton = p_state->skeletons.write[skel_i];
  3809. for (int i = 0; i < skeleton->joints.size(); ++i) {
  3810. const GLTFNodeIndex node_i = skeleton->joints[i];
  3811. Ref<GLTFNode> node = p_state->nodes[node_i];
  3812. ERR_FAIL_COND_V(!node->joint, ERR_PARSE_ERROR);
  3813. ERR_FAIL_COND_V(node->skeleton >= 0, ERR_PARSE_ERROR);
  3814. node->skeleton = skel_i;
  3815. }
  3816. ERR_FAIL_COND_V(_determine_skeleton_roots(p_state, skel_i), ERR_PARSE_ERROR);
  3817. }
  3818. return OK;
  3819. }
  3820. Error GLTFDocument::_reparent_non_joint_skeleton_subtrees(Ref<GLTFState> p_state, Ref<GLTFSkeleton> p_skeleton, const Vector<GLTFNodeIndex> &p_non_joints) {
  3821. DisjointSet<GLTFNodeIndex> subtree_set;
  3822. // Populate the disjoint set with ONLY non joints that are in the skeleton hierarchy (non_joints vector)
  3823. // This way we can find any joints that lie in between joints, as the current glTF specification
  3824. // mentions nothing about non-joints being in between joints of the same skin. Hopefully one day we
  3825. // can remove this code.
  3826. // skinD depicted here explains this issue:
  3827. // https://github.com/KhronosGroup/glTF-Asset-Generator/blob/master/Output/Positive/Animation_Skin
  3828. for (int i = 0; i < p_non_joints.size(); ++i) {
  3829. const GLTFNodeIndex node_i = p_non_joints[i];
  3830. subtree_set.insert(node_i);
  3831. const GLTFNodeIndex parent_i = p_state->nodes[node_i]->parent;
  3832. if (parent_i >= 0 && p_non_joints.find(parent_i) >= 0 && !p_state->nodes[parent_i]->joint) {
  3833. subtree_set.create_union(parent_i, node_i);
  3834. }
  3835. }
  3836. // Find all the non joint subtrees and re-parent them to a new "fake" joint
  3837. Vector<GLTFNodeIndex> non_joint_subtree_roots;
  3838. subtree_set.get_representatives(non_joint_subtree_roots);
  3839. for (int root_i = 0; root_i < non_joint_subtree_roots.size(); ++root_i) {
  3840. const GLTFNodeIndex subtree_root = non_joint_subtree_roots[root_i];
  3841. Vector<GLTFNodeIndex> subtree_nodes;
  3842. subtree_set.get_members(subtree_nodes, subtree_root);
  3843. for (int subtree_i = 0; subtree_i < subtree_nodes.size(); ++subtree_i) {
  3844. Ref<GLTFNode> node = p_state->nodes[subtree_nodes[subtree_i]];
  3845. node->joint = true;
  3846. // Add the joint to the skeletons joints
  3847. p_skeleton->joints.push_back(subtree_nodes[subtree_i]);
  3848. }
  3849. }
  3850. return OK;
  3851. }
  3852. Error GLTFDocument::_determine_skeleton_roots(Ref<GLTFState> p_state, const GLTFSkeletonIndex p_skel_i) {
  3853. DisjointSet<GLTFNodeIndex> disjoint_set;
  3854. for (GLTFNodeIndex i = 0; i < p_state->nodes.size(); ++i) {
  3855. const Ref<GLTFNode> node = p_state->nodes[i];
  3856. if (node->skeleton != p_skel_i) {
  3857. continue;
  3858. }
  3859. disjoint_set.insert(i);
  3860. if (node->parent >= 0 && p_state->nodes[node->parent]->skeleton == p_skel_i) {
  3861. disjoint_set.create_union(node->parent, i);
  3862. }
  3863. }
  3864. Ref<GLTFSkeleton> skeleton = p_state->skeletons.write[p_skel_i];
  3865. Vector<GLTFNodeIndex> owners;
  3866. disjoint_set.get_representatives(owners);
  3867. Vector<GLTFNodeIndex> roots;
  3868. for (int i = 0; i < owners.size(); ++i) {
  3869. Vector<GLTFNodeIndex> set;
  3870. disjoint_set.get_members(set, owners[i]);
  3871. const GLTFNodeIndex root = _find_highest_node(p_state, set);
  3872. ERR_FAIL_COND_V(root < 0, FAILED);
  3873. roots.push_back(root);
  3874. }
  3875. roots.sort();
  3876. PoolVector<GLTFNodeIndex> roots_array;
  3877. roots_array.resize(roots.size());
  3878. PoolVector<GLTFNodeIndex>::Write write_roots = roots_array.write();
  3879. for (int32_t root_i = 0; root_i < roots_array.size(); root_i++) {
  3880. write_roots[root_i] = roots[root_i];
  3881. }
  3882. skeleton->roots = roots_array;
  3883. if (roots.size() == 0) {
  3884. return FAILED;
  3885. } else if (roots.size() == 1) {
  3886. return OK;
  3887. }
  3888. // Check that the subtrees have the same parent root
  3889. const GLTFNodeIndex parent = p_state->nodes[roots[0]]->parent;
  3890. for (int i = 1; i < roots.size(); ++i) {
  3891. if (p_state->nodes[roots[i]]->parent != parent) {
  3892. return FAILED;
  3893. }
  3894. }
  3895. return OK;
  3896. }
  3897. Error GLTFDocument::_create_skeletons(Ref<GLTFState> p_state) {
  3898. for (GLTFSkeletonIndex skel_i = 0; skel_i < p_state->skeletons.size(); ++skel_i) {
  3899. Ref<GLTFSkeleton> gltf_skeleton = p_state->skeletons.write[skel_i];
  3900. Skeleton *skeleton = memnew(Skeleton);
  3901. gltf_skeleton->godot_skeleton = skeleton;
  3902. p_state->skeleton3d_to_gltf_skeleton[skeleton->get_instance_id()] = skel_i;
  3903. // Make a unique name, no gltf node represents this skeleton
  3904. skeleton->set_name(_gen_unique_name(p_state, "Skeleton"));
  3905. List<GLTFNodeIndex> bones;
  3906. for (int i = 0; i < gltf_skeleton->roots.size(); ++i) {
  3907. bones.push_back(gltf_skeleton->roots[i]);
  3908. }
  3909. // Make the skeleton creation deterministic by going through the roots in
  3910. // a sorted order, and DEPTH FIRST
  3911. bones.sort();
  3912. while (!bones.empty()) {
  3913. const GLTFNodeIndex node_i = bones.front()->get();
  3914. bones.pop_front();
  3915. Ref<GLTFNode> node = p_state->nodes[node_i];
  3916. ERR_FAIL_COND_V(node->skeleton != skel_i, FAILED);
  3917. { // Add all child nodes to the stack (deterministically)
  3918. Vector<GLTFNodeIndex> child_nodes;
  3919. for (int i = 0; i < node->children.size(); ++i) {
  3920. const GLTFNodeIndex child_i = node->children[i];
  3921. if (p_state->nodes[child_i]->skeleton == skel_i) {
  3922. child_nodes.push_back(child_i);
  3923. }
  3924. }
  3925. // Depth first insertion
  3926. child_nodes.sort();
  3927. for (int i = child_nodes.size() - 1; i >= 0; --i) {
  3928. bones.push_front(child_nodes[i]);
  3929. }
  3930. }
  3931. const int bone_index = skeleton->get_bone_count();
  3932. if (node->get_name().empty()) {
  3933. node->set_name("bone");
  3934. }
  3935. node->set_name(_gen_unique_bone_name(p_state, skel_i, node->get_name()));
  3936. skeleton->add_bone(node->get_name());
  3937. skeleton->set_bone_rest(bone_index, node->xform);
  3938. if (node->parent >= 0 && p_state->nodes[node->parent]->skeleton == skel_i) {
  3939. const int bone_parent = skeleton->find_bone(p_state->nodes[node->parent]->get_name());
  3940. ERR_FAIL_COND_V(bone_parent < 0, FAILED);
  3941. skeleton->set_bone_parent(bone_index, skeleton->find_bone(p_state->nodes[node->parent]->get_name()));
  3942. }
  3943. p_state->scene_nodes.insert(node_i, skeleton);
  3944. }
  3945. }
  3946. ERR_FAIL_COND_V(_map_skin_joints_indices_to_skeleton_bone_indices(p_state), ERR_PARSE_ERROR);
  3947. return OK;
  3948. }
  3949. Error GLTFDocument::_map_skin_joints_indices_to_skeleton_bone_indices(Ref<GLTFState> p_state) {
  3950. for (GLTFSkinIndex skin_i = 0; skin_i < p_state->skins.size(); ++skin_i) {
  3951. Ref<GLTFSkin> skin = p_state->skins.write[skin_i];
  3952. Ref<GLTFSkeleton> skeleton = p_state->skeletons[skin->skeleton];
  3953. for (int joint_index = 0; joint_index < skin->joints_original.size(); ++joint_index) {
  3954. const GLTFNodeIndex node_i = skin->joints_original[joint_index];
  3955. const Ref<GLTFNode> node = p_state->nodes[node_i];
  3956. const int bone_index = skeleton->godot_skeleton->find_bone(node->get_name());
  3957. ERR_FAIL_COND_V(bone_index < 0, FAILED);
  3958. skin->joint_i_to_bone_i.insert(joint_index, bone_index);
  3959. }
  3960. }
  3961. return OK;
  3962. }
  3963. Error GLTFDocument::_serialize_skins(Ref<GLTFState> p_state) {
  3964. _remove_duplicate_skins(p_state);
  3965. Array json_skins;
  3966. for (int skin_i = 0; skin_i < p_state->skins.size(); skin_i++) {
  3967. Ref<GLTFSkin> gltf_skin = p_state->skins[skin_i];
  3968. Dictionary json_skin;
  3969. json_skin["inverseBindMatrices"] = _encode_accessor_as_xform(p_state, gltf_skin->inverse_binds, false);
  3970. json_skin["joints"] = gltf_skin->get_joints();
  3971. json_skin["name"] = gltf_skin->get_name();
  3972. json_skins.push_back(json_skin);
  3973. }
  3974. if (!p_state->skins.size()) {
  3975. return OK;
  3976. }
  3977. p_state->json["skins"] = json_skins;
  3978. return OK;
  3979. }
  3980. Error GLTFDocument::_create_skins(Ref<GLTFState> p_state) {
  3981. for (GLTFSkinIndex skin_i = 0; skin_i < p_state->skins.size(); ++skin_i) {
  3982. Ref<GLTFSkin> gltf_skin = p_state->skins.write[skin_i];
  3983. Ref<Skin> skin;
  3984. skin.instance();
  3985. // Some skins don't have IBM's! What absolute monsters!
  3986. const bool has_ibms = !gltf_skin->inverse_binds.empty();
  3987. for (int joint_i = 0; joint_i < gltf_skin->joints_original.size(); ++joint_i) {
  3988. GLTFNodeIndex node = gltf_skin->joints_original[joint_i];
  3989. String bone_name = p_state->nodes[node]->get_name();
  3990. Transform xform;
  3991. if (has_ibms) {
  3992. xform = gltf_skin->inverse_binds[joint_i];
  3993. }
  3994. if (p_state->use_named_skin_binds) {
  3995. skin->add_named_bind(bone_name, xform);
  3996. } else {
  3997. int32_t bone_i = gltf_skin->joint_i_to_bone_i[joint_i];
  3998. skin->add_bind(bone_i, xform);
  3999. }
  4000. }
  4001. gltf_skin->godot_skin = skin;
  4002. }
  4003. // Purge the duplicates!
  4004. _remove_duplicate_skins(p_state);
  4005. // Create unique names now, after removing duplicates
  4006. for (GLTFSkinIndex skin_i = 0; skin_i < p_state->skins.size(); ++skin_i) {
  4007. Ref<Skin> skin = p_state->skins.write[skin_i]->godot_skin;
  4008. if (skin->get_name().empty()) {
  4009. // Make a unique name, no gltf node represents this skin
  4010. skin->set_name(_gen_unique_name(p_state, "Skin"));
  4011. }
  4012. }
  4013. return OK;
  4014. }
  4015. bool GLTFDocument::_skins_are_same(const Ref<Skin> p_skin_a, const Ref<Skin> p_skin_b) {
  4016. if (p_skin_a->get_bind_count() != p_skin_b->get_bind_count()) {
  4017. return false;
  4018. }
  4019. for (int i = 0; i < p_skin_a->get_bind_count(); ++i) {
  4020. if (p_skin_a->get_bind_bone(i) != p_skin_b->get_bind_bone(i)) {
  4021. return false;
  4022. }
  4023. if (p_skin_a->get_bind_name(i) != p_skin_b->get_bind_name(i)) {
  4024. return false;
  4025. }
  4026. Transform a_xform = p_skin_a->get_bind_pose(i);
  4027. Transform b_xform = p_skin_b->get_bind_pose(i);
  4028. if (a_xform != b_xform) {
  4029. return false;
  4030. }
  4031. }
  4032. return true;
  4033. }
  4034. void GLTFDocument::_remove_duplicate_skins(Ref<GLTFState> p_state) {
  4035. for (int i = 0; i < p_state->skins.size(); ++i) {
  4036. for (int j = i + 1; j < p_state->skins.size(); ++j) {
  4037. const Ref<Skin> skin_i = p_state->skins[i]->godot_skin;
  4038. const Ref<Skin> skin_j = p_state->skins[j]->godot_skin;
  4039. if (_skins_are_same(skin_i, skin_j)) {
  4040. // replace it and delete the old
  4041. p_state->skins.write[j]->godot_skin = skin_i;
  4042. }
  4043. }
  4044. }
  4045. }
  4046. Error GLTFDocument::_serialize_lights(Ref<GLTFState> p_state) {
  4047. if (p_state->lights.empty()) {
  4048. return OK;
  4049. }
  4050. Array lights;
  4051. for (GLTFLightIndex i = 0; i < p_state->lights.size(); i++) {
  4052. Ref<GLTFLight> light = p_state->lights[i];
  4053. Dictionary d = light->to_dictionary();
  4054. lights.push_back(d);
  4055. }
  4056. Dictionary extensions;
  4057. if (p_state->json.has("extensions")) {
  4058. extensions = p_state->json["extensions"];
  4059. } else {
  4060. p_state->json["extensions"] = extensions;
  4061. }
  4062. Dictionary lights_punctual;
  4063. extensions["KHR_lights_punctual"] = lights_punctual;
  4064. lights_punctual["lights"] = lights;
  4065. print_verbose("glTF: Total lights: " + itos(p_state->lights.size()));
  4066. return OK;
  4067. }
  4068. Error GLTFDocument::_serialize_cameras(Ref<GLTFState> p_state) {
  4069. Array cameras;
  4070. cameras.resize(p_state->cameras.size());
  4071. for (GLTFCameraIndex i = 0; i < p_state->cameras.size(); i++) {
  4072. Ref<GLTFCamera> camera = p_state->cameras[i];
  4073. Dictionary d = camera->to_dictionary();
  4074. cameras[i] = d;
  4075. }
  4076. if (!p_state->cameras.size()) {
  4077. return OK;
  4078. }
  4079. p_state->json["cameras"] = cameras;
  4080. print_verbose("glTF: Total cameras: " + itos(p_state->cameras.size()));
  4081. return OK;
  4082. }
  4083. Error GLTFDocument::_parse_lights(Ref<GLTFState> p_state) {
  4084. if (!p_state->json.has("extensions")) {
  4085. return OK;
  4086. }
  4087. Dictionary extensions = p_state->json["extensions"];
  4088. if (!extensions.has("KHR_lights_punctual")) {
  4089. return OK;
  4090. }
  4091. Dictionary lights_punctual = extensions["KHR_lights_punctual"];
  4092. if (!lights_punctual.has("lights")) {
  4093. return OK;
  4094. }
  4095. const Array &lights = lights_punctual["lights"];
  4096. for (GLTFLightIndex light_i = 0; light_i < lights.size(); light_i++) {
  4097. Ref<GLTFLight> light = GLTFLight::from_dictionary(lights[light_i]);
  4098. if (light.is_null()) {
  4099. return Error::ERR_PARSE_ERROR;
  4100. }
  4101. p_state->lights.push_back(light);
  4102. }
  4103. print_verbose("glTF: Total lights: " + itos(p_state->lights.size()));
  4104. return OK;
  4105. }
  4106. Error GLTFDocument::_parse_cameras(Ref<GLTFState> p_state) {
  4107. if (!p_state->json.has("cameras")) {
  4108. return OK;
  4109. }
  4110. const Array cameras = p_state->json["cameras"];
  4111. for (GLTFCameraIndex i = 0; i < cameras.size(); i++) {
  4112. Ref<GLTFCamera> camera = GLTFCamera::from_dictionary(cameras[i]);
  4113. if (camera.is_null()) {
  4114. return Error::ERR_PARSE_ERROR;
  4115. }
  4116. p_state->cameras.push_back(camera);
  4117. }
  4118. print_verbose("glTF: Total cameras: " + itos(p_state->cameras.size()));
  4119. return OK;
  4120. }
  4121. String GLTFDocument::interpolation_to_string(const GLTFAnimation::Interpolation p_interp) {
  4122. String interp = "LINEAR";
  4123. if (p_interp == GLTFAnimation::INTERP_STEP) {
  4124. interp = "STEP";
  4125. } else if (p_interp == GLTFAnimation::INTERP_LINEAR) {
  4126. interp = "LINEAR";
  4127. } else if (p_interp == GLTFAnimation::INTERP_CATMULLROMSPLINE) {
  4128. interp = "CATMULLROMSPLINE";
  4129. } else if (p_interp == GLTFAnimation::INTERP_CUBIC_SPLINE) {
  4130. interp = "CUBICSPLINE";
  4131. }
  4132. return interp;
  4133. }
  4134. Error GLTFDocument::_serialize_animations(Ref<GLTFState> p_state) {
  4135. if (!p_state->animation_players.size()) {
  4136. return OK;
  4137. }
  4138. for (int32_t player_i = 0; player_i < p_state->animation_players.size(); player_i++) {
  4139. List<StringName> animation_names;
  4140. AnimationPlayer *animation_player = p_state->animation_players[player_i];
  4141. animation_player->get_animation_list(&animation_names);
  4142. if (animation_names.size()) {
  4143. for (int animation_name_i = 0; animation_name_i < animation_names.size(); animation_name_i++) {
  4144. _convert_animation(p_state, animation_player, animation_names[animation_name_i]);
  4145. }
  4146. }
  4147. }
  4148. Array animations;
  4149. for (GLTFAnimationIndex animation_i = 0; animation_i < p_state->animations.size(); animation_i++) {
  4150. Dictionary d;
  4151. Ref<GLTFAnimation> gltf_animation = p_state->animations[animation_i];
  4152. if (!gltf_animation->get_tracks().size()) {
  4153. continue;
  4154. }
  4155. if (!gltf_animation->get_name().empty()) {
  4156. d["name"] = gltf_animation->get_name();
  4157. }
  4158. Array channels;
  4159. Array samplers;
  4160. for (Map<int, GLTFAnimation::Track>::Element *track_i = gltf_animation->get_tracks().front(); track_i; track_i = track_i->next()) {
  4161. GLTFAnimation::Track track = track_i->get();
  4162. if (track.translation_track.times.size()) {
  4163. Dictionary t;
  4164. t["sampler"] = samplers.size();
  4165. Dictionary s;
  4166. s["interpolation"] = interpolation_to_string(track.translation_track.interpolation);
  4167. Vector<real_t> times = Variant(track.translation_track.times);
  4168. s["input"] = _encode_accessor_as_floats(p_state, times, false);
  4169. Vector<Vector3> values = Variant(track.translation_track.values);
  4170. s["output"] = _encode_accessor_as_vec3(p_state, values, false);
  4171. samplers.push_back(s);
  4172. Dictionary target;
  4173. target["path"] = "translation";
  4174. target["node"] = track_i->key();
  4175. t["target"] = target;
  4176. channels.push_back(t);
  4177. }
  4178. if (track.rotation_track.times.size()) {
  4179. Dictionary t;
  4180. t["sampler"] = samplers.size();
  4181. Dictionary s;
  4182. s["interpolation"] = interpolation_to_string(track.rotation_track.interpolation);
  4183. Vector<real_t> times = Variant(track.rotation_track.times);
  4184. s["input"] = _encode_accessor_as_floats(p_state, times, false);
  4185. Vector<Quat> values = track.rotation_track.values;
  4186. s["output"] = _encode_accessor_as_quats(p_state, values, false);
  4187. samplers.push_back(s);
  4188. Dictionary target;
  4189. target["path"] = "rotation";
  4190. target["node"] = track_i->key();
  4191. t["target"] = target;
  4192. channels.push_back(t);
  4193. }
  4194. if (track.scale_track.times.size()) {
  4195. Dictionary t;
  4196. t["sampler"] = samplers.size();
  4197. Dictionary s;
  4198. s["interpolation"] = interpolation_to_string(track.scale_track.interpolation);
  4199. Vector<real_t> times = Variant(track.scale_track.times);
  4200. s["input"] = _encode_accessor_as_floats(p_state, times, false);
  4201. Vector<Vector3> values = Variant(track.scale_track.values);
  4202. s["output"] = _encode_accessor_as_vec3(p_state, values, false);
  4203. samplers.push_back(s);
  4204. Dictionary target;
  4205. target["path"] = "scale";
  4206. target["node"] = track_i->key();
  4207. t["target"] = target;
  4208. channels.push_back(t);
  4209. }
  4210. if (track.weight_tracks.size()) {
  4211. double length = 0.0f;
  4212. for (int32_t track_idx = 0; track_idx < track.weight_tracks.size(); track_idx++) {
  4213. int32_t last_time_index = track.weight_tracks[track_idx].times.size() - 1;
  4214. length = MAX(length, track.weight_tracks[track_idx].times[last_time_index]);
  4215. }
  4216. Dictionary t;
  4217. t["sampler"] = samplers.size();
  4218. Dictionary s;
  4219. Vector<real_t> times;
  4220. const double increment = 1.0 / BAKE_FPS;
  4221. {
  4222. double time = 0.0;
  4223. bool last = false;
  4224. while (true) {
  4225. times.push_back(time);
  4226. if (last) {
  4227. break;
  4228. }
  4229. time += increment;
  4230. if (time >= length) {
  4231. last = true;
  4232. time = length;
  4233. }
  4234. }
  4235. }
  4236. for (int32_t track_idx = 0; track_idx < track.weight_tracks.size(); track_idx++) {
  4237. double time = 0.0;
  4238. bool last = false;
  4239. Vector<real_t> weight_track;
  4240. while (true) {
  4241. float weight = _interpolate_track<float>(track.weight_tracks[track_idx].times,
  4242. track.weight_tracks[track_idx].values,
  4243. time,
  4244. track.weight_tracks[track_idx].interpolation);
  4245. weight_track.push_back(weight);
  4246. if (last) {
  4247. break;
  4248. }
  4249. time += increment;
  4250. if (time >= length) {
  4251. last = true;
  4252. time = length;
  4253. }
  4254. }
  4255. track.weight_tracks.write[track_idx].times = times;
  4256. track.weight_tracks.write[track_idx].values = weight_track;
  4257. }
  4258. Vector<real_t> all_track_times = times;
  4259. Vector<real_t> all_track_values;
  4260. int32_t values_size = track.weight_tracks[0].values.size();
  4261. int32_t weight_tracks_size = track.weight_tracks.size();
  4262. all_track_values.resize(weight_tracks_size * values_size);
  4263. for (int k = 0; k < track.weight_tracks.size(); k++) {
  4264. Vector<float> wdata = track.weight_tracks[k].values;
  4265. for (int l = 0; l < wdata.size(); l++) {
  4266. int32_t index = l * weight_tracks_size + k;
  4267. ERR_BREAK(index >= all_track_values.size());
  4268. all_track_values.write[index] = wdata.write[l];
  4269. }
  4270. }
  4271. s["interpolation"] = interpolation_to_string(track.weight_tracks[track.weight_tracks.size() - 1].interpolation);
  4272. s["input"] = _encode_accessor_as_floats(p_state, all_track_times, false);
  4273. s["output"] = _encode_accessor_as_floats(p_state, all_track_values, false);
  4274. samplers.push_back(s);
  4275. Dictionary target;
  4276. target["path"] = "weights";
  4277. target["node"] = track_i->key();
  4278. t["target"] = target;
  4279. channels.push_back(t);
  4280. }
  4281. }
  4282. if (channels.size() && samplers.size()) {
  4283. d["channels"] = channels;
  4284. d["samplers"] = samplers;
  4285. animations.push_back(d);
  4286. }
  4287. }
  4288. if (!animations.size()) {
  4289. return OK;
  4290. }
  4291. p_state->json["animations"] = animations;
  4292. print_verbose("glTF: Total animations '" + itos(p_state->animations.size()) + "'.");
  4293. return OK;
  4294. }
  4295. Error GLTFDocument::_parse_animations(Ref<GLTFState> p_state) {
  4296. if (!p_state->json.has("animations")) {
  4297. return OK;
  4298. }
  4299. const Array &animations = p_state->json["animations"];
  4300. for (GLTFAnimationIndex i = 0; i < animations.size(); i++) {
  4301. const Dictionary &d = animations[i];
  4302. Ref<GLTFAnimation> animation;
  4303. animation.instance();
  4304. if (!d.has("channels") || !d.has("samplers")) {
  4305. continue;
  4306. }
  4307. Array channels = d["channels"];
  4308. Array samplers = d["samplers"];
  4309. if (d.has("name")) {
  4310. const String name = d["name"];
  4311. if (name.begins_with("loop") || name.ends_with("loop") || name.begins_with("cycle") || name.ends_with("cycle")) {
  4312. animation->set_loop(true);
  4313. }
  4314. if (p_state->use_legacy_names) {
  4315. animation->set_name(_sanitize_scene_name(p_state, name));
  4316. } else {
  4317. animation->set_name(_gen_unique_animation_name(p_state, name));
  4318. }
  4319. }
  4320. for (int j = 0; j < channels.size(); j++) {
  4321. const Dictionary &c = channels[j];
  4322. if (!c.has("target")) {
  4323. continue;
  4324. }
  4325. const Dictionary &t = c["target"];
  4326. if (!t.has("node") || !t.has("path")) {
  4327. continue;
  4328. }
  4329. ERR_FAIL_COND_V(!c.has("sampler"), ERR_PARSE_ERROR);
  4330. const int sampler = c["sampler"];
  4331. ERR_FAIL_INDEX_V(sampler, samplers.size(), ERR_PARSE_ERROR);
  4332. GLTFNodeIndex node = t["node"];
  4333. String path = t["path"];
  4334. ERR_FAIL_INDEX_V(node, p_state->nodes.size(), ERR_PARSE_ERROR);
  4335. GLTFAnimation::Track *track = nullptr;
  4336. if (!animation->get_tracks().has(node)) {
  4337. animation->get_tracks()[node] = GLTFAnimation::Track();
  4338. }
  4339. track = &animation->get_tracks()[node];
  4340. const Dictionary &s = samplers[sampler];
  4341. ERR_FAIL_COND_V(!s.has("input"), ERR_PARSE_ERROR);
  4342. ERR_FAIL_COND_V(!s.has("output"), ERR_PARSE_ERROR);
  4343. const int input = s["input"];
  4344. const int output = s["output"];
  4345. GLTFAnimation::Interpolation interp = GLTFAnimation::INTERP_LINEAR;
  4346. int output_count = 1;
  4347. if (s.has("interpolation")) {
  4348. const String &in = s["interpolation"];
  4349. if (in == "STEP") {
  4350. interp = GLTFAnimation::INTERP_STEP;
  4351. } else if (in == "LINEAR") {
  4352. interp = GLTFAnimation::INTERP_LINEAR;
  4353. } else if (in == "CATMULLROMSPLINE") {
  4354. interp = GLTFAnimation::INTERP_CATMULLROMSPLINE;
  4355. output_count = 3;
  4356. } else if (in == "CUBICSPLINE") {
  4357. interp = GLTFAnimation::INTERP_CUBIC_SPLINE;
  4358. output_count = 3;
  4359. }
  4360. }
  4361. const Vector<float> times = _decode_accessor_as_floats(p_state, input, false);
  4362. if (path == "translation") {
  4363. const Vector<Vector3> translations = _decode_accessor_as_vec3(p_state, output, false);
  4364. track->translation_track.interpolation = interp;
  4365. track->translation_track.times = Variant(times); //convert via variant
  4366. track->translation_track.values = Variant(translations); //convert via variant
  4367. } else if (path == "rotation") {
  4368. const Vector<Quat> rotations = _decode_accessor_as_quat(p_state, output, false);
  4369. track->rotation_track.interpolation = interp;
  4370. track->rotation_track.times = Variant(times); //convert via variant
  4371. track->rotation_track.values = rotations;
  4372. } else if (path == "scale") {
  4373. const Vector<Vector3> scales = _decode_accessor_as_vec3(p_state, output, false);
  4374. track->scale_track.interpolation = interp;
  4375. track->scale_track.times = Variant(times); //convert via variant
  4376. track->scale_track.values = Variant(scales); //convert via variant
  4377. } else if (path == "weights") {
  4378. const Vector<float> weights = _decode_accessor_as_floats(p_state, output, false);
  4379. ERR_FAIL_INDEX_V(p_state->nodes[node]->mesh, p_state->meshes.size(), ERR_PARSE_ERROR);
  4380. Ref<GLTFMesh> mesh = p_state->meshes[p_state->nodes[node]->mesh];
  4381. ERR_CONTINUE(!mesh->get_blend_weights().size());
  4382. const int wc = mesh->get_blend_weights().size();
  4383. track->weight_tracks.resize(wc);
  4384. const int expected_value_count = times.size() * output_count * wc;
  4385. ERR_CONTINUE_MSG(weights.size() != expected_value_count, "Invalid weight data, expected " + itos(expected_value_count) + " weight values, got " + itos(weights.size()) + " instead.");
  4386. const int wlen = weights.size() / wc;
  4387. for (int k = 0; k < wc; k++) { //separate tracks, having them together is not such a good idea
  4388. GLTFAnimation::Channel<float> cf;
  4389. cf.interpolation = interp;
  4390. cf.times = Variant(times);
  4391. Vector<float> wdata;
  4392. wdata.resize(wlen);
  4393. for (int l = 0; l < wlen; l++) {
  4394. wdata.write[l] = weights[l * wc + k];
  4395. }
  4396. cf.values = wdata;
  4397. track->weight_tracks.write[k] = cf;
  4398. }
  4399. } else {
  4400. WARN_PRINT("Invalid path '" + path + "'.");
  4401. }
  4402. }
  4403. p_state->animations.push_back(animation);
  4404. }
  4405. print_verbose("glTF: Total animations '" + itos(p_state->animations.size()) + "'.");
  4406. return OK;
  4407. }
  4408. void GLTFDocument::_assign_scene_names(Ref<GLTFState> p_state) {
  4409. for (int i = 0; i < p_state->nodes.size(); i++) {
  4410. Ref<GLTFNode> gltf_node = p_state->nodes[i];
  4411. // Any joints get unique names generated when the skeleton is made, unique to the skeleton
  4412. if (gltf_node->skeleton >= 0) {
  4413. continue;
  4414. }
  4415. if (gltf_node->get_name().empty()) {
  4416. if (gltf_node->mesh >= 0) {
  4417. gltf_node->set_name(_gen_unique_name(p_state, "Mesh"));
  4418. } else if (gltf_node->camera >= 0) {
  4419. gltf_node->set_name(_gen_unique_name(p_state, "Camera"));
  4420. } else {
  4421. gltf_node->set_name(_gen_unique_name(p_state, "Node"));
  4422. }
  4423. }
  4424. gltf_node->set_name(_gen_unique_name(p_state, gltf_node->get_name()));
  4425. }
  4426. // Assign a unique name to the scene last to avoid naming conflicts with the root
  4427. p_state->scene_name = _gen_unique_name(p_state, p_state->scene_name);
  4428. }
  4429. BoneAttachment *GLTFDocument::_generate_bone_attachment(Ref<GLTFState> p_state, Skeleton *p_skeleton, const GLTFNodeIndex p_node_index, const GLTFNodeIndex p_bone_index) {
  4430. Ref<GLTFNode> gltf_node = p_state->nodes[p_node_index];
  4431. Ref<GLTFNode> bone_node = p_state->nodes[p_bone_index];
  4432. BoneAttachment *bone_attachment = memnew(BoneAttachment);
  4433. print_verbose("glTF: Creating bone attachment for: " + gltf_node->get_name());
  4434. ERR_FAIL_COND_V(!bone_node->joint, nullptr);
  4435. bone_attachment->set_bone_name(bone_node->get_name());
  4436. return bone_attachment;
  4437. }
  4438. GLTFMeshIndex GLTFDocument::_convert_mesh_to_gltf(Ref<GLTFState> p_state, MeshInstance *p_mesh_instance) {
  4439. ERR_FAIL_NULL_V(p_mesh_instance, -1);
  4440. if (p_mesh_instance->get_mesh().is_null()) {
  4441. return -1;
  4442. }
  4443. Ref<ArrayMesh> import_mesh;
  4444. import_mesh.instance();
  4445. Ref<Mesh> godot_mesh = p_mesh_instance->get_mesh();
  4446. if (godot_mesh.is_null()) {
  4447. return -1;
  4448. }
  4449. int32_t blend_count = godot_mesh->get_blend_shape_count();
  4450. Vector<float> blend_weights;
  4451. blend_weights.resize(blend_count);
  4452. Ref<ArrayMesh> am = godot_mesh;
  4453. if (am != nullptr) {
  4454. import_mesh = am;
  4455. } else {
  4456. for (int32_t surface_i = 0; surface_i < godot_mesh->get_surface_count(); surface_i++) {
  4457. Mesh::PrimitiveType primitive_type = godot_mesh->surface_get_primitive_type(surface_i);
  4458. Array arrays = godot_mesh->surface_get_arrays(surface_i);
  4459. Ref<Material> mat = godot_mesh->surface_get_material(surface_i);
  4460. if (p_mesh_instance->get_surface_material(surface_i).is_valid()) {
  4461. mat = p_mesh_instance->get_surface_material(surface_i);
  4462. }
  4463. if (p_mesh_instance->get_material_override().is_valid()) {
  4464. mat = p_mesh_instance->get_material_override();
  4465. }
  4466. int32_t mat_idx = import_mesh->get_surface_count();
  4467. import_mesh->add_surface_from_arrays(primitive_type, arrays);
  4468. import_mesh->surface_set_material(mat_idx, mat);
  4469. }
  4470. }
  4471. for (int32_t blend_i = 0; blend_i < blend_count; blend_i++) {
  4472. blend_weights.write[blend_i] = 0.0f;
  4473. }
  4474. Ref<GLTFMesh> gltf_mesh;
  4475. gltf_mesh.instance();
  4476. Array instance_materials;
  4477. for (int32_t surface_i = 0; surface_i < import_mesh->get_surface_count(); surface_i++) {
  4478. Ref<Material> mat = import_mesh->surface_get_material(surface_i);
  4479. if (p_mesh_instance->get_surface_material(surface_i).is_valid()) {
  4480. mat = p_mesh_instance->get_surface_material(surface_i);
  4481. }
  4482. if (p_mesh_instance->get_material_override().is_valid()) {
  4483. mat = p_mesh_instance->get_material_override();
  4484. }
  4485. instance_materials.append(mat);
  4486. }
  4487. gltf_mesh->set_instance_materials(instance_materials);
  4488. gltf_mesh->set_mesh(import_mesh);
  4489. gltf_mesh->set_blend_weights(blend_weights);
  4490. GLTFMeshIndex mesh_i = p_state->meshes.size();
  4491. p_state->meshes.push_back(gltf_mesh);
  4492. return mesh_i;
  4493. }
  4494. Spatial *GLTFDocument::_generate_mesh_instance(Ref<GLTFState> p_state, Node *p_scene_parent, const GLTFNodeIndex p_node_index) {
  4495. Ref<GLTFNode> gltf_node = p_state->nodes[p_node_index];
  4496. ERR_FAIL_INDEX_V(gltf_node->mesh, p_state->meshes.size(), nullptr);
  4497. MeshInstance *mi = memnew(MeshInstance);
  4498. print_verbose("glTF: Creating mesh for: " + gltf_node->get_name());
  4499. Ref<GLTFMesh> mesh = p_state->meshes.write[gltf_node->mesh];
  4500. if (mesh.is_null()) {
  4501. return mi;
  4502. }
  4503. Ref<ArrayMesh> import_mesh = mesh->get_mesh();
  4504. if (import_mesh.is_null()) {
  4505. return mi;
  4506. }
  4507. mi->set_mesh(import_mesh);
  4508. for (int i = 0; i < mesh->get_blend_weights().size(); i++) {
  4509. mi->set("blend_shapes/" + mesh->get_mesh()->get_blend_shape_name(i), mesh->get_blend_weights()[i]);
  4510. }
  4511. return mi;
  4512. }
  4513. Spatial *GLTFDocument::_generate_light(Ref<GLTFState> p_state, Node *p_scene_parent, const GLTFNodeIndex p_node_index) {
  4514. Ref<GLTFNode> gltf_node = p_state->nodes[p_node_index];
  4515. ERR_FAIL_INDEX_V(gltf_node->light, p_state->lights.size(), nullptr);
  4516. print_verbose("glTF: Creating light for: " + gltf_node->get_name());
  4517. Ref<GLTFLight> l = p_state->lights[gltf_node->light];
  4518. return l->to_node();
  4519. }
  4520. Camera *GLTFDocument::_generate_camera(Ref<GLTFState> p_state, Node *p_scene_parent, const GLTFNodeIndex p_node_index) {
  4521. Ref<GLTFNode> gltf_node = p_state->nodes[p_node_index];
  4522. ERR_FAIL_INDEX_V(gltf_node->camera, p_state->cameras.size(), nullptr);
  4523. print_verbose("glTF: Creating camera for: " + gltf_node->get_name());
  4524. Ref<GLTFCamera> c = p_state->cameras[gltf_node->camera];
  4525. return c->to_node();
  4526. }
  4527. GLTFCameraIndex GLTFDocument::_convert_camera(Ref<GLTFState> p_state, Camera *p_camera) {
  4528. print_verbose("glTF: Converting camera: " + p_camera->get_name());
  4529. Ref<GLTFCamera> c = GLTFCamera::from_node(p_camera);
  4530. GLTFCameraIndex camera_index = p_state->cameras.size();
  4531. p_state->cameras.push_back(c);
  4532. return camera_index;
  4533. }
  4534. GLTFLightIndex GLTFDocument::_convert_light(Ref<GLTFState> p_state, Light *p_light) {
  4535. print_verbose("glTF: Converting light: " + p_light->get_name());
  4536. Ref<GLTFLight> l = GLTFLight::from_node(p_light);
  4537. GLTFLightIndex light_index = p_state->lights.size();
  4538. p_state->lights.push_back(l);
  4539. return light_index;
  4540. }
  4541. void GLTFDocument::_convert_spatial(Ref<GLTFState> p_state, Spatial *p_spatial, Ref<GLTFNode> p_node) {
  4542. Transform xform = p_spatial->get_transform();
  4543. p_node->scale = xform.basis.get_scale();
  4544. p_node->rotation = xform.basis.get_rotation_quat();
  4545. p_node->translation = xform.origin;
  4546. }
  4547. Spatial *GLTFDocument::_generate_spatial(Ref<GLTFState> p_state, Node *p_scene_parent, const GLTFNodeIndex p_node_index) {
  4548. Ref<GLTFNode> gltf_node = p_state->nodes[p_node_index];
  4549. Spatial *spatial = memnew(Spatial);
  4550. print_verbose("glTF: Converting spatial: " + gltf_node->get_name());
  4551. return spatial;
  4552. }
  4553. void GLTFDocument::_convert_scene_node(Ref<GLTFState> p_state, Node *p_current, const GLTFNodeIndex p_gltf_parent, const GLTFNodeIndex p_gltf_root) {
  4554. bool retflag = true;
  4555. _check_visibility(p_current, retflag);
  4556. if (retflag) {
  4557. return;
  4558. }
  4559. Ref<GLTFNode> gltf_node;
  4560. gltf_node.instance();
  4561. gltf_node->set_name(_gen_unique_name(p_state, p_current->get_name()));
  4562. if (cast_to<Spatial>(p_current)) {
  4563. Spatial *spatial = cast_to<Spatial>(p_current);
  4564. _convert_spatial(p_state, spatial, gltf_node);
  4565. }
  4566. if (cast_to<MeshInstance>(p_current)) {
  4567. MeshInstance *mi = cast_to<MeshInstance>(p_current);
  4568. _convert_mesh_instance_to_gltf(mi, p_state, gltf_node);
  4569. } else if (cast_to<BoneAttachment>(p_current)) {
  4570. BoneAttachment *bone = cast_to<BoneAttachment>(p_current);
  4571. _convert_bone_attachment_to_gltf(bone, p_state, p_gltf_parent, p_gltf_root, gltf_node);
  4572. return;
  4573. } else if (cast_to<Skeleton>(p_current)) {
  4574. Skeleton *skel = cast_to<Skeleton>(p_current);
  4575. _convert_skeleton_to_gltf(skel, p_state, p_gltf_parent, p_gltf_root, gltf_node);
  4576. // We ignore the Godot Engine node that is the skeleton.
  4577. return;
  4578. } else if (cast_to<MultiMeshInstance>(p_current)) {
  4579. MultiMeshInstance *multi = cast_to<MultiMeshInstance>(p_current);
  4580. _convert_multi_mesh_instance_to_gltf(multi, p_gltf_parent, p_gltf_root, gltf_node, p_state);
  4581. #ifdef MODULE_CSG_ENABLED
  4582. } else if (cast_to<CSGShape>(p_current)) {
  4583. CSGShape *shape = cast_to<CSGShape>(p_current);
  4584. if (shape->get_parent() && shape->is_root_shape()) {
  4585. _convert_csg_shape_to_gltf(shape, p_gltf_parent, gltf_node, p_state);
  4586. }
  4587. #endif // MODULE_CSG_ENABLED
  4588. #ifdef MODULE_GRIDMAP_ENABLED
  4589. } else if (cast_to<GridMap>(p_current)) {
  4590. GridMap *gridmap = Object::cast_to<GridMap>(p_current);
  4591. _convert_grid_map_to_gltf(gridmap, p_gltf_parent, p_gltf_root, gltf_node, p_state);
  4592. #endif // MODULE_GRIDMAP_ENABLED
  4593. } else if (cast_to<Camera>(p_current)) {
  4594. Camera *camera = Object::cast_to<Camera>(p_current);
  4595. _convert_camera_to_gltf(camera, p_state, gltf_node);
  4596. } else if (cast_to<Light>(p_current)) {
  4597. Light *light = Object::cast_to<Light>(p_current);
  4598. _convert_light_to_gltf(light, p_state, gltf_node);
  4599. } else if (cast_to<AnimationPlayer>(p_current)) {
  4600. AnimationPlayer *animation_player = Object::cast_to<AnimationPlayer>(p_current);
  4601. _convert_animation_player_to_gltf(animation_player, p_state, p_gltf_parent, p_gltf_root, gltf_node, p_current);
  4602. }
  4603. for (int ext_i = 0; ext_i < document_extensions.size(); ext_i++) {
  4604. Ref<GLTFDocumentExtension> ext = document_extensions[ext_i];
  4605. ERR_CONTINUE(ext.is_null());
  4606. ext->convert_scene_node(p_state, gltf_node, p_current);
  4607. }
  4608. GLTFNodeIndex current_node_i = p_state->nodes.size();
  4609. GLTFNodeIndex gltf_root = p_gltf_root;
  4610. if (gltf_root == -1) {
  4611. gltf_root = current_node_i;
  4612. Array scenes;
  4613. scenes.push_back(gltf_root);
  4614. p_state->json["scene"] = scenes;
  4615. }
  4616. _create_gltf_node(p_state, p_current, current_node_i, p_gltf_parent, gltf_root, gltf_node);
  4617. for (int node_i = 0; node_i < p_current->get_child_count(); node_i++) {
  4618. _convert_scene_node(p_state, p_current->get_child(node_i), current_node_i, gltf_root);
  4619. }
  4620. }
  4621. #ifdef MODULE_CSG_ENABLED
  4622. void GLTFDocument::_convert_csg_shape_to_gltf(CSGShape *p_current, GLTFNodeIndex p_gltf_parent, Ref<GLTFNode> p_gltf_node, Ref<GLTFState> p_state) {
  4623. CSGShape *csg = p_current;
  4624. csg->call("_update_shape");
  4625. Array meshes = csg->get_meshes();
  4626. if (meshes.size() != 2) {
  4627. return;
  4628. }
  4629. Ref<Material> mat;
  4630. if (csg->get_material_override().is_valid()) {
  4631. mat = csg->get_material_override();
  4632. }
  4633. Ref<GLTFMesh> gltf_mesh;
  4634. gltf_mesh.instance();
  4635. Ref<ArrayMesh> import_mesh;
  4636. import_mesh.instance();
  4637. Ref<ArrayMesh> array_mesh = csg->get_meshes()[1];
  4638. for (int32_t surface_i = 0; surface_i < array_mesh->get_surface_count(); surface_i++) {
  4639. import_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, array_mesh->surface_get_arrays(surface_i));
  4640. }
  4641. gltf_mesh->set_mesh(import_mesh);
  4642. GLTFMeshIndex mesh_i = p_state->meshes.size();
  4643. p_state->meshes.push_back(gltf_mesh);
  4644. p_gltf_node->mesh = mesh_i;
  4645. p_gltf_node->xform = csg->get_meshes()[0];
  4646. p_gltf_node->set_name(_gen_unique_name(p_state, csg->get_name()));
  4647. }
  4648. #endif // MODULE_CSG_ENABLED
  4649. void GLTFDocument::_create_gltf_node(Ref<GLTFState> p_state, Node *p_scene_parent, GLTFNodeIndex current_node_i,
  4650. GLTFNodeIndex p_parent_node_index, GLTFNodeIndex p_root_gltf_node, Ref<GLTFNode> p_gltf_node) {
  4651. p_state->scene_nodes.insert(current_node_i, p_scene_parent);
  4652. p_state->nodes.push_back(p_gltf_node);
  4653. ERR_FAIL_COND(current_node_i == p_parent_node_index);
  4654. p_state->nodes.write[current_node_i]->parent = p_parent_node_index;
  4655. if (p_parent_node_index == -1) {
  4656. return;
  4657. }
  4658. p_state->nodes.write[p_parent_node_index]->children.push_back(current_node_i);
  4659. }
  4660. void GLTFDocument::_convert_animation_player_to_gltf(AnimationPlayer *p_animation_player, Ref<GLTFState> p_state, GLTFNodeIndex p_gltf_current, GLTFNodeIndex p_gltf_root_index, Ref<GLTFNode> p_gltf_node, Node *p_scene_parent) {
  4661. ERR_FAIL_COND(!p_animation_player);
  4662. p_state->animation_players.push_back(p_animation_player);
  4663. print_verbose(String("glTF: Converting animation player: ") + p_animation_player->get_name());
  4664. }
  4665. void GLTFDocument::_check_visibility(Node *p_node, bool &r_retflag) {
  4666. r_retflag = true;
  4667. Spatial *spatial = Object::cast_to<Spatial>(p_node);
  4668. Node2D *node_2d = Object::cast_to<Node2D>(p_node);
  4669. if (node_2d && !node_2d->is_visible()) {
  4670. return;
  4671. }
  4672. if (spatial && !spatial->is_visible()) {
  4673. return;
  4674. }
  4675. r_retflag = false;
  4676. }
  4677. void GLTFDocument::_convert_camera_to_gltf(Camera *p_camera, Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node) {
  4678. ERR_FAIL_COND(!p_camera);
  4679. GLTFCameraIndex camera_index = _convert_camera(p_state, p_camera);
  4680. if (camera_index != -1) {
  4681. p_gltf_node->camera = camera_index;
  4682. }
  4683. }
  4684. void GLTFDocument::_convert_light_to_gltf(Light *p_light, Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node) {
  4685. ERR_FAIL_COND(!p_light);
  4686. GLTFLightIndex light_index = _convert_light(p_state, p_light);
  4687. if (light_index != -1) {
  4688. p_gltf_node->light = light_index;
  4689. }
  4690. }
  4691. #ifdef MODULE_GRIDMAP_ENABLED
  4692. void GLTFDocument::_convert_grid_map_to_gltf(GridMap *p_grid_map, GLTFNodeIndex p_parent_node_index, GLTFNodeIndex p_root_node_index, Ref<GLTFNode> p_gltf_node, Ref<GLTFState> p_state) {
  4693. Array cells = p_grid_map->get_used_cells();
  4694. for (int32_t k = 0; k < cells.size(); k++) {
  4695. GLTFNode *new_gltf_node = memnew(GLTFNode);
  4696. p_gltf_node->children.push_back(p_state->nodes.size());
  4697. p_state->nodes.push_back(new_gltf_node);
  4698. Vector3 cell_location = cells[k];
  4699. int32_t cell = p_grid_map->get_cell_item(
  4700. cell_location.x, cell_location.y, cell_location.z);
  4701. Transform cell_xform;
  4702. cell_xform.basis.set_orthogonal_index(
  4703. p_grid_map->get_cell_item_orientation(
  4704. cell_location.x, cell_location.y, cell_location.z));
  4705. cell_xform.basis.scale(Vector3(p_grid_map->get_cell_scale(),
  4706. p_grid_map->get_cell_scale(),
  4707. p_grid_map->get_cell_scale()));
  4708. cell_xform.set_origin(p_grid_map->map_to_world(
  4709. cell_location.x, cell_location.y, cell_location.z));
  4710. Ref<GLTFMesh> gltf_mesh;
  4711. gltf_mesh.instance();
  4712. gltf_mesh->set_mesh(_mesh_to_array_mesh(p_grid_map->get_mesh_library()->get_item_mesh(cell)));
  4713. new_gltf_node->mesh = p_state->meshes.size();
  4714. p_state->meshes.push_back(gltf_mesh);
  4715. new_gltf_node->xform = cell_xform * p_grid_map->get_transform();
  4716. new_gltf_node->set_name(_gen_unique_name(p_state, p_grid_map->get_mesh_library()->get_item_name(cell)));
  4717. }
  4718. }
  4719. #endif // MODULE_GRIDMAP_ENABLED
  4720. void GLTFDocument::_convert_multi_mesh_instance_to_gltf(MultiMeshInstance *p_multi_mesh_instance, GLTFNodeIndex p_parent_node_index, GLTFNodeIndex p_root_node_index, Ref<GLTFNode> p_gltf_node, Ref<GLTFState> p_state) {
  4721. Ref<MultiMesh> multi_mesh = p_multi_mesh_instance->get_multimesh();
  4722. if (multi_mesh.is_valid()) {
  4723. for (int32_t instance_i = 0; instance_i < multi_mesh->get_instance_count();
  4724. instance_i++) {
  4725. GLTFNode *new_gltf_node = memnew(GLTFNode);
  4726. Transform transform;
  4727. if (multi_mesh->get_transform_format() == MultiMesh::TRANSFORM_2D) {
  4728. Transform2D xform_2d = multi_mesh->get_instance_transform_2d(instance_i);
  4729. transform.origin =
  4730. Vector3(xform_2d.get_origin().x, 0, xform_2d.get_origin().y);
  4731. real_t rotation = xform_2d.get_rotation();
  4732. Quat quat(Vector3(0, 1, 0), rotation);
  4733. Size2 scale = xform_2d.get_scale();
  4734. transform.basis.set_quat_scale(quat,
  4735. Vector3(scale.x, 0, scale.y));
  4736. transform =
  4737. p_multi_mesh_instance->get_transform() * transform;
  4738. } else if (multi_mesh->get_transform_format() == MultiMesh::TRANSFORM_3D) {
  4739. transform = p_multi_mesh_instance->get_transform() *
  4740. multi_mesh->get_instance_transform(instance_i);
  4741. }
  4742. Ref<ArrayMesh> mm = multi_mesh->get_mesh();
  4743. if (mm.is_valid()) {
  4744. Ref<ArrayMesh> mesh;
  4745. mesh.instance();
  4746. for (int32_t surface_i = 0; surface_i < mm->get_surface_count(); surface_i++) {
  4747. Array surface = mm->surface_get_arrays(surface_i);
  4748. mesh->add_surface_from_arrays(mm->surface_get_primitive_type(surface_i), surface);
  4749. }
  4750. Ref<GLTFMesh> gltf_mesh;
  4751. gltf_mesh.instance();
  4752. gltf_mesh->set_name(multi_mesh->get_name());
  4753. gltf_mesh->set_mesh(mesh);
  4754. new_gltf_node->mesh = p_state->meshes.size();
  4755. p_state->meshes.push_back(gltf_mesh);
  4756. }
  4757. new_gltf_node->xform = transform;
  4758. new_gltf_node->set_name(_gen_unique_name(p_state, p_multi_mesh_instance->get_name()));
  4759. p_gltf_node->children.push_back(p_state->nodes.size());
  4760. p_state->nodes.push_back(new_gltf_node);
  4761. }
  4762. }
  4763. }
  4764. void GLTFDocument::_convert_skeleton_to_gltf(Skeleton *p_skeleton3d, Ref<GLTFState> p_state, GLTFNodeIndex p_parent_node_index, GLTFNodeIndex p_root_node_index, Ref<GLTFNode> p_gltf_node) {
  4765. Skeleton *skeleton = p_skeleton3d;
  4766. Ref<GLTFSkeleton> gltf_skeleton;
  4767. gltf_skeleton.instance();
  4768. // GLTFSkeleton is only used to hold internal p_state data. It will not be written to the document.
  4769. //
  4770. gltf_skeleton->godot_skeleton = skeleton;
  4771. GLTFSkeletonIndex skeleton_i = p_state->skeletons.size();
  4772. p_state->skeleton3d_to_gltf_skeleton[skeleton->get_instance_id()] = skeleton_i;
  4773. p_state->skeletons.push_back(gltf_skeleton);
  4774. BoneId bone_count = skeleton->get_bone_count();
  4775. for (BoneId bone_i = 0; bone_i < bone_count; bone_i++) {
  4776. Ref<GLTFNode> joint_node;
  4777. joint_node.instance();
  4778. // Note that we cannot use _gen_unique_bone_name here, because glTF spec requires all node
  4779. // names to be unique regardless of whether or not they are used as joints.
  4780. joint_node->set_name(_gen_unique_name(p_state, skeleton->get_bone_name(bone_i)));
  4781. Transform xform = skeleton->get_bone_rest(bone_i) * skeleton->get_bone_pose(bone_i);
  4782. joint_node->scale = xform.basis.get_scale();
  4783. joint_node->rotation = xform.basis.get_rotation_quat();
  4784. joint_node->translation = xform.origin;
  4785. joint_node->joint = true;
  4786. GLTFNodeIndex current_node_i = p_state->nodes.size();
  4787. p_state->scene_nodes.insert(current_node_i, skeleton);
  4788. p_state->nodes.push_back(joint_node);
  4789. gltf_skeleton->joints.push_back(current_node_i);
  4790. if (skeleton->get_bone_parent(bone_i) == -1) {
  4791. gltf_skeleton->roots.push_back(current_node_i);
  4792. }
  4793. gltf_skeleton->godot_bone_node.insert(bone_i, current_node_i);
  4794. }
  4795. for (BoneId bone_i = 0; bone_i < bone_count; bone_i++) {
  4796. GLTFNodeIndex current_node_i = gltf_skeleton->godot_bone_node[bone_i];
  4797. BoneId parent_bone_id = skeleton->get_bone_parent(bone_i);
  4798. if (parent_bone_id == -1) {
  4799. if (p_parent_node_index != -1) {
  4800. p_state->nodes.write[current_node_i]->parent = p_parent_node_index;
  4801. p_state->nodes.write[p_parent_node_index]->children.push_back(current_node_i);
  4802. }
  4803. } else {
  4804. GLTFNodeIndex parent_node_i = gltf_skeleton->godot_bone_node[parent_bone_id];
  4805. p_state->nodes.write[current_node_i]->parent = parent_node_i;
  4806. p_state->nodes.write[parent_node_i]->children.push_back(current_node_i);
  4807. }
  4808. }
  4809. // Remove placeholder skeleton3d node by not creating the gltf node
  4810. // Skins are per mesh
  4811. for (int node_i = 0; node_i < skeleton->get_child_count(); node_i++) {
  4812. _convert_scene_node(p_state, skeleton->get_child(node_i), p_parent_node_index, p_root_node_index);
  4813. }
  4814. }
  4815. void GLTFDocument::_convert_bone_attachment_to_gltf(BoneAttachment *p_bone_attachment, Ref<GLTFState> p_state, GLTFNodeIndex p_parent_node_index, GLTFNodeIndex p_root_node_index, Ref<GLTFNode> p_gltf_node) {
  4816. Skeleton *skeleton;
  4817. // Note that relative transforms to external skeletons and pose overrides are not supported.
  4818. skeleton = cast_to<Skeleton>(p_bone_attachment->get_parent());
  4819. GLTFSkeletonIndex skel_gltf_i = -1;
  4820. if (skeleton != nullptr && p_state->skeleton3d_to_gltf_skeleton.has(skeleton->get_instance_id())) {
  4821. skel_gltf_i = p_state->skeleton3d_to_gltf_skeleton[skeleton->get_instance_id()];
  4822. }
  4823. int bone_idx = -1;
  4824. if (skeleton != nullptr) {
  4825. bone_idx = skeleton->find_bone(p_bone_attachment->get_bone_name());
  4826. }
  4827. GLTFNodeIndex par_node_index = p_parent_node_index;
  4828. if (skeleton != nullptr && bone_idx != -1 && skel_gltf_i != -1) {
  4829. Ref<GLTFSkeleton> gltf_skeleton = p_state->skeletons.write[skel_gltf_i];
  4830. gltf_skeleton->bone_attachments.push_back(p_bone_attachment);
  4831. par_node_index = gltf_skeleton->joints[bone_idx];
  4832. }
  4833. for (int node_i = 0; node_i < p_bone_attachment->get_child_count(); node_i++) {
  4834. _convert_scene_node(p_state, p_bone_attachment->get_child(node_i), par_node_index, p_root_node_index);
  4835. }
  4836. }
  4837. void GLTFDocument::_convert_mesh_instance_to_gltf(MeshInstance *p_scene_parent, Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node) {
  4838. GLTFMeshIndex gltf_mesh_index = _convert_mesh_to_gltf(p_state, p_scene_parent);
  4839. if (gltf_mesh_index != -1) {
  4840. p_gltf_node->mesh = gltf_mesh_index;
  4841. }
  4842. }
  4843. void GLTFDocument::_generate_scene_node(Ref<GLTFState> p_state, Node *p_scene_parent, Spatial *p_scene_root, const GLTFNodeIndex p_node_index) {
  4844. Ref<GLTFNode> gltf_node = p_state->nodes[p_node_index];
  4845. if (gltf_node->skeleton >= 0) {
  4846. _generate_skeleton_bone_node(p_state, p_scene_parent, p_scene_root, p_node_index);
  4847. return;
  4848. }
  4849. Spatial *current_node = nullptr;
  4850. // Is our parent a skeleton
  4851. Skeleton *active_skeleton = Object::cast_to<Skeleton>(p_scene_parent);
  4852. const bool non_bone_parented_to_skeleton = active_skeleton;
  4853. // If we have an active skeleton, and the node is node skinned, we need to create a bone attachment
  4854. if (non_bone_parented_to_skeleton && gltf_node->skin < 0) {
  4855. // Bone Attachment - Parent Case
  4856. BoneAttachment *bone_attachment = _generate_bone_attachment(p_state, active_skeleton, p_node_index, gltf_node->parent);
  4857. p_scene_parent->add_child(bone_attachment);
  4858. bone_attachment->set_owner(p_scene_root);
  4859. // There is no gltf_node that represent this, so just directly create a unique name
  4860. bone_attachment->set_name(_gen_unique_name(p_state, "BoneAttachment"));
  4861. // We change the scene_parent to our bone attachment now. We do not set current_node because we want to make the node
  4862. // and attach it to the bone_attachment
  4863. p_scene_parent = bone_attachment;
  4864. }
  4865. // Check if any GLTFDocumentExtension classes want to generate a node for us.
  4866. for (int ext_i = 0; ext_i < document_extensions.size(); ext_i++) {
  4867. Ref<GLTFDocumentExtension> ext = document_extensions[ext_i];
  4868. ERR_CONTINUE(ext.is_null());
  4869. current_node = ext->generate_scene_node(p_state, gltf_node, p_scene_parent);
  4870. if (current_node) {
  4871. break;
  4872. }
  4873. }
  4874. // If none of our GLTFDocumentExtension classes generated us a node, we generate one.
  4875. if (!current_node) {
  4876. if (gltf_node->mesh >= 0) {
  4877. current_node = _generate_mesh_instance(p_state, p_scene_parent, p_node_index);
  4878. } else if (gltf_node->camera >= 0) {
  4879. current_node = _generate_camera(p_state, p_scene_parent, p_node_index);
  4880. } else if (gltf_node->light >= 0) {
  4881. current_node = _generate_light(p_state, p_scene_parent, p_node_index);
  4882. } else {
  4883. current_node = _generate_spatial(p_state, p_scene_parent, p_node_index);
  4884. }
  4885. }
  4886. // Add the node we generated and set the owner to the scene root.
  4887. p_scene_parent->add_child(current_node);
  4888. if (current_node != p_scene_root) {
  4889. Array args;
  4890. args.append(p_scene_root);
  4891. current_node->propagate_call(StringName("set_owner"), args);
  4892. }
  4893. current_node->set_transform(gltf_node->xform);
  4894. current_node->set_name(gltf_node->get_name());
  4895. p_state->scene_nodes.insert(p_node_index, current_node);
  4896. for (int i = 0; i < gltf_node->children.size(); ++i) {
  4897. _generate_scene_node(p_state, current_node, p_scene_root, gltf_node->children[i]);
  4898. }
  4899. }
  4900. void GLTFDocument::_generate_skeleton_bone_node(Ref<GLTFState> p_state, Node *p_scene_parent, Spatial *p_scene_root, const GLTFNodeIndex p_node_index) {
  4901. Ref<GLTFNode> gltf_node = p_state->nodes[p_node_index];
  4902. Spatial *current_node = nullptr;
  4903. Skeleton *skeleton = p_state->skeletons[gltf_node->skeleton]->godot_skeleton;
  4904. // In this case, this node is already a bone in skeleton.
  4905. const bool is_skinned_mesh = (gltf_node->skin >= 0 && gltf_node->mesh >= 0);
  4906. const bool requires_extra_node = (gltf_node->mesh >= 0 || gltf_node->camera >= 0 || gltf_node->light >= 0);
  4907. Skeleton *active_skeleton = Object::cast_to<Skeleton>(p_scene_parent);
  4908. if (active_skeleton != skeleton) {
  4909. if (active_skeleton) {
  4910. // Bone Attachment - Direct Parented Skeleton Case
  4911. BoneAttachment *bone_attachment = _generate_bone_attachment(p_state, active_skeleton, p_node_index, gltf_node->parent);
  4912. p_scene_parent->add_child(bone_attachment);
  4913. bone_attachment->set_owner(p_scene_root);
  4914. // There is no gltf_node that represent this, so just directly create a unique name
  4915. bone_attachment->set_name(_gen_unique_name(p_state, "BoneAttachment"));
  4916. // We change the scene_parent to our bone attachment now. We do not set current_node because we want to make the node
  4917. // and attach it to the bone_attachment
  4918. p_scene_parent = bone_attachment;
  4919. WARN_PRINT(vformat("glTF: Generating scene detected direct parented Skeletons at node %d", p_node_index));
  4920. }
  4921. // Add it to the scene if it has not already been added
  4922. if (skeleton->get_parent() == nullptr) {
  4923. p_scene_parent->add_child(skeleton);
  4924. skeleton->set_owner(p_scene_root);
  4925. }
  4926. }
  4927. active_skeleton = skeleton;
  4928. current_node = skeleton;
  4929. if (requires_extra_node) {
  4930. // skinned meshes must not be placed in a bone attachment.
  4931. if (!is_skinned_mesh) {
  4932. // Bone Attachment - Same Node Case
  4933. BoneAttachment *bone_attachment = _generate_bone_attachment(p_state, active_skeleton, p_node_index, p_node_index);
  4934. p_scene_parent->add_child(bone_attachment);
  4935. bone_attachment->set_owner(p_scene_root);
  4936. // There is no gltf_node that represent this, so just directly create a unique name
  4937. bone_attachment->set_name(_gen_unique_name(p_state, "BoneAttachment"));
  4938. // We change the scene_parent to our bone attachment now. We do not set current_node because we want to make the node
  4939. // and attach it to the bone_attachment
  4940. p_scene_parent = bone_attachment;
  4941. }
  4942. // Check if any GLTFDocumentExtension classes want to generate a node for us.
  4943. for (int ext_i = 0; ext_i < document_extensions.size(); ext_i++) {
  4944. Ref<GLTFDocumentExtension> ext = document_extensions[ext_i];
  4945. ERR_CONTINUE(ext.is_null());
  4946. current_node = ext->generate_scene_node(p_state, gltf_node, p_scene_parent);
  4947. if (current_node) {
  4948. break;
  4949. }
  4950. }
  4951. // If none of our GLTFDocumentExtension classes generated us a node, we generate one.
  4952. if (!current_node) {
  4953. if (gltf_node->mesh >= 0) {
  4954. current_node = _generate_mesh_instance(p_state, p_scene_parent, p_node_index);
  4955. } else if (gltf_node->camera >= 0) {
  4956. current_node = _generate_camera(p_state, p_scene_parent, p_node_index);
  4957. } else if (gltf_node->light >= 0) {
  4958. current_node = _generate_light(p_state, p_scene_parent, p_node_index);
  4959. } else {
  4960. current_node = _generate_spatial(p_state, p_scene_parent, p_node_index);
  4961. }
  4962. }
  4963. // Add the node we generated and set the owner to the scene root.
  4964. p_scene_parent->add_child(current_node);
  4965. if (current_node != p_scene_root) {
  4966. Array args;
  4967. args.append(p_scene_root);
  4968. current_node->propagate_call(StringName("set_owner"), args);
  4969. }
  4970. // Do not set transform here. Transform is already applied to our bone.
  4971. if (p_state->use_legacy_names) {
  4972. current_node->set_name(_legacy_validate_node_name(gltf_node->get_name()));
  4973. } else {
  4974. current_node->set_name(gltf_node->get_name());
  4975. }
  4976. }
  4977. p_state->scene_nodes.insert(p_node_index, current_node);
  4978. for (int i = 0; i < gltf_node->children.size(); ++i) {
  4979. _generate_scene_node(p_state, active_skeleton, p_scene_root, gltf_node->children[i]);
  4980. }
  4981. }
  4982. template <class T>
  4983. struct EditorSceneImporterGLTFInterpolate {
  4984. T lerp(const T &a, const T &b, float c) const {
  4985. return a + (b - a) * c;
  4986. }
  4987. T catmull_rom(const T &p0, const T &p1, const T &p2, const T &p3, float t) {
  4988. const float t2 = t * t;
  4989. const float t3 = t2 * t;
  4990. return 0.5f * ((2.0f * p1) + (-p0 + p2) * t + (2.0f * p0 - 5.0f * p1 + 4.0f * p2 - p3) * t2 + (-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3);
  4991. }
  4992. T bezier(T start, T control_1, T control_2, T end, float t) {
  4993. /* Formula from Wikipedia article on Bezier curves. */
  4994. const real_t omt = (1.0 - t);
  4995. const real_t omt2 = omt * omt;
  4996. const real_t omt3 = omt2 * omt;
  4997. const real_t t2 = t * t;
  4998. const real_t t3 = t2 * t;
  4999. return start * omt3 + control_1 * omt2 * t * 3.0 + control_2 * omt * t2 * 3.0 + end * t3;
  5000. }
  5001. };
  5002. // thank you for existing, partial specialization
  5003. template <>
  5004. struct EditorSceneImporterGLTFInterpolate<Quat> {
  5005. Quat lerp(const Quat &a, const Quat &b, const float c) const {
  5006. ERR_FAIL_COND_V_MSG(!a.is_normalized(), Quat(), "The quaternion \"a\" must be normalized.");
  5007. ERR_FAIL_COND_V_MSG(!b.is_normalized(), Quat(), "The quaternion \"b\" must be normalized.");
  5008. return a.slerp(b, c).normalized();
  5009. }
  5010. Quat catmull_rom(const Quat &p0, const Quat &p1, const Quat &p2, const Quat &p3, const float c) {
  5011. ERR_FAIL_COND_V_MSG(!p1.is_normalized(), Quat(), "The quaternion \"p1\" must be normalized.");
  5012. ERR_FAIL_COND_V_MSG(!p2.is_normalized(), Quat(), "The quaternion \"p2\" must be normalized.");
  5013. return p1.slerp(p2, c).normalized();
  5014. }
  5015. Quat bezier(const Quat start, const Quat control_1, const Quat control_2, const Quat end, const float t) {
  5016. ERR_FAIL_COND_V_MSG(!start.is_normalized(), Quat(), "The start quaternion must be normalized.");
  5017. ERR_FAIL_COND_V_MSG(!end.is_normalized(), Quat(), "The end quaternion must be normalized.");
  5018. return start.slerp(end, t).normalized();
  5019. }
  5020. };
  5021. template <class T>
  5022. T GLTFDocument::_interpolate_track(const Vector<float> &p_times, const Vector<T> &p_values, const float p_time, const GLTFAnimation::Interpolation p_interp) {
  5023. ERR_FAIL_COND_V(!p_values.size(), T());
  5024. if (p_times.size() != (p_values.size() / (p_interp == GLTFAnimation::INTERP_CUBIC_SPLINE ? 3 : 1))) {
  5025. ERR_PRINT_ONCE("The interpolated values are not corresponding to its times.");
  5026. return p_values[0];
  5027. }
  5028. //could use binary search, worth it?
  5029. int idx = -1;
  5030. for (int i = 0; i < p_times.size(); i++) {
  5031. if (p_times[i] > p_time) {
  5032. break;
  5033. }
  5034. idx++;
  5035. }
  5036. EditorSceneImporterGLTFInterpolate<T> interp;
  5037. switch (p_interp) {
  5038. case GLTFAnimation::INTERP_LINEAR: {
  5039. if (idx == -1) {
  5040. return p_values[0];
  5041. } else if (idx >= p_times.size() - 1) {
  5042. return p_values[p_times.size() - 1];
  5043. }
  5044. const float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
  5045. return interp.lerp(p_values[idx], p_values[idx + 1], c);
  5046. } break;
  5047. case GLTFAnimation::INTERP_STEP: {
  5048. if (idx == -1) {
  5049. return p_values[0];
  5050. } else if (idx >= p_times.size() - 1) {
  5051. return p_values[p_times.size() - 1];
  5052. }
  5053. return p_values[idx];
  5054. } break;
  5055. case GLTFAnimation::INTERP_CATMULLROMSPLINE: {
  5056. if (idx == -1) {
  5057. return p_values[1];
  5058. } else if (idx >= p_times.size() - 1) {
  5059. return p_values[1 + p_times.size() - 1];
  5060. }
  5061. const float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
  5062. return interp.catmull_rom(p_values[idx - 1], p_values[idx], p_values[idx + 1], p_values[idx + 3], c);
  5063. } break;
  5064. case GLTFAnimation::INTERP_CUBIC_SPLINE: {
  5065. if (idx == -1) {
  5066. return p_values[1];
  5067. } else if (idx >= p_times.size() - 1) {
  5068. return p_values[(p_times.size() - 1) * 3 + 1];
  5069. }
  5070. const float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
  5071. const T from = p_values[idx * 3 + 1];
  5072. const T c1 = from + p_values[idx * 3 + 2];
  5073. const T to = p_values[idx * 3 + 4];
  5074. const T c2 = to + p_values[idx * 3 + 3];
  5075. return interp.bezier(from, c1, c2, to, c);
  5076. } break;
  5077. }
  5078. ERR_FAIL_V(p_values[0]);
  5079. }
  5080. void GLTFDocument::_import_animation(Ref<GLTFState> p_state, AnimationPlayer *p_animation_player, const GLTFAnimationIndex p_index, const int p_bake_fps) {
  5081. Ref<GLTFAnimation> anim = p_state->animations[p_index];
  5082. String name = anim->get_name();
  5083. if (name.empty()) {
  5084. // No node represent these, and they are not in the hierarchy, so just make a unique name
  5085. name = _gen_unique_name(p_state, "Animation");
  5086. }
  5087. Ref<Animation> animation;
  5088. animation.instance();
  5089. animation->set_name(name);
  5090. if (anim->get_loop()) {
  5091. animation->set_loop(true);
  5092. }
  5093. float length = 0.0;
  5094. for (Map<int, GLTFAnimation::Track>::Element *track_i = anim->get_tracks().front(); track_i; track_i = track_i->next()) {
  5095. const GLTFAnimation::Track &track = track_i->get();
  5096. //need to find the path: for skeletons, weight tracks will affect the mesh
  5097. NodePath node_path;
  5098. //for skeletons, transform tracks always affect bones
  5099. NodePath transform_node_path;
  5100. GLTFNodeIndex node_index = track_i->key();
  5101. const Ref<GLTFNode> gltf_node = p_state->nodes[track_i->key()];
  5102. Node *root = p_animation_player->get_parent();
  5103. ERR_FAIL_COND(root == nullptr);
  5104. Map<GLTFNodeIndex, Node *>::Element *node_element = p_state->scene_nodes.find(node_index);
  5105. ERR_CONTINUE_MSG(node_element == nullptr, vformat("Unable to find node %d for animation", node_index));
  5106. node_path = root->get_path_to(node_element->get());
  5107. if (gltf_node->skeleton >= 0) {
  5108. const Skeleton *sk = p_state->skeletons[gltf_node->skeleton]->godot_skeleton;
  5109. ERR_FAIL_COND(sk == nullptr);
  5110. const String path = p_animation_player->get_parent()->get_path_to(sk);
  5111. const String bone = gltf_node->get_name();
  5112. transform_node_path = path + ":" + bone;
  5113. } else {
  5114. transform_node_path = node_path;
  5115. }
  5116. for (int i = 0; i < track.rotation_track.times.size(); i++) {
  5117. length = MAX(length, track.rotation_track.times[i]);
  5118. }
  5119. for (int i = 0; i < track.translation_track.times.size(); i++) {
  5120. length = MAX(length, track.translation_track.times[i]);
  5121. }
  5122. for (int i = 0; i < track.scale_track.times.size(); i++) {
  5123. length = MAX(length, track.scale_track.times[i]);
  5124. }
  5125. for (int i = 0; i < track.weight_tracks.size(); i++) {
  5126. for (int j = 0; j < track.weight_tracks[i].times.size(); j++) {
  5127. length = MAX(length, track.weight_tracks[i].times[j]);
  5128. }
  5129. }
  5130. // Animated TRS properties will not affect a skinned mesh.
  5131. const bool transform_affects_skinned_mesh_instance = gltf_node->skeleton < 0 && gltf_node->skin >= 0;
  5132. if ((track.rotation_track.values.size() || track.translation_track.values.size() || track.scale_track.values.size()) && !transform_affects_skinned_mesh_instance) {
  5133. //make transform track
  5134. int track_idx = animation->get_track_count();
  5135. animation->add_track(Animation::TYPE_TRANSFORM);
  5136. animation->track_set_path(track_idx, transform_node_path);
  5137. //first determine animation length
  5138. const double increment = 1.0 / p_bake_fps;
  5139. double time = 0.0;
  5140. Vector3 base_pos;
  5141. Quat base_rot;
  5142. Vector3 base_scale = Vector3(1, 1, 1);
  5143. if (!track.rotation_track.values.size()) {
  5144. base_rot = p_state->nodes[track_i->key()]->rotation.normalized();
  5145. }
  5146. if (!track.translation_track.values.size()) {
  5147. base_pos = p_state->nodes[track_i->key()]->translation;
  5148. }
  5149. if (!track.scale_track.values.size()) {
  5150. base_scale = p_state->nodes[track_i->key()]->scale;
  5151. }
  5152. bool last = false;
  5153. while (true) {
  5154. Vector3 pos = base_pos;
  5155. Quat rot = base_rot;
  5156. Vector3 scale = base_scale;
  5157. if (track.translation_track.times.size()) {
  5158. pos = _interpolate_track<Vector3>(track.translation_track.times, track.translation_track.values, time, track.translation_track.interpolation);
  5159. }
  5160. if (track.rotation_track.times.size()) {
  5161. rot = _interpolate_track<Quat>(track.rotation_track.times, track.rotation_track.values, time, track.rotation_track.interpolation);
  5162. }
  5163. if (track.scale_track.times.size()) {
  5164. scale = _interpolate_track<Vector3>(track.scale_track.times, track.scale_track.values, time, track.scale_track.interpolation);
  5165. }
  5166. if (gltf_node->skeleton >= 0) {
  5167. Transform xform;
  5168. xform.basis.set_quat_scale(rot, scale);
  5169. xform.origin = pos;
  5170. const Skeleton *skeleton = p_state->skeletons[gltf_node->skeleton]->godot_skeleton;
  5171. const int bone_idx = skeleton->find_bone(gltf_node->get_name());
  5172. xform = skeleton->get_bone_rest(bone_idx).affine_inverse() * xform;
  5173. rot = xform.basis.get_rotation_quat();
  5174. rot.normalize();
  5175. scale = xform.basis.get_scale();
  5176. pos = xform.origin;
  5177. }
  5178. animation->transform_track_insert_key(track_idx, time, pos, rot, scale);
  5179. if (last) {
  5180. break;
  5181. }
  5182. time += increment;
  5183. if (time >= length) {
  5184. last = true;
  5185. time = length;
  5186. }
  5187. }
  5188. }
  5189. for (int i = 0; i < track.weight_tracks.size(); i++) {
  5190. ERR_CONTINUE(gltf_node->mesh < 0 || gltf_node->mesh >= p_state->meshes.size());
  5191. Ref<GLTFMesh> mesh = p_state->meshes[gltf_node->mesh];
  5192. ERR_CONTINUE(mesh.is_null());
  5193. ERR_CONTINUE(mesh->get_mesh().is_null());
  5194. const String prop = "blend_shapes/" + mesh->get_mesh()->get_blend_shape_name(i);
  5195. const String blend_path = String(node_path) + ":" + prop;
  5196. const int track_idx = animation->get_track_count();
  5197. animation->add_track(Animation::TYPE_VALUE);
  5198. animation->track_set_path(track_idx, blend_path);
  5199. // Only LINEAR and STEP (NEAREST) can be supported out of the box by Godot's Animation,
  5200. // the other modes have to be baked.
  5201. GLTFAnimation::Interpolation gltf_interp = track.weight_tracks[i].interpolation;
  5202. if (gltf_interp == GLTFAnimation::INTERP_LINEAR || gltf_interp == GLTFAnimation::INTERP_STEP) {
  5203. animation->track_set_interpolation_type(track_idx, gltf_interp == GLTFAnimation::INTERP_STEP ? Animation::INTERPOLATION_NEAREST : Animation::INTERPOLATION_LINEAR);
  5204. for (int j = 0; j < track.weight_tracks[i].times.size(); j++) {
  5205. const float t = track.weight_tracks[i].times[j];
  5206. const float attribs = track.weight_tracks[i].values[j];
  5207. animation->track_insert_key(track_idx, t, attribs);
  5208. }
  5209. } else {
  5210. // CATMULLROMSPLINE or CUBIC_SPLINE have to be baked, apologies.
  5211. const double increment = 1.0 / p_bake_fps;
  5212. double time = 0.0;
  5213. bool last = false;
  5214. while (true) {
  5215. _interpolate_track<float>(track.weight_tracks[i].times, track.weight_tracks[i].values, time, gltf_interp);
  5216. if (last) {
  5217. break;
  5218. }
  5219. time += increment;
  5220. if (time >= length) {
  5221. last = true;
  5222. time = length;
  5223. }
  5224. }
  5225. }
  5226. }
  5227. }
  5228. animation->set_length(length);
  5229. p_animation_player->add_animation(name, animation);
  5230. }
  5231. void GLTFDocument::_convert_mesh_instances(Ref<GLTFState> p_state) {
  5232. for (GLTFNodeIndex mi_node_i = 0; mi_node_i < p_state->nodes.size(); ++mi_node_i) {
  5233. Ref<GLTFNode> node = p_state->nodes[mi_node_i];
  5234. if (node->mesh < 0) {
  5235. continue;
  5236. }
  5237. Map<GLTFNodeIndex, Node *>::Element *mi_element = p_state->scene_nodes.find(mi_node_i);
  5238. if (!mi_element) {
  5239. continue;
  5240. }
  5241. MeshInstance *mi = Object::cast_to<MeshInstance>(mi_element->get());
  5242. ERR_CONTINUE(!mi);
  5243. Transform mi_xform = mi->get_transform();
  5244. node->scale = mi_xform.basis.get_scale();
  5245. node->rotation = mi_xform.basis.get_rotation_quat();
  5246. node->translation = mi_xform.origin;
  5247. Skeleton *skeleton = Object::cast_to<Skeleton>(mi->get_node(mi->get_skeleton_path()));
  5248. if (!skeleton) {
  5249. continue;
  5250. }
  5251. if (!skeleton->get_bone_count()) {
  5252. continue;
  5253. }
  5254. Ref<Skin> skin = mi->get_skin();
  5255. Ref<GLTFSkin> gltf_skin;
  5256. gltf_skin.instance();
  5257. Array json_joints;
  5258. NodePath skeleton_path = mi->get_skeleton_path();
  5259. Node *skel_node = mi->get_node_or_null(skeleton_path);
  5260. Skeleton *godot_skeleton = nullptr;
  5261. if (skel_node != nullptr) {
  5262. godot_skeleton = cast_to<Skeleton>(skel_node);
  5263. }
  5264. if (godot_skeleton != nullptr && p_state->skeleton3d_to_gltf_skeleton.has(godot_skeleton->get_instance_id())) {
  5265. // This is a skinned mesh. If the mesh has no ARRAY_WEIGHTS or ARRAY_BONES, it will be invisible.
  5266. const GLTFSkeletonIndex skeleton_gltf_i = p_state->skeleton3d_to_gltf_skeleton[godot_skeleton->get_instance_id()];
  5267. Ref<GLTFSkeleton> gltf_skeleton = p_state->skeletons[skeleton_gltf_i];
  5268. int bone_cnt = skeleton->get_bone_count();
  5269. ERR_FAIL_COND(bone_cnt != gltf_skeleton->joints.size());
  5270. ObjectID gltf_skin_key = 0;
  5271. if (skin.is_valid()) {
  5272. gltf_skin_key = skin->get_instance_id();
  5273. }
  5274. ObjectID gltf_skel_key = godot_skeleton->get_instance_id();
  5275. GLTFSkinIndex skin_gltf_i = -1;
  5276. GLTFNodeIndex root_gltf_i = -1;
  5277. if (!gltf_skeleton->roots.empty()) {
  5278. root_gltf_i = gltf_skeleton->roots[0];
  5279. }
  5280. if (p_state->skin_and_skeleton3d_to_gltf_skin.has(gltf_skin_key) && p_state->skin_and_skeleton3d_to_gltf_skin[gltf_skin_key].has(gltf_skel_key)) {
  5281. skin_gltf_i = p_state->skin_and_skeleton3d_to_gltf_skin[gltf_skin_key][gltf_skel_key];
  5282. } else {
  5283. if (skin.is_null()) {
  5284. // Note that gltf_skin_key should remain null, so these can share a reference.
  5285. skin = skeleton->register_skin(nullptr)->get_skin();
  5286. }
  5287. gltf_skin.instance();
  5288. gltf_skin->godot_skin = skin;
  5289. gltf_skin->set_name(skin->get_name());
  5290. gltf_skin->skeleton = skeleton_gltf_i;
  5291. gltf_skin->skin_root = root_gltf_i;
  5292. //gltf_state->godot_to_gltf_node[skel_node]
  5293. HashMap<StringName, int> bone_name_to_idx;
  5294. for (int bone_i = 0; bone_i < bone_cnt; bone_i++) {
  5295. bone_name_to_idx[skeleton->get_bone_name(bone_i)] = bone_i;
  5296. }
  5297. for (int bind_i = 0, cnt = skin->get_bind_count(); bind_i < cnt; bind_i++) {
  5298. int bone_i = skin->get_bind_bone(bind_i);
  5299. Transform bind_pose = skin->get_bind_pose(bind_i);
  5300. StringName bind_name = skin->get_bind_name(bind_i);
  5301. if (bind_name != StringName()) {
  5302. bone_i = bone_name_to_idx[bind_name];
  5303. }
  5304. ERR_CONTINUE(bone_i < 0 || bone_i >= bone_cnt);
  5305. if (bind_name == StringName()) {
  5306. bind_name = skeleton->get_bone_name(bone_i);
  5307. }
  5308. GLTFNodeIndex skeleton_bone_i = gltf_skeleton->joints[bone_i];
  5309. gltf_skin->joints_original.push_back(skeleton_bone_i);
  5310. gltf_skin->joints.push_back(skeleton_bone_i);
  5311. gltf_skin->inverse_binds.push_back(bind_pose);
  5312. if (skeleton->get_bone_parent(bone_i) == -1) {
  5313. gltf_skin->roots.push_back(skeleton_bone_i);
  5314. }
  5315. gltf_skin->joint_i_to_bone_i[bind_i] = bone_i;
  5316. gltf_skin->joint_i_to_name[bind_i] = bind_name;
  5317. }
  5318. skin_gltf_i = p_state->skins.size();
  5319. p_state->skins.push_back(gltf_skin);
  5320. p_state->skin_and_skeleton3d_to_gltf_skin[gltf_skin_key][gltf_skel_key] = skin_gltf_i;
  5321. }
  5322. node->skin = skin_gltf_i;
  5323. node->skeleton = skeleton_gltf_i;
  5324. }
  5325. }
  5326. }
  5327. float GLTFDocument::solve_metallic(float p_dielectric_specular, float p_diffuse, float p_specular, float p_one_minus_specular_strength) {
  5328. if (p_specular <= p_dielectric_specular) {
  5329. return 0.0f;
  5330. }
  5331. const float a = p_dielectric_specular;
  5332. const float b = p_diffuse * p_one_minus_specular_strength / (1.0f - p_dielectric_specular) + p_specular - 2.0f * p_dielectric_specular;
  5333. const float c = p_dielectric_specular - p_specular;
  5334. const float D = b * b - 4.0f * a * c;
  5335. return CLAMP((-b + Math::sqrt(D)) / (2.0f * a), 0.0f, 1.0f);
  5336. }
  5337. float GLTFDocument::get_perceived_brightness(const Color p_color) {
  5338. const Color coeff = Color(R_BRIGHTNESS_COEFF, G_BRIGHTNESS_COEFF, B_BRIGHTNESS_COEFF);
  5339. const Color value = coeff * (p_color * p_color);
  5340. const float r = value.r;
  5341. const float g = value.g;
  5342. const float b = value.b;
  5343. return Math::sqrt(r + g + b);
  5344. }
  5345. float GLTFDocument::get_max_component(const Color &p_color) {
  5346. const float r = p_color.r;
  5347. const float g = p_color.g;
  5348. const float b = p_color.b;
  5349. return MAX(MAX(r, g), b);
  5350. }
  5351. void GLTFDocument::_process_mesh_instances(Ref<GLTFState> p_state, Node *p_scene_root) {
  5352. for (GLTFNodeIndex node_i = 0; node_i < p_state->nodes.size(); ++node_i) {
  5353. Ref<GLTFNode> node = p_state->nodes[node_i];
  5354. if (node->skin >= 0 && node->mesh >= 0) {
  5355. const GLTFSkinIndex skin_i = node->skin;
  5356. Map<GLTFNodeIndex, Node *>::Element *mi_element = p_state->scene_nodes.find(node_i);
  5357. ERR_CONTINUE_MSG(mi_element == nullptr, vformat("Unable to find node %d", node_i));
  5358. MeshInstance *mi = Object::cast_to<MeshInstance>(mi_element->get());
  5359. ERR_CONTINUE_MSG(mi == nullptr, vformat("Unable to cast node %d of type %s to MeshInstance", node_i, mi_element->get()->get_class_name()));
  5360. const GLTFSkeletonIndex skel_i = p_state->skins.write[node->skin]->skeleton;
  5361. Ref<GLTFSkeleton> gltf_skeleton = p_state->skeletons.write[skel_i];
  5362. Skeleton *skeleton = gltf_skeleton->godot_skeleton;
  5363. ERR_CONTINUE_MSG(skeleton == nullptr, vformat("Unable to find Skeleton for node %d skin %d", node_i, skin_i));
  5364. mi->get_parent()->remove_child(mi);
  5365. skeleton->add_child(mi);
  5366. mi->set_owner(skeleton->get_owner());
  5367. mi->set_skin(p_state->skins.write[skin_i]->godot_skin);
  5368. mi->set_skeleton_path(mi->get_path_to(skeleton));
  5369. mi->set_transform(Transform());
  5370. }
  5371. }
  5372. }
  5373. GLTFAnimation::Track GLTFDocument::_convert_animation_track(Ref<GLTFState> p_state, GLTFAnimation::Track p_track, Ref<Animation> p_animation, Transform p_bone_rest, int32_t p_track_i, GLTFNodeIndex p_node_i) {
  5374. Animation::InterpolationType interpolation = p_animation->track_get_interpolation_type(p_track_i);
  5375. GLTFAnimation::Interpolation gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
  5376. if (interpolation == Animation::InterpolationType::INTERPOLATION_LINEAR) {
  5377. gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
  5378. } else if (interpolation == Animation::InterpolationType::INTERPOLATION_NEAREST) {
  5379. gltf_interpolation = GLTFAnimation::INTERP_STEP;
  5380. } else if (interpolation == Animation::InterpolationType::INTERPOLATION_CUBIC) {
  5381. gltf_interpolation = GLTFAnimation::INTERP_CUBIC_SPLINE;
  5382. }
  5383. Animation::TrackType track_type = p_animation->track_get_type(p_track_i);
  5384. int32_t key_count = p_animation->track_get_key_count(p_track_i);
  5385. Vector<float> times;
  5386. times.resize(key_count);
  5387. String path = p_animation->track_get_path(p_track_i);
  5388. for (int32_t key_i = 0; key_i < key_count; key_i++) {
  5389. times.write[key_i] = p_animation->track_get_key_time(p_track_i, key_i);
  5390. }
  5391. if (track_type == Animation::TYPE_TRANSFORM) {
  5392. p_track.translation_track.times = times;
  5393. p_track.translation_track.interpolation = gltf_interpolation;
  5394. p_track.rotation_track.times = times;
  5395. p_track.rotation_track.interpolation = gltf_interpolation;
  5396. p_track.scale_track.times = times;
  5397. p_track.scale_track.interpolation = gltf_interpolation;
  5398. p_track.scale_track.values.resize(key_count);
  5399. p_track.scale_track.interpolation = gltf_interpolation;
  5400. p_track.translation_track.values.resize(key_count);
  5401. p_track.translation_track.interpolation = gltf_interpolation;
  5402. p_track.rotation_track.values.resize(key_count);
  5403. p_track.rotation_track.interpolation = gltf_interpolation;
  5404. for (int32_t key_i = 0; key_i < key_count; key_i++) {
  5405. Vector3 translation;
  5406. Quat rotation;
  5407. Vector3 scale;
  5408. Error err = p_animation->transform_track_get_key(p_track_i, key_i, &translation, &rotation, &scale);
  5409. ERR_CONTINUE(err != OK);
  5410. Transform xform;
  5411. xform.basis.set_quat_scale(rotation, scale);
  5412. xform.origin = translation;
  5413. xform = p_bone_rest * xform;
  5414. p_track.translation_track.values.write[key_i] = xform.get_origin();
  5415. p_track.rotation_track.values.write[key_i] = xform.basis.get_rotation_quat();
  5416. p_track.scale_track.values.write[key_i] = xform.basis.get_scale();
  5417. }
  5418. } else if (path.find(":transform") != -1) {
  5419. p_track.translation_track.times = times;
  5420. p_track.translation_track.interpolation = gltf_interpolation;
  5421. p_track.rotation_track.times = times;
  5422. p_track.rotation_track.interpolation = gltf_interpolation;
  5423. p_track.scale_track.times = times;
  5424. p_track.scale_track.interpolation = gltf_interpolation;
  5425. p_track.scale_track.values.resize(key_count);
  5426. p_track.scale_track.interpolation = gltf_interpolation;
  5427. p_track.translation_track.values.resize(key_count);
  5428. p_track.translation_track.interpolation = gltf_interpolation;
  5429. p_track.rotation_track.values.resize(key_count);
  5430. p_track.rotation_track.interpolation = gltf_interpolation;
  5431. for (int32_t key_i = 0; key_i < key_count; key_i++) {
  5432. Transform xform = p_animation->track_get_key_value(p_track_i, key_i);
  5433. p_track.translation_track.values.write[key_i] = xform.get_origin();
  5434. p_track.rotation_track.values.write[key_i] = xform.basis.get_rotation_quat();
  5435. p_track.scale_track.values.write[key_i] = xform.basis.get_scale();
  5436. }
  5437. } else if (track_type == Animation::TYPE_VALUE) {
  5438. if (path.find("/rotation_quat") != -1) {
  5439. p_track.rotation_track.times = times;
  5440. p_track.rotation_track.interpolation = gltf_interpolation;
  5441. p_track.rotation_track.values.resize(key_count);
  5442. p_track.rotation_track.interpolation = gltf_interpolation;
  5443. for (int32_t key_i = 0; key_i < key_count; key_i++) {
  5444. Quat rotation_track = p_animation->track_get_key_value(p_track_i, key_i);
  5445. p_track.rotation_track.values.write[key_i] = rotation_track;
  5446. }
  5447. } else if (path.find(":translation") != -1) {
  5448. p_track.translation_track.times = times;
  5449. p_track.translation_track.interpolation = gltf_interpolation;
  5450. p_track.translation_track.values.resize(key_count);
  5451. p_track.translation_track.interpolation = gltf_interpolation;
  5452. for (int32_t key_i = 0; key_i < key_count; key_i++) {
  5453. Vector3 translation = p_animation->track_get_key_value(p_track_i, key_i);
  5454. p_track.translation_track.values.write[key_i] = translation;
  5455. }
  5456. } else if (path.find(":rotation_degrees") != -1) {
  5457. p_track.rotation_track.times = times;
  5458. p_track.rotation_track.interpolation = gltf_interpolation;
  5459. p_track.rotation_track.values.resize(key_count);
  5460. p_track.rotation_track.interpolation = gltf_interpolation;
  5461. for (int32_t key_i = 0; key_i < key_count; key_i++) {
  5462. Vector3 rotation_degrees = p_animation->track_get_key_value(p_track_i, key_i);
  5463. Vector3 rotation_radian;
  5464. rotation_radian.x = Math::deg2rad(rotation_degrees.x);
  5465. rotation_radian.y = Math::deg2rad(rotation_degrees.y);
  5466. rotation_radian.z = Math::deg2rad(rotation_degrees.z);
  5467. p_track.rotation_track.values.write[key_i] = Quat(rotation_radian);
  5468. }
  5469. } else if (path.find(":scale") != -1) {
  5470. p_track.scale_track.times = times;
  5471. p_track.scale_track.interpolation = gltf_interpolation;
  5472. p_track.scale_track.values.resize(key_count);
  5473. p_track.scale_track.interpolation = gltf_interpolation;
  5474. for (int32_t key_i = 0; key_i < key_count; key_i++) {
  5475. Vector3 scale_track = p_animation->track_get_key_value(p_track_i, key_i);
  5476. p_track.scale_track.values.write[key_i] = scale_track;
  5477. }
  5478. }
  5479. } else if (track_type == Animation::TYPE_BEZIER) {
  5480. if (path.find("/scale") != -1) {
  5481. const int32_t keys = p_animation->track_get_key_time(p_track_i, key_count - 1) * BAKE_FPS;
  5482. if (!p_track.scale_track.times.size()) {
  5483. Vector<float> new_times;
  5484. new_times.resize(keys);
  5485. for (int32_t key_i = 0; key_i < keys; key_i++) {
  5486. new_times.write[key_i] = key_i / BAKE_FPS;
  5487. }
  5488. p_track.scale_track.times = new_times;
  5489. p_track.scale_track.interpolation = gltf_interpolation;
  5490. p_track.scale_track.values.resize(keys);
  5491. for (int32_t key_i = 0; key_i < keys; key_i++) {
  5492. p_track.scale_track.values.write[key_i] = Vector3(1.0f, 1.0f, 1.0f);
  5493. }
  5494. p_track.scale_track.interpolation = gltf_interpolation;
  5495. }
  5496. for (int32_t key_i = 0; key_i < keys; key_i++) {
  5497. Vector3 bezier_track = p_track.scale_track.values[key_i];
  5498. if (path.find("/scale:x") != -1) {
  5499. bezier_track.x = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
  5500. bezier_track.x = p_bone_rest.affine_inverse().basis.get_scale().x * bezier_track.x;
  5501. } else if (path.find("/scale:y") != -1) {
  5502. bezier_track.y = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
  5503. bezier_track.y = p_bone_rest.affine_inverse().basis.get_scale().y * bezier_track.y;
  5504. } else if (path.find("/scale:z") != -1) {
  5505. bezier_track.z = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
  5506. bezier_track.z = p_bone_rest.affine_inverse().basis.get_scale().z * bezier_track.z;
  5507. }
  5508. p_track.scale_track.values.write[key_i] = bezier_track;
  5509. }
  5510. } else if (path.find("/translation") != -1) {
  5511. const int32_t keys = p_animation->track_get_key_time(p_track_i, key_count - 1) * BAKE_FPS;
  5512. if (!p_track.translation_track.times.size()) {
  5513. Vector<float> new_times;
  5514. new_times.resize(keys);
  5515. for (int32_t key_i = 0; key_i < keys; key_i++) {
  5516. new_times.write[key_i] = key_i / BAKE_FPS;
  5517. }
  5518. p_track.translation_track.times = new_times;
  5519. p_track.translation_track.interpolation = gltf_interpolation;
  5520. p_track.translation_track.values.resize(keys);
  5521. p_track.translation_track.interpolation = gltf_interpolation;
  5522. }
  5523. for (int32_t key_i = 0; key_i < keys; key_i++) {
  5524. Vector3 bezier_track = p_track.translation_track.values[key_i];
  5525. if (path.find("/translation:x") != -1) {
  5526. bezier_track.x = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
  5527. bezier_track.x = p_bone_rest.affine_inverse().origin.x * bezier_track.x;
  5528. } else if (path.find("/translation:y") != -1) {
  5529. bezier_track.y = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
  5530. bezier_track.y = p_bone_rest.affine_inverse().origin.y * bezier_track.y;
  5531. } else if (path.find("/translation:z") != -1) {
  5532. bezier_track.z = p_animation->bezier_track_interpolate(p_track_i, key_i / BAKE_FPS);
  5533. bezier_track.z = p_bone_rest.affine_inverse().origin.z * bezier_track.z;
  5534. }
  5535. p_track.translation_track.values.write[key_i] = bezier_track;
  5536. }
  5537. }
  5538. }
  5539. return p_track;
  5540. }
  5541. void GLTFDocument::_convert_animation(Ref<GLTFState> p_state, AnimationPlayer *p_animation_player, String p_animation_track_name) {
  5542. Ref<Animation> animation = p_animation_player->get_animation(p_animation_track_name);
  5543. Ref<GLTFAnimation> gltf_animation;
  5544. gltf_animation.instance();
  5545. gltf_animation->set_name(_gen_unique_name(p_state, p_animation_track_name));
  5546. for (int32_t track_i = 0; track_i < animation->get_track_count(); track_i++) {
  5547. if (!animation->track_is_enabled(track_i)) {
  5548. continue;
  5549. }
  5550. String orig_track_path = animation->track_get_path(track_i);
  5551. if (String(orig_track_path).find(":translation") != -1) {
  5552. const Vector<String> node_suffix = String(orig_track_path).split(":translation");
  5553. const NodePath path = node_suffix[0];
  5554. const Node *node = p_animation_player->get_parent()->get_node_or_null(path);
  5555. for (Map<GLTFNodeIndex, Node *>::Element *translation_scene_node_i = p_state->scene_nodes.front(); translation_scene_node_i; translation_scene_node_i = translation_scene_node_i->next()) {
  5556. if (translation_scene_node_i->get() == node) {
  5557. GLTFNodeIndex node_index = translation_scene_node_i->key();
  5558. Map<int, GLTFAnimation::Track>::Element *translation_track_i = gltf_animation->get_tracks().find(node_index);
  5559. GLTFAnimation::Track track;
  5560. if (translation_track_i) {
  5561. track = translation_track_i->get();
  5562. }
  5563. track = _convert_animation_track(p_state, track, animation, Transform(), track_i, node_index);
  5564. gltf_animation->get_tracks().insert(node_index, track);
  5565. }
  5566. }
  5567. } else if (String(orig_track_path).find(":rotation_degrees") != -1) {
  5568. const Vector<String> node_suffix = String(orig_track_path).split(":rotation_degrees");
  5569. const NodePath path = node_suffix[0];
  5570. const Node *node = p_animation_player->get_parent()->get_node_or_null(path);
  5571. for (Map<GLTFNodeIndex, Node *>::Element *rotation_degree_scene_node_i = p_state->scene_nodes.front(); rotation_degree_scene_node_i; rotation_degree_scene_node_i = rotation_degree_scene_node_i->next()) {
  5572. if (rotation_degree_scene_node_i->get() == node) {
  5573. GLTFNodeIndex node_index = rotation_degree_scene_node_i->key();
  5574. Map<int, GLTFAnimation::Track>::Element *rotation_degree_track_i = gltf_animation->get_tracks().find(node_index);
  5575. GLTFAnimation::Track track;
  5576. if (rotation_degree_track_i) {
  5577. track = rotation_degree_track_i->get();
  5578. }
  5579. track = _convert_animation_track(p_state, track, animation, Transform(), track_i, node_index);
  5580. gltf_animation->get_tracks().insert(node_index, track);
  5581. }
  5582. }
  5583. } else if (String(orig_track_path).find(":scale") != -1) {
  5584. const Vector<String> node_suffix = String(orig_track_path).split(":scale");
  5585. const NodePath path = node_suffix[0];
  5586. const Node *node = p_animation_player->get_parent()->get_node_or_null(path);
  5587. for (Map<GLTFNodeIndex, Node *>::Element *scale_scene_node_i = p_state->scene_nodes.front(); scale_scene_node_i; scale_scene_node_i = scale_scene_node_i->next()) {
  5588. if (scale_scene_node_i->get() == node) {
  5589. GLTFNodeIndex node_index = scale_scene_node_i->key();
  5590. Map<int, GLTFAnimation::Track>::Element *scale_track_i = gltf_animation->get_tracks().find(node_index);
  5591. GLTFAnimation::Track track;
  5592. if (scale_track_i) {
  5593. track = scale_track_i->get();
  5594. }
  5595. track = _convert_animation_track(p_state, track, animation, Transform(), track_i, node_index);
  5596. gltf_animation->get_tracks().insert(node_index, track);
  5597. }
  5598. }
  5599. } else if (String(orig_track_path).find(":transform") != -1) {
  5600. const Vector<String> node_suffix = String(orig_track_path).split(":transform");
  5601. const NodePath path = node_suffix[0];
  5602. const Node *node = p_animation_player->get_parent()->get_node_or_null(path);
  5603. for (Map<GLTFNodeIndex, Node *>::Element *transform_track_i = p_state->scene_nodes.front(); transform_track_i; transform_track_i = transform_track_i->next()) {
  5604. if (transform_track_i->get() == node) {
  5605. GLTFAnimation::Track track;
  5606. track = _convert_animation_track(p_state, track, animation, Transform(), track_i, transform_track_i->key());
  5607. gltf_animation->get_tracks().insert(transform_track_i->key(), track);
  5608. }
  5609. }
  5610. } else if (String(orig_track_path).find(":blend_shapes/") != -1) {
  5611. const Vector<String> node_suffix = String(orig_track_path).split(":blend_shapes/");
  5612. const NodePath path = node_suffix[0];
  5613. const String suffix = node_suffix[1];
  5614. Node *node = p_animation_player->get_parent()->get_node_or_null(path);
  5615. MeshInstance *mi = cast_to<MeshInstance>(node);
  5616. Ref<Mesh> mesh = mi->get_mesh();
  5617. ERR_CONTINUE(mesh.is_null());
  5618. int32_t mesh_index = -1;
  5619. for (Map<GLTFNodeIndex, Node *>::Element *mesh_track_i = p_state->scene_nodes.front(); mesh_track_i; mesh_track_i = mesh_track_i->next()) {
  5620. if (mesh_track_i->get() == node) {
  5621. mesh_index = mesh_track_i->key();
  5622. }
  5623. }
  5624. ERR_CONTINUE(mesh_index == -1);
  5625. Map<int, GLTFAnimation::Track> &tracks = gltf_animation->get_tracks();
  5626. GLTFAnimation::Track track = gltf_animation->get_tracks().has(mesh_index) ? gltf_animation->get_tracks()[mesh_index] : GLTFAnimation::Track();
  5627. if (!tracks.has(mesh_index)) {
  5628. for (int32_t shape_i = 0; shape_i < mesh->get_blend_shape_count(); shape_i++) {
  5629. String shape_name = mesh->get_blend_shape_name(shape_i);
  5630. NodePath shape_path = String(path) + ":blend_shapes/" + shape_name;
  5631. int32_t shape_track_i = animation->find_track(shape_path);
  5632. if (shape_track_i == -1) {
  5633. GLTFAnimation::Channel<float> weight;
  5634. weight.interpolation = GLTFAnimation::INTERP_LINEAR;
  5635. weight.times.push_back(0.0f);
  5636. weight.times.push_back(0.0f);
  5637. weight.values.push_back(0.0f);
  5638. weight.values.push_back(0.0f);
  5639. track.weight_tracks.push_back(weight);
  5640. continue;
  5641. }
  5642. Animation::InterpolationType interpolation = animation->track_get_interpolation_type(track_i);
  5643. GLTFAnimation::Interpolation gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
  5644. if (interpolation == Animation::InterpolationType::INTERPOLATION_LINEAR) {
  5645. gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
  5646. } else if (interpolation == Animation::InterpolationType::INTERPOLATION_NEAREST) {
  5647. gltf_interpolation = GLTFAnimation::INTERP_STEP;
  5648. } else if (interpolation == Animation::InterpolationType::INTERPOLATION_CUBIC) {
  5649. gltf_interpolation = GLTFAnimation::INTERP_CUBIC_SPLINE;
  5650. }
  5651. int32_t key_count = animation->track_get_key_count(shape_track_i);
  5652. GLTFAnimation::Channel<float> weight;
  5653. weight.interpolation = gltf_interpolation;
  5654. weight.times.resize(key_count);
  5655. for (int32_t time_i = 0; time_i < key_count; time_i++) {
  5656. weight.times.write[time_i] = animation->track_get_key_time(shape_track_i, time_i);
  5657. }
  5658. weight.values.resize(key_count);
  5659. for (int32_t value_i = 0; value_i < key_count; value_i++) {
  5660. weight.values.write[value_i] = animation->track_get_key_value(shape_track_i, value_i);
  5661. }
  5662. track.weight_tracks.push_back(weight);
  5663. }
  5664. tracks[mesh_index] = track;
  5665. }
  5666. } else if (String(orig_track_path).find(":") != -1) {
  5667. //Process skeleton
  5668. const Vector<String> node_suffix = String(orig_track_path).split(":");
  5669. const String node = node_suffix[0];
  5670. const NodePath node_path = node;
  5671. const String suffix = node_suffix[1];
  5672. Node *godot_node = p_animation_player->get_parent()->get_node_or_null(node_path);
  5673. Skeleton *skeleton = nullptr;
  5674. GLTFSkeletonIndex skeleton_gltf_i = -1;
  5675. for (GLTFSkeletonIndex skeleton_i = 0; skeleton_i < p_state->skeletons.size(); skeleton_i++) {
  5676. if (p_state->skeletons[skeleton_i]->godot_skeleton == cast_to<Skeleton>(godot_node)) {
  5677. skeleton = p_state->skeletons[skeleton_i]->godot_skeleton;
  5678. skeleton_gltf_i = skeleton_i;
  5679. ERR_CONTINUE(!skeleton);
  5680. Ref<GLTFSkeleton> skeleton_gltf = p_state->skeletons[skeleton_gltf_i];
  5681. int32_t bone = skeleton->find_bone(suffix);
  5682. ERR_CONTINUE(bone == -1);
  5683. Transform xform = skeleton->get_bone_rest(bone);
  5684. if (!skeleton_gltf->godot_bone_node.has(bone)) {
  5685. continue;
  5686. }
  5687. GLTFNodeIndex node_i = skeleton_gltf->godot_bone_node[bone];
  5688. Map<int, GLTFAnimation::Track>::Element *property_track_i = gltf_animation->get_tracks().find(node_i);
  5689. GLTFAnimation::Track track;
  5690. if (property_track_i) {
  5691. track = property_track_i->get();
  5692. }
  5693. track = _convert_animation_track(p_state, track, animation, xform, track_i, node_i);
  5694. gltf_animation->get_tracks()[node_i] = track;
  5695. }
  5696. }
  5697. } else if (String(orig_track_path).find(":") == -1) {
  5698. ERR_CONTINUE(!p_animation_player->get_parent());
  5699. for (int32_t node_i = 0; node_i < p_animation_player->get_parent()->get_child_count(); node_i++) {
  5700. const Node *child = p_animation_player->get_parent()->get_child(node_i);
  5701. const Node *node = child->get_node_or_null(orig_track_path);
  5702. for (Map<GLTFNodeIndex, Node *>::Element *scene_node_i = p_state->scene_nodes.front(); scene_node_i; scene_node_i = scene_node_i->next()) {
  5703. if (scene_node_i->get() == node) {
  5704. GLTFNodeIndex node_index = scene_node_i->key();
  5705. Map<int, GLTFAnimation::Track>::Element *node_track_i = gltf_animation->get_tracks().find(node_index);
  5706. GLTFAnimation::Track track;
  5707. if (node_track_i) {
  5708. track = node_track_i->get();
  5709. }
  5710. track = _convert_animation_track(p_state, track, animation, Transform(), track_i, node_index);
  5711. gltf_animation->get_tracks().insert(node_index, track);
  5712. break;
  5713. }
  5714. }
  5715. }
  5716. }
  5717. }
  5718. if (gltf_animation->get_tracks().size()) {
  5719. p_state->animations.push_back(gltf_animation);
  5720. }
  5721. }
  5722. void GLTFDocument::_bind_methods() {
  5723. ClassDB::bind_method(D_METHOD("register_gltf_document_extension", "extension", "first_priority"), &GLTFDocument::_register_gltf_document_extension, DEFVAL(false));
  5724. ClassDB::bind_method(D_METHOD("unregister_gltf_document_extension", "extension"), &GLTFDocument::_unregister_gltf_document_extension);
  5725. ClassDB::bind_method(D_METHOD("unregister_all_gltf_document_extensions"), &GLTFDocument::_unregister_all_gltf_document_extensions);
  5726. }
  5727. // Since Godot 3.x does not have static methods, we'll use instance methods to call the static methods.
  5728. void GLTFDocument::_register_gltf_document_extension(Ref<GLTFDocumentExtension> p_extension, bool p_first_priority) {
  5729. GLTFDocument::register_gltf_document_extension(p_extension, p_first_priority);
  5730. }
  5731. void GLTFDocument::_unregister_gltf_document_extension(Ref<GLTFDocumentExtension> p_extension) {
  5732. GLTFDocument::unregister_gltf_document_extension(p_extension);
  5733. }
  5734. void GLTFDocument::_unregister_all_gltf_document_extensions() {
  5735. GLTFDocument::unregister_all_gltf_document_extensions();
  5736. }
  5737. Vector<Ref<GLTFDocumentExtension>> GLTFDocument::all_document_extensions;
  5738. void GLTFDocument::register_gltf_document_extension(Ref<GLTFDocumentExtension> p_extension, bool p_first_priority) {
  5739. if (all_document_extensions.find(p_extension) == -1) {
  5740. if (p_first_priority) {
  5741. all_document_extensions.insert(0, p_extension);
  5742. } else {
  5743. all_document_extensions.push_back(p_extension);
  5744. }
  5745. }
  5746. }
  5747. void GLTFDocument::unregister_gltf_document_extension(Ref<GLTFDocumentExtension> p_extension) {
  5748. all_document_extensions.erase(p_extension);
  5749. }
  5750. void GLTFDocument::unregister_all_gltf_document_extensions() {
  5751. all_document_extensions.clear();
  5752. }
  5753. void GLTFDocument::extension_generate_scene(Ref<GLTFState> p_state) {
  5754. ERR_FAIL_COND(p_state.is_null());
  5755. ERR_FAIL_INDEX(0, p_state->root_nodes.size());
  5756. Error err = OK;
  5757. for (int ext_i = 0; ext_i < document_extensions.size(); ext_i++) {
  5758. Ref<GLTFDocumentExtension> ext = document_extensions[ext_i];
  5759. ERR_CONTINUE(ext.is_null());
  5760. err = ext->import_post_parse(p_state);
  5761. ERR_FAIL_COND(err != OK);
  5762. }
  5763. GLTFNodeIndex gltf_root = p_state->root_nodes.write[0];
  5764. Node *gltf_root_node = p_state->get_scene_node(gltf_root);
  5765. Node *root = gltf_root_node->get_parent();
  5766. ERR_FAIL_NULL(root);
  5767. for (int node_i = 0; node_i < p_state->scene_nodes.size(); node_i++) {
  5768. Node *node = p_state->scene_nodes[node_i];
  5769. ERR_CONTINUE(!node);
  5770. for (int ext_i = 0; ext_i < document_extensions.size(); ext_i++) {
  5771. Ref<GLTFDocumentExtension> ext = document_extensions[ext_i];
  5772. ERR_CONTINUE(ext.is_null());
  5773. ERR_CONTINUE(!p_state->json.has("nodes"));
  5774. Array nodes = p_state->json["nodes"];
  5775. ERR_CONTINUE(node_i >= nodes.size());
  5776. ERR_CONTINUE(node_i < 0);
  5777. Dictionary node_json = nodes[node_i];
  5778. Ref<GLTFNode> gltf_node = p_state->nodes[node_i];
  5779. err = ext->import_node(p_state, gltf_node, node_json, node);
  5780. ERR_CONTINUE(err != OK);
  5781. }
  5782. }
  5783. for (int ext_i = 0; ext_i < document_extensions.size(); ext_i++) {
  5784. Ref<GLTFDocumentExtension> ext = document_extensions[ext_i];
  5785. ERR_CONTINUE(ext.is_null());
  5786. err = ext->import_post(p_state, root);
  5787. ERR_CONTINUE(err != OK);
  5788. }
  5789. }
  5790. Error GLTFDocument::parse(Ref<GLTFState> p_state, String p_path, bool p_read_binary) {
  5791. Error err;
  5792. FileAccessRef file = FileAccess::open(p_path, FileAccess::READ, &err);
  5793. if (!file) {
  5794. return err;
  5795. }
  5796. uint32_t magic = file->get_32();
  5797. if (magic == 0x46546C67) {
  5798. //binary file
  5799. //text file
  5800. err = _parse_glb(p_path, p_state);
  5801. if (err) {
  5802. return FAILED;
  5803. }
  5804. } else {
  5805. //text file
  5806. err = _parse_json(p_path, p_state);
  5807. if (err) {
  5808. return FAILED;
  5809. }
  5810. }
  5811. file->close();
  5812. // get file's name, use for scene name if none
  5813. p_state->filename = p_path.get_file().get_slice(".", 0);
  5814. ERR_FAIL_COND_V(!p_state->json.has("asset"), Error::FAILED);
  5815. Dictionary asset = p_state->json["asset"];
  5816. ERR_FAIL_COND_V(!asset.has("version"), Error::FAILED);
  5817. String version = asset["version"];
  5818. p_state->major_version = version.get_slice(".", 0).to_int();
  5819. p_state->minor_version = version.get_slice(".", 1).to_int();
  5820. document_extensions.clear();
  5821. for (int ext_i = 0; ext_i < all_document_extensions.size(); ext_i++) {
  5822. Ref<GLTFDocumentExtension> ext = all_document_extensions[ext_i];
  5823. ERR_CONTINUE(ext.is_null());
  5824. err = ext->import_preflight(p_state, p_state->json["extensionsUsed"]);
  5825. if (err == OK) {
  5826. document_extensions.push_back(ext);
  5827. }
  5828. }
  5829. /* PARSE EXTENSIONS */
  5830. err = _parse_gltf_extensions(p_state);
  5831. if (err != OK) {
  5832. return Error::FAILED;
  5833. }
  5834. /* PARSE SCENE */
  5835. err = _parse_scenes(p_state);
  5836. if (err != OK) {
  5837. return Error::FAILED;
  5838. }
  5839. /* PARSE NODES */
  5840. err = _parse_nodes(p_state);
  5841. if (err != OK) {
  5842. return Error::FAILED;
  5843. }
  5844. /* PARSE BUFFERS */
  5845. err = _parse_buffers(p_state, p_path.get_base_dir());
  5846. if (err != OK) {
  5847. return Error::FAILED;
  5848. }
  5849. /* PARSE BUFFER VIEWS */
  5850. err = _parse_buffer_views(p_state);
  5851. if (err != OK) {
  5852. return Error::FAILED;
  5853. }
  5854. /* PARSE ACCESSORS */
  5855. err = _parse_accessors(p_state);
  5856. if (err != OK) {
  5857. return Error::FAILED;
  5858. }
  5859. /* PARSE IMAGES */
  5860. err = _parse_images(p_state, p_path.get_base_dir());
  5861. if (err != OK) {
  5862. return Error::FAILED;
  5863. }
  5864. /* PARSE TEXTURE SAMPLERS */
  5865. err = _parse_texture_samplers(p_state);
  5866. if (err != OK) {
  5867. return Error::FAILED;
  5868. }
  5869. /* PARSE TEXTURES */
  5870. err = _parse_textures(p_state);
  5871. if (err != OK) {
  5872. return Error::FAILED;
  5873. }
  5874. /* PARSE MATERIALS */
  5875. err = _parse_materials(p_state);
  5876. if (err != OK) {
  5877. return Error::FAILED;
  5878. }
  5879. /* PARSE SKINS */
  5880. err = _parse_skins(p_state);
  5881. if (err != OK) {
  5882. return Error::FAILED;
  5883. }
  5884. /* DETERMINE SKELETONS */
  5885. err = _determine_skeletons(p_state);
  5886. if (err != OK) {
  5887. return Error::FAILED;
  5888. }
  5889. /* CREATE SKELETONS */
  5890. err = _create_skeletons(p_state);
  5891. if (err != OK) {
  5892. return Error::FAILED;
  5893. }
  5894. /* CREATE SKINS */
  5895. err = _create_skins(p_state);
  5896. if (err != OK) {
  5897. return Error::FAILED;
  5898. }
  5899. /* PARSE MESHES (we have enough info now) */
  5900. err = _parse_meshes(p_state);
  5901. if (err != OK) {
  5902. return Error::FAILED;
  5903. }
  5904. /* PARSE LIGHTS */
  5905. err = _parse_lights(p_state);
  5906. if (err != OK) {
  5907. return Error::FAILED;
  5908. }
  5909. /* PARSE CAMERAS */
  5910. err = _parse_cameras(p_state);
  5911. if (err != OK) {
  5912. return Error::FAILED;
  5913. }
  5914. /* PARSE ANIMATIONS */
  5915. err = _parse_animations(p_state);
  5916. if (err != OK) {
  5917. return Error::FAILED;
  5918. }
  5919. /* ASSIGN SCENE NAMES */
  5920. _assign_scene_names(p_state);
  5921. return OK;
  5922. }
  5923. Dictionary _serialize_texture_transform_uv(Vector2 p_offset, Vector2 p_scale) {
  5924. Dictionary texture_transform;
  5925. bool is_offset = p_offset != Vector2(0.0, 0.0);
  5926. if (is_offset) {
  5927. Array offset;
  5928. offset.resize(2);
  5929. offset[0] = p_offset.x;
  5930. offset[1] = p_offset.y;
  5931. texture_transform["offset"] = offset;
  5932. }
  5933. bool is_scaled = p_scale != Vector2(1.0, 1.0);
  5934. if (is_scaled) {
  5935. Array scale;
  5936. scale.resize(2);
  5937. scale[0] = p_scale.x;
  5938. scale[1] = p_scale.y;
  5939. texture_transform["scale"] = scale;
  5940. }
  5941. Dictionary extension;
  5942. // Note: Godot doesn't support texture rotation.
  5943. if (is_offset || is_scaled) {
  5944. extension["KHR_texture_transform"] = texture_transform;
  5945. }
  5946. return extension;
  5947. }
  5948. Dictionary GLTFDocument::_serialize_texture_transform_uv1(Ref<Material3D> p_material) {
  5949. if (p_material.is_valid()) {
  5950. Vector3 offset = p_material->get_uv1_offset();
  5951. Vector3 scale = p_material->get_uv1_scale();
  5952. return _serialize_texture_transform_uv(Vector2(offset.x, offset.y), Vector2(scale.x, scale.y));
  5953. }
  5954. return Dictionary();
  5955. }
  5956. Dictionary GLTFDocument::_serialize_texture_transform_uv2(Ref<Material3D> p_material) {
  5957. if (p_material.is_valid()) {
  5958. Vector3 offset = p_material->get_uv2_offset();
  5959. Vector3 scale = p_material->get_uv2_scale();
  5960. return _serialize_texture_transform_uv(Vector2(offset.x, offset.y), Vector2(scale.x, scale.y));
  5961. }
  5962. return Dictionary();
  5963. }
  5964. Error GLTFDocument::_serialize_version(Ref<GLTFState> p_state) {
  5965. const String version = "2.0";
  5966. p_state->major_version = version.get_slice(".", 0).to_int();
  5967. p_state->minor_version = version.get_slice(".", 1).to_int();
  5968. Dictionary asset;
  5969. asset["version"] = version;
  5970. String hash = String(VERSION_HASH);
  5971. asset["generator"] = String(VERSION_FULL_NAME) + String("@") + (hash.empty() ? String("unknown") : hash);
  5972. p_state->json["asset"] = asset;
  5973. ERR_FAIL_COND_V(!asset.has("version"), Error::FAILED);
  5974. ERR_FAIL_COND_V(!p_state->json.has("asset"), Error::FAILED);
  5975. return OK;
  5976. }
  5977. Error GLTFDocument::_serialize_file(Ref<GLTFState> p_state, const String p_path) {
  5978. Error err = FAILED;
  5979. if (p_path.to_lower().ends_with("glb")) {
  5980. err = _encode_buffer_glb(p_state, p_path);
  5981. ERR_FAIL_COND_V(err != OK, err);
  5982. FileAccessRef file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  5983. ERR_FAIL_COND_V(!file, FAILED);
  5984. String json = JSON::print(p_state->json);
  5985. const uint32_t magic = 0x46546C67; // GLTF
  5986. const int32_t header_size = 12;
  5987. const int32_t chunk_header_size = 8;
  5988. CharString cs = json.utf8();
  5989. const uint32_t text_data_length = cs.length();
  5990. const uint32_t text_chunk_length = ((text_data_length + 3) & (~3));
  5991. const uint32_t text_chunk_type = 0x4E4F534A; //JSON
  5992. uint32_t binary_data_length = 0;
  5993. if (p_state->buffers.size()) {
  5994. binary_data_length = p_state->buffers[0].size();
  5995. }
  5996. const uint32_t binary_chunk_length = ((binary_data_length + 3) & (~3));
  5997. const uint32_t binary_chunk_type = 0x004E4942; //BIN
  5998. file->create(FileAccess::ACCESS_RESOURCES);
  5999. file->store_32(magic);
  6000. file->store_32(p_state->major_version); // version
  6001. file->store_32(header_size + chunk_header_size + text_chunk_length + chunk_header_size + binary_chunk_length); // length
  6002. file->store_32(text_chunk_length);
  6003. file->store_32(text_chunk_type);
  6004. file->store_buffer((uint8_t *)&cs[0], cs.length());
  6005. for (uint32_t pad_i = text_data_length; pad_i < text_chunk_length; pad_i++) {
  6006. file->store_8(' ');
  6007. }
  6008. if (binary_chunk_length) {
  6009. file->store_32(binary_chunk_length);
  6010. file->store_32(binary_chunk_type);
  6011. file->store_buffer(p_state->buffers[0].ptr(), binary_data_length);
  6012. }
  6013. for (uint32_t pad_i = binary_data_length; pad_i < binary_chunk_length; pad_i++) {
  6014. file->store_8(0);
  6015. }
  6016. file->close();
  6017. } else {
  6018. err = _encode_buffer_bins(p_state, p_path);
  6019. ERR_FAIL_COND_V(err != OK, err);
  6020. FileAccessRef file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  6021. ERR_FAIL_COND_V(!file, FAILED);
  6022. file->create(FileAccess::ACCESS_RESOURCES);
  6023. String json = JSON::print(p_state->json);
  6024. file->store_string(json);
  6025. file->close();
  6026. }
  6027. return err;
  6028. }
  6029. Error GLTFDocument::_parse_gltf_extensions(Ref<GLTFState> p_state) {
  6030. ERR_FAIL_COND_V(p_state.is_null(), ERR_PARSE_ERROR);
  6031. if (p_state->json.has("extensionsUsed")) {
  6032. Vector<String> ext_array = p_state->json["extensionsUsed"];
  6033. p_state->extensions_used = ext_array;
  6034. }
  6035. if (p_state->json.has("extensionsRequired")) {
  6036. Vector<String> ext_array = p_state->json["extensionsRequired"];
  6037. p_state->extensions_required = ext_array;
  6038. }
  6039. Set<String> supported_extensions;
  6040. supported_extensions.insert("KHR_lights_punctual");
  6041. supported_extensions.insert("KHR_materials_pbrSpecularGlossiness");
  6042. supported_extensions.insert("KHR_texture_transform");
  6043. supported_extensions.insert("KHR_materials_unlit");
  6044. for (int ext_i = 0; ext_i < document_extensions.size(); ext_i++) {
  6045. Ref<GLTFDocumentExtension> ext = document_extensions[ext_i];
  6046. Vector<String> ext_supported_extensions = ext->get_supported_extensions();
  6047. for (int i = 0; i < ext_supported_extensions.size(); ++i) {
  6048. supported_extensions.insert(ext_supported_extensions[i]);
  6049. }
  6050. }
  6051. Error ret = Error::OK;
  6052. for (int i = 0; i < p_state->extensions_required.size(); i++) {
  6053. if (!supported_extensions.has(p_state->extensions_required[i])) {
  6054. ERR_PRINT("GLTF: Can't import file '" + p_state->filename + "', required extension '" + String(p_state->extensions_required[i]) + "' is not supported. Are you missing a GLTFDocumentExtension plugin?");
  6055. ret = ERR_UNAVAILABLE;
  6056. }
  6057. }
  6058. return ret;
  6059. }