gltf_document.cpp 336 KB

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