gltf_document.cpp 331 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659
  1. /**************************************************************************/
  2. /* gltf_document.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "gltf_document.h"
  31. #include "extensions/gltf_document_extension_convert_importer_mesh.h"
  32. #include "extensions/gltf_spec_gloss.h"
  33. #include "gltf_state.h"
  34. #include "skin_tool.h"
  35. #include "core/config/project_settings.h"
  36. #include "core/crypto/crypto_core.h"
  37. #include "core/io/config_file.h"
  38. #include "core/io/dir_access.h"
  39. #include "core/io/file_access.h"
  40. #include "core/io/file_access_memory.h"
  41. #include "core/io/json.h"
  42. #include "core/io/stream_peer.h"
  43. #include "core/object/object_id.h"
  44. #include "core/version.h"
  45. #include "scene/2d/node_2d.h"
  46. #include "scene/3d/bone_attachment_3d.h"
  47. #include "scene/3d/camera_3d.h"
  48. #include "scene/3d/importer_mesh_instance_3d.h"
  49. #include "scene/3d/light_3d.h"
  50. #include "scene/3d/mesh_instance_3d.h"
  51. #include "scene/3d/multimesh_instance_3d.h"
  52. #include "scene/animation/animation_player.h"
  53. #include "scene/resources/3d/skin.h"
  54. #include "scene/resources/image_texture.h"
  55. #include "scene/resources/portable_compressed_texture.h"
  56. #include "scene/resources/surface_tool.h"
  57. #ifdef TOOLS_ENABLED
  58. #include "editor/editor_file_system.h"
  59. #endif
  60. // FIXME: Hardcoded to avoid editor dependency.
  61. #define GLTF_IMPORT_GENERATE_TANGENT_ARRAYS 8
  62. #define GLTF_IMPORT_USE_NAMED_SKIN_BINDS 16
  63. #define GLTF_IMPORT_DISCARD_MESHES_AND_MATERIALS 32
  64. #define GLTF_IMPORT_FORCE_DISABLE_MESH_COMPRESSION 64
  65. #include <stdio.h>
  66. #include <stdlib.h>
  67. #include <cstdint>
  68. constexpr int COMPONENT_COUNT_FOR_ACCESSOR_TYPE[7] = {
  69. 1, 2, 3, 4, 4, 9, 16
  70. };
  71. static void _attach_extras_to_meta(const Dictionary &p_extras, Ref<Resource> p_node) {
  72. if (!p_extras.is_empty()) {
  73. p_node->set_meta("extras", p_extras);
  74. }
  75. }
  76. static void _attach_meta_to_extras(Ref<Resource> p_node, Dictionary &p_json) {
  77. if (p_node->has_meta("extras")) {
  78. Dictionary node_extras = p_node->get_meta("extras");
  79. if (p_json.has("extras")) {
  80. Dictionary extras = p_json["extras"];
  81. extras.merge(node_extras);
  82. } else {
  83. p_json["extras"] = node_extras;
  84. }
  85. }
  86. }
  87. static Ref<ImporterMesh> _mesh_to_importer_mesh(Ref<Mesh> p_mesh) {
  88. Ref<ImporterMesh> importer_mesh;
  89. importer_mesh.instantiate();
  90. if (p_mesh.is_null()) {
  91. return importer_mesh;
  92. }
  93. Ref<ArrayMesh> array_mesh = p_mesh;
  94. if (p_mesh->get_blend_shape_count()) {
  95. ArrayMesh::BlendShapeMode shape_mode = ArrayMesh::BLEND_SHAPE_MODE_NORMALIZED;
  96. if (array_mesh.is_valid()) {
  97. shape_mode = array_mesh->get_blend_shape_mode();
  98. }
  99. importer_mesh->set_blend_shape_mode(shape_mode);
  100. for (int morph_i = 0; morph_i < p_mesh->get_blend_shape_count(); morph_i++) {
  101. importer_mesh->add_blend_shape(p_mesh->get_blend_shape_name(morph_i));
  102. }
  103. }
  104. for (int32_t surface_i = 0; surface_i < p_mesh->get_surface_count(); surface_i++) {
  105. Array array = p_mesh->surface_get_arrays(surface_i);
  106. Ref<Material> mat = p_mesh->surface_get_material(surface_i);
  107. String mat_name;
  108. if (mat.is_valid()) {
  109. mat_name = mat->get_name();
  110. } else {
  111. // Assign default material when no material is assigned.
  112. mat.instantiate();
  113. }
  114. importer_mesh->add_surface(p_mesh->surface_get_primitive_type(surface_i),
  115. array, p_mesh->surface_get_blend_shape_arrays(surface_i), p_mesh->surface_get_lods(surface_i), mat,
  116. mat_name, p_mesh->surface_get_format(surface_i));
  117. }
  118. importer_mesh->merge_meta_from(*p_mesh);
  119. return importer_mesh;
  120. }
  121. Error GLTFDocument::_serialize(Ref<GLTFState> p_state) {
  122. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  123. ERR_CONTINUE(ext.is_null());
  124. Error err = ext->export_preserialize(p_state);
  125. ERR_CONTINUE(err != OK);
  126. }
  127. /* STEP CONVERT MESH INSTANCES */
  128. _convert_mesh_instances(p_state);
  129. /* STEP SERIALIZE CAMERAS */
  130. Error err = _serialize_cameras(p_state);
  131. if (err != OK) {
  132. return Error::FAILED;
  133. }
  134. /* STEP 3 CREATE SKINS */
  135. err = _serialize_skins(p_state);
  136. if (err != OK) {
  137. return Error::FAILED;
  138. }
  139. /* STEP SERIALIZE MESHES (we have enough info now) */
  140. err = _serialize_meshes(p_state);
  141. if (err != OK) {
  142. return Error::FAILED;
  143. }
  144. /* STEP SERIALIZE TEXTURES */
  145. err = _serialize_materials(p_state);
  146. if (err != OK) {
  147. return Error::FAILED;
  148. }
  149. /* STEP SERIALIZE TEXTURE SAMPLERS */
  150. err = _serialize_texture_samplers(p_state);
  151. if (err != OK) {
  152. return Error::FAILED;
  153. }
  154. /* STEP SERIALIZE ANIMATIONS */
  155. err = _serialize_animations(p_state);
  156. if (err != OK) {
  157. return Error::FAILED;
  158. }
  159. /* STEP SERIALIZE ACCESSORS */
  160. err = _encode_accessors(p_state);
  161. if (err != OK) {
  162. return Error::FAILED;
  163. }
  164. /* STEP SERIALIZE IMAGES */
  165. err = _serialize_images(p_state);
  166. if (err != OK) {
  167. return Error::FAILED;
  168. }
  169. /* STEP SERIALIZE TEXTURES */
  170. err = _serialize_textures(p_state);
  171. if (err != OK) {
  172. return Error::FAILED;
  173. }
  174. for (GLTFBufferViewIndex i = 0; i < p_state->buffer_views.size(); i++) {
  175. p_state->buffer_views.write[i]->buffer = 0;
  176. }
  177. /* STEP SERIALIZE BUFFER VIEWS */
  178. err = _encode_buffer_views(p_state);
  179. if (err != OK) {
  180. return Error::FAILED;
  181. }
  182. /* STEP SERIALIZE NODES */
  183. err = _serialize_nodes(p_state);
  184. if (err != OK) {
  185. return Error::FAILED;
  186. }
  187. /* STEP SERIALIZE SCENE */
  188. err = _serialize_scenes(p_state);
  189. if (err != OK) {
  190. return Error::FAILED;
  191. }
  192. /* STEP SERIALIZE LIGHTS */
  193. err = _serialize_lights(p_state);
  194. if (err != OK) {
  195. return Error::FAILED;
  196. }
  197. /* STEP SERIALIZE EXTENSIONS */
  198. err = _serialize_gltf_extensions(p_state);
  199. if (err != OK) {
  200. return Error::FAILED;
  201. }
  202. /* STEP SERIALIZE VERSION */
  203. err = _serialize_asset_header(p_state);
  204. if (err != OK) {
  205. return Error::FAILED;
  206. }
  207. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  208. ERR_CONTINUE(ext.is_null());
  209. err = ext->export_post(p_state);
  210. ERR_FAIL_COND_V(err != OK, err);
  211. }
  212. return OK;
  213. }
  214. Error GLTFDocument::_serialize_gltf_extensions(Ref<GLTFState> p_state) const {
  215. Vector<String> extensions_used = p_state->extensions_used;
  216. Vector<String> extensions_required = p_state->extensions_required;
  217. if (!p_state->lights.is_empty()) {
  218. extensions_used.push_back("KHR_lights_punctual");
  219. }
  220. if (p_state->use_khr_texture_transform) {
  221. extensions_used.push_back("KHR_texture_transform");
  222. extensions_required.push_back("KHR_texture_transform");
  223. }
  224. if (!extensions_used.is_empty()) {
  225. extensions_used.sort();
  226. p_state->json["extensionsUsed"] = extensions_used;
  227. }
  228. if (!extensions_required.is_empty()) {
  229. extensions_required.sort();
  230. p_state->json["extensionsRequired"] = extensions_required;
  231. }
  232. return OK;
  233. }
  234. Error GLTFDocument::_serialize_scenes(Ref<GLTFState> p_state) {
  235. // Godot only supports one scene per glTF file.
  236. Array scenes;
  237. Dictionary scene_dict;
  238. scenes.append(scene_dict);
  239. p_state->json["scenes"] = scenes;
  240. p_state->json["scene"] = 0;
  241. // Add nodes to the scene dict.
  242. if (!p_state->root_nodes.is_empty()) {
  243. scene_dict["nodes"] = p_state->root_nodes;
  244. }
  245. if (!p_state->scene_name.is_empty()) {
  246. scene_dict["name"] = p_state->scene_name;
  247. }
  248. return OK;
  249. }
  250. Error GLTFDocument::_parse_json(const String &p_path, Ref<GLTFState> p_state) {
  251. Error err;
  252. Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::READ, &err);
  253. if (file.is_null()) {
  254. return err;
  255. }
  256. Vector<uint8_t> array;
  257. array.resize(file->get_length());
  258. file->get_buffer(array.ptrw(), array.size());
  259. String text;
  260. text.parse_utf8((const char *)array.ptr(), array.size());
  261. JSON json;
  262. err = json.parse(text);
  263. if (err != OK) {
  264. _err_print_error("", p_path.utf8().get_data(), json.get_error_line(), json.get_error_message().utf8().get_data(), false, ERR_HANDLER_SCRIPT);
  265. return err;
  266. }
  267. p_state->json = json.get_data();
  268. return OK;
  269. }
  270. Error GLTFDocument::_parse_glb(Ref<FileAccess> p_file, Ref<GLTFState> p_state) {
  271. ERR_FAIL_COND_V(p_file.is_null(), ERR_INVALID_PARAMETER);
  272. ERR_FAIL_COND_V(p_state.is_null(), ERR_INVALID_PARAMETER);
  273. ERR_FAIL_COND_V(p_file->get_position() != 0, ERR_FILE_CANT_READ);
  274. uint32_t magic = p_file->get_32();
  275. ERR_FAIL_COND_V(magic != 0x46546C67, ERR_FILE_UNRECOGNIZED); //glTF
  276. p_file->get_32(); // version
  277. p_file->get_32(); // length
  278. uint32_t chunk_length = p_file->get_32();
  279. uint32_t chunk_type = p_file->get_32();
  280. ERR_FAIL_COND_V(chunk_type != 0x4E4F534A, ERR_PARSE_ERROR); //JSON
  281. Vector<uint8_t> json_data;
  282. json_data.resize(chunk_length);
  283. uint32_t len = p_file->get_buffer(json_data.ptrw(), chunk_length);
  284. ERR_FAIL_COND_V(len != chunk_length, ERR_FILE_CORRUPT);
  285. String text;
  286. text.parse_utf8((const char *)json_data.ptr(), json_data.size());
  287. JSON json;
  288. Error err = json.parse(text);
  289. if (err != OK) {
  290. _err_print_error("", "", json.get_error_line(), json.get_error_message().utf8().get_data(), false, ERR_HANDLER_SCRIPT);
  291. return err;
  292. }
  293. p_state->json = json.get_data();
  294. //data?
  295. chunk_length = p_file->get_32();
  296. chunk_type = p_file->get_32();
  297. if (p_file->eof_reached()) {
  298. return OK; //all good
  299. }
  300. ERR_FAIL_COND_V(chunk_type != 0x004E4942, ERR_PARSE_ERROR); //BIN
  301. p_state->glb_data.resize(chunk_length);
  302. len = p_file->get_buffer(p_state->glb_data.ptrw(), chunk_length);
  303. ERR_FAIL_COND_V(len != chunk_length, ERR_FILE_CORRUPT);
  304. return OK;
  305. }
  306. static Array _vec3_to_arr(const Vector3 &p_vec3) {
  307. Array array;
  308. array.resize(3);
  309. array[0] = p_vec3.x;
  310. array[1] = p_vec3.y;
  311. array[2] = p_vec3.z;
  312. return array;
  313. }
  314. static Vector3 _arr_to_vec3(const Array &p_array) {
  315. ERR_FAIL_COND_V(p_array.size() != 3, Vector3());
  316. return Vector3(p_array[0], p_array[1], p_array[2]);
  317. }
  318. static Array _quaternion_to_array(const Quaternion &p_quaternion) {
  319. Array array;
  320. array.resize(4);
  321. array[0] = p_quaternion.x;
  322. array[1] = p_quaternion.y;
  323. array[2] = p_quaternion.z;
  324. array[3] = p_quaternion.w;
  325. return array;
  326. }
  327. static Quaternion _arr_to_quaternion(const Array &p_array) {
  328. ERR_FAIL_COND_V(p_array.size() != 4, Quaternion());
  329. return Quaternion(p_array[0], p_array[1], p_array[2], p_array[3]);
  330. }
  331. static Transform3D _arr_to_xform(const Array &p_array) {
  332. ERR_FAIL_COND_V(p_array.size() != 16, Transform3D());
  333. Transform3D xform;
  334. xform.basis.set_column(Vector3::AXIS_X, Vector3(p_array[0], p_array[1], p_array[2]));
  335. xform.basis.set_column(Vector3::AXIS_Y, Vector3(p_array[4], p_array[5], p_array[6]));
  336. xform.basis.set_column(Vector3::AXIS_Z, Vector3(p_array[8], p_array[9], p_array[10]));
  337. xform.set_origin(Vector3(p_array[12], p_array[13], p_array[14]));
  338. return xform;
  339. }
  340. static Vector<real_t> _xform_to_array(const Transform3D p_transform) {
  341. Vector<real_t> array;
  342. array.resize(16);
  343. Vector3 axis_x = p_transform.get_basis().get_column(Vector3::AXIS_X);
  344. array.write[0] = axis_x.x;
  345. array.write[1] = axis_x.y;
  346. array.write[2] = axis_x.z;
  347. array.write[3] = 0.0f;
  348. Vector3 axis_y = p_transform.get_basis().get_column(Vector3::AXIS_Y);
  349. array.write[4] = axis_y.x;
  350. array.write[5] = axis_y.y;
  351. array.write[6] = axis_y.z;
  352. array.write[7] = 0.0f;
  353. Vector3 axis_z = p_transform.get_basis().get_column(Vector3::AXIS_Z);
  354. array.write[8] = axis_z.x;
  355. array.write[9] = axis_z.y;
  356. array.write[10] = axis_z.z;
  357. array.write[11] = 0.0f;
  358. Vector3 origin = p_transform.get_origin();
  359. array.write[12] = origin.x;
  360. array.write[13] = origin.y;
  361. array.write[14] = origin.z;
  362. array.write[15] = 1.0f;
  363. return array;
  364. }
  365. Error GLTFDocument::_serialize_nodes(Ref<GLTFState> p_state) {
  366. Array nodes;
  367. for (int i = 0; i < p_state->nodes.size(); i++) {
  368. Dictionary node;
  369. Ref<GLTFNode> gltf_node = p_state->nodes[i];
  370. Dictionary extensions;
  371. node["extensions"] = extensions;
  372. if (!gltf_node->get_name().is_empty()) {
  373. node["name"] = gltf_node->get_name();
  374. }
  375. if (gltf_node->camera != -1) {
  376. node["camera"] = gltf_node->camera;
  377. }
  378. if (gltf_node->light != -1) {
  379. Dictionary lights_punctual;
  380. extensions["KHR_lights_punctual"] = lights_punctual;
  381. lights_punctual["light"] = gltf_node->light;
  382. }
  383. if (gltf_node->mesh != -1) {
  384. node["mesh"] = gltf_node->mesh;
  385. }
  386. if (gltf_node->skin != -1) {
  387. node["skin"] = gltf_node->skin;
  388. }
  389. if (gltf_node->skeleton != -1 && gltf_node->skin < 0) {
  390. }
  391. if (gltf_node->transform.basis.is_orthogonal()) {
  392. // An orthogonal transform is decomposable into TRS, so prefer that.
  393. const Vector3 position = gltf_node->get_position();
  394. if (!position.is_zero_approx()) {
  395. node["translation"] = _vec3_to_arr(position);
  396. }
  397. const Quaternion rotation = gltf_node->get_rotation();
  398. if (!rotation.is_equal_approx(Quaternion())) {
  399. node["rotation"] = _quaternion_to_array(rotation);
  400. }
  401. const Vector3 scale = gltf_node->get_scale();
  402. if (!scale.is_equal_approx(Vector3(1.0f, 1.0f, 1.0f))) {
  403. node["scale"] = _vec3_to_arr(scale);
  404. }
  405. } else {
  406. node["matrix"] = _xform_to_array(gltf_node->transform);
  407. }
  408. if (gltf_node->children.size()) {
  409. Array children;
  410. for (int j = 0; j < gltf_node->children.size(); j++) {
  411. children.push_back(gltf_node->children[j]);
  412. }
  413. node["children"] = children;
  414. }
  415. Node *scene_node = nullptr;
  416. if (i < (int)p_state->scene_nodes.size()) {
  417. scene_node = p_state->scene_nodes[i];
  418. }
  419. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  420. ERR_CONTINUE(ext.is_null());
  421. Error err = ext->export_node(p_state, gltf_node, node, scene_node);
  422. ERR_CONTINUE(err != OK);
  423. }
  424. if (extensions.is_empty()) {
  425. node.erase("extensions");
  426. }
  427. _attach_meta_to_extras(gltf_node, node);
  428. nodes.push_back(node);
  429. }
  430. if (!nodes.is_empty()) {
  431. p_state->json["nodes"] = nodes;
  432. }
  433. return OK;
  434. }
  435. String GLTFDocument::_gen_unique_name(Ref<GLTFState> p_state, const String &p_name) {
  436. return _gen_unique_name_static(p_state->unique_names, p_name);
  437. }
  438. String GLTFDocument::_sanitize_animation_name(const String &p_name) {
  439. String anim_name = p_name.validate_node_name();
  440. return AnimationLibrary::validate_library_name(anim_name);
  441. }
  442. String GLTFDocument::_gen_unique_animation_name(Ref<GLTFState> p_state, const String &p_name) {
  443. const String s_name = _sanitize_animation_name(p_name);
  444. String u_name;
  445. int index = 1;
  446. while (true) {
  447. u_name = s_name;
  448. if (index > 1) {
  449. u_name += itos(index);
  450. }
  451. if (!p_state->unique_animation_names.has(u_name)) {
  452. break;
  453. }
  454. index++;
  455. }
  456. p_state->unique_animation_names.insert(u_name);
  457. return u_name;
  458. }
  459. String GLTFDocument::_sanitize_bone_name(const String &p_name) {
  460. String bone_name = p_name;
  461. bone_name = bone_name.replace(":", "_");
  462. bone_name = bone_name.replace("/", "_");
  463. return bone_name;
  464. }
  465. String GLTFDocument::_gen_unique_bone_name(Ref<GLTFState> p_state, const GLTFSkeletonIndex p_skel_i, const String &p_name) {
  466. String s_name = _sanitize_bone_name(p_name);
  467. if (s_name.is_empty()) {
  468. s_name = "bone";
  469. }
  470. String u_name;
  471. int index = 1;
  472. while (true) {
  473. u_name = s_name;
  474. if (index > 1) {
  475. u_name += "_" + itos(index);
  476. }
  477. if (!p_state->skeletons[p_skel_i]->unique_names.has(u_name)) {
  478. break;
  479. }
  480. index++;
  481. }
  482. p_state->skeletons.write[p_skel_i]->unique_names.insert(u_name);
  483. return u_name;
  484. }
  485. Error GLTFDocument::_parse_scenes(Ref<GLTFState> p_state) {
  486. p_state->unique_names.insert("Skeleton3D"); // Reserve skeleton name.
  487. ERR_FAIL_COND_V(!p_state->json.has("scenes"), ERR_FILE_CORRUPT);
  488. const Array &scenes = p_state->json["scenes"];
  489. int loaded_scene = 0;
  490. if (p_state->json.has("scene")) {
  491. loaded_scene = p_state->json["scene"];
  492. } else {
  493. WARN_PRINT("The load-time scene is not defined in the glTF2 file. Picking the first scene.");
  494. }
  495. if (scenes.size()) {
  496. ERR_FAIL_COND_V(loaded_scene >= scenes.size(), ERR_FILE_CORRUPT);
  497. const Dictionary &scene_dict = scenes[loaded_scene];
  498. ERR_FAIL_COND_V(!scene_dict.has("nodes"), ERR_UNAVAILABLE);
  499. const Array &nodes = scene_dict["nodes"];
  500. for (int j = 0; j < nodes.size(); j++) {
  501. p_state->root_nodes.push_back(nodes[j]);
  502. }
  503. // Determine what to use for the scene name.
  504. if (scene_dict.has("name") && !String(scene_dict["name"]).is_empty() && !((String)scene_dict["name"]).begins_with("Scene")) {
  505. p_state->scene_name = scene_dict["name"];
  506. } else if (p_state->scene_name.is_empty()) {
  507. p_state->scene_name = p_state->filename;
  508. }
  509. if (_naming_version == 0) {
  510. p_state->scene_name = _gen_unique_name(p_state, p_state->scene_name);
  511. }
  512. }
  513. return OK;
  514. }
  515. Error GLTFDocument::_parse_nodes(Ref<GLTFState> p_state) {
  516. ERR_FAIL_COND_V(!p_state->json.has("nodes"), ERR_FILE_CORRUPT);
  517. const Array &nodes = p_state->json["nodes"];
  518. for (int i = 0; i < nodes.size(); i++) {
  519. Ref<GLTFNode> node;
  520. node.instantiate();
  521. const Dictionary &n = nodes[i];
  522. if (n.has("name")) {
  523. node->set_original_name(n["name"]);
  524. node->set_name(n["name"]);
  525. }
  526. if (n.has("camera")) {
  527. node->camera = n["camera"];
  528. }
  529. if (n.has("mesh")) {
  530. node->mesh = n["mesh"];
  531. }
  532. if (n.has("skin")) {
  533. node->skin = n["skin"];
  534. }
  535. if (n.has("matrix")) {
  536. node->transform = _arr_to_xform(n["matrix"]);
  537. } else {
  538. if (n.has("translation")) {
  539. node->set_position(_arr_to_vec3(n["translation"]));
  540. }
  541. if (n.has("rotation")) {
  542. node->set_rotation(_arr_to_quaternion(n["rotation"]));
  543. }
  544. if (n.has("scale")) {
  545. node->set_scale(_arr_to_vec3(n["scale"]));
  546. }
  547. }
  548. node->set_additional_data("GODOT_rest_transform", node->transform);
  549. if (n.has("extensions")) {
  550. Dictionary extensions = n["extensions"];
  551. if (extensions.has("KHR_lights_punctual")) {
  552. Dictionary lights_punctual = extensions["KHR_lights_punctual"];
  553. if (lights_punctual.has("light")) {
  554. GLTFLightIndex light = lights_punctual["light"];
  555. node->light = light;
  556. }
  557. }
  558. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  559. ERR_CONTINUE(ext.is_null());
  560. Error err = ext->parse_node_extensions(p_state, node, extensions);
  561. ERR_CONTINUE_MSG(err != OK, "glTF: Encountered error " + itos(err) + " when parsing node extensions for node " + node->get_name() + " in file " + p_state->filename + ". Continuing.");
  562. }
  563. }
  564. if (n.has("extras")) {
  565. _attach_extras_to_meta(n["extras"], node);
  566. }
  567. if (n.has("children")) {
  568. const Array &children = n["children"];
  569. for (int j = 0; j < children.size(); j++) {
  570. node->children.push_back(children[j]);
  571. }
  572. }
  573. p_state->nodes.push_back(node);
  574. }
  575. // build the hierarchy
  576. for (GLTFNodeIndex node_i = 0; node_i < p_state->nodes.size(); node_i++) {
  577. for (int j = 0; j < p_state->nodes[node_i]->children.size(); j++) {
  578. GLTFNodeIndex child_i = p_state->nodes[node_i]->children[j];
  579. ERR_FAIL_INDEX_V(child_i, p_state->nodes.size(), ERR_FILE_CORRUPT);
  580. ERR_CONTINUE(p_state->nodes[child_i]->parent != -1); //node already has a parent, wtf.
  581. p_state->nodes.write[child_i]->parent = node_i;
  582. }
  583. }
  584. _compute_node_heights(p_state);
  585. return OK;
  586. }
  587. void GLTFDocument::_compute_node_heights(Ref<GLTFState> p_state) {
  588. p_state->root_nodes.clear();
  589. for (GLTFNodeIndex node_i = 0; node_i < p_state->nodes.size(); ++node_i) {
  590. Ref<GLTFNode> node = p_state->nodes[node_i];
  591. node->height = 0;
  592. GLTFNodeIndex current_i = node_i;
  593. while (current_i >= 0) {
  594. const GLTFNodeIndex parent_i = p_state->nodes[current_i]->parent;
  595. if (parent_i >= 0) {
  596. ++node->height;
  597. }
  598. current_i = parent_i;
  599. }
  600. if (node->height == 0) {
  601. p_state->root_nodes.push_back(node_i);
  602. }
  603. }
  604. }
  605. static Vector<uint8_t> _parse_base64_uri(const String &p_uri) {
  606. int start = p_uri.find_char(',');
  607. ERR_FAIL_COND_V(start == -1, Vector<uint8_t>());
  608. CharString substr = p_uri.substr(start + 1).ascii();
  609. int strlen = substr.length();
  610. Vector<uint8_t> buf;
  611. buf.resize(strlen / 4 * 3 + 1 + 1);
  612. size_t len = 0;
  613. ERR_FAIL_COND_V(CryptoCore::b64_decode(buf.ptrw(), buf.size(), &len, (unsigned char *)substr.get_data(), strlen) != OK, Vector<uint8_t>());
  614. buf.resize(len);
  615. return buf;
  616. }
  617. Error GLTFDocument::_encode_buffer_glb(Ref<GLTFState> p_state, const String &p_path) {
  618. print_verbose("glTF: Total buffers: " + itos(p_state->buffers.size()));
  619. if (p_state->buffers.is_empty()) {
  620. return OK;
  621. }
  622. Array buffers;
  623. if (!p_state->buffers.is_empty()) {
  624. Vector<uint8_t> buffer_data = p_state->buffers[0];
  625. Dictionary gltf_buffer;
  626. gltf_buffer["byteLength"] = buffer_data.size();
  627. buffers.push_back(gltf_buffer);
  628. }
  629. for (GLTFBufferIndex i = 1; i < p_state->buffers.size() - 1; i++) {
  630. Vector<uint8_t> buffer_data = p_state->buffers[i];
  631. Dictionary gltf_buffer;
  632. String filename = p_path.get_basename().get_file() + itos(i) + ".bin";
  633. String path = p_path.get_base_dir() + "/" + filename;
  634. Error err;
  635. Ref<FileAccess> file = FileAccess::open(path, FileAccess::WRITE, &err);
  636. if (file.is_null()) {
  637. return err;
  638. }
  639. if (buffer_data.size() == 0) {
  640. return OK;
  641. }
  642. file->create(FileAccess::ACCESS_RESOURCES);
  643. file->store_buffer(buffer_data.ptr(), buffer_data.size());
  644. gltf_buffer["uri"] = filename;
  645. gltf_buffer["byteLength"] = buffer_data.size();
  646. buffers.push_back(gltf_buffer);
  647. }
  648. p_state->json["buffers"] = buffers;
  649. return OK;
  650. }
  651. Error GLTFDocument::_encode_buffer_bins(Ref<GLTFState> p_state, const String &p_path) {
  652. print_verbose("glTF: Total buffers: " + itos(p_state->buffers.size()));
  653. if (p_state->buffers.is_empty()) {
  654. return OK;
  655. }
  656. Array buffers;
  657. for (GLTFBufferIndex i = 0; i < p_state->buffers.size(); i++) {
  658. Vector<uint8_t> buffer_data = p_state->buffers[i];
  659. Dictionary gltf_buffer;
  660. String filename = p_path.get_basename().get_file() + itos(i) + ".bin";
  661. String path = p_path.get_base_dir() + "/" + filename;
  662. Error err;
  663. Ref<FileAccess> file = FileAccess::open(path, FileAccess::WRITE, &err);
  664. if (file.is_null()) {
  665. return err;
  666. }
  667. if (buffer_data.size() == 0) {
  668. return OK;
  669. }
  670. file->create(FileAccess::ACCESS_RESOURCES);
  671. file->store_buffer(buffer_data.ptr(), buffer_data.size());
  672. gltf_buffer["uri"] = filename;
  673. gltf_buffer["byteLength"] = buffer_data.size();
  674. buffers.push_back(gltf_buffer);
  675. }
  676. p_state->json["buffers"] = buffers;
  677. return OK;
  678. }
  679. Error GLTFDocument::_parse_buffers(Ref<GLTFState> p_state, const String &p_base_path) {
  680. if (!p_state->json.has("buffers")) {
  681. return OK;
  682. }
  683. const Array &buffers = p_state->json["buffers"];
  684. for (GLTFBufferIndex i = 0; i < buffers.size(); i++) {
  685. if (i == 0 && p_state->glb_data.size()) {
  686. p_state->buffers.push_back(p_state->glb_data);
  687. } else {
  688. const Dictionary &buffer = buffers[i];
  689. if (buffer.has("uri")) {
  690. Vector<uint8_t> buffer_data;
  691. String uri = buffer["uri"];
  692. if (uri.begins_with("data:")) { // Embedded data using base64.
  693. // Validate data MIME types and throw an error if it's one we don't know/support.
  694. if (!uri.begins_with("data:application/octet-stream;base64") &&
  695. !uri.begins_with("data:application/gltf-buffer;base64")) {
  696. ERR_PRINT("glTF: Got buffer with an unknown URI data type: " + uri);
  697. }
  698. buffer_data = _parse_base64_uri(uri);
  699. } else { // Relative path to an external image file.
  700. ERR_FAIL_COND_V(p_base_path.is_empty(), ERR_INVALID_PARAMETER);
  701. uri = uri.uri_decode();
  702. uri = p_base_path.path_join(uri).replace("\\", "/"); // Fix for Windows.
  703. ERR_FAIL_COND_V_MSG(!FileAccess::exists(uri), ERR_FILE_NOT_FOUND, "glTF: Binary file not found: " + uri);
  704. buffer_data = FileAccess::get_file_as_bytes(uri);
  705. ERR_FAIL_COND_V_MSG(buffer_data.is_empty(), ERR_PARSE_ERROR, "glTF: Couldn't load binary file as an array: " + uri);
  706. }
  707. ERR_FAIL_COND_V(!buffer.has("byteLength"), ERR_PARSE_ERROR);
  708. int byteLength = buffer["byteLength"];
  709. ERR_FAIL_COND_V(byteLength < buffer_data.size(), ERR_PARSE_ERROR);
  710. p_state->buffers.push_back(buffer_data);
  711. }
  712. }
  713. }
  714. print_verbose("glTF: Total buffers: " + itos(p_state->buffers.size()));
  715. return OK;
  716. }
  717. Error GLTFDocument::_encode_buffer_views(Ref<GLTFState> p_state) {
  718. Array buffers;
  719. for (GLTFBufferViewIndex i = 0; i < p_state->buffer_views.size(); i++) {
  720. Dictionary d;
  721. Ref<GLTFBufferView> buffer_view = p_state->buffer_views[i];
  722. d["buffer"] = buffer_view->buffer;
  723. d["byteLength"] = buffer_view->byte_length;
  724. d["byteOffset"] = buffer_view->byte_offset;
  725. if (buffer_view->byte_stride != -1) {
  726. d["byteStride"] = buffer_view->byte_stride;
  727. }
  728. if (buffer_view->indices) {
  729. d["target"] = GLTFDocument::ELEMENT_ARRAY_BUFFER;
  730. } else if (buffer_view->vertex_attributes) {
  731. d["target"] = GLTFDocument::ARRAY_BUFFER;
  732. }
  733. ERR_FAIL_COND_V(!d.has("buffer"), ERR_INVALID_DATA);
  734. ERR_FAIL_COND_V(!d.has("byteLength"), ERR_INVALID_DATA);
  735. buffers.push_back(d);
  736. }
  737. print_verbose("glTF: Total buffer views: " + itos(p_state->buffer_views.size()));
  738. if (!buffers.size()) {
  739. return OK;
  740. }
  741. p_state->json["bufferViews"] = buffers;
  742. return OK;
  743. }
  744. Error GLTFDocument::_parse_buffer_views(Ref<GLTFState> p_state) {
  745. if (!p_state->json.has("bufferViews")) {
  746. return OK;
  747. }
  748. const Array &buffers = p_state->json["bufferViews"];
  749. for (GLTFBufferViewIndex i = 0; i < buffers.size(); i++) {
  750. const Dictionary &d = buffers[i];
  751. Ref<GLTFBufferView> buffer_view;
  752. buffer_view.instantiate();
  753. ERR_FAIL_COND_V(!d.has("buffer"), ERR_PARSE_ERROR);
  754. buffer_view->buffer = d["buffer"];
  755. ERR_FAIL_COND_V(!d.has("byteLength"), ERR_PARSE_ERROR);
  756. buffer_view->byte_length = d["byteLength"];
  757. if (d.has("byteOffset")) {
  758. buffer_view->byte_offset = d["byteOffset"];
  759. }
  760. if (d.has("byteStride")) {
  761. buffer_view->byte_stride = d["byteStride"];
  762. }
  763. if (d.has("target")) {
  764. const int target = d["target"];
  765. buffer_view->indices = target == GLTFDocument::ELEMENT_ARRAY_BUFFER;
  766. buffer_view->vertex_attributes = target == GLTFDocument::ARRAY_BUFFER;
  767. }
  768. p_state->buffer_views.push_back(buffer_view);
  769. }
  770. print_verbose("glTF: Total buffer views: " + itos(p_state->buffer_views.size()));
  771. return OK;
  772. }
  773. Error GLTFDocument::_encode_accessors(Ref<GLTFState> p_state) {
  774. Array accessors;
  775. for (GLTFAccessorIndex i = 0; i < p_state->accessors.size(); i++) {
  776. Dictionary d;
  777. Ref<GLTFAccessor> accessor = p_state->accessors[i];
  778. d["componentType"] = accessor->component_type;
  779. d["count"] = accessor->count;
  780. d["type"] = _get_accessor_type_name(accessor->accessor_type);
  781. d["normalized"] = accessor->normalized;
  782. d["max"] = accessor->max;
  783. d["min"] = accessor->min;
  784. if (accessor->buffer_view != -1) {
  785. // bufferView may be omitted to zero-initialize the buffer. When this happens, byteOffset MUST also be omitted.
  786. d["byteOffset"] = accessor->byte_offset;
  787. d["bufferView"] = accessor->buffer_view;
  788. }
  789. if (accessor->sparse_count > 0) {
  790. Dictionary s;
  791. s["count"] = accessor->sparse_count;
  792. Dictionary si;
  793. si["bufferView"] = accessor->sparse_indices_buffer_view;
  794. si["componentType"] = accessor->sparse_indices_component_type;
  795. if (accessor->sparse_indices_byte_offset != -1) {
  796. si["byteOffset"] = accessor->sparse_indices_byte_offset;
  797. }
  798. ERR_FAIL_COND_V(!si.has("bufferView") || !si.has("componentType"), ERR_PARSE_ERROR);
  799. s["indices"] = si;
  800. Dictionary sv;
  801. sv["bufferView"] = accessor->sparse_values_buffer_view;
  802. if (accessor->sparse_values_byte_offset != -1) {
  803. sv["byteOffset"] = accessor->sparse_values_byte_offset;
  804. }
  805. ERR_FAIL_COND_V(!sv.has("bufferView"), ERR_PARSE_ERROR);
  806. s["values"] = sv;
  807. ERR_FAIL_COND_V(!s.has("count") || !s.has("indices") || !s.has("values"), ERR_PARSE_ERROR);
  808. d["sparse"] = s;
  809. }
  810. accessors.push_back(d);
  811. }
  812. if (!accessors.size()) {
  813. return OK;
  814. }
  815. p_state->json["accessors"] = accessors;
  816. ERR_FAIL_COND_V(!p_state->json.has("accessors"), ERR_FILE_CORRUPT);
  817. print_verbose("glTF: Total accessors: " + itos(p_state->accessors.size()));
  818. return OK;
  819. }
  820. String GLTFDocument::_get_accessor_type_name(const GLTFAccessor::GLTFAccessorType p_accessor_type) {
  821. if (p_accessor_type == GLTFAccessor::TYPE_SCALAR) {
  822. return "SCALAR";
  823. }
  824. if (p_accessor_type == GLTFAccessor::TYPE_VEC2) {
  825. return "VEC2";
  826. }
  827. if (p_accessor_type == GLTFAccessor::TYPE_VEC3) {
  828. return "VEC3";
  829. }
  830. if (p_accessor_type == GLTFAccessor::TYPE_VEC4) {
  831. return "VEC4";
  832. }
  833. if (p_accessor_type == GLTFAccessor::TYPE_MAT2) {
  834. return "MAT2";
  835. }
  836. if (p_accessor_type == GLTFAccessor::TYPE_MAT3) {
  837. return "MAT3";
  838. }
  839. if (p_accessor_type == GLTFAccessor::TYPE_MAT4) {
  840. return "MAT4";
  841. }
  842. ERR_FAIL_V("SCALAR");
  843. }
  844. GLTFAccessor::GLTFAccessorType GLTFDocument::_get_accessor_type_from_str(const String &p_string) {
  845. if (p_string == "SCALAR") {
  846. return GLTFAccessor::TYPE_SCALAR;
  847. }
  848. if (p_string == "VEC2") {
  849. return GLTFAccessor::TYPE_VEC2;
  850. }
  851. if (p_string == "VEC3") {
  852. return GLTFAccessor::TYPE_VEC3;
  853. }
  854. if (p_string == "VEC4") {
  855. return GLTFAccessor::TYPE_VEC4;
  856. }
  857. if (p_string == "MAT2") {
  858. return GLTFAccessor::TYPE_MAT2;
  859. }
  860. if (p_string == "MAT3") {
  861. return GLTFAccessor::TYPE_MAT3;
  862. }
  863. if (p_string == "MAT4") {
  864. return GLTFAccessor::TYPE_MAT4;
  865. }
  866. ERR_FAIL_V(GLTFAccessor::TYPE_SCALAR);
  867. }
  868. Error GLTFDocument::_parse_accessors(Ref<GLTFState> p_state) {
  869. if (!p_state->json.has("accessors")) {
  870. return OK;
  871. }
  872. const Array &accessors = p_state->json["accessors"];
  873. for (GLTFAccessorIndex i = 0; i < accessors.size(); i++) {
  874. const Dictionary &d = accessors[i];
  875. Ref<GLTFAccessor> accessor;
  876. accessor.instantiate();
  877. ERR_FAIL_COND_V(!d.has("componentType"), ERR_PARSE_ERROR);
  878. accessor->component_type = (GLTFAccessor::GLTFComponentType)(int32_t)d["componentType"];
  879. ERR_FAIL_COND_V(!d.has("count"), ERR_PARSE_ERROR);
  880. accessor->count = d["count"];
  881. ERR_FAIL_COND_V(!d.has("type"), ERR_PARSE_ERROR);
  882. accessor->accessor_type = _get_accessor_type_from_str(d["type"]);
  883. if (d.has("bufferView")) {
  884. accessor->buffer_view = d["bufferView"]; //optional because it may be sparse...
  885. }
  886. if (d.has("byteOffset")) {
  887. accessor->byte_offset = d["byteOffset"];
  888. }
  889. if (d.has("normalized")) {
  890. accessor->normalized = d["normalized"];
  891. }
  892. if (d.has("max")) {
  893. accessor->max = d["max"];
  894. }
  895. if (d.has("min")) {
  896. accessor->min = d["min"];
  897. }
  898. if (d.has("sparse")) {
  899. const Dictionary &s = d["sparse"];
  900. ERR_FAIL_COND_V(!s.has("count"), ERR_PARSE_ERROR);
  901. accessor->sparse_count = s["count"];
  902. ERR_FAIL_COND_V(!s.has("indices"), ERR_PARSE_ERROR);
  903. const Dictionary &si = s["indices"];
  904. ERR_FAIL_COND_V(!si.has("bufferView"), ERR_PARSE_ERROR);
  905. accessor->sparse_indices_buffer_view = si["bufferView"];
  906. ERR_FAIL_COND_V(!si.has("componentType"), ERR_PARSE_ERROR);
  907. accessor->sparse_indices_component_type = (GLTFAccessor::GLTFComponentType)(int32_t)si["componentType"];
  908. if (si.has("byteOffset")) {
  909. accessor->sparse_indices_byte_offset = si["byteOffset"];
  910. }
  911. ERR_FAIL_COND_V(!s.has("values"), ERR_PARSE_ERROR);
  912. const Dictionary &sv = s["values"];
  913. ERR_FAIL_COND_V(!sv.has("bufferView"), ERR_PARSE_ERROR);
  914. accessor->sparse_values_buffer_view = sv["bufferView"];
  915. if (sv.has("byteOffset")) {
  916. accessor->sparse_values_byte_offset = sv["byteOffset"];
  917. }
  918. }
  919. p_state->accessors.push_back(accessor);
  920. }
  921. print_verbose("glTF: Total accessors: " + itos(p_state->accessors.size()));
  922. return OK;
  923. }
  924. double GLTFDocument::_filter_number(double p_float) {
  925. if (!Math::is_finite(p_float)) {
  926. // 3.6.2.2. "Values of NaN, +Infinity, and -Infinity MUST NOT be present."
  927. return 0.0f;
  928. }
  929. return (double)(float)p_float;
  930. }
  931. String GLTFDocument::_get_component_type_name(const GLTFAccessor::GLTFComponentType p_component) {
  932. switch (p_component) {
  933. case GLTFAccessor::COMPONENT_TYPE_NONE:
  934. return "None";
  935. case GLTFAccessor::COMPONENT_TYPE_SIGNED_BYTE:
  936. return "Byte";
  937. case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_BYTE:
  938. return "UByte";
  939. case GLTFAccessor::COMPONENT_TYPE_SIGNED_SHORT:
  940. return "Short";
  941. case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_SHORT:
  942. return "UShort";
  943. case GLTFAccessor::COMPONENT_TYPE_SIGNED_INT:
  944. return "Int";
  945. case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_INT:
  946. return "UInt";
  947. case GLTFAccessor::COMPONENT_TYPE_SINGLE_FLOAT:
  948. return "Float";
  949. case GLTFAccessor::COMPONENT_TYPE_DOUBLE_FLOAT:
  950. return "Double";
  951. case GLTFAccessor::COMPONENT_TYPE_HALF_FLOAT:
  952. return "Half";
  953. case GLTFAccessor::COMPONENT_TYPE_SIGNED_LONG:
  954. return "Long";
  955. case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_LONG:
  956. return "ULong";
  957. }
  958. return "<Error>";
  959. }
  960. Error GLTFDocument::_encode_buffer_view(Ref<GLTFState> p_state, const double *p_src, const int p_count, const GLTFAccessor::GLTFAccessorType p_accessor_type, const GLTFAccessor::GLTFComponentType p_component_type, const bool p_normalized, const int p_byte_offset, const bool p_for_vertex, GLTFBufferViewIndex &r_accessor, const bool p_for_vertex_indices) {
  961. const int component_count = COMPONENT_COUNT_FOR_ACCESSOR_TYPE[p_accessor_type];
  962. const int component_size = _get_component_type_size(p_component_type);
  963. ERR_FAIL_COND_V(component_size == 0, FAILED);
  964. int skip_every = 0;
  965. int skip_bytes = 0;
  966. //special case of alignments, as described in spec
  967. switch (p_component_type) {
  968. case GLTFAccessor::COMPONENT_TYPE_SIGNED_BYTE:
  969. case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_BYTE: {
  970. if (p_accessor_type == GLTFAccessor::TYPE_MAT2) {
  971. skip_every = 2;
  972. skip_bytes = 2;
  973. }
  974. if (p_accessor_type == GLTFAccessor::TYPE_MAT3) {
  975. skip_every = 3;
  976. skip_bytes = 1;
  977. }
  978. } break;
  979. case GLTFAccessor::COMPONENT_TYPE_SIGNED_SHORT:
  980. case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_SHORT: {
  981. if (p_accessor_type == GLTFAccessor::TYPE_MAT3) {
  982. skip_every = 6;
  983. skip_bytes = 4;
  984. }
  985. } break;
  986. default: {
  987. }
  988. }
  989. Ref<GLTFBufferView> bv;
  990. bv.instantiate();
  991. const uint32_t offset = bv->byte_offset = p_byte_offset;
  992. Vector<uint8_t> &gltf_buffer = p_state->buffers.write[0];
  993. int stride = component_count * component_size;
  994. if (p_for_vertex && stride % 4) {
  995. stride += 4 - (stride % 4); //according to spec must be multiple of 4
  996. }
  997. //use to debug
  998. print_verbose("glTF: encoding accessor type " + _get_accessor_type_name(p_accessor_type) + " component type: " + _get_component_type_name(p_component_type) + " stride: " + itos(stride) + " amount " + itos(p_count));
  999. print_verbose("glTF: encoding accessor offset " + itos(p_byte_offset) + " view offset: " + itos(bv->byte_offset) + " total buffer len: " + itos(gltf_buffer.size()) + " view len " + itos(bv->byte_length));
  1000. const int buffer_end = (stride * (p_count - 1)) + component_size;
  1001. // TODO define bv->byte_stride
  1002. bv->byte_offset = gltf_buffer.size();
  1003. if (p_for_vertex_indices) {
  1004. bv->indices = true;
  1005. } else if (p_for_vertex) {
  1006. bv->vertex_attributes = true;
  1007. bv->byte_stride = stride;
  1008. }
  1009. switch (p_component_type) {
  1010. case GLTFAccessor::COMPONENT_TYPE_NONE: {
  1011. ERR_FAIL_V_MSG(ERR_INVALID_DATA, "glTF: Failed to encode buffer view, component type not set.");
  1012. }
  1013. case GLTFAccessor::COMPONENT_TYPE_SIGNED_BYTE: {
  1014. Vector<int8_t> buffer;
  1015. buffer.resize(p_count * component_count);
  1016. int32_t dst_i = 0;
  1017. for (int i = 0; i < p_count; i++) {
  1018. for (int j = 0; j < component_count; j++) {
  1019. if (skip_every && j > 0 && (j % skip_every) == 0) {
  1020. dst_i += skip_bytes;
  1021. }
  1022. double d = *p_src;
  1023. if (p_normalized) {
  1024. buffer.write[dst_i] = d * 128.0;
  1025. } else {
  1026. buffer.write[dst_i] = d;
  1027. }
  1028. p_src++;
  1029. dst_i++;
  1030. }
  1031. }
  1032. int64_t old_size = gltf_buffer.size();
  1033. gltf_buffer.resize(old_size + (buffer.size() * sizeof(int8_t)));
  1034. memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(int8_t));
  1035. bv->byte_length = buffer.size() * sizeof(int8_t);
  1036. } break;
  1037. case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_BYTE: {
  1038. Vector<uint8_t> buffer;
  1039. buffer.resize(p_count * component_count);
  1040. int32_t dst_i = 0;
  1041. for (int i = 0; i < p_count; i++) {
  1042. for (int j = 0; j < component_count; j++) {
  1043. if (skip_every && j > 0 && (j % skip_every) == 0) {
  1044. dst_i += skip_bytes;
  1045. }
  1046. double d = *p_src;
  1047. if (p_normalized) {
  1048. buffer.write[dst_i] = d * 255.0;
  1049. } else {
  1050. buffer.write[dst_i] = d;
  1051. }
  1052. p_src++;
  1053. dst_i++;
  1054. }
  1055. }
  1056. gltf_buffer.append_array(buffer);
  1057. bv->byte_length = buffer.size() * sizeof(uint8_t);
  1058. } break;
  1059. case GLTFAccessor::COMPONENT_TYPE_SIGNED_SHORT: {
  1060. Vector<int16_t> buffer;
  1061. buffer.resize(p_count * component_count);
  1062. int32_t dst_i = 0;
  1063. for (int i = 0; i < p_count; i++) {
  1064. for (int j = 0; j < component_count; j++) {
  1065. if (skip_every && j > 0 && (j % skip_every) == 0) {
  1066. dst_i += skip_bytes;
  1067. }
  1068. double d = *p_src;
  1069. if (p_normalized) {
  1070. buffer.write[dst_i] = d * 32768.0;
  1071. } else {
  1072. buffer.write[dst_i] = d;
  1073. }
  1074. p_src++;
  1075. dst_i++;
  1076. }
  1077. }
  1078. int64_t old_size = gltf_buffer.size();
  1079. gltf_buffer.resize(old_size + (buffer.size() * sizeof(int16_t)));
  1080. memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(int16_t));
  1081. bv->byte_length = buffer.size() * sizeof(int16_t);
  1082. } break;
  1083. case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_SHORT: {
  1084. Vector<uint16_t> buffer;
  1085. buffer.resize(p_count * component_count);
  1086. int32_t dst_i = 0;
  1087. for (int i = 0; i < p_count; i++) {
  1088. for (int j = 0; j < component_count; j++) {
  1089. if (skip_every && j > 0 && (j % skip_every) == 0) {
  1090. dst_i += skip_bytes;
  1091. }
  1092. double d = *p_src;
  1093. if (p_normalized) {
  1094. buffer.write[dst_i] = d * 65535.0;
  1095. } else {
  1096. buffer.write[dst_i] = d;
  1097. }
  1098. p_src++;
  1099. dst_i++;
  1100. }
  1101. }
  1102. int64_t old_size = gltf_buffer.size();
  1103. gltf_buffer.resize(old_size + (buffer.size() * sizeof(uint16_t)));
  1104. memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(uint16_t));
  1105. bv->byte_length = buffer.size() * sizeof(uint16_t);
  1106. } break;
  1107. case GLTFAccessor::COMPONENT_TYPE_SIGNED_INT: {
  1108. Vector<int32_t> buffer;
  1109. buffer.resize(p_count * component_count);
  1110. int32_t dst_i = 0;
  1111. for (int i = 0; i < p_count; i++) {
  1112. for (int j = 0; j < component_count; j++) {
  1113. if (skip_every && j > 0 && (j % skip_every) == 0) {
  1114. dst_i += skip_bytes;
  1115. }
  1116. double d = *p_src;
  1117. buffer.write[dst_i] = d;
  1118. p_src++;
  1119. dst_i++;
  1120. }
  1121. }
  1122. int64_t old_size = gltf_buffer.size();
  1123. gltf_buffer.resize(old_size + (buffer.size() * sizeof(uint32_t)));
  1124. memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(uint32_t));
  1125. bv->byte_length = buffer.size() * sizeof(uint32_t);
  1126. } break;
  1127. case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_INT: {
  1128. Vector<uint32_t> buffer;
  1129. buffer.resize(p_count * component_count);
  1130. int32_t dst_i = 0;
  1131. for (int i = 0; i < p_count; i++) {
  1132. for (int j = 0; j < component_count; j++) {
  1133. if (skip_every && j > 0 && (j % skip_every) == 0) {
  1134. dst_i += skip_bytes;
  1135. }
  1136. double d = *p_src;
  1137. buffer.write[dst_i] = d;
  1138. p_src++;
  1139. dst_i++;
  1140. }
  1141. }
  1142. int64_t old_size = gltf_buffer.size();
  1143. gltf_buffer.resize(old_size + (buffer.size() * sizeof(uint32_t)));
  1144. memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(uint32_t));
  1145. bv->byte_length = buffer.size() * sizeof(uint32_t);
  1146. } break;
  1147. case GLTFAccessor::COMPONENT_TYPE_SINGLE_FLOAT: {
  1148. Vector<float> buffer;
  1149. buffer.resize(p_count * component_count);
  1150. int32_t dst_i = 0;
  1151. for (int i = 0; i < p_count; i++) {
  1152. for (int j = 0; j < component_count; j++) {
  1153. if (skip_every && j > 0 && (j % skip_every) == 0) {
  1154. dst_i += skip_bytes;
  1155. }
  1156. double d = *p_src;
  1157. buffer.write[dst_i] = d;
  1158. p_src++;
  1159. dst_i++;
  1160. }
  1161. }
  1162. int64_t old_size = gltf_buffer.size();
  1163. gltf_buffer.resize(old_size + (buffer.size() * sizeof(float)));
  1164. memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(float));
  1165. bv->byte_length = buffer.size() * sizeof(float);
  1166. } break;
  1167. case GLTFAccessor::COMPONENT_TYPE_DOUBLE_FLOAT: {
  1168. Vector<double> buffer;
  1169. buffer.resize(p_count * component_count);
  1170. int32_t dst_i = 0;
  1171. for (int i = 0; i < p_count; i++) {
  1172. for (int j = 0; j < component_count; j++) {
  1173. if (skip_every && j > 0 && (j % skip_every) == 0) {
  1174. dst_i += skip_bytes;
  1175. }
  1176. double d = *p_src;
  1177. buffer.write[dst_i] = d;
  1178. p_src++;
  1179. dst_i++;
  1180. }
  1181. }
  1182. int64_t old_size = gltf_buffer.size();
  1183. gltf_buffer.resize(old_size + (buffer.size() * sizeof(double)));
  1184. memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(double));
  1185. bv->byte_length = buffer.size() * sizeof(double);
  1186. } break;
  1187. case GLTFAccessor::COMPONENT_TYPE_HALF_FLOAT: {
  1188. ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "glTF: Half float not supported yet.");
  1189. } break;
  1190. case GLTFAccessor::COMPONENT_TYPE_SIGNED_LONG: {
  1191. Vector<int64_t> buffer;
  1192. buffer.resize(p_count * component_count);
  1193. int32_t dst_i = 0;
  1194. for (int i = 0; i < p_count; i++) {
  1195. for (int j = 0; j < component_count; j++) {
  1196. if (skip_every && j > 0 && (j % skip_every) == 0) {
  1197. dst_i += skip_bytes;
  1198. }
  1199. // FIXME: This can result in precision loss because int64_t can store some values that double can't.
  1200. double d = *p_src;
  1201. buffer.write[dst_i] = d;
  1202. p_src++;
  1203. dst_i++;
  1204. }
  1205. }
  1206. int64_t old_size = gltf_buffer.size();
  1207. gltf_buffer.resize(old_size + (buffer.size() * sizeof(int64_t)));
  1208. memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(int64_t));
  1209. bv->byte_length = buffer.size() * sizeof(int64_t);
  1210. } break;
  1211. case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_LONG: {
  1212. Vector<uint64_t> buffer;
  1213. buffer.resize(p_count * component_count);
  1214. int32_t dst_i = 0;
  1215. for (int i = 0; i < p_count; i++) {
  1216. for (int j = 0; j < component_count; j++) {
  1217. if (skip_every && j > 0 && (j % skip_every) == 0) {
  1218. dst_i += skip_bytes;
  1219. }
  1220. // FIXME: This can result in precision loss because int64_t can store some values that double can't.
  1221. double d = *p_src;
  1222. buffer.write[dst_i] = d;
  1223. p_src++;
  1224. dst_i++;
  1225. }
  1226. }
  1227. int64_t old_size = gltf_buffer.size();
  1228. gltf_buffer.resize(old_size + (buffer.size() * sizeof(uint64_t)));
  1229. memcpy(gltf_buffer.ptrw() + old_size, buffer.ptrw(), buffer.size() * sizeof(uint64_t));
  1230. bv->byte_length = buffer.size() * sizeof(uint64_t);
  1231. } break;
  1232. }
  1233. ERR_FAIL_COND_V(buffer_end > bv->byte_length, ERR_INVALID_DATA);
  1234. ERR_FAIL_COND_V((int)(offset + buffer_end) > gltf_buffer.size(), ERR_INVALID_DATA);
  1235. int pad_bytes = (4 - gltf_buffer.size()) & 3;
  1236. for (int i = 0; i < pad_bytes; i++) {
  1237. gltf_buffer.push_back(0);
  1238. }
  1239. r_accessor = bv->buffer = p_state->buffer_views.size();
  1240. p_state->buffer_views.push_back(bv);
  1241. return OK;
  1242. }
  1243. Error GLTFDocument::_decode_buffer_view(Ref<GLTFState> p_state, double *p_dst, const GLTFBufferViewIndex p_buffer_view, const int p_skip_every, const int p_skip_bytes, const int p_element_size, const int p_count, const GLTFAccessor::GLTFAccessorType p_accessor_type, const int p_component_count, const GLTFAccessor::GLTFComponentType p_component_type, const int p_component_size, const bool p_normalized, const int p_byte_offset, const bool p_for_vertex) {
  1244. const Ref<GLTFBufferView> bv = p_state->buffer_views[p_buffer_view];
  1245. int stride = p_element_size;
  1246. if (bv->byte_stride != -1) {
  1247. stride = bv->byte_stride;
  1248. }
  1249. if (p_for_vertex && stride % 4) {
  1250. stride += 4 - (stride % 4); //according to spec must be multiple of 4
  1251. }
  1252. ERR_FAIL_INDEX_V(bv->buffer, p_state->buffers.size(), ERR_PARSE_ERROR);
  1253. const uint32_t offset = bv->byte_offset + p_byte_offset;
  1254. Vector<uint8_t> buffer = p_state->buffers[bv->buffer]; //copy on write, so no performance hit
  1255. const uint8_t *bufptr = buffer.ptr();
  1256. //use to debug
  1257. print_verbose("glTF: accessor type " + _get_accessor_type_name(p_accessor_type) + " component type: " + _get_component_type_name(p_component_type) + " stride: " + itos(stride) + " amount " + itos(p_count));
  1258. print_verbose("glTF: accessor offset " + itos(p_byte_offset) + " view offset: " + itos(bv->byte_offset) + " total buffer len: " + itos(buffer.size()) + " view len " + itos(bv->byte_length));
  1259. const int buffer_end = (stride * (p_count - 1)) + p_element_size;
  1260. ERR_FAIL_COND_V(buffer_end > bv->byte_length, ERR_PARSE_ERROR);
  1261. ERR_FAIL_COND_V((int)(offset + buffer_end) > buffer.size(), ERR_PARSE_ERROR);
  1262. //fill everything as doubles
  1263. for (int i = 0; i < p_count; i++) {
  1264. const uint8_t *src = &bufptr[offset + i * stride];
  1265. for (int j = 0; j < p_component_count; j++) {
  1266. if (p_skip_every && j > 0 && (j % p_skip_every) == 0) {
  1267. src += p_skip_bytes;
  1268. }
  1269. double d = 0;
  1270. switch (p_component_type) {
  1271. case GLTFAccessor::COMPONENT_TYPE_NONE: {
  1272. ERR_FAIL_V_MSG(ERR_INVALID_DATA, "glTF: Failed to decode buffer view, component type not set.");
  1273. } break;
  1274. case GLTFAccessor::COMPONENT_TYPE_SIGNED_BYTE: {
  1275. int8_t b = int8_t(*src);
  1276. if (p_normalized) {
  1277. d = (double(b) / 128.0);
  1278. } else {
  1279. d = double(b);
  1280. }
  1281. } break;
  1282. case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_BYTE: {
  1283. uint8_t b = *src;
  1284. if (p_normalized) {
  1285. d = (double(b) / 255.0);
  1286. } else {
  1287. d = double(b);
  1288. }
  1289. } break;
  1290. case GLTFAccessor::COMPONENT_TYPE_SIGNED_SHORT: {
  1291. int16_t s = *(int16_t *)src;
  1292. if (p_normalized) {
  1293. d = (double(s) / 32768.0);
  1294. } else {
  1295. d = double(s);
  1296. }
  1297. } break;
  1298. case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_SHORT: {
  1299. uint16_t s = *(uint16_t *)src;
  1300. if (p_normalized) {
  1301. d = (double(s) / 65535.0);
  1302. } else {
  1303. d = double(s);
  1304. }
  1305. } break;
  1306. case GLTFAccessor::COMPONENT_TYPE_SIGNED_INT: {
  1307. d = *(int32_t *)src;
  1308. } break;
  1309. case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_INT: {
  1310. d = *(uint32_t *)src;
  1311. } break;
  1312. case GLTFAccessor::COMPONENT_TYPE_SINGLE_FLOAT: {
  1313. d = *(float *)src;
  1314. } break;
  1315. case GLTFAccessor::COMPONENT_TYPE_DOUBLE_FLOAT: {
  1316. d = *(double *)src;
  1317. } break;
  1318. case GLTFAccessor::COMPONENT_TYPE_HALF_FLOAT: {
  1319. ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "glTF: Half float not supported yet.");
  1320. } break;
  1321. case GLTFAccessor::COMPONENT_TYPE_SIGNED_LONG: {
  1322. d = *(int64_t *)src;
  1323. } break;
  1324. case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_LONG: {
  1325. d = *(uint64_t *)src;
  1326. } break;
  1327. }
  1328. *p_dst++ = d;
  1329. src += p_component_size;
  1330. }
  1331. }
  1332. return OK;
  1333. }
  1334. int GLTFDocument::_get_component_type_size(const GLTFAccessor::GLTFComponentType p_component_type) {
  1335. switch (p_component_type) {
  1336. case GLTFAccessor::COMPONENT_TYPE_NONE:
  1337. ERR_FAIL_V(0);
  1338. case GLTFAccessor::COMPONENT_TYPE_SIGNED_BYTE:
  1339. case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_BYTE:
  1340. return 1;
  1341. case GLTFAccessor::COMPONENT_TYPE_SIGNED_SHORT:
  1342. case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_SHORT:
  1343. case GLTFAccessor::COMPONENT_TYPE_HALF_FLOAT:
  1344. return 2;
  1345. case GLTFAccessor::COMPONENT_TYPE_SIGNED_INT:
  1346. case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_INT:
  1347. case GLTFAccessor::COMPONENT_TYPE_SINGLE_FLOAT:
  1348. return 4;
  1349. case GLTFAccessor::COMPONENT_TYPE_DOUBLE_FLOAT:
  1350. case GLTFAccessor::COMPONENT_TYPE_SIGNED_LONG:
  1351. case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_LONG:
  1352. return 8;
  1353. }
  1354. ERR_FAIL_V(0);
  1355. }
  1356. Vector<double> GLTFDocument::_decode_accessor(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  1357. //spec, for reference:
  1358. //https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#data-alignment
  1359. ERR_FAIL_INDEX_V(p_accessor, p_state->accessors.size(), Vector<double>());
  1360. const Ref<GLTFAccessor> a = p_state->accessors[p_accessor];
  1361. const int component_count = COMPONENT_COUNT_FOR_ACCESSOR_TYPE[a->accessor_type];
  1362. const int component_size = _get_component_type_size(a->component_type);
  1363. ERR_FAIL_COND_V(component_size == 0, Vector<double>());
  1364. int element_size = component_count * component_size;
  1365. int skip_every = 0;
  1366. int skip_bytes = 0;
  1367. //special case of alignments, as described in spec
  1368. switch (a->component_type) {
  1369. case GLTFAccessor::COMPONENT_TYPE_SIGNED_BYTE:
  1370. case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_BYTE: {
  1371. if (a->accessor_type == GLTFAccessor::TYPE_MAT2) {
  1372. skip_every = 2;
  1373. skip_bytes = 2;
  1374. element_size = 8; //override for this case
  1375. }
  1376. if (a->accessor_type == GLTFAccessor::TYPE_MAT3) {
  1377. skip_every = 3;
  1378. skip_bytes = 1;
  1379. element_size = 12; //override for this case
  1380. }
  1381. } break;
  1382. case GLTFAccessor::COMPONENT_TYPE_SIGNED_SHORT:
  1383. case GLTFAccessor::COMPONENT_TYPE_UNSIGNED_SHORT: {
  1384. if (a->accessor_type == GLTFAccessor::TYPE_MAT3) {
  1385. skip_every = 6;
  1386. skip_bytes = 4;
  1387. element_size = 16; //override for this case
  1388. }
  1389. } break;
  1390. default: {
  1391. }
  1392. }
  1393. Vector<double> dst_buffer;
  1394. dst_buffer.resize(component_count * a->count);
  1395. double *dst = dst_buffer.ptrw();
  1396. if (a->buffer_view >= 0) {
  1397. ERR_FAIL_INDEX_V(a->buffer_view, p_state->buffer_views.size(), Vector<double>());
  1398. const Error err = _decode_buffer_view(p_state, dst, a->buffer_view, skip_every, skip_bytes, element_size, a->count, a->accessor_type, component_count, a->component_type, component_size, a->normalized, a->byte_offset, p_for_vertex);
  1399. if (err != OK) {
  1400. return Vector<double>();
  1401. }
  1402. } else {
  1403. //fill with zeros, as bufferview is not defined.
  1404. for (int i = 0; i < (a->count * component_count); i++) {
  1405. dst_buffer.write[i] = 0;
  1406. }
  1407. }
  1408. if (a->sparse_count > 0) {
  1409. // I could not find any file using this, so this code is so far untested
  1410. Vector<double> indices;
  1411. indices.resize(a->sparse_count);
  1412. const int indices_component_size = _get_component_type_size(a->sparse_indices_component_type);
  1413. Error err = _decode_buffer_view(p_state, indices.ptrw(), a->sparse_indices_buffer_view, 0, 0, indices_component_size, a->sparse_count, GLTFAccessor::TYPE_SCALAR, 1, a->sparse_indices_component_type, indices_component_size, false, a->sparse_indices_byte_offset, false);
  1414. if (err != OK) {
  1415. return Vector<double>();
  1416. }
  1417. Vector<double> data;
  1418. data.resize(component_count * a->sparse_count);
  1419. err = _decode_buffer_view(p_state, data.ptrw(), a->sparse_values_buffer_view, skip_every, skip_bytes, element_size, a->sparse_count, a->accessor_type, component_count, a->component_type, component_size, a->normalized, a->sparse_values_byte_offset, p_for_vertex);
  1420. if (err != OK) {
  1421. return Vector<double>();
  1422. }
  1423. for (int i = 0; i < indices.size(); i++) {
  1424. const int write_offset = int(indices[i]) * component_count;
  1425. for (int j = 0; j < component_count; j++) {
  1426. dst[write_offset + j] = data[i * component_count + j];
  1427. }
  1428. }
  1429. }
  1430. return dst_buffer;
  1431. }
  1432. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_ints(Ref<GLTFState> p_state, const Vector<int32_t> p_attribs, const bool p_for_vertex, const bool p_for_vertex_indices) {
  1433. if (p_attribs.size() == 0) {
  1434. return -1;
  1435. }
  1436. const int element_count = 1;
  1437. const int ret_size = p_attribs.size();
  1438. Vector<double> attribs;
  1439. attribs.resize(ret_size);
  1440. Vector<double> type_max;
  1441. type_max.resize(element_count);
  1442. Vector<double> type_min;
  1443. type_min.resize(element_count);
  1444. int max_index = 0;
  1445. for (int i = 0; i < p_attribs.size(); i++) {
  1446. attribs.write[i] = p_attribs[i];
  1447. if (p_attribs[i] > max_index) {
  1448. max_index = p_attribs[i];
  1449. }
  1450. if (i == 0) {
  1451. for (int32_t type_i = 0; type_i < element_count; type_i++) {
  1452. type_max.write[type_i] = attribs[(i * element_count) + type_i];
  1453. type_min.write[type_i] = attribs[(i * element_count) + type_i];
  1454. }
  1455. }
  1456. for (int32_t type_i = 0; type_i < element_count; type_i++) {
  1457. type_max.write[type_i] = MAX(attribs[(i * element_count) + type_i], type_max[type_i]);
  1458. type_min.write[type_i] = MIN(attribs[(i * element_count) + type_i], type_min[type_i]);
  1459. }
  1460. }
  1461. ERR_FAIL_COND_V(attribs.is_empty(), -1);
  1462. Ref<GLTFAccessor> accessor;
  1463. accessor.instantiate();
  1464. GLTFBufferIndex buffer_view_i;
  1465. if (p_state->buffers.is_empty()) {
  1466. p_state->buffers.push_back(Vector<uint8_t>());
  1467. }
  1468. int64_t size = p_state->buffers[0].size();
  1469. const GLTFAccessor::GLTFAccessorType accessor_type = GLTFAccessor::TYPE_SCALAR;
  1470. GLTFAccessor::GLTFComponentType component_type;
  1471. if (max_index > 65535 || p_for_vertex) {
  1472. component_type = GLTFAccessor::COMPONENT_TYPE_UNSIGNED_INT;
  1473. } else {
  1474. component_type = GLTFAccessor::COMPONENT_TYPE_UNSIGNED_SHORT;
  1475. }
  1476. accessor->max = type_max;
  1477. accessor->min = type_min;
  1478. accessor->normalized = false;
  1479. accessor->count = ret_size;
  1480. accessor->accessor_type = accessor_type;
  1481. accessor->component_type = component_type;
  1482. accessor->byte_offset = 0;
  1483. Error err = _encode_buffer_view(p_state, attribs.ptr(), attribs.size(), accessor_type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i, p_for_vertex_indices);
  1484. if (err != OK) {
  1485. return -1;
  1486. }
  1487. accessor->buffer_view = buffer_view_i;
  1488. p_state->accessors.push_back(accessor);
  1489. return p_state->accessors.size() - 1;
  1490. }
  1491. Vector<int> GLTFDocument::_decode_accessor_as_ints(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex, const Vector<int> &p_packed_vertex_ids) {
  1492. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  1493. Vector<int> ret;
  1494. if (attribs.size() == 0) {
  1495. return ret;
  1496. }
  1497. const double *attribs_ptr = attribs.ptr();
  1498. int ret_size = attribs.size();
  1499. if (!p_packed_vertex_ids.is_empty()) {
  1500. ERR_FAIL_COND_V(p_packed_vertex_ids[p_packed_vertex_ids.size() - 1] >= ret_size, ret);
  1501. ret_size = p_packed_vertex_ids.size();
  1502. }
  1503. ret.resize(ret_size);
  1504. for (int i = 0; i < ret_size; i++) {
  1505. int src_i = i;
  1506. if (!p_packed_vertex_ids.is_empty()) {
  1507. src_i = p_packed_vertex_ids[i];
  1508. }
  1509. ret.write[i] = int(attribs_ptr[src_i]);
  1510. }
  1511. return ret;
  1512. }
  1513. Vector<float> GLTFDocument::_decode_accessor_as_floats(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex, const Vector<int> &p_packed_vertex_ids) {
  1514. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  1515. Vector<float> ret;
  1516. if (attribs.size() == 0) {
  1517. return ret;
  1518. }
  1519. const double *attribs_ptr = attribs.ptr();
  1520. int ret_size = attribs.size();
  1521. if (!p_packed_vertex_ids.is_empty()) {
  1522. ERR_FAIL_COND_V(p_packed_vertex_ids[p_packed_vertex_ids.size() - 1] >= ret_size, ret);
  1523. ret_size = p_packed_vertex_ids.size();
  1524. }
  1525. ret.resize(ret_size);
  1526. for (int i = 0; i < ret_size; i++) {
  1527. int src_i = i;
  1528. if (!p_packed_vertex_ids.is_empty()) {
  1529. src_i = p_packed_vertex_ids[i];
  1530. }
  1531. ret.write[i] = float(attribs_ptr[src_i]);
  1532. }
  1533. return ret;
  1534. }
  1535. void GLTFDocument::_round_min_max_components(Vector<double> &r_type_min, Vector<double> &r_type_max) {
  1536. // 3.6.2.5: For floating-point components, JSON-stored minimum and maximum values represent single precision
  1537. // floats and SHOULD be rounded to single precision before usage to avoid any potential boundary mismatches.
  1538. for (int32_t type_i = 0; type_i < r_type_min.size(); type_i++) {
  1539. r_type_min.write[type_i] = (double)(float)r_type_min[type_i];
  1540. r_type_max.write[type_i] = (double)(float)r_type_max[type_i];
  1541. }
  1542. }
  1543. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_vec2(Ref<GLTFState> p_state, const Vector<Vector2> p_attribs, const bool p_for_vertex) {
  1544. if (p_attribs.size() == 0) {
  1545. return -1;
  1546. }
  1547. const int element_count = 2;
  1548. const int ret_size = p_attribs.size() * element_count;
  1549. Vector<double> attribs;
  1550. attribs.resize(ret_size);
  1551. Vector<double> type_max;
  1552. type_max.resize(element_count);
  1553. Vector<double> type_min;
  1554. type_min.resize(element_count);
  1555. for (int i = 0; i < p_attribs.size(); i++) {
  1556. Vector2 attrib = p_attribs[i];
  1557. attribs.write[(i * element_count) + 0] = _filter_number(attrib.x);
  1558. attribs.write[(i * element_count) + 1] = _filter_number(attrib.y);
  1559. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1560. }
  1561. _round_min_max_components(type_min, type_max);
  1562. ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
  1563. Ref<GLTFAccessor> accessor;
  1564. accessor.instantiate();
  1565. GLTFBufferIndex buffer_view_i;
  1566. if (p_state->buffers.is_empty()) {
  1567. p_state->buffers.push_back(Vector<uint8_t>());
  1568. }
  1569. int64_t size = p_state->buffers[0].size();
  1570. const GLTFAccessor::GLTFAccessorType accessor_type = GLTFAccessor::TYPE_VEC2;
  1571. const GLTFAccessor::GLTFComponentType component_type = GLTFAccessor::COMPONENT_TYPE_SINGLE_FLOAT;
  1572. accessor->max = type_max;
  1573. accessor->min = type_min;
  1574. accessor->normalized = false;
  1575. accessor->count = p_attribs.size();
  1576. accessor->accessor_type = accessor_type;
  1577. accessor->component_type = component_type;
  1578. accessor->byte_offset = 0;
  1579. Error err = _encode_buffer_view(p_state, attribs.ptr(), p_attribs.size(), accessor_type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1580. if (err != OK) {
  1581. return -1;
  1582. }
  1583. accessor->buffer_view = buffer_view_i;
  1584. p_state->accessors.push_back(accessor);
  1585. return p_state->accessors.size() - 1;
  1586. }
  1587. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_color(Ref<GLTFState> p_state, const Vector<Color> p_attribs, const bool p_for_vertex) {
  1588. if (p_attribs.size() == 0) {
  1589. return -1;
  1590. }
  1591. const int ret_size = p_attribs.size() * 4;
  1592. Vector<double> attribs;
  1593. attribs.resize(ret_size);
  1594. const int element_count = 4;
  1595. Vector<double> type_max;
  1596. type_max.resize(element_count);
  1597. Vector<double> type_min;
  1598. type_min.resize(element_count);
  1599. for (int i = 0; i < p_attribs.size(); i++) {
  1600. Color attrib = p_attribs[i];
  1601. attribs.write[(i * element_count) + 0] = _filter_number(attrib.r);
  1602. attribs.write[(i * element_count) + 1] = _filter_number(attrib.g);
  1603. attribs.write[(i * element_count) + 2] = _filter_number(attrib.b);
  1604. attribs.write[(i * element_count) + 3] = _filter_number(attrib.a);
  1605. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1606. }
  1607. _round_min_max_components(type_min, type_max);
  1608. ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
  1609. Ref<GLTFAccessor> accessor;
  1610. accessor.instantiate();
  1611. GLTFBufferIndex buffer_view_i;
  1612. if (p_state->buffers.is_empty()) {
  1613. p_state->buffers.push_back(Vector<uint8_t>());
  1614. }
  1615. int64_t size = p_state->buffers[0].size();
  1616. const GLTFAccessor::GLTFAccessorType accessor_type = GLTFAccessor::TYPE_VEC4;
  1617. const GLTFAccessor::GLTFComponentType component_type = GLTFAccessor::COMPONENT_TYPE_SINGLE_FLOAT;
  1618. accessor->max = type_max;
  1619. accessor->min = type_min;
  1620. accessor->normalized = false;
  1621. accessor->count = p_attribs.size();
  1622. accessor->accessor_type = accessor_type;
  1623. accessor->component_type = component_type;
  1624. accessor->byte_offset = 0;
  1625. Error err = _encode_buffer_view(p_state, attribs.ptr(), p_attribs.size(), accessor_type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1626. if (err != OK) {
  1627. return -1;
  1628. }
  1629. accessor->buffer_view = buffer_view_i;
  1630. p_state->accessors.push_back(accessor);
  1631. return p_state->accessors.size() - 1;
  1632. }
  1633. void GLTFDocument::_calc_accessor_min_max(int p_i, const int p_element_count, Vector<double> &p_type_max, Vector<double> p_attribs, Vector<double> &p_type_min) {
  1634. if (p_i == 0) {
  1635. for (int32_t type_i = 0; type_i < p_element_count; type_i++) {
  1636. p_type_max.write[type_i] = p_attribs[(p_i * p_element_count) + type_i];
  1637. p_type_min.write[type_i] = p_attribs[(p_i * p_element_count) + type_i];
  1638. }
  1639. }
  1640. for (int32_t type_i = 0; type_i < p_element_count; type_i++) {
  1641. p_type_max.write[type_i] = MAX(p_attribs[(p_i * p_element_count) + type_i], p_type_max[type_i]);
  1642. p_type_min.write[type_i] = MIN(p_attribs[(p_i * p_element_count) + type_i], p_type_min[type_i]);
  1643. }
  1644. }
  1645. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_weights(Ref<GLTFState> p_state, const Vector<Color> p_attribs, const bool p_for_vertex) {
  1646. if (p_attribs.size() == 0) {
  1647. return -1;
  1648. }
  1649. const int ret_size = p_attribs.size() * 4;
  1650. Vector<double> attribs;
  1651. attribs.resize(ret_size);
  1652. const int element_count = 4;
  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. Color attrib = p_attribs[i];
  1659. attribs.write[(i * element_count) + 0] = _filter_number(attrib.r);
  1660. attribs.write[(i * element_count) + 1] = _filter_number(attrib.g);
  1661. attribs.write[(i * element_count) + 2] = _filter_number(attrib.b);
  1662. attribs.write[(i * element_count) + 3] = _filter_number(attrib.a);
  1663. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1664. }
  1665. _round_min_max_components(type_min, type_max);
  1666. ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
  1667. Ref<GLTFAccessor> accessor;
  1668. accessor.instantiate();
  1669. GLTFBufferIndex buffer_view_i;
  1670. if (p_state->buffers.is_empty()) {
  1671. p_state->buffers.push_back(Vector<uint8_t>());
  1672. }
  1673. int64_t size = p_state->buffers[0].size();
  1674. const GLTFAccessor::GLTFAccessorType accessor_type = GLTFAccessor::TYPE_VEC4;
  1675. const GLTFAccessor::GLTFComponentType component_type = GLTFAccessor::COMPONENT_TYPE_SINGLE_FLOAT;
  1676. accessor->max = type_max;
  1677. accessor->min = type_min;
  1678. accessor->normalized = false;
  1679. accessor->count = p_attribs.size();
  1680. accessor->accessor_type = accessor_type;
  1681. accessor->component_type = component_type;
  1682. accessor->byte_offset = 0;
  1683. Error err = _encode_buffer_view(p_state, attribs.ptr(), p_attribs.size(), accessor_type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1684. if (err != OK) {
  1685. return -1;
  1686. }
  1687. accessor->buffer_view = buffer_view_i;
  1688. p_state->accessors.push_back(accessor);
  1689. return p_state->accessors.size() - 1;
  1690. }
  1691. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_joints(Ref<GLTFState> p_state, const Vector<Color> p_attribs, const bool p_for_vertex) {
  1692. if (p_attribs.size() == 0) {
  1693. return -1;
  1694. }
  1695. const int element_count = 4;
  1696. const int ret_size = p_attribs.size() * element_count;
  1697. Vector<double> attribs;
  1698. attribs.resize(ret_size);
  1699. Vector<double> type_max;
  1700. type_max.resize(element_count);
  1701. Vector<double> type_min;
  1702. type_min.resize(element_count);
  1703. for (int i = 0; i < p_attribs.size(); i++) {
  1704. Color attrib = p_attribs[i];
  1705. attribs.write[(i * element_count) + 0] = _filter_number(attrib.r);
  1706. attribs.write[(i * element_count) + 1] = _filter_number(attrib.g);
  1707. attribs.write[(i * element_count) + 2] = _filter_number(attrib.b);
  1708. attribs.write[(i * element_count) + 3] = _filter_number(attrib.a);
  1709. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1710. }
  1711. _round_min_max_components(type_min, type_max);
  1712. ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
  1713. Ref<GLTFAccessor> accessor;
  1714. accessor.instantiate();
  1715. GLTFBufferIndex buffer_view_i;
  1716. if (p_state->buffers.is_empty()) {
  1717. p_state->buffers.push_back(Vector<uint8_t>());
  1718. }
  1719. int64_t size = p_state->buffers[0].size();
  1720. const GLTFAccessor::GLTFAccessorType accessor_type = GLTFAccessor::TYPE_VEC4;
  1721. const GLTFAccessor::GLTFComponentType component_type = GLTFAccessor::COMPONENT_TYPE_UNSIGNED_SHORT;
  1722. accessor->max = type_max;
  1723. accessor->min = type_min;
  1724. accessor->normalized = false;
  1725. accessor->count = p_attribs.size();
  1726. accessor->accessor_type = accessor_type;
  1727. accessor->component_type = component_type;
  1728. accessor->byte_offset = 0;
  1729. Error err = _encode_buffer_view(p_state, attribs.ptr(), p_attribs.size(), accessor_type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1730. if (err != OK) {
  1731. return -1;
  1732. }
  1733. accessor->buffer_view = buffer_view_i;
  1734. p_state->accessors.push_back(accessor);
  1735. return p_state->accessors.size() - 1;
  1736. }
  1737. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_quaternions(Ref<GLTFState> p_state, const Vector<Quaternion> p_attribs, const bool p_for_vertex) {
  1738. if (p_attribs.size() == 0) {
  1739. return -1;
  1740. }
  1741. const int element_count = 4;
  1742. const int ret_size = p_attribs.size() * element_count;
  1743. Vector<double> attribs;
  1744. attribs.resize(ret_size);
  1745. Vector<double> type_max;
  1746. type_max.resize(element_count);
  1747. Vector<double> type_min;
  1748. type_min.resize(element_count);
  1749. for (int i = 0; i < p_attribs.size(); i++) {
  1750. Quaternion quaternion = p_attribs[i];
  1751. attribs.write[(i * element_count) + 0] = _filter_number(quaternion.x);
  1752. attribs.write[(i * element_count) + 1] = _filter_number(quaternion.y);
  1753. attribs.write[(i * element_count) + 2] = _filter_number(quaternion.z);
  1754. attribs.write[(i * element_count) + 3] = _filter_number(quaternion.w);
  1755. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1756. }
  1757. _round_min_max_components(type_min, type_max);
  1758. ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
  1759. Ref<GLTFAccessor> accessor;
  1760. accessor.instantiate();
  1761. GLTFBufferIndex buffer_view_i;
  1762. if (p_state->buffers.is_empty()) {
  1763. p_state->buffers.push_back(Vector<uint8_t>());
  1764. }
  1765. int64_t size = p_state->buffers[0].size();
  1766. const GLTFAccessor::GLTFAccessorType accessor_type = GLTFAccessor::TYPE_VEC4;
  1767. const GLTFAccessor::GLTFComponentType component_type = GLTFAccessor::COMPONENT_TYPE_SINGLE_FLOAT;
  1768. accessor->max = type_max;
  1769. accessor->min = type_min;
  1770. accessor->normalized = false;
  1771. accessor->count = p_attribs.size();
  1772. accessor->accessor_type = accessor_type;
  1773. accessor->component_type = component_type;
  1774. accessor->byte_offset = 0;
  1775. Error err = _encode_buffer_view(p_state, attribs.ptr(), p_attribs.size(), accessor_type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1776. if (err != OK) {
  1777. return -1;
  1778. }
  1779. accessor->buffer_view = buffer_view_i;
  1780. p_state->accessors.push_back(accessor);
  1781. return p_state->accessors.size() - 1;
  1782. }
  1783. Vector<Vector2> GLTFDocument::_decode_accessor_as_vec2(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex, const Vector<int> &p_packed_vertex_ids) {
  1784. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  1785. Vector<Vector2> ret;
  1786. if (attribs.size() == 0) {
  1787. return ret;
  1788. }
  1789. ERR_FAIL_COND_V(attribs.size() % 2 != 0, ret);
  1790. const double *attribs_ptr = attribs.ptr();
  1791. int ret_size = attribs.size() / 2;
  1792. if (!p_packed_vertex_ids.is_empty()) {
  1793. ERR_FAIL_COND_V(p_packed_vertex_ids[p_packed_vertex_ids.size() - 1] >= ret_size, ret);
  1794. ret_size = p_packed_vertex_ids.size();
  1795. }
  1796. ret.resize(ret_size);
  1797. for (int i = 0; i < ret_size; i++) {
  1798. int src_i = i;
  1799. if (!p_packed_vertex_ids.is_empty()) {
  1800. src_i = p_packed_vertex_ids[i];
  1801. }
  1802. ret.write[i] = Vector2(attribs_ptr[src_i * 2 + 0], attribs_ptr[src_i * 2 + 1]);
  1803. }
  1804. return ret;
  1805. }
  1806. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_floats(Ref<GLTFState> p_state, const Vector<double> p_attribs, const bool p_for_vertex) {
  1807. if (p_attribs.size() == 0) {
  1808. return -1;
  1809. }
  1810. const int element_count = 1;
  1811. const int ret_size = p_attribs.size();
  1812. Vector<double> attribs;
  1813. attribs.resize(ret_size);
  1814. Vector<double> type_max;
  1815. type_max.resize(element_count);
  1816. Vector<double> type_min;
  1817. type_min.resize(element_count);
  1818. for (int i = 0; i < p_attribs.size(); i++) {
  1819. attribs.write[i] = _filter_number(p_attribs[i]);
  1820. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1821. }
  1822. _round_min_max_components(type_min, type_max);
  1823. ERR_FAIL_COND_V(attribs.is_empty(), -1);
  1824. Ref<GLTFAccessor> accessor;
  1825. accessor.instantiate();
  1826. GLTFBufferIndex buffer_view_i;
  1827. if (p_state->buffers.is_empty()) {
  1828. p_state->buffers.push_back(Vector<uint8_t>());
  1829. }
  1830. int64_t size = p_state->buffers[0].size();
  1831. const GLTFAccessor::GLTFAccessorType accessor_type = GLTFAccessor::TYPE_SCALAR;
  1832. const GLTFAccessor::GLTFComponentType component_type = GLTFAccessor::COMPONENT_TYPE_SINGLE_FLOAT;
  1833. accessor->max = type_max;
  1834. accessor->min = type_min;
  1835. accessor->normalized = false;
  1836. accessor->count = ret_size;
  1837. accessor->accessor_type = accessor_type;
  1838. accessor->component_type = component_type;
  1839. accessor->byte_offset = 0;
  1840. Error err = _encode_buffer_view(p_state, attribs.ptr(), attribs.size(), accessor_type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1841. if (err != OK) {
  1842. return -1;
  1843. }
  1844. accessor->buffer_view = buffer_view_i;
  1845. p_state->accessors.push_back(accessor);
  1846. return p_state->accessors.size() - 1;
  1847. }
  1848. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_vec3(Ref<GLTFState> p_state, const Vector<Vector3> p_attribs, const bool p_for_vertex) {
  1849. if (p_attribs.size() == 0) {
  1850. return -1;
  1851. }
  1852. const int element_count = 3;
  1853. const int ret_size = p_attribs.size() * element_count;
  1854. Vector<double> attribs;
  1855. attribs.resize(ret_size);
  1856. Vector<double> type_max;
  1857. type_max.resize(element_count);
  1858. Vector<double> type_min;
  1859. type_min.resize(element_count);
  1860. for (int i = 0; i < p_attribs.size(); i++) {
  1861. Vector3 attrib = p_attribs[i];
  1862. attribs.write[(i * element_count) + 0] = _filter_number(attrib.x);
  1863. attribs.write[(i * element_count) + 1] = _filter_number(attrib.y);
  1864. attribs.write[(i * element_count) + 2] = _filter_number(attrib.z);
  1865. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1866. }
  1867. _round_min_max_components(type_min, type_max);
  1868. ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
  1869. Ref<GLTFAccessor> accessor;
  1870. accessor.instantiate();
  1871. GLTFBufferIndex buffer_view_i;
  1872. if (p_state->buffers.is_empty()) {
  1873. p_state->buffers.push_back(Vector<uint8_t>());
  1874. }
  1875. int64_t size = p_state->buffers[0].size();
  1876. const GLTFAccessor::GLTFAccessorType accessor_type = GLTFAccessor::TYPE_VEC3;
  1877. const GLTFAccessor::GLTFComponentType component_type = GLTFAccessor::COMPONENT_TYPE_SINGLE_FLOAT;
  1878. accessor->max = type_max;
  1879. accessor->min = type_min;
  1880. accessor->normalized = false;
  1881. accessor->count = p_attribs.size();
  1882. accessor->accessor_type = accessor_type;
  1883. accessor->component_type = component_type;
  1884. accessor->byte_offset = 0;
  1885. Error err = _encode_buffer_view(p_state, attribs.ptr(), p_attribs.size(), accessor_type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  1886. if (err != OK) {
  1887. return -1;
  1888. }
  1889. accessor->buffer_view = buffer_view_i;
  1890. p_state->accessors.push_back(accessor);
  1891. return p_state->accessors.size() - 1;
  1892. }
  1893. GLTFAccessorIndex GLTFDocument::_encode_sparse_accessor_as_vec3(Ref<GLTFState> p_state, const Vector<Vector3> p_attribs, const Vector<Vector3> p_reference_attribs, const float p_reference_multiplier, const bool p_for_vertex, const GLTFAccessorIndex p_reference_accessor) {
  1894. if (p_attribs.size() == 0) {
  1895. return -1;
  1896. }
  1897. const int element_count = 3;
  1898. Vector<double> attribs;
  1899. Vector<double> type_max;
  1900. Vector<double> type_min;
  1901. attribs.resize(p_attribs.size() * element_count);
  1902. type_max.resize(element_count);
  1903. type_min.resize(element_count);
  1904. Vector<double> changed_indices;
  1905. Vector<double> changed_values;
  1906. int max_changed_index = 0;
  1907. for (int i = 0; i < p_attribs.size(); i++) {
  1908. Vector3 attrib = p_attribs[i];
  1909. bool is_different = false;
  1910. if (i < p_reference_attribs.size()) {
  1911. is_different = !(attrib * p_reference_multiplier).is_equal_approx(p_reference_attribs[i]);
  1912. if (!is_different) {
  1913. attrib = p_reference_attribs[i];
  1914. }
  1915. } else {
  1916. is_different = !(attrib * p_reference_multiplier).is_zero_approx();
  1917. if (!is_different) {
  1918. attrib = Vector3();
  1919. }
  1920. }
  1921. attribs.write[(i * element_count) + 0] = _filter_number(attrib.x);
  1922. attribs.write[(i * element_count) + 1] = _filter_number(attrib.y);
  1923. attribs.write[(i * element_count) + 2] = _filter_number(attrib.z);
  1924. if (is_different) {
  1925. changed_indices.push_back(i);
  1926. if (i > max_changed_index) {
  1927. max_changed_index = i;
  1928. }
  1929. changed_values.push_back(_filter_number(attrib.x));
  1930. changed_values.push_back(_filter_number(attrib.y));
  1931. changed_values.push_back(_filter_number(attrib.z));
  1932. }
  1933. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  1934. }
  1935. _round_min_max_components(type_min, type_max);
  1936. if (attribs.size() % element_count != 0) {
  1937. return -1;
  1938. }
  1939. Ref<GLTFAccessor> sparse_accessor;
  1940. sparse_accessor.instantiate();
  1941. if (p_state->buffers.is_empty()) {
  1942. p_state->buffers.push_back(Vector<uint8_t>());
  1943. }
  1944. int64_t size = p_state->buffers[0].size();
  1945. const GLTFAccessor::GLTFAccessorType accessor_type = GLTFAccessor::TYPE_VEC3;
  1946. const GLTFAccessor::GLTFComponentType component_type = GLTFAccessor::COMPONENT_TYPE_SINGLE_FLOAT;
  1947. sparse_accessor->normalized = false;
  1948. sparse_accessor->count = p_attribs.size();
  1949. sparse_accessor->accessor_type = accessor_type;
  1950. sparse_accessor->component_type = component_type;
  1951. if (p_reference_accessor < p_state->accessors.size() && p_reference_accessor >= 0 && p_state->accessors[p_reference_accessor].is_valid()) {
  1952. sparse_accessor->byte_offset = p_state->accessors[p_reference_accessor]->byte_offset;
  1953. sparse_accessor->buffer_view = p_state->accessors[p_reference_accessor]->buffer_view;
  1954. }
  1955. sparse_accessor->max = type_max;
  1956. sparse_accessor->min = type_min;
  1957. int sparse_accessor_index_stride = max_changed_index > 65535 ? 4 : 2;
  1958. int sparse_accessor_storage_size = changed_indices.size() * (sparse_accessor_index_stride + element_count * sizeof(float));
  1959. int conventional_storage_size = p_attribs.size() * element_count * sizeof(float);
  1960. if (changed_indices.size() > 0 && sparse_accessor_storage_size < conventional_storage_size) {
  1961. // It must be worthwhile to use a sparse accessor.
  1962. GLTFBufferIndex buffer_view_i_indices = -1;
  1963. GLTFBufferIndex buffer_view_i_values = -1;
  1964. if (sparse_accessor_index_stride == 4) {
  1965. sparse_accessor->sparse_indices_component_type = GLTFAccessor::COMPONENT_TYPE_UNSIGNED_INT;
  1966. } else {
  1967. sparse_accessor->sparse_indices_component_type = GLTFAccessor::COMPONENT_TYPE_UNSIGNED_SHORT;
  1968. }
  1969. if (_encode_buffer_view(p_state, changed_indices.ptr(), changed_indices.size(), GLTFAccessor::TYPE_SCALAR, sparse_accessor->sparse_indices_component_type, sparse_accessor->normalized, sparse_accessor->sparse_indices_byte_offset, false, buffer_view_i_indices) != OK) {
  1970. return -1;
  1971. }
  1972. // We use changed_indices.size() here, because we must pass the number of vec3 values rather than the number of components.
  1973. if (_encode_buffer_view(p_state, changed_values.ptr(), changed_indices.size(), sparse_accessor->accessor_type, sparse_accessor->component_type, sparse_accessor->normalized, sparse_accessor->sparse_values_byte_offset, false, buffer_view_i_values) != OK) {
  1974. return -1;
  1975. }
  1976. sparse_accessor->sparse_indices_buffer_view = buffer_view_i_indices;
  1977. sparse_accessor->sparse_values_buffer_view = buffer_view_i_values;
  1978. sparse_accessor->sparse_count = changed_indices.size();
  1979. } else if (changed_indices.size() > 0) {
  1980. GLTFBufferIndex buffer_view_i;
  1981. sparse_accessor->byte_offset = 0;
  1982. Error err = _encode_buffer_view(p_state, attribs.ptr(), p_attribs.size(), accessor_type, component_type, sparse_accessor->normalized, size, p_for_vertex, buffer_view_i);
  1983. if (err != OK) {
  1984. return -1;
  1985. }
  1986. sparse_accessor->buffer_view = buffer_view_i;
  1987. }
  1988. p_state->accessors.push_back(sparse_accessor);
  1989. return p_state->accessors.size() - 1;
  1990. }
  1991. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_xform(Ref<GLTFState> p_state, const Vector<Transform3D> p_attribs, const bool p_for_vertex) {
  1992. if (p_attribs.size() == 0) {
  1993. return -1;
  1994. }
  1995. const int element_count = 16;
  1996. const int ret_size = p_attribs.size() * element_count;
  1997. Vector<double> attribs;
  1998. attribs.resize(ret_size);
  1999. Vector<double> type_max;
  2000. type_max.resize(element_count);
  2001. Vector<double> type_min;
  2002. type_min.resize(element_count);
  2003. for (int i = 0; i < p_attribs.size(); i++) {
  2004. Transform3D attrib = p_attribs[i];
  2005. Basis basis = attrib.get_basis();
  2006. Vector3 axis_0 = basis.get_column(Vector3::AXIS_X);
  2007. attribs.write[i * element_count + 0] = _filter_number(axis_0.x);
  2008. attribs.write[i * element_count + 1] = _filter_number(axis_0.y);
  2009. attribs.write[i * element_count + 2] = _filter_number(axis_0.z);
  2010. attribs.write[i * element_count + 3] = 0.0;
  2011. Vector3 axis_1 = basis.get_column(Vector3::AXIS_Y);
  2012. attribs.write[i * element_count + 4] = _filter_number(axis_1.x);
  2013. attribs.write[i * element_count + 5] = _filter_number(axis_1.y);
  2014. attribs.write[i * element_count + 6] = _filter_number(axis_1.z);
  2015. attribs.write[i * element_count + 7] = 0.0;
  2016. Vector3 axis_2 = basis.get_column(Vector3::AXIS_Z);
  2017. attribs.write[i * element_count + 8] = _filter_number(axis_2.x);
  2018. attribs.write[i * element_count + 9] = _filter_number(axis_2.y);
  2019. attribs.write[i * element_count + 10] = _filter_number(axis_2.z);
  2020. attribs.write[i * element_count + 11] = 0.0;
  2021. Vector3 origin = attrib.get_origin();
  2022. attribs.write[i * element_count + 12] = _filter_number(origin.x);
  2023. attribs.write[i * element_count + 13] = _filter_number(origin.y);
  2024. attribs.write[i * element_count + 14] = _filter_number(origin.z);
  2025. attribs.write[i * element_count + 15] = 1.0;
  2026. _calc_accessor_min_max(i, element_count, type_max, attribs, type_min);
  2027. }
  2028. _round_min_max_components(type_min, type_max);
  2029. ERR_FAIL_COND_V(attribs.size() % element_count != 0, -1);
  2030. Ref<GLTFAccessor> accessor;
  2031. accessor.instantiate();
  2032. GLTFBufferIndex buffer_view_i;
  2033. if (p_state->buffers.is_empty()) {
  2034. p_state->buffers.push_back(Vector<uint8_t>());
  2035. }
  2036. int64_t size = p_state->buffers[0].size();
  2037. const GLTFAccessor::GLTFAccessorType accessor_type = GLTFAccessor::TYPE_MAT4;
  2038. const GLTFAccessor::GLTFComponentType component_type = GLTFAccessor::COMPONENT_TYPE_SINGLE_FLOAT;
  2039. accessor->max = type_max;
  2040. accessor->min = type_min;
  2041. accessor->normalized = false;
  2042. accessor->count = p_attribs.size();
  2043. accessor->accessor_type = accessor_type;
  2044. accessor->component_type = component_type;
  2045. accessor->byte_offset = 0;
  2046. Error err = _encode_buffer_view(p_state, attribs.ptr(), p_attribs.size(), accessor_type, component_type, accessor->normalized, size, p_for_vertex, buffer_view_i);
  2047. if (err != OK) {
  2048. return -1;
  2049. }
  2050. accessor->buffer_view = buffer_view_i;
  2051. p_state->accessors.push_back(accessor);
  2052. return p_state->accessors.size() - 1;
  2053. }
  2054. Vector<Vector3> GLTFDocument::_decode_accessor_as_vec3(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex, const Vector<int> &p_packed_vertex_ids) {
  2055. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  2056. Vector<Vector3> ret;
  2057. if (attribs.size() == 0) {
  2058. return ret;
  2059. }
  2060. ERR_FAIL_COND_V(attribs.size() % 3 != 0, ret);
  2061. const double *attribs_ptr = attribs.ptr();
  2062. int ret_size = attribs.size() / 3;
  2063. if (!p_packed_vertex_ids.is_empty()) {
  2064. ERR_FAIL_COND_V(p_packed_vertex_ids[p_packed_vertex_ids.size() - 1] >= ret_size, ret);
  2065. ret_size = p_packed_vertex_ids.size();
  2066. }
  2067. ret.resize(ret_size);
  2068. for (int i = 0; i < ret_size; i++) {
  2069. int src_i = i;
  2070. if (!p_packed_vertex_ids.is_empty()) {
  2071. src_i = p_packed_vertex_ids[i];
  2072. }
  2073. ret.write[i] = Vector3(attribs_ptr[src_i * 3 + 0], attribs_ptr[src_i * 3 + 1], attribs_ptr[src_i * 3 + 2]);
  2074. }
  2075. return ret;
  2076. }
  2077. Vector<Color> GLTFDocument::_decode_accessor_as_color(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex, const Vector<int> &p_packed_vertex_ids) {
  2078. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  2079. Vector<Color> ret;
  2080. if (attribs.size() == 0) {
  2081. return ret;
  2082. }
  2083. const int accessor_type = p_state->accessors[p_accessor]->accessor_type;
  2084. ERR_FAIL_COND_V(!(accessor_type == GLTFAccessor::TYPE_VEC3 || accessor_type == GLTFAccessor::TYPE_VEC4), ret);
  2085. int vec_len = 3;
  2086. if (accessor_type == GLTFAccessor::TYPE_VEC4) {
  2087. vec_len = 4;
  2088. }
  2089. ERR_FAIL_COND_V(attribs.size() % vec_len != 0, ret);
  2090. const double *attribs_ptr = attribs.ptr();
  2091. int ret_size = attribs.size() / vec_len;
  2092. if (!p_packed_vertex_ids.is_empty()) {
  2093. ERR_FAIL_COND_V(p_packed_vertex_ids[p_packed_vertex_ids.size() - 1] >= ret_size, ret);
  2094. ret_size = p_packed_vertex_ids.size();
  2095. }
  2096. ret.resize(ret_size);
  2097. for (int i = 0; i < ret_size; i++) {
  2098. int src_i = i;
  2099. if (!p_packed_vertex_ids.is_empty()) {
  2100. src_i = p_packed_vertex_ids[i];
  2101. }
  2102. ret.write[i] = Color(attribs_ptr[src_i * vec_len + 0], attribs_ptr[src_i * vec_len + 1], attribs_ptr[src_i * vec_len + 2], vec_len == 4 ? attribs_ptr[src_i * 4 + 3] : 1.0);
  2103. }
  2104. return ret;
  2105. }
  2106. Vector<Quaternion> GLTFDocument::_decode_accessor_as_quaternion(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  2107. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  2108. Vector<Quaternion> ret;
  2109. if (attribs.size() == 0) {
  2110. return ret;
  2111. }
  2112. ERR_FAIL_COND_V(attribs.size() % 4 != 0, ret);
  2113. const double *attribs_ptr = attribs.ptr();
  2114. const int ret_size = attribs.size() / 4;
  2115. ret.resize(ret_size);
  2116. {
  2117. for (int i = 0; i < ret_size; i++) {
  2118. ret.write[i] = Quaternion(attribs_ptr[i * 4 + 0], attribs_ptr[i * 4 + 1], attribs_ptr[i * 4 + 2], attribs_ptr[i * 4 + 3]).normalized();
  2119. }
  2120. }
  2121. return ret;
  2122. }
  2123. Vector<Transform2D> GLTFDocument::_decode_accessor_as_xform2d(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  2124. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  2125. Vector<Transform2D> ret;
  2126. if (attribs.size() == 0) {
  2127. return ret;
  2128. }
  2129. ERR_FAIL_COND_V(attribs.size() % 4 != 0, ret);
  2130. ret.resize(attribs.size() / 4);
  2131. for (int i = 0; i < ret.size(); i++) {
  2132. ret.write[i][0] = Vector2(attribs[i * 4 + 0], attribs[i * 4 + 1]);
  2133. ret.write[i][1] = Vector2(attribs[i * 4 + 2], attribs[i * 4 + 3]);
  2134. }
  2135. return ret;
  2136. }
  2137. Vector<Basis> GLTFDocument::_decode_accessor_as_basis(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  2138. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  2139. Vector<Basis> ret;
  2140. if (attribs.size() == 0) {
  2141. return ret;
  2142. }
  2143. ERR_FAIL_COND_V(attribs.size() % 9 != 0, ret);
  2144. ret.resize(attribs.size() / 9);
  2145. for (int i = 0; i < ret.size(); i++) {
  2146. ret.write[i].set_column(0, Vector3(attribs[i * 9 + 0], attribs[i * 9 + 1], attribs[i * 9 + 2]));
  2147. ret.write[i].set_column(1, Vector3(attribs[i * 9 + 3], attribs[i * 9 + 4], attribs[i * 9 + 5]));
  2148. ret.write[i].set_column(2, Vector3(attribs[i * 9 + 6], attribs[i * 9 + 7], attribs[i * 9 + 8]));
  2149. }
  2150. return ret;
  2151. }
  2152. Vector<Transform3D> GLTFDocument::_decode_accessor_as_xform(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, const bool p_for_vertex) {
  2153. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, p_for_vertex);
  2154. Vector<Transform3D> ret;
  2155. if (attribs.size() == 0) {
  2156. return ret;
  2157. }
  2158. ERR_FAIL_COND_V(attribs.size() % 16 != 0, ret);
  2159. ret.resize(attribs.size() / 16);
  2160. for (int i = 0; i < ret.size(); i++) {
  2161. ret.write[i].basis.set_column(0, Vector3(attribs[i * 16 + 0], attribs[i * 16 + 1], attribs[i * 16 + 2]));
  2162. ret.write[i].basis.set_column(1, Vector3(attribs[i * 16 + 4], attribs[i * 16 + 5], attribs[i * 16 + 6]));
  2163. ret.write[i].basis.set_column(2, Vector3(attribs[i * 16 + 8], attribs[i * 16 + 9], attribs[i * 16 + 10]));
  2164. ret.write[i].set_origin(Vector3(attribs[i * 16 + 12], attribs[i * 16 + 13], attribs[i * 16 + 14]));
  2165. }
  2166. return ret;
  2167. }
  2168. Vector<Variant> GLTFDocument::_decode_accessor_as_variant(Ref<GLTFState> p_state, const GLTFAccessorIndex p_accessor, Variant::Type p_variant_type, GLTFAccessor::GLTFAccessorType p_accessor_type) {
  2169. const Vector<double> attribs = _decode_accessor(p_state, p_accessor, false);
  2170. Vector<Variant> ret;
  2171. ERR_FAIL_COND_V_MSG(attribs.is_empty(), ret, "glTF: The accessor was empty.");
  2172. const int component_count = COMPONENT_COUNT_FOR_ACCESSOR_TYPE[p_accessor_type];
  2173. ERR_FAIL_COND_V_MSG(attribs.size() % component_count != 0, ret, "glTF: The accessor size was not a multiple of the component count.");
  2174. const int ret_size = attribs.size() / component_count;
  2175. ret.resize(ret_size);
  2176. for (int i = 0; i < ret_size; i++) {
  2177. switch (p_variant_type) {
  2178. case Variant::BOOL: {
  2179. ret.write[i] = attribs[i * component_count] != 0.0;
  2180. } break;
  2181. case Variant::INT: {
  2182. ret.write[i] = (int64_t)attribs[i * component_count];
  2183. } break;
  2184. case Variant::FLOAT: {
  2185. ret.write[i] = attribs[i * component_count];
  2186. } break;
  2187. case Variant::VECTOR2:
  2188. case Variant::RECT2:
  2189. case Variant::VECTOR3:
  2190. case Variant::VECTOR4:
  2191. case Variant::PLANE:
  2192. case Variant::QUATERNION: {
  2193. // General-purpose code for importing glTF accessor data with any component count into structs up to 4 `real_t`s in size.
  2194. Variant v;
  2195. switch (component_count) {
  2196. case 1: {
  2197. v = Vector4(attribs[i * component_count], 0.0f, 0.0f, 0.0f);
  2198. } break;
  2199. case 2: {
  2200. v = Vector4(attribs[i * component_count], attribs[i * component_count + 1], 0.0f, 0.0f);
  2201. } break;
  2202. case 3: {
  2203. v = Vector4(attribs[i * component_count], attribs[i * component_count + 1], attribs[i * component_count + 2], 0.0f);
  2204. } break;
  2205. default: {
  2206. v = Vector4(attribs[i * component_count], attribs[i * component_count + 1], attribs[i * component_count + 2], attribs[i * component_count + 3]);
  2207. } break;
  2208. }
  2209. // Evil hack that relies on the structure of Variant, but it's the
  2210. // only way to accomplish this without a ton of code duplication.
  2211. *(Variant::Type *)&v = p_variant_type;
  2212. ret.write[i] = v;
  2213. } break;
  2214. case Variant::VECTOR2I:
  2215. case Variant::RECT2I:
  2216. case Variant::VECTOR3I:
  2217. case Variant::VECTOR4I: {
  2218. // General-purpose code for importing glTF accessor data with any component count into structs up to 4 `int32_t`s in size.
  2219. Variant v;
  2220. switch (component_count) {
  2221. case 1: {
  2222. v = Vector4i((int32_t)attribs[i * component_count], 0, 0, 0);
  2223. } break;
  2224. case 2: {
  2225. v = Vector4i((int32_t)attribs[i * component_count], (int32_t)attribs[i * component_count + 1], 0, 0);
  2226. } break;
  2227. case 3: {
  2228. v = Vector4i((int32_t)attribs[i * component_count], (int32_t)attribs[i * component_count + 1], (int32_t)attribs[i * component_count + 2], 0);
  2229. } break;
  2230. default: {
  2231. v = Vector4i((int32_t)attribs[i * component_count], (int32_t)attribs[i * component_count + 1], (int32_t)attribs[i * component_count + 2], (int32_t)attribs[i * component_count + 3]);
  2232. } break;
  2233. }
  2234. // Evil hack that relies on the structure of Variant, but it's the
  2235. // only way to accomplish this without a ton of code duplication.
  2236. *(Variant::Type *)&v = p_variant_type;
  2237. ret.write[i] = v;
  2238. } break;
  2239. // No more generalized hacks, each of the below types needs a lot of repetitive code.
  2240. case Variant::COLOR: {
  2241. Variant v;
  2242. switch (component_count) {
  2243. case 1: {
  2244. v = Color(attribs[i * component_count], 0.0f, 0.0f, 1.0f);
  2245. } break;
  2246. case 2: {
  2247. v = Color(attribs[i * component_count], attribs[i * component_count + 1], 0.0f, 1.0f);
  2248. } break;
  2249. case 3: {
  2250. v = Color(attribs[i * component_count], attribs[i * component_count + 1], attribs[i * component_count + 2], 1.0f);
  2251. } break;
  2252. default: {
  2253. v = Color(attribs[i * component_count], attribs[i * component_count + 1], attribs[i * component_count + 2], attribs[i * component_count + 3]);
  2254. } break;
  2255. }
  2256. ret.write[i] = v;
  2257. } break;
  2258. case Variant::TRANSFORM2D: {
  2259. Transform2D t;
  2260. switch (component_count) {
  2261. case 4: {
  2262. t.columns[0] = Vector2(attribs[i * component_count + 0], attribs[i * component_count + 1]);
  2263. t.columns[1] = Vector2(attribs[i * component_count + 2], attribs[i * component_count + 3]);
  2264. } break;
  2265. case 9: {
  2266. t.columns[0] = Vector2(attribs[i * component_count + 0], attribs[i * component_count + 1]);
  2267. t.columns[1] = Vector2(attribs[i * component_count + 3], attribs[i * component_count + 4]);
  2268. t.columns[2] = Vector2(attribs[i * component_count + 6], attribs[i * component_count + 7]);
  2269. } break;
  2270. case 16: {
  2271. t.columns[0] = Vector2(attribs[i * component_count + 0], attribs[i * component_count + 1]);
  2272. t.columns[1] = Vector2(attribs[i * component_count + 4], attribs[i * component_count + 5]);
  2273. t.columns[2] = Vector2(attribs[i * component_count + 12], attribs[i * component_count + 13]);
  2274. } break;
  2275. }
  2276. ret.write[i] = t;
  2277. } break;
  2278. case Variant::BASIS: {
  2279. Basis b;
  2280. switch (component_count) {
  2281. case 4: {
  2282. b.rows[0] = Vector3(attribs[i * component_count + 0], attribs[i * component_count + 2], 0.0f);
  2283. b.rows[1] = Vector3(attribs[i * component_count + 1], attribs[i * component_count + 3], 0.0f);
  2284. } break;
  2285. case 9: {
  2286. b.rows[0] = Vector3(attribs[i * component_count + 0], attribs[i * component_count + 3], attribs[i * component_count + 6]);
  2287. b.rows[1] = Vector3(attribs[i * component_count + 1], attribs[i * component_count + 4], attribs[i * component_count + 7]);
  2288. b.rows[2] = Vector3(attribs[i * component_count + 2], attribs[i * component_count + 5], attribs[i * component_count + 8]);
  2289. } break;
  2290. case 16: {
  2291. b.rows[0] = Vector3(attribs[i * component_count + 0], attribs[i * component_count + 4], attribs[i * component_count + 8]);
  2292. b.rows[1] = Vector3(attribs[i * component_count + 1], attribs[i * component_count + 5], attribs[i * component_count + 9]);
  2293. b.rows[2] = Vector3(attribs[i * component_count + 2], attribs[i * component_count + 6], attribs[i * component_count + 10]);
  2294. } break;
  2295. }
  2296. ret.write[i] = b;
  2297. } break;
  2298. case Variant::TRANSFORM3D: {
  2299. Transform3D t;
  2300. switch (component_count) {
  2301. case 4: {
  2302. t.basis.rows[0] = Vector3(attribs[i * component_count + 0], attribs[i * component_count + 2], 0.0f);
  2303. t.basis.rows[1] = Vector3(attribs[i * component_count + 1], attribs[i * component_count + 3], 0.0f);
  2304. } break;
  2305. case 9: {
  2306. t.basis.rows[0] = Vector3(attribs[i * component_count + 0], attribs[i * component_count + 3], attribs[i * component_count + 6]);
  2307. t.basis.rows[1] = Vector3(attribs[i * component_count + 1], attribs[i * component_count + 4], attribs[i * component_count + 7]);
  2308. t.basis.rows[2] = Vector3(attribs[i * component_count + 2], attribs[i * component_count + 5], attribs[i * component_count + 8]);
  2309. } break;
  2310. case 16: {
  2311. t.basis.rows[0] = Vector3(attribs[i * component_count + 0], attribs[i * component_count + 4], attribs[i * component_count + 8]);
  2312. t.basis.rows[1] = Vector3(attribs[i * component_count + 1], attribs[i * component_count + 5], attribs[i * component_count + 9]);
  2313. t.basis.rows[2] = Vector3(attribs[i * component_count + 2], attribs[i * component_count + 6], attribs[i * component_count + 10]);
  2314. t.origin = Vector3(attribs[i * component_count + 12], attribs[i * component_count + 13], attribs[i * component_count + 14]);
  2315. } break;
  2316. }
  2317. ret.write[i] = t;
  2318. } break;
  2319. case Variant::PROJECTION: {
  2320. Projection p;
  2321. switch (component_count) {
  2322. case 4: {
  2323. p.columns[0] = Vector4(attribs[i * component_count + 0], attribs[i * component_count + 1], 0.0f, 0.0f);
  2324. p.columns[1] = Vector4(attribs[i * component_count + 4], attribs[i * component_count + 5], 0.0f, 0.0f);
  2325. } break;
  2326. case 9: {
  2327. p.columns[0] = Vector4(attribs[i * component_count + 0], attribs[i * component_count + 1], attribs[i * component_count + 2], 0.0f);
  2328. p.columns[1] = Vector4(attribs[i * component_count + 4], attribs[i * component_count + 5], attribs[i * component_count + 6], 0.0f);
  2329. p.columns[2] = Vector4(attribs[i * component_count + 8], attribs[i * component_count + 9], attribs[i * component_count + 10], 0.0f);
  2330. } break;
  2331. case 16: {
  2332. p.columns[0] = Vector4(attribs[i * component_count + 0], attribs[i * component_count + 1], attribs[i * component_count + 2], attribs[i * component_count + 3]);
  2333. p.columns[1] = Vector4(attribs[i * component_count + 4], attribs[i * component_count + 5], attribs[i * component_count + 6], attribs[i * component_count + 7]);
  2334. p.columns[2] = Vector4(attribs[i * component_count + 8], attribs[i * component_count + 9], attribs[i * component_count + 10], attribs[i * component_count + 11]);
  2335. p.columns[3] = Vector4(attribs[i * component_count + 12], attribs[i * component_count + 13], attribs[i * component_count + 14], attribs[i * component_count + 15]);
  2336. } break;
  2337. }
  2338. ret.write[i] = p;
  2339. } break;
  2340. default: {
  2341. ERR_FAIL_V_MSG(ret, "glTF: Cannot decode accessor as Variant of type " + Variant::get_type_name(p_variant_type) + ".");
  2342. }
  2343. }
  2344. }
  2345. return ret;
  2346. }
  2347. GLTFAccessorIndex GLTFDocument::_encode_accessor_as_variant(Ref<GLTFState> p_state, Vector<Variant> p_attribs, Variant::Type p_variant_type, GLTFAccessor::GLTFAccessorType p_accessor_type, GLTFAccessor::GLTFComponentType p_component_type) {
  2348. const int accessor_component_count = COMPONENT_COUNT_FOR_ACCESSOR_TYPE[p_accessor_type];
  2349. Vector<double> encoded_attribs;
  2350. for (const Variant &v : p_attribs) {
  2351. switch (p_variant_type) {
  2352. case Variant::NIL:
  2353. case Variant::BOOL:
  2354. case Variant::INT:
  2355. case Variant::FLOAT: {
  2356. // For scalar values, just append them. Variant can convert all of these to double. Some padding may also be needed.
  2357. encoded_attribs.append(v);
  2358. if (unlikely(accessor_component_count > 1)) {
  2359. for (int i = 1; i < accessor_component_count; i++) {
  2360. encoded_attribs.append(0.0);
  2361. }
  2362. }
  2363. } break;
  2364. case Variant::VECTOR2:
  2365. case Variant::VECTOR2I:
  2366. case Variant::VECTOR3:
  2367. case Variant::VECTOR3I:
  2368. case Variant::VECTOR4:
  2369. case Variant::VECTOR4I: {
  2370. // Variant can handle converting Vector2/2i/3/3i/4/4i to Vector4 for us.
  2371. Vector4 vec = v;
  2372. if (likely(accessor_component_count < 5)) {
  2373. for (int i = 0; i < accessor_component_count; i++) {
  2374. encoded_attribs.append(vec[i]);
  2375. }
  2376. }
  2377. } break;
  2378. case Variant::PLANE: {
  2379. Plane p = v;
  2380. if (likely(accessor_component_count == 4)) {
  2381. encoded_attribs.append(p.normal.x);
  2382. encoded_attribs.append(p.normal.y);
  2383. encoded_attribs.append(p.normal.z);
  2384. encoded_attribs.append(p.d);
  2385. }
  2386. } break;
  2387. case Variant::QUATERNION: {
  2388. Quaternion q = v;
  2389. if (likely(accessor_component_count < 5)) {
  2390. for (int i = 0; i < accessor_component_count; i++) {
  2391. encoded_attribs.append(q[i]);
  2392. }
  2393. }
  2394. } break;
  2395. case Variant::COLOR: {
  2396. Color c = v;
  2397. if (likely(accessor_component_count < 5)) {
  2398. for (int i = 0; i < accessor_component_count; i++) {
  2399. encoded_attribs.append(c[i]);
  2400. }
  2401. }
  2402. } break;
  2403. case Variant::RECT2:
  2404. case Variant::RECT2I: {
  2405. // Variant can handle converting Rect2i to Rect2 for us.
  2406. Rect2 r = v;
  2407. if (likely(accessor_component_count == 4)) {
  2408. encoded_attribs.append(r.position.x);
  2409. encoded_attribs.append(r.position.y);
  2410. encoded_attribs.append(r.size.x);
  2411. encoded_attribs.append(r.size.y);
  2412. }
  2413. } break;
  2414. case Variant::TRANSFORM2D:
  2415. case Variant::BASIS:
  2416. case Variant::TRANSFORM3D:
  2417. case Variant::PROJECTION: {
  2418. // Variant can handle converting Transform2D/Transform3D/Basis to Projection for us.
  2419. Projection p = v;
  2420. if (accessor_component_count == 16) {
  2421. for (int i = 0; i < 4; i++) {
  2422. encoded_attribs.append(p.columns[i][0]);
  2423. encoded_attribs.append(p.columns[i][1]);
  2424. encoded_attribs.append(p.columns[i][2]);
  2425. encoded_attribs.append(p.columns[i][3]);
  2426. }
  2427. } else if (accessor_component_count == 9) {
  2428. for (int i = 0; i < 3; i++) {
  2429. encoded_attribs.append(p.columns[i][0]);
  2430. encoded_attribs.append(p.columns[i][1]);
  2431. encoded_attribs.append(p.columns[i][2]);
  2432. }
  2433. } else if (accessor_component_count == 4) {
  2434. encoded_attribs.append(p.columns[0][0]);
  2435. encoded_attribs.append(p.columns[0][1]);
  2436. encoded_attribs.append(p.columns[1][0]);
  2437. encoded_attribs.append(p.columns[1][1]);
  2438. }
  2439. } break;
  2440. default: {
  2441. ERR_FAIL_V_MSG(-1, "glTF: Cannot encode accessor from Variant of type " + Variant::get_type_name(p_variant_type) + ".");
  2442. }
  2443. }
  2444. }
  2445. // Determine the min and max values for the accessor.
  2446. Vector<double> type_max;
  2447. type_max.resize(accessor_component_count);
  2448. Vector<double> type_min;
  2449. type_min.resize(accessor_component_count);
  2450. for (int i = 0; i < encoded_attribs.size(); i++) {
  2451. if (Math::is_zero_approx(encoded_attribs[i])) {
  2452. encoded_attribs.write[i] = 0.0;
  2453. } else {
  2454. encoded_attribs.write[i] = _filter_number(encoded_attribs[i]);
  2455. }
  2456. }
  2457. for (int i = 0; i < p_attribs.size(); i++) {
  2458. _calc_accessor_min_max(i, accessor_component_count, type_max, encoded_attribs, type_min);
  2459. }
  2460. _round_min_max_components(type_min, type_max);
  2461. // Encode the data in a buffer view.
  2462. GLTFBufferIndex buffer_view_index = 0;
  2463. if (p_state->buffers.is_empty()) {
  2464. p_state->buffers.push_back(Vector<uint8_t>());
  2465. }
  2466. const int64_t buffer_size = p_state->buffers[buffer_view_index].size();
  2467. Error err = _encode_buffer_view(p_state, encoded_attribs.ptr(), p_attribs.size(), p_accessor_type, p_component_type, false, buffer_size, false, buffer_view_index);
  2468. if (err != OK) {
  2469. return -1;
  2470. }
  2471. // Create the accessor and fill it with the data.
  2472. Ref<GLTFAccessor> accessor;
  2473. accessor.instantiate();
  2474. accessor->max = type_max;
  2475. accessor->min = type_min;
  2476. accessor->count = p_attribs.size();
  2477. accessor->accessor_type = p_accessor_type;
  2478. accessor->component_type = p_component_type;
  2479. accessor->byte_offset = 0;
  2480. accessor->buffer_view = buffer_view_index;
  2481. const GLTFAccessorIndex new_accessor_index = p_state->accessors.size();
  2482. p_state->accessors.push_back(accessor);
  2483. return new_accessor_index;
  2484. }
  2485. Error GLTFDocument::_serialize_meshes(Ref<GLTFState> p_state) {
  2486. Array meshes;
  2487. for (GLTFMeshIndex gltf_mesh_i = 0; gltf_mesh_i < p_state->meshes.size(); gltf_mesh_i++) {
  2488. print_verbose("glTF: Serializing mesh: " + itos(gltf_mesh_i));
  2489. Ref<ImporterMesh> import_mesh = p_state->meshes.write[gltf_mesh_i]->get_mesh();
  2490. if (import_mesh.is_null()) {
  2491. continue;
  2492. }
  2493. Array instance_materials = p_state->meshes.write[gltf_mesh_i]->get_instance_materials();
  2494. Array primitives;
  2495. Dictionary gltf_mesh;
  2496. Array target_names;
  2497. Array weights;
  2498. for (int morph_i = 0; morph_i < import_mesh->get_blend_shape_count(); morph_i++) {
  2499. target_names.push_back(import_mesh->get_blend_shape_name(morph_i));
  2500. }
  2501. for (int surface_i = 0; surface_i < import_mesh->get_surface_count(); surface_i++) {
  2502. Array targets;
  2503. Dictionary primitive;
  2504. Mesh::PrimitiveType primitive_type = import_mesh->get_surface_primitive_type(surface_i);
  2505. switch (primitive_type) {
  2506. case Mesh::PRIMITIVE_POINTS: {
  2507. primitive["mode"] = 0;
  2508. break;
  2509. }
  2510. case Mesh::PRIMITIVE_LINES: {
  2511. primitive["mode"] = 1;
  2512. break;
  2513. }
  2514. // case Mesh::PRIMITIVE_LINE_LOOP: {
  2515. // primitive["mode"] = 2;
  2516. // break;
  2517. // }
  2518. case Mesh::PRIMITIVE_LINE_STRIP: {
  2519. primitive["mode"] = 3;
  2520. break;
  2521. }
  2522. case Mesh::PRIMITIVE_TRIANGLES: {
  2523. primitive["mode"] = 4;
  2524. break;
  2525. }
  2526. case Mesh::PRIMITIVE_TRIANGLE_STRIP: {
  2527. primitive["mode"] = 5;
  2528. break;
  2529. }
  2530. // case Mesh::PRIMITIVE_TRIANGLE_FAN: {
  2531. // primitive["mode"] = 6;
  2532. // break;
  2533. // }
  2534. default: {
  2535. ERR_FAIL_V(FAILED);
  2536. }
  2537. }
  2538. Array array = import_mesh->get_surface_arrays(surface_i);
  2539. uint64_t format = import_mesh->get_surface_format(surface_i);
  2540. int32_t vertex_num = 0;
  2541. Dictionary attributes;
  2542. {
  2543. Vector<Vector3> a = array[Mesh::ARRAY_VERTEX];
  2544. ERR_FAIL_COND_V(a.is_empty(), ERR_INVALID_DATA);
  2545. attributes["POSITION"] = _encode_accessor_as_vec3(p_state, a, true);
  2546. vertex_num = a.size();
  2547. }
  2548. {
  2549. Vector<real_t> a = array[Mesh::ARRAY_TANGENT];
  2550. if (a.size()) {
  2551. const int ret_size = a.size() / 4;
  2552. Vector<Color> attribs;
  2553. attribs.resize(ret_size);
  2554. for (int i = 0; i < ret_size; i++) {
  2555. Color out;
  2556. out.r = a[(i * 4) + 0];
  2557. out.g = a[(i * 4) + 1];
  2558. out.b = a[(i * 4) + 2];
  2559. out.a = a[(i * 4) + 3];
  2560. attribs.write[i] = out;
  2561. }
  2562. attributes["TANGENT"] = _encode_accessor_as_color(p_state, attribs, true);
  2563. }
  2564. }
  2565. {
  2566. Vector<Vector3> a = array[Mesh::ARRAY_NORMAL];
  2567. if (a.size()) {
  2568. const int ret_size = a.size();
  2569. Vector<Vector3> attribs;
  2570. attribs.resize(ret_size);
  2571. for (int i = 0; i < ret_size; i++) {
  2572. attribs.write[i] = Vector3(a[i]).normalized();
  2573. }
  2574. attributes["NORMAL"] = _encode_accessor_as_vec3(p_state, attribs, true);
  2575. }
  2576. }
  2577. {
  2578. Vector<Vector2> a = array[Mesh::ARRAY_TEX_UV];
  2579. if (a.size()) {
  2580. attributes["TEXCOORD_0"] = _encode_accessor_as_vec2(p_state, a, true);
  2581. }
  2582. }
  2583. {
  2584. Vector<Vector2> a = array[Mesh::ARRAY_TEX_UV2];
  2585. if (a.size()) {
  2586. attributes["TEXCOORD_1"] = _encode_accessor_as_vec2(p_state, a, true);
  2587. }
  2588. }
  2589. for (int custom_i = 0; custom_i < 3; custom_i++) {
  2590. Vector<float> a = array[Mesh::ARRAY_CUSTOM0 + custom_i];
  2591. if (a.size()) {
  2592. int num_channels = 4;
  2593. int custom_shift = Mesh::ARRAY_FORMAT_CUSTOM0_SHIFT + custom_i * Mesh::ARRAY_FORMAT_CUSTOM_BITS;
  2594. switch ((format >> custom_shift) & Mesh::ARRAY_FORMAT_CUSTOM_MASK) {
  2595. case Mesh::ARRAY_CUSTOM_R_FLOAT:
  2596. num_channels = 1;
  2597. break;
  2598. case Mesh::ARRAY_CUSTOM_RG_FLOAT:
  2599. num_channels = 2;
  2600. break;
  2601. case Mesh::ARRAY_CUSTOM_RGB_FLOAT:
  2602. num_channels = 3;
  2603. break;
  2604. case Mesh::ARRAY_CUSTOM_RGBA_FLOAT:
  2605. num_channels = 4;
  2606. break;
  2607. }
  2608. int texcoord_i = 2 + 2 * custom_i;
  2609. String gltf_texcoord_key;
  2610. for (int prev_texcoord_i = 0; prev_texcoord_i < texcoord_i; prev_texcoord_i++) {
  2611. gltf_texcoord_key = vformat("TEXCOORD_%d", prev_texcoord_i);
  2612. if (!attributes.has(gltf_texcoord_key)) {
  2613. Vector<Vector2> empty;
  2614. empty.resize(vertex_num);
  2615. attributes[gltf_texcoord_key] = _encode_accessor_as_vec2(p_state, empty, true);
  2616. }
  2617. }
  2618. LocalVector<Vector2> first_channel;
  2619. first_channel.resize(vertex_num);
  2620. LocalVector<Vector2> second_channel;
  2621. second_channel.resize(vertex_num);
  2622. for (int32_t vert_i = 0; vert_i < vertex_num; vert_i++) {
  2623. float u = a[vert_i * num_channels + 0];
  2624. float v = (num_channels == 1 ? 0.0f : a[vert_i * num_channels + 1]);
  2625. first_channel[vert_i] = Vector2(u, v);
  2626. u = 0;
  2627. v = 0;
  2628. if (num_channels >= 3) {
  2629. u = a[vert_i * num_channels + 2];
  2630. v = (num_channels == 3 ? 0.0f : a[vert_i * num_channels + 3]);
  2631. second_channel[vert_i] = Vector2(u, v);
  2632. }
  2633. }
  2634. gltf_texcoord_key = vformat("TEXCOORD_%d", texcoord_i);
  2635. attributes[gltf_texcoord_key] = _encode_accessor_as_vec2(p_state, first_channel, true);
  2636. gltf_texcoord_key = vformat("TEXCOORD_%d", texcoord_i + 1);
  2637. attributes[gltf_texcoord_key] = _encode_accessor_as_vec2(p_state, second_channel, true);
  2638. }
  2639. }
  2640. {
  2641. Vector<Color> a = array[Mesh::ARRAY_COLOR];
  2642. if (a.size()) {
  2643. attributes["COLOR_0"] = _encode_accessor_as_color(p_state, a, true);
  2644. }
  2645. }
  2646. HashMap<int, int> joint_i_to_bone_i;
  2647. for (GLTFNodeIndex node_i = 0; node_i < p_state->nodes.size(); node_i++) {
  2648. GLTFSkinIndex skin_i = -1;
  2649. if (p_state->nodes[node_i]->mesh == gltf_mesh_i) {
  2650. skin_i = p_state->nodes[node_i]->skin;
  2651. }
  2652. if (skin_i != -1) {
  2653. joint_i_to_bone_i = p_state->skins[skin_i]->joint_i_to_bone_i;
  2654. break;
  2655. }
  2656. }
  2657. {
  2658. const Array &a = array[Mesh::ARRAY_BONES];
  2659. const Vector<Vector3> &vertex_array = array[Mesh::ARRAY_VERTEX];
  2660. if ((a.size() / JOINT_GROUP_SIZE) == vertex_array.size()) {
  2661. const int ret_size = a.size() / JOINT_GROUP_SIZE;
  2662. Vector<Color> attribs;
  2663. attribs.resize(ret_size);
  2664. {
  2665. for (int array_i = 0; array_i < attribs.size(); array_i++) {
  2666. int32_t joint_0 = a[(array_i * JOINT_GROUP_SIZE) + 0];
  2667. int32_t joint_1 = a[(array_i * JOINT_GROUP_SIZE) + 1];
  2668. int32_t joint_2 = a[(array_i * JOINT_GROUP_SIZE) + 2];
  2669. int32_t joint_3 = a[(array_i * JOINT_GROUP_SIZE) + 3];
  2670. attribs.write[array_i] = Color(joint_0, joint_1, joint_2, joint_3);
  2671. }
  2672. }
  2673. attributes["JOINTS_0"] = _encode_accessor_as_joints(p_state, attribs, true);
  2674. } else if ((a.size() / (JOINT_GROUP_SIZE * 2)) >= vertex_array.size()) {
  2675. Vector<Color> joints_0;
  2676. joints_0.resize(vertex_num);
  2677. Vector<Color> joints_1;
  2678. joints_1.resize(vertex_num);
  2679. int32_t weights_8_count = JOINT_GROUP_SIZE * 2;
  2680. for (int32_t vertex_i = 0; vertex_i < vertex_num; vertex_i++) {
  2681. Color joint_0;
  2682. joint_0.r = a[vertex_i * weights_8_count + 0];
  2683. joint_0.g = a[vertex_i * weights_8_count + 1];
  2684. joint_0.b = a[vertex_i * weights_8_count + 2];
  2685. joint_0.a = a[vertex_i * weights_8_count + 3];
  2686. joints_0.write[vertex_i] = joint_0;
  2687. Color joint_1;
  2688. joint_1.r = a[vertex_i * weights_8_count + 4];
  2689. joint_1.g = a[vertex_i * weights_8_count + 5];
  2690. joint_1.b = a[vertex_i * weights_8_count + 6];
  2691. joint_1.a = a[vertex_i * weights_8_count + 7];
  2692. joints_1.write[vertex_i] = joint_1;
  2693. }
  2694. attributes["JOINTS_0"] = _encode_accessor_as_joints(p_state, joints_0, true);
  2695. attributes["JOINTS_1"] = _encode_accessor_as_joints(p_state, joints_1, true);
  2696. }
  2697. }
  2698. {
  2699. const Array &a = array[Mesh::ARRAY_WEIGHTS];
  2700. const Vector<Vector3> &vertex_array = array[Mesh::ARRAY_VERTEX];
  2701. if ((a.size() / JOINT_GROUP_SIZE) == vertex_array.size()) {
  2702. int32_t vertex_count = vertex_array.size();
  2703. Vector<Color> attribs;
  2704. attribs.resize(vertex_count);
  2705. for (int i = 0; i < vertex_count; i++) {
  2706. Color weight_0(a[(i * JOINT_GROUP_SIZE) + 0], a[(i * JOINT_GROUP_SIZE) + 1], a[(i * JOINT_GROUP_SIZE) + 2], a[(i * JOINT_GROUP_SIZE) + 3]);
  2707. float divisor = weight_0.r + weight_0.g + weight_0.b + weight_0.a;
  2708. if (Math::is_zero_approx(divisor) || !Math::is_finite(divisor)) {
  2709. divisor = 1.0;
  2710. weight_0 = Color(1, 0, 0, 0);
  2711. }
  2712. attribs.write[i] = weight_0 / divisor;
  2713. }
  2714. attributes["WEIGHTS_0"] = _encode_accessor_as_weights(p_state, attribs, true);
  2715. } else if ((a.size() / (JOINT_GROUP_SIZE * 2)) >= vertex_array.size()) {
  2716. Vector<Color> weights_0;
  2717. weights_0.resize(vertex_num);
  2718. Vector<Color> weights_1;
  2719. weights_1.resize(vertex_num);
  2720. int32_t weights_8_count = JOINT_GROUP_SIZE * 2;
  2721. for (int32_t vertex_i = 0; vertex_i < vertex_num; vertex_i++) {
  2722. Color weight_0;
  2723. weight_0.r = a[vertex_i * weights_8_count + 0];
  2724. weight_0.g = a[vertex_i * weights_8_count + 1];
  2725. weight_0.b = a[vertex_i * weights_8_count + 2];
  2726. weight_0.a = a[vertex_i * weights_8_count + 3];
  2727. Color weight_1;
  2728. weight_1.r = a[vertex_i * weights_8_count + 4];
  2729. weight_1.g = a[vertex_i * weights_8_count + 5];
  2730. weight_1.b = a[vertex_i * weights_8_count + 6];
  2731. weight_1.a = a[vertex_i * weights_8_count + 7];
  2732. float divisor = weight_0.r + weight_0.g + weight_0.b + weight_0.a + weight_1.r + weight_1.g + weight_1.b + weight_1.a;
  2733. if (Math::is_zero_approx(divisor) || !Math::is_finite(divisor)) {
  2734. divisor = 1.0f;
  2735. weight_0 = Color(1, 0, 0, 0);
  2736. weight_1 = Color(0, 0, 0, 0);
  2737. }
  2738. weights_0.write[vertex_i] = weight_0 / divisor;
  2739. weights_1.write[vertex_i] = weight_1 / divisor;
  2740. }
  2741. attributes["WEIGHTS_0"] = _encode_accessor_as_weights(p_state, weights_0, true);
  2742. attributes["WEIGHTS_1"] = _encode_accessor_as_weights(p_state, weights_1, true);
  2743. }
  2744. }
  2745. {
  2746. Vector<int32_t> mesh_indices = array[Mesh::ARRAY_INDEX];
  2747. if (mesh_indices.size()) {
  2748. if (primitive_type == Mesh::PRIMITIVE_TRIANGLES) {
  2749. // Swap around indices, convert ccw to cw for front face.
  2750. const int is = mesh_indices.size();
  2751. for (int k = 0; k < is; k += 3) {
  2752. SWAP(mesh_indices.write[k + 0], mesh_indices.write[k + 2]);
  2753. }
  2754. }
  2755. primitive["indices"] = _encode_accessor_as_ints(p_state, mesh_indices, false, true);
  2756. } else {
  2757. if (primitive_type == Mesh::PRIMITIVE_TRIANGLES) {
  2758. // Generate indices because they need to be swapped for CW/CCW.
  2759. const Vector<Vector3> &vertices = array[Mesh::ARRAY_VERTEX];
  2760. Ref<SurfaceTool> st;
  2761. st.instantiate();
  2762. st->create_from_triangle_arrays(array);
  2763. st->index();
  2764. Vector<int32_t> generated_indices = st->commit_to_arrays()[Mesh::ARRAY_INDEX];
  2765. const int vs = vertices.size();
  2766. generated_indices.resize(vs);
  2767. {
  2768. for (int k = 0; k < vs; k += 3) {
  2769. generated_indices.write[k] = k;
  2770. generated_indices.write[k + 1] = k + 2;
  2771. generated_indices.write[k + 2] = k + 1;
  2772. }
  2773. }
  2774. primitive["indices"] = _encode_accessor_as_ints(p_state, generated_indices, false, true);
  2775. }
  2776. }
  2777. }
  2778. primitive["attributes"] = attributes;
  2779. // Blend shapes
  2780. print_verbose("glTF: Mesh has targets");
  2781. if (import_mesh->get_blend_shape_count()) {
  2782. ArrayMesh::BlendShapeMode shape_mode = import_mesh->get_blend_shape_mode();
  2783. const float normal_tangent_sparse_rounding = 0.001;
  2784. for (int morph_i = 0; morph_i < import_mesh->get_blend_shape_count(); morph_i++) {
  2785. Array array_morph = import_mesh->get_surface_blend_shape_arrays(surface_i, morph_i);
  2786. Dictionary t;
  2787. Vector<Vector3> varr = array_morph[Mesh::ARRAY_VERTEX];
  2788. Vector<Vector3> src_varr = array[Mesh::ARRAY_VERTEX];
  2789. Array mesh_arrays = import_mesh->get_surface_arrays(surface_i);
  2790. if (varr.size() && varr.size() == src_varr.size()) {
  2791. if (shape_mode == ArrayMesh::BlendShapeMode::BLEND_SHAPE_MODE_NORMALIZED) {
  2792. const int max_idx = src_varr.size();
  2793. for (int blend_i = 0; blend_i < max_idx; blend_i++) {
  2794. varr.write[blend_i] = varr[blend_i] - src_varr[blend_i];
  2795. }
  2796. }
  2797. GLTFAccessorIndex position_accessor = attributes["POSITION"];
  2798. if (position_accessor != -1) {
  2799. int new_accessor = _encode_sparse_accessor_as_vec3(p_state, varr, Vector<Vector3>(), 1.0, true, -1);
  2800. if (new_accessor != -1) {
  2801. t["POSITION"] = new_accessor;
  2802. }
  2803. }
  2804. }
  2805. Vector<Vector3> narr = array_morph[Mesh::ARRAY_NORMAL];
  2806. Vector<Vector3> src_narr = array[Mesh::ARRAY_NORMAL];
  2807. if (narr.size() && narr.size() == src_narr.size()) {
  2808. if (shape_mode == ArrayMesh::BlendShapeMode::BLEND_SHAPE_MODE_NORMALIZED) {
  2809. const int max_idx = src_narr.size();
  2810. for (int blend_i = 0; blend_i < max_idx; blend_i++) {
  2811. narr.write[blend_i] = narr[blend_i] - src_narr[blend_i];
  2812. }
  2813. }
  2814. GLTFAccessorIndex normal_accessor = attributes["NORMAL"];
  2815. if (normal_accessor != -1) {
  2816. int new_accessor = _encode_sparse_accessor_as_vec3(p_state, narr, Vector<Vector3>(), normal_tangent_sparse_rounding, true, -1);
  2817. if (new_accessor != -1) {
  2818. t["NORMAL"] = new_accessor;
  2819. }
  2820. }
  2821. }
  2822. Vector<real_t> tarr = array_morph[Mesh::ARRAY_TANGENT];
  2823. Vector<real_t> src_tarr = array[Mesh::ARRAY_TANGENT];
  2824. if (tarr.size() && tarr.size() == src_tarr.size()) {
  2825. const int ret_size = tarr.size() / 4;
  2826. Vector<Vector3> attribs;
  2827. attribs.resize(ret_size);
  2828. for (int i = 0; i < ret_size; i++) {
  2829. Vector3 vec3;
  2830. vec3.x = tarr[(i * 4) + 0] - src_tarr[(i * 4) + 0];
  2831. vec3.y = tarr[(i * 4) + 1] - src_tarr[(i * 4) + 1];
  2832. vec3.z = tarr[(i * 4) + 2] - src_tarr[(i * 4) + 2];
  2833. attribs.write[i] = vec3;
  2834. }
  2835. GLTFAccessorIndex tangent_accessor = attributes["TANGENT"];
  2836. if (tangent_accessor != -1) {
  2837. int new_accessor = _encode_sparse_accessor_as_vec3(p_state, attribs, Vector<Vector3>(), normal_tangent_sparse_rounding, true, -1);
  2838. if (new_accessor != -1) {
  2839. t["TANGENT"] = new_accessor;
  2840. }
  2841. }
  2842. }
  2843. targets.push_back(t);
  2844. }
  2845. }
  2846. Variant v;
  2847. if (surface_i < instance_materials.size()) {
  2848. v = instance_materials.get(surface_i);
  2849. }
  2850. Ref<Material> mat = v;
  2851. if (mat.is_null()) {
  2852. mat = import_mesh->get_surface_material(surface_i);
  2853. }
  2854. if (mat.is_valid()) {
  2855. HashMap<Ref<Material>, GLTFMaterialIndex>::Iterator material_cache_i = p_state->material_cache.find(mat);
  2856. if (material_cache_i && material_cache_i->value != -1) {
  2857. primitive["material"] = material_cache_i->value;
  2858. } else {
  2859. GLTFMaterialIndex mat_i = p_state->materials.size();
  2860. p_state->materials.push_back(mat);
  2861. primitive["material"] = mat_i;
  2862. p_state->material_cache.insert(mat, mat_i);
  2863. }
  2864. }
  2865. if (targets.size()) {
  2866. primitive["targets"] = targets;
  2867. }
  2868. primitives.push_back(primitive);
  2869. }
  2870. Dictionary e;
  2871. e["targetNames"] = target_names;
  2872. gltf_mesh["extras"] = e;
  2873. _attach_meta_to_extras(import_mesh, gltf_mesh);
  2874. weights.resize(target_names.size());
  2875. for (int name_i = 0; name_i < target_names.size(); name_i++) {
  2876. real_t weight = 0.0;
  2877. if (name_i < p_state->meshes.write[gltf_mesh_i]->get_blend_weights().size()) {
  2878. weight = p_state->meshes.write[gltf_mesh_i]->get_blend_weights()[name_i];
  2879. }
  2880. weights[name_i] = weight;
  2881. }
  2882. if (weights.size()) {
  2883. gltf_mesh["weights"] = weights;
  2884. }
  2885. ERR_FAIL_COND_V(target_names.size() != weights.size(), FAILED);
  2886. gltf_mesh["primitives"] = primitives;
  2887. meshes.push_back(gltf_mesh);
  2888. }
  2889. if (!meshes.size()) {
  2890. return OK;
  2891. }
  2892. p_state->json["meshes"] = meshes;
  2893. print_verbose("glTF: Total meshes: " + itos(meshes.size()));
  2894. return OK;
  2895. }
  2896. Error GLTFDocument::_parse_meshes(Ref<GLTFState> p_state) {
  2897. if (!p_state->json.has("meshes")) {
  2898. return OK;
  2899. }
  2900. Array meshes = p_state->json["meshes"];
  2901. for (GLTFMeshIndex i = 0; i < meshes.size(); i++) {
  2902. print_verbose("glTF: Parsing mesh: " + itos(i));
  2903. Dictionary mesh_dict = meshes[i];
  2904. Ref<GLTFMesh> mesh;
  2905. mesh.instantiate();
  2906. bool has_vertex_color = false;
  2907. ERR_FAIL_COND_V(!mesh_dict.has("primitives"), ERR_PARSE_ERROR);
  2908. Array primitives = mesh_dict["primitives"];
  2909. const Dictionary &extras = mesh_dict.has("extras") ? (Dictionary)mesh_dict["extras"] : Dictionary();
  2910. _attach_extras_to_meta(extras, mesh);
  2911. Ref<ImporterMesh> import_mesh;
  2912. import_mesh.instantiate();
  2913. String mesh_name = "mesh";
  2914. if (mesh_dict.has("name") && !String(mesh_dict["name"]).is_empty()) {
  2915. mesh_name = mesh_dict["name"];
  2916. mesh->set_original_name(mesh_name);
  2917. }
  2918. import_mesh->set_name(_gen_unique_name(p_state, vformat("%s_%s", p_state->scene_name, mesh_name)));
  2919. mesh->set_name(import_mesh->get_name());
  2920. TypedArray<Material> instance_materials;
  2921. for (int j = 0; j < primitives.size(); j++) {
  2922. uint64_t flags = RS::ARRAY_FLAG_COMPRESS_ATTRIBUTES;
  2923. Dictionary mesh_prim = primitives[j];
  2924. Array array;
  2925. array.resize(Mesh::ARRAY_MAX);
  2926. ERR_FAIL_COND_V(!mesh_prim.has("attributes"), ERR_PARSE_ERROR);
  2927. Dictionary a = mesh_prim["attributes"];
  2928. Mesh::PrimitiveType primitive = Mesh::PRIMITIVE_TRIANGLES;
  2929. if (mesh_prim.has("mode")) {
  2930. const int mode = mesh_prim["mode"];
  2931. ERR_FAIL_INDEX_V(mode, 7, ERR_FILE_CORRUPT);
  2932. // Convert mesh.primitive.mode to Godot Mesh enum. See:
  2933. // https://www.khronos.org/registry/glTF/specs/2.0/glTF-2.0.html#_mesh_primitive_mode
  2934. static const Mesh::PrimitiveType primitives2[7] = {
  2935. Mesh::PRIMITIVE_POINTS, // 0 POINTS
  2936. Mesh::PRIMITIVE_LINES, // 1 LINES
  2937. Mesh::PRIMITIVE_LINES, // 2 LINE_LOOP; loop not supported, should be converted
  2938. Mesh::PRIMITIVE_LINE_STRIP, // 3 LINE_STRIP
  2939. Mesh::PRIMITIVE_TRIANGLES, // 4 TRIANGLES
  2940. Mesh::PRIMITIVE_TRIANGLE_STRIP, // 5 TRIANGLE_STRIP
  2941. Mesh::PRIMITIVE_TRIANGLES, // 6 TRIANGLE_FAN fan not supported, should be converted
  2942. // TODO: Line loop and triangle fan are not supported and need to be converted to lines and triangles.
  2943. };
  2944. primitive = primitives2[mode];
  2945. }
  2946. int32_t orig_vertex_num = 0;
  2947. ERR_FAIL_COND_V(!a.has("POSITION"), ERR_PARSE_ERROR);
  2948. if (a.has("POSITION")) {
  2949. PackedVector3Array vertices = _decode_accessor_as_vec3(p_state, a["POSITION"], true);
  2950. array[Mesh::ARRAY_VERTEX] = vertices;
  2951. orig_vertex_num = vertices.size();
  2952. }
  2953. int32_t vertex_num = orig_vertex_num;
  2954. Vector<int> indices;
  2955. Vector<int> indices_mapping;
  2956. Vector<int> indices_rev_mapping;
  2957. Vector<int> indices_vec4_mapping;
  2958. if (mesh_prim.has("indices")) {
  2959. indices = _decode_accessor_as_ints(p_state, mesh_prim["indices"], false);
  2960. const int is = indices.size();
  2961. if (primitive == Mesh::PRIMITIVE_TRIANGLES) {
  2962. // Swap around indices, convert ccw to cw for front face.
  2963. int *w = indices.ptrw();
  2964. for (int k = 0; k < is; k += 3) {
  2965. SWAP(w[k + 1], w[k + 2]);
  2966. }
  2967. }
  2968. const int *indices_w = indices.ptrw();
  2969. Vector<bool> used_indices;
  2970. used_indices.resize_zeroed(orig_vertex_num);
  2971. bool *used_w = used_indices.ptrw();
  2972. for (int idx_i = 0; idx_i < is; idx_i++) {
  2973. ERR_FAIL_INDEX_V(indices_w[idx_i], orig_vertex_num, ERR_INVALID_DATA);
  2974. used_w[indices_w[idx_i]] = true;
  2975. }
  2976. indices_rev_mapping.resize_zeroed(orig_vertex_num);
  2977. int *rev_w = indices_rev_mapping.ptrw();
  2978. vertex_num = 0;
  2979. for (int vert_i = 0; vert_i < orig_vertex_num; vert_i++) {
  2980. if (used_w[vert_i]) {
  2981. rev_w[vert_i] = indices_mapping.size();
  2982. indices_mapping.push_back(vert_i);
  2983. indices_vec4_mapping.push_back(vert_i * 4 + 0);
  2984. indices_vec4_mapping.push_back(vert_i * 4 + 1);
  2985. indices_vec4_mapping.push_back(vert_i * 4 + 2);
  2986. indices_vec4_mapping.push_back(vert_i * 4 + 3);
  2987. vertex_num++;
  2988. }
  2989. }
  2990. }
  2991. ERR_FAIL_COND_V(vertex_num <= 0, ERR_INVALID_DECLARATION);
  2992. if (a.has("POSITION")) {
  2993. PackedVector3Array vertices = _decode_accessor_as_vec3(p_state, a["POSITION"], true, indices_mapping);
  2994. array[Mesh::ARRAY_VERTEX] = vertices;
  2995. }
  2996. if (a.has("NORMAL")) {
  2997. array[Mesh::ARRAY_NORMAL] = _decode_accessor_as_vec3(p_state, a["NORMAL"], true, indices_mapping);
  2998. }
  2999. if (a.has("TANGENT")) {
  3000. array[Mesh::ARRAY_TANGENT] = _decode_accessor_as_floats(p_state, a["TANGENT"], true, indices_vec4_mapping);
  3001. }
  3002. if (a.has("TEXCOORD_0")) {
  3003. array[Mesh::ARRAY_TEX_UV] = _decode_accessor_as_vec2(p_state, a["TEXCOORD_0"], true, indices_mapping);
  3004. }
  3005. if (a.has("TEXCOORD_1")) {
  3006. array[Mesh::ARRAY_TEX_UV2] = _decode_accessor_as_vec2(p_state, a["TEXCOORD_1"], true, indices_mapping);
  3007. }
  3008. for (int custom_i = 0; custom_i < 3; custom_i++) {
  3009. Vector<float> cur_custom;
  3010. Vector<Vector2> texcoord_first;
  3011. Vector<Vector2> texcoord_second;
  3012. int texcoord_i = 2 + 2 * custom_i;
  3013. String gltf_texcoord_key = vformat("TEXCOORD_%d", texcoord_i);
  3014. int num_channels = 0;
  3015. if (a.has(gltf_texcoord_key)) {
  3016. texcoord_first = _decode_accessor_as_vec2(p_state, a[gltf_texcoord_key], true, indices_mapping);
  3017. num_channels = 2;
  3018. }
  3019. gltf_texcoord_key = vformat("TEXCOORD_%d", texcoord_i + 1);
  3020. if (a.has(gltf_texcoord_key)) {
  3021. texcoord_second = _decode_accessor_as_vec2(p_state, a[gltf_texcoord_key], true, indices_mapping);
  3022. num_channels = 4;
  3023. }
  3024. if (!num_channels) {
  3025. break;
  3026. }
  3027. if (num_channels == 2 || num_channels == 4) {
  3028. cur_custom.resize(vertex_num * num_channels);
  3029. for (int32_t uv_i = 0; uv_i < texcoord_first.size() && uv_i < vertex_num; uv_i++) {
  3030. cur_custom.write[uv_i * num_channels + 0] = texcoord_first[uv_i].x;
  3031. cur_custom.write[uv_i * num_channels + 1] = texcoord_first[uv_i].y;
  3032. }
  3033. // Vector.resize seems to not zero-initialize. Ensure all unused elements are 0:
  3034. for (int32_t uv_i = texcoord_first.size(); uv_i < vertex_num; uv_i++) {
  3035. cur_custom.write[uv_i * num_channels + 0] = 0;
  3036. cur_custom.write[uv_i * num_channels + 1] = 0;
  3037. }
  3038. }
  3039. if (num_channels == 4) {
  3040. for (int32_t uv_i = 0; uv_i < texcoord_second.size() && uv_i < vertex_num; uv_i++) {
  3041. // num_channels must be 4
  3042. cur_custom.write[uv_i * num_channels + 2] = texcoord_second[uv_i].x;
  3043. cur_custom.write[uv_i * num_channels + 3] = texcoord_second[uv_i].y;
  3044. }
  3045. // Vector.resize seems to not zero-initialize. Ensure all unused elements are 0:
  3046. for (int32_t uv_i = texcoord_second.size(); uv_i < vertex_num; uv_i++) {
  3047. cur_custom.write[uv_i * num_channels + 2] = 0;
  3048. cur_custom.write[uv_i * num_channels + 3] = 0;
  3049. }
  3050. }
  3051. if (cur_custom.size() > 0) {
  3052. array[Mesh::ARRAY_CUSTOM0 + custom_i] = cur_custom;
  3053. int custom_shift = Mesh::ARRAY_FORMAT_CUSTOM0_SHIFT + custom_i * Mesh::ARRAY_FORMAT_CUSTOM_BITS;
  3054. if (num_channels == 2) {
  3055. flags |= Mesh::ARRAY_CUSTOM_RG_FLOAT << custom_shift;
  3056. } else {
  3057. flags |= Mesh::ARRAY_CUSTOM_RGBA_FLOAT << custom_shift;
  3058. }
  3059. }
  3060. }
  3061. if (a.has("COLOR_0")) {
  3062. array[Mesh::ARRAY_COLOR] = _decode_accessor_as_color(p_state, a["COLOR_0"], true, indices_mapping);
  3063. has_vertex_color = true;
  3064. }
  3065. if (a.has("JOINTS_0") && !a.has("JOINTS_1")) {
  3066. PackedInt32Array joints_0 = _decode_accessor_as_ints(p_state, a["JOINTS_0"], true, indices_vec4_mapping);
  3067. ERR_FAIL_COND_V(joints_0.size() != 4 * vertex_num, ERR_INVALID_DATA);
  3068. array[Mesh::ARRAY_BONES] = joints_0;
  3069. } else if (a.has("JOINTS_0") && a.has("JOINTS_1")) {
  3070. PackedInt32Array joints_0 = _decode_accessor_as_ints(p_state, a["JOINTS_0"], true, indices_vec4_mapping);
  3071. PackedInt32Array joints_1 = _decode_accessor_as_ints(p_state, a["JOINTS_1"], true, indices_vec4_mapping);
  3072. ERR_FAIL_COND_V(joints_0.size() != joints_1.size(), ERR_INVALID_DATA);
  3073. ERR_FAIL_COND_V(joints_0.size() != 4 * vertex_num, ERR_INVALID_DATA);
  3074. int32_t weight_8_count = JOINT_GROUP_SIZE * 2;
  3075. Vector<int> joints;
  3076. joints.resize(vertex_num * weight_8_count);
  3077. for (int32_t vertex_i = 0; vertex_i < vertex_num; vertex_i++) {
  3078. joints.write[vertex_i * weight_8_count + 0] = joints_0[vertex_i * JOINT_GROUP_SIZE + 0];
  3079. joints.write[vertex_i * weight_8_count + 1] = joints_0[vertex_i * JOINT_GROUP_SIZE + 1];
  3080. joints.write[vertex_i * weight_8_count + 2] = joints_0[vertex_i * JOINT_GROUP_SIZE + 2];
  3081. joints.write[vertex_i * weight_8_count + 3] = joints_0[vertex_i * JOINT_GROUP_SIZE + 3];
  3082. joints.write[vertex_i * weight_8_count + 4] = joints_1[vertex_i * JOINT_GROUP_SIZE + 0];
  3083. joints.write[vertex_i * weight_8_count + 5] = joints_1[vertex_i * JOINT_GROUP_SIZE + 1];
  3084. joints.write[vertex_i * weight_8_count + 6] = joints_1[vertex_i * JOINT_GROUP_SIZE + 2];
  3085. joints.write[vertex_i * weight_8_count + 7] = joints_1[vertex_i * JOINT_GROUP_SIZE + 3];
  3086. }
  3087. array[Mesh::ARRAY_BONES] = joints;
  3088. }
  3089. if (a.has("WEIGHTS_0") && !a.has("WEIGHTS_1")) {
  3090. Vector<float> weights = _decode_accessor_as_floats(p_state, a["WEIGHTS_0"], true, indices_vec4_mapping);
  3091. ERR_FAIL_COND_V(weights.size() != 4 * vertex_num, ERR_INVALID_DATA);
  3092. { // glTF does not seem to normalize the weights for some reason.
  3093. int wc = weights.size();
  3094. float *w = weights.ptrw();
  3095. for (int k = 0; k < wc; k += 4) {
  3096. float total = 0.0;
  3097. total += w[k + 0];
  3098. total += w[k + 1];
  3099. total += w[k + 2];
  3100. total += w[k + 3];
  3101. if (total > 0.0) {
  3102. w[k + 0] /= total;
  3103. w[k + 1] /= total;
  3104. w[k + 2] /= total;
  3105. w[k + 3] /= total;
  3106. }
  3107. }
  3108. }
  3109. array[Mesh::ARRAY_WEIGHTS] = weights;
  3110. } else if (a.has("WEIGHTS_0") && a.has("WEIGHTS_1")) {
  3111. Vector<float> weights_0 = _decode_accessor_as_floats(p_state, a["WEIGHTS_0"], true, indices_vec4_mapping);
  3112. Vector<float> weights_1 = _decode_accessor_as_floats(p_state, a["WEIGHTS_1"], true, indices_vec4_mapping);
  3113. Vector<float> weights;
  3114. ERR_FAIL_COND_V(weights_0.size() != weights_1.size(), ERR_INVALID_DATA);
  3115. ERR_FAIL_COND_V(weights_0.size() != 4 * vertex_num, ERR_INVALID_DATA);
  3116. int32_t weight_8_count = JOINT_GROUP_SIZE * 2;
  3117. weights.resize(vertex_num * weight_8_count);
  3118. for (int32_t vertex_i = 0; vertex_i < vertex_num; vertex_i++) {
  3119. weights.write[vertex_i * weight_8_count + 0] = weights_0[vertex_i * JOINT_GROUP_SIZE + 0];
  3120. weights.write[vertex_i * weight_8_count + 1] = weights_0[vertex_i * JOINT_GROUP_SIZE + 1];
  3121. weights.write[vertex_i * weight_8_count + 2] = weights_0[vertex_i * JOINT_GROUP_SIZE + 2];
  3122. weights.write[vertex_i * weight_8_count + 3] = weights_0[vertex_i * JOINT_GROUP_SIZE + 3];
  3123. weights.write[vertex_i * weight_8_count + 4] = weights_1[vertex_i * JOINT_GROUP_SIZE + 0];
  3124. weights.write[vertex_i * weight_8_count + 5] = weights_1[vertex_i * JOINT_GROUP_SIZE + 1];
  3125. weights.write[vertex_i * weight_8_count + 6] = weights_1[vertex_i * JOINT_GROUP_SIZE + 2];
  3126. weights.write[vertex_i * weight_8_count + 7] = weights_1[vertex_i * JOINT_GROUP_SIZE + 3];
  3127. }
  3128. { // glTF does not seem to normalize the weights for some reason.
  3129. int wc = weights.size();
  3130. float *w = weights.ptrw();
  3131. for (int k = 0; k < wc; k += weight_8_count) {
  3132. float total = 0.0;
  3133. total += w[k + 0];
  3134. total += w[k + 1];
  3135. total += w[k + 2];
  3136. total += w[k + 3];
  3137. total += w[k + 4];
  3138. total += w[k + 5];
  3139. total += w[k + 6];
  3140. total += w[k + 7];
  3141. if (total > 0.0) {
  3142. w[k + 0] /= total;
  3143. w[k + 1] /= total;
  3144. w[k + 2] /= total;
  3145. w[k + 3] /= total;
  3146. w[k + 4] /= total;
  3147. w[k + 5] /= total;
  3148. w[k + 6] /= total;
  3149. w[k + 7] /= total;
  3150. }
  3151. }
  3152. }
  3153. array[Mesh::ARRAY_WEIGHTS] = weights;
  3154. flags |= Mesh::ARRAY_FLAG_USE_8_BONE_WEIGHTS;
  3155. }
  3156. if (!indices.is_empty()) {
  3157. int *w = indices.ptrw();
  3158. const int is = indices.size();
  3159. for (int ind_i = 0; ind_i < is; ind_i++) {
  3160. w[ind_i] = indices_rev_mapping[indices[ind_i]];
  3161. }
  3162. array[Mesh::ARRAY_INDEX] = indices;
  3163. } else if (primitive == Mesh::PRIMITIVE_TRIANGLES) {
  3164. // Generate indices because they need to be swapped for CW/CCW.
  3165. const Vector<Vector3> &vertices = array[Mesh::ARRAY_VERTEX];
  3166. ERR_FAIL_COND_V(vertices.is_empty(), ERR_PARSE_ERROR);
  3167. const int vs = vertices.size();
  3168. indices.resize(vs);
  3169. {
  3170. int *w = indices.ptrw();
  3171. for (int k = 0; k < vs; k += 3) {
  3172. w[k] = k;
  3173. w[k + 1] = k + 2;
  3174. w[k + 2] = k + 1;
  3175. }
  3176. }
  3177. array[Mesh::ARRAY_INDEX] = indices;
  3178. }
  3179. bool generate_tangents = p_state->force_generate_tangents && (primitive == Mesh::PRIMITIVE_TRIANGLES && !a.has("TANGENT") && a.has("NORMAL"));
  3180. if (generate_tangents && !a.has("TEXCOORD_0")) {
  3181. // If we don't have UVs we provide a dummy tangent array.
  3182. Vector<float> tangents;
  3183. tangents.resize(vertex_num * 4);
  3184. float *tangentsw = tangents.ptrw();
  3185. Vector<Vector3> normals = array[Mesh::ARRAY_NORMAL];
  3186. for (int k = 0; k < vertex_num; k++) {
  3187. Vector3 tan = Vector3(normals[k].z, -normals[k].x, normals[k].y).cross(normals[k].normalized()).normalized();
  3188. tangentsw[k * 4 + 0] = tan.x;
  3189. tangentsw[k * 4 + 1] = tan.y;
  3190. tangentsw[k * 4 + 2] = tan.z;
  3191. tangentsw[k * 4 + 3] = 1.0;
  3192. }
  3193. array[Mesh::ARRAY_TANGENT] = tangents;
  3194. }
  3195. // Disable compression if all z equals 0 (the mesh is 2D).
  3196. const Vector<Vector3> &vertices = array[Mesh::ARRAY_VERTEX];
  3197. bool is_mesh_2d = true;
  3198. for (int k = 0; k < vertices.size(); k++) {
  3199. if (!Math::is_zero_approx(vertices[k].z)) {
  3200. is_mesh_2d = false;
  3201. break;
  3202. }
  3203. }
  3204. if (p_state->force_disable_compression || is_mesh_2d || !a.has("POSITION") || !a.has("NORMAL") || mesh_prim.has("targets") || (a.has("JOINTS_0") || a.has("JOINTS_1"))) {
  3205. flags &= ~RS::ARRAY_FLAG_COMPRESS_ATTRIBUTES;
  3206. }
  3207. Ref<SurfaceTool> mesh_surface_tool;
  3208. mesh_surface_tool.instantiate();
  3209. mesh_surface_tool->create_from_triangle_arrays(array);
  3210. if (a.has("JOINTS_0") && a.has("JOINTS_1")) {
  3211. mesh_surface_tool->set_skin_weight_count(SurfaceTool::SKIN_8_WEIGHTS);
  3212. }
  3213. mesh_surface_tool->index();
  3214. if (generate_tangents && a.has("TEXCOORD_0")) {
  3215. //must generate mikktspace tangents.. ergh..
  3216. mesh_surface_tool->generate_tangents();
  3217. }
  3218. array = mesh_surface_tool->commit_to_arrays();
  3219. if ((flags & RS::ARRAY_FLAG_COMPRESS_ATTRIBUTES) && a.has("NORMAL") && (a.has("TANGENT") || generate_tangents)) {
  3220. // Compression is enabled, so let's validate that the normals and tangents are correct.
  3221. Vector<Vector3> normals = array[Mesh::ARRAY_NORMAL];
  3222. Vector<float> tangents = array[Mesh::ARRAY_TANGENT];
  3223. for (int vert = 0; vert < normals.size(); vert++) {
  3224. Vector3 tan = Vector3(tangents[vert * 4 + 0], tangents[vert * 4 + 1], tangents[vert * 4 + 2]);
  3225. if (abs(tan.dot(normals[vert])) > 0.0001) {
  3226. // Tangent is not perpendicular to the normal, so we can't use compression.
  3227. flags &= ~RS::ARRAY_FLAG_COMPRESS_ATTRIBUTES;
  3228. }
  3229. }
  3230. }
  3231. Array morphs;
  3232. // Blend shapes
  3233. if (mesh_prim.has("targets")) {
  3234. print_verbose("glTF: Mesh has targets");
  3235. const Array &targets = mesh_prim["targets"];
  3236. import_mesh->set_blend_shape_mode(Mesh::BLEND_SHAPE_MODE_NORMALIZED);
  3237. if (j == 0) {
  3238. const Array &target_names = extras.has("targetNames") ? (Array)extras["targetNames"] : Array();
  3239. for (int k = 0; k < targets.size(); k++) {
  3240. String bs_name;
  3241. if (k < target_names.size() && ((String)target_names[k]).size() != 0) {
  3242. bs_name = (String)target_names[k];
  3243. } else {
  3244. bs_name = String("morph_") + itos(k);
  3245. }
  3246. import_mesh->add_blend_shape(bs_name);
  3247. }
  3248. }
  3249. for (int k = 0; k < targets.size(); k++) {
  3250. const Dictionary &t = targets[k];
  3251. Array array_copy;
  3252. array_copy.resize(Mesh::ARRAY_MAX);
  3253. for (int l = 0; l < Mesh::ARRAY_MAX; l++) {
  3254. array_copy[l] = array[l];
  3255. }
  3256. if (t.has("POSITION")) {
  3257. Vector<Vector3> varr = _decode_accessor_as_vec3(p_state, t["POSITION"], true, indices_mapping);
  3258. const Vector<Vector3> src_varr = array[Mesh::ARRAY_VERTEX];
  3259. const int size = src_varr.size();
  3260. ERR_FAIL_COND_V(size == 0, ERR_PARSE_ERROR);
  3261. {
  3262. const int max_idx = varr.size();
  3263. varr.resize(size);
  3264. Vector3 *w_varr = varr.ptrw();
  3265. const Vector3 *r_varr = varr.ptr();
  3266. const Vector3 *r_src_varr = src_varr.ptr();
  3267. for (int l = 0; l < size; l++) {
  3268. if (l < max_idx) {
  3269. w_varr[l] = r_varr[l] + r_src_varr[l];
  3270. } else {
  3271. w_varr[l] = r_src_varr[l];
  3272. }
  3273. }
  3274. }
  3275. array_copy[Mesh::ARRAY_VERTEX] = varr;
  3276. }
  3277. if (t.has("NORMAL")) {
  3278. Vector<Vector3> narr = _decode_accessor_as_vec3(p_state, t["NORMAL"], true, indices_mapping);
  3279. const Vector<Vector3> src_narr = array[Mesh::ARRAY_NORMAL];
  3280. int size = src_narr.size();
  3281. ERR_FAIL_COND_V(size == 0, ERR_PARSE_ERROR);
  3282. {
  3283. int max_idx = narr.size();
  3284. narr.resize(size);
  3285. Vector3 *w_narr = narr.ptrw();
  3286. const Vector3 *r_narr = narr.ptr();
  3287. const Vector3 *r_src_narr = src_narr.ptr();
  3288. for (int l = 0; l < size; l++) {
  3289. if (l < max_idx) {
  3290. w_narr[l] = r_narr[l] + r_src_narr[l];
  3291. } else {
  3292. w_narr[l] = r_src_narr[l];
  3293. }
  3294. }
  3295. }
  3296. array_copy[Mesh::ARRAY_NORMAL] = narr;
  3297. }
  3298. if (t.has("TANGENT")) {
  3299. const Vector<Vector3> tangents_v3 = _decode_accessor_as_vec3(p_state, t["TANGENT"], true, indices_mapping);
  3300. const Vector<float> src_tangents = array[Mesh::ARRAY_TANGENT];
  3301. ERR_FAIL_COND_V(src_tangents.is_empty(), ERR_PARSE_ERROR);
  3302. Vector<float> tangents_v4;
  3303. {
  3304. int max_idx = tangents_v3.size();
  3305. int size4 = src_tangents.size();
  3306. tangents_v4.resize(size4);
  3307. float *w4 = tangents_v4.ptrw();
  3308. const Vector3 *r3 = tangents_v3.ptr();
  3309. const float *r4 = src_tangents.ptr();
  3310. for (int l = 0; l < size4 / 4; l++) {
  3311. if (l < max_idx) {
  3312. w4[l * 4 + 0] = r3[l].x + r4[l * 4 + 0];
  3313. w4[l * 4 + 1] = r3[l].y + r4[l * 4 + 1];
  3314. w4[l * 4 + 2] = r3[l].z + r4[l * 4 + 2];
  3315. } else {
  3316. w4[l * 4 + 0] = r4[l * 4 + 0];
  3317. w4[l * 4 + 1] = r4[l * 4 + 1];
  3318. w4[l * 4 + 2] = r4[l * 4 + 2];
  3319. }
  3320. w4[l * 4 + 3] = r4[l * 4 + 3]; //copy flip value
  3321. }
  3322. }
  3323. array_copy[Mesh::ARRAY_TANGENT] = tangents_v4;
  3324. }
  3325. Ref<SurfaceTool> blend_surface_tool;
  3326. blend_surface_tool.instantiate();
  3327. blend_surface_tool->create_from_triangle_arrays(array_copy);
  3328. if (a.has("JOINTS_0") && a.has("JOINTS_1")) {
  3329. blend_surface_tool->set_skin_weight_count(SurfaceTool::SKIN_8_WEIGHTS);
  3330. }
  3331. blend_surface_tool->index();
  3332. if (generate_tangents) {
  3333. blend_surface_tool->generate_tangents();
  3334. }
  3335. array_copy = blend_surface_tool->commit_to_arrays();
  3336. // Enforce blend shape mask array format
  3337. for (int l = 0; l < Mesh::ARRAY_MAX; l++) {
  3338. if (!(Mesh::ARRAY_FORMAT_BLEND_SHAPE_MASK & (1ULL << l))) {
  3339. array_copy[l] = Variant();
  3340. }
  3341. }
  3342. morphs.push_back(array_copy);
  3343. }
  3344. }
  3345. Ref<Material> mat;
  3346. String mat_name;
  3347. if (!p_state->discard_meshes_and_materials) {
  3348. if (mesh_prim.has("material")) {
  3349. const int material = mesh_prim["material"];
  3350. ERR_FAIL_INDEX_V(material, p_state->materials.size(), ERR_FILE_CORRUPT);
  3351. Ref<Material> mat3d = p_state->materials[material];
  3352. ERR_FAIL_COND_V(mat3d.is_null(), ERR_FILE_CORRUPT);
  3353. Ref<BaseMaterial3D> base_material = mat3d;
  3354. if (has_vertex_color && base_material.is_valid()) {
  3355. base_material->set_flag(BaseMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  3356. }
  3357. mat = mat3d;
  3358. } else {
  3359. Ref<StandardMaterial3D> mat3d;
  3360. mat3d.instantiate();
  3361. if (has_vertex_color) {
  3362. mat3d->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  3363. }
  3364. mat = mat3d;
  3365. }
  3366. ERR_FAIL_COND_V(mat.is_null(), ERR_FILE_CORRUPT);
  3367. instance_materials.append(mat);
  3368. mat_name = mat->get_name();
  3369. }
  3370. import_mesh->add_surface(primitive, array, morphs,
  3371. Dictionary(), mat, mat_name, flags);
  3372. }
  3373. Vector<float> blend_weights;
  3374. blend_weights.resize(import_mesh->get_blend_shape_count());
  3375. for (int32_t weight_i = 0; weight_i < blend_weights.size(); weight_i++) {
  3376. blend_weights.write[weight_i] = 0.0f;
  3377. }
  3378. if (mesh_dict.has("weights")) {
  3379. const Array &weights = mesh_dict["weights"];
  3380. for (int j = 0; j < weights.size(); j++) {
  3381. if (j >= blend_weights.size()) {
  3382. break;
  3383. }
  3384. blend_weights.write[j] = weights[j];
  3385. }
  3386. }
  3387. mesh->set_blend_weights(blend_weights);
  3388. mesh->set_instance_materials(instance_materials);
  3389. mesh->set_mesh(import_mesh);
  3390. p_state->meshes.push_back(mesh);
  3391. }
  3392. print_verbose("glTF: Total meshes: " + itos(p_state->meshes.size()));
  3393. return OK;
  3394. }
  3395. void GLTFDocument::set_naming_version(int p_version) {
  3396. _naming_version = p_version;
  3397. }
  3398. int GLTFDocument::get_naming_version() const {
  3399. return _naming_version;
  3400. }
  3401. void GLTFDocument::set_image_format(const String &p_image_format) {
  3402. _image_format = p_image_format;
  3403. }
  3404. String GLTFDocument::get_image_format() const {
  3405. return _image_format;
  3406. }
  3407. void GLTFDocument::set_lossy_quality(float p_lossy_quality) {
  3408. _lossy_quality = p_lossy_quality;
  3409. }
  3410. float GLTFDocument::get_lossy_quality() const {
  3411. return _lossy_quality;
  3412. }
  3413. Error GLTFDocument::_serialize_images(Ref<GLTFState> p_state) {
  3414. Array images;
  3415. // Check if any extension wants to be the image saver.
  3416. _image_save_extension = Ref<GLTFDocumentExtension>();
  3417. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  3418. ERR_CONTINUE(ext.is_null());
  3419. Vector<String> image_formats = ext->get_saveable_image_formats();
  3420. if (image_formats.has(_image_format)) {
  3421. _image_save_extension = ext;
  3422. break;
  3423. }
  3424. }
  3425. // Serialize every image in the state's images array.
  3426. for (int i = 0; i < p_state->images.size(); i++) {
  3427. Dictionary image_dict;
  3428. ERR_CONTINUE(p_state->images[i].is_null());
  3429. Ref<Image> image = p_state->images[i]->get_image();
  3430. ERR_CONTINUE(image.is_null());
  3431. if (image->is_compressed()) {
  3432. image->decompress();
  3433. ERR_FAIL_COND_V_MSG(image->is_compressed(), ERR_INVALID_DATA, "glTF: Image was compressed, but could not be decompressed.");
  3434. }
  3435. if (p_state->filename.to_lower().ends_with("gltf")) {
  3436. String img_name = p_state->images[i]->get_name();
  3437. if (img_name.is_empty()) {
  3438. img_name = itos(i);
  3439. }
  3440. img_name = _gen_unique_name(p_state, img_name);
  3441. img_name = img_name.pad_zeros(3);
  3442. String relative_texture_dir = "textures";
  3443. String full_texture_dir = p_state->base_path.path_join(relative_texture_dir);
  3444. Ref<DirAccess> da = DirAccess::open(p_state->base_path);
  3445. ERR_FAIL_COND_V(da.is_null(), FAILED);
  3446. if (!da->dir_exists(full_texture_dir)) {
  3447. da->make_dir(full_texture_dir);
  3448. }
  3449. if (_image_save_extension.is_valid()) {
  3450. img_name = img_name + _image_save_extension->get_image_file_extension();
  3451. Error err = _image_save_extension->save_image_at_path(p_state, image, full_texture_dir.path_join(img_name), _image_format, _lossy_quality);
  3452. ERR_FAIL_COND_V_MSG(err != OK, err, "glTF: Failed to save image in '" + _image_format + "' format as a separate file.");
  3453. } else if (_image_format == "PNG") {
  3454. img_name = img_name + ".png";
  3455. image->save_png(full_texture_dir.path_join(img_name));
  3456. } else if (_image_format == "JPEG") {
  3457. img_name = img_name + ".jpg";
  3458. image->save_jpg(full_texture_dir.path_join(img_name), _lossy_quality);
  3459. } else {
  3460. ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "glTF: Unknown image format '" + _image_format + "'.");
  3461. }
  3462. image_dict["uri"] = relative_texture_dir.path_join(img_name).uri_encode();
  3463. } else {
  3464. GLTFBufferViewIndex bvi;
  3465. Ref<GLTFBufferView> bv;
  3466. bv.instantiate();
  3467. const GLTFBufferIndex bi = 0;
  3468. bv->buffer = bi;
  3469. bv->byte_offset = p_state->buffers[bi].size();
  3470. ERR_FAIL_INDEX_V(bi, p_state->buffers.size(), ERR_PARAMETER_RANGE_ERROR);
  3471. Vector<uint8_t> buffer;
  3472. Ref<ImageTexture> img_tex = image;
  3473. if (img_tex.is_valid()) {
  3474. image = img_tex->get_image();
  3475. }
  3476. // Save in various image formats. Note that if the format is "None",
  3477. // the state's images will be empty, so this code will not be reached.
  3478. if (_image_save_extension.is_valid()) {
  3479. buffer = _image_save_extension->serialize_image_to_bytes(p_state, image, image_dict, _image_format, _lossy_quality);
  3480. } else if (_image_format == "PNG") {
  3481. buffer = image->save_png_to_buffer();
  3482. image_dict["mimeType"] = "image/png";
  3483. } else if (_image_format == "JPEG") {
  3484. buffer = image->save_jpg_to_buffer(_lossy_quality);
  3485. image_dict["mimeType"] = "image/jpeg";
  3486. } else {
  3487. ERR_FAIL_V_MSG(ERR_UNAVAILABLE, "glTF: Unknown image format '" + _image_format + "'.");
  3488. }
  3489. ERR_FAIL_COND_V_MSG(buffer.is_empty(), ERR_INVALID_DATA, "glTF: Failed to save image in '" + _image_format + "' format.");
  3490. bv->byte_length = buffer.size();
  3491. p_state->buffers.write[bi].resize(p_state->buffers[bi].size() + bv->byte_length);
  3492. memcpy(&p_state->buffers.write[bi].write[bv->byte_offset], buffer.ptr(), buffer.size());
  3493. ERR_FAIL_COND_V(bv->byte_offset + bv->byte_length > p_state->buffers[bi].size(), ERR_FILE_CORRUPT);
  3494. p_state->buffer_views.push_back(bv);
  3495. bvi = p_state->buffer_views.size() - 1;
  3496. image_dict["bufferView"] = bvi;
  3497. }
  3498. images.push_back(image_dict);
  3499. }
  3500. print_verbose("Total images: " + itos(p_state->images.size()));
  3501. if (!images.size()) {
  3502. return OK;
  3503. }
  3504. p_state->json["images"] = images;
  3505. return OK;
  3506. }
  3507. Ref<Image> GLTFDocument::_parse_image_bytes_into_image(Ref<GLTFState> p_state, const Vector<uint8_t> &p_bytes, const String &p_mime_type, int p_index, String &r_file_extension) {
  3508. Ref<Image> r_image;
  3509. r_image.instantiate();
  3510. // Check if any GLTFDocumentExtensions want to import this data as an image.
  3511. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  3512. ERR_CONTINUE(ext.is_null());
  3513. Error err = ext->parse_image_data(p_state, p_bytes, p_mime_type, r_image);
  3514. ERR_CONTINUE_MSG(err != OK, "glTF: Encountered error " + itos(err) + " when parsing image " + itos(p_index) + " in file " + p_state->filename + ". Continuing.");
  3515. if (!r_image->is_empty()) {
  3516. r_file_extension = ext->get_image_file_extension();
  3517. return r_image;
  3518. }
  3519. }
  3520. // If no extension wanted to import this data as an image, try to load a PNG or JPEG.
  3521. // First we honor the mime types if they were defined.
  3522. if (p_mime_type == "image/png") { // Load buffer as PNG.
  3523. r_image->load_png_from_buffer(p_bytes);
  3524. r_file_extension = ".png";
  3525. } else if (p_mime_type == "image/jpeg") { // Loader buffer as JPEG.
  3526. r_image->load_jpg_from_buffer(p_bytes);
  3527. r_file_extension = ".jpg";
  3528. }
  3529. // If we didn't pass the above tests, we attempt loading as PNG and then JPEG directly.
  3530. // This covers URIs with base64-encoded data with application/* type but
  3531. // no optional mimeType property, or bufferViews with a bogus mimeType
  3532. // (e.g. `image/jpeg` but the data is actually PNG).
  3533. // That's not *exactly* what the spec mandates but this lets us be
  3534. // lenient with bogus glb files which do exist in production.
  3535. if (r_image->is_empty()) { // Try PNG first.
  3536. r_image->load_png_from_buffer(p_bytes);
  3537. }
  3538. if (r_image->is_empty()) { // And then JPEG.
  3539. r_image->load_jpg_from_buffer(p_bytes);
  3540. }
  3541. // If it still can't be loaded, give up and insert an empty image as placeholder.
  3542. if (r_image->is_empty()) {
  3543. ERR_PRINT(vformat("glTF: Couldn't load image index '%d' with its given mimetype: %s.", p_index, p_mime_type));
  3544. }
  3545. return r_image;
  3546. }
  3547. void GLTFDocument::_parse_image_save_image(Ref<GLTFState> p_state, const Vector<uint8_t> &p_bytes, const String &p_resource_uri, const String &p_file_extension, int p_index, Ref<Image> p_image) {
  3548. GLTFState::GLTFHandleBinary handling = GLTFState::GLTFHandleBinary(p_state->handle_binary_image);
  3549. if (p_image->is_empty() || handling == GLTFState::GLTFHandleBinary::HANDLE_BINARY_DISCARD_TEXTURES) {
  3550. p_state->images.push_back(Ref<Texture2D>());
  3551. p_state->source_images.push_back(Ref<Image>());
  3552. return;
  3553. }
  3554. #ifdef TOOLS_ENABLED
  3555. if (Engine::get_singleton()->is_editor_hint() && handling == GLTFState::GLTFHandleBinary::HANDLE_BINARY_EXTRACT_TEXTURES) {
  3556. if (p_state->extract_path.is_empty()) {
  3557. WARN_PRINT("glTF: Couldn't extract image because the base and extract paths are empty. It will be loaded directly instead, uncompressed.");
  3558. } else if (p_state->extract_path.begins_with("res://.godot/imported")) {
  3559. WARN_PRINT(vformat("glTF: Extract path is in the imported directory. Image index '%d' will be loaded directly, uncompressed.", p_index));
  3560. } else {
  3561. if (p_image->get_name().is_empty()) {
  3562. WARN_PRINT(vformat("glTF: Image index '%d' did not have a name. It will be automatically given a name based on its index.", p_index));
  3563. p_image->set_name(itos(p_index));
  3564. }
  3565. bool must_write = true; // If the resource does not exist on the disk within res:// directory write it.
  3566. bool must_import = true; // Trigger import.
  3567. Vector<uint8_t> img_data = p_image->get_data();
  3568. Dictionary generator_parameters;
  3569. String file_path;
  3570. // If resource_uri is within res:// folder but outside of .godot/imported folder, use it.
  3571. if (!p_resource_uri.is_empty() && !p_resource_uri.begins_with("res://.godot/imported") && !p_resource_uri.begins_with("res://..")) {
  3572. file_path = p_resource_uri;
  3573. must_import = true;
  3574. must_write = !FileAccess::exists(file_path);
  3575. } else {
  3576. // Texture data has to be written to the res:// folder and imported.
  3577. file_path = p_state->get_extract_path().path_join(p_state->get_extract_prefix() + "_" + p_image->get_name());
  3578. file_path += p_file_extension.is_empty() ? ".png" : p_file_extension;
  3579. if (FileAccess::exists(file_path + ".import")) {
  3580. Ref<ConfigFile> config;
  3581. config.instantiate();
  3582. config->load(file_path + ".import");
  3583. if (config->has_section_key("remap", "generator_parameters")) {
  3584. generator_parameters = (Dictionary)config->get_value("remap", "generator_parameters");
  3585. }
  3586. if (!generator_parameters.has("md5")) {
  3587. must_write = false; // Didn't come from a gltf document; don't overwrite.
  3588. must_import = false; // And don't import.
  3589. }
  3590. }
  3591. }
  3592. if (must_write) {
  3593. String existing_md5 = generator_parameters["md5"];
  3594. unsigned char md5_hash[16];
  3595. CryptoCore::md5(img_data.ptr(), img_data.size(), md5_hash);
  3596. String new_md5 = String::hex_encode_buffer(md5_hash, 16);
  3597. generator_parameters["md5"] = new_md5;
  3598. if (new_md5 == existing_md5) {
  3599. must_write = false;
  3600. must_import = false;
  3601. }
  3602. }
  3603. if (must_write) {
  3604. Error err = OK;
  3605. if (p_file_extension.is_empty()) {
  3606. // If a file extension was not specified, save the image data to a PNG file.
  3607. err = p_image->save_png(file_path);
  3608. ERR_FAIL_COND(err != OK);
  3609. } else {
  3610. // If a file extension was specified, save the original bytes to a file with that extension.
  3611. Ref<FileAccess> file = FileAccess::open(file_path, FileAccess::WRITE, &err);
  3612. ERR_FAIL_COND(err != OK);
  3613. file->store_buffer(p_bytes);
  3614. file->close();
  3615. }
  3616. }
  3617. if (must_import) {
  3618. // ResourceLoader::import will crash if not is_editor_hint(), so this case is protected above and will fall through to uncompressed.
  3619. HashMap<StringName, Variant> custom_options;
  3620. custom_options[SNAME("mipmaps/generate")] = true;
  3621. // Will only use project settings defaults if custom_importer is empty.
  3622. EditorFileSystem::get_singleton()->update_file(file_path);
  3623. EditorFileSystem::get_singleton()->reimport_append(file_path, custom_options, String(), generator_parameters);
  3624. }
  3625. Ref<Texture2D> saved_image = ResourceLoader::load(file_path, "Texture2D");
  3626. if (saved_image.is_valid()) {
  3627. p_state->images.push_back(saved_image);
  3628. p_state->source_images.push_back(saved_image->get_image());
  3629. return;
  3630. } else {
  3631. WARN_PRINT(vformat("glTF: Image index '%d' with the name '%s' resolved to %s couldn't be imported. It will be loaded directly instead, uncompressed.", p_index, p_image->get_name(), file_path));
  3632. }
  3633. }
  3634. }
  3635. #endif // TOOLS_ENABLED
  3636. if (handling == GLTFState::GLTFHandleBinary::HANDLE_BINARY_EMBED_AS_BASISU) {
  3637. Ref<PortableCompressedTexture2D> tex;
  3638. tex.instantiate();
  3639. tex->set_name(p_image->get_name());
  3640. tex->set_keep_compressed_buffer(true);
  3641. tex->create_from_image(p_image, PortableCompressedTexture2D::COMPRESSION_MODE_BASIS_UNIVERSAL);
  3642. p_state->images.push_back(tex);
  3643. p_state->source_images.push_back(p_image);
  3644. return;
  3645. }
  3646. // This handles the case of HANDLE_BINARY_EMBED_AS_UNCOMPRESSED, and it also serves
  3647. // as a fallback for HANDLE_BINARY_EXTRACT_TEXTURES when this is not the editor.
  3648. Ref<ImageTexture> tex;
  3649. tex.instantiate();
  3650. tex->set_name(p_image->get_name());
  3651. tex->set_image(p_image);
  3652. p_state->images.push_back(tex);
  3653. p_state->source_images.push_back(p_image);
  3654. }
  3655. Error GLTFDocument::_parse_images(Ref<GLTFState> p_state, const String &p_base_path) {
  3656. ERR_FAIL_COND_V(p_state.is_null(), ERR_INVALID_PARAMETER);
  3657. if (!p_state->json.has("images")) {
  3658. return OK;
  3659. }
  3660. // Ref: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#images
  3661. const Array &images = p_state->json["images"];
  3662. HashSet<String> used_names;
  3663. for (int i = 0; i < images.size(); i++) {
  3664. const Dictionary &dict = images[i];
  3665. // glTF 2.0 supports PNG and JPEG types, which can be specified as (from spec):
  3666. // "- a URI to an external file in one of the supported images formats, or
  3667. // - a URI with embedded base64-encoded data, or
  3668. // - a reference to a bufferView; in that case mimeType must be defined."
  3669. // Since mimeType is optional for external files and base64 data, we'll have to
  3670. // fall back on letting Godot parse the data to figure out if it's PNG or JPEG.
  3671. // We'll assume that we use either URI or bufferView, so let's warn the user
  3672. // if their image somehow uses both. And fail if it has neither.
  3673. ERR_CONTINUE_MSG(!dict.has("uri") && !dict.has("bufferView"), "Invalid image definition in glTF file, it should specify an 'uri' or 'bufferView'.");
  3674. if (dict.has("uri") && dict.has("bufferView")) {
  3675. WARN_PRINT("Invalid image definition in glTF file using both 'uri' and 'bufferView'. 'uri' will take precedence.");
  3676. }
  3677. String mime_type;
  3678. if (dict.has("mimeType")) { // Should be "image/png", "image/jpeg", or something handled by an extension.
  3679. mime_type = dict["mimeType"];
  3680. }
  3681. String image_name;
  3682. if (dict.has("name")) {
  3683. image_name = dict["name"];
  3684. image_name = image_name.get_file().get_basename().validate_filename();
  3685. }
  3686. if (image_name.is_empty()) {
  3687. image_name = itos(i);
  3688. }
  3689. while (used_names.has(image_name)) {
  3690. image_name += "_" + itos(i);
  3691. }
  3692. String resource_uri;
  3693. used_names.insert(image_name);
  3694. // Load the image data. If we get a byte array, store here for later.
  3695. Vector<uint8_t> data;
  3696. if (dict.has("uri")) {
  3697. // Handles the first two bullet points from the spec (embedded data, or external file).
  3698. String uri = dict["uri"];
  3699. if (uri.begins_with("data:")) { // Embedded data using base64.
  3700. data = _parse_base64_uri(uri);
  3701. // mimeType is optional, but if we have it defined in the URI, let's use it.
  3702. if (mime_type.is_empty() && uri.contains_char(';')) {
  3703. // Trim "data:" prefix which is 5 characters long, and end at ";base64".
  3704. mime_type = uri.substr(5, uri.find(";base64") - 5);
  3705. }
  3706. } else { // Relative path to an external image file.
  3707. ERR_FAIL_COND_V(p_base_path.is_empty(), ERR_INVALID_PARAMETER);
  3708. uri = uri.uri_decode();
  3709. uri = p_base_path.path_join(uri).replace("\\", "/"); // Fix for Windows.
  3710. resource_uri = uri.simplify_path();
  3711. // ResourceLoader will rely on the file extension to use the relevant loader.
  3712. // The spec says that if mimeType is defined, it should take precedence (e.g.
  3713. // there could be a `.png` image which is actually JPEG), but there's no easy
  3714. // API for that in Godot, so we'd have to load as a buffer (i.e. embedded in
  3715. // the material), so we only do that only as fallback.
  3716. if (ResourceLoader::exists(resource_uri)) {
  3717. Ref<Texture2D> texture = ResourceLoader::load(resource_uri, "Texture2D");
  3718. if (texture.is_valid()) {
  3719. p_state->images.push_back(texture);
  3720. p_state->source_images.push_back(texture->get_image());
  3721. continue;
  3722. }
  3723. }
  3724. // mimeType is optional, but if we have it in the file extension, let's use it.
  3725. // If the mimeType does not match with the file extension, either it should be
  3726. // specified in the file, or the GLTFDocumentExtension should handle it.
  3727. if (mime_type.is_empty()) {
  3728. mime_type = "image/" + resource_uri.get_extension();
  3729. }
  3730. // Fallback to loading as byte array. This enables us to support the
  3731. // spec's requirement that we honor mimetype regardless of file URI.
  3732. data = FileAccess::get_file_as_bytes(resource_uri);
  3733. if (data.size() == 0) {
  3734. WARN_PRINT(vformat("glTF: Image index '%d' couldn't be loaded as a buffer of MIME type '%s' from URI: %s because there was no data to load. Skipping it.", i, mime_type, resource_uri));
  3735. p_state->images.push_back(Ref<Texture2D>()); // Placeholder to keep count.
  3736. p_state->source_images.push_back(Ref<Image>());
  3737. continue;
  3738. }
  3739. }
  3740. } else if (dict.has("bufferView")) {
  3741. // Handles the third bullet point from the spec (bufferView).
  3742. ERR_FAIL_COND_V_MSG(mime_type.is_empty(), ERR_FILE_CORRUPT, vformat("glTF: Image index '%d' specifies 'bufferView' but no 'mimeType', which is invalid.", i));
  3743. const GLTFBufferViewIndex bvi = dict["bufferView"];
  3744. ERR_FAIL_INDEX_V(bvi, p_state->buffer_views.size(), ERR_PARAMETER_RANGE_ERROR);
  3745. Ref<GLTFBufferView> bv = p_state->buffer_views[bvi];
  3746. const GLTFBufferIndex bi = bv->buffer;
  3747. ERR_FAIL_INDEX_V(bi, p_state->buffers.size(), ERR_PARAMETER_RANGE_ERROR);
  3748. ERR_FAIL_COND_V(bv->byte_offset + bv->byte_length > p_state->buffers[bi].size(), ERR_FILE_CORRUPT);
  3749. const PackedByteArray &buffer = p_state->buffers[bi];
  3750. data = buffer.slice(bv->byte_offset, bv->byte_offset + bv->byte_length);
  3751. }
  3752. // Done loading the image data bytes. Check that we actually got data to parse.
  3753. // Note: There are paths above that return early, so this point might not be reached.
  3754. if (data.is_empty()) {
  3755. WARN_PRINT(vformat("glTF: Image index '%d' couldn't be loaded, no data found. Skipping it.", i));
  3756. p_state->images.push_back(Ref<Texture2D>()); // Placeholder to keep count.
  3757. p_state->source_images.push_back(Ref<Image>());
  3758. continue;
  3759. }
  3760. // Parse the image data from bytes into an Image resource and save if needed.
  3761. String file_extension;
  3762. Ref<Image> img = _parse_image_bytes_into_image(p_state, data, mime_type, i, file_extension);
  3763. img->set_name(image_name);
  3764. _parse_image_save_image(p_state, data, resource_uri, file_extension, i, img);
  3765. }
  3766. print_verbose("glTF: Total images: " + itos(p_state->images.size()));
  3767. return OK;
  3768. }
  3769. Error GLTFDocument::_serialize_textures(Ref<GLTFState> p_state) {
  3770. if (!p_state->textures.size()) {
  3771. return OK;
  3772. }
  3773. Array textures;
  3774. for (int32_t i = 0; i < p_state->textures.size(); i++) {
  3775. Dictionary texture_dict;
  3776. Ref<GLTFTexture> gltf_texture = p_state->textures[i];
  3777. if (_image_save_extension.is_valid()) {
  3778. Error err = _image_save_extension->serialize_texture_json(p_state, texture_dict, gltf_texture, _image_format);
  3779. ERR_FAIL_COND_V(err != OK, err);
  3780. } else {
  3781. ERR_CONTINUE(gltf_texture->get_src_image() == -1);
  3782. texture_dict["source"] = gltf_texture->get_src_image();
  3783. }
  3784. GLTFTextureSamplerIndex sampler_index = gltf_texture->get_sampler();
  3785. if (sampler_index != -1) {
  3786. texture_dict["sampler"] = sampler_index;
  3787. }
  3788. textures.push_back(texture_dict);
  3789. }
  3790. p_state->json["textures"] = textures;
  3791. return OK;
  3792. }
  3793. Error GLTFDocument::_parse_textures(Ref<GLTFState> p_state) {
  3794. if (!p_state->json.has("textures")) {
  3795. return OK;
  3796. }
  3797. const Array &textures = p_state->json["textures"];
  3798. for (GLTFTextureIndex i = 0; i < textures.size(); i++) {
  3799. const Dictionary &texture_dict = textures[i];
  3800. Ref<GLTFTexture> gltf_texture;
  3801. gltf_texture.instantiate();
  3802. // Check if any GLTFDocumentExtensions want to handle this texture JSON.
  3803. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  3804. ERR_CONTINUE(ext.is_null());
  3805. Error err = ext->parse_texture_json(p_state, texture_dict, gltf_texture);
  3806. ERR_CONTINUE_MSG(err != OK, "glTF: Encountered error " + itos(err) + " when parsing texture JSON " + String(Variant(texture_dict)) + " in file " + p_state->filename + ". Continuing.");
  3807. if (gltf_texture->get_src_image() != -1) {
  3808. break;
  3809. }
  3810. }
  3811. if (gltf_texture->get_src_image() == -1) {
  3812. // No extensions handled it, so use the base glTF source.
  3813. // This may be the fallback, or the only option anyway.
  3814. ERR_FAIL_COND_V(!texture_dict.has("source"), ERR_PARSE_ERROR);
  3815. gltf_texture->set_src_image(texture_dict["source"]);
  3816. }
  3817. if (gltf_texture->get_sampler() == -1 && texture_dict.has("sampler")) {
  3818. gltf_texture->set_sampler(texture_dict["sampler"]);
  3819. }
  3820. p_state->textures.push_back(gltf_texture);
  3821. }
  3822. return OK;
  3823. }
  3824. GLTFTextureIndex GLTFDocument::_set_texture(Ref<GLTFState> p_state, Ref<Texture2D> p_texture, StandardMaterial3D::TextureFilter p_filter_mode, bool p_repeats) {
  3825. ERR_FAIL_COND_V(p_texture.is_null(), -1);
  3826. Ref<GLTFTexture> gltf_texture;
  3827. gltf_texture.instantiate();
  3828. ERR_FAIL_COND_V(p_texture->get_image().is_null(), -1);
  3829. GLTFImageIndex gltf_src_image_i = p_state->images.size();
  3830. p_state->images.push_back(p_texture);
  3831. p_state->source_images.push_back(p_texture->get_image());
  3832. gltf_texture->set_src_image(gltf_src_image_i);
  3833. gltf_texture->set_sampler(_set_sampler_for_mode(p_state, p_filter_mode, p_repeats));
  3834. GLTFTextureIndex gltf_texture_i = p_state->textures.size();
  3835. p_state->textures.push_back(gltf_texture);
  3836. return gltf_texture_i;
  3837. }
  3838. Ref<Texture2D> GLTFDocument::_get_texture(Ref<GLTFState> p_state, const GLTFTextureIndex p_texture, int p_texture_types) {
  3839. ERR_FAIL_INDEX_V(p_texture, p_state->textures.size(), Ref<Texture2D>());
  3840. const GLTFImageIndex image = p_state->textures[p_texture]->get_src_image();
  3841. ERR_FAIL_INDEX_V(image, p_state->images.size(), Ref<Texture2D>());
  3842. if (GLTFState::GLTFHandleBinary(p_state->handle_binary_image) == GLTFState::GLTFHandleBinary::HANDLE_BINARY_EMBED_AS_BASISU) {
  3843. ERR_FAIL_INDEX_V(image, p_state->source_images.size(), Ref<Texture2D>());
  3844. Ref<PortableCompressedTexture2D> portable_texture;
  3845. portable_texture.instantiate();
  3846. portable_texture->set_keep_compressed_buffer(true);
  3847. Ref<Image> new_img = p_state->source_images[image]->duplicate();
  3848. ERR_FAIL_COND_V(new_img.is_null(), Ref<Texture2D>());
  3849. new_img->generate_mipmaps();
  3850. if (p_texture_types) {
  3851. portable_texture->create_from_image(new_img, PortableCompressedTexture2D::COMPRESSION_MODE_BASIS_UNIVERSAL, true);
  3852. } else {
  3853. portable_texture->create_from_image(new_img, PortableCompressedTexture2D::COMPRESSION_MODE_BASIS_UNIVERSAL, false);
  3854. }
  3855. p_state->images.write[image] = portable_texture;
  3856. p_state->source_images.write[image] = new_img;
  3857. }
  3858. return p_state->images[image];
  3859. }
  3860. GLTFTextureSamplerIndex GLTFDocument::_set_sampler_for_mode(Ref<GLTFState> p_state, StandardMaterial3D::TextureFilter p_filter_mode, bool p_repeats) {
  3861. for (int i = 0; i < p_state->texture_samplers.size(); ++i) {
  3862. if (p_state->texture_samplers[i]->get_filter_mode() == p_filter_mode) {
  3863. return i;
  3864. }
  3865. }
  3866. GLTFTextureSamplerIndex gltf_sampler_i = p_state->texture_samplers.size();
  3867. Ref<GLTFTextureSampler> gltf_sampler;
  3868. gltf_sampler.instantiate();
  3869. gltf_sampler->set_filter_mode(p_filter_mode);
  3870. gltf_sampler->set_wrap_mode(p_repeats);
  3871. p_state->texture_samplers.push_back(gltf_sampler);
  3872. return gltf_sampler_i;
  3873. }
  3874. Ref<GLTFTextureSampler> GLTFDocument::_get_sampler_for_texture(Ref<GLTFState> p_state, const GLTFTextureIndex p_texture) {
  3875. ERR_FAIL_INDEX_V(p_texture, p_state->textures.size(), Ref<Texture2D>());
  3876. const GLTFTextureSamplerIndex sampler = p_state->textures[p_texture]->get_sampler();
  3877. if (sampler == -1) {
  3878. return p_state->default_texture_sampler;
  3879. } else {
  3880. ERR_FAIL_INDEX_V(sampler, p_state->texture_samplers.size(), Ref<GLTFTextureSampler>());
  3881. return p_state->texture_samplers[sampler];
  3882. }
  3883. }
  3884. Error GLTFDocument::_serialize_texture_samplers(Ref<GLTFState> p_state) {
  3885. if (!p_state->texture_samplers.size()) {
  3886. return OK;
  3887. }
  3888. Array samplers;
  3889. for (int32_t i = 0; i < p_state->texture_samplers.size(); ++i) {
  3890. Dictionary d;
  3891. Ref<GLTFTextureSampler> s = p_state->texture_samplers[i];
  3892. d["magFilter"] = s->get_mag_filter();
  3893. d["minFilter"] = s->get_min_filter();
  3894. d["wrapS"] = s->get_wrap_s();
  3895. d["wrapT"] = s->get_wrap_t();
  3896. samplers.push_back(d);
  3897. }
  3898. p_state->json["samplers"] = samplers;
  3899. return OK;
  3900. }
  3901. Error GLTFDocument::_parse_texture_samplers(Ref<GLTFState> p_state) {
  3902. p_state->default_texture_sampler.instantiate();
  3903. p_state->default_texture_sampler->set_min_filter(GLTFTextureSampler::FilterMode::LINEAR_MIPMAP_LINEAR);
  3904. p_state->default_texture_sampler->set_mag_filter(GLTFTextureSampler::FilterMode::LINEAR);
  3905. p_state->default_texture_sampler->set_wrap_s(GLTFTextureSampler::WrapMode::REPEAT);
  3906. p_state->default_texture_sampler->set_wrap_t(GLTFTextureSampler::WrapMode::REPEAT);
  3907. if (!p_state->json.has("samplers")) {
  3908. return OK;
  3909. }
  3910. const Array &samplers = p_state->json["samplers"];
  3911. for (int i = 0; i < samplers.size(); ++i) {
  3912. const Dictionary &d = samplers[i];
  3913. Ref<GLTFTextureSampler> sampler;
  3914. sampler.instantiate();
  3915. if (d.has("minFilter")) {
  3916. sampler->set_min_filter(d["minFilter"]);
  3917. } else {
  3918. sampler->set_min_filter(GLTFTextureSampler::FilterMode::LINEAR_MIPMAP_LINEAR);
  3919. }
  3920. if (d.has("magFilter")) {
  3921. sampler->set_mag_filter(d["magFilter"]);
  3922. } else {
  3923. sampler->set_mag_filter(GLTFTextureSampler::FilterMode::LINEAR);
  3924. }
  3925. if (d.has("wrapS")) {
  3926. sampler->set_wrap_s(d["wrapS"]);
  3927. } else {
  3928. sampler->set_wrap_s(GLTFTextureSampler::WrapMode::DEFAULT);
  3929. }
  3930. if (d.has("wrapT")) {
  3931. sampler->set_wrap_t(d["wrapT"]);
  3932. } else {
  3933. sampler->set_wrap_t(GLTFTextureSampler::WrapMode::DEFAULT);
  3934. }
  3935. p_state->texture_samplers.push_back(sampler);
  3936. }
  3937. return OK;
  3938. }
  3939. Error GLTFDocument::_serialize_materials(Ref<GLTFState> p_state) {
  3940. Array materials;
  3941. for (int32_t i = 0; i < p_state->materials.size(); i++) {
  3942. Dictionary d;
  3943. Ref<Material> material = p_state->materials[i];
  3944. if (material.is_null()) {
  3945. materials.push_back(d);
  3946. continue;
  3947. }
  3948. if (!material->get_name().is_empty()) {
  3949. d["name"] = _gen_unique_name(p_state, material->get_name());
  3950. }
  3951. Ref<BaseMaterial3D> base_material = material;
  3952. if (base_material.is_null()) {
  3953. materials.push_back(d);
  3954. continue;
  3955. }
  3956. Dictionary mr;
  3957. {
  3958. Array arr;
  3959. const Color c = base_material->get_albedo().srgb_to_linear();
  3960. arr.push_back(c.r);
  3961. arr.push_back(c.g);
  3962. arr.push_back(c.b);
  3963. arr.push_back(c.a);
  3964. mr["baseColorFactor"] = arr;
  3965. }
  3966. if (_image_format != "None") {
  3967. Dictionary bct;
  3968. Ref<Texture2D> albedo_texture = base_material->get_texture(BaseMaterial3D::TEXTURE_ALBEDO);
  3969. GLTFTextureIndex gltf_texture_index = -1;
  3970. if (albedo_texture.is_valid() && albedo_texture->get_image().is_valid()) {
  3971. albedo_texture->set_name(material->get_name() + "_albedo");
  3972. gltf_texture_index = _set_texture(p_state, albedo_texture, base_material->get_texture_filter(), base_material->get_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT));
  3973. }
  3974. if (gltf_texture_index != -1) {
  3975. bct["index"] = gltf_texture_index;
  3976. Dictionary extensions = _serialize_texture_transform_uv1(material);
  3977. if (!extensions.is_empty()) {
  3978. bct["extensions"] = extensions;
  3979. p_state->use_khr_texture_transform = true;
  3980. }
  3981. mr["baseColorTexture"] = bct;
  3982. }
  3983. }
  3984. mr["metallicFactor"] = base_material->get_metallic();
  3985. mr["roughnessFactor"] = base_material->get_roughness();
  3986. if (_image_format != "None") {
  3987. bool has_roughness = base_material->get_texture(BaseMaterial3D::TEXTURE_ROUGHNESS).is_valid() && base_material->get_texture(BaseMaterial3D::TEXTURE_ROUGHNESS)->get_image().is_valid();
  3988. bool has_ao = base_material->get_feature(BaseMaterial3D::FEATURE_AMBIENT_OCCLUSION) && base_material->get_texture(BaseMaterial3D::TEXTURE_AMBIENT_OCCLUSION).is_valid();
  3989. bool has_metalness = base_material->get_texture(BaseMaterial3D::TEXTURE_METALLIC).is_valid() && base_material->get_texture(BaseMaterial3D::TEXTURE_METALLIC)->get_image().is_valid();
  3990. if (has_ao || has_roughness || has_metalness) {
  3991. Dictionary mrt;
  3992. Ref<Texture2D> roughness_texture = base_material->get_texture(BaseMaterial3D::TEXTURE_ROUGHNESS);
  3993. BaseMaterial3D::TextureChannel roughness_channel = base_material->get_roughness_texture_channel();
  3994. Ref<Texture2D> metallic_texture = base_material->get_texture(BaseMaterial3D::TEXTURE_METALLIC);
  3995. BaseMaterial3D::TextureChannel metalness_channel = base_material->get_metallic_texture_channel();
  3996. Ref<Texture2D> ao_texture = base_material->get_texture(BaseMaterial3D::TEXTURE_AMBIENT_OCCLUSION);
  3997. BaseMaterial3D::TextureChannel ao_channel = base_material->get_ao_texture_channel();
  3998. Ref<ImageTexture> orm_texture;
  3999. orm_texture.instantiate();
  4000. Ref<Image> orm_image;
  4001. orm_image.instantiate();
  4002. int32_t height = 0;
  4003. int32_t width = 0;
  4004. Ref<Image> ao_image;
  4005. if (has_ao) {
  4006. height = ao_texture->get_height();
  4007. width = ao_texture->get_width();
  4008. ao_image = ao_texture->get_image();
  4009. Ref<ImageTexture> img_tex = ao_image;
  4010. if (img_tex.is_valid()) {
  4011. ao_image = img_tex->get_image();
  4012. }
  4013. if (ao_image->is_compressed()) {
  4014. ao_image->decompress();
  4015. }
  4016. }
  4017. Ref<Image> roughness_image;
  4018. if (has_roughness) {
  4019. height = roughness_texture->get_height();
  4020. width = roughness_texture->get_width();
  4021. roughness_image = roughness_texture->get_image();
  4022. Ref<ImageTexture> img_tex = roughness_image;
  4023. if (img_tex.is_valid()) {
  4024. roughness_image = img_tex->get_image();
  4025. }
  4026. if (roughness_image->is_compressed()) {
  4027. roughness_image->decompress();
  4028. }
  4029. }
  4030. Ref<Image> metallness_image;
  4031. if (has_metalness) {
  4032. height = metallic_texture->get_height();
  4033. width = metallic_texture->get_width();
  4034. metallness_image = metallic_texture->get_image();
  4035. Ref<ImageTexture> img_tex = metallness_image;
  4036. if (img_tex.is_valid()) {
  4037. metallness_image = img_tex->get_image();
  4038. }
  4039. if (metallness_image->is_compressed()) {
  4040. metallness_image->decompress();
  4041. }
  4042. }
  4043. Ref<Texture2D> albedo_texture = base_material->get_texture(BaseMaterial3D::TEXTURE_ALBEDO);
  4044. if (albedo_texture.is_valid() && albedo_texture->get_image().is_valid()) {
  4045. height = albedo_texture->get_height();
  4046. width = albedo_texture->get_width();
  4047. }
  4048. orm_image->initialize_data(width, height, false, Image::FORMAT_RGBA8);
  4049. if (ao_image.is_valid() && ao_image->get_size() != Vector2(width, height)) {
  4050. ao_image->resize(width, height, Image::INTERPOLATE_LANCZOS);
  4051. }
  4052. if (roughness_image.is_valid() && roughness_image->get_size() != Vector2(width, height)) {
  4053. roughness_image->resize(width, height, Image::INTERPOLATE_LANCZOS);
  4054. }
  4055. if (metallness_image.is_valid() && metallness_image->get_size() != Vector2(width, height)) {
  4056. metallness_image->resize(width, height, Image::INTERPOLATE_LANCZOS);
  4057. }
  4058. for (int32_t h = 0; h < height; h++) {
  4059. for (int32_t w = 0; w < width; w++) {
  4060. Color c = Color(1.0f, 1.0f, 1.0f);
  4061. if (has_ao) {
  4062. if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_RED == ao_channel) {
  4063. c.r = ao_image->get_pixel(w, h).r;
  4064. } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_GREEN == ao_channel) {
  4065. c.r = ao_image->get_pixel(w, h).g;
  4066. } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_BLUE == ao_channel) {
  4067. c.r = ao_image->get_pixel(w, h).b;
  4068. } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_ALPHA == ao_channel) {
  4069. c.r = ao_image->get_pixel(w, h).a;
  4070. }
  4071. }
  4072. if (has_roughness) {
  4073. if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_RED == roughness_channel) {
  4074. c.g = roughness_image->get_pixel(w, h).r;
  4075. } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_GREEN == roughness_channel) {
  4076. c.g = roughness_image->get_pixel(w, h).g;
  4077. } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_BLUE == roughness_channel) {
  4078. c.g = roughness_image->get_pixel(w, h).b;
  4079. } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_ALPHA == roughness_channel) {
  4080. c.g = roughness_image->get_pixel(w, h).a;
  4081. }
  4082. }
  4083. if (has_metalness) {
  4084. if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_RED == metalness_channel) {
  4085. c.b = metallness_image->get_pixel(w, h).r;
  4086. } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_GREEN == metalness_channel) {
  4087. c.b = metallness_image->get_pixel(w, h).g;
  4088. } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_BLUE == metalness_channel) {
  4089. c.b = metallness_image->get_pixel(w, h).b;
  4090. } else if (BaseMaterial3D::TextureChannel::TEXTURE_CHANNEL_ALPHA == metalness_channel) {
  4091. c.b = metallness_image->get_pixel(w, h).a;
  4092. }
  4093. }
  4094. orm_image->set_pixel(w, h, c);
  4095. }
  4096. }
  4097. orm_image->generate_mipmaps();
  4098. orm_texture->set_image(orm_image);
  4099. GLTFTextureIndex orm_texture_index = -1;
  4100. if (has_ao || has_roughness || has_metalness) {
  4101. orm_texture->set_name(material->get_name() + "_orm");
  4102. orm_texture_index = _set_texture(p_state, orm_texture, base_material->get_texture_filter(), base_material->get_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT));
  4103. }
  4104. if (has_ao) {
  4105. Dictionary occt;
  4106. occt["index"] = orm_texture_index;
  4107. d["occlusionTexture"] = occt;
  4108. }
  4109. if (has_roughness || has_metalness) {
  4110. mrt["index"] = orm_texture_index;
  4111. Dictionary extensions = _serialize_texture_transform_uv1(material);
  4112. if (!extensions.is_empty()) {
  4113. mrt["extensions"] = extensions;
  4114. p_state->use_khr_texture_transform = true;
  4115. }
  4116. mr["metallicRoughnessTexture"] = mrt;
  4117. }
  4118. }
  4119. }
  4120. d["pbrMetallicRoughness"] = mr;
  4121. if (base_material->get_feature(BaseMaterial3D::FEATURE_NORMAL_MAPPING) && _image_format != "None") {
  4122. Dictionary nt;
  4123. Ref<ImageTexture> tex;
  4124. tex.instantiate();
  4125. {
  4126. Ref<Texture2D> normal_texture = base_material->get_texture(BaseMaterial3D::TEXTURE_NORMAL);
  4127. if (normal_texture.is_valid()) {
  4128. // Code for uncompressing RG normal maps
  4129. Ref<Image> img = normal_texture->get_image();
  4130. if (img.is_valid()) {
  4131. Ref<ImageTexture> img_tex = img;
  4132. if (img_tex.is_valid()) {
  4133. img = img_tex->get_image();
  4134. }
  4135. img->decompress();
  4136. img->convert(Image::FORMAT_RGBA8);
  4137. for (int32_t y = 0; y < img->get_height(); y++) {
  4138. for (int32_t x = 0; x < img->get_width(); x++) {
  4139. Color c = img->get_pixel(x, y);
  4140. Vector2 red_green = Vector2(c.r, c.g);
  4141. red_green = red_green * Vector2(2.0f, 2.0f) - Vector2(1.0f, 1.0f);
  4142. float blue = 1.0f - red_green.dot(red_green);
  4143. blue = MAX(0.0f, blue);
  4144. c.b = Math::sqrt(blue);
  4145. img->set_pixel(x, y, c);
  4146. }
  4147. }
  4148. tex->set_image(img);
  4149. }
  4150. }
  4151. }
  4152. GLTFTextureIndex gltf_texture_index = -1;
  4153. if (tex.is_valid() && tex->get_image().is_valid()) {
  4154. tex->set_name(material->get_name() + "_normal");
  4155. gltf_texture_index = _set_texture(p_state, tex, base_material->get_texture_filter(), base_material->get_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT));
  4156. }
  4157. nt["scale"] = base_material->get_normal_scale();
  4158. if (gltf_texture_index != -1) {
  4159. nt["index"] = gltf_texture_index;
  4160. d["normalTexture"] = nt;
  4161. }
  4162. }
  4163. if (base_material->get_feature(BaseMaterial3D::FEATURE_EMISSION)) {
  4164. const Color c = base_material->get_emission().linear_to_srgb();
  4165. Array arr;
  4166. arr.push_back(c.r);
  4167. arr.push_back(c.g);
  4168. arr.push_back(c.b);
  4169. d["emissiveFactor"] = arr;
  4170. }
  4171. if (base_material->get_feature(BaseMaterial3D::FEATURE_EMISSION) && _image_format != "None") {
  4172. Dictionary et;
  4173. Ref<Texture2D> emission_texture = base_material->get_texture(BaseMaterial3D::TEXTURE_EMISSION);
  4174. GLTFTextureIndex gltf_texture_index = -1;
  4175. if (emission_texture.is_valid() && emission_texture->get_image().is_valid()) {
  4176. emission_texture->set_name(material->get_name() + "_emission");
  4177. gltf_texture_index = _set_texture(p_state, emission_texture, base_material->get_texture_filter(), base_material->get_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT));
  4178. }
  4179. if (gltf_texture_index != -1) {
  4180. et["index"] = gltf_texture_index;
  4181. d["emissiveTexture"] = et;
  4182. }
  4183. }
  4184. const bool ds = base_material->get_cull_mode() == BaseMaterial3D::CULL_DISABLED;
  4185. if (ds) {
  4186. d["doubleSided"] = ds;
  4187. }
  4188. if (base_material->get_transparency() == BaseMaterial3D::TRANSPARENCY_ALPHA_SCISSOR) {
  4189. d["alphaMode"] = "MASK";
  4190. d["alphaCutoff"] = base_material->get_alpha_scissor_threshold();
  4191. } else if (base_material->get_transparency() != BaseMaterial3D::TRANSPARENCY_DISABLED) {
  4192. d["alphaMode"] = "BLEND";
  4193. }
  4194. Dictionary extensions;
  4195. if (base_material->get_shading_mode() == BaseMaterial3D::SHADING_MODE_UNSHADED) {
  4196. Dictionary mat_unlit;
  4197. extensions["KHR_materials_unlit"] = mat_unlit;
  4198. p_state->add_used_extension("KHR_materials_unlit");
  4199. }
  4200. if (base_material->get_feature(BaseMaterial3D::FEATURE_EMISSION) && !Math::is_equal_approx(base_material->get_emission_energy_multiplier(), 1.0f)) {
  4201. Dictionary mat_emissive_strength;
  4202. mat_emissive_strength["emissiveStrength"] = base_material->get_emission_energy_multiplier();
  4203. extensions["KHR_materials_emissive_strength"] = mat_emissive_strength;
  4204. p_state->add_used_extension("KHR_materials_emissive_strength");
  4205. }
  4206. d["extensions"] = extensions;
  4207. _attach_meta_to_extras(material, d);
  4208. materials.push_back(d);
  4209. }
  4210. if (!materials.size()) {
  4211. return OK;
  4212. }
  4213. p_state->json["materials"] = materials;
  4214. print_verbose("Total materials: " + itos(p_state->materials.size()));
  4215. return OK;
  4216. }
  4217. Error GLTFDocument::_parse_materials(Ref<GLTFState> p_state) {
  4218. if (!p_state->json.has("materials")) {
  4219. return OK;
  4220. }
  4221. const Array &materials = p_state->json["materials"];
  4222. for (GLTFMaterialIndex i = 0; i < materials.size(); i++) {
  4223. const Dictionary &material_dict = materials[i];
  4224. Ref<StandardMaterial3D> material;
  4225. material.instantiate();
  4226. if (material_dict.has("name") && !String(material_dict["name"]).is_empty()) {
  4227. material->set_name(material_dict["name"]);
  4228. } else {
  4229. material->set_name(vformat("material_%s", itos(i)));
  4230. }
  4231. Dictionary material_extensions;
  4232. if (material_dict.has("extensions")) {
  4233. material_extensions = material_dict["extensions"];
  4234. }
  4235. if (material_extensions.has("KHR_materials_unlit")) {
  4236. material->set_shading_mode(BaseMaterial3D::SHADING_MODE_UNSHADED);
  4237. }
  4238. if (material_extensions.has("KHR_materials_emissive_strength")) {
  4239. Dictionary emissive_strength = material_extensions["KHR_materials_emissive_strength"];
  4240. if (emissive_strength.has("emissiveStrength")) {
  4241. material->set_emission_energy_multiplier(emissive_strength["emissiveStrength"]);
  4242. }
  4243. }
  4244. if (material_extensions.has("KHR_materials_pbrSpecularGlossiness")) {
  4245. WARN_PRINT("Material uses a specular and glossiness workflow. Textures will be converted to roughness and metallic workflow, which may not be 100% accurate.");
  4246. Dictionary sgm = material_extensions["KHR_materials_pbrSpecularGlossiness"];
  4247. Ref<GLTFSpecGloss> spec_gloss;
  4248. spec_gloss.instantiate();
  4249. if (sgm.has("diffuseTexture")) {
  4250. const Dictionary &diffuse_texture_dict = sgm["diffuseTexture"];
  4251. if (diffuse_texture_dict.has("index")) {
  4252. Ref<GLTFTextureSampler> diffuse_sampler = _get_sampler_for_texture(p_state, diffuse_texture_dict["index"]);
  4253. if (diffuse_sampler.is_valid()) {
  4254. material->set_texture_filter(diffuse_sampler->get_filter_mode());
  4255. material->set_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT, diffuse_sampler->get_wrap_mode());
  4256. }
  4257. Ref<Texture2D> diffuse_texture = _get_texture(p_state, diffuse_texture_dict["index"], TEXTURE_TYPE_GENERIC);
  4258. if (diffuse_texture.is_valid()) {
  4259. spec_gloss->diffuse_img = diffuse_texture->get_image();
  4260. material->set_texture(BaseMaterial3D::TEXTURE_ALBEDO, diffuse_texture);
  4261. }
  4262. }
  4263. }
  4264. if (sgm.has("diffuseFactor")) {
  4265. const Array &arr = sgm["diffuseFactor"];
  4266. ERR_FAIL_COND_V(arr.size() != 4, ERR_PARSE_ERROR);
  4267. const Color c = Color(arr[0], arr[1], arr[2], arr[3]).linear_to_srgb();
  4268. spec_gloss->diffuse_factor = c;
  4269. material->set_albedo(spec_gloss->diffuse_factor);
  4270. }
  4271. if (sgm.has("specularFactor")) {
  4272. const Array &arr = sgm["specularFactor"];
  4273. ERR_FAIL_COND_V(arr.size() != 3, ERR_PARSE_ERROR);
  4274. spec_gloss->specular_factor = Color(arr[0], arr[1], arr[2]);
  4275. }
  4276. if (sgm.has("glossinessFactor")) {
  4277. spec_gloss->gloss_factor = sgm["glossinessFactor"];
  4278. material->set_roughness(1.0f - CLAMP(spec_gloss->gloss_factor, 0.0f, 1.0f));
  4279. }
  4280. if (sgm.has("specularGlossinessTexture")) {
  4281. const Dictionary &spec_gloss_texture = sgm["specularGlossinessTexture"];
  4282. if (spec_gloss_texture.has("index")) {
  4283. const Ref<Texture2D> orig_texture = _get_texture(p_state, spec_gloss_texture["index"], TEXTURE_TYPE_GENERIC);
  4284. if (orig_texture.is_valid()) {
  4285. spec_gloss->spec_gloss_img = orig_texture->get_image();
  4286. }
  4287. }
  4288. }
  4289. spec_gloss_to_rough_metal(spec_gloss, material);
  4290. } else if (material_dict.has("pbrMetallicRoughness")) {
  4291. const Dictionary &mr = material_dict["pbrMetallicRoughness"];
  4292. if (mr.has("baseColorFactor")) {
  4293. const Array &arr = mr["baseColorFactor"];
  4294. ERR_FAIL_COND_V(arr.size() != 4, ERR_PARSE_ERROR);
  4295. const Color c = Color(arr[0], arr[1], arr[2], arr[3]).linear_to_srgb();
  4296. material->set_albedo(c);
  4297. }
  4298. if (mr.has("baseColorTexture")) {
  4299. const Dictionary &bct = mr["baseColorTexture"];
  4300. if (bct.has("index")) {
  4301. Ref<GLTFTextureSampler> bct_sampler = _get_sampler_for_texture(p_state, bct["index"]);
  4302. material->set_texture_filter(bct_sampler->get_filter_mode());
  4303. material->set_flag(BaseMaterial3D::FLAG_USE_TEXTURE_REPEAT, bct_sampler->get_wrap_mode());
  4304. material->set_texture(BaseMaterial3D::TEXTURE_ALBEDO, _get_texture(p_state, bct["index"], TEXTURE_TYPE_GENERIC));
  4305. }
  4306. if (!mr.has("baseColorFactor")) {
  4307. material->set_albedo(Color(1, 1, 1));
  4308. }
  4309. _set_texture_transform_uv1(bct, material);
  4310. }
  4311. if (mr.has("metallicFactor")) {
  4312. material->set_metallic(mr["metallicFactor"]);
  4313. } else {
  4314. material->set_metallic(1.0);
  4315. }
  4316. if (mr.has("roughnessFactor")) {
  4317. material->set_roughness(mr["roughnessFactor"]);
  4318. } else {
  4319. material->set_roughness(1.0);
  4320. }
  4321. if (mr.has("metallicRoughnessTexture")) {
  4322. const Dictionary &bct = mr["metallicRoughnessTexture"];
  4323. if (bct.has("index")) {
  4324. const Ref<Texture2D> t = _get_texture(p_state, bct["index"], TEXTURE_TYPE_GENERIC);
  4325. material->set_texture(BaseMaterial3D::TEXTURE_METALLIC, t);
  4326. material->set_metallic_texture_channel(BaseMaterial3D::TEXTURE_CHANNEL_BLUE);
  4327. material->set_texture(BaseMaterial3D::TEXTURE_ROUGHNESS, t);
  4328. material->set_roughness_texture_channel(BaseMaterial3D::TEXTURE_CHANNEL_GREEN);
  4329. if (!mr.has("metallicFactor")) {
  4330. material->set_metallic(1);
  4331. }
  4332. if (!mr.has("roughnessFactor")) {
  4333. material->set_roughness(1);
  4334. }
  4335. }
  4336. }
  4337. }
  4338. if (material_dict.has("normalTexture")) {
  4339. const Dictionary &bct = material_dict["normalTexture"];
  4340. if (bct.has("index")) {
  4341. material->set_texture(BaseMaterial3D::TEXTURE_NORMAL, _get_texture(p_state, bct["index"], TEXTURE_TYPE_NORMAL));
  4342. material->set_feature(BaseMaterial3D::FEATURE_NORMAL_MAPPING, true);
  4343. }
  4344. if (bct.has("scale")) {
  4345. material->set_normal_scale(bct["scale"]);
  4346. }
  4347. }
  4348. if (material_dict.has("occlusionTexture")) {
  4349. const Dictionary &bct = material_dict["occlusionTexture"];
  4350. if (bct.has("index")) {
  4351. material->set_texture(BaseMaterial3D::TEXTURE_AMBIENT_OCCLUSION, _get_texture(p_state, bct["index"], TEXTURE_TYPE_GENERIC));
  4352. material->set_ao_texture_channel(BaseMaterial3D::TEXTURE_CHANNEL_RED);
  4353. material->set_feature(BaseMaterial3D::FEATURE_AMBIENT_OCCLUSION, true);
  4354. }
  4355. }
  4356. if (material_dict.has("emissiveFactor")) {
  4357. const Array &arr = material_dict["emissiveFactor"];
  4358. ERR_FAIL_COND_V(arr.size() != 3, ERR_PARSE_ERROR);
  4359. const Color c = Color(arr[0], arr[1], arr[2]).linear_to_srgb();
  4360. material->set_feature(BaseMaterial3D::FEATURE_EMISSION, true);
  4361. material->set_emission(c);
  4362. }
  4363. if (material_dict.has("emissiveTexture")) {
  4364. const Dictionary &bct = material_dict["emissiveTexture"];
  4365. if (bct.has("index")) {
  4366. material->set_texture(BaseMaterial3D::TEXTURE_EMISSION, _get_texture(p_state, bct["index"], TEXTURE_TYPE_GENERIC));
  4367. material->set_feature(BaseMaterial3D::FEATURE_EMISSION, true);
  4368. material->set_emission(Color(0, 0, 0));
  4369. }
  4370. }
  4371. if (material_dict.has("doubleSided")) {
  4372. const bool ds = material_dict["doubleSided"];
  4373. if (ds) {
  4374. material->set_cull_mode(BaseMaterial3D::CULL_DISABLED);
  4375. }
  4376. }
  4377. if (material_dict.has("alphaMode")) {
  4378. const String &am = material_dict["alphaMode"];
  4379. if (am == "BLEND") {
  4380. material->set_transparency(BaseMaterial3D::TRANSPARENCY_ALPHA_DEPTH_PRE_PASS);
  4381. } else if (am == "MASK") {
  4382. material->set_transparency(BaseMaterial3D::TRANSPARENCY_ALPHA_SCISSOR);
  4383. }
  4384. }
  4385. if (material_dict.has("alphaCutoff")) {
  4386. material->set_alpha_scissor_threshold(material_dict["alphaCutoff"]);
  4387. } else {
  4388. material->set_alpha_scissor_threshold(0.5f);
  4389. }
  4390. if (material_dict.has("extras")) {
  4391. _attach_extras_to_meta(material_dict["extras"], material);
  4392. }
  4393. p_state->materials.push_back(material);
  4394. }
  4395. print_verbose("Total materials: " + itos(p_state->materials.size()));
  4396. return OK;
  4397. }
  4398. void GLTFDocument::_set_texture_transform_uv1(const Dictionary &p_dict, Ref<BaseMaterial3D> p_material) {
  4399. if (p_dict.has("extensions")) {
  4400. const Dictionary &extensions = p_dict["extensions"];
  4401. if (extensions.has("KHR_texture_transform")) {
  4402. if (p_material.is_valid()) {
  4403. const Dictionary &texture_transform = extensions["KHR_texture_transform"];
  4404. const Array &offset_arr = texture_transform["offset"];
  4405. if (offset_arr.size() == 2) {
  4406. const Vector3 offset_vector3 = Vector3(offset_arr[0], offset_arr[1], 0.0f);
  4407. p_material->set_uv1_offset(offset_vector3);
  4408. }
  4409. const Array &scale_arr = texture_transform["scale"];
  4410. if (scale_arr.size() == 2) {
  4411. const Vector3 scale_vector3 = Vector3(scale_arr[0], scale_arr[1], 1.0f);
  4412. p_material->set_uv1_scale(scale_vector3);
  4413. }
  4414. }
  4415. }
  4416. }
  4417. }
  4418. void GLTFDocument::spec_gloss_to_rough_metal(Ref<GLTFSpecGloss> r_spec_gloss, Ref<BaseMaterial3D> p_material) {
  4419. if (r_spec_gloss.is_null()) {
  4420. return;
  4421. }
  4422. if (r_spec_gloss->spec_gloss_img.is_null()) {
  4423. return;
  4424. }
  4425. if (r_spec_gloss->diffuse_img.is_null()) {
  4426. return;
  4427. }
  4428. if (p_material.is_null()) {
  4429. return;
  4430. }
  4431. bool has_roughness = false;
  4432. bool has_metal = false;
  4433. p_material->set_roughness(1.0f);
  4434. p_material->set_metallic(1.0f);
  4435. Ref<Image> rm_img = Image::create_empty(r_spec_gloss->spec_gloss_img->get_width(), r_spec_gloss->spec_gloss_img->get_height(), false, Image::FORMAT_RGBA8);
  4436. r_spec_gloss->spec_gloss_img->decompress();
  4437. if (r_spec_gloss->diffuse_img.is_valid()) {
  4438. r_spec_gloss->diffuse_img->decompress();
  4439. 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);
  4440. r_spec_gloss->spec_gloss_img->resize(r_spec_gloss->diffuse_img->get_width(), r_spec_gloss->diffuse_img->get_height(), Image::INTERPOLATE_LANCZOS);
  4441. }
  4442. for (int32_t y = 0; y < r_spec_gloss->spec_gloss_img->get_height(); y++) {
  4443. for (int32_t x = 0; x < r_spec_gloss->spec_gloss_img->get_width(); x++) {
  4444. const Color specular_pixel = r_spec_gloss->spec_gloss_img->get_pixel(x, y).srgb_to_linear();
  4445. Color specular = Color(specular_pixel.r, specular_pixel.g, specular_pixel.b);
  4446. specular *= r_spec_gloss->specular_factor;
  4447. Color diffuse = Color(1.0f, 1.0f, 1.0f);
  4448. diffuse *= r_spec_gloss->diffuse_img->get_pixel(x, y).srgb_to_linear();
  4449. float metallic = 0.0f;
  4450. Color base_color;
  4451. spec_gloss_to_metal_base_color(specular, diffuse, base_color, metallic);
  4452. Color mr = Color(1.0f, 1.0f, 1.0f);
  4453. mr.g = specular_pixel.a;
  4454. mr.b = metallic;
  4455. if (!Math::is_equal_approx(mr.g, 1.0f)) {
  4456. has_roughness = true;
  4457. }
  4458. if (!Math::is_zero_approx(mr.b)) {
  4459. has_metal = true;
  4460. }
  4461. mr.g *= r_spec_gloss->gloss_factor;
  4462. mr.g = 1.0f - mr.g;
  4463. rm_img->set_pixel(x, y, mr);
  4464. if (r_spec_gloss->diffuse_img.is_valid()) {
  4465. r_spec_gloss->diffuse_img->set_pixel(x, y, base_color.linear_to_srgb());
  4466. }
  4467. }
  4468. }
  4469. rm_img->generate_mipmaps();
  4470. r_spec_gloss->diffuse_img->generate_mipmaps();
  4471. p_material->set_texture(BaseMaterial3D::TEXTURE_ALBEDO, ImageTexture::create_from_image(r_spec_gloss->diffuse_img));
  4472. Ref<ImageTexture> rm_image_texture = ImageTexture::create_from_image(rm_img);
  4473. if (has_roughness) {
  4474. p_material->set_texture(BaseMaterial3D::TEXTURE_ROUGHNESS, rm_image_texture);
  4475. p_material->set_roughness_texture_channel(BaseMaterial3D::TEXTURE_CHANNEL_GREEN);
  4476. }
  4477. if (has_metal) {
  4478. p_material->set_texture(BaseMaterial3D::TEXTURE_METALLIC, rm_image_texture);
  4479. p_material->set_metallic_texture_channel(BaseMaterial3D::TEXTURE_CHANNEL_BLUE);
  4480. }
  4481. }
  4482. void GLTFDocument::spec_gloss_to_metal_base_color(const Color &p_specular_factor, const Color &p_diffuse, Color &r_base_color, float &r_metallic) {
  4483. const Color DIELECTRIC_SPECULAR = Color(0.04f, 0.04f, 0.04f);
  4484. Color specular = Color(p_specular_factor.r, p_specular_factor.g, p_specular_factor.b);
  4485. const float one_minus_specular_strength = 1.0f - get_max_component(specular);
  4486. const float dielectric_specular_red = DIELECTRIC_SPECULAR.r;
  4487. float brightness_diffuse = get_perceived_brightness(p_diffuse);
  4488. const float brightness_specular = get_perceived_brightness(specular);
  4489. r_metallic = solve_metallic(dielectric_specular_red, brightness_diffuse, brightness_specular, one_minus_specular_strength);
  4490. const float one_minus_metallic = 1.0f - r_metallic;
  4491. const Color base_color_from_diffuse = p_diffuse * (one_minus_specular_strength / (1.0f - dielectric_specular_red) / MAX(one_minus_metallic, CMP_EPSILON));
  4492. const Color base_color_from_specular = (specular - (DIELECTRIC_SPECULAR * (one_minus_metallic))) * (1.0f / MAX(r_metallic, CMP_EPSILON));
  4493. r_base_color.r = Math::lerp(base_color_from_diffuse.r, base_color_from_specular.r, r_metallic * r_metallic);
  4494. r_base_color.g = Math::lerp(base_color_from_diffuse.g, base_color_from_specular.g, r_metallic * r_metallic);
  4495. r_base_color.b = Math::lerp(base_color_from_diffuse.b, base_color_from_specular.b, r_metallic * r_metallic);
  4496. r_base_color.a = p_diffuse.a;
  4497. r_base_color = r_base_color.clamp();
  4498. }
  4499. Error GLTFDocument::_parse_skins(Ref<GLTFState> p_state) {
  4500. if (!p_state->json.has("skins")) {
  4501. return OK;
  4502. }
  4503. const Array &skins = p_state->json["skins"];
  4504. // Create the base skins, and mark nodes that are joints
  4505. for (int i = 0; i < skins.size(); i++) {
  4506. const Dictionary &d = skins[i];
  4507. Ref<GLTFSkin> skin;
  4508. skin.instantiate();
  4509. ERR_FAIL_COND_V(!d.has("joints"), ERR_PARSE_ERROR);
  4510. const Array &joints = d["joints"];
  4511. if (d.has("inverseBindMatrices")) {
  4512. skin->inverse_binds = _decode_accessor_as_xform(p_state, d["inverseBindMatrices"], false);
  4513. ERR_FAIL_COND_V(skin->inverse_binds.size() != joints.size(), ERR_PARSE_ERROR);
  4514. }
  4515. for (int j = 0; j < joints.size(); j++) {
  4516. const GLTFNodeIndex node = joints[j];
  4517. ERR_FAIL_INDEX_V(node, p_state->nodes.size(), ERR_PARSE_ERROR);
  4518. skin->joints.push_back(node);
  4519. skin->joints_original.push_back(node);
  4520. p_state->nodes.write[node]->joint = true;
  4521. }
  4522. if (d.has("name") && !String(d["name"]).is_empty()) {
  4523. skin->set_name(d["name"]);
  4524. } else {
  4525. skin->set_name(vformat("skin_%s", itos(i)));
  4526. }
  4527. if (d.has("skeleton")) {
  4528. skin->skin_root = d["skeleton"];
  4529. }
  4530. p_state->skins.push_back(skin);
  4531. }
  4532. for (GLTFSkinIndex i = 0; i < p_state->skins.size(); ++i) {
  4533. Ref<GLTFSkin> skin = p_state->skins.write[i];
  4534. // Expand the skin to capture all the extra non-joints that lie in between the actual joints,
  4535. // and expand the hierarchy to ensure multi-rooted trees lie on the same height level
  4536. ERR_FAIL_COND_V(SkinTool::_expand_skin(p_state->nodes, skin), ERR_PARSE_ERROR);
  4537. ERR_FAIL_COND_V(SkinTool::_verify_skin(p_state->nodes, skin), ERR_PARSE_ERROR);
  4538. }
  4539. print_verbose("glTF: Total skins: " + itos(p_state->skins.size()));
  4540. return OK;
  4541. }
  4542. Error GLTFDocument::_serialize_skins(Ref<GLTFState> p_state) {
  4543. _remove_duplicate_skins(p_state);
  4544. Array json_skins;
  4545. for (int skin_i = 0; skin_i < p_state->skins.size(); skin_i++) {
  4546. Ref<GLTFSkin> gltf_skin = p_state->skins[skin_i];
  4547. Dictionary json_skin;
  4548. json_skin["inverseBindMatrices"] = _encode_accessor_as_xform(p_state, gltf_skin->inverse_binds, false);
  4549. json_skin["joints"] = gltf_skin->get_joints();
  4550. json_skin["name"] = gltf_skin->get_name();
  4551. json_skins.push_back(json_skin);
  4552. }
  4553. if (!p_state->skins.size()) {
  4554. return OK;
  4555. }
  4556. p_state->json["skins"] = json_skins;
  4557. return OK;
  4558. }
  4559. Error GLTFDocument::_create_skins(Ref<GLTFState> p_state) {
  4560. for (GLTFSkinIndex skin_i = 0; skin_i < p_state->skins.size(); ++skin_i) {
  4561. Ref<GLTFSkin> gltf_skin = p_state->skins.write[skin_i];
  4562. Ref<Skin> skin;
  4563. skin.instantiate();
  4564. // Some skins don't have IBM's! What absolute monsters!
  4565. const bool has_ibms = !gltf_skin->inverse_binds.is_empty();
  4566. for (int joint_i = 0; joint_i < gltf_skin->joints_original.size(); ++joint_i) {
  4567. GLTFNodeIndex node = gltf_skin->joints_original[joint_i];
  4568. String bone_name = p_state->nodes[node]->get_name();
  4569. Transform3D xform;
  4570. if (has_ibms) {
  4571. xform = gltf_skin->inverse_binds[joint_i];
  4572. }
  4573. if (p_state->use_named_skin_binds) {
  4574. skin->add_named_bind(bone_name, xform);
  4575. } else {
  4576. int32_t bone_i = gltf_skin->joint_i_to_bone_i[joint_i];
  4577. skin->add_bind(bone_i, xform);
  4578. }
  4579. }
  4580. gltf_skin->godot_skin = skin;
  4581. }
  4582. // Purge the duplicates!
  4583. _remove_duplicate_skins(p_state);
  4584. // Create unique names now, after removing duplicates
  4585. for (GLTFSkinIndex skin_i = 0; skin_i < p_state->skins.size(); ++skin_i) {
  4586. Ref<Skin> skin = p_state->skins.write[skin_i]->godot_skin;
  4587. if (skin->get_name().is_empty()) {
  4588. // Make a unique name, no gltf node represents this skin
  4589. skin->set_name(_gen_unique_name(p_state, "Skin"));
  4590. }
  4591. }
  4592. return OK;
  4593. }
  4594. bool GLTFDocument::_skins_are_same(const Ref<Skin> p_skin_a, const Ref<Skin> p_skin_b) {
  4595. if (p_skin_a->get_bind_count() != p_skin_b->get_bind_count()) {
  4596. return false;
  4597. }
  4598. for (int i = 0; i < p_skin_a->get_bind_count(); ++i) {
  4599. if (p_skin_a->get_bind_bone(i) != p_skin_b->get_bind_bone(i)) {
  4600. return false;
  4601. }
  4602. if (p_skin_a->get_bind_name(i) != p_skin_b->get_bind_name(i)) {
  4603. return false;
  4604. }
  4605. Transform3D a_xform = p_skin_a->get_bind_pose(i);
  4606. Transform3D b_xform = p_skin_b->get_bind_pose(i);
  4607. if (a_xform != b_xform) {
  4608. return false;
  4609. }
  4610. }
  4611. return true;
  4612. }
  4613. void GLTFDocument::_remove_duplicate_skins(Ref<GLTFState> p_state) {
  4614. for (int i = 0; i < p_state->skins.size(); ++i) {
  4615. for (int j = i + 1; j < p_state->skins.size(); ++j) {
  4616. const Ref<Skin> skin_i = p_state->skins[i]->godot_skin;
  4617. const Ref<Skin> skin_j = p_state->skins[j]->godot_skin;
  4618. if (_skins_are_same(skin_i, skin_j)) {
  4619. // replace it and delete the old
  4620. p_state->skins.write[j]->godot_skin = skin_i;
  4621. }
  4622. }
  4623. }
  4624. }
  4625. Error GLTFDocument::_serialize_lights(Ref<GLTFState> p_state) {
  4626. if (p_state->lights.is_empty()) {
  4627. return OK;
  4628. }
  4629. Array lights;
  4630. for (GLTFLightIndex i = 0; i < p_state->lights.size(); i++) {
  4631. lights.push_back(p_state->lights[i]->to_dictionary());
  4632. }
  4633. Dictionary extensions;
  4634. if (p_state->json.has("extensions")) {
  4635. extensions = p_state->json["extensions"];
  4636. } else {
  4637. p_state->json["extensions"] = extensions;
  4638. }
  4639. Dictionary lights_punctual;
  4640. extensions["KHR_lights_punctual"] = lights_punctual;
  4641. lights_punctual["lights"] = lights;
  4642. print_verbose("glTF: Total lights: " + itos(p_state->lights.size()));
  4643. return OK;
  4644. }
  4645. Error GLTFDocument::_serialize_cameras(Ref<GLTFState> p_state) {
  4646. Array cameras;
  4647. cameras.resize(p_state->cameras.size());
  4648. for (GLTFCameraIndex i = 0; i < p_state->cameras.size(); i++) {
  4649. cameras[i] = p_state->cameras[i]->to_dictionary();
  4650. }
  4651. if (!p_state->cameras.size()) {
  4652. return OK;
  4653. }
  4654. p_state->json["cameras"] = cameras;
  4655. print_verbose("glTF: Total cameras: " + itos(p_state->cameras.size()));
  4656. return OK;
  4657. }
  4658. Error GLTFDocument::_parse_lights(Ref<GLTFState> p_state) {
  4659. if (!p_state->json.has("extensions")) {
  4660. return OK;
  4661. }
  4662. Dictionary extensions = p_state->json["extensions"];
  4663. if (!extensions.has("KHR_lights_punctual")) {
  4664. return OK;
  4665. }
  4666. Dictionary lights_punctual = extensions["KHR_lights_punctual"];
  4667. if (!lights_punctual.has("lights")) {
  4668. return OK;
  4669. }
  4670. const Array &lights = lights_punctual["lights"];
  4671. for (GLTFLightIndex light_i = 0; light_i < lights.size(); light_i++) {
  4672. Ref<GLTFLight> light = GLTFLight::from_dictionary(lights[light_i]);
  4673. if (light.is_null()) {
  4674. return Error::ERR_PARSE_ERROR;
  4675. }
  4676. p_state->lights.push_back(light);
  4677. }
  4678. print_verbose("glTF: Total lights: " + itos(p_state->lights.size()));
  4679. return OK;
  4680. }
  4681. Error GLTFDocument::_parse_cameras(Ref<GLTFState> p_state) {
  4682. if (!p_state->json.has("cameras")) {
  4683. return OK;
  4684. }
  4685. const Array cameras = p_state->json["cameras"];
  4686. for (GLTFCameraIndex i = 0; i < cameras.size(); i++) {
  4687. p_state->cameras.push_back(GLTFCamera::from_dictionary(cameras[i]));
  4688. }
  4689. print_verbose("glTF: Total cameras: " + itos(p_state->cameras.size()));
  4690. return OK;
  4691. }
  4692. String GLTFDocument::interpolation_to_string(const GLTFAnimation::Interpolation p_interp) {
  4693. String interp = "LINEAR";
  4694. if (p_interp == GLTFAnimation::INTERP_STEP) {
  4695. interp = "STEP";
  4696. } else if (p_interp == GLTFAnimation::INTERP_LINEAR) {
  4697. interp = "LINEAR";
  4698. } else if (p_interp == GLTFAnimation::INTERP_CATMULLROMSPLINE) {
  4699. interp = "CATMULLROMSPLINE";
  4700. } else if (p_interp == GLTFAnimation::INTERP_CUBIC_SPLINE) {
  4701. interp = "CUBICSPLINE";
  4702. }
  4703. return interp;
  4704. }
  4705. Error GLTFDocument::_serialize_animations(Ref<GLTFState> p_state) {
  4706. if (!p_state->animation_players.size()) {
  4707. return OK;
  4708. }
  4709. for (int32_t player_i = 0; player_i < p_state->animation_players.size(); player_i++) {
  4710. AnimationPlayer *animation_player = p_state->animation_players[player_i];
  4711. List<StringName> animations;
  4712. animation_player->get_animation_list(&animations);
  4713. for (const StringName &animation_name : animations) {
  4714. _convert_animation(p_state, animation_player, animation_name);
  4715. }
  4716. }
  4717. Array animations;
  4718. for (GLTFAnimationIndex animation_i = 0; animation_i < p_state->animations.size(); animation_i++) {
  4719. Dictionary d;
  4720. Ref<GLTFAnimation> gltf_animation = p_state->animations[animation_i];
  4721. if (gltf_animation->is_empty_of_tracks()) {
  4722. continue;
  4723. }
  4724. if (!gltf_animation->get_name().is_empty()) {
  4725. d["name"] = gltf_animation->get_name();
  4726. }
  4727. Array channels;
  4728. Array samplers;
  4729. // Serialize glTF node tracks with the vanilla glTF animation system.
  4730. for (KeyValue<int, GLTFAnimation::NodeTrack> &track_i : gltf_animation->get_node_tracks()) {
  4731. GLTFAnimation::NodeTrack track = track_i.value;
  4732. if (track.position_track.times.size()) {
  4733. Dictionary t;
  4734. t["sampler"] = samplers.size();
  4735. Dictionary s;
  4736. s["interpolation"] = interpolation_to_string(track.position_track.interpolation);
  4737. Vector<double> times = track.position_track.times;
  4738. s["input"] = _encode_accessor_as_floats(p_state, times, false);
  4739. Vector<Vector3> values = track.position_track.values;
  4740. s["output"] = _encode_accessor_as_vec3(p_state, values, false);
  4741. samplers.push_back(s);
  4742. Dictionary target;
  4743. target["path"] = "translation";
  4744. target["node"] = track_i.key;
  4745. t["target"] = target;
  4746. channels.push_back(t);
  4747. }
  4748. if (track.rotation_track.times.size()) {
  4749. Dictionary t;
  4750. t["sampler"] = samplers.size();
  4751. Dictionary s;
  4752. s["interpolation"] = interpolation_to_string(track.rotation_track.interpolation);
  4753. Vector<double> times = track.rotation_track.times;
  4754. s["input"] = _encode_accessor_as_floats(p_state, times, false);
  4755. Vector<Quaternion> values = track.rotation_track.values;
  4756. s["output"] = _encode_accessor_as_quaternions(p_state, values, false);
  4757. samplers.push_back(s);
  4758. Dictionary target;
  4759. target["path"] = "rotation";
  4760. target["node"] = track_i.key;
  4761. t["target"] = target;
  4762. channels.push_back(t);
  4763. }
  4764. if (track.scale_track.times.size()) {
  4765. Dictionary t;
  4766. t["sampler"] = samplers.size();
  4767. Dictionary s;
  4768. s["interpolation"] = interpolation_to_string(track.scale_track.interpolation);
  4769. Vector<double> times = track.scale_track.times;
  4770. s["input"] = _encode_accessor_as_floats(p_state, times, false);
  4771. Vector<Vector3> values = track.scale_track.values;
  4772. s["output"] = _encode_accessor_as_vec3(p_state, values, false);
  4773. samplers.push_back(s);
  4774. Dictionary target;
  4775. target["path"] = "scale";
  4776. target["node"] = track_i.key;
  4777. t["target"] = target;
  4778. channels.push_back(t);
  4779. }
  4780. if (track.weight_tracks.size()) {
  4781. double length = 0.0f;
  4782. for (int32_t track_idx = 0; track_idx < track.weight_tracks.size(); track_idx++) {
  4783. int32_t last_time_index = track.weight_tracks[track_idx].times.size() - 1;
  4784. length = MAX(length, track.weight_tracks[track_idx].times[last_time_index]);
  4785. }
  4786. Dictionary t;
  4787. t["sampler"] = samplers.size();
  4788. Dictionary s;
  4789. Vector<double> times;
  4790. const double increment = 1.0 / p_state->get_bake_fps();
  4791. {
  4792. double time = 0.0;
  4793. bool last = false;
  4794. while (true) {
  4795. times.push_back(time);
  4796. if (last) {
  4797. break;
  4798. }
  4799. time += increment;
  4800. if (time >= length) {
  4801. last = true;
  4802. time = length;
  4803. }
  4804. }
  4805. }
  4806. for (int32_t track_idx = 0; track_idx < track.weight_tracks.size(); track_idx++) {
  4807. double time = 0.0;
  4808. bool last = false;
  4809. Vector<real_t> weight_track;
  4810. while (true) {
  4811. float weight = _interpolate_track<real_t>(track.weight_tracks[track_idx].times,
  4812. track.weight_tracks[track_idx].values,
  4813. time,
  4814. track.weight_tracks[track_idx].interpolation);
  4815. weight_track.push_back(weight);
  4816. if (last) {
  4817. break;
  4818. }
  4819. time += increment;
  4820. if (time >= length) {
  4821. last = true;
  4822. time = length;
  4823. }
  4824. }
  4825. track.weight_tracks.write[track_idx].times = times;
  4826. track.weight_tracks.write[track_idx].values = weight_track;
  4827. }
  4828. Vector<double> all_track_times = times;
  4829. Vector<double> all_track_values;
  4830. int32_t values_size = track.weight_tracks[0].values.size();
  4831. int32_t weight_tracks_size = track.weight_tracks.size();
  4832. all_track_values.resize(weight_tracks_size * values_size);
  4833. for (int k = 0; k < track.weight_tracks.size(); k++) {
  4834. Vector<real_t> wdata = track.weight_tracks[k].values;
  4835. for (int l = 0; l < wdata.size(); l++) {
  4836. int32_t index = l * weight_tracks_size + k;
  4837. ERR_BREAK(index >= all_track_values.size());
  4838. all_track_values.write[index] = wdata.write[l];
  4839. }
  4840. }
  4841. s["interpolation"] = interpolation_to_string(track.weight_tracks[track.weight_tracks.size() - 1].interpolation);
  4842. s["input"] = _encode_accessor_as_floats(p_state, all_track_times, false);
  4843. s["output"] = _encode_accessor_as_floats(p_state, all_track_values, false);
  4844. samplers.push_back(s);
  4845. Dictionary target;
  4846. target["path"] = "weights";
  4847. target["node"] = track_i.key;
  4848. t["target"] = target;
  4849. channels.push_back(t);
  4850. }
  4851. }
  4852. if (!gltf_animation->get_pointer_tracks().is_empty()) {
  4853. // Serialize glTF pointer tracks with the KHR_animation_pointer extension.
  4854. if (!p_state->extensions_used.has("KHR_animation_pointer")) {
  4855. p_state->extensions_used.push_back("KHR_animation_pointer");
  4856. }
  4857. for (KeyValue<String, GLTFAnimation::Channel<Variant>> &pointer_track_iter : gltf_animation->get_pointer_tracks()) {
  4858. const String &json_pointer = pointer_track_iter.key;
  4859. const GLTFAnimation::Channel<Variant> &pointer_track = pointer_track_iter.value;
  4860. const Ref<GLTFObjectModelProperty> &obj_model_prop = p_state->object_model_properties[json_pointer];
  4861. Dictionary channel;
  4862. channel["sampler"] = samplers.size();
  4863. Dictionary channel_target;
  4864. channel_target["path"] = "pointer";
  4865. Dictionary channel_target_ext;
  4866. Dictionary channel_target_ext_khr_anim_ptr;
  4867. channel_target_ext_khr_anim_ptr["pointer"] = json_pointer;
  4868. channel_target_ext["KHR_animation_pointer"] = channel_target_ext_khr_anim_ptr;
  4869. channel_target["extensions"] = channel_target_ext;
  4870. channel["target"] = channel_target;
  4871. channels.push_back(channel);
  4872. Dictionary sampler;
  4873. sampler["input"] = _encode_accessor_as_floats(p_state, pointer_track.times, false);
  4874. sampler["interpolation"] = interpolation_to_string(pointer_track.interpolation);
  4875. sampler["output"] = _encode_accessor_as_variant(p_state, pointer_track.values, obj_model_prop->get_variant_type(), obj_model_prop->get_accessor_type());
  4876. samplers.push_back(sampler);
  4877. }
  4878. }
  4879. if (channels.size() && samplers.size()) {
  4880. d["channels"] = channels;
  4881. d["samplers"] = samplers;
  4882. animations.push_back(d);
  4883. }
  4884. }
  4885. if (!animations.size()) {
  4886. return OK;
  4887. }
  4888. p_state->json["animations"] = animations;
  4889. print_verbose("glTF: Total animations '" + itos(p_state->animations.size()) + "'.");
  4890. return OK;
  4891. }
  4892. Error GLTFDocument::_parse_animations(Ref<GLTFState> p_state) {
  4893. if (!p_state->json.has("animations")) {
  4894. return OK;
  4895. }
  4896. const Array &animations = p_state->json["animations"];
  4897. for (GLTFAnimationIndex anim_index = 0; anim_index < animations.size(); anim_index++) {
  4898. const Dictionary &anim_dict = animations[anim_index];
  4899. Ref<GLTFAnimation> animation;
  4900. animation.instantiate();
  4901. if (!anim_dict.has("channels") || !anim_dict.has("samplers")) {
  4902. continue;
  4903. }
  4904. Array channels = anim_dict["channels"];
  4905. Array samplers = anim_dict["samplers"];
  4906. if (anim_dict.has("name")) {
  4907. const String anim_name = anim_dict["name"];
  4908. const String anim_name_lower = anim_name.to_lower();
  4909. if (anim_name_lower.begins_with("loop") || anim_name_lower.ends_with("loop") || anim_name_lower.begins_with("cycle") || anim_name_lower.ends_with("cycle")) {
  4910. animation->set_loop(true);
  4911. }
  4912. animation->set_original_name(anim_name);
  4913. animation->set_name(_gen_unique_animation_name(p_state, anim_name));
  4914. }
  4915. for (int channel_index = 0; channel_index < channels.size(); channel_index++) {
  4916. const Dictionary &anim_channel = channels[channel_index];
  4917. ERR_FAIL_COND_V_MSG(!anim_channel.has("sampler"), ERR_PARSE_ERROR, "glTF: Animation channel missing required 'sampler' property.");
  4918. ERR_FAIL_COND_V_MSG(!anim_channel.has("target"), ERR_PARSE_ERROR, "glTF: Animation channel missing required 'target' property.");
  4919. // Parse sampler.
  4920. const int sampler_index = anim_channel["sampler"];
  4921. ERR_FAIL_INDEX_V(sampler_index, samplers.size(), ERR_PARSE_ERROR);
  4922. const Dictionary &sampler_dict = samplers[sampler_index];
  4923. ERR_FAIL_COND_V(!sampler_dict.has("input"), ERR_PARSE_ERROR);
  4924. ERR_FAIL_COND_V(!sampler_dict.has("output"), ERR_PARSE_ERROR);
  4925. const int input_time_accessor_index = sampler_dict["input"];
  4926. const int output_value_accessor_index = sampler_dict["output"];
  4927. GLTFAnimation::Interpolation interp = GLTFAnimation::INTERP_LINEAR;
  4928. int output_count = 1;
  4929. if (sampler_dict.has("interpolation")) {
  4930. const String &in = sampler_dict["interpolation"];
  4931. if (in == "STEP") {
  4932. interp = GLTFAnimation::INTERP_STEP;
  4933. } else if (in == "LINEAR") {
  4934. interp = GLTFAnimation::INTERP_LINEAR;
  4935. } else if (in == "CATMULLROMSPLINE") {
  4936. interp = GLTFAnimation::INTERP_CATMULLROMSPLINE;
  4937. output_count = 3;
  4938. } else if (in == "CUBICSPLINE") {
  4939. interp = GLTFAnimation::INTERP_CUBIC_SPLINE;
  4940. output_count = 3;
  4941. }
  4942. }
  4943. const Vector<double> times = _decode_accessor(p_state, input_time_accessor_index, false);
  4944. // Parse target.
  4945. const Dictionary &anim_target = anim_channel["target"];
  4946. ERR_FAIL_COND_V_MSG(!anim_target.has("path"), ERR_PARSE_ERROR, "glTF: Animation channel target missing required 'path' property.");
  4947. String path = anim_target["path"];
  4948. if (path == "pointer") {
  4949. ERR_FAIL_COND_V(!anim_target.has("extensions"), ERR_PARSE_ERROR);
  4950. Dictionary target_extensions = anim_target["extensions"];
  4951. ERR_FAIL_COND_V(!target_extensions.has("KHR_animation_pointer"), ERR_PARSE_ERROR);
  4952. Dictionary khr_anim_ptr = target_extensions["KHR_animation_pointer"];
  4953. ERR_FAIL_COND_V(!khr_anim_ptr.has("pointer"), ERR_PARSE_ERROR);
  4954. String anim_json_ptr = khr_anim_ptr["pointer"];
  4955. _parse_animation_pointer(p_state, anim_json_ptr, animation, interp, times, output_value_accessor_index);
  4956. } else {
  4957. // If it's not a pointer, it's a regular animation channel from vanilla glTF (pos/rot/scale/weights).
  4958. if (!anim_target.has("node")) {
  4959. WARN_PRINT("glTF: Animation channel target missing 'node' property. Ignoring this channel.");
  4960. continue;
  4961. }
  4962. GLTFNodeIndex node = anim_target["node"];
  4963. ERR_FAIL_INDEX_V(node, p_state->nodes.size(), ERR_PARSE_ERROR);
  4964. GLTFAnimation::NodeTrack *track = nullptr;
  4965. if (!animation->get_node_tracks().has(node)) {
  4966. animation->get_node_tracks()[node] = GLTFAnimation::NodeTrack();
  4967. }
  4968. track = &animation->get_node_tracks()[node];
  4969. if (path == "translation") {
  4970. const Vector<Vector3> positions = _decode_accessor_as_vec3(p_state, output_value_accessor_index, false);
  4971. track->position_track.interpolation = interp;
  4972. track->position_track.times = times;
  4973. track->position_track.values = positions;
  4974. } else if (path == "rotation") {
  4975. const Vector<Quaternion> rotations = _decode_accessor_as_quaternion(p_state, output_value_accessor_index, false);
  4976. track->rotation_track.interpolation = interp;
  4977. track->rotation_track.times = times;
  4978. track->rotation_track.values = rotations;
  4979. } else if (path == "scale") {
  4980. const Vector<Vector3> scales = _decode_accessor_as_vec3(p_state, output_value_accessor_index, false);
  4981. track->scale_track.interpolation = interp;
  4982. track->scale_track.times = times;
  4983. track->scale_track.values = scales;
  4984. } else if (path == "weights") {
  4985. const Vector<float> weights = _decode_accessor_as_floats(p_state, output_value_accessor_index, false);
  4986. ERR_FAIL_INDEX_V(p_state->nodes[node]->mesh, p_state->meshes.size(), ERR_PARSE_ERROR);
  4987. Ref<GLTFMesh> mesh = p_state->meshes[p_state->nodes[node]->mesh];
  4988. const int wc = mesh->get_blend_weights().size();
  4989. ERR_CONTINUE_MSG(wc == 0, "glTF: Animation tried to animate weights, but mesh has no weights.");
  4990. track->weight_tracks.resize(wc);
  4991. const int expected_value_count = times.size() * output_count * wc;
  4992. ERR_CONTINUE_MSG(weights.size() != expected_value_count, "Invalid weight data, expected " + itos(expected_value_count) + " weight values, got " + itos(weights.size()) + " instead.");
  4993. const int wlen = weights.size() / wc;
  4994. for (int k = 0; k < wc; k++) { //separate tracks, having them together is not such a good idea
  4995. GLTFAnimation::Channel<real_t> cf;
  4996. cf.interpolation = interp;
  4997. cf.times = Variant(times);
  4998. Vector<real_t> wdata;
  4999. wdata.resize(wlen);
  5000. for (int l = 0; l < wlen; l++) {
  5001. wdata.write[l] = weights[l * wc + k];
  5002. }
  5003. cf.values = wdata;
  5004. track->weight_tracks.write[k] = cf;
  5005. }
  5006. } else {
  5007. WARN_PRINT("Invalid path '" + path + "'.");
  5008. }
  5009. }
  5010. }
  5011. p_state->animations.push_back(animation);
  5012. }
  5013. print_verbose("glTF: Total animations '" + itos(p_state->animations.size()) + "'.");
  5014. return OK;
  5015. }
  5016. void GLTFDocument::_parse_animation_pointer(Ref<GLTFState> p_state, const String &p_animation_json_pointer, const Ref<GLTFAnimation> p_gltf_animation, const GLTFAnimation::Interpolation p_interp, const Vector<double> &p_times, const int p_output_value_accessor_index) {
  5017. // Special case: Convert TRS animation pointers to node track pos/rot/scale.
  5018. // This is required to handle skeleton bones, and improves performance for regular nodes.
  5019. // Mark this as unlikely because TRS animation pointers are not recommended,
  5020. // since vanilla glTF animations can already animate TRS properties directly.
  5021. // But having this code exist is required to be spec-compliant and handle all test files.
  5022. // Note that TRS still needs to be handled in the general case as well, for KHR_interactivity.
  5023. const PackedStringArray split = p_animation_json_pointer.split("/", false, 3);
  5024. if (unlikely(split.size() == 3 && split[0] == "nodes" && (split[2] == "translation" || split[2] == "rotation" || split[2] == "scale" || split[2] == "matrix" || split[2] == "weights"))) {
  5025. const GLTFNodeIndex node_index = split[1].to_int();
  5026. HashMap<int, GLTFAnimation::NodeTrack> &node_tracks = p_gltf_animation->get_node_tracks();
  5027. if (!node_tracks.has(node_index)) {
  5028. node_tracks[node_index] = GLTFAnimation::NodeTrack();
  5029. }
  5030. GLTFAnimation::NodeTrack *track = &node_tracks[node_index];
  5031. if (split[2] == "translation") {
  5032. const Vector<Vector3> positions = _decode_accessor_as_vec3(p_state, p_output_value_accessor_index, false);
  5033. track->position_track.interpolation = p_interp;
  5034. track->position_track.times = p_times;
  5035. track->position_track.values = positions;
  5036. } else if (split[2] == "rotation") {
  5037. const Vector<Quaternion> rotations = _decode_accessor_as_quaternion(p_state, p_output_value_accessor_index, false);
  5038. track->rotation_track.interpolation = p_interp;
  5039. track->rotation_track.times = p_times;
  5040. track->rotation_track.values = rotations;
  5041. } else if (split[2] == "scale") {
  5042. const Vector<Vector3> scales = _decode_accessor_as_vec3(p_state, p_output_value_accessor_index, false);
  5043. track->scale_track.interpolation = p_interp;
  5044. track->scale_track.times = p_times;
  5045. track->scale_track.values = scales;
  5046. } else if (split[2] == "matrix") {
  5047. const Vector<Transform3D> transforms = _decode_accessor_as_xform(p_state, p_output_value_accessor_index, false);
  5048. track->position_track.interpolation = p_interp;
  5049. track->position_track.times = p_times;
  5050. track->position_track.values.resize(transforms.size());
  5051. track->rotation_track.interpolation = p_interp;
  5052. track->rotation_track.times = p_times;
  5053. track->rotation_track.values.resize(transforms.size());
  5054. track->scale_track.interpolation = p_interp;
  5055. track->scale_track.times = p_times;
  5056. track->scale_track.values.resize(transforms.size());
  5057. for (int i = 0; i < transforms.size(); i++) {
  5058. track->position_track.values.write[i] = transforms[i].get_origin();
  5059. track->rotation_track.values.write[i] = transforms[i].basis.get_rotation_quaternion();
  5060. track->scale_track.values.write[i] = transforms[i].basis.get_scale();
  5061. }
  5062. } else { // if (split[2] == "weights")
  5063. const Vector<float> accessor_weights = _decode_accessor_as_floats(p_state, p_output_value_accessor_index, false);
  5064. const GLTFMeshIndex mesh_index = p_state->nodes[node_index]->mesh;
  5065. ERR_FAIL_INDEX(mesh_index, p_state->meshes.size());
  5066. const Ref<GLTFMesh> gltf_mesh = p_state->meshes[mesh_index];
  5067. const Vector<float> &blend_weights = gltf_mesh->get_blend_weights();
  5068. const int blend_weight_count = gltf_mesh->get_blend_weights().size();
  5069. const int anim_weights_size = accessor_weights.size();
  5070. // For example, if a mesh has 2 blend weights, and the accessor provides 10 values, then there are 5 frames of animation, each with 2 blend weights.
  5071. ERR_FAIL_COND_MSG(blend_weight_count == 0 || ((anim_weights_size % blend_weight_count) != 0), "glTF: Cannot apply " + itos(accessor_weights.size()) + " weights to a mesh with " + itos(blend_weights.size()) + " blend weights.");
  5072. const int frame_count = anim_weights_size / blend_weight_count;
  5073. track->weight_tracks.resize(blend_weight_count);
  5074. for (int blend_weight_index = 0; blend_weight_index < blend_weight_count; blend_weight_index++) {
  5075. GLTFAnimation::Channel<real_t> weight_track;
  5076. weight_track.interpolation = p_interp;
  5077. weight_track.times = p_times;
  5078. weight_track.values.resize(frame_count);
  5079. for (int frame_index = 0; frame_index < frame_count; frame_index++) {
  5080. // For example, if a mesh has 2 blend weights, and the accessor provides 10 values,
  5081. // then the first frame has indices [0, 1], the second frame has [2, 3], and so on.
  5082. // Here we process all frames of one blend weight, so we want [0, 2, 4, 6, 8] or [1, 3, 5, 7, 9].
  5083. // For the fist one we calculate 0 * 2 + 0, 1 * 2 + 0, 2 * 2 + 0, etc, then for the second 0 * 2 + 1, 1 * 2 + 1, 2 * 2 + 1, etc.
  5084. weight_track.values.write[frame_index] = accessor_weights[frame_index * blend_weight_count + blend_weight_index];
  5085. }
  5086. track->weight_tracks.write[blend_weight_index] = weight_track;
  5087. }
  5088. }
  5089. // The special case was handled, return to skip the general case.
  5090. return;
  5091. }
  5092. // General case: Convert animation pointers to Variant value pointer tracks.
  5093. Ref<GLTFObjectModelProperty> obj_model_prop = import_object_model_property(p_state, p_animation_json_pointer);
  5094. if (obj_model_prop.is_null() || !obj_model_prop->has_node_paths()) {
  5095. // Exit quietly, `import_object_model_property` already prints a warning if the property is not found.
  5096. return;
  5097. }
  5098. HashMap<String, GLTFAnimation::Channel<Variant>> &anim_ptr_map = p_gltf_animation->get_pointer_tracks();
  5099. GLTFAnimation::Channel<Variant> channel;
  5100. channel.interpolation = p_interp;
  5101. channel.times = p_times;
  5102. channel.values = _decode_accessor_as_variant(p_state, p_output_value_accessor_index, obj_model_prop->get_variant_type(), obj_model_prop->get_accessor_type());
  5103. anim_ptr_map[p_animation_json_pointer] = channel;
  5104. }
  5105. void GLTFDocument::_assign_node_names(Ref<GLTFState> p_state) {
  5106. for (int i = 0; i < p_state->nodes.size(); i++) {
  5107. Ref<GLTFNode> gltf_node = p_state->nodes[i];
  5108. // Any joints get unique names generated when the skeleton is made, unique to the skeleton
  5109. if (gltf_node->skeleton >= 0) {
  5110. continue;
  5111. }
  5112. String gltf_node_name = gltf_node->get_name();
  5113. if (gltf_node_name.is_empty()) {
  5114. if (_naming_version == 0) {
  5115. if (gltf_node->mesh >= 0) {
  5116. gltf_node_name = _gen_unique_name(p_state, "Mesh");
  5117. } else if (gltf_node->camera >= 0) {
  5118. gltf_node_name = _gen_unique_name(p_state, "Camera3D");
  5119. } else {
  5120. gltf_node_name = _gen_unique_name(p_state, "Node");
  5121. }
  5122. } else {
  5123. if (gltf_node->mesh >= 0) {
  5124. gltf_node_name = "Mesh";
  5125. } else if (gltf_node->camera >= 0) {
  5126. gltf_node_name = "Camera";
  5127. } else {
  5128. gltf_node_name = "Node";
  5129. }
  5130. }
  5131. }
  5132. gltf_node->set_name(_gen_unique_name(p_state, gltf_node_name));
  5133. }
  5134. }
  5135. BoneAttachment3D *GLTFDocument::_generate_bone_attachment(Ref<GLTFState> p_state, Skeleton3D *p_skeleton, const GLTFNodeIndex p_node_index, const GLTFNodeIndex p_bone_index) {
  5136. Ref<GLTFNode> gltf_node = p_state->nodes[p_node_index];
  5137. Ref<GLTFNode> bone_node = p_state->nodes[p_bone_index];
  5138. BoneAttachment3D *bone_attachment = memnew(BoneAttachment3D);
  5139. print_verbose("glTF: Creating bone attachment for: " + gltf_node->get_name());
  5140. ERR_FAIL_COND_V(!bone_node->joint, nullptr);
  5141. bone_attachment->set_bone_name(bone_node->get_name());
  5142. return bone_attachment;
  5143. }
  5144. GLTFMeshIndex GLTFDocument::_convert_mesh_to_gltf(Ref<GLTFState> p_state, MeshInstance3D *p_mesh_instance) {
  5145. ERR_FAIL_NULL_V(p_mesh_instance, -1);
  5146. ERR_FAIL_COND_V_MSG(p_mesh_instance->get_mesh().is_null(), -1, "glTF: Tried to export a MeshInstance3D node named " + p_mesh_instance->get_name() + ", but it has no mesh. This node will be exported without a mesh.");
  5147. Ref<Mesh> mesh_resource = p_mesh_instance->get_mesh();
  5148. ERR_FAIL_COND_V_MSG(mesh_resource->get_surface_count() == 0, -1, "glTF: Tried to export a MeshInstance3D node named " + p_mesh_instance->get_name() + ", but its mesh has no surfaces. This node will be exported without a mesh.");
  5149. TypedArray<Material> instance_materials;
  5150. for (int32_t surface_i = 0; surface_i < mesh_resource->get_surface_count(); surface_i++) {
  5151. Ref<Material> mat = p_mesh_instance->get_active_material(surface_i);
  5152. instance_materials.append(mat);
  5153. }
  5154. Ref<ImporterMesh> current_mesh = _mesh_to_importer_mesh(mesh_resource);
  5155. Vector<float> blend_weights;
  5156. int32_t blend_count = mesh_resource->get_blend_shape_count();
  5157. blend_weights.resize(blend_count);
  5158. for (int32_t blend_i = 0; blend_i < blend_count; blend_i++) {
  5159. blend_weights.write[blend_i] = 0.0f;
  5160. }
  5161. Ref<GLTFMesh> gltf_mesh;
  5162. gltf_mesh.instantiate();
  5163. gltf_mesh->set_instance_materials(instance_materials);
  5164. gltf_mesh->set_mesh(current_mesh);
  5165. gltf_mesh->set_blend_weights(blend_weights);
  5166. GLTFMeshIndex mesh_i = p_state->meshes.size();
  5167. p_state->meshes.push_back(gltf_mesh);
  5168. return mesh_i;
  5169. }
  5170. ImporterMeshInstance3D *GLTFDocument::_generate_mesh_instance(Ref<GLTFState> p_state, const GLTFNodeIndex p_node_index) {
  5171. Ref<GLTFNode> gltf_node = p_state->nodes[p_node_index];
  5172. ERR_FAIL_INDEX_V(gltf_node->mesh, p_state->meshes.size(), nullptr);
  5173. ImporterMeshInstance3D *mi = memnew(ImporterMeshInstance3D);
  5174. print_verbose("glTF: Creating mesh for: " + gltf_node->get_name());
  5175. p_state->scene_mesh_instances.insert(p_node_index, mi);
  5176. Ref<GLTFMesh> mesh = p_state->meshes.write[gltf_node->mesh];
  5177. if (mesh.is_null()) {
  5178. return mi;
  5179. }
  5180. Ref<ImporterMesh> import_mesh = mesh->get_mesh();
  5181. if (import_mesh.is_null()) {
  5182. return mi;
  5183. }
  5184. mi->set_mesh(import_mesh);
  5185. import_mesh->merge_meta_from(*mesh);
  5186. return mi;
  5187. }
  5188. Light3D *GLTFDocument::_generate_light(Ref<GLTFState> p_state, const GLTFNodeIndex p_node_index) {
  5189. Ref<GLTFNode> gltf_node = p_state->nodes[p_node_index];
  5190. ERR_FAIL_INDEX_V(gltf_node->light, p_state->lights.size(), nullptr);
  5191. print_verbose("glTF: Creating light for: " + gltf_node->get_name());
  5192. Ref<GLTFLight> l = p_state->lights[gltf_node->light];
  5193. return l->to_node();
  5194. }
  5195. Camera3D *GLTFDocument::_generate_camera(Ref<GLTFState> p_state, const GLTFNodeIndex p_node_index) {
  5196. Ref<GLTFNode> gltf_node = p_state->nodes[p_node_index];
  5197. ERR_FAIL_INDEX_V(gltf_node->camera, p_state->cameras.size(), nullptr);
  5198. print_verbose("glTF: Creating camera for: " + gltf_node->get_name());
  5199. Ref<GLTFCamera> c = p_state->cameras[gltf_node->camera];
  5200. return c->to_node();
  5201. }
  5202. GLTFCameraIndex GLTFDocument::_convert_camera(Ref<GLTFState> p_state, Camera3D *p_camera) {
  5203. print_verbose("glTF: Converting camera: " + p_camera->get_name());
  5204. Ref<GLTFCamera> c = GLTFCamera::from_node(p_camera);
  5205. GLTFCameraIndex camera_index = p_state->cameras.size();
  5206. p_state->cameras.push_back(c);
  5207. return camera_index;
  5208. }
  5209. GLTFLightIndex GLTFDocument::_convert_light(Ref<GLTFState> p_state, Light3D *p_light) {
  5210. print_verbose("glTF: Converting light: " + p_light->get_name());
  5211. Ref<GLTFLight> l = GLTFLight::from_node(p_light);
  5212. GLTFLightIndex light_index = p_state->lights.size();
  5213. p_state->lights.push_back(l);
  5214. return light_index;
  5215. }
  5216. void GLTFDocument::_convert_spatial(Ref<GLTFState> p_state, Node3D *p_spatial, Ref<GLTFNode> p_node) {
  5217. p_node->transform = p_spatial->get_transform();
  5218. }
  5219. Node3D *GLTFDocument::_generate_spatial(Ref<GLTFState> p_state, const GLTFNodeIndex p_node_index) {
  5220. Ref<GLTFNode> gltf_node = p_state->nodes[p_node_index];
  5221. Node3D *spatial = memnew(Node3D);
  5222. print_verbose("glTF: Converting spatial: " + gltf_node->get_name());
  5223. return spatial;
  5224. }
  5225. void GLTFDocument::_convert_scene_node(Ref<GLTFState> p_state, Node *p_current, const GLTFNodeIndex p_gltf_parent, const GLTFNodeIndex p_gltf_root) {
  5226. bool retflag = true;
  5227. _check_visibility(p_current, retflag);
  5228. if (retflag) {
  5229. return;
  5230. }
  5231. #ifdef TOOLS_ENABLED
  5232. if (Engine::get_singleton()->is_editor_hint() && p_gltf_root != -1 && p_current->get_owner() == nullptr) {
  5233. WARN_VERBOSE("glTF export warning: Node '" + p_current->get_name() + "' has no owner. This is likely a temporary node generated by a @tool script. This would not be saved when saving the Godot scene, therefore it will not be exported to glTF.");
  5234. return;
  5235. }
  5236. #endif // TOOLS_ENABLED
  5237. Ref<GLTFNode> gltf_node;
  5238. gltf_node.instantiate();
  5239. gltf_node->set_original_name(p_current->get_name());
  5240. gltf_node->set_name(_gen_unique_name(p_state, p_current->get_name()));
  5241. gltf_node->merge_meta_from(p_current);
  5242. if (Object::cast_to<Node3D>(p_current)) {
  5243. Node3D *spatial = Object::cast_to<Node3D>(p_current);
  5244. _convert_spatial(p_state, spatial, gltf_node);
  5245. }
  5246. if (Object::cast_to<MeshInstance3D>(p_current)) {
  5247. MeshInstance3D *mi = Object::cast_to<MeshInstance3D>(p_current);
  5248. _convert_mesh_instance_to_gltf(mi, p_state, gltf_node);
  5249. } else if (Object::cast_to<BoneAttachment3D>(p_current)) {
  5250. BoneAttachment3D *bone = Object::cast_to<BoneAttachment3D>(p_current);
  5251. _convert_bone_attachment_to_gltf(bone, p_state, p_gltf_parent, p_gltf_root, gltf_node);
  5252. return;
  5253. } else if (Object::cast_to<Skeleton3D>(p_current)) {
  5254. Skeleton3D *skel = Object::cast_to<Skeleton3D>(p_current);
  5255. _convert_skeleton_to_gltf(skel, p_state, p_gltf_parent, p_gltf_root, gltf_node);
  5256. // We ignore the Godot Engine node that is the skeleton.
  5257. return;
  5258. } else if (Object::cast_to<MultiMeshInstance3D>(p_current)) {
  5259. MultiMeshInstance3D *multi = Object::cast_to<MultiMeshInstance3D>(p_current);
  5260. _convert_multi_mesh_instance_to_gltf(multi, p_gltf_parent, p_gltf_root, gltf_node, p_state);
  5261. #ifdef MODULE_CSG_ENABLED
  5262. } else if (Object::cast_to<CSGShape3D>(p_current)) {
  5263. CSGShape3D *shape = Object::cast_to<CSGShape3D>(p_current);
  5264. if (shape->get_parent() && shape->is_root_shape()) {
  5265. _convert_csg_shape_to_gltf(shape, p_gltf_parent, gltf_node, p_state);
  5266. }
  5267. #endif // MODULE_CSG_ENABLED
  5268. #ifdef MODULE_GRIDMAP_ENABLED
  5269. } else if (Object::cast_to<GridMap>(p_current)) {
  5270. GridMap *gridmap = Object::cast_to<GridMap>(p_current);
  5271. _convert_grid_map_to_gltf(gridmap, p_gltf_parent, p_gltf_root, gltf_node, p_state);
  5272. #endif // MODULE_GRIDMAP_ENABLED
  5273. } else if (Object::cast_to<Camera3D>(p_current)) {
  5274. Camera3D *camera = Object::cast_to<Camera3D>(p_current);
  5275. _convert_camera_to_gltf(camera, p_state, gltf_node);
  5276. } else if (Object::cast_to<Light3D>(p_current)) {
  5277. Light3D *light = Object::cast_to<Light3D>(p_current);
  5278. _convert_light_to_gltf(light, p_state, gltf_node);
  5279. } else if (Object::cast_to<AnimationPlayer>(p_current)) {
  5280. AnimationPlayer *animation_player = Object::cast_to<AnimationPlayer>(p_current);
  5281. p_state->animation_players.push_back(animation_player);
  5282. }
  5283. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  5284. ERR_CONTINUE(ext.is_null());
  5285. ext->convert_scene_node(p_state, gltf_node, p_current);
  5286. }
  5287. GLTFNodeIndex current_node_i;
  5288. if (gltf_node->get_parent() == -1) {
  5289. current_node_i = p_state->append_gltf_node(gltf_node, p_current, p_gltf_parent);
  5290. } else if (gltf_node->get_parent() < -1) {
  5291. return;
  5292. } else {
  5293. current_node_i = p_state->nodes.size() - 1;
  5294. while (gltf_node != p_state->nodes[current_node_i]) {
  5295. current_node_i--;
  5296. }
  5297. }
  5298. const GLTFNodeIndex gltf_root = (p_gltf_root == -1) ? current_node_i : p_gltf_root;
  5299. for (int node_i = 0; node_i < p_current->get_child_count(); node_i++) {
  5300. _convert_scene_node(p_state, p_current->get_child(node_i), current_node_i, gltf_root);
  5301. }
  5302. }
  5303. #ifdef MODULE_CSG_ENABLED
  5304. void GLTFDocument::_convert_csg_shape_to_gltf(CSGShape3D *p_current, GLTFNodeIndex p_gltf_parent, Ref<GLTFNode> p_gltf_node, Ref<GLTFState> p_state) {
  5305. CSGShape3D *csg = p_current;
  5306. csg->call("_update_shape");
  5307. Array meshes = csg->get_meshes();
  5308. if (meshes.size() != 2) {
  5309. return;
  5310. }
  5311. Ref<ImporterMesh> mesh;
  5312. mesh.instantiate();
  5313. {
  5314. Ref<ArrayMesh> csg_mesh = csg->get_meshes()[1];
  5315. for (int32_t surface_i = 0; surface_i < csg_mesh->get_surface_count(); surface_i++) {
  5316. Array array = csg_mesh->surface_get_arrays(surface_i);
  5317. Ref<Material> mat;
  5318. Ref<Material> mat_override = csg->get_material_override();
  5319. if (mat_override.is_valid()) {
  5320. mat = mat_override;
  5321. }
  5322. Ref<Material> mat_surface_override = csg_mesh->surface_get_material(surface_i);
  5323. if (mat_surface_override.is_valid() && mat.is_null()) {
  5324. mat = mat_surface_override;
  5325. }
  5326. String mat_name;
  5327. if (mat.is_valid()) {
  5328. mat_name = mat->get_name();
  5329. } else {
  5330. // Assign default material when no material is assigned.
  5331. mat.instantiate();
  5332. }
  5333. mesh->add_surface(csg_mesh->surface_get_primitive_type(surface_i),
  5334. array, csg_mesh->surface_get_blend_shape_arrays(surface_i), csg_mesh->surface_get_lods(surface_i), mat,
  5335. mat_name, csg_mesh->surface_get_format(surface_i));
  5336. }
  5337. }
  5338. Ref<GLTFMesh> gltf_mesh;
  5339. gltf_mesh.instantiate();
  5340. gltf_mesh->set_mesh(mesh);
  5341. gltf_mesh->set_original_name(csg->get_name());
  5342. GLTFMeshIndex mesh_i = p_state->meshes.size();
  5343. p_state->meshes.push_back(gltf_mesh);
  5344. p_gltf_node->mesh = mesh_i;
  5345. p_gltf_node->transform = csg->get_transform();
  5346. p_gltf_node->set_original_name(csg->get_name());
  5347. p_gltf_node->set_name(_gen_unique_name(p_state, csg->get_name()));
  5348. }
  5349. #endif // MODULE_CSG_ENABLED
  5350. void GLTFDocument::_check_visibility(Node *p_node, bool &r_retflag) {
  5351. r_retflag = true;
  5352. Node3D *spatial = Object::cast_to<Node3D>(p_node);
  5353. Node2D *node_2d = Object::cast_to<Node2D>(p_node);
  5354. if (node_2d && !node_2d->is_visible()) {
  5355. return;
  5356. }
  5357. if (spatial && !spatial->is_visible()) {
  5358. return;
  5359. }
  5360. r_retflag = false;
  5361. }
  5362. void GLTFDocument::_convert_camera_to_gltf(Camera3D *camera, Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node) {
  5363. ERR_FAIL_NULL(camera);
  5364. GLTFCameraIndex camera_index = _convert_camera(p_state, camera);
  5365. if (camera_index != -1) {
  5366. p_gltf_node->camera = camera_index;
  5367. }
  5368. }
  5369. void GLTFDocument::_convert_light_to_gltf(Light3D *light, Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node) {
  5370. ERR_FAIL_NULL(light);
  5371. GLTFLightIndex light_index = _convert_light(p_state, light);
  5372. if (light_index != -1) {
  5373. p_gltf_node->light = light_index;
  5374. }
  5375. }
  5376. #ifdef MODULE_GRIDMAP_ENABLED
  5377. void GLTFDocument::_convert_grid_map_to_gltf(GridMap *p_grid_map, GLTFNodeIndex p_parent_node_index, GLTFNodeIndex p_root_node_index, Ref<GLTFNode> p_gltf_node, Ref<GLTFState> p_state) {
  5378. Array cells = p_grid_map->get_used_cells();
  5379. for (int32_t k = 0; k < cells.size(); k++) {
  5380. GLTFNode *new_gltf_node = memnew(GLTFNode);
  5381. p_gltf_node->children.push_back(p_state->nodes.size());
  5382. p_state->nodes.push_back(new_gltf_node);
  5383. Vector3 cell_location = cells[k];
  5384. int32_t cell = p_grid_map->get_cell_item(
  5385. Vector3(cell_location.x, cell_location.y, cell_location.z));
  5386. Transform3D cell_xform;
  5387. cell_xform.basis = p_grid_map->get_basis_with_orthogonal_index(
  5388. p_grid_map->get_cell_item_orientation(
  5389. Vector3(cell_location.x, cell_location.y, cell_location.z)));
  5390. cell_xform.basis.scale(Vector3(p_grid_map->get_cell_scale(),
  5391. p_grid_map->get_cell_scale(),
  5392. p_grid_map->get_cell_scale()));
  5393. cell_xform.set_origin(p_grid_map->map_to_local(
  5394. Vector3(cell_location.x, cell_location.y, cell_location.z)));
  5395. Ref<GLTFMesh> gltf_mesh;
  5396. gltf_mesh.instantiate();
  5397. gltf_mesh->set_mesh(_mesh_to_importer_mesh(p_grid_map->get_mesh_library()->get_item_mesh(cell)));
  5398. gltf_mesh->set_original_name(p_grid_map->get_mesh_library()->get_item_name(cell));
  5399. new_gltf_node->mesh = p_state->meshes.size();
  5400. p_state->meshes.push_back(gltf_mesh);
  5401. new_gltf_node->transform = cell_xform * p_grid_map->get_transform();
  5402. new_gltf_node->set_original_name(p_grid_map->get_mesh_library()->get_item_name(cell));
  5403. new_gltf_node->set_name(_gen_unique_name(p_state, p_grid_map->get_mesh_library()->get_item_name(cell)));
  5404. }
  5405. }
  5406. #endif // MODULE_GRIDMAP_ENABLED
  5407. void GLTFDocument::_convert_multi_mesh_instance_to_gltf(
  5408. MultiMeshInstance3D *p_multi_mesh_instance,
  5409. GLTFNodeIndex p_parent_node_index,
  5410. GLTFNodeIndex p_root_node_index,
  5411. Ref<GLTFNode> p_gltf_node, Ref<GLTFState> p_state) {
  5412. ERR_FAIL_NULL(p_multi_mesh_instance);
  5413. Ref<MultiMesh> multi_mesh = p_multi_mesh_instance->get_multimesh();
  5414. if (multi_mesh.is_null()) {
  5415. return;
  5416. }
  5417. Ref<GLTFMesh> gltf_mesh;
  5418. gltf_mesh.instantiate();
  5419. Ref<Mesh> mesh = multi_mesh->get_mesh();
  5420. if (mesh.is_null()) {
  5421. return;
  5422. }
  5423. gltf_mesh->set_original_name(multi_mesh->get_name());
  5424. gltf_mesh->set_name(multi_mesh->get_name());
  5425. Ref<ImporterMesh> importer_mesh;
  5426. importer_mesh.instantiate();
  5427. Ref<ArrayMesh> array_mesh = multi_mesh->get_mesh();
  5428. if (array_mesh.is_valid()) {
  5429. importer_mesh->set_blend_shape_mode(array_mesh->get_blend_shape_mode());
  5430. for (int32_t blend_i = 0; blend_i < array_mesh->get_blend_shape_count(); blend_i++) {
  5431. importer_mesh->add_blend_shape(array_mesh->get_blend_shape_name(blend_i));
  5432. }
  5433. }
  5434. for (int32_t surface_i = 0; surface_i < mesh->get_surface_count(); surface_i++) {
  5435. Ref<Material> mat = mesh->surface_get_material(surface_i);
  5436. String material_name;
  5437. if (mat.is_valid()) {
  5438. material_name = mat->get_name();
  5439. }
  5440. Array blend_arrays;
  5441. if (array_mesh.is_valid()) {
  5442. blend_arrays = array_mesh->surface_get_blend_shape_arrays(surface_i);
  5443. }
  5444. importer_mesh->add_surface(mesh->surface_get_primitive_type(surface_i), mesh->surface_get_arrays(surface_i),
  5445. blend_arrays, mesh->surface_get_lods(surface_i), mat, material_name, mesh->surface_get_format(surface_i));
  5446. }
  5447. gltf_mesh->set_mesh(importer_mesh);
  5448. GLTFMeshIndex mesh_index = p_state->meshes.size();
  5449. p_state->meshes.push_back(gltf_mesh);
  5450. for (int32_t instance_i = 0; instance_i < multi_mesh->get_instance_count();
  5451. instance_i++) {
  5452. Transform3D transform;
  5453. if (multi_mesh->get_transform_format() == MultiMesh::TRANSFORM_2D) {
  5454. Transform2D xform_2d = multi_mesh->get_instance_transform_2d(instance_i);
  5455. transform.origin =
  5456. Vector3(xform_2d.get_origin().x, 0, xform_2d.get_origin().y);
  5457. real_t rotation = xform_2d.get_rotation();
  5458. Quaternion quaternion(Vector3(0, 1, 0), rotation);
  5459. Size2 scale = xform_2d.get_scale();
  5460. transform.basis.set_quaternion_scale(quaternion,
  5461. Vector3(scale.x, 0, scale.y));
  5462. transform = p_multi_mesh_instance->get_transform() * transform;
  5463. } else if (multi_mesh->get_transform_format() == MultiMesh::TRANSFORM_3D) {
  5464. transform = p_multi_mesh_instance->get_transform() *
  5465. multi_mesh->get_instance_transform(instance_i);
  5466. }
  5467. Ref<GLTFNode> new_gltf_node;
  5468. new_gltf_node.instantiate();
  5469. new_gltf_node->mesh = mesh_index;
  5470. new_gltf_node->transform = transform;
  5471. new_gltf_node->set_original_name(p_multi_mesh_instance->get_name());
  5472. new_gltf_node->set_name(_gen_unique_name(p_state, p_multi_mesh_instance->get_name()));
  5473. p_gltf_node->children.push_back(p_state->nodes.size());
  5474. p_state->nodes.push_back(new_gltf_node);
  5475. }
  5476. }
  5477. void GLTFDocument::_convert_skeleton_to_gltf(Skeleton3D *p_skeleton3d, Ref<GLTFState> p_state, GLTFNodeIndex p_parent_node_index, GLTFNodeIndex p_root_node_index, Ref<GLTFNode> p_gltf_node) {
  5478. Skeleton3D *skeleton = p_skeleton3d;
  5479. Ref<GLTFSkeleton> gltf_skeleton;
  5480. gltf_skeleton.instantiate();
  5481. // GLTFSkeleton is only used to hold internal p_state data. It will not be written to the document.
  5482. //
  5483. gltf_skeleton->godot_skeleton = skeleton;
  5484. GLTFSkeletonIndex skeleton_i = p_state->skeletons.size();
  5485. p_state->skeleton3d_to_gltf_skeleton[skeleton->get_instance_id()] = skeleton_i;
  5486. p_state->skeletons.push_back(gltf_skeleton);
  5487. BoneId bone_count = skeleton->get_bone_count();
  5488. for (BoneId bone_i = 0; bone_i < bone_count; bone_i++) {
  5489. Ref<GLTFNode> joint_node;
  5490. joint_node.instantiate();
  5491. // Note that we cannot use _gen_unique_bone_name here, because glTF spec requires all node
  5492. // names to be unique regardless of whether or not they are used as joints.
  5493. joint_node->set_original_name(skeleton->get_bone_name(bone_i));
  5494. joint_node->set_name(_gen_unique_name(p_state, skeleton->get_bone_name(bone_i)));
  5495. joint_node->transform = skeleton->get_bone_pose(bone_i);
  5496. joint_node->joint = true;
  5497. if (p_skeleton3d->has_bone_meta(bone_i, "extras")) {
  5498. joint_node->set_meta("extras", p_skeleton3d->get_bone_meta(bone_i, "extras"));
  5499. }
  5500. GLTFNodeIndex current_node_i = p_state->nodes.size();
  5501. p_state->scene_nodes.insert(current_node_i, skeleton);
  5502. p_state->nodes.push_back(joint_node);
  5503. gltf_skeleton->joints.push_back(current_node_i);
  5504. if (skeleton->get_bone_parent(bone_i) == -1) {
  5505. gltf_skeleton->roots.push_back(current_node_i);
  5506. }
  5507. gltf_skeleton->godot_bone_node.insert(bone_i, current_node_i);
  5508. }
  5509. for (BoneId bone_i = 0; bone_i < bone_count; bone_i++) {
  5510. GLTFNodeIndex current_node_i = gltf_skeleton->godot_bone_node[bone_i];
  5511. BoneId parent_bone_id = skeleton->get_bone_parent(bone_i);
  5512. if (parent_bone_id == -1) {
  5513. if (p_parent_node_index != -1) {
  5514. p_state->nodes.write[current_node_i]->parent = p_parent_node_index;
  5515. p_state->nodes.write[p_parent_node_index]->children.push_back(current_node_i);
  5516. }
  5517. } else {
  5518. GLTFNodeIndex parent_node_i = gltf_skeleton->godot_bone_node[parent_bone_id];
  5519. p_state->nodes.write[current_node_i]->parent = parent_node_i;
  5520. p_state->nodes.write[parent_node_i]->children.push_back(current_node_i);
  5521. }
  5522. }
  5523. // Remove placeholder skeleton3d node by not creating the gltf node
  5524. // Skins are per mesh
  5525. for (int node_i = 0; node_i < skeleton->get_child_count(); node_i++) {
  5526. _convert_scene_node(p_state, skeleton->get_child(node_i), p_parent_node_index, p_root_node_index);
  5527. }
  5528. }
  5529. void GLTFDocument::_convert_bone_attachment_to_gltf(BoneAttachment3D *p_bone_attachment, Ref<GLTFState> p_state, GLTFNodeIndex p_parent_node_index, GLTFNodeIndex p_root_node_index, Ref<GLTFNode> p_gltf_node) {
  5530. Skeleton3D *skeleton;
  5531. // Note that relative transforms to external skeletons and pose overrides are not supported.
  5532. if (p_bone_attachment->get_use_external_skeleton()) {
  5533. skeleton = Object::cast_to<Skeleton3D>(p_bone_attachment->get_node_or_null(p_bone_attachment->get_external_skeleton()));
  5534. } else {
  5535. skeleton = Object::cast_to<Skeleton3D>(p_bone_attachment->get_parent());
  5536. }
  5537. GLTFSkeletonIndex skel_gltf_i = -1;
  5538. if (skeleton != nullptr && p_state->skeleton3d_to_gltf_skeleton.has(skeleton->get_instance_id())) {
  5539. skel_gltf_i = p_state->skeleton3d_to_gltf_skeleton[skeleton->get_instance_id()];
  5540. }
  5541. int bone_idx = -1;
  5542. if (skeleton != nullptr) {
  5543. bone_idx = p_bone_attachment->get_bone_idx();
  5544. if (bone_idx == -1) {
  5545. bone_idx = skeleton->find_bone(p_bone_attachment->get_bone_name());
  5546. }
  5547. }
  5548. GLTFNodeIndex par_node_index = p_parent_node_index;
  5549. if (skeleton != nullptr && bone_idx != -1 && skel_gltf_i != -1) {
  5550. Ref<GLTFSkeleton> gltf_skeleton = p_state->skeletons.write[skel_gltf_i];
  5551. gltf_skeleton->bone_attachments.push_back(p_bone_attachment);
  5552. par_node_index = gltf_skeleton->joints[bone_idx];
  5553. }
  5554. for (int node_i = 0; node_i < p_bone_attachment->get_child_count(); node_i++) {
  5555. _convert_scene_node(p_state, p_bone_attachment->get_child(node_i), par_node_index, p_root_node_index);
  5556. }
  5557. }
  5558. void GLTFDocument::_convert_mesh_instance_to_gltf(MeshInstance3D *p_scene_parent, Ref<GLTFState> p_state, Ref<GLTFNode> p_gltf_node) {
  5559. GLTFMeshIndex gltf_mesh_index = _convert_mesh_to_gltf(p_state, p_scene_parent);
  5560. if (gltf_mesh_index != -1) {
  5561. p_gltf_node->mesh = gltf_mesh_index;
  5562. }
  5563. }
  5564. void GLTFDocument::_generate_scene_node(Ref<GLTFState> p_state, const GLTFNodeIndex p_node_index, Node *p_scene_parent, Node *p_scene_root) {
  5565. Ref<GLTFNode> gltf_node = p_state->nodes[p_node_index];
  5566. if (gltf_node->skeleton >= 0) {
  5567. _generate_skeleton_bone_node(p_state, p_node_index, p_scene_parent, p_scene_root);
  5568. return;
  5569. }
  5570. Node3D *current_node = nullptr;
  5571. // Is our parent a skeleton
  5572. Skeleton3D *active_skeleton = Object::cast_to<Skeleton3D>(p_scene_parent);
  5573. const bool non_bone_parented_to_skeleton = active_skeleton;
  5574. // skinned meshes must not be placed in a bone attachment.
  5575. if (non_bone_parented_to_skeleton && gltf_node->skin < 0) {
  5576. // Bone Attachment - Parent Case
  5577. BoneAttachment3D *bone_attachment = _generate_bone_attachment(p_state, active_skeleton, p_node_index, gltf_node->parent);
  5578. p_scene_parent->add_child(bone_attachment, true);
  5579. // Find the correct bone_idx so we can properly serialize it.
  5580. bone_attachment->set_bone_idx(active_skeleton->find_bone(gltf_node->get_name()));
  5581. bone_attachment->set_owner(p_scene_root);
  5582. // There is no gltf_node that represent this, so just directly create a unique name
  5583. bone_attachment->set_name(gltf_node->get_name());
  5584. // We change the scene_parent to our bone attachment now. We do not set current_node because we want to make the node
  5585. // and attach it to the bone_attachment
  5586. p_scene_parent = bone_attachment;
  5587. }
  5588. // Check if any GLTFDocumentExtension classes want to generate a node for us.
  5589. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  5590. ERR_CONTINUE(ext.is_null());
  5591. current_node = ext->generate_scene_node(p_state, gltf_node, p_scene_parent);
  5592. if (current_node) {
  5593. break;
  5594. }
  5595. }
  5596. // If none of our GLTFDocumentExtension classes generated us a node, we generate one.
  5597. if (!current_node) {
  5598. if (gltf_node->skin >= 0 && gltf_node->mesh >= 0 && !gltf_node->children.is_empty()) {
  5599. // glTF specifies that skinned meshes should ignore their node transforms,
  5600. // only being controlled by the skeleton, so Godot will reparent a skinned
  5601. // mesh to its skeleton. However, we still need to ensure any child nodes
  5602. // keep their place in the tree, so if there are any child nodes, the skinned
  5603. // mesh must not be the base node, so generate an empty spatial base.
  5604. current_node = _generate_spatial(p_state, p_node_index);
  5605. Node3D *mesh_inst = _generate_mesh_instance(p_state, p_node_index);
  5606. mesh_inst->set_name(gltf_node->get_name());
  5607. current_node->add_child(mesh_inst, true);
  5608. } else if (gltf_node->mesh >= 0) {
  5609. current_node = _generate_mesh_instance(p_state, p_node_index);
  5610. } else if (gltf_node->camera >= 0) {
  5611. current_node = _generate_camera(p_state, p_node_index);
  5612. } else if (gltf_node->light >= 0) {
  5613. current_node = _generate_light(p_state, p_node_index);
  5614. } else {
  5615. current_node = _generate_spatial(p_state, p_node_index);
  5616. }
  5617. }
  5618. String gltf_node_name = gltf_node->get_name();
  5619. if (!gltf_node_name.is_empty()) {
  5620. current_node->set_name(gltf_node_name);
  5621. }
  5622. // Note: p_scene_parent and p_scene_root must either both be null or both be valid.
  5623. if (p_scene_root == nullptr) {
  5624. // If the root node argument is null, this is the root node.
  5625. p_scene_root = current_node;
  5626. // If multiple nodes were generated under the root node, ensure they have the owner set.
  5627. if (unlikely(current_node->get_child_count() > 0)) {
  5628. Array args;
  5629. args.append(p_scene_root);
  5630. for (int i = 0; i < current_node->get_child_count(); i++) {
  5631. Node *child = current_node->get_child(i);
  5632. child->propagate_call(StringName("set_owner"), args);
  5633. }
  5634. }
  5635. } else {
  5636. // Add the node we generated and set the owner to the scene root.
  5637. p_scene_parent->add_child(current_node, true);
  5638. Array args;
  5639. args.append(p_scene_root);
  5640. current_node->propagate_call(StringName("set_owner"), args);
  5641. current_node->set_transform(gltf_node->transform);
  5642. }
  5643. current_node->merge_meta_from(*gltf_node);
  5644. p_state->scene_nodes.insert(p_node_index, current_node);
  5645. for (int i = 0; i < gltf_node->children.size(); ++i) {
  5646. _generate_scene_node(p_state, gltf_node->children[i], current_node, p_scene_root);
  5647. }
  5648. }
  5649. void GLTFDocument::_generate_skeleton_bone_node(Ref<GLTFState> p_state, const GLTFNodeIndex p_node_index, Node *p_scene_parent, Node *p_scene_root) {
  5650. Ref<GLTFNode> gltf_node = p_state->nodes[p_node_index];
  5651. Node3D *current_node = nullptr;
  5652. Skeleton3D *skeleton = p_state->skeletons[gltf_node->skeleton]->godot_skeleton;
  5653. // In this case, this node is already a bone in skeleton.
  5654. const bool is_skinned_mesh = (gltf_node->skin >= 0 && gltf_node->mesh >= 0);
  5655. const bool requires_extra_node = (gltf_node->mesh >= 0 || gltf_node->camera >= 0 || gltf_node->light >= 0);
  5656. Skeleton3D *active_skeleton = Object::cast_to<Skeleton3D>(p_scene_parent);
  5657. if (active_skeleton != skeleton) {
  5658. if (active_skeleton) {
  5659. // Should no longer be possible.
  5660. ERR_PRINT(vformat("glTF: Generating scene detected direct parented Skeletons at node %d", p_node_index));
  5661. BoneAttachment3D *bone_attachment = _generate_bone_attachment(p_state, active_skeleton, p_node_index, gltf_node->parent);
  5662. p_scene_parent->add_child(bone_attachment, true);
  5663. bone_attachment->set_owner(p_scene_root);
  5664. // There is no gltf_node that represent this, so just directly create a unique name
  5665. bone_attachment->set_name(_gen_unique_name(p_state, "BoneAttachment3D"));
  5666. // We change the scene_parent to our bone attachment now. We do not set current_node because we want to make the node
  5667. // and attach it to the bone_attachment
  5668. p_scene_parent = bone_attachment;
  5669. }
  5670. if (skeleton->get_parent() == nullptr) {
  5671. if (p_scene_root) {
  5672. p_scene_parent->add_child(skeleton, true);
  5673. skeleton->set_owner(p_scene_root);
  5674. } else {
  5675. p_scene_parent = skeleton;
  5676. p_scene_root = skeleton;
  5677. }
  5678. }
  5679. }
  5680. active_skeleton = skeleton;
  5681. current_node = active_skeleton;
  5682. if (active_skeleton) {
  5683. p_scene_parent = active_skeleton;
  5684. }
  5685. if (requires_extra_node) {
  5686. current_node = nullptr;
  5687. // skinned meshes must not be placed in a bone attachment.
  5688. if (!is_skinned_mesh) {
  5689. // Bone Attachment - Same Node Case
  5690. BoneAttachment3D *bone_attachment = _generate_bone_attachment(p_state, active_skeleton, p_node_index, p_node_index);
  5691. p_scene_parent->add_child(bone_attachment, true);
  5692. // Find the correct bone_idx so we can properly serialize it.
  5693. bone_attachment->set_bone_idx(active_skeleton->find_bone(gltf_node->get_name()));
  5694. bone_attachment->set_owner(p_scene_root);
  5695. // There is no gltf_node that represent this, so just directly create a unique name
  5696. bone_attachment->set_name(gltf_node->get_name());
  5697. // We change the scene_parent to our bone attachment now. We do not set current_node because we want to make the node
  5698. // and attach it to the bone_attachment
  5699. p_scene_parent = bone_attachment;
  5700. }
  5701. // Check if any GLTFDocumentExtension classes want to generate a node for us.
  5702. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  5703. ERR_CONTINUE(ext.is_null());
  5704. current_node = ext->generate_scene_node(p_state, gltf_node, p_scene_parent);
  5705. if (current_node) {
  5706. break;
  5707. }
  5708. }
  5709. // If none of our GLTFDocumentExtension classes generated us a node, we generate one.
  5710. if (!current_node) {
  5711. if (gltf_node->mesh >= 0) {
  5712. current_node = _generate_mesh_instance(p_state, p_node_index);
  5713. } else if (gltf_node->camera >= 0) {
  5714. current_node = _generate_camera(p_state, p_node_index);
  5715. } else if (gltf_node->light >= 0) {
  5716. current_node = _generate_light(p_state, p_node_index);
  5717. } else {
  5718. current_node = _generate_spatial(p_state, p_node_index);
  5719. }
  5720. }
  5721. // Add the node we generated and set the owner to the scene root.
  5722. p_scene_parent->add_child(current_node, true);
  5723. if (current_node != p_scene_root) {
  5724. Array args;
  5725. args.append(p_scene_root);
  5726. current_node->propagate_call(StringName("set_owner"), args);
  5727. }
  5728. // Do not set transform here. Transform is already applied to our bone.
  5729. current_node->set_name(gltf_node->get_name());
  5730. }
  5731. p_state->scene_nodes.insert(p_node_index, current_node);
  5732. for (int i = 0; i < gltf_node->children.size(); ++i) {
  5733. _generate_scene_node(p_state, gltf_node->children[i], active_skeleton, p_scene_root);
  5734. }
  5735. }
  5736. template <typename T>
  5737. struct SceneFormatImporterGLTFInterpolate {
  5738. T lerp(const T &a, const T &b, float c) const {
  5739. return a + (b - a) * c;
  5740. }
  5741. T catmull_rom(const T &p0, const T &p1, const T &p2, const T &p3, float t) {
  5742. const float t2 = t * t;
  5743. const float t3 = t2 * t;
  5744. 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);
  5745. }
  5746. T hermite(T start, T tan_start, T end, T tan_end, float t) {
  5747. /* Formula from the glTF 2.0 specification. */
  5748. const real_t t2 = t * t;
  5749. const real_t t3 = t2 * t;
  5750. const real_t h00 = 2.0 * t3 - 3.0 * t2 + 1.0;
  5751. const real_t h10 = t3 - 2.0 * t2 + t;
  5752. const real_t h01 = -2.0 * t3 + 3.0 * t2;
  5753. const real_t h11 = t3 - t2;
  5754. return start * h00 + tan_start * h10 + end * h01 + tan_end * h11;
  5755. }
  5756. };
  5757. // thank you for existing, partial specialization
  5758. template <>
  5759. struct SceneFormatImporterGLTFInterpolate<Quaternion> {
  5760. Quaternion lerp(const Quaternion &a, const Quaternion &b, const float c) const {
  5761. ERR_FAIL_COND_V_MSG(!a.is_normalized(), Quaternion(), vformat("The quaternion \"a\" %s must be normalized.", a));
  5762. ERR_FAIL_COND_V_MSG(!b.is_normalized(), Quaternion(), vformat("The quaternion \"b\" %s must be normalized.", b));
  5763. return a.slerp(b, c).normalized();
  5764. }
  5765. Quaternion catmull_rom(const Quaternion &p0, const Quaternion &p1, const Quaternion &p2, const Quaternion &p3, const float c) {
  5766. ERR_FAIL_COND_V_MSG(!p1.is_normalized(), Quaternion(), vformat("The quaternion \"p1\" (%s) must be normalized.", p1));
  5767. ERR_FAIL_COND_V_MSG(!p2.is_normalized(), Quaternion(), vformat("The quaternion \"p2\" (%s) must be normalized.", p2));
  5768. return p1.slerp(p2, c).normalized();
  5769. }
  5770. Quaternion hermite(const Quaternion start, const Quaternion tan_start, const Quaternion end, const Quaternion tan_end, const float t) {
  5771. ERR_FAIL_COND_V_MSG(!start.is_normalized(), Quaternion(), vformat("The start quaternion %s must be normalized.", start));
  5772. ERR_FAIL_COND_V_MSG(!end.is_normalized(), Quaternion(), vformat("The end quaternion %s must be normalized.", end));
  5773. return start.slerp(end, t).normalized();
  5774. }
  5775. };
  5776. template <typename T>
  5777. T GLTFDocument::_interpolate_track(const Vector<double> &p_times, const Vector<T> &p_values, const float p_time, const GLTFAnimation::Interpolation p_interp) {
  5778. ERR_FAIL_COND_V(p_values.is_empty(), T());
  5779. if (p_times.size() != (p_values.size() / (p_interp == GLTFAnimation::INTERP_CUBIC_SPLINE ? 3 : 1))) {
  5780. ERR_PRINT_ONCE("The interpolated values are not corresponding to its times.");
  5781. return p_values[0];
  5782. }
  5783. //could use binary search, worth it?
  5784. int idx = -1;
  5785. for (int i = 0; i < p_times.size(); i++) {
  5786. if (p_times[i] > p_time) {
  5787. break;
  5788. }
  5789. idx++;
  5790. }
  5791. SceneFormatImporterGLTFInterpolate<T> interp;
  5792. switch (p_interp) {
  5793. case GLTFAnimation::INTERP_LINEAR: {
  5794. if (idx == -1) {
  5795. return p_values[0];
  5796. } else if (idx >= p_times.size() - 1) {
  5797. return p_values[p_times.size() - 1];
  5798. }
  5799. const float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
  5800. return interp.lerp(p_values[idx], p_values[idx + 1], c);
  5801. } break;
  5802. case GLTFAnimation::INTERP_STEP: {
  5803. if (idx == -1) {
  5804. return p_values[0];
  5805. } else if (idx >= p_times.size() - 1) {
  5806. return p_values[p_times.size() - 1];
  5807. }
  5808. return p_values[idx];
  5809. } break;
  5810. case GLTFAnimation::INTERP_CATMULLROMSPLINE: {
  5811. if (idx == -1) {
  5812. return p_values[1];
  5813. } else if (idx >= p_times.size() - 1) {
  5814. return p_values[1 + p_times.size() - 1];
  5815. }
  5816. const float c = (p_time - p_times[idx]) / (p_times[idx + 1] - p_times[idx]);
  5817. return interp.catmull_rom(p_values[idx - 1], p_values[idx], p_values[idx + 1], p_values[idx + 3], c);
  5818. } break;
  5819. case GLTFAnimation::INTERP_CUBIC_SPLINE: {
  5820. if (idx == -1) {
  5821. return p_values[1];
  5822. } else if (idx >= p_times.size() - 1) {
  5823. return p_values[(p_times.size() - 1) * 3 + 1];
  5824. }
  5825. const float td = (p_times[idx + 1] - p_times[idx]);
  5826. const float c = (p_time - p_times[idx]) / td;
  5827. const T &from = p_values[idx * 3 + 1];
  5828. const T tan_from = td * p_values[idx * 3 + 2];
  5829. const T &to = p_values[idx * 3 + 4];
  5830. const T tan_to = td * p_values[idx * 3 + 3];
  5831. return interp.hermite(from, tan_from, to, tan_to, c);
  5832. } break;
  5833. }
  5834. ERR_FAIL_V(p_values[0]);
  5835. }
  5836. NodePath GLTFDocument::_find_material_node_path(Ref<GLTFState> p_state, Ref<Material> p_material) {
  5837. int mesh_index = 0;
  5838. for (Ref<GLTFMesh> gltf_mesh : p_state->meshes) {
  5839. TypedArray<Material> materials = gltf_mesh->get_instance_materials();
  5840. for (int mat_index = 0; mat_index < materials.size(); mat_index++) {
  5841. if (materials[mat_index] == p_material) {
  5842. for (Ref<GLTFNode> gltf_node : p_state->nodes) {
  5843. if (gltf_node->mesh == mesh_index) {
  5844. NodePath node_path = gltf_node->get_scene_node_path(p_state);
  5845. // Example: MyNode:mesh:surface_0/material:albedo_color, so we want the mesh:surface_0/material part.
  5846. Vector<StringName> subpath;
  5847. subpath.append("mesh");
  5848. subpath.append("surface_" + itos(mat_index) + "/material");
  5849. return NodePath(node_path.get_names(), subpath, false);
  5850. }
  5851. }
  5852. }
  5853. }
  5854. mesh_index++;
  5855. }
  5856. return NodePath();
  5857. }
  5858. Ref<GLTFObjectModelProperty> GLTFDocument::import_object_model_property(Ref<GLTFState> p_state, const String &p_json_pointer) {
  5859. if (p_state->object_model_properties.has(p_json_pointer)) {
  5860. return p_state->object_model_properties[p_json_pointer];
  5861. }
  5862. Ref<GLTFObjectModelProperty> ret;
  5863. // Split the JSON pointer into its components.
  5864. const PackedStringArray split = p_json_pointer.split("/", false);
  5865. ERR_FAIL_COND_V_MSG(split.size() < 3, ret, "glTF: Cannot use JSON pointer '" + p_json_pointer + "' because it does not contain enough elements. The only animatable properties are at least 3 levels deep (ex: '/nodes/0/translation' or '/materials/0/emissiveFactor').");
  5866. ret.instantiate();
  5867. ret->set_json_pointers({ split });
  5868. // Partial paths are passed to GLTFDocumentExtension classes if GLTFDocument cannot handle a given JSON pointer.
  5869. TypedArray<NodePath> partial_paths;
  5870. // Note: This might not be an integer, but in that case, we don't use this value anyway.
  5871. const int top_level_index = split[1].to_int();
  5872. // For JSON pointers present in the core glTF Object Model, hard-code them in GLTFDocument.
  5873. // https://github.com/KhronosGroup/glTF/blob/main/specification/2.0/ObjectModel.adoc
  5874. if (split[0] == "nodes") {
  5875. ERR_FAIL_INDEX_V_MSG(top_level_index, p_state->nodes.size(), ret, vformat("glTF: Unable to find node %d for JSON pointer '%s'.", top_level_index, p_json_pointer));
  5876. Ref<GLTFNode> pointed_gltf_node = p_state->nodes[top_level_index];
  5877. NodePath node_path = pointed_gltf_node->get_scene_node_path(p_state);
  5878. partial_paths.append(node_path);
  5879. // Check if it's something we should be able to handle.
  5880. const String &node_prop = split[2];
  5881. if (node_prop == "translation") {
  5882. ret->append_path_to_property(node_path, "position");
  5883. ret->set_types(Variant::VECTOR3, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT3);
  5884. } else if (node_prop == "rotation") {
  5885. ret->append_path_to_property(node_path, "quaternion");
  5886. ret->set_types(Variant::QUATERNION, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT4);
  5887. } else if (node_prop == "scale") {
  5888. ret->append_path_to_property(node_path, "scale");
  5889. ret->set_types(Variant::VECTOR3, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT3);
  5890. } else if (node_prop == "matrix") {
  5891. ret->append_path_to_property(node_path, "transform");
  5892. ret->set_types(Variant::TRANSFORM3D, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT4X4);
  5893. } else if (node_prop == "globalMatrix") {
  5894. ret->append_path_to_property(node_path, "global_transform");
  5895. ret->set_types(Variant::TRANSFORM3D, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT4X4);
  5896. } else if (node_prop == "weights") {
  5897. if (split.size() > 3) {
  5898. const String &weight_index_string = split[3];
  5899. ret->append_path_to_property(node_path, "blend_shapes/morph_" + weight_index_string);
  5900. ret->set_types(Variant::FLOAT, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT);
  5901. }
  5902. // Else, Godot's MeshInstance3D does not expose the blend shape weights as one property.
  5903. // But that's fine, we handle this case in _parse_animation_pointer instead.
  5904. }
  5905. } else if (split[0] == "cameras") {
  5906. const String &camera_prop = split[2];
  5907. for (Ref<GLTFNode> gltf_node : p_state->nodes) {
  5908. if (gltf_node->camera == top_level_index) {
  5909. NodePath node_path = gltf_node->get_scene_node_path(p_state);
  5910. partial_paths.append(node_path);
  5911. // Check if it's something we should be able to handle.
  5912. if (camera_prop == "orthographic" || camera_prop == "perspective") {
  5913. ERR_FAIL_COND_V(split.size() < 4, ret);
  5914. ret->set_types(Variant::FLOAT, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT);
  5915. const String &sub_prop = split[3];
  5916. if (sub_prop == "xmag" || sub_prop == "ymag") {
  5917. ret->append_path_to_property(node_path, "size");
  5918. } else if (sub_prop == "yfov") {
  5919. ret->append_path_to_property(node_path, "fov");
  5920. GLTFCamera::set_fov_conversion_expressions(ret);
  5921. } else if (sub_prop == "zfar") {
  5922. ret->append_path_to_property(node_path, "far");
  5923. } else if (sub_prop == "znear") {
  5924. ret->append_path_to_property(node_path, "near");
  5925. }
  5926. }
  5927. }
  5928. }
  5929. } else if (split[0] == "materials") {
  5930. ERR_FAIL_INDEX_V_MSG(top_level_index, p_state->materials.size(), ret, vformat("glTF: Unable to find material %d for JSON pointer '%s'.", top_level_index, p_json_pointer));
  5931. Ref<Material> pointed_material = p_state->materials[top_level_index];
  5932. NodePath mat_path = _find_material_node_path(p_state, pointed_material);
  5933. if (mat_path.is_empty()) {
  5934. WARN_PRINT(vformat("glTF: Unable to find a path to the material %d for JSON pointer '%s'. This is likely bad data but it's also possible this is intentional. Continuing anyway.", top_level_index, p_json_pointer));
  5935. } else {
  5936. partial_paths.append(mat_path);
  5937. const String &mat_prop = split[2];
  5938. if (mat_prop == "alphaCutoff") {
  5939. ret->append_path_to_property(mat_path, "alpha_scissor_threshold");
  5940. ret->set_types(Variant::FLOAT, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT);
  5941. } else if (mat_prop == "emissiveFactor") {
  5942. ret->append_path_to_property(mat_path, "emission");
  5943. ret->set_types(Variant::COLOR, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT3);
  5944. } else if (mat_prop == "extensions") {
  5945. ERR_FAIL_COND_V(split.size() < 5, ret);
  5946. const String &ext_name = split[3];
  5947. const String &ext_prop = split[4];
  5948. if (ext_name == "KHR_materials_emissive_strength" && ext_prop == "emissiveStrength") {
  5949. ret->append_path_to_property(mat_path, "emission_energy_multiplier");
  5950. ret->set_types(Variant::FLOAT, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT);
  5951. }
  5952. } else {
  5953. ERR_FAIL_COND_V(split.size() < 4, ret);
  5954. const String &sub_prop = split[3];
  5955. if (mat_prop == "normalTexture") {
  5956. if (sub_prop == "scale") {
  5957. ret->append_path_to_property(mat_path, "normal_scale");
  5958. ret->set_types(Variant::FLOAT, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT);
  5959. }
  5960. } else if (mat_prop == "occlusionTexture") {
  5961. if (sub_prop == "strength") {
  5962. // This is the closest thing Godot has to an occlusion strength property.
  5963. ret->append_path_to_property(mat_path, "ao_light_affect");
  5964. ret->set_types(Variant::FLOAT, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT);
  5965. }
  5966. } else if (mat_prop == "pbrMetallicRoughness") {
  5967. if (sub_prop == "baseColorFactor") {
  5968. ret->append_path_to_property(mat_path, "albedo_color");
  5969. ret->set_types(Variant::COLOR, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT4);
  5970. } else if (sub_prop == "metallicFactor") {
  5971. ret->append_path_to_property(mat_path, "metallic");
  5972. ret->set_types(Variant::FLOAT, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT);
  5973. } else if (sub_prop == "roughnessFactor") {
  5974. ret->append_path_to_property(mat_path, "roughness");
  5975. ret->set_types(Variant::FLOAT, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT);
  5976. } else if (sub_prop == "baseColorTexture") {
  5977. ERR_FAIL_COND_V(split.size() < 6, ret);
  5978. const String &tex_ext_dict = split[4];
  5979. const String &tex_ext_name = split[5];
  5980. const String &tex_ext_prop = split[6];
  5981. if (tex_ext_dict == "extensions" && tex_ext_name == "KHR_texture_transform") {
  5982. // Godot only supports UVs for the whole material, not per texture.
  5983. // We treat the albedo texture as the main texture, and import as UV1.
  5984. // Godot does not support texture rotation, only offset and scale.
  5985. if (tex_ext_prop == "offset") {
  5986. ret->append_path_to_property(mat_path, "uv1_offset");
  5987. ret->set_types(Variant::VECTOR3, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT2);
  5988. } else if (tex_ext_prop == "scale") {
  5989. ret->append_path_to_property(mat_path, "uv1_scale");
  5990. ret->set_types(Variant::VECTOR3, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT2);
  5991. }
  5992. }
  5993. }
  5994. }
  5995. }
  5996. }
  5997. } else if (split[0] == "meshes") {
  5998. for (Ref<GLTFNode> gltf_node : p_state->nodes) {
  5999. if (gltf_node->mesh == top_level_index) {
  6000. NodePath node_path = gltf_node->get_scene_node_path(p_state);
  6001. Vector<StringName> subpath;
  6002. subpath.append("mesh");
  6003. partial_paths.append(NodePath(node_path.get_names(), subpath, false));
  6004. break;
  6005. }
  6006. }
  6007. } else if (split[0] == "extensions") {
  6008. if (split[1] == "KHR_lights_punctual" && split[2] == "lights" && split.size() > 4) {
  6009. const int light_index = split[3].to_int();
  6010. ERR_FAIL_INDEX_V_MSG(light_index, p_state->lights.size(), ret, vformat("glTF: Unable to find light %d for JSON pointer '%s'.", light_index, p_json_pointer));
  6011. const String &light_prop = split[4];
  6012. const Ref<GLTFLight> pointed_light = p_state->lights[light_index];
  6013. for (Ref<GLTFNode> gltf_node : p_state->nodes) {
  6014. if (gltf_node->light == light_index) {
  6015. NodePath node_path = gltf_node->get_scene_node_path(p_state);
  6016. partial_paths.append(node_path);
  6017. ret->set_types(Variant::FLOAT, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT);
  6018. // Check if it's something we should be able to handle.
  6019. if (light_prop == "color") {
  6020. ret->append_path_to_property(node_path, "light_color");
  6021. ret->set_types(Variant::COLOR, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT3);
  6022. } else if (light_prop == "intensity") {
  6023. ret->append_path_to_property(node_path, "light_energy");
  6024. } else if (light_prop == "range") {
  6025. const String &light_type = p_state->lights[light_index]->light_type;
  6026. if (light_type == "spot") {
  6027. ret->append_path_to_property(node_path, "spot_range");
  6028. } else {
  6029. ret->append_path_to_property(node_path, "omni_range");
  6030. }
  6031. } else if (light_prop == "spot") {
  6032. ERR_FAIL_COND_V(split.size() < 6, ret);
  6033. const String &sub_prop = split[5];
  6034. if (sub_prop == "innerConeAngle") {
  6035. ret->append_path_to_property(node_path, "spot_angle_attenuation");
  6036. GLTFLight::set_cone_inner_attenuation_conversion_expressions(ret);
  6037. } else if (sub_prop == "outerConeAngle") {
  6038. ret->append_path_to_property(node_path, "spot_angle");
  6039. }
  6040. }
  6041. }
  6042. }
  6043. }
  6044. }
  6045. // Additional JSON pointers can be added by GLTFDocumentExtension classes.
  6046. // We only need this if no mapping has been found yet from GLTFDocument's internal code.
  6047. // When available, we pass the partial paths to the extension to help it generate the full path.
  6048. // For example, for `/nodes/3/extensions/MY_ext/prop`, we pass a NodePath that leads to node 3,
  6049. // so the GLTFDocumentExtension class only needs to resolve the last `MY_ext/prop` part of the path.
  6050. // It should check `split.size() > 4 and split[0] == "nodes" and split[2] == "extensions" and split[3] == "MY_ext"`
  6051. // at the start of the function to check if this JSON pointer applies to it, then it can handle `split[4]`.
  6052. if (!ret->has_node_paths()) {
  6053. for (Ref<GLTFDocumentExtension> ext : all_document_extensions) {
  6054. ret = ext->import_object_model_property(p_state, split, partial_paths);
  6055. if (ret.is_valid() && ret->has_node_paths()) {
  6056. if (!ret->has_json_pointers()) {
  6057. ret->set_json_pointers({ split });
  6058. }
  6059. break;
  6060. }
  6061. }
  6062. if (ret.is_null() || !ret->has_node_paths()) {
  6063. if (split.has("KHR_texture_transform")) {
  6064. WARN_VERBOSE(vformat("glTF: Texture transforms are only supported per material in Godot. All KHR_texture_transform properties will be ignored except for the albedo texture. Ignoring JSON pointer '%s'.", p_json_pointer));
  6065. } else {
  6066. WARN_PRINT(vformat("glTF: Animation contained JSON pointer '%s' which could not be resolved. This property will not be animated.", p_json_pointer));
  6067. }
  6068. }
  6069. }
  6070. p_state->object_model_properties[p_json_pointer] = ret;
  6071. return ret;
  6072. }
  6073. Ref<GLTFObjectModelProperty> GLTFDocument::export_object_model_property(Ref<GLTFState> p_state, const NodePath &p_node_path, const Node *p_godot_node, GLTFNodeIndex p_gltf_node_index) {
  6074. Ref<GLTFObjectModelProperty> ret;
  6075. const Object *target_object = p_godot_node;
  6076. const Vector<StringName> subpath = p_node_path.get_subnames();
  6077. ERR_FAIL_COND_V_MSG(subpath.is_empty(), ret, "glTF: Cannot export empty property. No property was specified in the NodePath: " + p_node_path);
  6078. int target_prop_depth = 0;
  6079. for (StringName subname : subpath) {
  6080. Variant target_property = target_object->get(subname);
  6081. if (target_property.get_type() == Variant::OBJECT) {
  6082. target_object = target_property;
  6083. if (target_object) {
  6084. target_prop_depth++;
  6085. continue;
  6086. }
  6087. }
  6088. break;
  6089. }
  6090. const String &target_prop = subpath[target_prop_depth];
  6091. ret.instantiate();
  6092. ret->set_node_paths({ p_node_path });
  6093. Vector<PackedStringArray> split_json_pointers;
  6094. PackedStringArray split_json_pointer;
  6095. if (Object::cast_to<BaseMaterial3D>(target_object)) {
  6096. for (int i = 0; i < p_state->materials.size(); i++) {
  6097. if (p_state->materials[i].ptr() == target_object) {
  6098. split_json_pointer.append("materials");
  6099. split_json_pointer.append(itos(i));
  6100. if (target_prop == "alpha_scissor_threshold") {
  6101. split_json_pointer.append("alphaCutoff");
  6102. ret->set_types(Variant::FLOAT, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT);
  6103. } else if (target_prop == "emission") {
  6104. split_json_pointer.append("emissiveFactor");
  6105. ret->set_types(Variant::COLOR, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT3);
  6106. } else if (target_prop == "emission_energy_multiplier") {
  6107. split_json_pointer.append("extensions");
  6108. split_json_pointer.append("KHR_materials_emissive_strength");
  6109. split_json_pointer.append("emissiveStrength");
  6110. ret->set_types(Variant::FLOAT, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT);
  6111. } else if (target_prop == "normal_scale") {
  6112. split_json_pointer.append("normalTexture");
  6113. split_json_pointer.append("scale");
  6114. ret->set_types(Variant::FLOAT, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT);
  6115. } else if (target_prop == "ao_light_affect") {
  6116. split_json_pointer.append("occlusionTexture");
  6117. split_json_pointer.append("strength");
  6118. ret->set_types(Variant::FLOAT, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT);
  6119. } else if (target_prop == "albedo_color") {
  6120. split_json_pointer.append("pbrMetallicRoughness");
  6121. split_json_pointer.append("baseColorFactor");
  6122. ret->set_types(Variant::COLOR, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT4);
  6123. } else if (target_prop == "metallic") {
  6124. split_json_pointer.append("pbrMetallicRoughness");
  6125. split_json_pointer.append("metallicFactor");
  6126. ret->set_types(Variant::FLOAT, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT);
  6127. } else if (target_prop == "roughness") {
  6128. split_json_pointer.append("pbrMetallicRoughness");
  6129. split_json_pointer.append("roughnessFactor");
  6130. ret->set_types(Variant::FLOAT, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT);
  6131. } else if (target_prop == "uv1_offset" || target_prop == "uv1_scale") {
  6132. split_json_pointer.append("pbrMetallicRoughness");
  6133. split_json_pointer.append("baseColorTexture");
  6134. split_json_pointer.append("extensions");
  6135. split_json_pointer.append("KHR_texture_transform");
  6136. if (target_prop == "uv1_offset") {
  6137. split_json_pointer.append("offset");
  6138. } else {
  6139. split_json_pointer.append("scale");
  6140. }
  6141. ret->set_types(Variant::VECTOR3, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT2);
  6142. } else {
  6143. split_json_pointer.clear();
  6144. }
  6145. break;
  6146. }
  6147. }
  6148. } else {
  6149. // Properties directly on Godot nodes.
  6150. Ref<GLTFNode> gltf_node = p_state->nodes[p_gltf_node_index];
  6151. if (Object::cast_to<Camera3D>(target_object) && gltf_node->camera >= 0) {
  6152. split_json_pointer.append("cameras");
  6153. split_json_pointer.append(itos(gltf_node->camera));
  6154. const Camera3D *camera_node = Object::cast_to<Camera3D>(target_object);
  6155. const Camera3D::ProjectionType projection_type = camera_node->get_projection();
  6156. if (projection_type == Camera3D::PROJECTION_PERSPECTIVE) {
  6157. split_json_pointer.append("perspective");
  6158. } else {
  6159. split_json_pointer.append("orthographic");
  6160. }
  6161. ret->set_types(Variant::FLOAT, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT);
  6162. if (target_prop == "size") {
  6163. PackedStringArray xmag = split_json_pointer.duplicate();
  6164. xmag.append("xmag");
  6165. split_json_pointers.append(xmag);
  6166. split_json_pointer.append("ymag");
  6167. } else if (target_prop == "fov") {
  6168. split_json_pointer.append("yfov");
  6169. GLTFCamera::set_fov_conversion_expressions(ret);
  6170. } else if (target_prop == "far") {
  6171. split_json_pointer.append("zfar");
  6172. } else if (target_prop == "near") {
  6173. split_json_pointer.append("znear");
  6174. } else {
  6175. split_json_pointer.clear();
  6176. }
  6177. } else if (Object::cast_to<Light3D>(target_object) && gltf_node->light >= 0) {
  6178. split_json_pointer.append("extensions");
  6179. split_json_pointer.append("KHR_lights_punctual");
  6180. split_json_pointer.append("lights");
  6181. split_json_pointer.append(itos(gltf_node->light));
  6182. ret->set_types(Variant::FLOAT, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT);
  6183. if (target_prop == "light_color") {
  6184. split_json_pointer.append("color");
  6185. ret->set_types(Variant::COLOR, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT3);
  6186. } else if (target_prop == "light_energy") {
  6187. split_json_pointer.append("intensity");
  6188. } else if (target_prop == "spot_range") {
  6189. split_json_pointer.append("range");
  6190. } else if (target_prop == "omni_range") {
  6191. split_json_pointer.append("range");
  6192. } else if (target_prop == "spot_angle") {
  6193. split_json_pointer.append("spot");
  6194. split_json_pointer.append("outerConeAngle");
  6195. } else if (target_prop == "spot_angle_attenuation") {
  6196. split_json_pointer.append("spot");
  6197. split_json_pointer.append("innerConeAngle");
  6198. GLTFLight::set_cone_inner_attenuation_conversion_expressions(ret);
  6199. } else {
  6200. split_json_pointer.clear();
  6201. }
  6202. } else if (Object::cast_to<MeshInstance3D>(target_object) && target_prop.begins_with("blend_shapes/morph_")) {
  6203. const String &weight_index_string = target_prop.trim_prefix("blend_shapes/morph_");
  6204. split_json_pointer.append("nodes");
  6205. split_json_pointer.append(itos(p_gltf_node_index));
  6206. split_json_pointer.append("weights");
  6207. split_json_pointer.append(weight_index_string);
  6208. }
  6209. // Transform properties. Check for all 3D nodes if we haven't resolved the JSON pointer yet.
  6210. // Note: Do not put this in an `else`, because otherwise this will not be reached.
  6211. if (split_json_pointer.is_empty() && Object::cast_to<Node3D>(target_object)) {
  6212. split_json_pointer.append("nodes");
  6213. split_json_pointer.append(itos(p_gltf_node_index));
  6214. if (target_prop == "position") {
  6215. split_json_pointer.append("translation");
  6216. ret->set_types(Variant::VECTOR3, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT3);
  6217. } else if (target_prop == "quaternion") {
  6218. // Note: Only Quaternion rotation can be converted from Godot in this mapping.
  6219. // Struct methods like from_euler are not accessible from the Expression class. :(
  6220. split_json_pointer.append("rotation");
  6221. ret->set_types(Variant::QUATERNION, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT4);
  6222. } else if (target_prop == "scale") {
  6223. split_json_pointer.append("scale");
  6224. ret->set_types(Variant::VECTOR3, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT3);
  6225. } else if (target_prop == "transform") {
  6226. split_json_pointer.append("matrix");
  6227. ret->set_types(Variant::TRANSFORM3D, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT4X4);
  6228. } else if (target_prop == "global_transform") {
  6229. split_json_pointer.append("globalMatrix");
  6230. ret->set_types(Variant::TRANSFORM3D, GLTFObjectModelProperty::GLTF_OBJECT_MODEL_TYPE_FLOAT4X4);
  6231. } else {
  6232. split_json_pointer.clear();
  6233. }
  6234. }
  6235. }
  6236. // Additional JSON pointers can be added by GLTFDocumentExtension classes.
  6237. // We only need this if no mapping has been found yet from GLTFDocument's internal code.
  6238. // We pass as many pieces of information as we can to the extension to give it lots of context.
  6239. if (split_json_pointer.is_empty()) {
  6240. for (Ref<GLTFDocumentExtension> ext : all_document_extensions) {
  6241. ret = ext->export_object_model_property(p_state, p_node_path, p_godot_node, p_gltf_node_index, target_object, target_prop_depth);
  6242. if (ret.is_valid() && ret->has_json_pointers()) {
  6243. if (!ret->has_node_paths()) {
  6244. ret->set_node_paths({ p_node_path });
  6245. }
  6246. break;
  6247. }
  6248. }
  6249. } else {
  6250. // GLTFDocument's internal code found a mapping, so set it and return it.
  6251. split_json_pointers.append(split_json_pointer);
  6252. ret->set_json_pointers(split_json_pointers);
  6253. }
  6254. return ret;
  6255. }
  6256. void GLTFDocument::_import_animation(Ref<GLTFState> p_state, AnimationPlayer *p_animation_player, const GLTFAnimationIndex p_index, const bool p_trimming, const bool p_remove_immutable_tracks) {
  6257. ERR_FAIL_COND(p_state.is_null());
  6258. Node *scene_root = p_animation_player->get_parent();
  6259. ERR_FAIL_NULL(scene_root);
  6260. Ref<GLTFAnimation> anim = p_state->animations[p_index];
  6261. String anim_name = anim->get_name();
  6262. if (anim_name.is_empty()) {
  6263. // No node represent these, and they are not in the hierarchy, so just make a unique name
  6264. anim_name = _gen_unique_name(p_state, "Animation");
  6265. }
  6266. Ref<Animation> animation;
  6267. animation.instantiate();
  6268. animation->set_name(anim_name);
  6269. animation->set_step(1.0 / p_state->get_bake_fps());
  6270. if (anim->get_loop()) {
  6271. animation->set_loop_mode(Animation::LOOP_LINEAR);
  6272. }
  6273. double anim_start = p_trimming ? INFINITY : 0.0;
  6274. double anim_end = 0.0;
  6275. for (const KeyValue<int, GLTFAnimation::NodeTrack> &track_i : anim->get_node_tracks()) {
  6276. const GLTFAnimation::NodeTrack &track = track_i.value;
  6277. //need to find the path: for skeletons, weight tracks will affect the mesh
  6278. NodePath node_path;
  6279. //for skeletons, transform tracks always affect bones
  6280. NodePath transform_node_path;
  6281. //for meshes, especially skinned meshes, there are cases where it will be added as a child
  6282. NodePath mesh_instance_node_path;
  6283. GLTFNodeIndex node_index = track_i.key;
  6284. const Ref<GLTFNode> gltf_node = p_state->nodes[track_i.key];
  6285. HashMap<GLTFNodeIndex, Node *>::Iterator node_element = p_state->scene_nodes.find(node_index);
  6286. ERR_CONTINUE_MSG(!node_element, vformat("Unable to find node %d for animation.", node_index));
  6287. node_path = scene_root->get_path_to(node_element->value);
  6288. HashMap<GLTFNodeIndex, ImporterMeshInstance3D *>::Iterator mesh_instance_element = p_state->scene_mesh_instances.find(node_index);
  6289. if (mesh_instance_element) {
  6290. mesh_instance_node_path = scene_root->get_path_to(mesh_instance_element->value);
  6291. } else {
  6292. mesh_instance_node_path = node_path;
  6293. }
  6294. if (gltf_node->skeleton >= 0) {
  6295. const Skeleton3D *sk = p_state->skeletons[gltf_node->skeleton]->godot_skeleton;
  6296. ERR_FAIL_NULL(sk);
  6297. const String path = p_animation_player->get_parent()->get_path_to(sk);
  6298. const String bone = gltf_node->get_name();
  6299. transform_node_path = path + ":" + bone;
  6300. } else {
  6301. transform_node_path = node_path;
  6302. }
  6303. if (p_trimming) {
  6304. for (int i = 0; i < track.rotation_track.times.size(); i++) {
  6305. anim_start = MIN(anim_start, track.rotation_track.times[i]);
  6306. anim_end = MAX(anim_end, track.rotation_track.times[i]);
  6307. }
  6308. for (int i = 0; i < track.position_track.times.size(); i++) {
  6309. anim_start = MIN(anim_start, track.position_track.times[i]);
  6310. anim_end = MAX(anim_end, track.position_track.times[i]);
  6311. }
  6312. for (int i = 0; i < track.scale_track.times.size(); i++) {
  6313. anim_start = MIN(anim_start, track.scale_track.times[i]);
  6314. anim_end = MAX(anim_end, track.scale_track.times[i]);
  6315. }
  6316. for (int i = 0; i < track.weight_tracks.size(); i++) {
  6317. for (int j = 0; j < track.weight_tracks[i].times.size(); j++) {
  6318. anim_start = MIN(anim_start, track.weight_tracks[i].times[j]);
  6319. anim_end = MAX(anim_end, track.weight_tracks[i].times[j]);
  6320. }
  6321. }
  6322. } else {
  6323. // If you don't use trimming and the first key time is not at 0.0, fake keys will be inserted.
  6324. for (int i = 0; i < track.rotation_track.times.size(); i++) {
  6325. anim_end = MAX(anim_end, track.rotation_track.times[i]);
  6326. }
  6327. for (int i = 0; i < track.position_track.times.size(); i++) {
  6328. anim_end = MAX(anim_end, track.position_track.times[i]);
  6329. }
  6330. for (int i = 0; i < track.scale_track.times.size(); i++) {
  6331. anim_end = MAX(anim_end, track.scale_track.times[i]);
  6332. }
  6333. for (int i = 0; i < track.weight_tracks.size(); i++) {
  6334. for (int j = 0; j < track.weight_tracks[i].times.size(); j++) {
  6335. anim_end = MAX(anim_end, track.weight_tracks[i].times[j]);
  6336. }
  6337. }
  6338. }
  6339. // Animated TRS properties will not affect a skinned mesh.
  6340. const bool transform_affects_skinned_mesh_instance = gltf_node->skeleton < 0 && gltf_node->skin >= 0;
  6341. if ((track.rotation_track.values.size() || track.position_track.values.size() || track.scale_track.values.size()) && !transform_affects_skinned_mesh_instance) {
  6342. //make transform track
  6343. int base_idx = animation->get_track_count();
  6344. int position_idx = -1;
  6345. int rotation_idx = -1;
  6346. int scale_idx = -1;
  6347. if (track.position_track.values.size()) {
  6348. bool is_default = true; //discard the track if all it contains is default values
  6349. if (p_remove_immutable_tracks) {
  6350. Vector3 base_pos = gltf_node->get_position();
  6351. for (int i = 0; i < track.position_track.times.size(); i++) {
  6352. int value_index = track.position_track.interpolation == GLTFAnimation::INTERP_CUBIC_SPLINE ? (1 + i * 3) : i;
  6353. ERR_FAIL_COND_MSG(value_index >= track.position_track.values.size(), "Animation sampler output accessor with 'CUBICSPLINE' interpolation doesn't have enough elements.");
  6354. Vector3 value = track.position_track.values[value_index];
  6355. if (!value.is_equal_approx(base_pos)) {
  6356. is_default = false;
  6357. break;
  6358. }
  6359. }
  6360. }
  6361. if (!p_remove_immutable_tracks || !is_default) {
  6362. position_idx = base_idx;
  6363. animation->add_track(Animation::TYPE_POSITION_3D);
  6364. animation->track_set_path(position_idx, transform_node_path);
  6365. animation->track_set_imported(position_idx, true); //helps merging later
  6366. if (track.position_track.interpolation == GLTFAnimation::INTERP_STEP) {
  6367. animation->track_set_interpolation_type(position_idx, Animation::InterpolationType::INTERPOLATION_NEAREST);
  6368. }
  6369. base_idx++;
  6370. }
  6371. }
  6372. if (track.rotation_track.values.size()) {
  6373. bool is_default = true; //discard the track if all it contains is default values
  6374. if (p_remove_immutable_tracks) {
  6375. Quaternion base_rot = gltf_node->get_rotation();
  6376. for (int i = 0; i < track.rotation_track.times.size(); i++) {
  6377. int value_index = track.rotation_track.interpolation == GLTFAnimation::INTERP_CUBIC_SPLINE ? (1 + i * 3) : i;
  6378. ERR_FAIL_COND_MSG(value_index >= track.rotation_track.values.size(), "Animation sampler output accessor with 'CUBICSPLINE' interpolation doesn't have enough elements.");
  6379. Quaternion value = track.rotation_track.values[value_index].normalized();
  6380. if (!value.is_equal_approx(base_rot)) {
  6381. is_default = false;
  6382. break;
  6383. }
  6384. }
  6385. }
  6386. if (!p_remove_immutable_tracks || !is_default) {
  6387. rotation_idx = base_idx;
  6388. animation->add_track(Animation::TYPE_ROTATION_3D);
  6389. animation->track_set_path(rotation_idx, transform_node_path);
  6390. animation->track_set_imported(rotation_idx, true); //helps merging later
  6391. if (track.rotation_track.interpolation == GLTFAnimation::INTERP_STEP) {
  6392. animation->track_set_interpolation_type(rotation_idx, Animation::InterpolationType::INTERPOLATION_NEAREST);
  6393. }
  6394. base_idx++;
  6395. }
  6396. }
  6397. if (track.scale_track.values.size()) {
  6398. bool is_default = true; //discard the track if all it contains is default values
  6399. if (p_remove_immutable_tracks) {
  6400. Vector3 base_scale = gltf_node->get_scale();
  6401. for (int i = 0; i < track.scale_track.times.size(); i++) {
  6402. int value_index = track.scale_track.interpolation == GLTFAnimation::INTERP_CUBIC_SPLINE ? (1 + i * 3) : i;
  6403. ERR_FAIL_COND_MSG(value_index >= track.scale_track.values.size(), "Animation sampler output accessor with 'CUBICSPLINE' interpolation doesn't have enough elements.");
  6404. Vector3 value = track.scale_track.values[value_index];
  6405. if (!value.is_equal_approx(base_scale)) {
  6406. is_default = false;
  6407. break;
  6408. }
  6409. }
  6410. }
  6411. if (!p_remove_immutable_tracks || !is_default) {
  6412. scale_idx = base_idx;
  6413. animation->add_track(Animation::TYPE_SCALE_3D);
  6414. animation->track_set_path(scale_idx, transform_node_path);
  6415. animation->track_set_imported(scale_idx, true); //helps merging later
  6416. if (track.scale_track.interpolation == GLTFAnimation::INTERP_STEP) {
  6417. animation->track_set_interpolation_type(scale_idx, Animation::InterpolationType::INTERPOLATION_NEAREST);
  6418. }
  6419. base_idx++;
  6420. }
  6421. }
  6422. const double increment = 1.0 / p_state->get_bake_fps();
  6423. double time = anim_start;
  6424. Vector3 base_pos;
  6425. Quaternion base_rot;
  6426. Vector3 base_scale = Vector3(1, 1, 1);
  6427. if (rotation_idx == -1) {
  6428. base_rot = gltf_node->get_rotation();
  6429. }
  6430. if (position_idx == -1) {
  6431. base_pos = gltf_node->get_position();
  6432. }
  6433. if (scale_idx == -1) {
  6434. base_scale = gltf_node->get_scale();
  6435. }
  6436. bool last = false;
  6437. while (true) {
  6438. Vector3 pos = base_pos;
  6439. Quaternion rot = base_rot;
  6440. Vector3 scale = base_scale;
  6441. if (position_idx >= 0) {
  6442. pos = _interpolate_track<Vector3>(track.position_track.times, track.position_track.values, time, track.position_track.interpolation);
  6443. animation->position_track_insert_key(position_idx, time - anim_start, pos);
  6444. }
  6445. if (rotation_idx >= 0) {
  6446. rot = _interpolate_track<Quaternion>(track.rotation_track.times, track.rotation_track.values, time, track.rotation_track.interpolation);
  6447. animation->rotation_track_insert_key(rotation_idx, time - anim_start, rot);
  6448. }
  6449. if (scale_idx >= 0) {
  6450. scale = _interpolate_track<Vector3>(track.scale_track.times, track.scale_track.values, time, track.scale_track.interpolation);
  6451. animation->scale_track_insert_key(scale_idx, time - anim_start, scale);
  6452. }
  6453. if (last) {
  6454. break;
  6455. }
  6456. time += increment;
  6457. if (time >= anim_end) {
  6458. last = true;
  6459. time = anim_end;
  6460. }
  6461. }
  6462. }
  6463. for (int i = 0; i < track.weight_tracks.size(); i++) {
  6464. ERR_CONTINUE(gltf_node->mesh < 0 || gltf_node->mesh >= p_state->meshes.size());
  6465. Ref<GLTFMesh> mesh = p_state->meshes[gltf_node->mesh];
  6466. ERR_CONTINUE(mesh.is_null());
  6467. ERR_CONTINUE(mesh->get_mesh().is_null());
  6468. ERR_CONTINUE(mesh->get_mesh()->get_mesh().is_null());
  6469. const String blend_path = String(mesh_instance_node_path) + ":" + String(mesh->get_mesh()->get_blend_shape_name(i));
  6470. const int track_idx = animation->get_track_count();
  6471. animation->add_track(Animation::TYPE_BLEND_SHAPE);
  6472. animation->track_set_path(track_idx, blend_path);
  6473. animation->track_set_imported(track_idx, true); //helps merging later
  6474. // Only LINEAR and STEP (NEAREST) can be supported out of the box by Godot's Animation,
  6475. // the other modes have to be baked.
  6476. GLTFAnimation::Interpolation gltf_interp = track.weight_tracks[i].interpolation;
  6477. if (gltf_interp == GLTFAnimation::INTERP_LINEAR || gltf_interp == GLTFAnimation::INTERP_STEP) {
  6478. animation->track_set_interpolation_type(track_idx, gltf_interp == GLTFAnimation::INTERP_STEP ? Animation::INTERPOLATION_NEAREST : Animation::INTERPOLATION_LINEAR);
  6479. for (int j = 0; j < track.weight_tracks[i].times.size(); j++) {
  6480. const float t = track.weight_tracks[i].times[j];
  6481. const float attribs = track.weight_tracks[i].values[j];
  6482. animation->blend_shape_track_insert_key(track_idx, t, attribs);
  6483. }
  6484. } else {
  6485. // CATMULLROMSPLINE or CUBIC_SPLINE have to be baked, apologies.
  6486. const double increment = 1.0 / p_state->get_bake_fps();
  6487. double time = 0.0;
  6488. bool last = false;
  6489. while (true) {
  6490. real_t blend = _interpolate_track<real_t>(track.weight_tracks[i].times, track.weight_tracks[i].values, time, gltf_interp);
  6491. animation->blend_shape_track_insert_key(track_idx, time - anim_start, blend);
  6492. if (last) {
  6493. break;
  6494. }
  6495. time += increment;
  6496. if (time >= anim_end) {
  6497. last = true;
  6498. time = anim_end;
  6499. }
  6500. }
  6501. }
  6502. }
  6503. }
  6504. for (const KeyValue<String, GLTFAnimation::Channel<Variant>> &track_iter : anim->get_pointer_tracks()) {
  6505. // Determine the property to animate.
  6506. const String json_pointer = track_iter.key;
  6507. const Ref<GLTFObjectModelProperty> prop = import_object_model_property(p_state, json_pointer);
  6508. ERR_FAIL_COND(prop.is_null());
  6509. // Adjust the animation duration to encompass all keyframes.
  6510. const GLTFAnimation::Channel<Variant> &channel = track_iter.value;
  6511. ERR_CONTINUE_MSG(channel.times.size() != channel.values.size(), vformat("glTF: Animation pointer '%s' has mismatched keyframe times and values.", json_pointer));
  6512. if (p_trimming) {
  6513. for (int i = 0; i < channel.times.size(); i++) {
  6514. anim_start = MIN(anim_start, channel.times[i]);
  6515. anim_end = MAX(anim_end, channel.times[i]);
  6516. }
  6517. } else {
  6518. for (int i = 0; i < channel.times.size(); i++) {
  6519. anim_end = MAX(anim_end, channel.times[i]);
  6520. }
  6521. }
  6522. // Begin converting the glTF animation to a Godot animation.
  6523. const Ref<Expression> gltf_to_godot_expr = prop->get_gltf_to_godot_expression();
  6524. const bool is_gltf_to_godot_expr_valid = gltf_to_godot_expr.is_valid();
  6525. for (const NodePath node_path : prop->get_node_paths()) {
  6526. // If using an expression, determine the base instance to pass to the expression.
  6527. Object *base_instance = nullptr;
  6528. if (is_gltf_to_godot_expr_valid) {
  6529. Ref<Resource> resource;
  6530. Vector<StringName> leftover_subpath;
  6531. base_instance = scene_root->get_node_and_resource(node_path, resource, leftover_subpath);
  6532. if (resource.is_valid()) {
  6533. base_instance = resource.ptr();
  6534. }
  6535. }
  6536. // Add a track and insert all keys and values.
  6537. const int track_index = animation->get_track_count();
  6538. animation->add_track(Animation::TYPE_VALUE);
  6539. animation->track_set_interpolation_type(track_index, GLTFAnimation::gltf_to_godot_interpolation(channel.interpolation));
  6540. animation->track_set_path(track_index, node_path);
  6541. for (int i = 0; i < channel.times.size(); i++) {
  6542. const double time = channel.times[i];
  6543. Variant value = channel.values[i];
  6544. if (is_gltf_to_godot_expr_valid) {
  6545. Array inputs;
  6546. inputs.append(value);
  6547. value = gltf_to_godot_expr->execute(inputs, base_instance);
  6548. }
  6549. animation->track_insert_key(track_index, time, value);
  6550. }
  6551. }
  6552. }
  6553. animation->set_length(anim_end - anim_start);
  6554. Ref<AnimationLibrary> library;
  6555. if (!p_animation_player->has_animation_library("")) {
  6556. library.instantiate();
  6557. p_animation_player->add_animation_library("", library);
  6558. } else {
  6559. library = p_animation_player->get_animation_library("");
  6560. }
  6561. library->add_animation(anim_name, animation);
  6562. }
  6563. void GLTFDocument::_convert_mesh_instances(Ref<GLTFState> p_state) {
  6564. for (GLTFNodeIndex mi_node_i = 0; mi_node_i < p_state->nodes.size(); ++mi_node_i) {
  6565. Ref<GLTFNode> node = p_state->nodes[mi_node_i];
  6566. if (node->mesh < 0) {
  6567. continue;
  6568. }
  6569. HashMap<GLTFNodeIndex, Node *>::Iterator mi_element = p_state->scene_nodes.find(mi_node_i);
  6570. if (!mi_element) {
  6571. continue;
  6572. }
  6573. MeshInstance3D *mi = Object::cast_to<MeshInstance3D>(mi_element->value);
  6574. if (!mi) {
  6575. continue;
  6576. }
  6577. node->transform = mi->get_transform();
  6578. Node *skel_node = mi->get_node_or_null(mi->get_skeleton_path());
  6579. Skeleton3D *godot_skeleton = Object::cast_to<Skeleton3D>(skel_node);
  6580. if (!godot_skeleton || godot_skeleton->get_bone_count() == 0) {
  6581. continue;
  6582. }
  6583. // At this point in the code, we know we have a Skeleton3D with at least one bone.
  6584. Ref<Skin> skin = mi->get_skin();
  6585. Ref<GLTFSkin> gltf_skin;
  6586. gltf_skin.instantiate();
  6587. Array json_joints;
  6588. if (p_state->skeleton3d_to_gltf_skeleton.has(godot_skeleton->get_instance_id())) {
  6589. // This is a skinned mesh. If the mesh has no ARRAY_WEIGHTS or ARRAY_BONES, it will be invisible.
  6590. const GLTFSkeletonIndex skeleton_gltf_i = p_state->skeleton3d_to_gltf_skeleton[godot_skeleton->get_instance_id()];
  6591. Ref<GLTFSkeleton> gltf_skeleton = p_state->skeletons[skeleton_gltf_i];
  6592. int bone_cnt = godot_skeleton->get_bone_count();
  6593. ERR_FAIL_COND(bone_cnt != gltf_skeleton->joints.size());
  6594. ObjectID gltf_skin_key;
  6595. if (skin.is_valid()) {
  6596. gltf_skin_key = skin->get_instance_id();
  6597. }
  6598. ObjectID gltf_skel_key = godot_skeleton->get_instance_id();
  6599. GLTFSkinIndex skin_gltf_i = -1;
  6600. GLTFNodeIndex root_gltf_i = -1;
  6601. if (!gltf_skeleton->roots.is_empty()) {
  6602. root_gltf_i = gltf_skeleton->roots[0];
  6603. }
  6604. if (p_state->skin_and_skeleton3d_to_gltf_skin.has(gltf_skin_key) && p_state->skin_and_skeleton3d_to_gltf_skin[gltf_skin_key].has(gltf_skel_key)) {
  6605. skin_gltf_i = p_state->skin_and_skeleton3d_to_gltf_skin[gltf_skin_key][gltf_skel_key];
  6606. } else {
  6607. if (skin.is_null()) {
  6608. // Note that gltf_skin_key should remain null, so these can share a reference.
  6609. skin = godot_skeleton->create_skin_from_rest_transforms();
  6610. }
  6611. gltf_skin.instantiate();
  6612. gltf_skin->godot_skin = skin;
  6613. gltf_skin->set_name(skin->get_name());
  6614. gltf_skin->skeleton = skeleton_gltf_i;
  6615. gltf_skin->skin_root = root_gltf_i;
  6616. //gltf_state->godot_to_gltf_node[skel_node]
  6617. HashMap<StringName, int> bone_name_to_idx;
  6618. for (int bone_i = 0; bone_i < bone_cnt; bone_i++) {
  6619. bone_name_to_idx[godot_skeleton->get_bone_name(bone_i)] = bone_i;
  6620. }
  6621. for (int bind_i = 0, cnt = skin->get_bind_count(); bind_i < cnt; bind_i++) {
  6622. int bone_i = skin->get_bind_bone(bind_i);
  6623. Transform3D bind_pose = skin->get_bind_pose(bind_i);
  6624. StringName bind_name = skin->get_bind_name(bind_i);
  6625. if (bind_name != StringName()) {
  6626. bone_i = bone_name_to_idx[bind_name];
  6627. }
  6628. ERR_CONTINUE(bone_i < 0 || bone_i >= bone_cnt);
  6629. if (bind_name == StringName()) {
  6630. bind_name = godot_skeleton->get_bone_name(bone_i);
  6631. }
  6632. GLTFNodeIndex skeleton_bone_i = gltf_skeleton->joints[bone_i];
  6633. gltf_skin->joints_original.push_back(skeleton_bone_i);
  6634. gltf_skin->joints.push_back(skeleton_bone_i);
  6635. gltf_skin->inverse_binds.push_back(bind_pose);
  6636. if (godot_skeleton->get_bone_parent(bone_i) == -1) {
  6637. gltf_skin->roots.push_back(skeleton_bone_i);
  6638. }
  6639. gltf_skin->joint_i_to_bone_i[bind_i] = bone_i;
  6640. gltf_skin->joint_i_to_name[bind_i] = bind_name;
  6641. }
  6642. skin_gltf_i = p_state->skins.size();
  6643. p_state->skins.push_back(gltf_skin);
  6644. p_state->skin_and_skeleton3d_to_gltf_skin[gltf_skin_key][gltf_skel_key] = skin_gltf_i;
  6645. }
  6646. node->skin = skin_gltf_i;
  6647. node->skeleton = skeleton_gltf_i;
  6648. }
  6649. }
  6650. }
  6651. float GLTFDocument::solve_metallic(float p_dielectric_specular, float p_diffuse, float p_specular, float p_one_minus_specular_strength) {
  6652. if (p_specular <= p_dielectric_specular) {
  6653. return 0.0f;
  6654. }
  6655. const float a = p_dielectric_specular;
  6656. const float b = p_diffuse * p_one_minus_specular_strength / (1.0f - p_dielectric_specular) + p_specular - 2.0f * p_dielectric_specular;
  6657. const float c = p_dielectric_specular - p_specular;
  6658. const float D = b * b - 4.0f * a * c;
  6659. return CLAMP((-b + Math::sqrt(D)) / (2.0f * a), 0.0f, 1.0f);
  6660. }
  6661. float GLTFDocument::get_perceived_brightness(const Color p_color) {
  6662. const Color coeff = Color(R_BRIGHTNESS_COEFF, G_BRIGHTNESS_COEFF, B_BRIGHTNESS_COEFF);
  6663. const Color value = coeff * (p_color * p_color);
  6664. const float r = value.r;
  6665. const float g = value.g;
  6666. const float b = value.b;
  6667. return Math::sqrt(r + g + b);
  6668. }
  6669. float GLTFDocument::get_max_component(const Color &p_color) {
  6670. const float r = p_color.r;
  6671. const float g = p_color.g;
  6672. const float b = p_color.b;
  6673. return MAX(MAX(r, g), b);
  6674. }
  6675. void GLTFDocument::_process_mesh_instances(Ref<GLTFState> p_state, Node *p_scene_root) {
  6676. for (GLTFNodeIndex node_i = 0; node_i < p_state->nodes.size(); ++node_i) {
  6677. Ref<GLTFNode> node = p_state->nodes[node_i];
  6678. if (node->skin >= 0 && node->mesh >= 0) {
  6679. const GLTFSkinIndex skin_i = node->skin;
  6680. ImporterMeshInstance3D *mi = nullptr;
  6681. HashMap<GLTFNodeIndex, ImporterMeshInstance3D *>::Iterator mi_element = p_state->scene_mesh_instances.find(node_i);
  6682. if (mi_element) {
  6683. mi = mi_element->value;
  6684. } else {
  6685. HashMap<GLTFNodeIndex, Node *>::Iterator si_element = p_state->scene_nodes.find(node_i);
  6686. ERR_CONTINUE_MSG(!si_element, vformat("Unable to find node %d", node_i));
  6687. mi = Object::cast_to<ImporterMeshInstance3D>(si_element->value);
  6688. ERR_CONTINUE_MSG(mi == nullptr, vformat("Unable to cast node %d of type %s to ImporterMeshInstance3D", node_i, si_element->value->get_class_name()));
  6689. }
  6690. const GLTFSkeletonIndex skel_i = p_state->skins.write[node->skin]->skeleton;
  6691. Ref<GLTFSkeleton> gltf_skeleton = p_state->skeletons.write[skel_i];
  6692. Skeleton3D *skeleton = gltf_skeleton->godot_skeleton;
  6693. ERR_CONTINUE_MSG(skeleton == nullptr, vformat("Unable to find Skeleton for node %d skin %d", node_i, skin_i));
  6694. mi->get_parent()->remove_child(mi);
  6695. mi->set_owner(nullptr);
  6696. skeleton->add_child(mi, true);
  6697. mi->set_owner(p_scene_root);
  6698. mi->set_skin(p_state->skins.write[skin_i]->godot_skin);
  6699. mi->set_skeleton_path(mi->get_path_to(skeleton));
  6700. mi->set_transform(Transform3D());
  6701. }
  6702. }
  6703. }
  6704. GLTFNodeIndex GLTFDocument::_node_and_or_bone_to_gltf_node_index(Ref<GLTFState> p_state, const Vector<StringName> &p_node_subpath, const Node *p_godot_node) {
  6705. const Skeleton3D *skeleton = Object::cast_to<Skeleton3D>(p_godot_node);
  6706. if (skeleton && p_node_subpath.size() == 1) {
  6707. // Special case: Handle skeleton bone TRS tracks. They use the format `A/B/C/Skeleton3D:bone_name`.
  6708. // We have a Skeleton3D, check if it has a bone with the same name as this subpath.
  6709. const String &bone_name = p_node_subpath[0];
  6710. const int32_t bone_index = skeleton->find_bone(bone_name);
  6711. if (bone_index != -1) {
  6712. // A bone was found! But we still need to figure out which glTF node it corresponds to.
  6713. for (GLTFSkeletonIndex skeleton_i = 0; skeleton_i < p_state->skeletons.size(); skeleton_i++) {
  6714. const Ref<GLTFSkeleton> &skeleton_gltf = p_state->skeletons[skeleton_i];
  6715. if (skeleton == skeleton_gltf->godot_skeleton) {
  6716. GLTFNodeIndex node_i = skeleton_gltf->godot_bone_node[bone_index];
  6717. return node_i;
  6718. }
  6719. }
  6720. ERR_FAIL_V_MSG(-1, vformat("glTF: Found a bone %s in a Skeleton3D that wasn't in the GLTFState. Ensure that all nodes referenced by the AnimationPlayer are in the scene you are exporting.", bone_name));
  6721. }
  6722. }
  6723. // General case: Not a skeleton bone, usually this means a normal node, or it could be the Skeleton3D itself.
  6724. for (const KeyValue<GLTFNodeIndex, Node *> &scene_node_i : p_state->scene_nodes) {
  6725. if (scene_node_i.value == p_godot_node) {
  6726. return scene_node_i.key;
  6727. }
  6728. }
  6729. ERR_FAIL_V_MSG(-1, vformat("glTF: A node was animated, but it wasn't found in the GLTFState. Ensure that all nodes referenced by the AnimationPlayer are in the scene you are exporting."));
  6730. }
  6731. bool GLTFDocument::_convert_animation_node_track(Ref<GLTFState> p_state, GLTFAnimation::NodeTrack &p_gltf_node_track, const Ref<Animation> &p_godot_animation, int32_t p_godot_anim_track_index, Vector<double> &p_times) {
  6732. GLTFAnimation::Interpolation gltf_interpolation = GLTFAnimation::godot_to_gltf_interpolation(p_godot_animation, p_godot_anim_track_index);
  6733. const Animation::TrackType track_type = p_godot_animation->track_get_type(p_godot_anim_track_index);
  6734. const int32_t key_count = p_godot_animation->track_get_key_count(p_godot_anim_track_index);
  6735. const NodePath node_path = p_godot_animation->track_get_path(p_godot_anim_track_index);
  6736. const Vector<StringName> subpath = node_path.get_subnames();
  6737. double anim_end = p_godot_animation->get_length();
  6738. if (track_type == Animation::TYPE_SCALE_3D) {
  6739. if (gltf_interpolation == GLTFAnimation::INTERP_CUBIC_SPLINE) {
  6740. gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
  6741. p_gltf_node_track.scale_track.times.clear();
  6742. p_gltf_node_track.scale_track.values.clear();
  6743. // CATMULLROMSPLINE or CUBIC_SPLINE have to be baked, apologies.
  6744. const double increment = 1.0 / p_state->get_bake_fps();
  6745. double time = 0.0;
  6746. bool last = false;
  6747. while (true) {
  6748. Vector3 scale;
  6749. Error err = p_godot_animation->try_scale_track_interpolate(p_godot_anim_track_index, time, &scale);
  6750. ERR_CONTINUE(err != OK);
  6751. p_gltf_node_track.scale_track.values.push_back(scale);
  6752. p_gltf_node_track.scale_track.times.push_back(time);
  6753. if (last) {
  6754. break;
  6755. }
  6756. time += increment;
  6757. if (time >= anim_end) {
  6758. last = true;
  6759. time = anim_end;
  6760. }
  6761. }
  6762. } else {
  6763. p_gltf_node_track.scale_track.times = p_times;
  6764. p_gltf_node_track.scale_track.interpolation = gltf_interpolation;
  6765. p_gltf_node_track.scale_track.values.resize(key_count);
  6766. for (int32_t key_i = 0; key_i < key_count; key_i++) {
  6767. Vector3 scale;
  6768. Error err = p_godot_animation->scale_track_get_key(p_godot_anim_track_index, key_i, &scale);
  6769. ERR_CONTINUE(err != OK);
  6770. p_gltf_node_track.scale_track.values.write[key_i] = scale;
  6771. }
  6772. }
  6773. } else if (track_type == Animation::TYPE_POSITION_3D) {
  6774. if (gltf_interpolation == GLTFAnimation::INTERP_CUBIC_SPLINE) {
  6775. gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
  6776. p_gltf_node_track.position_track.times.clear();
  6777. p_gltf_node_track.position_track.values.clear();
  6778. // CATMULLROMSPLINE or CUBIC_SPLINE have to be baked, apologies.
  6779. const double increment = 1.0 / p_state->get_bake_fps();
  6780. double time = 0.0;
  6781. bool last = false;
  6782. while (true) {
  6783. Vector3 scale;
  6784. Error err = p_godot_animation->try_position_track_interpolate(p_godot_anim_track_index, time, &scale);
  6785. ERR_CONTINUE(err != OK);
  6786. p_gltf_node_track.position_track.values.push_back(scale);
  6787. p_gltf_node_track.position_track.times.push_back(time);
  6788. if (last) {
  6789. break;
  6790. }
  6791. time += increment;
  6792. if (time >= anim_end) {
  6793. last = true;
  6794. time = anim_end;
  6795. }
  6796. }
  6797. } else {
  6798. p_gltf_node_track.position_track.times = p_times;
  6799. p_gltf_node_track.position_track.values.resize(key_count);
  6800. p_gltf_node_track.position_track.interpolation = gltf_interpolation;
  6801. for (int32_t key_i = 0; key_i < key_count; key_i++) {
  6802. Vector3 position;
  6803. Error err = p_godot_animation->position_track_get_key(p_godot_anim_track_index, key_i, &position);
  6804. ERR_CONTINUE(err != OK);
  6805. p_gltf_node_track.position_track.values.write[key_i] = position;
  6806. }
  6807. }
  6808. } else if (track_type == Animation::TYPE_ROTATION_3D) {
  6809. if (gltf_interpolation == GLTFAnimation::INTERP_CUBIC_SPLINE) {
  6810. gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
  6811. p_gltf_node_track.rotation_track.times.clear();
  6812. p_gltf_node_track.rotation_track.values.clear();
  6813. // CATMULLROMSPLINE or CUBIC_SPLINE have to be baked, apologies.
  6814. const double increment = 1.0 / p_state->get_bake_fps();
  6815. double time = 0.0;
  6816. bool last = false;
  6817. while (true) {
  6818. Quaternion rotation;
  6819. Error err = p_godot_animation->try_rotation_track_interpolate(p_godot_anim_track_index, time, &rotation);
  6820. ERR_CONTINUE(err != OK);
  6821. p_gltf_node_track.rotation_track.values.push_back(rotation);
  6822. p_gltf_node_track.rotation_track.times.push_back(time);
  6823. if (last) {
  6824. break;
  6825. }
  6826. time += increment;
  6827. if (time >= anim_end) {
  6828. last = true;
  6829. time = anim_end;
  6830. }
  6831. }
  6832. } else {
  6833. p_gltf_node_track.rotation_track.times = p_times;
  6834. p_gltf_node_track.rotation_track.values.resize(key_count);
  6835. p_gltf_node_track.rotation_track.interpolation = gltf_interpolation;
  6836. for (int32_t key_i = 0; key_i < key_count; key_i++) {
  6837. Quaternion rotation;
  6838. Error err = p_godot_animation->rotation_track_get_key(p_godot_anim_track_index, key_i, &rotation);
  6839. ERR_CONTINUE(err != OK);
  6840. p_gltf_node_track.rotation_track.values.write[key_i] = rotation;
  6841. }
  6842. }
  6843. } else if (subpath.size() > 0) {
  6844. const StringName &node_prop = subpath[0];
  6845. if (track_type == Animation::TYPE_VALUE) {
  6846. if (node_prop == "position") {
  6847. p_gltf_node_track.position_track.interpolation = gltf_interpolation;
  6848. p_gltf_node_track.position_track.times = p_times;
  6849. p_gltf_node_track.position_track.values.resize(key_count);
  6850. if (gltf_interpolation == GLTFAnimation::INTERP_CUBIC_SPLINE) {
  6851. gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
  6852. p_gltf_node_track.position_track.times.clear();
  6853. p_gltf_node_track.position_track.values.clear();
  6854. // CATMULLROMSPLINE or CUBIC_SPLINE have to be baked, apologies.
  6855. const double increment = 1.0 / p_state->get_bake_fps();
  6856. double time = 0.0;
  6857. bool last = false;
  6858. while (true) {
  6859. Vector3 position;
  6860. Error err = p_godot_animation->try_position_track_interpolate(p_godot_anim_track_index, time, &position);
  6861. ERR_CONTINUE(err != OK);
  6862. p_gltf_node_track.position_track.values.push_back(position);
  6863. p_gltf_node_track.position_track.times.push_back(time);
  6864. if (last) {
  6865. break;
  6866. }
  6867. time += increment;
  6868. if (time >= anim_end) {
  6869. last = true;
  6870. time = anim_end;
  6871. }
  6872. }
  6873. } else {
  6874. for (int32_t key_i = 0; key_i < key_count; key_i++) {
  6875. Vector3 position = p_godot_animation->track_get_key_value(p_godot_anim_track_index, key_i);
  6876. p_gltf_node_track.position_track.values.write[key_i] = position;
  6877. }
  6878. }
  6879. } else if (node_prop == "rotation" || node_prop == "rotation_degrees" || node_prop == "quaternion") {
  6880. p_gltf_node_track.rotation_track.interpolation = gltf_interpolation;
  6881. p_gltf_node_track.rotation_track.times = p_times;
  6882. p_gltf_node_track.rotation_track.values.resize(key_count);
  6883. if (gltf_interpolation == GLTFAnimation::INTERP_CUBIC_SPLINE) {
  6884. gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
  6885. p_gltf_node_track.rotation_track.times.clear();
  6886. p_gltf_node_track.rotation_track.values.clear();
  6887. // CATMULLROMSPLINE or CUBIC_SPLINE have to be baked, apologies.
  6888. const double increment = 1.0 / p_state->get_bake_fps();
  6889. double time = 0.0;
  6890. bool last = false;
  6891. while (true) {
  6892. Quaternion rotation;
  6893. Error err = p_godot_animation->try_rotation_track_interpolate(p_godot_anim_track_index, time, &rotation);
  6894. ERR_CONTINUE(err != OK);
  6895. p_gltf_node_track.rotation_track.values.push_back(rotation);
  6896. p_gltf_node_track.rotation_track.times.push_back(time);
  6897. if (last) {
  6898. break;
  6899. }
  6900. time += increment;
  6901. if (time >= anim_end) {
  6902. last = true;
  6903. time = anim_end;
  6904. }
  6905. }
  6906. } else {
  6907. for (int32_t key_i = 0; key_i < key_count; key_i++) {
  6908. Quaternion rotation_quaternion;
  6909. if (node_prop == "quaternion") {
  6910. rotation_quaternion = p_godot_animation->track_get_key_value(p_godot_anim_track_index, key_i);
  6911. } else {
  6912. Vector3 rotation_euler = p_godot_animation->track_get_key_value(p_godot_anim_track_index, key_i);
  6913. if (node_prop == "rotation_degrees") {
  6914. rotation_euler *= Math_TAU / 360.0;
  6915. }
  6916. rotation_quaternion = Quaternion::from_euler(rotation_euler);
  6917. }
  6918. p_gltf_node_track.rotation_track.values.write[key_i] = rotation_quaternion;
  6919. }
  6920. }
  6921. } else if (node_prop == "scale") {
  6922. p_gltf_node_track.scale_track.interpolation = gltf_interpolation;
  6923. p_gltf_node_track.scale_track.times = p_times;
  6924. p_gltf_node_track.scale_track.values.resize(key_count);
  6925. if (gltf_interpolation == GLTFAnimation::INTERP_CUBIC_SPLINE) {
  6926. gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
  6927. p_gltf_node_track.scale_track.times.clear();
  6928. p_gltf_node_track.scale_track.values.clear();
  6929. // CATMULLROMSPLINE or CUBIC_SPLINE have to be baked, apologies.
  6930. const double increment = 1.0 / p_state->get_bake_fps();
  6931. double time = 0.0;
  6932. bool last = false;
  6933. while (true) {
  6934. Vector3 scale;
  6935. Error err = p_godot_animation->try_scale_track_interpolate(p_godot_anim_track_index, time, &scale);
  6936. ERR_CONTINUE(err != OK);
  6937. p_gltf_node_track.scale_track.values.push_back(scale);
  6938. p_gltf_node_track.scale_track.times.push_back(time);
  6939. if (last) {
  6940. break;
  6941. }
  6942. time += increment;
  6943. if (time >= anim_end) {
  6944. last = true;
  6945. time = anim_end;
  6946. }
  6947. }
  6948. } else {
  6949. for (int32_t key_i = 0; key_i < key_count; key_i++) {
  6950. Vector3 scale_track = p_godot_animation->track_get_key_value(p_godot_anim_track_index, key_i);
  6951. p_gltf_node_track.scale_track.values.write[key_i] = scale_track;
  6952. }
  6953. }
  6954. } else if (node_prop == "transform") {
  6955. p_gltf_node_track.position_track.interpolation = gltf_interpolation;
  6956. p_gltf_node_track.position_track.times = p_times;
  6957. p_gltf_node_track.position_track.values.resize(key_count);
  6958. p_gltf_node_track.rotation_track.interpolation = gltf_interpolation;
  6959. p_gltf_node_track.rotation_track.times = p_times;
  6960. p_gltf_node_track.rotation_track.values.resize(key_count);
  6961. p_gltf_node_track.scale_track.interpolation = gltf_interpolation;
  6962. p_gltf_node_track.scale_track.times = p_times;
  6963. p_gltf_node_track.scale_track.values.resize(key_count);
  6964. if (gltf_interpolation == GLTFAnimation::INTERP_CUBIC_SPLINE) {
  6965. gltf_interpolation = GLTFAnimation::INTERP_LINEAR;
  6966. p_gltf_node_track.position_track.times.clear();
  6967. p_gltf_node_track.position_track.values.clear();
  6968. p_gltf_node_track.rotation_track.times.clear();
  6969. p_gltf_node_track.rotation_track.values.clear();
  6970. p_gltf_node_track.scale_track.times.clear();
  6971. p_gltf_node_track.scale_track.values.clear();
  6972. // CATMULLROMSPLINE or CUBIC_SPLINE have to be baked, apologies.
  6973. const double increment = 1.0 / p_state->get_bake_fps();
  6974. double time = 0.0;
  6975. bool last = false;
  6976. while (true) {
  6977. Vector3 position;
  6978. Quaternion rotation;
  6979. Vector3 scale;
  6980. Error err = p_godot_animation->try_position_track_interpolate(p_godot_anim_track_index, time, &position);
  6981. ERR_CONTINUE(err != OK);
  6982. err = p_godot_animation->try_rotation_track_interpolate(p_godot_anim_track_index, time, &rotation);
  6983. ERR_CONTINUE(err != OK);
  6984. err = p_godot_animation->try_scale_track_interpolate(p_godot_anim_track_index, time, &scale);
  6985. ERR_CONTINUE(err != OK);
  6986. p_gltf_node_track.position_track.values.push_back(position);
  6987. p_gltf_node_track.position_track.times.push_back(time);
  6988. p_gltf_node_track.rotation_track.values.push_back(rotation);
  6989. p_gltf_node_track.rotation_track.times.push_back(time);
  6990. p_gltf_node_track.scale_track.values.push_back(scale);
  6991. p_gltf_node_track.scale_track.times.push_back(time);
  6992. if (last) {
  6993. break;
  6994. }
  6995. time += increment;
  6996. if (time >= anim_end) {
  6997. last = true;
  6998. time = anim_end;
  6999. }
  7000. }
  7001. } else {
  7002. for (int32_t key_i = 0; key_i < key_count; key_i++) {
  7003. Transform3D transform = p_godot_animation->track_get_key_value(p_godot_anim_track_index, key_i);
  7004. p_gltf_node_track.position_track.values.write[key_i] = transform.get_origin();
  7005. p_gltf_node_track.rotation_track.values.write[key_i] = transform.basis.get_rotation_quaternion();
  7006. p_gltf_node_track.scale_track.values.write[key_i] = transform.basis.get_scale();
  7007. }
  7008. }
  7009. } else {
  7010. // This is a Value track animating a property, but not a TRS property, so it can't be converted into a node track.
  7011. return false;
  7012. }
  7013. } else if (track_type == Animation::TYPE_BEZIER) {
  7014. const int32_t keys = anim_end * p_state->get_bake_fps();
  7015. if (node_prop == "scale") {
  7016. if (p_gltf_node_track.scale_track.times.is_empty()) {
  7017. p_gltf_node_track.scale_track.interpolation = gltf_interpolation;
  7018. Vector<double> new_times;
  7019. new_times.resize(keys);
  7020. for (int32_t key_i = 0; key_i < keys; key_i++) {
  7021. new_times.write[key_i] = key_i / p_state->get_bake_fps();
  7022. }
  7023. p_gltf_node_track.scale_track.times = new_times;
  7024. p_gltf_node_track.scale_track.values.resize(keys);
  7025. for (int32_t key_i = 0; key_i < keys; key_i++) {
  7026. p_gltf_node_track.scale_track.values.write[key_i] = Vector3(1.0f, 1.0f, 1.0f);
  7027. }
  7028. for (int32_t key_i = 0; key_i < keys; key_i++) {
  7029. Vector3 bezier_track = p_gltf_node_track.scale_track.values[key_i];
  7030. if (subpath.size() == 2) {
  7031. if (subpath[1] == StringName("x")) {
  7032. bezier_track.x = p_godot_animation->bezier_track_interpolate(p_godot_anim_track_index, key_i / p_state->get_bake_fps());
  7033. } else if (subpath[1] == StringName("y")) {
  7034. bezier_track.y = p_godot_animation->bezier_track_interpolate(p_godot_anim_track_index, key_i / p_state->get_bake_fps());
  7035. } else if (subpath[1] == StringName("z")) {
  7036. bezier_track.z = p_godot_animation->bezier_track_interpolate(p_godot_anim_track_index, key_i / p_state->get_bake_fps());
  7037. }
  7038. }
  7039. p_gltf_node_track.scale_track.values.write[key_i] = bezier_track;
  7040. }
  7041. }
  7042. } else if (node_prop == "position") {
  7043. if (p_gltf_node_track.position_track.times.is_empty()) {
  7044. p_gltf_node_track.position_track.interpolation = gltf_interpolation;
  7045. Vector<double> new_times;
  7046. new_times.resize(keys);
  7047. for (int32_t key_i = 0; key_i < keys; key_i++) {
  7048. new_times.write[key_i] = key_i / p_state->get_bake_fps();
  7049. }
  7050. p_gltf_node_track.position_track.times = new_times;
  7051. p_gltf_node_track.position_track.values.resize(keys);
  7052. }
  7053. for (int32_t key_i = 0; key_i < keys; key_i++) {
  7054. Vector3 bezier_track = p_gltf_node_track.position_track.values[key_i];
  7055. if (subpath.size() == 2) {
  7056. if (subpath[1] == StringName("x")) {
  7057. bezier_track.x = p_godot_animation->bezier_track_interpolate(p_godot_anim_track_index, key_i / p_state->get_bake_fps());
  7058. } else if (subpath[1] == StringName("y")) {
  7059. bezier_track.y = p_godot_animation->bezier_track_interpolate(p_godot_anim_track_index, key_i / p_state->get_bake_fps());
  7060. } else if (subpath[1] == StringName("z")) {
  7061. bezier_track.z = p_godot_animation->bezier_track_interpolate(p_godot_anim_track_index, key_i / p_state->get_bake_fps());
  7062. }
  7063. }
  7064. p_gltf_node_track.position_track.values.write[key_i] = bezier_track;
  7065. }
  7066. } else if (node_prop == "quaternion") {
  7067. if (p_gltf_node_track.rotation_track.times.is_empty()) {
  7068. p_gltf_node_track.rotation_track.interpolation = gltf_interpolation;
  7069. Vector<double> new_times;
  7070. new_times.resize(keys);
  7071. for (int32_t key_i = 0; key_i < keys; key_i++) {
  7072. new_times.write[key_i] = key_i / p_state->get_bake_fps();
  7073. }
  7074. p_gltf_node_track.rotation_track.times = new_times;
  7075. p_gltf_node_track.rotation_track.values.resize(keys);
  7076. }
  7077. for (int32_t key_i = 0; key_i < keys; key_i++) {
  7078. Quaternion bezier_track = p_gltf_node_track.rotation_track.values[key_i];
  7079. if (subpath.size() == 2) {
  7080. if (subpath[1] == StringName("x")) {
  7081. bezier_track.x = p_godot_animation->bezier_track_interpolate(p_godot_anim_track_index, key_i / p_state->get_bake_fps());
  7082. } else if (subpath[1] == StringName("y")) {
  7083. bezier_track.y = p_godot_animation->bezier_track_interpolate(p_godot_anim_track_index, key_i / p_state->get_bake_fps());
  7084. } else if (subpath[1] == StringName("z")) {
  7085. bezier_track.z = p_godot_animation->bezier_track_interpolate(p_godot_anim_track_index, key_i / p_state->get_bake_fps());
  7086. } else if (subpath[1] == StringName("w")) {
  7087. bezier_track.w = p_godot_animation->bezier_track_interpolate(p_godot_anim_track_index, key_i / p_state->get_bake_fps());
  7088. }
  7089. }
  7090. p_gltf_node_track.rotation_track.values.write[key_i] = bezier_track;
  7091. }
  7092. } else {
  7093. // This is a Bezier track animating a property, but not a TRS property, so it can't be converted into a node track.
  7094. return false;
  7095. }
  7096. } else {
  7097. // This property track isn't a Value track or Bezier track, so it can't be converted into a node track.
  7098. return false;
  7099. }
  7100. } else {
  7101. // This isn't a TRS track or a property track, so it can't be converted into a node track.
  7102. return false;
  7103. }
  7104. // If we reached this point, the track was some kind of TRS track and was successfully converted.
  7105. // All failure paths should return false before this point to indicate this
  7106. // isn't a node track so it can be handled by KHR_animation_pointer instead.
  7107. return true;
  7108. }
  7109. void GLTFDocument::_convert_animation(Ref<GLTFState> p_state, AnimationPlayer *p_animation_player, const String &p_animation_track_name) {
  7110. Ref<Animation> animation = p_animation_player->get_animation(p_animation_track_name);
  7111. Ref<GLTFAnimation> gltf_animation;
  7112. gltf_animation.instantiate();
  7113. gltf_animation->set_original_name(p_animation_track_name);
  7114. gltf_animation->set_name(_gen_unique_name(p_state, p_animation_track_name));
  7115. HashMap<int, GLTFAnimation::NodeTrack> &node_tracks = gltf_animation->get_node_tracks();
  7116. for (int32_t track_index = 0; track_index < animation->get_track_count(); track_index++) {
  7117. if (!animation->track_is_enabled(track_index)) {
  7118. continue;
  7119. }
  7120. // Get the Godot node and the glTF node index for the animation track.
  7121. const NodePath track_path = animation->track_get_path(track_index);
  7122. const Node *anim_player_parent = p_animation_player->get_parent();
  7123. const Node *animated_node = anim_player_parent->get_node_or_null(track_path);
  7124. ERR_CONTINUE_MSG(!animated_node, "glTF: Cannot get node for animated track using path: " + String(track_path));
  7125. const GLTFAnimation::Interpolation gltf_interpolation = GLTFAnimation::godot_to_gltf_interpolation(animation, track_index);
  7126. // First, check if it's a Blend Shape track.
  7127. if (animation->track_get_type(track_index) == Animation::TYPE_BLEND_SHAPE) {
  7128. const MeshInstance3D *mesh_instance = Object::cast_to<MeshInstance3D>(animated_node);
  7129. ERR_CONTINUE_MSG(!mesh_instance, "glTF: Animation had a Blend Shape track, but the node wasn't a MeshInstance3D. Ignoring this track.");
  7130. Ref<Mesh> mesh = mesh_instance->get_mesh();
  7131. ERR_CONTINUE(mesh.is_null());
  7132. int32_t mesh_index = -1;
  7133. for (const KeyValue<GLTFNodeIndex, Node *> &mesh_track_i : p_state->scene_nodes) {
  7134. if (mesh_track_i.value == animated_node) {
  7135. mesh_index = mesh_track_i.key;
  7136. }
  7137. }
  7138. ERR_CONTINUE(mesh_index == -1);
  7139. GLTFAnimation::NodeTrack track = node_tracks.has(mesh_index) ? node_tracks[mesh_index] : GLTFAnimation::NodeTrack();
  7140. if (!node_tracks.has(mesh_index)) {
  7141. for (int32_t shape_i = 0; shape_i < mesh->get_blend_shape_count(); shape_i++) {
  7142. String shape_name = mesh->get_blend_shape_name(shape_i);
  7143. NodePath shape_path = NodePath(track_path.get_names(), { shape_name }, false);
  7144. int32_t shape_track_i = animation->find_track(shape_path, Animation::TYPE_BLEND_SHAPE);
  7145. if (shape_track_i == -1) {
  7146. GLTFAnimation::Channel<real_t> weight;
  7147. weight.interpolation = GLTFAnimation::INTERP_LINEAR;
  7148. weight.times.push_back(0.0f);
  7149. weight.times.push_back(0.0f);
  7150. weight.values.push_back(0.0f);
  7151. weight.values.push_back(0.0f);
  7152. track.weight_tracks.push_back(weight);
  7153. continue;
  7154. }
  7155. int32_t key_count = animation->track_get_key_count(shape_track_i);
  7156. GLTFAnimation::Channel<real_t> weight;
  7157. weight.interpolation = gltf_interpolation;
  7158. weight.times.resize(key_count);
  7159. for (int32_t time_i = 0; time_i < key_count; time_i++) {
  7160. weight.times.write[time_i] = animation->track_get_key_time(shape_track_i, time_i);
  7161. }
  7162. weight.values.resize(key_count);
  7163. for (int32_t value_i = 0; value_i < key_count; value_i++) {
  7164. weight.values.write[value_i] = animation->track_get_key_value(shape_track_i, value_i);
  7165. }
  7166. track.weight_tracks.push_back(weight);
  7167. }
  7168. node_tracks[mesh_index] = track;
  7169. }
  7170. continue;
  7171. }
  7172. // If it's not a Blend Shape track, it must either be a TRS track, a property Value track, or something we can't handle.
  7173. // For the cases we can handle, we will need to know the glTF node index, glTF interpolation, and the times of the track.
  7174. const Vector<StringName> subnames = track_path.get_subnames();
  7175. const GLTFNodeIndex node_i = _node_and_or_bone_to_gltf_node_index(p_state, subnames, animated_node);
  7176. ERR_CONTINUE_MSG(node_i == -1, "glTF: Cannot get glTF node index for animated track using path: " + String(track_path));
  7177. const int anim_key_count = animation->track_get_key_count(track_index);
  7178. Vector<double> times;
  7179. times.resize(anim_key_count);
  7180. for (int32_t key_i = 0; key_i < anim_key_count; key_i++) {
  7181. times.write[key_i] = animation->track_get_key_time(track_index, key_i);
  7182. }
  7183. // Try converting the track to a TRS glTF node track. This will only succeed if the Godot animation is a TRS track.
  7184. const HashMap<int, GLTFAnimation::NodeTrack>::Iterator node_track_iter = node_tracks.find(node_i);
  7185. GLTFAnimation::NodeTrack track;
  7186. if (node_track_iter) {
  7187. track = node_track_iter->value;
  7188. }
  7189. if (_convert_animation_node_track(p_state, track, animation, track_index, times)) {
  7190. // If the track was successfully converted, save it and continue to the next track.
  7191. node_tracks[node_i] = track;
  7192. continue;
  7193. }
  7194. // If the track wasn't a TRS track or Blend Shape track, it might be a Value track animating a property.
  7195. // Then this is something that we need to handle with KHR_animation_pointer.
  7196. Ref<GLTFObjectModelProperty> obj_model_prop = export_object_model_property(p_state, track_path, animated_node, node_i);
  7197. if (obj_model_prop.is_valid() && obj_model_prop->has_json_pointers()) {
  7198. // Insert the property track into the KHR_animation_pointer pointer tracks.
  7199. GLTFAnimation::Channel<Variant> channel;
  7200. channel.interpolation = gltf_interpolation;
  7201. channel.times = times;
  7202. channel.values.resize(anim_key_count);
  7203. // If using an expression, determine the base instance to pass to the expression.
  7204. const Ref<Expression> godot_to_gltf_expr = obj_model_prop->get_godot_to_gltf_expression();
  7205. const bool is_godot_to_gltf_expr_valid = godot_to_gltf_expr.is_valid();
  7206. Object *base_instance = nullptr;
  7207. if (is_godot_to_gltf_expr_valid) {
  7208. Ref<Resource> resource;
  7209. Vector<StringName> leftover_subpath;
  7210. base_instance = anim_player_parent->get_node_and_resource(track_path, resource, leftover_subpath);
  7211. if (resource.is_valid()) {
  7212. base_instance = resource.ptr();
  7213. }
  7214. }
  7215. // Convert the Godot animation values into glTF animation values (still Variant).
  7216. for (int32_t key_i = 0; key_i < anim_key_count; key_i++) {
  7217. Variant value = animation->track_get_key_value(track_index, key_i);
  7218. if (is_godot_to_gltf_expr_valid) {
  7219. Array inputs;
  7220. inputs.append(value);
  7221. value = godot_to_gltf_expr->execute(inputs, base_instance);
  7222. }
  7223. channel.values.write[key_i] = value;
  7224. }
  7225. // Use the JSON pointer to insert the property track into the pointer tracks. There will usually be just one JSON pointer.
  7226. HashMap<String, GLTFAnimation::Channel<Variant>> &pointer_tracks = gltf_animation->get_pointer_tracks();
  7227. Vector<PackedStringArray> split_json_pointers = obj_model_prop->get_json_pointers();
  7228. for (const PackedStringArray &split_json_pointer : split_json_pointers) {
  7229. String json_pointer_str = "/" + String("/").join(split_json_pointer);
  7230. p_state->object_model_properties[json_pointer_str] = obj_model_prop;
  7231. pointer_tracks[json_pointer_str] = channel;
  7232. }
  7233. }
  7234. }
  7235. if (!gltf_animation->is_empty_of_tracks()) {
  7236. p_state->animations.push_back(gltf_animation);
  7237. }
  7238. }
  7239. Error GLTFDocument::_parse(Ref<GLTFState> p_state, String p_path, Ref<FileAccess> p_file) {
  7240. Error err;
  7241. if (p_file.is_null()) {
  7242. return FAILED;
  7243. }
  7244. p_file->seek(0);
  7245. uint32_t magic = p_file->get_32();
  7246. if (magic == 0x46546C67) {
  7247. //binary file
  7248. //text file
  7249. p_file->seek(0);
  7250. err = _parse_glb(p_file, p_state);
  7251. if (err != OK) {
  7252. return err;
  7253. }
  7254. } else {
  7255. p_file->seek(0);
  7256. String text = p_file->get_as_utf8_string();
  7257. JSON json;
  7258. err = json.parse(text);
  7259. if (err != OK) {
  7260. _err_print_error("", "", json.get_error_line(), json.get_error_message().utf8().get_data(), false, ERR_HANDLER_SCRIPT);
  7261. }
  7262. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  7263. p_state->json = json.get_data();
  7264. }
  7265. err = _parse_asset_header(p_state);
  7266. ERR_FAIL_COND_V(err != OK, err);
  7267. document_extensions.clear();
  7268. for (Ref<GLTFDocumentExtension> ext : all_document_extensions) {
  7269. ERR_CONTINUE(ext.is_null());
  7270. err = ext->import_preflight(p_state, p_state->json["extensionsUsed"]);
  7271. if (err == OK) {
  7272. document_extensions.push_back(ext);
  7273. }
  7274. }
  7275. err = _parse_gltf_state(p_state, p_path);
  7276. ERR_FAIL_COND_V(err != OK, err);
  7277. return OK;
  7278. }
  7279. Dictionary _serialize_texture_transform_uv(Vector2 p_offset, Vector2 p_scale) {
  7280. Dictionary texture_transform;
  7281. bool is_offset = p_offset != Vector2(0.0, 0.0);
  7282. if (is_offset) {
  7283. Array offset;
  7284. offset.resize(2);
  7285. offset[0] = p_offset.x;
  7286. offset[1] = p_offset.y;
  7287. texture_transform["offset"] = offset;
  7288. }
  7289. bool is_scaled = p_scale != Vector2(1.0, 1.0);
  7290. if (is_scaled) {
  7291. Array scale;
  7292. scale.resize(2);
  7293. scale[0] = p_scale.x;
  7294. scale[1] = p_scale.y;
  7295. texture_transform["scale"] = scale;
  7296. }
  7297. Dictionary extension;
  7298. // Note: Godot doesn't support texture rotation.
  7299. if (is_offset || is_scaled) {
  7300. extension["KHR_texture_transform"] = texture_transform;
  7301. }
  7302. return extension;
  7303. }
  7304. Dictionary GLTFDocument::_serialize_texture_transform_uv1(Ref<BaseMaterial3D> p_material) {
  7305. ERR_FAIL_COND_V(p_material.is_null(), Dictionary());
  7306. Vector3 offset = p_material->get_uv1_offset();
  7307. Vector3 scale = p_material->get_uv1_scale();
  7308. return _serialize_texture_transform_uv(Vector2(offset.x, offset.y), Vector2(scale.x, scale.y));
  7309. }
  7310. Dictionary GLTFDocument::_serialize_texture_transform_uv2(Ref<BaseMaterial3D> p_material) {
  7311. ERR_FAIL_COND_V(p_material.is_null(), Dictionary());
  7312. Vector3 offset = p_material->get_uv2_offset();
  7313. Vector3 scale = p_material->get_uv2_scale();
  7314. return _serialize_texture_transform_uv(Vector2(offset.x, offset.y), Vector2(scale.x, scale.y));
  7315. }
  7316. Error GLTFDocument::_serialize_asset_header(Ref<GLTFState> p_state) {
  7317. const String version = "2.0";
  7318. p_state->major_version = version.get_slice(".", 0).to_int();
  7319. p_state->minor_version = version.get_slice(".", 1).to_int();
  7320. Dictionary asset;
  7321. asset["version"] = version;
  7322. if (!p_state->copyright.is_empty()) {
  7323. asset["copyright"] = p_state->copyright;
  7324. }
  7325. String hash = String(VERSION_HASH);
  7326. asset["generator"] = String(VERSION_FULL_NAME) + String("@") + (hash.is_empty() ? String("unknown") : hash);
  7327. p_state->json["asset"] = asset;
  7328. ERR_FAIL_COND_V(!asset.has("version"), Error::FAILED);
  7329. ERR_FAIL_COND_V(!p_state->json.has("asset"), Error::FAILED);
  7330. return OK;
  7331. }
  7332. Error GLTFDocument::_serialize_file(Ref<GLTFState> p_state, const String p_path) {
  7333. Error err = FAILED;
  7334. if (p_path.to_lower().ends_with("glb")) {
  7335. err = _encode_buffer_glb(p_state, p_path);
  7336. ERR_FAIL_COND_V(err != OK, err);
  7337. Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  7338. ERR_FAIL_COND_V(file.is_null(), FAILED);
  7339. String json = Variant(p_state->json).to_json_string();
  7340. const uint32_t magic = 0x46546C67; // GLTF
  7341. const int32_t header_size = 12;
  7342. const int32_t chunk_header_size = 8;
  7343. CharString cs = json.utf8();
  7344. const uint32_t text_data_length = cs.length();
  7345. const uint32_t text_chunk_length = ((text_data_length + 3) & (~3));
  7346. const uint32_t text_chunk_type = 0x4E4F534A; //JSON
  7347. uint32_t binary_data_length = 0;
  7348. if (p_state->buffers.size() > 0) {
  7349. binary_data_length = p_state->buffers[0].size();
  7350. }
  7351. const uint32_t binary_chunk_length = ((binary_data_length + 3) & (~3));
  7352. const uint32_t binary_chunk_type = 0x004E4942; //BIN
  7353. file->create(FileAccess::ACCESS_RESOURCES);
  7354. file->store_32(magic);
  7355. file->store_32(p_state->major_version); // version
  7356. uint32_t total_length = header_size + chunk_header_size + text_chunk_length;
  7357. if (binary_chunk_length) {
  7358. total_length += chunk_header_size + binary_chunk_length;
  7359. }
  7360. file->store_32(total_length);
  7361. // Write the JSON text chunk.
  7362. file->store_32(text_chunk_length);
  7363. file->store_32(text_chunk_type);
  7364. file->store_buffer((uint8_t *)&cs[0], cs.length());
  7365. for (uint32_t pad_i = text_data_length; pad_i < text_chunk_length; pad_i++) {
  7366. file->store_8(' ');
  7367. }
  7368. // Write a single binary chunk.
  7369. if (binary_chunk_length) {
  7370. file->store_32(binary_chunk_length);
  7371. file->store_32(binary_chunk_type);
  7372. file->store_buffer(p_state->buffers[0].ptr(), binary_data_length);
  7373. for (uint32_t pad_i = binary_data_length; pad_i < binary_chunk_length; pad_i++) {
  7374. file->store_8(0);
  7375. }
  7376. }
  7377. } else {
  7378. err = _encode_buffer_bins(p_state, p_path);
  7379. ERR_FAIL_COND_V(err != OK, err);
  7380. Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE, &err);
  7381. ERR_FAIL_COND_V(file.is_null(), FAILED);
  7382. file->create(FileAccess::ACCESS_RESOURCES);
  7383. String json = Variant(p_state->json).to_json_string();
  7384. file->store_string(json);
  7385. }
  7386. return err;
  7387. }
  7388. void GLTFDocument::_bind_methods() {
  7389. BIND_ENUM_CONSTANT(ROOT_NODE_MODE_SINGLE_ROOT);
  7390. BIND_ENUM_CONSTANT(ROOT_NODE_MODE_KEEP_ROOT);
  7391. BIND_ENUM_CONSTANT(ROOT_NODE_MODE_MULTI_ROOT);
  7392. ClassDB::bind_method(D_METHOD("set_image_format", "image_format"), &GLTFDocument::set_image_format);
  7393. ClassDB::bind_method(D_METHOD("get_image_format"), &GLTFDocument::get_image_format);
  7394. ClassDB::bind_method(D_METHOD("set_lossy_quality", "lossy_quality"), &GLTFDocument::set_lossy_quality);
  7395. ClassDB::bind_method(D_METHOD("get_lossy_quality"), &GLTFDocument::get_lossy_quality);
  7396. ClassDB::bind_method(D_METHOD("set_root_node_mode", "root_node_mode"), &GLTFDocument::set_root_node_mode);
  7397. ClassDB::bind_method(D_METHOD("get_root_node_mode"), &GLTFDocument::get_root_node_mode);
  7398. ClassDB::bind_method(D_METHOD("append_from_file", "path", "state", "flags", "base_path"),
  7399. &GLTFDocument::append_from_file, DEFVAL(0), DEFVAL(String()));
  7400. ClassDB::bind_method(D_METHOD("append_from_buffer", "bytes", "base_path", "state", "flags"),
  7401. &GLTFDocument::append_from_buffer, DEFVAL(0));
  7402. ClassDB::bind_method(D_METHOD("append_from_scene", "node", "state", "flags"),
  7403. &GLTFDocument::append_from_scene, DEFVAL(0));
  7404. ClassDB::bind_method(D_METHOD("generate_scene", "state", "bake_fps", "trimming", "remove_immutable_tracks"),
  7405. &GLTFDocument::generate_scene, DEFVAL(30), DEFVAL(false), DEFVAL(true));
  7406. ClassDB::bind_method(D_METHOD("generate_buffer", "state"),
  7407. &GLTFDocument::generate_buffer);
  7408. ClassDB::bind_method(D_METHOD("write_to_filesystem", "state", "path"),
  7409. &GLTFDocument::write_to_filesystem);
  7410. ADD_PROPERTY(PropertyInfo(Variant::STRING, "image_format"), "set_image_format", "get_image_format");
  7411. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "lossy_quality"), "set_lossy_quality", "get_lossy_quality");
  7412. ADD_PROPERTY(PropertyInfo(Variant::INT, "root_node_mode"), "set_root_node_mode", "get_root_node_mode");
  7413. ClassDB::bind_static_method("GLTFDocument", D_METHOD("import_object_model_property", "state", "json_pointer"), &GLTFDocument::import_object_model_property);
  7414. ClassDB::bind_static_method("GLTFDocument", D_METHOD("export_object_model_property", "state", "node_path", "godot_node", "gltf_node_index"), &GLTFDocument::export_object_model_property);
  7415. ClassDB::bind_static_method("GLTFDocument", D_METHOD("register_gltf_document_extension", "extension", "first_priority"),
  7416. &GLTFDocument::register_gltf_document_extension, DEFVAL(false));
  7417. ClassDB::bind_static_method("GLTFDocument", D_METHOD("unregister_gltf_document_extension", "extension"),
  7418. &GLTFDocument::unregister_gltf_document_extension);
  7419. ClassDB::bind_static_method("GLTFDocument", D_METHOD("get_supported_gltf_extensions"),
  7420. &GLTFDocument::get_supported_gltf_extensions);
  7421. }
  7422. void GLTFDocument::_build_parent_hierarchy(Ref<GLTFState> p_state) {
  7423. // build the hierarchy
  7424. for (GLTFNodeIndex node_i = 0; node_i < p_state->nodes.size(); node_i++) {
  7425. for (int j = 0; j < p_state->nodes[node_i]->children.size(); j++) {
  7426. GLTFNodeIndex child_i = p_state->nodes[node_i]->children[j];
  7427. ERR_FAIL_INDEX(child_i, p_state->nodes.size());
  7428. if (p_state->nodes.write[child_i]->parent != -1) {
  7429. continue;
  7430. }
  7431. p_state->nodes.write[child_i]->parent = node_i;
  7432. }
  7433. }
  7434. }
  7435. Vector<Ref<GLTFDocumentExtension>> GLTFDocument::all_document_extensions;
  7436. void GLTFDocument::register_gltf_document_extension(Ref<GLTFDocumentExtension> p_extension, bool p_first_priority) {
  7437. if (!all_document_extensions.has(p_extension)) {
  7438. if (p_first_priority) {
  7439. all_document_extensions.insert(0, p_extension);
  7440. } else {
  7441. all_document_extensions.push_back(p_extension);
  7442. }
  7443. }
  7444. }
  7445. void GLTFDocument::unregister_gltf_document_extension(Ref<GLTFDocumentExtension> p_extension) {
  7446. all_document_extensions.erase(p_extension);
  7447. }
  7448. void GLTFDocument::unregister_all_gltf_document_extensions() {
  7449. all_document_extensions.clear();
  7450. }
  7451. Vector<Ref<GLTFDocumentExtension>> GLTFDocument::get_all_gltf_document_extensions() {
  7452. return all_document_extensions;
  7453. }
  7454. Vector<String> GLTFDocument::get_supported_gltf_extensions() {
  7455. HashSet<String> set = get_supported_gltf_extensions_hashset();
  7456. Vector<String> vec;
  7457. for (const String &s : set) {
  7458. vec.append(s);
  7459. }
  7460. vec.sort();
  7461. return vec;
  7462. }
  7463. HashSet<String> GLTFDocument::get_supported_gltf_extensions_hashset() {
  7464. HashSet<String> supported_extensions;
  7465. // If the extension is supported directly in GLTFDocument, list it here.
  7466. // Other built-in extensions are supported by GLTFDocumentExtension classes.
  7467. supported_extensions.insert("GODOT_single_root");
  7468. supported_extensions.insert("KHR_animation_pointer");
  7469. supported_extensions.insert("KHR_lights_punctual");
  7470. supported_extensions.insert("KHR_materials_emissive_strength");
  7471. supported_extensions.insert("KHR_materials_pbrSpecularGlossiness");
  7472. supported_extensions.insert("KHR_materials_unlit");
  7473. supported_extensions.insert("KHR_texture_transform");
  7474. for (Ref<GLTFDocumentExtension> ext : all_document_extensions) {
  7475. ERR_CONTINUE(ext.is_null());
  7476. Vector<String> ext_supported_extensions = ext->get_supported_extensions();
  7477. for (int i = 0; i < ext_supported_extensions.size(); ++i) {
  7478. supported_extensions.insert(ext_supported_extensions[i]);
  7479. }
  7480. }
  7481. return supported_extensions;
  7482. }
  7483. PackedByteArray GLTFDocument::_serialize_glb_buffer(Ref<GLTFState> p_state, Error *r_err) {
  7484. Error err = _encode_buffer_glb(p_state, "");
  7485. if (r_err) {
  7486. *r_err = err;
  7487. }
  7488. ERR_FAIL_COND_V(err != OK, PackedByteArray());
  7489. String json = Variant(p_state->json).to_json_string();
  7490. const uint32_t magic = 0x46546C67; // GLTF
  7491. const int32_t header_size = 12;
  7492. const int32_t chunk_header_size = 8;
  7493. CharString cs = json.utf8();
  7494. int32_t padding = (chunk_header_size + cs.length()) % 4;
  7495. const uint32_t text_chunk_length = cs.length() + padding;
  7496. const uint32_t text_chunk_type = 0x4E4F534A; //JSON
  7497. int32_t binary_data_length = 0;
  7498. if (p_state->buffers.size() > 0) {
  7499. binary_data_length = p_state->buffers[0].size();
  7500. }
  7501. const int32_t binary_chunk_length = binary_data_length;
  7502. const int32_t binary_chunk_type = 0x004E4942; //BIN
  7503. Ref<StreamPeerBuffer> buffer;
  7504. buffer.instantiate();
  7505. buffer->put_32(magic);
  7506. buffer->put_32(p_state->major_version); // version
  7507. buffer->put_32(header_size + chunk_header_size + text_chunk_length + chunk_header_size + binary_data_length); // length
  7508. buffer->put_32(text_chunk_length);
  7509. buffer->put_32(text_chunk_type);
  7510. buffer->put_data((uint8_t *)&cs[0], cs.length());
  7511. for (int i = 0; i < padding; i++) {
  7512. buffer->put_8(' ');
  7513. }
  7514. if (binary_chunk_length) {
  7515. buffer->put_32(binary_chunk_length);
  7516. buffer->put_32(binary_chunk_type);
  7517. buffer->put_data(p_state->buffers[0].ptr(), binary_data_length);
  7518. }
  7519. return buffer->get_data_array();
  7520. }
  7521. Node *GLTFDocument::_generate_scene_node_tree(Ref<GLTFState> p_state) {
  7522. // Generate the skeletons and skins (if any).
  7523. HashMap<ObjectID, SkinSkeletonIndex> skeleton_map;
  7524. Error err = SkinTool::_create_skeletons(p_state->unique_names, p_state->skins, p_state->nodes,
  7525. skeleton_map, p_state->skeletons, p_state->scene_nodes);
  7526. ERR_FAIL_COND_V_MSG(err != OK, nullptr, "glTF: Failed to create skeletons.");
  7527. err = _create_skins(p_state);
  7528. ERR_FAIL_COND_V_MSG(err != OK, nullptr, "glTF: Failed to create skins.");
  7529. // Run pre-generate for each extension, in case an extension needs to do something before generating the scene.
  7530. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  7531. ERR_CONTINUE(ext.is_null());
  7532. err = ext->import_pre_generate(p_state);
  7533. ERR_CONTINUE(err != OK);
  7534. }
  7535. // Generate the node tree.
  7536. Node *single_root;
  7537. if (p_state->extensions_used.has("GODOT_single_root")) {
  7538. _generate_scene_node(p_state, 0, nullptr, nullptr);
  7539. single_root = p_state->scene_nodes[0];
  7540. if (single_root && single_root->get_owner() && single_root->get_owner() != single_root) {
  7541. single_root = single_root->get_owner();
  7542. }
  7543. } else {
  7544. single_root = memnew(Node3D);
  7545. for (int32_t root_i = 0; root_i < p_state->root_nodes.size(); root_i++) {
  7546. _generate_scene_node(p_state, p_state->root_nodes[root_i], single_root, single_root);
  7547. }
  7548. }
  7549. // Assign the scene name and single root name to each other
  7550. // if one is missing, or do nothing if both are already set.
  7551. if (unlikely(p_state->scene_name.is_empty())) {
  7552. p_state->scene_name = single_root->get_name();
  7553. } else if (single_root->get_name() == StringName()) {
  7554. if (_naming_version == 0) {
  7555. single_root->set_name(p_state->scene_name);
  7556. } else {
  7557. single_root->set_name(_gen_unique_name(p_state, p_state->scene_name));
  7558. }
  7559. }
  7560. return single_root;
  7561. }
  7562. Error GLTFDocument::_parse_asset_header(Ref<GLTFState> p_state) {
  7563. if (!p_state->json.has("asset")) {
  7564. return ERR_PARSE_ERROR;
  7565. }
  7566. Dictionary asset = p_state->json["asset"];
  7567. if (!asset.has("version")) {
  7568. return ERR_PARSE_ERROR;
  7569. }
  7570. String version = asset["version"];
  7571. p_state->major_version = version.get_slice(".", 0).to_int();
  7572. p_state->minor_version = version.get_slice(".", 1).to_int();
  7573. if (asset.has("copyright")) {
  7574. p_state->copyright = asset["copyright"];
  7575. }
  7576. return OK;
  7577. }
  7578. Error GLTFDocument::_parse_gltf_state(Ref<GLTFState> p_state, const String &p_search_path) {
  7579. Error err;
  7580. /* PARSE EXTENSIONS */
  7581. err = _parse_gltf_extensions(p_state);
  7582. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  7583. /* PARSE SCENE */
  7584. err = _parse_scenes(p_state);
  7585. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  7586. /* PARSE NODES */
  7587. err = _parse_nodes(p_state);
  7588. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  7589. /* PARSE BUFFERS */
  7590. err = _parse_buffers(p_state, p_search_path);
  7591. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  7592. /* PARSE BUFFER VIEWS */
  7593. err = _parse_buffer_views(p_state);
  7594. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  7595. /* PARSE ACCESSORS */
  7596. err = _parse_accessors(p_state);
  7597. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  7598. if (!p_state->discard_meshes_and_materials) {
  7599. /* PARSE IMAGES */
  7600. err = _parse_images(p_state, p_search_path);
  7601. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  7602. /* PARSE TEXTURE SAMPLERS */
  7603. err = _parse_texture_samplers(p_state);
  7604. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  7605. /* PARSE TEXTURES */
  7606. err = _parse_textures(p_state);
  7607. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  7608. /* PARSE TEXTURES */
  7609. err = _parse_materials(p_state);
  7610. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  7611. }
  7612. /* PARSE SKINS */
  7613. err = _parse_skins(p_state);
  7614. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  7615. /* DETERMINE SKELETONS */
  7616. err = SkinTool::_determine_skeletons(p_state->skins, p_state->nodes, p_state->skeletons, p_state->get_import_as_skeleton_bones() ? p_state->root_nodes : Vector<GLTFNodeIndex>());
  7617. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  7618. /* ASSIGN SCENE NODE NAMES */
  7619. // This must be run AFTER determining skeletons, and BEFORE parsing animations.
  7620. _assign_node_names(p_state);
  7621. /* PARSE MESHES (we have enough info now) */
  7622. err = _parse_meshes(p_state);
  7623. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  7624. /* PARSE LIGHTS */
  7625. err = _parse_lights(p_state);
  7626. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  7627. /* PARSE CAMERAS */
  7628. err = _parse_cameras(p_state);
  7629. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  7630. /* PARSE ANIMATIONS */
  7631. err = _parse_animations(p_state);
  7632. ERR_FAIL_COND_V(err != OK, ERR_PARSE_ERROR);
  7633. return OK;
  7634. }
  7635. PackedByteArray GLTFDocument::generate_buffer(Ref<GLTFState> p_state) {
  7636. Ref<GLTFState> state = p_state;
  7637. ERR_FAIL_COND_V(state.is_null(), PackedByteArray());
  7638. // For buffers, set the state filename to an empty string, but
  7639. // don't touch the base path, in case the user set it manually.
  7640. state->filename = "";
  7641. Error err = _serialize(state);
  7642. ERR_FAIL_COND_V(err != OK, PackedByteArray());
  7643. PackedByteArray bytes = _serialize_glb_buffer(state, &err);
  7644. return bytes;
  7645. }
  7646. Error GLTFDocument::write_to_filesystem(Ref<GLTFState> p_state, const String &p_path) {
  7647. Ref<GLTFState> state = p_state;
  7648. ERR_FAIL_COND_V(state.is_null(), ERR_INVALID_PARAMETER);
  7649. state->set_base_path(p_path.get_base_dir());
  7650. state->filename = p_path.get_file();
  7651. Error err = _serialize(state);
  7652. if (err != OK) {
  7653. return err;
  7654. }
  7655. err = _serialize_file(state, p_path);
  7656. if (err != OK) {
  7657. return Error::FAILED;
  7658. }
  7659. return OK;
  7660. }
  7661. Node *GLTFDocument::generate_scene(Ref<GLTFState> p_state, float p_bake_fps, bool p_trimming, bool p_remove_immutable_tracks) {
  7662. Ref<GLTFState> state = p_state;
  7663. ERR_FAIL_COND_V(state.is_null(), nullptr);
  7664. ERR_FAIL_INDEX_V(0, state->root_nodes.size(), nullptr);
  7665. Error err = OK;
  7666. p_state->set_bake_fps(p_bake_fps);
  7667. Node *root = _generate_scene_node_tree(state);
  7668. ERR_FAIL_NULL_V(root, nullptr);
  7669. _process_mesh_instances(state, root);
  7670. if (state->get_create_animations() && state->animations.size()) {
  7671. AnimationPlayer *ap = memnew(AnimationPlayer);
  7672. root->add_child(ap, true);
  7673. ap->set_owner(root);
  7674. for (int i = 0; i < state->animations.size(); i++) {
  7675. _import_animation(state, ap, i, p_trimming, p_remove_immutable_tracks);
  7676. }
  7677. }
  7678. for (KeyValue<GLTFNodeIndex, Node *> E : state->scene_nodes) {
  7679. ERR_CONTINUE(!E.value);
  7680. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  7681. ERR_CONTINUE(ext.is_null());
  7682. Dictionary node_json;
  7683. if (state->json.has("nodes")) {
  7684. Array nodes = state->json["nodes"];
  7685. if (0 <= E.key && E.key < nodes.size()) {
  7686. node_json = nodes[E.key];
  7687. }
  7688. }
  7689. Ref<GLTFNode> gltf_node = state->nodes[E.key];
  7690. err = ext->import_node(p_state, gltf_node, node_json, E.value);
  7691. ERR_CONTINUE(err != OK);
  7692. }
  7693. }
  7694. ImporterMeshInstance3D *root_importer_mesh = Object::cast_to<ImporterMeshInstance3D>(root);
  7695. if (unlikely(root_importer_mesh)) {
  7696. root = GLTFDocumentExtensionConvertImporterMesh::convert_importer_mesh_instance_3d(root_importer_mesh);
  7697. memdelete(root_importer_mesh);
  7698. }
  7699. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  7700. ERR_CONTINUE(ext.is_null());
  7701. err = ext->import_post(p_state, root);
  7702. ERR_CONTINUE(err != OK);
  7703. }
  7704. ERR_FAIL_NULL_V(root, nullptr);
  7705. return root;
  7706. }
  7707. Error GLTFDocument::append_from_scene(Node *p_node, Ref<GLTFState> p_state, uint32_t p_flags) {
  7708. ERR_FAIL_NULL_V(p_node, FAILED);
  7709. Ref<GLTFState> state = p_state;
  7710. ERR_FAIL_COND_V(state.is_null(), FAILED);
  7711. state->use_named_skin_binds = p_flags & GLTF_IMPORT_USE_NAMED_SKIN_BINDS;
  7712. state->discard_meshes_and_materials = p_flags & GLTF_IMPORT_DISCARD_MESHES_AND_MATERIALS;
  7713. state->force_generate_tangents = p_flags & GLTF_IMPORT_GENERATE_TANGENT_ARRAYS;
  7714. state->force_disable_compression = p_flags & GLTF_IMPORT_FORCE_DISABLE_MESH_COMPRESSION;
  7715. if (!state->buffers.size()) {
  7716. state->buffers.push_back(Vector<uint8_t>());
  7717. }
  7718. // Perform export preflight for document extensions. Only extensions that
  7719. // return OK will be used for the rest of the export steps.
  7720. document_extensions.clear();
  7721. for (Ref<GLTFDocumentExtension> ext : all_document_extensions) {
  7722. ERR_CONTINUE(ext.is_null());
  7723. Error err = ext->export_preflight(state, p_node);
  7724. if (err == OK) {
  7725. document_extensions.push_back(ext);
  7726. }
  7727. }
  7728. // Add the root node(s) and their descendants to the state.
  7729. if (_root_node_mode == RootNodeMode::ROOT_NODE_MODE_MULTI_ROOT) {
  7730. const int child_count = p_node->get_child_count();
  7731. if (child_count > 0) {
  7732. for (int i = 0; i < child_count; i++) {
  7733. _convert_scene_node(state, p_node->get_child(i), -1, -1);
  7734. }
  7735. state->scene_name = p_node->get_name();
  7736. return OK;
  7737. }
  7738. }
  7739. if (_root_node_mode == RootNodeMode::ROOT_NODE_MODE_SINGLE_ROOT) {
  7740. state->extensions_used.append("GODOT_single_root");
  7741. }
  7742. _convert_scene_node(state, p_node, -1, -1);
  7743. // Run post-convert for each extension, in case an extension needs to do something after converting the scene.
  7744. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  7745. ERR_CONTINUE(ext.is_null());
  7746. Error err = ext->export_post_convert(p_state, p_node);
  7747. ERR_CONTINUE(err != OK);
  7748. }
  7749. return OK;
  7750. }
  7751. Error GLTFDocument::append_from_buffer(PackedByteArray p_bytes, String p_base_path, Ref<GLTFState> p_state, uint32_t p_flags) {
  7752. Ref<GLTFState> state = p_state;
  7753. ERR_FAIL_COND_V(state.is_null(), FAILED);
  7754. // TODO Add missing texture and missing .bin file paths to r_missing_deps 2021-09-10 fire
  7755. Error err = FAILED;
  7756. state->use_named_skin_binds = p_flags & GLTF_IMPORT_USE_NAMED_SKIN_BINDS;
  7757. state->discard_meshes_and_materials = p_flags & GLTF_IMPORT_DISCARD_MESHES_AND_MATERIALS;
  7758. state->force_generate_tangents = p_flags & GLTF_IMPORT_GENERATE_TANGENT_ARRAYS;
  7759. state->force_disable_compression = p_flags & GLTF_IMPORT_FORCE_DISABLE_MESH_COMPRESSION;
  7760. Ref<FileAccessMemory> file_access;
  7761. file_access.instantiate();
  7762. file_access->open_custom(p_bytes.ptr(), p_bytes.size());
  7763. state->set_base_path(p_base_path.get_base_dir());
  7764. err = _parse(p_state, state->base_path, file_access);
  7765. ERR_FAIL_COND_V(err != OK, err);
  7766. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  7767. ERR_CONTINUE(ext.is_null());
  7768. err = ext->import_post_parse(state);
  7769. ERR_FAIL_COND_V(err != OK, err);
  7770. }
  7771. return OK;
  7772. }
  7773. Error GLTFDocument::append_from_file(String p_path, Ref<GLTFState> p_state, uint32_t p_flags, String p_base_path) {
  7774. Ref<GLTFState> state = p_state;
  7775. // TODO Add missing texture and missing .bin file paths to r_missing_deps 2021-09-10 fire
  7776. if (state == Ref<GLTFState>()) {
  7777. state.instantiate();
  7778. }
  7779. state->set_filename(p_path.get_file().get_basename());
  7780. state->use_named_skin_binds = p_flags & GLTF_IMPORT_USE_NAMED_SKIN_BINDS;
  7781. state->discard_meshes_and_materials = p_flags & GLTF_IMPORT_DISCARD_MESHES_AND_MATERIALS;
  7782. state->force_generate_tangents = p_flags & GLTF_IMPORT_GENERATE_TANGENT_ARRAYS;
  7783. state->force_disable_compression = p_flags & GLTF_IMPORT_FORCE_DISABLE_MESH_COMPRESSION;
  7784. Error err;
  7785. Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::READ, &err);
  7786. ERR_FAIL_COND_V_MSG(err != OK, err, vformat(R"(Can't open file at path "%s")", p_path));
  7787. ERR_FAIL_COND_V(file.is_null(), ERR_FILE_CANT_OPEN);
  7788. String base_path = p_base_path;
  7789. if (base_path.is_empty()) {
  7790. base_path = p_path.get_base_dir();
  7791. }
  7792. state->set_base_path(base_path);
  7793. err = _parse(p_state, base_path, file);
  7794. ERR_FAIL_COND_V(err != OK, err);
  7795. for (Ref<GLTFDocumentExtension> ext : document_extensions) {
  7796. ERR_CONTINUE(ext.is_null());
  7797. err = ext->import_post_parse(p_state);
  7798. ERR_FAIL_COND_V(err != OK, err);
  7799. }
  7800. return OK;
  7801. }
  7802. Error GLTFDocument::_parse_gltf_extensions(Ref<GLTFState> p_state) {
  7803. ERR_FAIL_COND_V(p_state.is_null(), ERR_PARSE_ERROR);
  7804. if (p_state->json.has("extensionsUsed")) {
  7805. Vector<String> ext_array = p_state->json["extensionsUsed"];
  7806. p_state->extensions_used = ext_array;
  7807. }
  7808. if (p_state->json.has("extensionsRequired")) {
  7809. Vector<String> ext_array = p_state->json["extensionsRequired"];
  7810. p_state->extensions_required = ext_array;
  7811. }
  7812. HashSet<String> supported_extensions = get_supported_gltf_extensions_hashset();
  7813. Error ret = OK;
  7814. for (int i = 0; i < p_state->extensions_required.size(); i++) {
  7815. if (!supported_extensions.has(p_state->extensions_required[i])) {
  7816. ERR_PRINT("glTF: Can't import file '" + p_state->filename + "', required extension '" + String(p_state->extensions_required[i]) + "' is not supported. Are you missing a GLTFDocumentExtension plugin?");
  7817. ret = ERR_UNAVAILABLE;
  7818. }
  7819. }
  7820. return ret;
  7821. }
  7822. void GLTFDocument::set_root_node_mode(GLTFDocument::RootNodeMode p_root_node_mode) {
  7823. _root_node_mode = p_root_node_mode;
  7824. }
  7825. GLTFDocument::RootNodeMode GLTFDocument::get_root_node_mode() const {
  7826. return _root_node_mode;
  7827. }
  7828. String GLTFDocument::_gen_unique_name_static(HashSet<String> &r_unique_names, const String &p_name) {
  7829. const String s_name = p_name.validate_node_name();
  7830. String u_name;
  7831. int index = 1;
  7832. while (true) {
  7833. u_name = s_name;
  7834. if (index > 1) {
  7835. u_name += itos(index);
  7836. }
  7837. if (!r_unique_names.has(u_name)) {
  7838. break;
  7839. }
  7840. index++;
  7841. }
  7842. r_unique_names.insert(u_name);
  7843. return u_name;
  7844. }