gltf_document.cpp 262 KB

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