gltf_document.cpp 236 KB

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