gltfpack.cpp 93 KB

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