gltf_document.cpp 228 KB

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