gltf_document.cpp 221 KB

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