gltf_document.cpp 222 KB

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