gltfpack.cpp 103 KB

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