gltfpack.cpp 118 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609
  1. // gltfpack is part of meshoptimizer library; see meshoptimizer.h for version/license details
  2. //
  3. // gltfpack is a command-line tool that takes a glTF file as an input and can produce two types of files:
  4. // - regular glb/gltf files that use data that has been optimized for GPU consumption using various cache optimizers
  5. // and quantization
  6. // - packed glb/gltf files that additionally use meshoptimizer codecs to reduce the size of vertex/index data; these
  7. // files can be further compressed with deflate/etc.
  8. //
  9. // To load regular glb files, it should be sufficient to use a standard glTF loader (although note that these files
  10. // use quantized position/texture coordinates that require support for KHR_mesh_quantization; THREE.js and BabylonJS
  11. // support these files out of the box).
  12. // To load packed glb files, meshoptimizer vertex decoder needs to be integrated into the loader; demo/GLTFLoader.js
  13. // contains a work-in-progress loader - please note that the extension specification isn't ready yet so the format
  14. // will change!
  15. #ifndef _CRT_SECURE_NO_WARNINGS
  16. #define _CRT_SECURE_NO_WARNINGS
  17. #endif
  18. #ifndef _CRT_NONSTDC_NO_WARNINGS
  19. #define _CRT_NONSTDC_NO_WARNINGS
  20. #endif
  21. #include "../src/meshoptimizer.h"
  22. #include <algorithm>
  23. #include <string>
  24. #include <vector>
  25. #include <float.h>
  26. #include <limits.h>
  27. #include <math.h>
  28. #include <stdint.h>
  29. #include <stdio.h>
  30. #include <string.h>
  31. #ifdef _WIN32
  32. #include <io.h>
  33. #define popen _popen
  34. #define pclose _pclose
  35. #else
  36. #include <unistd.h>
  37. #endif
  38. #include "cgltf.h"
  39. #include "fast_obj.h"
  40. struct Attr
  41. {
  42. float f[4];
  43. };
  44. struct Stream
  45. {
  46. cgltf_attribute_type type;
  47. int index;
  48. int target; // 0 = base mesh, 1+ = morph target
  49. std::vector<Attr> data;
  50. };
  51. struct Mesh
  52. {
  53. cgltf_node* node;
  54. cgltf_material* material;
  55. cgltf_skin* skin;
  56. cgltf_primitive_type type;
  57. std::vector<Stream> streams;
  58. std::vector<unsigned int> indices;
  59. size_t targets;
  60. std::vector<float> target_weights;
  61. std::vector<const char*> target_names;
  62. };
  63. struct Track
  64. {
  65. cgltf_node* node;
  66. cgltf_animation_path_type path;
  67. bool dummy;
  68. size_t components; // 1 unless path is cgltf_animation_path_type_weights
  69. cgltf_interpolation_type interpolation;
  70. std::vector<float> time; // empty for resampled or constant animations
  71. std::vector<Attr> data;
  72. };
  73. struct Animation
  74. {
  75. const char* name;
  76. float start;
  77. int frames;
  78. std::vector<Track> tracks;
  79. };
  80. struct Settings
  81. {
  82. int pos_bits;
  83. int tex_bits;
  84. int nrm_bits;
  85. bool nrm_unnormalized;
  86. int anim_freq;
  87. bool anim_const;
  88. bool keep_named;
  89. float simplify_threshold;
  90. bool simplify_aggressive;
  91. bool texture_embed;
  92. bool texture_basis;
  93. bool texture_ktx2;
  94. int texture_quality;
  95. bool compress;
  96. bool fallback;
  97. int verbose;
  98. };
  99. struct QuantizationParams
  100. {
  101. float pos_offset[3];
  102. float pos_scale;
  103. int pos_bits;
  104. float uv_offset[2];
  105. float uv_scale[2];
  106. int uv_bits;
  107. };
  108. struct StreamFormat
  109. {
  110. cgltf_type type;
  111. cgltf_component_type component_type;
  112. bool normalized;
  113. size_t stride;
  114. };
  115. struct NodeInfo
  116. {
  117. bool keep;
  118. bool animated;
  119. unsigned int animated_paths;
  120. int remap;
  121. std::vector<size_t> meshes;
  122. };
  123. struct MaterialInfo
  124. {
  125. bool keep;
  126. int remap;
  127. };
  128. struct ImageInfo
  129. {
  130. bool normal_map;
  131. bool srgb;
  132. };
  133. struct ExtensionInfo
  134. {
  135. const char* name;
  136. bool used;
  137. bool required;
  138. };
  139. struct BufferView
  140. {
  141. enum Kind
  142. {
  143. Kind_Vertex,
  144. Kind_Index,
  145. Kind_Skin,
  146. Kind_Time,
  147. Kind_Keyframe,
  148. Kind_Image,
  149. Kind_Count
  150. };
  151. Kind kind;
  152. int variant;
  153. size_t stride;
  154. bool compressed;
  155. std::string data;
  156. size_t bytes;
  157. };
  158. const char* getError(cgltf_result result, cgltf_data* data)
  159. {
  160. switch (result)
  161. {
  162. case cgltf_result_file_not_found:
  163. return data ? "resource not found" : "file not found";
  164. case cgltf_result_io_error:
  165. return "I/O error";
  166. case cgltf_result_invalid_json:
  167. return "invalid JSON";
  168. case cgltf_result_invalid_gltf:
  169. return "invalid GLTF";
  170. case cgltf_result_out_of_memory:
  171. return "out of memory";
  172. case cgltf_result_legacy_gltf:
  173. return "legacy GLTF";
  174. case cgltf_result_data_too_short:
  175. return data ? "buffer too short" : "not a GLTF file";
  176. case cgltf_result_unknown_format:
  177. return data ? "unknown resource format" : "not a GLTF file";
  178. default:
  179. return "unknown error";
  180. }
  181. }
  182. cgltf_accessor* getAccessor(const cgltf_attribute* attributes, size_t attribute_count, cgltf_attribute_type type, int index = 0)
  183. {
  184. for (size_t i = 0; i < attribute_count; ++i)
  185. if (attributes[i].type == type && attributes[i].index == index)
  186. return attributes[i].data;
  187. return 0;
  188. }
  189. void readAccessor(std::vector<float>& data, const cgltf_accessor* accessor)
  190. {
  191. assert(accessor->type == cgltf_type_scalar);
  192. data.resize(accessor->count);
  193. cgltf_accessor_unpack_floats(accessor, &data[0], data.size());
  194. }
  195. void readAccessor(std::vector<Attr>& data, const cgltf_accessor* accessor)
  196. {
  197. size_t components = cgltf_num_components(accessor->type);
  198. std::vector<float> temp(accessor->count * components);
  199. cgltf_accessor_unpack_floats(accessor, &temp[0], temp.size());
  200. data.resize(accessor->count);
  201. for (size_t i = 0; i < accessor->count; ++i)
  202. {
  203. for (size_t k = 0; k < components && k < 4; ++k)
  204. data[i].f[k] = temp[i * components + k];
  205. }
  206. }
  207. void transformPosition(float* ptr, const float* transform)
  208. {
  209. float x = ptr[0] * transform[0] + ptr[1] * transform[4] + ptr[2] * transform[8] + transform[12];
  210. float y = ptr[0] * transform[1] + ptr[1] * transform[5] + ptr[2] * transform[9] + transform[13];
  211. float z = ptr[0] * transform[2] + ptr[1] * transform[6] + ptr[2] * transform[10] + transform[14];
  212. ptr[0] = x;
  213. ptr[1] = y;
  214. ptr[2] = z;
  215. }
  216. void transformNormal(float* ptr, const float* transform)
  217. {
  218. float x = ptr[0] * transform[0] + ptr[1] * transform[4] + ptr[2] * transform[8];
  219. float y = ptr[0] * transform[1] + ptr[1] * transform[5] + ptr[2] * transform[9];
  220. float z = ptr[0] * transform[2] + ptr[1] * transform[6] + ptr[2] * transform[10];
  221. float l = sqrtf(x * x + y * y + z * z);
  222. float s = (l == 0.f) ? 0.f : 1 / l;
  223. ptr[0] = x * s;
  224. ptr[1] = y * s;
  225. ptr[2] = z * s;
  226. }
  227. void transformMesh(Mesh& mesh, const cgltf_node* node)
  228. {
  229. float transform[16];
  230. cgltf_node_transform_world(node, transform);
  231. for (size_t si = 0; si < mesh.streams.size(); ++si)
  232. {
  233. Stream& stream = mesh.streams[si];
  234. if (stream.type == cgltf_attribute_type_position)
  235. {
  236. for (size_t i = 0; i < stream.data.size(); ++i)
  237. transformPosition(stream.data[i].f, transform);
  238. }
  239. else if (stream.type == cgltf_attribute_type_normal || stream.type == cgltf_attribute_type_tangent)
  240. {
  241. for (size_t i = 0; i < stream.data.size(); ++i)
  242. transformNormal(stream.data[i].f, transform);
  243. }
  244. }
  245. }
  246. void parseMeshes(cgltf_data* data, std::vector<Mesh>& meshes)
  247. {
  248. for (size_t ni = 0; ni < data->nodes_count; ++ni)
  249. {
  250. cgltf_node& node = data->nodes[ni];
  251. if (!node.mesh)
  252. continue;
  253. const cgltf_mesh& mesh = *node.mesh;
  254. int mesh_id = int(&mesh - data->meshes);
  255. for (size_t pi = 0; pi < mesh.primitives_count; ++pi)
  256. {
  257. const cgltf_primitive& primitive = mesh.primitives[pi];
  258. if (primitive.type != cgltf_primitive_type_triangles && primitive.type != cgltf_primitive_type_points)
  259. {
  260. fprintf(stderr, "Warning: ignoring primitive %d of mesh %d because type %d is not supported\n", int(pi), mesh_id, primitive.type);
  261. continue;
  262. }
  263. if (primitive.type == cgltf_primitive_type_points && primitive.indices)
  264. {
  265. fprintf(stderr, "Warning: ignoring primitive %d of mesh %d because indexed points are not supported\n", int(pi), mesh_id);
  266. continue;
  267. }
  268. Mesh result = {};
  269. result.node = &node;
  270. result.material = primitive.material;
  271. result.skin = node.skin;
  272. result.type = primitive.type;
  273. if (primitive.indices)
  274. {
  275. result.indices.resize(primitive.indices->count);
  276. for (size_t i = 0; i < primitive.indices->count; ++i)
  277. result.indices[i] = unsigned(cgltf_accessor_read_index(primitive.indices, i));
  278. }
  279. else if (primitive.type != cgltf_primitive_type_points)
  280. {
  281. size_t count = primitive.attributes ? primitive.attributes[0].data->count : 0;
  282. // note, while we could generate a good index buffer, reindexMesh will take care of this
  283. result.indices.resize(count);
  284. for (size_t i = 0; i < count; ++i)
  285. result.indices[i] = unsigned(i);
  286. }
  287. for (size_t ai = 0; ai < primitive.attributes_count; ++ai)
  288. {
  289. const cgltf_attribute& attr = primitive.attributes[ai];
  290. if (attr.type == cgltf_attribute_type_invalid)
  291. {
  292. fprintf(stderr, "Warning: ignoring unknown attribute %s in primitive %d of mesh %d\n", attr.name, int(pi), mesh_id);
  293. continue;
  294. }
  295. Stream s = {attr.type, attr.index};
  296. readAccessor(s.data, attr.data);
  297. if (attr.type == cgltf_attribute_type_color && attr.data->type == cgltf_type_vec3)
  298. {
  299. for (size_t i = 0; i < s.data.size(); ++i)
  300. s.data[i].f[3] = 1.0f;
  301. }
  302. result.streams.push_back(s);
  303. }
  304. for (size_t ti = 0; ti < primitive.targets_count; ++ti)
  305. {
  306. const cgltf_morph_target& target = primitive.targets[ti];
  307. for (size_t ai = 0; ai < target.attributes_count; ++ai)
  308. {
  309. const cgltf_attribute& attr = target.attributes[ai];
  310. if (attr.type == cgltf_attribute_type_invalid)
  311. {
  312. fprintf(stderr, "Warning: ignoring unknown attribute %s in morph target %d of primitive %d of mesh %d\n", attr.name, int(ti), int(pi), mesh_id);
  313. continue;
  314. }
  315. Stream s = {attr.type, attr.index, int(ti + 1)};
  316. readAccessor(s.data, attr.data);
  317. result.streams.push_back(s);
  318. }
  319. }
  320. result.targets = primitive.targets_count;
  321. result.target_weights.assign(mesh.weights, mesh.weights + mesh.weights_count);
  322. result.target_names.assign(mesh.target_names, mesh.target_names + mesh.target_names_count);
  323. meshes.push_back(result);
  324. }
  325. }
  326. }
  327. void defaultFree(void*, void* p)
  328. {
  329. free(p);
  330. }
  331. int textureIndex(const std::vector<std::string>& textures, const char* name)
  332. {
  333. for (size_t i = 0; i < textures.size(); ++i)
  334. if (textures[i] == name)
  335. return int(i);
  336. return -1;
  337. }
  338. cgltf_data* parseSceneObj(fastObjMesh* obj)
  339. {
  340. cgltf_data* data = (cgltf_data*)calloc(1, sizeof(cgltf_data));
  341. data->memory_free = defaultFree;
  342. std::vector<std::string> textures;
  343. for (unsigned int mi = 0; mi < obj->material_count; ++mi)
  344. {
  345. fastObjMaterial& om = obj->materials[mi];
  346. if (om.map_Kd.name && textureIndex(textures, om.map_Kd.name) < 0)
  347. textures.push_back(om.map_Kd.name);
  348. }
  349. data->images = (cgltf_image*)calloc(textures.size(), sizeof(cgltf_image));
  350. data->images_count = textures.size();
  351. for (size_t i = 0; i < textures.size(); ++i)
  352. {
  353. data->images[i].uri = strdup(textures[i].c_str());
  354. }
  355. data->textures = (cgltf_texture*)calloc(textures.size(), sizeof(cgltf_texture));
  356. data->textures_count = textures.size();
  357. for (size_t i = 0; i < textures.size(); ++i)
  358. {
  359. data->textures[i].image = &data->images[i];
  360. }
  361. data->materials = (cgltf_material*)calloc(obj->material_count, sizeof(cgltf_material));
  362. data->materials_count = obj->material_count;
  363. for (unsigned int mi = 0; mi < obj->material_count; ++mi)
  364. {
  365. cgltf_material& gm = data->materials[mi];
  366. fastObjMaterial& om = obj->materials[mi];
  367. gm.has_pbr_metallic_roughness = true;
  368. gm.pbr_metallic_roughness.base_color_factor[0] = 1.0f;
  369. gm.pbr_metallic_roughness.base_color_factor[1] = 1.0f;
  370. gm.pbr_metallic_roughness.base_color_factor[2] = 1.0f;
  371. gm.pbr_metallic_roughness.base_color_factor[3] = 1.0f;
  372. gm.pbr_metallic_roughness.metallic_factor = 0.0f;
  373. gm.pbr_metallic_roughness.roughness_factor = 1.0f;
  374. gm.alpha_cutoff = 0.5f;
  375. if (om.map_Kd.name)
  376. {
  377. gm.pbr_metallic_roughness.base_color_texture.texture = &data->textures[textureIndex(textures, om.map_Kd.name)];
  378. gm.pbr_metallic_roughness.base_color_texture.scale = 1.0f;
  379. gm.alpha_mode = (om.illum == 4 || om.illum == 6 || om.illum == 7 || om.illum == 9) ? cgltf_alpha_mode_mask : cgltf_alpha_mode_opaque;
  380. }
  381. if (om.map_d.name)
  382. {
  383. gm.alpha_mode = cgltf_alpha_mode_blend;
  384. }
  385. }
  386. return data;
  387. }
  388. void parseMeshesObj(fastObjMesh* obj, cgltf_data* data, std::vector<Mesh>& meshes)
  389. {
  390. unsigned int material_count = std::max(obj->material_count, 1u);
  391. std::vector<size_t> vertex_count(material_count);
  392. std::vector<size_t> index_count(material_count);
  393. for (unsigned int fi = 0; fi < obj->face_count; ++fi)
  394. {
  395. unsigned int mi = obj->face_materials[fi];
  396. vertex_count[mi] += obj->face_vertices[fi];
  397. index_count[mi] += (obj->face_vertices[fi] - 2) * 3;
  398. }
  399. std::vector<size_t> mesh_index(material_count);
  400. for (unsigned int mi = 0; mi < material_count; ++mi)
  401. {
  402. if (index_count[mi] == 0)
  403. continue;
  404. mesh_index[mi] = meshes.size();
  405. meshes.push_back(Mesh());
  406. Mesh& mesh = meshes.back();
  407. if (data->materials_count)
  408. {
  409. assert(mi < data->materials_count);
  410. mesh.material = &data->materials[mi];
  411. }
  412. mesh.type = cgltf_primitive_type_triangles;
  413. mesh.streams.resize(3);
  414. mesh.streams[0].type = cgltf_attribute_type_position;
  415. mesh.streams[0].data.resize(vertex_count[mi]);
  416. mesh.streams[1].type = cgltf_attribute_type_normal;
  417. mesh.streams[1].data.resize(vertex_count[mi]);
  418. mesh.streams[2].type = cgltf_attribute_type_texcoord;
  419. mesh.streams[2].data.resize(vertex_count[mi]);
  420. mesh.indices.resize(index_count[mi]);
  421. mesh.targets = 0;
  422. }
  423. std::vector<size_t> vertex_offset(material_count);
  424. std::vector<size_t> index_offset(material_count);
  425. size_t group_offset = 0;
  426. for (unsigned int fi = 0; fi < obj->face_count; ++fi)
  427. {
  428. unsigned int mi = obj->face_materials[fi];
  429. Mesh& mesh = meshes[mesh_index[mi]];
  430. size_t vo = vertex_offset[mi];
  431. size_t io = index_offset[mi];
  432. for (unsigned int vi = 0; vi < obj->face_vertices[fi]; ++vi)
  433. {
  434. fastObjIndex ii = obj->indices[group_offset + vi];
  435. Attr p = {{obj->positions[ii.p * 3 + 0], obj->positions[ii.p * 3 + 1], obj->positions[ii.p * 3 + 2]}};
  436. Attr n = {{obj->normals[ii.n * 3 + 0], obj->normals[ii.n * 3 + 1], obj->normals[ii.n * 3 + 2]}};
  437. Attr t = {{obj->texcoords[ii.t * 2 + 0], 1.f - obj->texcoords[ii.t * 2 + 1]}};
  438. mesh.streams[0].data[vo + vi] = p;
  439. mesh.streams[1].data[vo + vi] = n;
  440. mesh.streams[2].data[vo + vi] = t;
  441. }
  442. for (unsigned int vi = 2; vi < obj->face_vertices[fi]; ++vi)
  443. {
  444. size_t to = io + (vi - 2) * 3;
  445. mesh.indices[to + 0] = unsigned(vo);
  446. mesh.indices[to + 1] = unsigned(vo + vi - 1);
  447. mesh.indices[to + 2] = unsigned(vo + vi);
  448. }
  449. vertex_offset[mi] += obj->face_vertices[fi];
  450. index_offset[mi] += (obj->face_vertices[fi] - 2) * 3;
  451. group_offset += obj->face_vertices[fi];
  452. }
  453. }
  454. void parseAnimations(cgltf_data* data, std::vector<Animation>& animations)
  455. {
  456. for (size_t i = 0; i < data->animations_count; ++i)
  457. {
  458. const cgltf_animation& animation = data->animations[i];
  459. Animation result = {};
  460. result.name = animation.name;
  461. for (size_t j = 0; j < animation.channels_count; ++j)
  462. {
  463. const cgltf_animation_channel& channel = animation.channels[j];
  464. if (!channel.target_node)
  465. {
  466. fprintf(stderr, "Warning: ignoring channel %d of animation %d because it has no target node\n", int(j), int(i));
  467. continue;
  468. }
  469. Track track = {};
  470. track.node = channel.target_node;
  471. track.path = channel.target_path;
  472. track.components = (channel.target_path == cgltf_animation_path_type_weights) ? track.node->mesh->primitives[0].targets_count : 1;
  473. track.interpolation = channel.sampler->interpolation;
  474. readAccessor(track.time, channel.sampler->input);
  475. readAccessor(track.data, channel.sampler->output);
  476. result.tracks.push_back(track);
  477. }
  478. if (result.tracks.empty())
  479. {
  480. fprintf(stderr, "Warning: ignoring animation %d because it has no valid tracks\n", int(i));
  481. continue;
  482. }
  483. animations.push_back(result);
  484. }
  485. }
  486. bool areTextureViewsEqual(const cgltf_texture_view& lhs, const cgltf_texture_view& rhs)
  487. {
  488. if (lhs.has_transform != rhs.has_transform)
  489. return false;
  490. if (lhs.has_transform)
  491. {
  492. const cgltf_texture_transform& lt = lhs.transform;
  493. const cgltf_texture_transform& rt = rhs.transform;
  494. if (memcmp(lt.offset, rt.offset, sizeof(cgltf_float) * 2) != 0)
  495. return false;
  496. if (lt.rotation != rt.rotation)
  497. return false;
  498. if (memcmp(lt.scale, rt.scale, sizeof(cgltf_float) * 2) != 0)
  499. return false;
  500. if (lt.texcoord != rt.texcoord)
  501. return false;
  502. }
  503. if (lhs.texture != rhs.texture)
  504. return false;
  505. if (lhs.texcoord != rhs.texcoord)
  506. return false;
  507. if (lhs.scale != rhs.scale)
  508. return false;
  509. return true;
  510. }
  511. bool areMaterialsEqual(const cgltf_material& lhs, const cgltf_material& rhs)
  512. {
  513. if (lhs.has_pbr_metallic_roughness != rhs.has_pbr_metallic_roughness)
  514. return false;
  515. if (lhs.has_pbr_metallic_roughness)
  516. {
  517. const cgltf_pbr_metallic_roughness& lpbr = lhs.pbr_metallic_roughness;
  518. const cgltf_pbr_metallic_roughness& rpbr = rhs.pbr_metallic_roughness;
  519. if (!areTextureViewsEqual(lpbr.base_color_texture, rpbr.base_color_texture))
  520. return false;
  521. if (!areTextureViewsEqual(lpbr.metallic_roughness_texture, rpbr.metallic_roughness_texture))
  522. return false;
  523. if (memcmp(lpbr.base_color_factor, rpbr.base_color_factor, sizeof(cgltf_float) * 4) != 0)
  524. return false;
  525. if (lpbr.metallic_factor != rpbr.metallic_factor)
  526. return false;
  527. if (lpbr.roughness_factor != rpbr.roughness_factor)
  528. return false;
  529. }
  530. if (lhs.has_pbr_specular_glossiness != rhs.has_pbr_specular_glossiness)
  531. return false;
  532. if (lhs.has_pbr_specular_glossiness)
  533. {
  534. const cgltf_pbr_specular_glossiness& lpbr = lhs.pbr_specular_glossiness;
  535. const cgltf_pbr_specular_glossiness& rpbr = rhs.pbr_specular_glossiness;
  536. if (!areTextureViewsEqual(lpbr.diffuse_texture, rpbr.diffuse_texture))
  537. return false;
  538. if (!areTextureViewsEqual(lpbr.specular_glossiness_texture, rpbr.specular_glossiness_texture))
  539. return false;
  540. if (memcmp(lpbr.diffuse_factor, rpbr.diffuse_factor, sizeof(cgltf_float) * 4) != 0)
  541. return false;
  542. if (memcmp(lpbr.specular_factor, rpbr.specular_factor, sizeof(cgltf_float) * 3) != 0)
  543. return false;
  544. if (lpbr.glossiness_factor != rpbr.glossiness_factor)
  545. return false;
  546. }
  547. if (!areTextureViewsEqual(lhs.normal_texture, rhs.normal_texture))
  548. return false;
  549. if (!areTextureViewsEqual(lhs.occlusion_texture, rhs.occlusion_texture))
  550. return false;
  551. if (!areTextureViewsEqual(lhs.emissive_texture, rhs.emissive_texture))
  552. return false;
  553. if (memcmp(lhs.emissive_factor, rhs.emissive_factor, sizeof(cgltf_float) * 3) != 0)
  554. return false;
  555. if (lhs.alpha_mode != rhs.alpha_mode)
  556. return false;
  557. if (lhs.alpha_cutoff != rhs.alpha_cutoff)
  558. return false;
  559. if (lhs.double_sided != rhs.double_sided)
  560. return false;
  561. if (lhs.unlit != rhs.unlit)
  562. return false;
  563. return true;
  564. }
  565. bool usesTextureSet(const cgltf_material& material, int set)
  566. {
  567. if (material.has_pbr_metallic_roughness)
  568. {
  569. const cgltf_pbr_metallic_roughness& pbr = material.pbr_metallic_roughness;
  570. if (pbr.base_color_texture.texture && pbr.base_color_texture.texcoord == set)
  571. return true;
  572. if (pbr.metallic_roughness_texture.texture && pbr.metallic_roughness_texture.texcoord == set)
  573. return true;
  574. }
  575. if (material.has_pbr_specular_glossiness)
  576. {
  577. const cgltf_pbr_specular_glossiness& pbr = material.pbr_specular_glossiness;
  578. if (pbr.diffuse_texture.texture && pbr.diffuse_texture.texcoord == set)
  579. return true;
  580. if (pbr.specular_glossiness_texture.texture && pbr.specular_glossiness_texture.texcoord == set)
  581. return true;
  582. }
  583. if (material.normal_texture.texture && material.normal_texture.texcoord == set)
  584. return true;
  585. if (material.occlusion_texture.texture && material.occlusion_texture.texcoord == set)
  586. return true;
  587. if (material.emissive_texture.texture && material.emissive_texture.texcoord == set)
  588. return true;
  589. return false;
  590. }
  591. void mergeMeshMaterials(cgltf_data* data, std::vector<Mesh>& meshes)
  592. {
  593. for (size_t i = 0; i < meshes.size(); ++i)
  594. {
  595. Mesh& mesh = meshes[i];
  596. if (!mesh.material)
  597. continue;
  598. for (int j = 0; j < mesh.material - data->materials; ++j)
  599. {
  600. if (areMaterialsEqual(*mesh.material, data->materials[j]))
  601. {
  602. mesh.material = &data->materials[j];
  603. break;
  604. }
  605. }
  606. }
  607. }
  608. bool compareMeshTargets(const Mesh& lhs, const Mesh& rhs)
  609. {
  610. if (lhs.targets != rhs.targets)
  611. return false;
  612. if (lhs.target_weights.size() != rhs.target_weights.size())
  613. return false;
  614. for (size_t i = 0; i < lhs.target_weights.size(); ++i)
  615. if (lhs.target_weights[i] != rhs.target_weights[i])
  616. return false;
  617. if (lhs.target_names.size() != rhs.target_names.size())
  618. return false;
  619. for (size_t i = 0; i < lhs.target_names.size(); ++i)
  620. if (strcmp(lhs.target_names[i], rhs.target_names[i]) != 0)
  621. return false;
  622. return true;
  623. }
  624. bool canMergeMeshes(const Mesh& lhs, const Mesh& rhs, const Settings& settings)
  625. {
  626. if (lhs.node != rhs.node)
  627. {
  628. if (!lhs.node || !rhs.node)
  629. return false;
  630. if (lhs.node->parent != rhs.node->parent)
  631. return false;
  632. bool lhs_transform = lhs.node->has_translation | lhs.node->has_rotation | lhs.node->has_scale | lhs.node->has_matrix | (!!lhs.node->weights);
  633. bool rhs_transform = rhs.node->has_translation | rhs.node->has_rotation | rhs.node->has_scale | rhs.node->has_matrix | (!!rhs.node->weights);
  634. if (lhs_transform || rhs_transform)
  635. return false;
  636. if (settings.keep_named)
  637. {
  638. if (lhs.node->name && *lhs.node->name)
  639. return false;
  640. if (rhs.node->name && *rhs.node->name)
  641. return false;
  642. }
  643. // we can merge nodes that don't have transforms of their own and have the same parent
  644. // this is helpful when instead of splitting mesh into primitives, DCCs split mesh into mesh nodes
  645. }
  646. if (lhs.material != rhs.material)
  647. return false;
  648. if (lhs.skin != rhs.skin)
  649. return false;
  650. if (lhs.type != rhs.type)
  651. return false;
  652. if (!compareMeshTargets(lhs, rhs))
  653. return false;
  654. if (lhs.indices.empty() != rhs.indices.empty())
  655. return false;
  656. if (lhs.streams.size() != rhs.streams.size())
  657. return false;
  658. for (size_t i = 0; i < lhs.streams.size(); ++i)
  659. if (lhs.streams[i].type != rhs.streams[i].type || lhs.streams[i].index != rhs.streams[i].index || lhs.streams[i].target != rhs.streams[i].target)
  660. return false;
  661. return true;
  662. }
  663. void mergeMeshes(Mesh& target, const Mesh& mesh)
  664. {
  665. assert(target.streams.size() == mesh.streams.size());
  666. size_t vertex_offset = target.streams[0].data.size();
  667. size_t index_offset = target.indices.size();
  668. for (size_t i = 0; i < target.streams.size(); ++i)
  669. target.streams[i].data.insert(target.streams[i].data.end(), mesh.streams[i].data.begin(), mesh.streams[i].data.end());
  670. target.indices.resize(target.indices.size() + mesh.indices.size());
  671. size_t index_count = mesh.indices.size();
  672. for (size_t i = 0; i < index_count; ++i)
  673. target.indices[index_offset + i] = unsigned(vertex_offset + mesh.indices[i]);
  674. }
  675. void mergeMeshes(std::vector<Mesh>& meshes, const Settings& settings)
  676. {
  677. for (size_t i = 0; i < meshes.size(); ++i)
  678. {
  679. Mesh& target = meshes[i];
  680. if (target.streams.empty())
  681. continue;
  682. size_t target_vertices = target.streams[0].data.size();
  683. size_t target_indices = target.indices.size();
  684. size_t last_merged = i;
  685. for (size_t j = i + 1; j < meshes.size(); ++j)
  686. {
  687. Mesh& mesh = meshes[j];
  688. if (!mesh.streams.empty() && canMergeMeshes(target, mesh, settings))
  689. {
  690. target_vertices += mesh.streams[0].data.size();
  691. target_indices += mesh.indices.size();
  692. last_merged = j;
  693. }
  694. }
  695. for (size_t j = 0; j < target.streams.size(); ++j)
  696. target.streams[j].data.reserve(target_vertices);
  697. target.indices.reserve(target_indices);
  698. for (size_t j = i + 1; j <= last_merged; ++j)
  699. {
  700. Mesh& mesh = meshes[j];
  701. if (!mesh.streams.empty() && canMergeMeshes(target, mesh, settings))
  702. {
  703. mergeMeshes(target, mesh);
  704. mesh.streams.clear();
  705. mesh.indices.clear();
  706. }
  707. }
  708. assert(target.streams[0].data.size() == target_vertices);
  709. assert(target.indices.size() == target_indices);
  710. }
  711. }
  712. void filterEmptyMeshes(std::vector<Mesh>& meshes)
  713. {
  714. size_t write = 0;
  715. for (size_t i = 0; i < meshes.size(); ++i)
  716. {
  717. Mesh& mesh = meshes[i];
  718. if (mesh.streams.empty())
  719. continue;
  720. if (mesh.streams[0].data.empty())
  721. continue;
  722. if (mesh.type == cgltf_primitive_type_triangles && mesh.indices.empty())
  723. continue;
  724. // the following code is roughly equivalent to meshes[write] = std::move(mesh)
  725. std::vector<Stream> streams;
  726. streams.swap(mesh.streams);
  727. std::vector<unsigned int> indices;
  728. indices.swap(mesh.indices);
  729. meshes[write] = mesh;
  730. meshes[write].streams.swap(streams);
  731. meshes[write].indices.swap(indices);
  732. write++;
  733. }
  734. meshes.resize(write);
  735. }
  736. bool hasColorData(const std::vector<Attr>& data)
  737. {
  738. const float threshold = 0.99f;
  739. for (size_t i = 0; i < data.size(); ++i)
  740. {
  741. const Attr& a = data[i];
  742. if (a.f[0] < threshold || a.f[1] < threshold || a.f[2] < threshold || a.f[3] < threshold)
  743. return true;
  744. }
  745. return false;
  746. }
  747. void filterStreams(Mesh& mesh)
  748. {
  749. size_t write = 0;
  750. for (size_t i = 0; i < mesh.streams.size(); ++i)
  751. {
  752. Stream& stream = mesh.streams[i];
  753. if (stream.type == cgltf_attribute_type_texcoord && (!mesh.material || !usesTextureSet(*mesh.material, stream.index)))
  754. continue;
  755. if (stream.type == cgltf_attribute_type_tangent && (!mesh.material || !mesh.material->normal_texture.texture))
  756. continue;
  757. if ((stream.type == cgltf_attribute_type_joints || stream.type == cgltf_attribute_type_weights) && !mesh.skin)
  758. continue;
  759. if (stream.type == cgltf_attribute_type_color && !hasColorData(stream.data))
  760. continue;
  761. // the following code is roughly equivalent to streams[write] = std::move(stream)
  762. std::vector<Attr> data;
  763. data.swap(stream.data);
  764. mesh.streams[write] = stream;
  765. mesh.streams[write].data.swap(data);
  766. write++;
  767. }
  768. mesh.streams.resize(write);
  769. }
  770. void reindexMesh(Mesh& mesh)
  771. {
  772. size_t total_vertices = mesh.streams[0].data.size();
  773. size_t total_indices = mesh.indices.size();
  774. std::vector<meshopt_Stream> streams;
  775. for (size_t i = 0; i < mesh.streams.size(); ++i)
  776. {
  777. if (mesh.streams[i].target)
  778. continue;
  779. assert(mesh.streams[i].data.size() == total_vertices);
  780. meshopt_Stream stream = {&mesh.streams[i].data[0], sizeof(Attr), sizeof(Attr)};
  781. streams.push_back(stream);
  782. }
  783. std::vector<unsigned int> remap(total_vertices);
  784. size_t unique_vertices = meshopt_generateVertexRemapMulti(&remap[0], &mesh.indices[0], total_indices, total_vertices, &streams[0], streams.size());
  785. assert(unique_vertices <= total_vertices);
  786. meshopt_remapIndexBuffer(&mesh.indices[0], &mesh.indices[0], total_indices, &remap[0]);
  787. for (size_t i = 0; i < mesh.streams.size(); ++i)
  788. {
  789. assert(mesh.streams[i].data.size() == total_vertices);
  790. meshopt_remapVertexBuffer(&mesh.streams[i].data[0], &mesh.streams[i].data[0], total_vertices, sizeof(Attr), &remap[0]);
  791. mesh.streams[i].data.resize(unique_vertices);
  792. }
  793. }
  794. void filterTriangles(Mesh& mesh)
  795. {
  796. unsigned int* indices = &mesh.indices[0];
  797. size_t total_indices = mesh.indices.size();
  798. size_t write = 0;
  799. for (size_t i = 0; i < total_indices; i += 3)
  800. {
  801. unsigned int a = indices[i + 0], b = indices[i + 1], c = indices[i + 2];
  802. if (a != b && a != c && b != c)
  803. {
  804. indices[write + 0] = a;
  805. indices[write + 1] = b;
  806. indices[write + 2] = c;
  807. write += 3;
  808. }
  809. }
  810. mesh.indices.resize(write);
  811. }
  812. Stream* getStream(Mesh& mesh, cgltf_attribute_type type, int index = 0)
  813. {
  814. for (size_t i = 0; i < mesh.streams.size(); ++i)
  815. if (mesh.streams[i].type == type && mesh.streams[i].index == index)
  816. return &mesh.streams[i];
  817. return 0;
  818. }
  819. void simplifyMesh(Mesh& mesh, float threshold, bool aggressive)
  820. {
  821. if (threshold >= 1)
  822. return;
  823. const Stream* positions = getStream(mesh, cgltf_attribute_type_position);
  824. if (!positions)
  825. return;
  826. size_t vertex_count = mesh.streams[0].data.size();
  827. size_t target_index_count = size_t(double(mesh.indices.size() / 3) * threshold) * 3;
  828. float target_error = 1e-2f;
  829. if (target_index_count < 1)
  830. return;
  831. std::vector<unsigned int> indices(mesh.indices.size());
  832. indices.resize(meshopt_simplify(&indices[0], &mesh.indices[0], mesh.indices.size(), positions->data[0].f, vertex_count, sizeof(Attr), target_index_count, target_error));
  833. mesh.indices.swap(indices);
  834. // Note: if the simplifier got stuck, we can try to reindex without normals/tangents and retry
  835. // For now we simply fall back to aggressive simplifier instead
  836. // if the mesh is complex enough and the precise simplifier got "stuck", we'll try to simplify using the sloppy simplifier which is guaranteed to reach the target count
  837. if (aggressive && target_index_count > 50 * 3 && mesh.indices.size() > target_index_count)
  838. {
  839. indices.resize(meshopt_simplifySloppy(&indices[0], &mesh.indices[0], mesh.indices.size(), positions->data[0].f, vertex_count, sizeof(Attr), target_index_count));
  840. mesh.indices.swap(indices);
  841. }
  842. }
  843. void optimizeMesh(Mesh& mesh)
  844. {
  845. size_t vertex_count = mesh.streams[0].data.size();
  846. meshopt_optimizeVertexCache(&mesh.indices[0], &mesh.indices[0], mesh.indices.size(), vertex_count);
  847. std::vector<unsigned int> remap(vertex_count);
  848. size_t unique_vertices = meshopt_optimizeVertexFetchRemap(&remap[0], &mesh.indices[0], mesh.indices.size(), vertex_count);
  849. assert(unique_vertices <= vertex_count);
  850. meshopt_remapIndexBuffer(&mesh.indices[0], &mesh.indices[0], mesh.indices.size(), &remap[0]);
  851. for (size_t i = 0; i < mesh.streams.size(); ++i)
  852. {
  853. assert(mesh.streams[i].data.size() == vertex_count);
  854. meshopt_remapVertexBuffer(&mesh.streams[i].data[0], &mesh.streams[i].data[0], vertex_count, sizeof(Attr), &remap[0]);
  855. mesh.streams[i].data.resize(unique_vertices);
  856. }
  857. }
  858. struct BoneInfluence
  859. {
  860. float i;
  861. float w;
  862. };
  863. struct BoneInfluenceIndexPredicate
  864. {
  865. bool operator()(const BoneInfluence& lhs, const BoneInfluence& rhs) const
  866. {
  867. return lhs.i < rhs.i;
  868. }
  869. };
  870. struct BoneInfluenceWeightPredicate
  871. {
  872. bool operator()(const BoneInfluence& lhs, const BoneInfluence& rhs) const
  873. {
  874. return lhs.w > rhs.w;
  875. }
  876. };
  877. void filterBones(Mesh& mesh)
  878. {
  879. const int kMaxGroups = 8;
  880. std::pair<Stream*, Stream*> groups[kMaxGroups];
  881. int group_count = 0;
  882. // gather all joint/weight groups; each group contains 4 bone influences
  883. for (int i = 0; i < kMaxGroups; ++i)
  884. {
  885. Stream* jg = getStream(mesh, cgltf_attribute_type_joints, int(i));
  886. Stream* wg = getStream(mesh, cgltf_attribute_type_weights, int(i));
  887. if (!jg || !wg)
  888. break;
  889. groups[group_count++] = std::make_pair(jg, wg);
  890. }
  891. if (group_count == 0)
  892. return;
  893. // weights below cutoff can't be represented in quantized 8-bit storage
  894. const float weight_cutoff = 0.5f / 255.f;
  895. size_t vertex_count = mesh.streams[0].data.size();
  896. BoneInfluence inf[kMaxGroups * 4] = {};
  897. for (size_t i = 0; i < vertex_count; ++i)
  898. {
  899. int count = 0;
  900. // gather all bone influences for this vertex
  901. for (int j = 0; j < group_count; ++j)
  902. {
  903. const Attr& ja = groups[j].first->data[i];
  904. const Attr& wa = groups[j].second->data[i];
  905. for (int k = 0; k < 4; ++k)
  906. if (wa.f[k] > weight_cutoff)
  907. {
  908. inf[count].i = ja.f[k];
  909. inf[count].w = wa.f[k];
  910. count++;
  911. }
  912. }
  913. // pick top 4 influences - could use partial_sort but it is slower on small sets
  914. std::sort(inf, inf + count, BoneInfluenceWeightPredicate());
  915. // now sort top 4 influences by bone index - this improves compression ratio
  916. std::sort(inf, inf + std::min(4, count), BoneInfluenceIndexPredicate());
  917. // copy the top 4 influences back into stream 0 - we will remove other streams at the end
  918. Attr& ja = groups[0].first->data[i];
  919. Attr& wa = groups[0].second->data[i];
  920. for (int k = 0; k < 4; ++k)
  921. {
  922. if (k < count)
  923. {
  924. ja.f[k] = inf[k].i;
  925. wa.f[k] = inf[k].w;
  926. }
  927. else
  928. {
  929. ja.f[k] = 0.f;
  930. wa.f[k] = 0.f;
  931. }
  932. }
  933. }
  934. // remove redundant weight/joint streams
  935. for (size_t i = 0; i < mesh.streams.size();)
  936. {
  937. Stream& s = mesh.streams[i];
  938. if ((s.type == cgltf_attribute_type_joints || s.type == cgltf_attribute_type_weights) && s.index > 0)
  939. mesh.streams.erase(mesh.streams.begin() + i);
  940. else
  941. ++i;
  942. }
  943. }
  944. void simplifyPointMesh(Mesh& mesh, float threshold)
  945. {
  946. if (threshold >= 1)
  947. return;
  948. const Stream* positions = getStream(mesh, cgltf_attribute_type_position);
  949. if (!positions)
  950. return;
  951. size_t vertex_count = mesh.streams[0].data.size();
  952. size_t target_vertex_count = size_t(double(vertex_count) * threshold);
  953. if (target_vertex_count < 1)
  954. return;
  955. std::vector<unsigned int> indices(target_vertex_count);
  956. indices.resize(meshopt_simplifyPoints(&indices[0], positions->data[0].f, vertex_count, sizeof(Attr), target_vertex_count));
  957. std::vector<Attr> scratch(indices.size());
  958. for (size_t i = 0; i < mesh.streams.size(); ++i)
  959. {
  960. std::vector<Attr>& data = mesh.streams[i].data;
  961. assert(data.size() == vertex_count);
  962. for (size_t j = 0; j < indices.size(); ++j)
  963. scratch[j] = data[indices[j]];
  964. data = scratch;
  965. }
  966. }
  967. void sortPointMesh(Mesh& mesh)
  968. {
  969. const Stream* positions = getStream(mesh, cgltf_attribute_type_position);
  970. if (!positions)
  971. return;
  972. size_t vertex_count = mesh.streams[0].data.size();
  973. std::vector<unsigned int> remap(vertex_count);
  974. meshopt_spatialSortRemap(&remap[0], positions->data[0].f, vertex_count, sizeof(Attr));
  975. for (size_t i = 0; i < mesh.streams.size(); ++i)
  976. {
  977. assert(mesh.streams[i].data.size() == vertex_count);
  978. meshopt_remapVertexBuffer(&mesh.streams[i].data[0], &mesh.streams[i].data[0], vertex_count, sizeof(Attr), &remap[0]);
  979. }
  980. }
  981. void processMesh(Mesh& mesh, const Settings& settings)
  982. {
  983. filterStreams(mesh);
  984. switch (mesh.type)
  985. {
  986. case cgltf_primitive_type_points:
  987. assert(mesh.indices.empty());
  988. simplifyPointMesh(mesh, settings.simplify_threshold);
  989. sortPointMesh(mesh);
  990. break;
  991. case cgltf_primitive_type_triangles:
  992. filterBones(mesh);
  993. reindexMesh(mesh);
  994. filterTriangles(mesh);
  995. simplifyMesh(mesh, settings.simplify_threshold, settings.simplify_aggressive);
  996. optimizeMesh(mesh);
  997. break;
  998. default:
  999. assert(!"Unknown primitive type");
  1000. }
  1001. }
  1002. bool getAttributeBounds(const std::vector<Mesh>& meshes, cgltf_attribute_type type, Attr& min, Attr& max)
  1003. {
  1004. min.f[0] = min.f[1] = min.f[2] = min.f[3] = +FLT_MAX;
  1005. max.f[0] = max.f[1] = max.f[2] = max.f[3] = -FLT_MAX;
  1006. Attr pad = {};
  1007. bool valid = false;
  1008. for (size_t i = 0; i < meshes.size(); ++i)
  1009. {
  1010. const Mesh& mesh = meshes[i];
  1011. for (size_t j = 0; j < mesh.streams.size(); ++j)
  1012. {
  1013. const Stream& s = mesh.streams[j];
  1014. if (s.type == type)
  1015. {
  1016. if (s.target == 0)
  1017. {
  1018. for (size_t k = 0; k < s.data.size(); ++k)
  1019. {
  1020. const Attr& a = s.data[k];
  1021. min.f[0] = std::min(min.f[0], a.f[0]);
  1022. min.f[1] = std::min(min.f[1], a.f[1]);
  1023. min.f[2] = std::min(min.f[2], a.f[2]);
  1024. min.f[3] = std::min(min.f[3], a.f[3]);
  1025. max.f[0] = std::max(max.f[0], a.f[0]);
  1026. max.f[1] = std::max(max.f[1], a.f[1]);
  1027. max.f[2] = std::max(max.f[2], a.f[2]);
  1028. max.f[3] = std::max(max.f[3], a.f[3]);
  1029. valid = true;
  1030. }
  1031. }
  1032. else
  1033. {
  1034. for (size_t k = 0; k < s.data.size(); ++k)
  1035. {
  1036. const Attr& a = s.data[k];
  1037. pad.f[0] = std::max(pad.f[0], fabsf(a.f[0]));
  1038. pad.f[1] = std::max(pad.f[1], fabsf(a.f[1]));
  1039. pad.f[2] = std::max(pad.f[2], fabsf(a.f[2]));
  1040. pad.f[3] = std::max(pad.f[3], fabsf(a.f[3]));
  1041. }
  1042. }
  1043. }
  1044. }
  1045. }
  1046. if (valid)
  1047. {
  1048. for (int k = 0; k < 4; ++k)
  1049. {
  1050. min.f[k] -= pad.f[k];
  1051. max.f[k] += pad.f[k];
  1052. }
  1053. }
  1054. return valid;
  1055. }
  1056. QuantizationParams prepareQuantization(const std::vector<Mesh>& meshes, const Settings& settings)
  1057. {
  1058. QuantizationParams result = {};
  1059. result.pos_bits = settings.pos_bits;
  1060. Attr pos_min, pos_max;
  1061. if (getAttributeBounds(meshes, cgltf_attribute_type_position, pos_min, pos_max))
  1062. {
  1063. result.pos_offset[0] = pos_min.f[0];
  1064. result.pos_offset[1] = pos_min.f[1];
  1065. result.pos_offset[2] = pos_min.f[2];
  1066. result.pos_scale = std::max(pos_max.f[0] - pos_min.f[0], std::max(pos_max.f[1] - pos_min.f[1], pos_max.f[2] - pos_min.f[2]));
  1067. }
  1068. result.uv_bits = settings.tex_bits;
  1069. Attr uv_min, uv_max;
  1070. if (getAttributeBounds(meshes, cgltf_attribute_type_texcoord, uv_min, uv_max))
  1071. {
  1072. result.uv_offset[0] = uv_min.f[0];
  1073. result.uv_offset[1] = uv_min.f[1];
  1074. result.uv_scale[0] = uv_max.f[0] - uv_min.f[0];
  1075. result.uv_scale[1] = uv_max.f[1] - uv_min.f[1];
  1076. }
  1077. return result;
  1078. }
  1079. void rescaleNormal(float& nx, float& ny, float& nz)
  1080. {
  1081. // scale the normal to make sure the largest component is +-1.0
  1082. // this reduces the entropy of the normal by ~1.5 bits without losing precision
  1083. // it's better to use octahedral encoding but that requires special shader support
  1084. float nm = std::max(fabsf(nx), std::max(fabsf(ny), fabsf(nz)));
  1085. float ns = nm == 0.f ? 0.f : 1 / nm;
  1086. nx *= ns;
  1087. ny *= ns;
  1088. nz *= ns;
  1089. }
  1090. void renormalizeWeights(uint8_t (&w)[4])
  1091. {
  1092. int sum = w[0] + w[1] + w[2] + w[3];
  1093. if (sum == 255)
  1094. return;
  1095. // we assume that the total error is limited to 0.5/component = 2
  1096. // this means that it's acceptable to adjust the max. component to compensate for the error
  1097. int max = 0;
  1098. for (int k = 1; k < 4; ++k)
  1099. if (w[k] > w[max])
  1100. max = k;
  1101. w[max] += uint8_t(255 - sum);
  1102. }
  1103. StreamFormat writeVertexStream(std::string& bin, const Stream& stream, const QuantizationParams& params, const Settings& settings, bool has_targets)
  1104. {
  1105. if (stream.type == cgltf_attribute_type_position)
  1106. {
  1107. if (stream.target == 0)
  1108. {
  1109. float pos_rscale = params.pos_scale == 0.f ? 0.f : 1.f / params.pos_scale;
  1110. for (size_t i = 0; i < stream.data.size(); ++i)
  1111. {
  1112. const Attr& a = stream.data[i];
  1113. uint16_t v[4] = {
  1114. uint16_t(meshopt_quantizeUnorm((a.f[0] - params.pos_offset[0]) * pos_rscale, params.pos_bits)),
  1115. uint16_t(meshopt_quantizeUnorm((a.f[1] - params.pos_offset[1]) * pos_rscale, params.pos_bits)),
  1116. uint16_t(meshopt_quantizeUnorm((a.f[2] - params.pos_offset[2]) * pos_rscale, params.pos_bits)),
  1117. 0};
  1118. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1119. }
  1120. StreamFormat format = {cgltf_type_vec3, cgltf_component_type_r_16u, false, 8};
  1121. return format;
  1122. }
  1123. else
  1124. {
  1125. float pos_rscale = params.pos_scale == 0.f ? 0.f : 1.f / params.pos_scale;
  1126. int maxv = 0;
  1127. for (size_t i = 0; i < stream.data.size(); ++i)
  1128. {
  1129. const Attr& a = stream.data[i];
  1130. maxv = std::max(maxv, meshopt_quantizeUnorm(fabsf(a.f[0]) * pos_rscale, params.pos_bits));
  1131. maxv = std::max(maxv, meshopt_quantizeUnorm(fabsf(a.f[1]) * pos_rscale, params.pos_bits));
  1132. maxv = std::max(maxv, meshopt_quantizeUnorm(fabsf(a.f[2]) * pos_rscale, params.pos_bits));
  1133. }
  1134. if (maxv <= 127)
  1135. {
  1136. for (size_t i = 0; i < stream.data.size(); ++i)
  1137. {
  1138. const Attr& a = stream.data[i];
  1139. int8_t v[4] = {
  1140. int8_t((a.f[0] >= 0.f ? 1 : -1) * meshopt_quantizeUnorm(fabsf(a.f[0]) * pos_rscale, params.pos_bits)),
  1141. int8_t((a.f[1] >= 0.f ? 1 : -1) * meshopt_quantizeUnorm(fabsf(a.f[1]) * pos_rscale, params.pos_bits)),
  1142. int8_t((a.f[2] >= 0.f ? 1 : -1) * meshopt_quantizeUnorm(fabsf(a.f[2]) * pos_rscale, params.pos_bits)),
  1143. 0};
  1144. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1145. }
  1146. StreamFormat format = {cgltf_type_vec3, cgltf_component_type_r_8, false, 4};
  1147. return format;
  1148. }
  1149. else
  1150. {
  1151. for (size_t i = 0; i < stream.data.size(); ++i)
  1152. {
  1153. const Attr& a = stream.data[i];
  1154. int16_t v[4] = {
  1155. int16_t((a.f[0] >= 0.f ? 1 : -1) * meshopt_quantizeUnorm(fabsf(a.f[0]) * pos_rscale, params.pos_bits)),
  1156. int16_t((a.f[1] >= 0.f ? 1 : -1) * meshopt_quantizeUnorm(fabsf(a.f[1]) * pos_rscale, params.pos_bits)),
  1157. int16_t((a.f[2] >= 0.f ? 1 : -1) * meshopt_quantizeUnorm(fabsf(a.f[2]) * pos_rscale, params.pos_bits)),
  1158. 0};
  1159. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1160. }
  1161. StreamFormat format = {cgltf_type_vec3, cgltf_component_type_r_16, false, 8};
  1162. return format;
  1163. }
  1164. }
  1165. }
  1166. else if (stream.type == cgltf_attribute_type_texcoord)
  1167. {
  1168. float uv_rscale[2] = {
  1169. params.uv_scale[0] == 0.f ? 0.f : 1.f / params.uv_scale[0],
  1170. params.uv_scale[1] == 0.f ? 0.f : 1.f / params.uv_scale[1],
  1171. };
  1172. for (size_t i = 0; i < stream.data.size(); ++i)
  1173. {
  1174. const Attr& a = stream.data[i];
  1175. uint16_t v[2] = {
  1176. uint16_t(meshopt_quantizeUnorm((a.f[0] - params.uv_offset[0]) * uv_rscale[0], params.uv_bits)),
  1177. uint16_t(meshopt_quantizeUnorm((a.f[1] - params.uv_offset[1]) * uv_rscale[1], params.uv_bits)),
  1178. };
  1179. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1180. }
  1181. StreamFormat format = {cgltf_type_vec2, cgltf_component_type_r_16u, false, 4};
  1182. return format;
  1183. }
  1184. else if (stream.type == cgltf_attribute_type_normal)
  1185. {
  1186. bool unnormalized = settings.nrm_unnormalized && !has_targets;
  1187. int bits = unnormalized ? settings.nrm_bits : (settings.nrm_bits > 8 ? 16 : 8);
  1188. for (size_t i = 0; i < stream.data.size(); ++i)
  1189. {
  1190. const Attr& a = stream.data[i];
  1191. float nx = a.f[0], ny = a.f[1], nz = a.f[2];
  1192. if (unnormalized)
  1193. rescaleNormal(nx, ny, nz);
  1194. if (bits > 8)
  1195. {
  1196. int16_t v[4] = {
  1197. int16_t(meshopt_quantizeSnorm(nx, bits)),
  1198. int16_t(meshopt_quantizeSnorm(ny, bits)),
  1199. int16_t(meshopt_quantizeSnorm(nz, bits)),
  1200. 0};
  1201. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1202. }
  1203. else
  1204. {
  1205. int8_t v[4] = {
  1206. int8_t(meshopt_quantizeSnorm(nx, bits)),
  1207. int8_t(meshopt_quantizeSnorm(ny, bits)),
  1208. int8_t(meshopt_quantizeSnorm(nz, bits)),
  1209. 0};
  1210. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1211. }
  1212. }
  1213. if (bits > 8)
  1214. {
  1215. StreamFormat format = {cgltf_type_vec3, cgltf_component_type_r_16, true, 8};
  1216. return format;
  1217. }
  1218. else
  1219. {
  1220. StreamFormat format = {cgltf_type_vec3, cgltf_component_type_r_8, true, 4};
  1221. return format;
  1222. }
  1223. }
  1224. else if (stream.type == cgltf_attribute_type_tangent)
  1225. {
  1226. bool unnormalized = settings.nrm_unnormalized && !has_targets;
  1227. int bits = unnormalized ? settings.nrm_bits : (settings.nrm_bits > 8 ? 16 : 8);
  1228. for (size_t i = 0; i < stream.data.size(); ++i)
  1229. {
  1230. const Attr& a = stream.data[i];
  1231. float nx = a.f[0], ny = a.f[1], nz = a.f[2], nw = a.f[3];
  1232. if (unnormalized)
  1233. rescaleNormal(nx, ny, nz);
  1234. if (bits > 8)
  1235. {
  1236. int16_t v[4] = {
  1237. int16_t(meshopt_quantizeSnorm(nx, bits)),
  1238. int16_t(meshopt_quantizeSnorm(ny, bits)),
  1239. int16_t(meshopt_quantizeSnorm(nz, bits)),
  1240. int16_t(meshopt_quantizeSnorm(nw, 8))};
  1241. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1242. }
  1243. else
  1244. {
  1245. int8_t v[4] = {
  1246. int8_t(meshopt_quantizeSnorm(nx, bits)),
  1247. int8_t(meshopt_quantizeSnorm(ny, bits)),
  1248. int8_t(meshopt_quantizeSnorm(nz, bits)),
  1249. int8_t(meshopt_quantizeSnorm(nw, 8))};
  1250. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1251. }
  1252. }
  1253. cgltf_type type = (stream.target == 0) ? cgltf_type_vec4 : cgltf_type_vec3;
  1254. if (bits > 8)
  1255. {
  1256. StreamFormat format = {type, cgltf_component_type_r_16, true, 8};
  1257. return format;
  1258. }
  1259. else
  1260. {
  1261. StreamFormat format = {type, cgltf_component_type_r_8, true, 4};
  1262. return format;
  1263. }
  1264. }
  1265. else if (stream.type == cgltf_attribute_type_color)
  1266. {
  1267. for (size_t i = 0; i < stream.data.size(); ++i)
  1268. {
  1269. const Attr& a = stream.data[i];
  1270. uint8_t v[4] = {
  1271. uint8_t(meshopt_quantizeUnorm(a.f[0], 8)),
  1272. uint8_t(meshopt_quantizeUnorm(a.f[1], 8)),
  1273. uint8_t(meshopt_quantizeUnorm(a.f[2], 8)),
  1274. uint8_t(meshopt_quantizeUnorm(a.f[3], 8))};
  1275. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1276. }
  1277. StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_8u, true, 4};
  1278. return format;
  1279. }
  1280. else if (stream.type == cgltf_attribute_type_weights)
  1281. {
  1282. for (size_t i = 0; i < stream.data.size(); ++i)
  1283. {
  1284. const Attr& a = stream.data[i];
  1285. float ws = a.f[0] + a.f[1] + a.f[2] + a.f[3];
  1286. float wsi = (ws == 0.f) ? 0.f : 1.f / ws;
  1287. uint8_t v[4] = {
  1288. uint8_t(meshopt_quantizeUnorm(a.f[0] * wsi, 8)),
  1289. uint8_t(meshopt_quantizeUnorm(a.f[1] * wsi, 8)),
  1290. uint8_t(meshopt_quantizeUnorm(a.f[2] * wsi, 8)),
  1291. uint8_t(meshopt_quantizeUnorm(a.f[3] * wsi, 8))};
  1292. if (wsi != 0.f)
  1293. renormalizeWeights(v);
  1294. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1295. }
  1296. StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_8u, true, 4};
  1297. return format;
  1298. }
  1299. else if (stream.type == cgltf_attribute_type_joints)
  1300. {
  1301. unsigned int maxj = 0;
  1302. for (size_t i = 0; i < stream.data.size(); ++i)
  1303. maxj = std::max(maxj, unsigned(stream.data[i].f[0]));
  1304. assert(maxj <= 65535);
  1305. if (maxj <= 255)
  1306. {
  1307. for (size_t i = 0; i < stream.data.size(); ++i)
  1308. {
  1309. const Attr& a = stream.data[i];
  1310. uint8_t v[4] = {
  1311. uint8_t(a.f[0]),
  1312. uint8_t(a.f[1]),
  1313. uint8_t(a.f[2]),
  1314. uint8_t(a.f[3])};
  1315. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1316. }
  1317. StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_8u, false, 4};
  1318. return format;
  1319. }
  1320. else
  1321. {
  1322. for (size_t i = 0; i < stream.data.size(); ++i)
  1323. {
  1324. const Attr& a = stream.data[i];
  1325. uint16_t v[4] = {
  1326. uint16_t(a.f[0]),
  1327. uint16_t(a.f[1]),
  1328. uint16_t(a.f[2]),
  1329. uint16_t(a.f[3])};
  1330. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1331. }
  1332. StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_16u, false, 8};
  1333. return format;
  1334. }
  1335. }
  1336. else
  1337. {
  1338. for (size_t i = 0; i < stream.data.size(); ++i)
  1339. {
  1340. const Attr& a = stream.data[i];
  1341. float v[4] = {a.f[0], a.f[1], a.f[2], a.f[3]};
  1342. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1343. }
  1344. StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_32f, false, 16};
  1345. return format;
  1346. }
  1347. }
  1348. void getPositionBounds(int min[3], int max[3], const Stream& stream, const QuantizationParams& params)
  1349. {
  1350. assert(stream.type == cgltf_attribute_type_position);
  1351. assert(stream.data.size() > 0);
  1352. min[0] = min[1] = min[2] = INT_MAX;
  1353. max[0] = max[1] = max[2] = INT_MIN;
  1354. float pos_rscale = params.pos_scale == 0.f ? 0.f : 1.f / params.pos_scale;
  1355. if (stream.target == 0)
  1356. {
  1357. for (size_t i = 0; i < stream.data.size(); ++i)
  1358. {
  1359. const Attr& a = stream.data[i];
  1360. for (int k = 0; k < 3; ++k)
  1361. {
  1362. int v = meshopt_quantizeUnorm((a.f[k] - params.pos_offset[k]) * pos_rscale, params.pos_bits);
  1363. min[k] = std::min(min[k], v);
  1364. max[k] = std::max(max[k], v);
  1365. }
  1366. }
  1367. }
  1368. else
  1369. {
  1370. for (size_t i = 0; i < stream.data.size(); ++i)
  1371. {
  1372. const Attr& a = stream.data[i];
  1373. for (int k = 0; k < 3; ++k)
  1374. {
  1375. int v = (a.f[k] >= 0.f ? 1 : -1) * meshopt_quantizeUnorm(fabsf(a.f[k]) * pos_rscale, params.pos_bits);
  1376. min[k] = std::min(min[k], v);
  1377. max[k] = std::max(max[k], v);
  1378. }
  1379. }
  1380. }
  1381. }
  1382. StreamFormat writeIndexStream(std::string& bin, const std::vector<unsigned int>& stream)
  1383. {
  1384. unsigned int maxi = 0;
  1385. for (size_t i = 0; i < stream.size(); ++i)
  1386. maxi = std::max(maxi, stream[i]);
  1387. // save 16-bit indices if we can; note that we can't use restart index (65535)
  1388. if (maxi < 65535)
  1389. {
  1390. for (size_t i = 0; i < stream.size(); ++i)
  1391. {
  1392. uint16_t v[1] = {uint16_t(stream[i])};
  1393. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1394. }
  1395. StreamFormat format = {cgltf_type_scalar, cgltf_component_type_r_16u, false, 2};
  1396. return format;
  1397. }
  1398. else
  1399. {
  1400. for (size_t i = 0; i < stream.size(); ++i)
  1401. {
  1402. uint32_t v[1] = {stream[i]};
  1403. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1404. }
  1405. StreamFormat format = {cgltf_type_scalar, cgltf_component_type_r_32u, false, 4};
  1406. return format;
  1407. }
  1408. }
  1409. StreamFormat writeTimeStream(std::string& bin, const std::vector<float>& data)
  1410. {
  1411. for (size_t i = 0; i < data.size(); ++i)
  1412. {
  1413. float v[1] = {data[i]};
  1414. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1415. }
  1416. StreamFormat format = {cgltf_type_scalar, cgltf_component_type_r_32f, false, 4};
  1417. return format;
  1418. }
  1419. StreamFormat writeKeyframeStream(std::string& bin, cgltf_animation_path_type type, const std::vector<Attr>& data)
  1420. {
  1421. if (type == cgltf_animation_path_type_rotation)
  1422. {
  1423. for (size_t i = 0; i < data.size(); ++i)
  1424. {
  1425. const Attr& a = data[i];
  1426. int16_t v[4] = {
  1427. int16_t(meshopt_quantizeSnorm(a.f[0], 16)),
  1428. int16_t(meshopt_quantizeSnorm(a.f[1], 16)),
  1429. int16_t(meshopt_quantizeSnorm(a.f[2], 16)),
  1430. int16_t(meshopt_quantizeSnorm(a.f[3], 16)),
  1431. };
  1432. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1433. }
  1434. StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_16, true, 8};
  1435. return format;
  1436. }
  1437. else if (type == cgltf_animation_path_type_weights)
  1438. {
  1439. for (size_t i = 0; i < data.size(); ++i)
  1440. {
  1441. const Attr& a = data[i];
  1442. uint8_t v[1] = {uint8_t(meshopt_quantizeUnorm(a.f[0], 8))};
  1443. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1444. }
  1445. StreamFormat format = {cgltf_type_scalar, cgltf_component_type_r_8u, true, 1};
  1446. return format;
  1447. }
  1448. else if (type == cgltf_animation_path_type_translation || type == cgltf_animation_path_type_scale)
  1449. {
  1450. int bits = 15;
  1451. for (size_t i = 0; i < data.size(); ++i)
  1452. {
  1453. const Attr& a = data[i];
  1454. float v[3] = {
  1455. meshopt_quantizeFloat(a.f[0], bits),
  1456. meshopt_quantizeFloat(a.f[1], bits),
  1457. meshopt_quantizeFloat(a.f[2], bits)};
  1458. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1459. }
  1460. StreamFormat format = {cgltf_type_vec3, cgltf_component_type_r_32f, false, 12};
  1461. return format;
  1462. }
  1463. else
  1464. {
  1465. for (size_t i = 0; i < data.size(); ++i)
  1466. {
  1467. const Attr& a = data[i];
  1468. float v[4] = {a.f[0], a.f[1], a.f[2], a.f[3]};
  1469. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1470. }
  1471. StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_32f, false, 16};
  1472. return format;
  1473. }
  1474. }
  1475. void compressVertexStream(std::string& bin, const std::string& data, size_t count, size_t stride)
  1476. {
  1477. assert(data.size() == count * stride);
  1478. std::vector<unsigned char> compressed(meshopt_encodeVertexBufferBound(count, stride));
  1479. size_t size = meshopt_encodeVertexBuffer(&compressed[0], compressed.size(), data.c_str(), count, stride);
  1480. bin.append(reinterpret_cast<const char*>(&compressed[0]), size);
  1481. }
  1482. void compressIndexStream(std::string& bin, const std::string& data, size_t count, size_t stride)
  1483. {
  1484. assert(stride == 2 || stride == 4);
  1485. assert(data.size() == count * stride);
  1486. std::vector<unsigned char> compressed(meshopt_encodeIndexBufferBound(count, count * 3));
  1487. size_t size = 0;
  1488. if (stride == 2)
  1489. size = meshopt_encodeIndexBuffer(&compressed[0], compressed.size(), reinterpret_cast<const uint16_t*>(data.c_str()), count);
  1490. else
  1491. size = meshopt_encodeIndexBuffer(&compressed[0], compressed.size(), reinterpret_cast<const uint32_t*>(data.c_str()), count);
  1492. bin.append(reinterpret_cast<const char*>(&compressed[0]), size);
  1493. }
  1494. void comma(std::string& s)
  1495. {
  1496. char ch = s.empty() ? 0 : s[s.size() - 1];
  1497. if (ch != 0 && ch != '[' && ch != '{')
  1498. s += ",";
  1499. }
  1500. void append(std::string& s, size_t v)
  1501. {
  1502. char buf[32];
  1503. sprintf(buf, "%zu", v);
  1504. s += buf;
  1505. }
  1506. void append(std::string& s, float v)
  1507. {
  1508. char buf[512];
  1509. sprintf(buf, "%.9g", v);
  1510. s += buf;
  1511. }
  1512. void append(std::string& s, const char* v)
  1513. {
  1514. s += v;
  1515. }
  1516. void append(std::string& s, const std::string& v)
  1517. {
  1518. s += v;
  1519. }
  1520. const char* componentType(cgltf_component_type type)
  1521. {
  1522. switch (type)
  1523. {
  1524. case cgltf_component_type_r_8:
  1525. return "5120";
  1526. case cgltf_component_type_r_8u:
  1527. return "5121";
  1528. case cgltf_component_type_r_16:
  1529. return "5122";
  1530. case cgltf_component_type_r_16u:
  1531. return "5123";
  1532. case cgltf_component_type_r_32u:
  1533. return "5125";
  1534. case cgltf_component_type_r_32f:
  1535. return "5126";
  1536. default:
  1537. return "0";
  1538. }
  1539. }
  1540. const char* shapeType(cgltf_type type)
  1541. {
  1542. switch (type)
  1543. {
  1544. case cgltf_type_scalar:
  1545. return "SCALAR";
  1546. case cgltf_type_vec2:
  1547. return "VEC2";
  1548. case cgltf_type_vec3:
  1549. return "VEC3";
  1550. case cgltf_type_vec4:
  1551. return "VEC4";
  1552. case cgltf_type_mat2:
  1553. return "MAT2";
  1554. case cgltf_type_mat3:
  1555. return "MAT3";
  1556. case cgltf_type_mat4:
  1557. return "MAT4";
  1558. default:
  1559. return "";
  1560. }
  1561. }
  1562. const char* attributeType(cgltf_attribute_type type)
  1563. {
  1564. switch (type)
  1565. {
  1566. case cgltf_attribute_type_position:
  1567. return "POSITION";
  1568. case cgltf_attribute_type_normal:
  1569. return "NORMAL";
  1570. case cgltf_attribute_type_tangent:
  1571. return "TANGENT";
  1572. case cgltf_attribute_type_texcoord:
  1573. return "TEXCOORD";
  1574. case cgltf_attribute_type_color:
  1575. return "COLOR";
  1576. case cgltf_attribute_type_joints:
  1577. return "JOINTS";
  1578. case cgltf_attribute_type_weights:
  1579. return "WEIGHTS";
  1580. default:
  1581. return "ATTRIBUTE";
  1582. }
  1583. }
  1584. const char* animationPath(cgltf_animation_path_type type)
  1585. {
  1586. switch (type)
  1587. {
  1588. case cgltf_animation_path_type_translation:
  1589. return "translation";
  1590. case cgltf_animation_path_type_rotation:
  1591. return "rotation";
  1592. case cgltf_animation_path_type_scale:
  1593. return "scale";
  1594. case cgltf_animation_path_type_weights:
  1595. return "weights";
  1596. default:
  1597. return "";
  1598. }
  1599. }
  1600. const char* lightType(cgltf_light_type type)
  1601. {
  1602. switch (type)
  1603. {
  1604. case cgltf_light_type_directional:
  1605. return "directional";
  1606. case cgltf_light_type_point:
  1607. return "point";
  1608. case cgltf_light_type_spot:
  1609. return "spot";
  1610. default:
  1611. return "";
  1612. }
  1613. }
  1614. void writeTextureInfo(std::string& json, const cgltf_data* data, const cgltf_texture_view& view, const QuantizationParams& qp)
  1615. {
  1616. assert(view.texture);
  1617. cgltf_texture_transform transform = {};
  1618. if (view.has_transform)
  1619. {
  1620. transform = view.transform;
  1621. }
  1622. else
  1623. {
  1624. transform.scale[0] = transform.scale[1] = 1.f;
  1625. }
  1626. transform.offset[0] += qp.uv_offset[0];
  1627. transform.offset[1] += qp.uv_offset[1];
  1628. transform.scale[0] *= qp.uv_scale[0] / float((1 << qp.uv_bits) - 1);
  1629. transform.scale[1] *= qp.uv_scale[1] / float((1 << qp.uv_bits) - 1);
  1630. append(json, "{\"index\":");
  1631. append(json, size_t(view.texture - data->textures));
  1632. append(json, ",\"texCoord\":");
  1633. append(json, size_t(view.texcoord));
  1634. append(json, ",\"extensions\":{\"KHR_texture_transform\":{");
  1635. append(json, "\"offset\":[");
  1636. append(json, transform.offset[0]);
  1637. append(json, ",");
  1638. append(json, transform.offset[1]);
  1639. append(json, "],\"scale\":[");
  1640. append(json, transform.scale[0]);
  1641. append(json, ",");
  1642. append(json, transform.scale[1]);
  1643. append(json, "]");
  1644. if (transform.rotation != 0.f)
  1645. {
  1646. append(json, ",\"rotation\":");
  1647. append(json, transform.rotation);
  1648. }
  1649. append(json, "}}}");
  1650. }
  1651. void writeMaterialInfo(std::string& json, const cgltf_data* data, const cgltf_material& material, const QuantizationParams& qp)
  1652. {
  1653. static const float white[4] = {1, 1, 1, 1};
  1654. static const float black[4] = {0, 0, 0, 0};
  1655. if (material.name && *material.name)
  1656. {
  1657. comma(json);
  1658. append(json, "\"name\":\"");
  1659. append(json, material.name);
  1660. append(json, "\"");
  1661. }
  1662. if (material.has_pbr_metallic_roughness)
  1663. {
  1664. const cgltf_pbr_metallic_roughness& pbr = material.pbr_metallic_roughness;
  1665. comma(json);
  1666. append(json, "\"pbrMetallicRoughness\":{");
  1667. if (memcmp(pbr.base_color_factor, white, 16) != 0)
  1668. {
  1669. comma(json);
  1670. append(json, "\"baseColorFactor\":[");
  1671. append(json, pbr.base_color_factor[0]);
  1672. append(json, ",");
  1673. append(json, pbr.base_color_factor[1]);
  1674. append(json, ",");
  1675. append(json, pbr.base_color_factor[2]);
  1676. append(json, ",");
  1677. append(json, pbr.base_color_factor[3]);
  1678. append(json, "]");
  1679. }
  1680. if (pbr.base_color_texture.texture)
  1681. {
  1682. comma(json);
  1683. append(json, "\"baseColorTexture\":");
  1684. writeTextureInfo(json, data, pbr.base_color_texture, qp);
  1685. }
  1686. if (pbr.metallic_factor != 1)
  1687. {
  1688. comma(json);
  1689. append(json, "\"metallicFactor\":");
  1690. append(json, pbr.metallic_factor);
  1691. }
  1692. if (pbr.roughness_factor != 1)
  1693. {
  1694. comma(json);
  1695. append(json, "\"roughnessFactor\":");
  1696. append(json, pbr.roughness_factor);
  1697. }
  1698. if (pbr.metallic_roughness_texture.texture)
  1699. {
  1700. comma(json);
  1701. append(json, "\"metallicRoughnessTexture\":");
  1702. writeTextureInfo(json, data, pbr.metallic_roughness_texture, qp);
  1703. }
  1704. append(json, "}");
  1705. }
  1706. if (material.normal_texture.texture)
  1707. {
  1708. comma(json);
  1709. append(json, "\"normalTexture\":");
  1710. writeTextureInfo(json, data, material.normal_texture, qp);
  1711. }
  1712. if (material.occlusion_texture.texture)
  1713. {
  1714. comma(json);
  1715. append(json, "\"occlusionTexture\":");
  1716. writeTextureInfo(json, data, material.occlusion_texture, qp);
  1717. }
  1718. if (material.emissive_texture.texture)
  1719. {
  1720. comma(json);
  1721. append(json, "\"emissiveTexture\":");
  1722. writeTextureInfo(json, data, material.emissive_texture, qp);
  1723. }
  1724. if (memcmp(material.emissive_factor, black, 12) != 0)
  1725. {
  1726. comma(json);
  1727. append(json, "\"emissiveFactor\":[");
  1728. append(json, material.emissive_factor[0]);
  1729. append(json, ",");
  1730. append(json, material.emissive_factor[1]);
  1731. append(json, ",");
  1732. append(json, material.emissive_factor[2]);
  1733. append(json, "]");
  1734. }
  1735. if (material.alpha_mode != cgltf_alpha_mode_opaque)
  1736. {
  1737. comma(json);
  1738. append(json, "\"alphaMode\":");
  1739. append(json, (material.alpha_mode == cgltf_alpha_mode_blend) ? "\"BLEND\"" : "\"MASK\"");
  1740. }
  1741. if (material.alpha_cutoff != 0.5f)
  1742. {
  1743. comma(json);
  1744. append(json, "\"alphaCutoff\":");
  1745. append(json, material.alpha_cutoff);
  1746. }
  1747. if (material.double_sided)
  1748. {
  1749. comma(json);
  1750. append(json, "\"doubleSided\":true");
  1751. }
  1752. if (material.has_pbr_specular_glossiness || material.unlit)
  1753. {
  1754. comma(json);
  1755. append(json, "\"extensions\":{");
  1756. if (material.has_pbr_specular_glossiness)
  1757. {
  1758. const cgltf_pbr_specular_glossiness& pbr = material.pbr_specular_glossiness;
  1759. comma(json);
  1760. append(json, "\"KHR_materials_pbrSpecularGlossiness\":{");
  1761. if (pbr.diffuse_texture.texture)
  1762. {
  1763. comma(json);
  1764. append(json, "\"diffuseTexture\":");
  1765. writeTextureInfo(json, data, pbr.diffuse_texture, qp);
  1766. }
  1767. if (pbr.specular_glossiness_texture.texture)
  1768. {
  1769. comma(json);
  1770. append(json, "\"specularGlossinessTexture\":");
  1771. writeTextureInfo(json, data, pbr.specular_glossiness_texture, qp);
  1772. }
  1773. if (memcmp(pbr.diffuse_factor, white, 16) != 0)
  1774. {
  1775. comma(json);
  1776. append(json, "\"diffuseFactor\":[");
  1777. append(json, pbr.diffuse_factor[0]);
  1778. append(json, ",");
  1779. append(json, pbr.diffuse_factor[1]);
  1780. append(json, ",");
  1781. append(json, pbr.diffuse_factor[2]);
  1782. append(json, ",");
  1783. append(json, pbr.diffuse_factor[3]);
  1784. append(json, "]");
  1785. }
  1786. if (memcmp(pbr.specular_factor, white, 12) != 0)
  1787. {
  1788. comma(json);
  1789. append(json, "\"specularFactor\":[");
  1790. append(json, pbr.specular_factor[0]);
  1791. append(json, ",");
  1792. append(json, pbr.specular_factor[1]);
  1793. append(json, ",");
  1794. append(json, pbr.specular_factor[2]);
  1795. append(json, "]");
  1796. }
  1797. if (pbr.glossiness_factor != 1)
  1798. {
  1799. comma(json);
  1800. append(json, "\"glossinessFactor\":");
  1801. append(json, pbr.glossiness_factor);
  1802. }
  1803. append(json, "}");
  1804. }
  1805. if (material.unlit)
  1806. {
  1807. comma(json);
  1808. append(json, "\"KHR_materials_unlit\":{}");
  1809. }
  1810. append(json, "}");
  1811. }
  1812. }
  1813. size_t getBufferView(std::vector<BufferView>& views, BufferView::Kind kind, int variant, size_t stride, bool compressed)
  1814. {
  1815. if (variant >= 0)
  1816. {
  1817. for (size_t i = 0; i < views.size(); ++i)
  1818. if (views[i].kind == kind && views[i].variant == variant && views[i].stride == stride && views[i].compressed == compressed)
  1819. return i;
  1820. }
  1821. BufferView view = {kind, variant, stride, compressed};
  1822. views.push_back(view);
  1823. return views.size() - 1;
  1824. }
  1825. void writeBufferView(std::string& json, BufferView::Kind kind, size_t count, size_t stride, size_t bin_offset, size_t bin_size, int compression, size_t compressed_offset, size_t compressed_size)
  1826. {
  1827. assert(bin_size == count * stride);
  1828. // when compression is enabled, we store uncompressed data in buffer 1 and compressed data in buffer 0
  1829. // when compression is disabled, we store uncompressed data in buffer 0
  1830. size_t buffer = compression >= 0 ? 1 : 0;
  1831. append(json, "{\"buffer\":");
  1832. append(json, buffer);
  1833. append(json, ",\"byteOffset\":");
  1834. append(json, bin_offset);
  1835. append(json, ",\"byteLength\":");
  1836. append(json, bin_size);
  1837. if (kind == BufferView::Kind_Vertex)
  1838. {
  1839. append(json, ",\"byteStride\":");
  1840. append(json, stride);
  1841. }
  1842. if (kind == BufferView::Kind_Vertex || kind == BufferView::Kind_Index)
  1843. {
  1844. append(json, ",\"target\":");
  1845. append(json, (kind == BufferView::Kind_Vertex) ? "34962" : "34963");
  1846. }
  1847. if (compression >= 0)
  1848. {
  1849. append(json, ",\"extensions\":{");
  1850. append(json, "\"MESHOPT_compression\":{");
  1851. append(json, "\"buffer\":0");
  1852. append(json, ",\"byteOffset\":");
  1853. append(json, size_t(compressed_offset));
  1854. append(json, ",\"byteLength\":");
  1855. append(json, size_t(compressed_size));
  1856. append(json, ",\"byteStride\":");
  1857. append(json, stride);
  1858. append(json, ",\"mode\":");
  1859. append(json, size_t(compression));
  1860. append(json, ",\"count\":");
  1861. append(json, count);
  1862. append(json, "}}");
  1863. }
  1864. append(json, "}");
  1865. }
  1866. void writeAccessor(std::string& json, size_t view, size_t offset, cgltf_type type, cgltf_component_type component_type, bool normalized, size_t count, const float* min = 0, const float* max = 0, size_t numminmax = 0)
  1867. {
  1868. append(json, "{\"bufferView\":");
  1869. append(json, view);
  1870. append(json, ",\"byteOffset\":");
  1871. append(json, offset);
  1872. append(json, ",\"componentType\":");
  1873. append(json, componentType(component_type));
  1874. append(json, ",\"count\":");
  1875. append(json, count);
  1876. append(json, ",\"type\":\"");
  1877. append(json, shapeType(type));
  1878. append(json, "\"");
  1879. if (normalized)
  1880. {
  1881. append(json, ",\"normalized\":true");
  1882. }
  1883. if (min && max)
  1884. {
  1885. assert(numminmax);
  1886. append(json, ",\"min\":[");
  1887. for (size_t k = 0; k < numminmax; ++k)
  1888. {
  1889. comma(json);
  1890. append(json, min[k]);
  1891. }
  1892. append(json, "],\"max\":[");
  1893. for (size_t k = 0; k < numminmax; ++k)
  1894. {
  1895. comma(json);
  1896. append(json, max[k]);
  1897. }
  1898. append(json, "]");
  1899. }
  1900. append(json, "}");
  1901. }
  1902. float getDelta(const Attr& l, const Attr& r, cgltf_animation_path_type type)
  1903. {
  1904. switch (type)
  1905. {
  1906. case cgltf_animation_path_type_translation:
  1907. return std::max(std::max(fabsf(l.f[0] - r.f[0]), fabsf(l.f[1] - r.f[1])), fabsf(l.f[2] - r.f[2]));
  1908. case cgltf_animation_path_type_rotation:
  1909. return acosf(std::min(1.f, fabsf(l.f[0] * r.f[0] + l.f[1] * r.f[1] + l.f[2] * r.f[2] + l.f[3] * r.f[3])));
  1910. case cgltf_animation_path_type_scale:
  1911. return std::max(std::max(fabsf(l.f[0] / r.f[0] - 1), fabsf(l.f[1] / r.f[1] - 1)), fabsf(l.f[2] / r.f[2] - 1));
  1912. case cgltf_animation_path_type_weights:
  1913. return fabsf(l.f[0] - r.f[0]);
  1914. default:
  1915. assert(!"Uknown animation path");
  1916. return 0;
  1917. }
  1918. }
  1919. float getDeltaTolerance(cgltf_animation_path_type type)
  1920. {
  1921. switch (type)
  1922. {
  1923. case cgltf_animation_path_type_translation:
  1924. return 0.001f; // linear
  1925. case cgltf_animation_path_type_rotation:
  1926. return 0.001f; // radians
  1927. case cgltf_animation_path_type_scale:
  1928. return 0.001f; // ratio
  1929. case cgltf_animation_path_type_weights:
  1930. return 0.001f; // linear
  1931. default:
  1932. assert(!"Uknown animation path");
  1933. return 0;
  1934. }
  1935. }
  1936. Attr interpolateLinear(const Attr& l, const Attr& r, float t, cgltf_animation_path_type type)
  1937. {
  1938. if (type == cgltf_animation_path_type_rotation)
  1939. {
  1940. // Approximating slerp, https://zeux.io/2015/07/23/approximating-slerp/
  1941. // We also handle quaternion double-cover
  1942. float ca = l.f[0] * r.f[0] + l.f[1] * r.f[1] + l.f[2] * r.f[2] + l.f[3] * r.f[3];
  1943. float d = fabsf(ca);
  1944. float A = 1.0904f + d * (-3.2452f + d * (3.55645f - d * 1.43519f));
  1945. float B = 0.848013f + d * (-1.06021f + d * 0.215638f);
  1946. float k = A * (t - 0.5f) * (t - 0.5f) + B;
  1947. float ot = t + t * (t - 0.5f) * (t - 1) * k;
  1948. float t0 = 1 - ot;
  1949. float t1 = ca > 0 ? ot : -ot;
  1950. Attr lerp = {{
  1951. l.f[0] * t0 + r.f[0] * t1,
  1952. l.f[1] * t0 + r.f[1] * t1,
  1953. l.f[2] * t0 + r.f[2] * t1,
  1954. l.f[3] * t0 + r.f[3] * t1,
  1955. }};
  1956. float len = sqrtf(lerp.f[0] * lerp.f[0] + lerp.f[1] * lerp.f[1] + lerp.f[2] * lerp.f[2] + lerp.f[3] * lerp.f[3]);
  1957. if (len > 0.f)
  1958. {
  1959. lerp.f[0] /= len;
  1960. lerp.f[1] /= len;
  1961. lerp.f[2] /= len;
  1962. lerp.f[3] /= len;
  1963. }
  1964. return lerp;
  1965. }
  1966. else
  1967. {
  1968. Attr lerp = {{
  1969. l.f[0] * (1 - t) + r.f[0] * t,
  1970. l.f[1] * (1 - t) + r.f[1] * t,
  1971. l.f[2] * (1 - t) + r.f[2] * t,
  1972. l.f[3] * (1 - t) + r.f[3] * t,
  1973. }};
  1974. return lerp;
  1975. }
  1976. }
  1977. Attr interpolateHermite(const Attr& v0, const Attr& t0, const Attr& v1, const Attr& t1, float t, float dt, cgltf_animation_path_type type)
  1978. {
  1979. float s0 = 1 + t * t * (2 * t - 3);
  1980. float s1 = t + t * t * (t - 2);
  1981. float s2 = 1 - s0;
  1982. float s3 = t * t * (t - 1);
  1983. float ts1 = dt * s1;
  1984. float ts3 = dt * s3;
  1985. Attr lerp = {{
  1986. s0 * v0.f[0] + ts1 * t0.f[0] + s2 * v1.f[0] + ts3 * t1.f[0],
  1987. s0 * v0.f[1] + ts1 * t0.f[1] + s2 * v1.f[1] + ts3 * t1.f[1],
  1988. s0 * v0.f[2] + ts1 * t0.f[2] + s2 * v1.f[2] + ts3 * t1.f[2],
  1989. s0 * v0.f[3] + ts1 * t0.f[3] + s2 * v1.f[3] + ts3 * t1.f[3],
  1990. }};
  1991. if (type == cgltf_animation_path_type_rotation)
  1992. {
  1993. float len = sqrtf(lerp.f[0] * lerp.f[0] + lerp.f[1] * lerp.f[1] + lerp.f[2] * lerp.f[2] + lerp.f[3] * lerp.f[3]);
  1994. if (len > 0.f)
  1995. {
  1996. lerp.f[0] /= len;
  1997. lerp.f[1] /= len;
  1998. lerp.f[2] /= len;
  1999. lerp.f[3] /= len;
  2000. }
  2001. }
  2002. return lerp;
  2003. }
  2004. void resampleKeyframes(std::vector<Attr>& data, const std::vector<float>& input, const std::vector<Attr>& output, cgltf_animation_path_type type, cgltf_interpolation_type interpolation, size_t components, int frames, float mint, int freq)
  2005. {
  2006. size_t cursor = 0;
  2007. for (int i = 0; i < frames; ++i)
  2008. {
  2009. float time = mint + float(i) / freq;
  2010. while (cursor + 1 < input.size())
  2011. {
  2012. float next_time = input[cursor + 1];
  2013. if (next_time > time)
  2014. break;
  2015. cursor++;
  2016. }
  2017. if (cursor + 1 < input.size())
  2018. {
  2019. float cursor_time = input[cursor + 0];
  2020. float next_time = input[cursor + 1];
  2021. float range = next_time - cursor_time;
  2022. float inv_range = (range == 0.f) ? 0.f : 1.f / (next_time - cursor_time);
  2023. float t = std::max(0.f, std::min(1.f, (time - cursor_time) * inv_range));
  2024. for (size_t j = 0; j < components; ++j)
  2025. {
  2026. switch (interpolation)
  2027. {
  2028. case cgltf_interpolation_type_linear:
  2029. {
  2030. const Attr& v0 = output[(cursor + 0) * components + j];
  2031. const Attr& v1 = output[(cursor + 1) * components + j];
  2032. data.push_back(interpolateLinear(v0, v1, t, type));
  2033. }
  2034. break;
  2035. case cgltf_interpolation_type_step:
  2036. {
  2037. const Attr& v = output[cursor * components + j];
  2038. data.push_back(v);
  2039. }
  2040. break;
  2041. case cgltf_interpolation_type_cubic_spline:
  2042. {
  2043. const Attr& v0 = output[(cursor * 3 + 1) * components + j];
  2044. const Attr& b0 = output[(cursor * 3 + 2) * components + j];
  2045. const Attr& a1 = output[(cursor * 3 + 3) * components + j];
  2046. const Attr& v1 = output[(cursor * 3 + 4) * components + j];
  2047. data.push_back(interpolateHermite(v0, b0, v1, a1, t, range, type));
  2048. }
  2049. break;
  2050. default:
  2051. assert(!"Unknown interpolation type");
  2052. }
  2053. }
  2054. }
  2055. else
  2056. {
  2057. size_t offset = (interpolation == cgltf_interpolation_type_cubic_spline) ? cursor * 3 + 1 : cursor;
  2058. for (size_t j = 0; j < components; ++j)
  2059. {
  2060. const Attr& v = output[offset * components + j];
  2061. data.push_back(v);
  2062. }
  2063. }
  2064. }
  2065. }
  2066. bool isTrackEqual(const std::vector<Attr>& data, cgltf_animation_path_type type, int frames, const Attr* value, size_t components)
  2067. {
  2068. assert(data.size() == frames * components);
  2069. float tolerance = getDeltaTolerance(type);
  2070. for (int i = 0; i < frames; ++i)
  2071. {
  2072. for (size_t j = 0; j < components; ++j)
  2073. {
  2074. float delta = getDelta(value[j], data[i * components + j], type);
  2075. if (delta > tolerance)
  2076. return false;
  2077. }
  2078. }
  2079. return true;
  2080. }
  2081. void getBaseTransform(Attr* result, size_t components, cgltf_animation_path_type type, cgltf_node* node)
  2082. {
  2083. switch (type)
  2084. {
  2085. case cgltf_animation_path_type_translation:
  2086. memcpy(result->f, node->translation, 3 * sizeof(float));
  2087. break;
  2088. case cgltf_animation_path_type_rotation:
  2089. memcpy(result->f, node->rotation, 4 * sizeof(float));
  2090. break;
  2091. case cgltf_animation_path_type_scale:
  2092. memcpy(result->f, node->scale, 3 * sizeof(float));
  2093. break;
  2094. case cgltf_animation_path_type_weights:
  2095. if (node->weights_count)
  2096. {
  2097. assert(node->weights_count == components);
  2098. memcpy(result->f, node->weights, components * sizeof(float));
  2099. }
  2100. else if (node->mesh && node->mesh->weights_count)
  2101. {
  2102. assert(node->mesh->weights_count == components);
  2103. memcpy(result->f, node->mesh->weights, components * sizeof(float));
  2104. }
  2105. break;
  2106. default:
  2107. assert(!"Unknown animation path");
  2108. }
  2109. }
  2110. void processAnimation(Animation& animation, const Settings& settings)
  2111. {
  2112. float mint = 0, maxt = 0;
  2113. for (size_t i = 0; i < animation.tracks.size(); ++i)
  2114. {
  2115. const Track& track = animation.tracks[i];
  2116. assert(!track.time.empty());
  2117. mint = std::min(mint, track.time.front());
  2118. maxt = std::max(maxt, track.time.back());
  2119. }
  2120. // round the number of frames to nearest but favor the "up" direction
  2121. // this means that at 10 Hz resampling, we will try to preserve the last frame <10ms
  2122. // but if the last frame is <2ms we favor just removing this data
  2123. int frames = 1 + int((maxt - mint) * settings.anim_freq + 0.8f);
  2124. animation.start = mint;
  2125. animation.frames = frames;
  2126. std::vector<Attr> base;
  2127. for (size_t i = 0; i < animation.tracks.size(); ++i)
  2128. {
  2129. Track& track = animation.tracks[i];
  2130. std::vector<Attr> result;
  2131. resampleKeyframes(result, track.time, track.data, track.path, track.interpolation, track.components, frames, mint, settings.anim_freq);
  2132. track.time.clear();
  2133. track.data.swap(result);
  2134. if (isTrackEqual(track.data, track.path, frames, &track.data[0], track.components))
  2135. {
  2136. // track is constant (equal to first keyframe), we only need the first keyframe
  2137. track.data.resize(track.components);
  2138. // track.dummy is true iff track redundantly sets up the value to be equal to default node transform
  2139. base.resize(track.components);
  2140. getBaseTransform(&base[0], track.components, track.path, track.node);
  2141. track.dummy = isTrackEqual(track.data, track.path, 1, &base[0], track.components);
  2142. }
  2143. }
  2144. }
  2145. void markAnimated(cgltf_data* data, std::vector<NodeInfo>& nodes, const std::vector<Animation>& animations)
  2146. {
  2147. for (size_t i = 0; i < animations.size(); ++i)
  2148. {
  2149. const Animation& animation = animations[i];
  2150. for (size_t j = 0; j < animation.tracks.size(); ++j)
  2151. {
  2152. const Track& track = animation.tracks[j];
  2153. // mark nodes that have animation tracks that change their base transform as animated
  2154. if (!track.dummy)
  2155. {
  2156. NodeInfo& ni = nodes[track.node - data->nodes];
  2157. ni.animated_paths |= (1 << track.path);
  2158. }
  2159. }
  2160. }
  2161. for (size_t i = 0; i < data->nodes_count; ++i)
  2162. {
  2163. NodeInfo& ni = nodes[i];
  2164. for (cgltf_node* node = &data->nodes[i]; node; node = node->parent)
  2165. ni.animated |= nodes[node - data->nodes].animated_paths != 0;
  2166. }
  2167. }
  2168. void markNeededNodes(cgltf_data* data, std::vector<NodeInfo>& nodes, const std::vector<Mesh>& meshes, const std::vector<Animation>& animations, const Settings& settings)
  2169. {
  2170. // mark all joints as kept
  2171. for (size_t i = 0; i < data->skins_count; ++i)
  2172. {
  2173. const cgltf_skin& skin = data->skins[i];
  2174. // for now we keep all joints directly referenced by the skin and the entire ancestry tree; we keep names for joints as well
  2175. for (size_t j = 0; j < skin.joints_count; ++j)
  2176. {
  2177. NodeInfo& ni = nodes[skin.joints[j] - data->nodes];
  2178. ni.keep = true;
  2179. }
  2180. }
  2181. // mark all animated nodes as kept
  2182. for (size_t i = 0; i < animations.size(); ++i)
  2183. {
  2184. const Animation& animation = animations[i];
  2185. for (size_t j = 0; j < animation.tracks.size(); ++j)
  2186. {
  2187. const Track& track = animation.tracks[j];
  2188. if (settings.anim_const || !track.dummy)
  2189. {
  2190. NodeInfo& ni = nodes[track.node - data->nodes];
  2191. ni.keep = true;
  2192. }
  2193. }
  2194. }
  2195. // mark all mesh nodes as kept
  2196. for (size_t i = 0; i < meshes.size(); ++i)
  2197. {
  2198. const Mesh& mesh = meshes[i];
  2199. if (mesh.node)
  2200. {
  2201. NodeInfo& ni = nodes[mesh.node - data->nodes];
  2202. ni.keep = true;
  2203. }
  2204. }
  2205. // mark all light/camera nodes as kept
  2206. for (size_t i = 0; i < data->nodes_count; ++i)
  2207. {
  2208. const cgltf_node& node = data->nodes[i];
  2209. if (node.light || node.camera)
  2210. {
  2211. nodes[i].keep = true;
  2212. }
  2213. }
  2214. // mark all named nodes as needed (if -kn is specified)
  2215. if (settings.keep_named)
  2216. {
  2217. for (size_t i = 0; i < data->nodes_count; ++i)
  2218. {
  2219. const cgltf_node& node = data->nodes[i];
  2220. if (node.name && *node.name)
  2221. {
  2222. nodes[i].keep = true;
  2223. }
  2224. }
  2225. }
  2226. }
  2227. void markNeededMaterials(cgltf_data* data, std::vector<MaterialInfo>& materials, const std::vector<Mesh>& meshes)
  2228. {
  2229. // mark all used materials as kept
  2230. for (size_t i = 0; i < meshes.size(); ++i)
  2231. {
  2232. const Mesh& mesh = meshes[i];
  2233. if (mesh.material)
  2234. {
  2235. MaterialInfo& mi = materials[mesh.material - data->materials];
  2236. mi.keep = true;
  2237. }
  2238. }
  2239. }
  2240. void remapNodes(cgltf_data* data, std::vector<NodeInfo>& nodes, size_t& node_offset)
  2241. {
  2242. // to keep a node, we currently need to keep the entire ancestry chain
  2243. for (size_t i = 0; i < data->nodes_count; ++i)
  2244. {
  2245. if (!nodes[i].keep)
  2246. continue;
  2247. for (cgltf_node* node = &data->nodes[i]; node; node = node->parent)
  2248. nodes[node - data->nodes].keep = true;
  2249. }
  2250. // generate sequential indices for all nodes; they aren't sorted topologically
  2251. for (size_t i = 0; i < data->nodes_count; ++i)
  2252. {
  2253. NodeInfo& ni = nodes[i];
  2254. if (ni.keep)
  2255. {
  2256. ni.remap = int(node_offset);
  2257. node_offset++;
  2258. }
  2259. }
  2260. }
  2261. void analyzeImages(cgltf_data* data, std::vector<ImageInfo>& images)
  2262. {
  2263. for (size_t i = 0; i < data->materials_count; ++i)
  2264. {
  2265. const cgltf_material& material = data->materials[i];
  2266. if (material.has_pbr_metallic_roughness)
  2267. {
  2268. const cgltf_pbr_metallic_roughness& pbr = material.pbr_metallic_roughness;
  2269. if (pbr.base_color_texture.texture && pbr.base_color_texture.texture->image)
  2270. images[pbr.base_color_texture.texture->image - data->images].srgb = true;
  2271. }
  2272. if (material.has_pbr_specular_glossiness)
  2273. {
  2274. const cgltf_pbr_specular_glossiness& pbr = material.pbr_specular_glossiness;
  2275. if (pbr.diffuse_texture.texture && pbr.diffuse_texture.texture->image)
  2276. images[pbr.diffuse_texture.texture->image - data->images].srgb = true;
  2277. }
  2278. if (material.emissive_texture.texture && material.emissive_texture.texture->image)
  2279. images[material.emissive_texture.texture->image - data->images].srgb = true;
  2280. if (material.normal_texture.texture && material.normal_texture.texture->image)
  2281. images[material.normal_texture.texture->image - data->images].normal_map = true;
  2282. }
  2283. }
  2284. bool parseDataUri(const char* uri, std::string& mime_type, std::string& result)
  2285. {
  2286. if (strncmp(uri, "data:", 5) == 0)
  2287. {
  2288. const char* comma = strchr(uri, ',');
  2289. if (comma && comma - uri >= 7 && strncmp(comma - 7, ";base64", 7) == 0)
  2290. {
  2291. const char* base64 = comma + 1;
  2292. size_t base64_size = strlen(base64);
  2293. size_t size = base64_size - base64_size / 4;
  2294. if (base64_size >= 2)
  2295. {
  2296. size -= base64[base64_size - 2] == '=';
  2297. size -= base64[base64_size - 1] == '=';
  2298. }
  2299. void* data = 0;
  2300. cgltf_options options = {};
  2301. cgltf_result res = cgltf_load_buffer_base64(&options, size, base64, &data);
  2302. if (res != cgltf_result_success)
  2303. return false;
  2304. mime_type = std::string(uri + 5, comma - 7);
  2305. result = std::string(static_cast<const char*>(data), size);
  2306. free(data);
  2307. return true;
  2308. }
  2309. }
  2310. return false;
  2311. }
  2312. void writeEmbeddedImage(std::string& json, std::vector<BufferView>& views, const char* data, size_t size, const char* mime_type)
  2313. {
  2314. size_t view = getBufferView(views, BufferView::Kind_Image, -1, 1, false);
  2315. assert(views[view].data.empty());
  2316. views[view].data.assign(data, size);
  2317. append(json, "\"bufferView\":");
  2318. append(json, view);
  2319. append(json, ",\"mimeType\":\"");
  2320. append(json, mime_type);
  2321. append(json, "\"");
  2322. }
  2323. std::string inferMimeType(const char* path)
  2324. {
  2325. const char* ext = strrchr(path, '.');
  2326. if (!ext)
  2327. return "";
  2328. std::string extl = ext + 1;
  2329. for (size_t i = 0; i < extl.length(); ++i)
  2330. extl[i] = char(tolower(extl[i]));
  2331. if (extl == "jpg")
  2332. return "image/jpeg";
  2333. else
  2334. return "image/" + extl;
  2335. }
  2336. std::string getFullPath(const char* path, const char* base_path)
  2337. {
  2338. std::string result = base_path;
  2339. std::string::size_type slash = result.find_last_of("/\\");
  2340. result.erase(slash == std::string::npos ? 0 : slash + 1);
  2341. result += path;
  2342. return result;
  2343. }
  2344. std::string getFileName(const char* path)
  2345. {
  2346. std::string result = path;
  2347. std::string::size_type slash = result.find_last_of("/\\");
  2348. if (slash != std::string::npos)
  2349. result.erase(0, slash + 1);
  2350. std::string::size_type dot = result.find_last_of('.');
  2351. if (dot != std::string::npos)
  2352. result.erase(dot);
  2353. return result;
  2354. }
  2355. bool readFile(const char* path, std::string& data)
  2356. {
  2357. FILE* file = fopen(path, "rb");
  2358. if (!file)
  2359. return false;
  2360. fseek(file, 0, SEEK_END);
  2361. long length = ftell(file);
  2362. fseek(file, 0, SEEK_SET);
  2363. if (length <= 0)
  2364. {
  2365. fclose(file);
  2366. return false;
  2367. }
  2368. data.resize(length);
  2369. size_t result = fread(&data[0], 1, data.size(), file);
  2370. fclose(file);
  2371. return result == data.size();
  2372. }
  2373. bool writeFile(const char* path, const std::string& data)
  2374. {
  2375. FILE* file = fopen(path, "wb");
  2376. if (!file)
  2377. return false;
  2378. size_t result = fwrite(&data[0], 1, data.size(), file);
  2379. fclose(file);
  2380. return result == data.size();
  2381. }
  2382. struct TempFile
  2383. {
  2384. std::string path;
  2385. int fd;
  2386. TempFile(const char* suffix)
  2387. : fd(-1)
  2388. {
  2389. #ifdef _WIN32
  2390. const char* temp_dir = getenv("TEMP");
  2391. path = temp_dir ? temp_dir : ".";
  2392. path += "\\gltfpack-XXXXXX";
  2393. (void)_mktemp(&path[0]);
  2394. path += suffix;
  2395. #else
  2396. path = "/tmp/gltfpack-XXXXXX";
  2397. path += suffix;
  2398. fd = mkstemps(&path[0], strlen(suffix));
  2399. #endif
  2400. }
  2401. ~TempFile()
  2402. {
  2403. unlink(path.c_str());
  2404. #ifndef _WIN32
  2405. close(fd);
  2406. #endif
  2407. }
  2408. };
  2409. bool checkBasis()
  2410. {
  2411. const char* basisu_path = getenv("BASISU_PATH");
  2412. std::string cmd = basisu_path ? basisu_path : "basisu";
  2413. #ifdef _WIN32
  2414. cmd += " 2>nul";
  2415. #else
  2416. cmd += " 2>/dev/null";
  2417. #endif
  2418. FILE* pipe = popen(cmd.c_str(), "r");
  2419. if (!pipe)
  2420. return false;
  2421. char buf[15];
  2422. size_t read = fread(buf, 1, sizeof(buf), pipe);
  2423. pclose(pipe);
  2424. return read == sizeof(buf) && memcmp(buf, "Basis Universal", sizeof(buf)) == 0;
  2425. }
  2426. bool encodeBasis(const std::string& data, std::string& result, bool normal_map, bool srgb, int quality)
  2427. {
  2428. TempFile temp_input(".raw");
  2429. TempFile temp_output(".basis");
  2430. if (!writeFile(temp_input.path.c_str(), data))
  2431. return false;
  2432. const char* basisu_path = getenv("BASISU_PATH");
  2433. std::string cmd = basisu_path ? basisu_path : "basisu";
  2434. char ql[16];
  2435. sprintf(ql, "%d", (quality * 255 + 50) / 100);
  2436. cmd += " -q ";
  2437. cmd += ql;
  2438. cmd += " -mipmap";
  2439. if (normal_map)
  2440. {
  2441. cmd += " -normal_map";
  2442. // for optimal quality we should specify seperate_rg_to_color_alpha but this requires renderer awareness
  2443. }
  2444. else if (!srgb)
  2445. {
  2446. cmd += " -linear";
  2447. }
  2448. cmd += " -file ";
  2449. cmd += temp_input.path;
  2450. cmd += " -output_file ";
  2451. cmd += temp_output.path;
  2452. #ifdef _WIN32
  2453. cmd += " >nul";
  2454. #else
  2455. cmd += " >/dev/null";
  2456. #endif
  2457. int rc = system(cmd.c_str());
  2458. return rc == 0 && readFile(temp_output.path.c_str(), result);
  2459. }
  2460. // basistoktx.cpp
  2461. extern std::string basisToKtx(const std::string& basis, bool srgb);
  2462. void writeImage(std::string& json, std::vector<BufferView>& views, const cgltf_image& image, const ImageInfo& info, size_t index, const char* input_path, const char* output_path, const Settings& settings)
  2463. {
  2464. std::string img_data;
  2465. std::string mime_type;
  2466. if (image.uri && parseDataUri(image.uri, mime_type, img_data))
  2467. {
  2468. // we will re-embed img_data below
  2469. }
  2470. else if (image.buffer_view && image.buffer_view->buffer->data && image.mime_type)
  2471. {
  2472. const cgltf_buffer_view* view = image.buffer_view;
  2473. img_data.assign(static_cast<const char*>(view->buffer->data) + view->offset, view->size);
  2474. mime_type = image.mime_type;
  2475. }
  2476. else if (image.uri && settings.texture_embed)
  2477. {
  2478. std::string full_path = getFullPath(image.uri, input_path);
  2479. if (!readFile(full_path.c_str(), img_data))
  2480. {
  2481. fprintf(stderr, "Warning: unable to read image %s, skipping\n", image.uri);
  2482. }
  2483. mime_type = inferMimeType(image.uri);
  2484. }
  2485. if (!img_data.empty())
  2486. {
  2487. if (settings.texture_basis)
  2488. {
  2489. std::string encoded;
  2490. if (encodeBasis(img_data, encoded, info.normal_map, info.srgb, settings.texture_quality))
  2491. {
  2492. if (settings.texture_ktx2)
  2493. encoded = basisToKtx(encoded, info.srgb);
  2494. writeEmbeddedImage(json, views, encoded.c_str(), encoded.size(), settings.texture_ktx2 ? "image/ktx2" : "image/basis");
  2495. }
  2496. else
  2497. {
  2498. fprintf(stderr, "Warning: unable to encode image %d with Basis, skipping\n", int(index));
  2499. }
  2500. }
  2501. else
  2502. {
  2503. writeEmbeddedImage(json, views, img_data.c_str(), img_data.size(), mime_type.c_str());
  2504. }
  2505. }
  2506. else if (image.uri)
  2507. {
  2508. if (settings.texture_basis)
  2509. {
  2510. std::string full_path = getFullPath(image.uri, input_path);
  2511. std::string basis_path = getFileName(image.uri) + (settings.texture_ktx2 ? ".ktx2" : ".basis");
  2512. std::string basis_full_path = getFullPath(basis_path.c_str(), output_path);
  2513. if (readFile(full_path.c_str(), img_data))
  2514. {
  2515. std::string encoded;
  2516. if (encodeBasis(img_data, encoded, info.normal_map, info.srgb, settings.texture_quality))
  2517. {
  2518. if (settings.texture_ktx2)
  2519. encoded = basisToKtx(encoded, info.srgb);
  2520. if (writeFile(basis_full_path.c_str(), encoded))
  2521. {
  2522. append(json, "\"uri\":\"");
  2523. append(json, basis_path);
  2524. append(json, "\"");
  2525. }
  2526. else
  2527. {
  2528. fprintf(stderr, "Warning: unable to save Basis image %s, skipping\n", image.uri);
  2529. }
  2530. }
  2531. else
  2532. {
  2533. fprintf(stderr, "Warning: unable to encode image %s with Basis, skipping\n", image.uri);
  2534. }
  2535. }
  2536. else
  2537. {
  2538. fprintf(stderr, "Warning: unable to read image %s, skipping\n", image.uri);
  2539. }
  2540. }
  2541. else
  2542. {
  2543. append(json, "\"uri\":\"");
  2544. append(json, image.uri);
  2545. append(json, "\"");
  2546. }
  2547. }
  2548. else
  2549. {
  2550. fprintf(stderr, "Warning: ignoring image %d since it has no URI and no valid buffer data\n", int(index));
  2551. }
  2552. }
  2553. void writeTexture(std::string& json, const cgltf_texture& texture, cgltf_data* data, const Settings& settings)
  2554. {
  2555. if (texture.image)
  2556. {
  2557. if (settings.texture_ktx2)
  2558. {
  2559. append(json, "\"extensions\":{\"KHR_texture_basisu\":{\"source\":");
  2560. append(json, size_t(texture.image - data->images));
  2561. append(json, "}}");
  2562. }
  2563. else
  2564. {
  2565. append(json, "\"source\":");
  2566. append(json, size_t(texture.image - data->images));
  2567. }
  2568. }
  2569. }
  2570. void writeMeshAttributes(std::string& json, std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, const Mesh& mesh, int target, const QuantizationParams& qp, const Settings& settings)
  2571. {
  2572. std::string scratch;
  2573. for (size_t j = 0; j < mesh.streams.size(); ++j)
  2574. {
  2575. const Stream& stream = mesh.streams[j];
  2576. if (stream.target != target)
  2577. continue;
  2578. scratch.clear();
  2579. StreamFormat format = writeVertexStream(scratch, stream, qp, settings, mesh.targets > 0);
  2580. size_t view = getBufferView(views, BufferView::Kind_Vertex, stream.type, format.stride, settings.compress);
  2581. size_t offset = views[view].data.size();
  2582. views[view].data += scratch;
  2583. comma(json_accessors);
  2584. if (stream.type == cgltf_attribute_type_position)
  2585. {
  2586. int min[3] = {};
  2587. int max[3] = {};
  2588. getPositionBounds(min, max, stream, qp);
  2589. float minf[3] = {float(min[0]), float(min[1]), float(min[2])};
  2590. float maxf[3] = {float(max[0]), float(max[1]), float(max[2])};
  2591. writeAccessor(json_accessors, view, offset, format.type, format.component_type, format.normalized, stream.data.size(), minf, maxf, 3);
  2592. }
  2593. else
  2594. {
  2595. writeAccessor(json_accessors, view, offset, format.type, format.component_type, format.normalized, stream.data.size());
  2596. }
  2597. size_t vertex_accr = accr_offset++;
  2598. comma(json);
  2599. append(json, "\"");
  2600. append(json, attributeType(stream.type));
  2601. if (stream.type != cgltf_attribute_type_position && stream.type != cgltf_attribute_type_normal && stream.type != cgltf_attribute_type_tangent)
  2602. {
  2603. append(json, "_");
  2604. append(json, size_t(stream.index));
  2605. }
  2606. append(json, "\":");
  2607. append(json, vertex_accr);
  2608. }
  2609. }
  2610. size_t writeMeshIndices(std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, const Mesh& mesh, const Settings& settings)
  2611. {
  2612. std::string scratch;
  2613. StreamFormat format = writeIndexStream(scratch, mesh.indices);
  2614. // note: we prefer to merge all index streams together; however, index codec currently doesn't handle concatenated index streams well and loses compression ratio
  2615. int variant = settings.compress ? -1 : 0;
  2616. size_t view = getBufferView(views, BufferView::Kind_Index, variant, format.stride, settings.compress);
  2617. size_t offset = views[view].data.size();
  2618. views[view].data += scratch;
  2619. comma(json_accessors);
  2620. writeAccessor(json_accessors, view, offset, format.type, format.component_type, format.normalized, mesh.indices.size());
  2621. size_t index_accr = accr_offset++;
  2622. return index_accr;
  2623. }
  2624. size_t writeAnimationTime(std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, float mint, int frames, const Settings& settings)
  2625. {
  2626. std::vector<float> time(frames);
  2627. for (int j = 0; j < frames; ++j)
  2628. time[j] = mint + float(j) / settings.anim_freq;
  2629. std::string scratch;
  2630. StreamFormat format = writeTimeStream(scratch, time);
  2631. size_t view = getBufferView(views, BufferView::Kind_Time, 0, format.stride, settings.compress);
  2632. size_t offset = views[view].data.size();
  2633. views[view].data += scratch;
  2634. comma(json_accessors);
  2635. writeAccessor(json_accessors, view, offset, cgltf_type_scalar, format.component_type, format.normalized, frames, &time.front(), &time.back(), 1);
  2636. size_t time_accr = accr_offset++;
  2637. return time_accr;
  2638. }
  2639. size_t writeJointBindMatrices(std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, const cgltf_skin& skin, const QuantizationParams& qp, const Settings& settings)
  2640. {
  2641. std::string scratch;
  2642. for (size_t j = 0; j < skin.joints_count; ++j)
  2643. {
  2644. float transform[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
  2645. if (skin.inverse_bind_matrices)
  2646. {
  2647. cgltf_accessor_read_float(skin.inverse_bind_matrices, j, transform, 16);
  2648. }
  2649. float node_scale = qp.pos_scale / float((1 << qp.pos_bits) - 1);
  2650. // pos_offset has to be applied first, thus it results in an offset rotated by the bind matrix
  2651. transform[12] += qp.pos_offset[0] * transform[0] + qp.pos_offset[1] * transform[4] + qp.pos_offset[2] * transform[8];
  2652. transform[13] += qp.pos_offset[0] * transform[1] + qp.pos_offset[1] * transform[5] + qp.pos_offset[2] * transform[9];
  2653. transform[14] += qp.pos_offset[0] * transform[2] + qp.pos_offset[1] * transform[6] + qp.pos_offset[2] * transform[10];
  2654. // node_scale will be applied before the rotation/scale from transform
  2655. for (int k = 0; k < 12; ++k)
  2656. transform[k] *= node_scale;
  2657. scratch.append(reinterpret_cast<const char*>(transform), sizeof(transform));
  2658. }
  2659. size_t view = getBufferView(views, BufferView::Kind_Skin, 0, 64, settings.compress);
  2660. size_t offset = views[view].data.size();
  2661. views[view].data += scratch;
  2662. comma(json_accessors);
  2663. writeAccessor(json_accessors, view, offset, cgltf_type_mat4, cgltf_component_type_r_32f, false, skin.joints_count);
  2664. size_t matrix_accr = accr_offset++;
  2665. return matrix_accr;
  2666. }
  2667. void writeMeshNode(std::string& json, size_t mesh_offset, const Mesh& mesh, cgltf_data* data, const QuantizationParams& qp)
  2668. {
  2669. float node_scale = qp.pos_scale / float((1 << qp.pos_bits) - 1);
  2670. comma(json);
  2671. append(json, "{\"mesh\":");
  2672. append(json, mesh_offset);
  2673. if (mesh.skin)
  2674. {
  2675. comma(json);
  2676. append(json, "\"skin\":");
  2677. append(json, size_t(mesh.skin - data->skins));
  2678. }
  2679. append(json, ",\"translation\":[");
  2680. append(json, qp.pos_offset[0]);
  2681. append(json, ",");
  2682. append(json, qp.pos_offset[1]);
  2683. append(json, ",");
  2684. append(json, qp.pos_offset[2]);
  2685. append(json, "],\"scale\":[");
  2686. append(json, node_scale);
  2687. append(json, ",");
  2688. append(json, node_scale);
  2689. append(json, ",");
  2690. append(json, node_scale);
  2691. append(json, "]");
  2692. if (mesh.node && mesh.node->weights_count)
  2693. {
  2694. append(json, ",\"weights\":[");
  2695. for (size_t j = 0; j < mesh.node->weights_count; ++j)
  2696. {
  2697. comma(json);
  2698. append(json, mesh.node->weights[j]);
  2699. }
  2700. append(json, "]");
  2701. }
  2702. append(json, "}");
  2703. }
  2704. void writeNode(std::string& json, const cgltf_node& node, const std::vector<NodeInfo>& nodes, cgltf_data* data)
  2705. {
  2706. const NodeInfo& ni = nodes[&node - data->nodes];
  2707. comma(json);
  2708. append(json, "{");
  2709. if (node.name && *node.name)
  2710. {
  2711. comma(json);
  2712. append(json, "\"name\":\"");
  2713. append(json, node.name);
  2714. append(json, "\"");
  2715. }
  2716. if (node.has_translation)
  2717. {
  2718. comma(json);
  2719. append(json, "\"translation\":[");
  2720. append(json, node.translation[0]);
  2721. append(json, ",");
  2722. append(json, node.translation[1]);
  2723. append(json, ",");
  2724. append(json, node.translation[2]);
  2725. append(json, "]");
  2726. }
  2727. if (node.has_rotation)
  2728. {
  2729. comma(json);
  2730. append(json, "\"rotation\":[");
  2731. append(json, node.rotation[0]);
  2732. append(json, ",");
  2733. append(json, node.rotation[1]);
  2734. append(json, ",");
  2735. append(json, node.rotation[2]);
  2736. append(json, ",");
  2737. append(json, node.rotation[3]);
  2738. append(json, "]");
  2739. }
  2740. if (node.has_scale)
  2741. {
  2742. comma(json);
  2743. append(json, "\"scale\":[");
  2744. append(json, node.scale[0]);
  2745. append(json, ",");
  2746. append(json, node.scale[1]);
  2747. append(json, ",");
  2748. append(json, node.scale[2]);
  2749. append(json, "]");
  2750. }
  2751. if (node.has_matrix)
  2752. {
  2753. comma(json);
  2754. append(json, "\"matrix\":[");
  2755. for (int k = 0; k < 16; ++k)
  2756. {
  2757. comma(json);
  2758. append(json, node.matrix[k]);
  2759. }
  2760. append(json, "]");
  2761. }
  2762. if (node.children_count || !ni.meshes.empty())
  2763. {
  2764. comma(json);
  2765. append(json, "\"children\":[");
  2766. for (size_t j = 0; j < node.children_count; ++j)
  2767. {
  2768. const NodeInfo& ci = nodes[node.children[j] - data->nodes];
  2769. if (ci.keep)
  2770. {
  2771. comma(json);
  2772. append(json, size_t(ci.remap));
  2773. }
  2774. }
  2775. for (size_t j = 0; j < ni.meshes.size(); ++j)
  2776. {
  2777. comma(json);
  2778. append(json, ni.meshes[j]);
  2779. }
  2780. append(json, "]");
  2781. }
  2782. if (node.camera)
  2783. {
  2784. comma(json);
  2785. append(json, "\"camera\":");
  2786. append(json, size_t(node.camera - data->cameras));
  2787. }
  2788. if (node.light)
  2789. {
  2790. comma(json);
  2791. append(json, "\"extensions\":{\"KHR_lights_punctual\":{\"light\":");
  2792. append(json, size_t(node.light - data->lights));
  2793. append(json, "}}");
  2794. }
  2795. append(json, "}");
  2796. }
  2797. void writeAnimation(std::string& json, std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, const Animation& animation, size_t i, cgltf_data* data, const std::vector<NodeInfo>& nodes, const Settings& settings)
  2798. {
  2799. std::vector<const Track*> tracks;
  2800. for (size_t j = 0; j < animation.tracks.size(); ++j)
  2801. {
  2802. const Track& track = animation.tracks[j];
  2803. const NodeInfo& ni = nodes[track.node - data->nodes];
  2804. if (!ni.keep)
  2805. continue;
  2806. if (!settings.anim_const && (ni.animated_paths & (1 << track.path)) == 0)
  2807. continue;
  2808. tracks.push_back(&track);
  2809. }
  2810. if (tracks.empty())
  2811. {
  2812. fprintf(stderr, "Warning: ignoring animation %d because it has no valid tracks\n", int(i));
  2813. return;
  2814. }
  2815. bool needs_time = false;
  2816. bool needs_pose = false;
  2817. for (size_t j = 0; j < tracks.size(); ++j)
  2818. {
  2819. const Track& track = *tracks[j];
  2820. bool tc = track.data.size() == track.components;
  2821. needs_time = needs_time || !tc;
  2822. needs_pose = needs_pose || tc;
  2823. }
  2824. size_t time_accr = needs_time ? writeAnimationTime(views, json_accessors, accr_offset, animation.start, animation.frames, settings) : 0;
  2825. size_t pose_accr = needs_pose ? writeAnimationTime(views, json_accessors, accr_offset, animation.start, 1, settings) : 0;
  2826. std::string json_samplers;
  2827. std::string json_channels;
  2828. size_t track_offset = 0;
  2829. for (size_t j = 0; j < tracks.size(); ++j)
  2830. {
  2831. const Track& track = *tracks[j];
  2832. bool tc = track.data.size() == track.components;
  2833. std::string scratch;
  2834. StreamFormat format = writeKeyframeStream(scratch, track.path, track.data);
  2835. size_t view = getBufferView(views, BufferView::Kind_Keyframe, track.path, format.stride, settings.compress && track.path != cgltf_animation_path_type_weights);
  2836. size_t offset = views[view].data.size();
  2837. views[view].data += scratch;
  2838. comma(json_accessors);
  2839. writeAccessor(json_accessors, view, offset, format.type, format.component_type, format.normalized, track.data.size());
  2840. size_t data_accr = accr_offset++;
  2841. comma(json_samplers);
  2842. append(json_samplers, "{\"input\":");
  2843. append(json_samplers, tc ? pose_accr : time_accr);
  2844. append(json_samplers, ",\"output\":");
  2845. append(json_samplers, data_accr);
  2846. append(json_samplers, "}");
  2847. const NodeInfo& tni = nodes[track.node - data->nodes];
  2848. size_t target_node = size_t(tni.remap);
  2849. if (track.path == cgltf_animation_path_type_weights)
  2850. {
  2851. assert(tni.meshes.size() == 1);
  2852. target_node = tni.meshes[0];
  2853. }
  2854. comma(json_channels);
  2855. append(json_channels, "{\"sampler\":");
  2856. append(json_channels, track_offset);
  2857. append(json_channels, ",\"target\":{\"node\":");
  2858. append(json_channels, target_node);
  2859. append(json_channels, ",\"path\":\"");
  2860. append(json_channels, animationPath(track.path));
  2861. append(json_channels, "\"}}");
  2862. track_offset++;
  2863. }
  2864. comma(json);
  2865. append(json, "{");
  2866. if (animation.name && *animation.name)
  2867. {
  2868. append(json, "\"name\":\"");
  2869. append(json, animation.name);
  2870. append(json, "\",");
  2871. }
  2872. append(json, "\"samplers\":[");
  2873. append(json, json_samplers);
  2874. append(json, "],\"channels\":[");
  2875. append(json, json_channels);
  2876. append(json, "]}");
  2877. }
  2878. void writeCamera(std::string& json, const cgltf_camera& camera)
  2879. {
  2880. comma(json);
  2881. append(json, "{");
  2882. switch (camera.type)
  2883. {
  2884. case cgltf_camera_type_perspective:
  2885. append(json, "\"type\":\"perspective\",\"perspective\":{");
  2886. append(json, "\"yfov\":");
  2887. append(json, camera.data.perspective.yfov);
  2888. append(json, ",\"znear\":");
  2889. append(json, camera.data.perspective.znear);
  2890. if (camera.data.perspective.aspect_ratio != 0.f)
  2891. {
  2892. append(json, ",\"aspectRatio\":");
  2893. append(json, camera.data.perspective.aspect_ratio);
  2894. }
  2895. if (camera.data.perspective.zfar != 0.f)
  2896. {
  2897. append(json, ",\"zfar\":");
  2898. append(json, camera.data.perspective.zfar);
  2899. }
  2900. append(json, "}");
  2901. break;
  2902. case cgltf_camera_type_orthographic:
  2903. append(json, "\"type\":\"orthographic\",\"orthographic\":{");
  2904. append(json, "\"xmag\":");
  2905. append(json, camera.data.orthographic.xmag);
  2906. append(json, ",\"ymag\":");
  2907. append(json, camera.data.orthographic.ymag);
  2908. append(json, ",\"znear\":");
  2909. append(json, camera.data.orthographic.znear);
  2910. append(json, ",\"zfar\":");
  2911. append(json, camera.data.orthographic.zfar);
  2912. append(json, "}");
  2913. break;
  2914. default:
  2915. fprintf(stderr, "Warning: skipping camera of unknown type\n");
  2916. }
  2917. append(json, "}");
  2918. }
  2919. void writeLight(std::string& json, const cgltf_light& light)
  2920. {
  2921. static const float white[3] = {1, 1, 1};
  2922. comma(json);
  2923. append(json, "{\"type\":\"");
  2924. append(json, lightType(light.type));
  2925. append(json, "\"");
  2926. if (memcmp(light.color, white, sizeof(white)) != 0)
  2927. {
  2928. comma(json);
  2929. append(json, "\"color\":[");
  2930. append(json, light.color[0]);
  2931. append(json, ",");
  2932. append(json, light.color[1]);
  2933. append(json, ",");
  2934. append(json, light.color[2]);
  2935. append(json, "]");
  2936. }
  2937. if (light.intensity != 1.f)
  2938. {
  2939. comma(json);
  2940. append(json, "\"intensity\":");
  2941. append(json, light.intensity);
  2942. }
  2943. if (light.range != 0.f)
  2944. {
  2945. comma(json);
  2946. append(json, "\"range\":");
  2947. append(json, light.range);
  2948. }
  2949. if (light.type == cgltf_light_type_spot)
  2950. {
  2951. comma(json);
  2952. append(json, "\"spot\":{");
  2953. append(json, "\"innerConeAngle\":");
  2954. append(json, light.spot_inner_cone_angle);
  2955. append(json, ",\"outerConeAngle\":");
  2956. append(json, light.spot_outer_cone_angle == 0.f ? 0.78539816339f : light.spot_outer_cone_angle);
  2957. append(json, "}");
  2958. }
  2959. append(json, "}");
  2960. }
  2961. void writeArray(std::string& json, const char* name, const std::string& contents)
  2962. {
  2963. if (contents.empty())
  2964. return;
  2965. comma(json);
  2966. append(json, "\"");
  2967. append(json, name);
  2968. append(json, "\":[");
  2969. append(json, contents);
  2970. append(json, "]");
  2971. }
  2972. void writeExtensions(std::string& json, const ExtensionInfo* extensions, size_t count)
  2973. {
  2974. comma(json);
  2975. append(json, "\"extensionsUsed\":[");
  2976. for (size_t i = 0; i < count; ++i)
  2977. if (extensions[i].used)
  2978. {
  2979. comma(json);
  2980. append(json, "\"");
  2981. append(json, extensions[i].name);
  2982. append(json, "\"");
  2983. }
  2984. append(json, "]");
  2985. comma(json);
  2986. append(json, "\"extensionsRequired\":[");
  2987. for (size_t i = 0; i < count; ++i)
  2988. if (extensions[i].used && extensions[i].required)
  2989. {
  2990. comma(json);
  2991. append(json, "\"");
  2992. append(json, extensions[i].name);
  2993. append(json, "\"");
  2994. }
  2995. append(json, "]");
  2996. }
  2997. void finalizeBufferViews(std::string& json, std::vector<BufferView>& views, std::string& bin, std::string& fallback)
  2998. {
  2999. for (size_t i = 0; i < views.size(); ++i)
  3000. {
  3001. BufferView& view = views[i];
  3002. size_t bin_offset = bin.size();
  3003. size_t fallback_offset = fallback.size();
  3004. size_t count = view.data.size() / view.stride;
  3005. int compression = -1;
  3006. if (view.compressed)
  3007. {
  3008. if (view.kind == BufferView::Kind_Index)
  3009. {
  3010. compressIndexStream(bin, view.data, count, view.stride);
  3011. compression = 1;
  3012. }
  3013. else
  3014. {
  3015. compressVertexStream(bin, view.data, count, view.stride);
  3016. compression = 0;
  3017. }
  3018. fallback += view.data;
  3019. }
  3020. else
  3021. {
  3022. bin += view.data;
  3023. }
  3024. size_t raw_offset = (compression >= 0) ? fallback_offset : bin_offset;
  3025. comma(json);
  3026. writeBufferView(json, view.kind, count, view.stride, raw_offset, view.data.size(), compression, bin_offset, bin.size() - bin_offset);
  3027. // record written bytes for statistics
  3028. view.bytes = bin.size() - bin_offset;
  3029. // align each bufferView by 4 bytes
  3030. bin.resize((bin.size() + 3) & ~3);
  3031. fallback.resize((fallback.size() + 3) & ~3);
  3032. }
  3033. }
  3034. void printMeshStats(const std::vector<Mesh>& meshes, const char* name)
  3035. {
  3036. size_t triangles = 0;
  3037. size_t vertices = 0;
  3038. for (size_t i = 0; i < meshes.size(); ++i)
  3039. {
  3040. const Mesh& mesh = meshes[i];
  3041. triangles += mesh.indices.size() / 3;
  3042. vertices += mesh.streams.empty() ? 0 : mesh.streams[0].data.size();
  3043. }
  3044. printf("%s: %d triangles, %d vertices\n", name, int(triangles), int(vertices));
  3045. }
  3046. void printSceneStats(const std::vector<BufferView>& views, const std::vector<Mesh>& meshes, size_t node_offset, size_t mesh_offset, size_t material_offset, size_t json_size, size_t bin_size)
  3047. {
  3048. size_t bytes[BufferView::Kind_Count] = {};
  3049. for (size_t i = 0; i < views.size(); ++i)
  3050. {
  3051. const BufferView& view = views[i];
  3052. bytes[view.kind] += view.bytes;
  3053. }
  3054. printf("output: %d nodes, %d meshes (%d primitives), %d materials\n", int(node_offset), int(mesh_offset), int(meshes.size()), int(material_offset));
  3055. printf("output: JSON %d bytes, buffers %d bytes\n", int(json_size), int(bin_size));
  3056. printf("output: buffers: vertex %d bytes, index %d bytes, skin %d bytes, time %d bytes, keyframe %d bytes, image %d bytes\n",
  3057. int(bytes[BufferView::Kind_Vertex]), int(bytes[BufferView::Kind_Index]), int(bytes[BufferView::Kind_Skin]),
  3058. int(bytes[BufferView::Kind_Time]), int(bytes[BufferView::Kind_Keyframe]), int(bytes[BufferView::Kind_Image]));
  3059. }
  3060. void printAttributeStats(const std::vector<BufferView>& views, BufferView::Kind kind, const char* name)
  3061. {
  3062. for (size_t i = 0; i < views.size(); ++i)
  3063. {
  3064. const BufferView& view = views[i];
  3065. if (view.kind != kind)
  3066. continue;
  3067. const char* variant = "unknown";
  3068. switch (kind)
  3069. {
  3070. case BufferView::Kind_Vertex:
  3071. variant = attributeType(cgltf_attribute_type(view.variant));
  3072. break;
  3073. case BufferView::Kind_Index:
  3074. variant = "index";
  3075. break;
  3076. case BufferView::Kind_Keyframe:
  3077. variant = animationPath(cgltf_animation_path_type(view.variant));
  3078. break;
  3079. default:;
  3080. }
  3081. size_t count = view.data.size() / view.stride;
  3082. printf("stats: %s %s: compressed %d bytes (%.1f bits), raw %d bytes (%d bits)\n",
  3083. name,
  3084. variant,
  3085. int(view.bytes),
  3086. double(view.bytes) / double(count) * 8,
  3087. int(view.data.size()),
  3088. int(view.stride * 8));
  3089. }
  3090. }
  3091. void process(cgltf_data* data, const char* input_path, const char* output_path, std::vector<Mesh>& meshes, std::vector<Animation>& animations, const Settings& settings, std::string& json, std::string& bin, std::string& fallback)
  3092. {
  3093. if (settings.verbose)
  3094. {
  3095. printf("input: %d nodes, %d meshes (%d primitives), %d materials, %d skins, %d animations\n",
  3096. int(data->nodes_count), int(data->meshes_count), int(meshes.size()), int(data->materials_count), int(data->skins_count), int(animations.size()));
  3097. printMeshStats(meshes, "input");
  3098. }
  3099. for (size_t i = 0; i < animations.size(); ++i)
  3100. {
  3101. processAnimation(animations[i], settings);
  3102. }
  3103. std::vector<NodeInfo> nodes(data->nodes_count);
  3104. markAnimated(data, nodes, animations);
  3105. for (size_t i = 0; i < meshes.size(); ++i)
  3106. {
  3107. Mesh& mesh = meshes[i];
  3108. // note: when -kn is specified, we keep mesh-node attachment so that named nodes can be transformed
  3109. if (mesh.node && !settings.keep_named)
  3110. {
  3111. NodeInfo& ni = nodes[mesh.node - data->nodes];
  3112. // we transform all non-skinned non-animated meshes to world space
  3113. // this makes sure that quantization doesn't introduce gaps if the original scene was watertight
  3114. if (!ni.animated && !mesh.skin && mesh.targets == 0)
  3115. {
  3116. transformMesh(mesh, mesh.node);
  3117. mesh.node = 0;
  3118. }
  3119. // skinned and animated meshes will be anchored to the same node that they used to be in
  3120. // for animated meshes, this is important since they need to be transformed by the same animation
  3121. // for skinned meshes, in theory this isn't important since the transform of the skinned node doesn't matter; in practice this affects generated bounding box in three.js
  3122. }
  3123. }
  3124. mergeMeshMaterials(data, meshes);
  3125. mergeMeshes(meshes, settings);
  3126. filterEmptyMeshes(meshes);
  3127. markNeededNodes(data, nodes, meshes, animations, settings);
  3128. std::vector<MaterialInfo> materials(data->materials_count);
  3129. markNeededMaterials(data, materials, meshes);
  3130. for (size_t i = 0; i < meshes.size(); ++i)
  3131. {
  3132. processMesh(meshes[i], settings);
  3133. }
  3134. filterEmptyMeshes(meshes); // some meshes may become empty after processing
  3135. std::vector<ImageInfo> images(data->images_count);
  3136. analyzeImages(data, images);
  3137. QuantizationParams qp = prepareQuantization(meshes, settings);
  3138. std::string json_images;
  3139. std::string json_textures;
  3140. std::string json_materials;
  3141. std::string json_accessors;
  3142. std::string json_meshes;
  3143. std::string json_nodes;
  3144. std::string json_skins;
  3145. std::string json_roots;
  3146. std::string json_animations;
  3147. std::string json_cameras;
  3148. std::string json_lights;
  3149. std::vector<BufferView> views;
  3150. bool ext_pbr_specular_glossiness = false;
  3151. bool ext_unlit = false;
  3152. size_t accr_offset = 0;
  3153. size_t node_offset = 0;
  3154. size_t mesh_offset = 0;
  3155. size_t material_offset = 0;
  3156. for (size_t i = 0; i < data->images_count; ++i)
  3157. {
  3158. const cgltf_image& image = data->images[i];
  3159. if (settings.verbose && settings.texture_basis)
  3160. {
  3161. const char* uri = image.uri;
  3162. bool embedded = !uri || strncmp(uri, "data:", 5) == 0;
  3163. printf("image %d (%s) is being encoded with Basis\n", int(i), embedded ? "embedded" : uri);
  3164. }
  3165. comma(json_images);
  3166. append(json_images, "{");
  3167. writeImage(json_images, views, image, images[i], i, input_path, output_path, settings);
  3168. append(json_images, "}");
  3169. }
  3170. for (size_t i = 0; i < data->textures_count; ++i)
  3171. {
  3172. const cgltf_texture& texture = data->textures[i];
  3173. comma(json_textures);
  3174. append(json_textures, "{");
  3175. writeTexture(json_textures, texture, data, settings);
  3176. append(json_textures, "}");
  3177. }
  3178. for (size_t i = 0; i < data->materials_count; ++i)
  3179. {
  3180. MaterialInfo& mi = materials[i];
  3181. if (!mi.keep)
  3182. continue;
  3183. const cgltf_material& material = data->materials[i];
  3184. comma(json_materials);
  3185. append(json_materials, "{");
  3186. writeMaterialInfo(json_materials, data, material, qp);
  3187. append(json_materials, "}");
  3188. mi.remap = int(material_offset);
  3189. material_offset++;
  3190. ext_pbr_specular_glossiness = ext_pbr_specular_glossiness || material.has_pbr_specular_glossiness;
  3191. ext_unlit = ext_unlit || material.unlit;
  3192. }
  3193. for (size_t i = 0; i < meshes.size(); ++i)
  3194. {
  3195. const Mesh& mesh = meshes[i];
  3196. comma(json_meshes);
  3197. append(json_meshes, "{\"primitives\":[");
  3198. size_t pi = i;
  3199. for (; pi < meshes.size(); ++pi)
  3200. {
  3201. const Mesh& prim = meshes[pi];
  3202. if (prim.node != mesh.node || prim.skin != mesh.skin || prim.targets != mesh.targets)
  3203. break;
  3204. if (!compareMeshTargets(mesh, prim))
  3205. break;
  3206. comma(json_meshes);
  3207. append(json_meshes, "{\"attributes\":{");
  3208. writeMeshAttributes(json_meshes, views, json_accessors, accr_offset, prim, 0, qp, settings);
  3209. append(json_meshes, "}");
  3210. append(json_meshes, ",\"mode\":");
  3211. append(json_meshes, size_t(prim.type));
  3212. if (mesh.targets)
  3213. {
  3214. append(json_meshes, ",\"targets\":[");
  3215. for (size_t j = 0; j < mesh.targets; ++j)
  3216. {
  3217. comma(json_meshes);
  3218. append(json_meshes, "{");
  3219. writeMeshAttributes(json_meshes, views, json_accessors, accr_offset, prim, int(1 + j), qp, settings);
  3220. append(json_meshes, "}");
  3221. }
  3222. append(json_meshes, "]");
  3223. }
  3224. if (!prim.indices.empty())
  3225. {
  3226. size_t index_accr = writeMeshIndices(views, json_accessors, accr_offset, prim, settings);
  3227. append(json_meshes, ",\"indices\":");
  3228. append(json_meshes, index_accr);
  3229. }
  3230. if (prim.material)
  3231. {
  3232. MaterialInfo& mi = materials[prim.material - data->materials];
  3233. assert(mi.keep);
  3234. append(json_meshes, ",\"material\":");
  3235. append(json_meshes, size_t(mi.remap));
  3236. }
  3237. append(json_meshes, "}");
  3238. }
  3239. append(json_meshes, "]");
  3240. if (mesh.target_weights.size())
  3241. {
  3242. append(json_meshes, ",\"weights\":[");
  3243. for (size_t j = 0; j < mesh.target_weights.size(); ++j)
  3244. {
  3245. comma(json_meshes);
  3246. append(json_meshes, mesh.target_weights[j]);
  3247. }
  3248. append(json_meshes, "]");
  3249. }
  3250. if (mesh.target_names.size())
  3251. {
  3252. append(json_meshes, ",\"extras\":{\"targetNames\":[");
  3253. for (size_t j = 0; j < mesh.target_names.size(); ++j)
  3254. {
  3255. comma(json_meshes);
  3256. append(json_meshes, "\"");
  3257. append(json_meshes, mesh.target_names[j]);
  3258. append(json_meshes, "\"");
  3259. }
  3260. append(json_meshes, "]}");
  3261. }
  3262. append(json_meshes, "}");
  3263. writeMeshNode(json_nodes, mesh_offset, mesh, data, qp);
  3264. if (mesh.node)
  3265. {
  3266. NodeInfo& ni = nodes[mesh.node - data->nodes];
  3267. assert(ni.keep);
  3268. ni.meshes.push_back(node_offset);
  3269. }
  3270. else
  3271. {
  3272. comma(json_roots);
  3273. append(json_roots, node_offset);
  3274. }
  3275. node_offset++;
  3276. mesh_offset++;
  3277. // skip all meshes that we've written in this iteration
  3278. assert(pi > i);
  3279. i = pi - 1;
  3280. }
  3281. remapNodes(data, nodes, node_offset);
  3282. for (size_t i = 0; i < data->nodes_count; ++i)
  3283. {
  3284. NodeInfo& ni = nodes[i];
  3285. if (!ni.keep)
  3286. continue;
  3287. const cgltf_node& node = data->nodes[i];
  3288. if (!node.parent)
  3289. {
  3290. comma(json_roots);
  3291. append(json_roots, size_t(ni.remap));
  3292. }
  3293. writeNode(json_nodes, node, nodes, data);
  3294. }
  3295. for (size_t i = 0; i < data->skins_count; ++i)
  3296. {
  3297. const cgltf_skin& skin = data->skins[i];
  3298. size_t matrix_accr = writeJointBindMatrices(views, json_accessors, accr_offset, skin, qp, settings);
  3299. comma(json_skins);
  3300. append(json_skins, "{");
  3301. append(json_skins, "\"joints\":[");
  3302. for (size_t j = 0; j < skin.joints_count; ++j)
  3303. {
  3304. comma(json_skins);
  3305. append(json_skins, size_t(nodes[skin.joints[j] - data->nodes].remap));
  3306. }
  3307. append(json_skins, "]");
  3308. append(json_skins, ",\"inverseBindMatrices\":");
  3309. append(json_skins, matrix_accr);
  3310. if (skin.skeleton)
  3311. {
  3312. comma(json_skins);
  3313. append(json_skins, "\"skeleton\":");
  3314. append(json_skins, size_t(nodes[skin.skeleton - data->nodes].remap));
  3315. }
  3316. append(json_skins, "}");
  3317. }
  3318. for (size_t i = 0; i < animations.size(); ++i)
  3319. {
  3320. const Animation& animation = animations[i];
  3321. writeAnimation(json_animations, views, json_accessors, accr_offset, animation, i, data, nodes, settings);
  3322. }
  3323. for (size_t i = 0; i < data->cameras_count; ++i)
  3324. {
  3325. const cgltf_camera& camera = data->cameras[i];
  3326. writeCamera(json_cameras, camera);
  3327. }
  3328. for (size_t i = 0; i < data->lights_count; ++i)
  3329. {
  3330. const cgltf_light& light = data->lights[i];
  3331. writeLight(json_lights, light);
  3332. }
  3333. char version[32];
  3334. sprintf(version, "%d.%d", MESHOPTIMIZER_VERSION / 1000, (MESHOPTIMIZER_VERSION % 1000) / 10);
  3335. append(json, "\"asset\":{");
  3336. append(json, "\"version\":\"2.0\",\"generator\":\"gltfpack ");
  3337. append(json, version);
  3338. append(json, "\"");
  3339. if (data->asset.extras.start_offset)
  3340. {
  3341. append(json, ",\"extras\":");
  3342. json.append(data->json + data->asset.extras.start_offset, data->json + data->asset.extras.end_offset);
  3343. }
  3344. append(json, "}");
  3345. const ExtensionInfo extensions[] = {
  3346. {"KHR_mesh_quantization", true, true},
  3347. {"MESHOPT_compression", settings.compress, !settings.fallback},
  3348. {"KHR_texture_transform", !json_textures.empty(), false},
  3349. {"KHR_materials_pbrSpecularGlossiness", ext_pbr_specular_glossiness, false},
  3350. {"KHR_materials_unlit", ext_unlit, false},
  3351. {"KHR_lights_punctual", data->lights_count > 0, false},
  3352. {"KHR_image_ktx2", !json_textures.empty() && settings.texture_ktx2, true},
  3353. {"KHR_texture_basisu", !json_textures.empty() && settings.texture_ktx2, true},
  3354. };
  3355. writeExtensions(json, extensions, sizeof(extensions) / sizeof(extensions[0]));
  3356. std::string json_views;
  3357. finalizeBufferViews(json_views, views, bin, fallback);
  3358. writeArray(json, "bufferViews", json_views);
  3359. writeArray(json, "accessors", json_accessors);
  3360. writeArray(json, "images", json_images);
  3361. writeArray(json, "textures", json_textures);
  3362. writeArray(json, "materials", json_materials);
  3363. writeArray(json, "meshes", json_meshes);
  3364. writeArray(json, "skins", json_skins);
  3365. writeArray(json, "animations", json_animations);
  3366. writeArray(json, "nodes", json_nodes);
  3367. if (!json_roots.empty())
  3368. {
  3369. append(json, ",\"scenes\":[");
  3370. append(json, "{\"nodes\":[");
  3371. append(json, json_roots);
  3372. append(json, "]}]");
  3373. }
  3374. writeArray(json, "cameras", json_cameras);
  3375. if (!json_lights.empty())
  3376. {
  3377. append(json, ",\"extensions\":{\"KHR_lights_punctual\":{\"lights\":[");
  3378. append(json, json_lights);
  3379. append(json, "]}}");
  3380. }
  3381. if (!json_roots.empty())
  3382. {
  3383. append(json, ",\"scene\":0");
  3384. }
  3385. if (settings.verbose)
  3386. {
  3387. printMeshStats(meshes, "output");
  3388. printSceneStats(views, meshes, node_offset, mesh_offset, material_offset, json.size(), bin.size());
  3389. }
  3390. if (settings.verbose > 1)
  3391. {
  3392. printAttributeStats(views, BufferView::Kind_Vertex, "vertex");
  3393. printAttributeStats(views, BufferView::Kind_Index, "index");
  3394. printAttributeStats(views, BufferView::Kind_Keyframe, "keyframe");
  3395. }
  3396. }
  3397. void writeU32(FILE* out, uint32_t data)
  3398. {
  3399. fwrite(&data, 4, 1, out);
  3400. }
  3401. bool requiresExtension(cgltf_data* data, const char* name)
  3402. {
  3403. for (size_t i = 0; i < data->extensions_required_count; ++i)
  3404. if (strcmp(data->extensions_required[i], name) == 0)
  3405. return true;
  3406. return false;
  3407. }
  3408. const char* getBaseName(const char* path)
  3409. {
  3410. const char* slash = strrchr(path, '/');
  3411. const char* backslash = strrchr(path, '\\');
  3412. const char* rs = slash ? slash + 1 : path;
  3413. const char* bs = backslash ? backslash + 1 : path;
  3414. return std::max(rs, bs);
  3415. }
  3416. std::string getBufferSpec(const char* bin_path, size_t bin_size, const char* fallback_path, size_t fallback_size, bool fallback_ref)
  3417. {
  3418. std::string json;
  3419. append(json, "\"buffers\":[");
  3420. append(json, "{");
  3421. if (bin_path)
  3422. {
  3423. append(json, "\"uri\":\"");
  3424. append(json, bin_path);
  3425. append(json, "\"");
  3426. }
  3427. comma(json);
  3428. append(json, "\"byteLength\":");
  3429. append(json, bin_size);
  3430. append(json, "}");
  3431. if (fallback_ref)
  3432. {
  3433. comma(json);
  3434. append(json, "{");
  3435. if (fallback_path)
  3436. {
  3437. append(json, "\"uri\":\"");
  3438. append(json, fallback_path);
  3439. append(json, "\"");
  3440. }
  3441. comma(json);
  3442. append(json, "\"byteLength\":");
  3443. append(json, fallback_size);
  3444. append(json, ",\"extensions\":{");
  3445. append(json, "\"MESHOPT_compression\":{");
  3446. append(json, "\"fallback\":true");
  3447. append(json, "}}");
  3448. append(json, "}");
  3449. }
  3450. append(json, "]");
  3451. return json;
  3452. }
  3453. bool needsDummyBuffers(cgltf_data* data)
  3454. {
  3455. for (size_t i = 0; i < data->accessors_count; ++i)
  3456. {
  3457. cgltf_accessor* accessor = &data->accessors[i];
  3458. if (accessor->buffer_view && accessor->buffer_view->buffer->data == NULL)
  3459. return true;
  3460. if (accessor->is_sparse)
  3461. {
  3462. cgltf_accessor_sparse* sparse = &accessor->sparse;
  3463. if (sparse->indices_buffer_view->buffer->data == NULL)
  3464. return true;
  3465. if (sparse->values_buffer_view->buffer->data == NULL)
  3466. return true;
  3467. }
  3468. }
  3469. return false;
  3470. }
  3471. int gltfpack(const char* input, const char* output, const Settings& settings)
  3472. {
  3473. cgltf_data* data = 0;
  3474. std::vector<Mesh> meshes;
  3475. std::vector<Animation> animations;
  3476. const char* iext = strrchr(input, '.');
  3477. if (iext && (strcmp(iext, ".gltf") == 0 || strcmp(iext, ".GLTF") == 0 || strcmp(iext, ".glb") == 0 || strcmp(iext, ".GLB") == 0))
  3478. {
  3479. cgltf_options options = {};
  3480. cgltf_result result = cgltf_parse_file(&options, input, &data);
  3481. result = (result == cgltf_result_success) ? cgltf_load_buffers(&options, data, input) : result;
  3482. result = (result == cgltf_result_success) ? cgltf_validate(data) : result;
  3483. const char* error = NULL;
  3484. if (result != cgltf_result_success)
  3485. error = getError(result, data);
  3486. else if (requiresExtension(data, "KHR_draco_mesh_compression"))
  3487. error = "file requires Draco mesh compression support";
  3488. else if (requiresExtension(data, "MESHOPT_compression"))
  3489. error = "file has already been compressed using gltfpack";
  3490. else if (needsDummyBuffers(data))
  3491. error = "buffer has no data";
  3492. if (error)
  3493. {
  3494. fprintf(stderr, "Error loading %s: %s\n", input, error);
  3495. cgltf_free(data);
  3496. return 2;
  3497. }
  3498. parseMeshes(data, meshes);
  3499. parseAnimations(data, animations);
  3500. }
  3501. else if (iext && (strcmp(iext, ".obj") == 0 || strcmp(iext, ".OBJ") == 0))
  3502. {
  3503. fastObjMesh* obj = fast_obj_read(input);
  3504. if (!obj)
  3505. {
  3506. fprintf(stderr, "Error loading %s: file not found\n", input);
  3507. cgltf_free(data);
  3508. return 2;
  3509. }
  3510. data = parseSceneObj(obj);
  3511. parseMeshesObj(obj, data, meshes);
  3512. fast_obj_destroy(obj);
  3513. }
  3514. else
  3515. {
  3516. fprintf(stderr, "Error loading %s: unknown extension (expected .gltf or .glb or .obj)\n", input);
  3517. return 2;
  3518. }
  3519. if (data->images_count && settings.texture_basis)
  3520. {
  3521. if (!checkBasis())
  3522. {
  3523. fprintf(stderr, "Error: basisu is not present in PATH or BASISU_PATH is not set\n");
  3524. return 3;
  3525. }
  3526. }
  3527. std::string json, bin, fallback;
  3528. process(data, input, output, meshes, animations, settings, json, bin, fallback);
  3529. cgltf_free(data);
  3530. if (!output)
  3531. {
  3532. return 0;
  3533. }
  3534. const char* oext = strrchr(output, '.');
  3535. if (oext && (strcmp(oext, ".gltf") == 0 || strcmp(oext, ".GLTF") == 0))
  3536. {
  3537. std::string binpath = output;
  3538. binpath.replace(binpath.size() - 5, 5, ".bin");
  3539. std::string fbpath = output;
  3540. fbpath.replace(fbpath.size() - 5, 5, ".fallback.bin");
  3541. FILE* outjson = fopen(output, "wb");
  3542. FILE* outbin = fopen(binpath.c_str(), "wb");
  3543. FILE* outfb = settings.fallback ? fopen(fbpath.c_str(), "wb") : NULL;
  3544. if (!outjson || !outbin || (!outfb && settings.fallback))
  3545. {
  3546. fprintf(stderr, "Error saving %s\n", output);
  3547. return 4;
  3548. }
  3549. std::string bufferspec = getBufferSpec(getBaseName(binpath.c_str()), bin.size(), settings.fallback ? getBaseName(fbpath.c_str()) : NULL, fallback.size(), settings.compress);
  3550. fprintf(outjson, "{");
  3551. fwrite(bufferspec.c_str(), bufferspec.size(), 1, outjson);
  3552. fprintf(outjson, ",");
  3553. fwrite(json.c_str(), json.size(), 1, outjson);
  3554. fprintf(outjson, "}");
  3555. fwrite(bin.c_str(), bin.size(), 1, outbin);
  3556. if (settings.fallback)
  3557. fwrite(fallback.c_str(), fallback.size(), 1, outfb);
  3558. fclose(outjson);
  3559. fclose(outbin);
  3560. if (outfb)
  3561. fclose(outfb);
  3562. }
  3563. else if (oext && (strcmp(oext, ".glb") == 0 || strcmp(oext, ".GLB") == 0))
  3564. {
  3565. std::string fbpath = output;
  3566. fbpath.replace(fbpath.size() - 4, 4, ".fallback.bin");
  3567. FILE* out = fopen(output, "wb");
  3568. FILE* outfb = settings.fallback ? fopen(fbpath.c_str(), "wb") : NULL;
  3569. if (!out || (!outfb && settings.fallback))
  3570. {
  3571. fprintf(stderr, "Error saving %s\n", output);
  3572. return 4;
  3573. }
  3574. std::string bufferspec = getBufferSpec(NULL, bin.size(), settings.fallback ? getBaseName(fbpath.c_str()) : NULL, fallback.size(), settings.compress);
  3575. json.insert(0, "{" + bufferspec + ",");
  3576. json.push_back('}');
  3577. while (json.size() % 4)
  3578. json.push_back(' ');
  3579. while (bin.size() % 4)
  3580. bin.push_back('\0');
  3581. writeU32(out, 0x46546C67);
  3582. writeU32(out, 2);
  3583. writeU32(out, uint32_t(12 + 8 + json.size() + 8 + bin.size()));
  3584. writeU32(out, uint32_t(json.size()));
  3585. writeU32(out, 0x4E4F534A);
  3586. fwrite(json.c_str(), json.size(), 1, out);
  3587. writeU32(out, uint32_t(bin.size()));
  3588. writeU32(out, 0x004E4942);
  3589. fwrite(bin.c_str(), bin.size(), 1, out);
  3590. if (settings.fallback)
  3591. fwrite(fallback.c_str(), fallback.size(), 1, outfb);
  3592. fclose(out);
  3593. if (outfb)
  3594. fclose(outfb);
  3595. }
  3596. else
  3597. {
  3598. fprintf(stderr, "Error saving %s: unknown extension (expected .gltf or .glb)\n", output);
  3599. return 4;
  3600. }
  3601. return 0;
  3602. }
  3603. int main(int argc, char** argv)
  3604. {
  3605. Settings settings = {};
  3606. settings.pos_bits = 14;
  3607. settings.tex_bits = 12;
  3608. settings.nrm_bits = 8;
  3609. settings.anim_freq = 30;
  3610. settings.simplify_threshold = 1.f;
  3611. settings.texture_quality = 50;
  3612. const char* input = 0;
  3613. const char* output = 0;
  3614. bool help = false;
  3615. int test = 0;
  3616. for (int i = 1; i < argc; ++i)
  3617. {
  3618. const char* arg = argv[i];
  3619. if (strcmp(arg, "-vp") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
  3620. {
  3621. settings.pos_bits = atoi(argv[++i]);
  3622. }
  3623. else if (strcmp(arg, "-vt") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
  3624. {
  3625. settings.tex_bits = atoi(argv[++i]);
  3626. }
  3627. else if (strcmp(arg, "-vn") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
  3628. {
  3629. settings.nrm_bits = atoi(argv[++i]);
  3630. }
  3631. else if (strcmp(arg, "-vu") == 0)
  3632. {
  3633. settings.nrm_unnormalized = true;
  3634. }
  3635. else if (strcmp(arg, "-af") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
  3636. {
  3637. settings.anim_freq = atoi(argv[++i]);
  3638. }
  3639. else if (strcmp(arg, "-ac") == 0)
  3640. {
  3641. settings.anim_const = true;
  3642. }
  3643. else if (strcmp(arg, "-kn") == 0)
  3644. {
  3645. settings.keep_named = true;
  3646. }
  3647. else if (strcmp(arg, "-si") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
  3648. {
  3649. settings.simplify_threshold = float(atof(argv[++i]));
  3650. }
  3651. else if (strcmp(arg, "-sa") == 0)
  3652. {
  3653. settings.simplify_aggressive = true;
  3654. }
  3655. else if (strcmp(arg, "-te") == 0)
  3656. {
  3657. settings.texture_embed = true;
  3658. }
  3659. else if (strcmp(arg, "-tb") == 0)
  3660. {
  3661. settings.texture_basis = true;
  3662. }
  3663. else if (strcmp(arg, "-tc") == 0)
  3664. {
  3665. settings.texture_basis = true;
  3666. settings.texture_ktx2 = true;
  3667. }
  3668. else if (strcmp(arg, "-tq") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
  3669. {
  3670. settings.texture_quality = atoi(argv[++i]);
  3671. }
  3672. else if (strcmp(arg, "-i") == 0 && i + 1 < argc && !input)
  3673. {
  3674. input = argv[++i];
  3675. }
  3676. else if (strcmp(arg, "-o") == 0 && i + 1 < argc && !output)
  3677. {
  3678. output = argv[++i];
  3679. }
  3680. else if (strcmp(arg, "-c") == 0)
  3681. {
  3682. settings.compress = true;
  3683. }
  3684. else if (strcmp(arg, "-cf") == 0)
  3685. {
  3686. settings.compress = true;
  3687. settings.fallback = true;
  3688. }
  3689. else if (strcmp(arg, "-v") == 0)
  3690. {
  3691. settings.verbose = 1;
  3692. }
  3693. else if (strcmp(arg, "-vv") == 0)
  3694. {
  3695. settings.verbose = 2;
  3696. }
  3697. else if (strcmp(arg, "-h") == 0)
  3698. {
  3699. help = true;
  3700. }
  3701. else if (strcmp(arg, "-test") == 0)
  3702. {
  3703. test = i + 1;
  3704. break;
  3705. }
  3706. else
  3707. {
  3708. fprintf(stderr, "Unrecognized option %s\n", arg);
  3709. return 1;
  3710. }
  3711. }
  3712. if (test)
  3713. {
  3714. for (int i = test; i < argc; ++i)
  3715. {
  3716. printf("%s\n", argv[i]);
  3717. gltfpack(argv[i], NULL, settings);
  3718. }
  3719. return 0;
  3720. }
  3721. if (!input || !output || help)
  3722. {
  3723. fprintf(stderr, "Usage: gltfpack [options] -i input -o output\n");
  3724. fprintf(stderr, "\n");
  3725. fprintf(stderr, "Options:\n");
  3726. fprintf(stderr, "-i file: input file to process, .obj/.gltf/.glb\n");
  3727. fprintf(stderr, "-o file: output file path, .gltf/.glb\n");
  3728. fprintf(stderr, "-vp N: use N-bit quantization for positions (default: 14; N should be between 1 and 16)\n");
  3729. fprintf(stderr, "-vt N: use N-bit quantization for texture corodinates (default: 12; N should be between 1 and 16)\n");
  3730. fprintf(stderr, "-vn N: use N-bit quantization for normals and tangents (default: 8; N should be between 1 and 16)\n");
  3731. fprintf(stderr, "-vu: use unnormalized normal/tangent vectors to improve compression (default: off)\n");
  3732. fprintf(stderr, "-af N: resample animations at N Hz (default: 30)\n");
  3733. fprintf(stderr, "-ac: keep constant animation tracks even if they don't modify the node transform\n");
  3734. fprintf(stderr, "-kn: keep named nodes and meshes attached to named nodes so that named nodes can be transformed externally\n");
  3735. fprintf(stderr, "-si R: simplify meshes to achieve the ratio R (default: 1; R should be between 0 and 1)\n");
  3736. fprintf(stderr, "-sa: aggressively simplify to the target ratio disregarding quality\n");
  3737. fprintf(stderr, "-te: embed all textures into main buffer\n");
  3738. fprintf(stderr, "-tb: convert all textures to Basis Universal format (with basisu executable)\n");
  3739. fprintf(stderr, "-tc: convert all textures to KTX2 with BasisU supercompression (using basisu executable)\n");
  3740. fprintf(stderr, "-tq N: set texture encoding quality (default: 50; N should be between 1 and 100\n");
  3741. fprintf(stderr, "-c: produce compressed gltf/glb files\n");
  3742. fprintf(stderr, "-cf: produce compressed gltf/glb files with fallback for loaders that don't support compression\n");
  3743. fprintf(stderr, "-v: verbose output\n");
  3744. fprintf(stderr, "-h: display this help and exit\n");
  3745. return 1;
  3746. }
  3747. return gltfpack(input, output, settings);
  3748. }