gltf_document.cpp 272 KB

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