gltf_document.cpp 228 KB

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