2
0

gltfpack.cpp 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632
  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 ? (settings.nrm_bits > 8 ? 16 : 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. if (bits > 8)
  806. {
  807. int16_t v[4] = {
  808. int16_t(meshopt_quantizeSnorm(nx, bits)),
  809. int16_t(meshopt_quantizeSnorm(ny, bits)),
  810. int16_t(meshopt_quantizeSnorm(nz, bits)),
  811. 0};
  812. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  813. }
  814. else
  815. {
  816. int8_t v[4] = {
  817. int8_t(meshopt_quantizeSnorm(nx, bits)),
  818. int8_t(meshopt_quantizeSnorm(ny, bits)),
  819. int8_t(meshopt_quantizeSnorm(nz, bits)),
  820. 0};
  821. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  822. }
  823. }
  824. if (bits > 8)
  825. {
  826. StreamFormat format = {cgltf_type_vec3, cgltf_component_type_r_16, true, 8};
  827. return format;
  828. }
  829. else
  830. {
  831. StreamFormat format = {cgltf_type_vec3, cgltf_component_type_r_8, true, 4};
  832. return format;
  833. }
  834. }
  835. else if (stream.type == cgltf_attribute_type_tangent)
  836. {
  837. bool nrm_unit = has_targets || settings.nrm_unit;
  838. int bits = nrm_unit ? (settings.nrm_bits > 8 ? 16 : 8) : settings.nrm_bits;
  839. for (size_t i = 0; i < stream.data.size(); ++i)
  840. {
  841. const Attr& a = stream.data[i];
  842. float nx = a.f[0], ny = a.f[1], nz = a.f[2], nw = a.f[3];
  843. if (!nrm_unit)
  844. rescaleNormal(nx, ny, nz);
  845. if (bits > 8)
  846. {
  847. int16_t v[4] = {
  848. int16_t(meshopt_quantizeSnorm(nx, bits)),
  849. int16_t(meshopt_quantizeSnorm(ny, bits)),
  850. int16_t(meshopt_quantizeSnorm(nz, bits)),
  851. int16_t(meshopt_quantizeSnorm(nw, 8))};
  852. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  853. }
  854. else
  855. {
  856. int8_t v[4] = {
  857. int8_t(meshopt_quantizeSnorm(nx, bits)),
  858. int8_t(meshopt_quantizeSnorm(ny, bits)),
  859. int8_t(meshopt_quantizeSnorm(nz, bits)),
  860. int8_t(meshopt_quantizeSnorm(nw, 8))};
  861. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  862. }
  863. }
  864. cgltf_type type = (stream.target == 0) ? cgltf_type_vec4 : cgltf_type_vec3;
  865. if (bits > 8)
  866. {
  867. StreamFormat format = {type, cgltf_component_type_r_16, true, 8};
  868. return format;
  869. }
  870. else
  871. {
  872. StreamFormat format = {type, cgltf_component_type_r_8, true, 4};
  873. return format;
  874. }
  875. }
  876. else if (stream.type == cgltf_attribute_type_color)
  877. {
  878. for (size_t i = 0; i < stream.data.size(); ++i)
  879. {
  880. const Attr& a = stream.data[i];
  881. uint8_t v[4] = {
  882. uint8_t(meshopt_quantizeUnorm(a.f[0], 8)),
  883. uint8_t(meshopt_quantizeUnorm(a.f[1], 8)),
  884. uint8_t(meshopt_quantizeUnorm(a.f[2], 8)),
  885. uint8_t(meshopt_quantizeUnorm(a.f[3], 8))};
  886. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  887. }
  888. StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_8u, true, 4};
  889. return format;
  890. }
  891. else if (stream.type == cgltf_attribute_type_weights)
  892. {
  893. for (size_t i = 0; i < stream.data.size(); ++i)
  894. {
  895. const Attr& a = stream.data[i];
  896. uint8_t v[4] = {
  897. uint8_t(meshopt_quantizeUnorm(a.f[0], 8)),
  898. uint8_t(meshopt_quantizeUnorm(a.f[1], 8)),
  899. uint8_t(meshopt_quantizeUnorm(a.f[2], 8)),
  900. uint8_t(meshopt_quantizeUnorm(a.f[3], 8))};
  901. renormalizeWeights(v);
  902. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  903. }
  904. StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_8u, true, 4};
  905. return format;
  906. }
  907. else if (stream.type == cgltf_attribute_type_joints)
  908. {
  909. unsigned int maxj = 0;
  910. for (size_t i = 0; i < stream.data.size(); ++i)
  911. maxj = std::max(maxj, unsigned(stream.data[i].f[0]));
  912. assert(maxj <= 65535);
  913. if (maxj <= 255)
  914. {
  915. for (size_t i = 0; i < stream.data.size(); ++i)
  916. {
  917. const Attr& a = stream.data[i];
  918. uint8_t v[4] = {
  919. uint8_t(a.f[0]),
  920. uint8_t(a.f[1]),
  921. uint8_t(a.f[2]),
  922. uint8_t(a.f[3])};
  923. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  924. }
  925. StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_8u, false, 4};
  926. return format;
  927. }
  928. else
  929. {
  930. for (size_t i = 0; i < stream.data.size(); ++i)
  931. {
  932. const Attr& a = stream.data[i];
  933. uint16_t v[4] = {
  934. uint16_t(a.f[0]),
  935. uint16_t(a.f[1]),
  936. uint16_t(a.f[2]),
  937. uint16_t(a.f[3])};
  938. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  939. }
  940. StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_16u, false, 8};
  941. return format;
  942. }
  943. }
  944. else
  945. {
  946. for (size_t i = 0; i < stream.data.size(); ++i)
  947. {
  948. const Attr& a = stream.data[i];
  949. float v[4] = {
  950. a.f[0],
  951. a.f[1],
  952. a.f[2],
  953. a.f[3]};
  954. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  955. }
  956. StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_32f, false, 16};
  957. return format;
  958. }
  959. }
  960. void getPositionBounds(int min[3], int max[3], const Stream& stream, const QuantizationParams& params)
  961. {
  962. assert(stream.type == cgltf_attribute_type_position);
  963. assert(stream.data.size() > 0);
  964. min[0] = min[1] = min[2] = INT_MAX;
  965. max[0] = max[1] = max[2] = INT_MIN;
  966. float pos_rscale = params.pos_scale == 0.f ? 0.f : 1.f / params.pos_scale;
  967. if (stream.target == 0)
  968. {
  969. for (size_t i = 0; i < stream.data.size(); ++i)
  970. {
  971. const Attr& a = stream.data[i];
  972. for (int k = 0; k < 3; ++k)
  973. {
  974. int v = meshopt_quantizeUnorm((a.f[k] - params.pos_offset[k]) * pos_rscale, params.pos_bits);
  975. min[k] = std::min(min[k], v);
  976. max[k] = std::max(max[k], v);
  977. }
  978. }
  979. }
  980. else
  981. {
  982. for (size_t i = 0; i < stream.data.size(); ++i)
  983. {
  984. const Attr& a = stream.data[i];
  985. for (int k = 0; k < 3; ++k)
  986. {
  987. int v = (a.f[k] >= 0.f ? 1 : -1) * meshopt_quantizeUnorm(fabsf(a.f[k]) * pos_rscale, params.pos_bits);
  988. min[k] = std::min(min[k], v);
  989. max[k] = std::max(max[k], v);
  990. }
  991. }
  992. }
  993. }
  994. StreamFormat writeIndexStream(std::string& bin, const std::vector<unsigned int>& stream)
  995. {
  996. unsigned int maxi = 0;
  997. for (size_t i = 0; i < stream.size(); ++i)
  998. maxi = std::max(maxi, stream[i]);
  999. // save 16-bit indices if we can; note that we can't use restart index (65535)
  1000. if (maxi < 65535)
  1001. {
  1002. for (size_t i = 0; i < stream.size(); ++i)
  1003. {
  1004. uint16_t v[1] = {uint16_t(stream[i])};
  1005. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1006. }
  1007. StreamFormat format = {cgltf_type_scalar, cgltf_component_type_r_16u, false, 2};
  1008. return format;
  1009. }
  1010. else
  1011. {
  1012. for (size_t i = 0; i < stream.size(); ++i)
  1013. {
  1014. uint32_t v[1] = {stream[i]};
  1015. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1016. }
  1017. StreamFormat format = {cgltf_type_scalar, cgltf_component_type_r_32u, false, 4};
  1018. return format;
  1019. }
  1020. }
  1021. StreamFormat writeTimeStream(std::string& bin, const std::vector<float>& data)
  1022. {
  1023. for (size_t i = 0; i < data.size(); ++i)
  1024. {
  1025. float v[1] = {data[i]};
  1026. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1027. }
  1028. StreamFormat format = {cgltf_type_scalar, cgltf_component_type_r_32f, false, 4};
  1029. return format;
  1030. }
  1031. StreamFormat writeKeyframeStream(std::string& bin, cgltf_animation_path_type type, const std::vector<Attr>& data)
  1032. {
  1033. if (type == cgltf_animation_path_type_rotation)
  1034. {
  1035. for (size_t i = 0; i < data.size(); ++i)
  1036. {
  1037. const Attr& a = data[i];
  1038. int16_t v[4] = {
  1039. int16_t(meshopt_quantizeSnorm(a.f[0], 16)),
  1040. int16_t(meshopt_quantizeSnorm(a.f[1], 16)),
  1041. int16_t(meshopt_quantizeSnorm(a.f[2], 16)),
  1042. int16_t(meshopt_quantizeSnorm(a.f[3], 16)),
  1043. };
  1044. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1045. }
  1046. StreamFormat format = {cgltf_type_vec4, cgltf_component_type_r_16, true, 8};
  1047. return format;
  1048. }
  1049. else if (type == cgltf_animation_path_type_weights)
  1050. {
  1051. for (size_t i = 0; i < data.size(); ++i)
  1052. {
  1053. const Attr& a = data[i];
  1054. uint8_t v[1] = {uint8_t(meshopt_quantizeUnorm(a.f[0], 8))};
  1055. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1056. }
  1057. StreamFormat format = {cgltf_type_scalar, cgltf_component_type_r_8u, true, 1};
  1058. return format;
  1059. }
  1060. else
  1061. {
  1062. for (size_t i = 0; i < data.size(); ++i)
  1063. {
  1064. const Attr& a = data[i];
  1065. float v[3] = {a.f[0], a.f[1], a.f[2]};
  1066. bin.append(reinterpret_cast<const char*>(v), sizeof(v));
  1067. }
  1068. StreamFormat format = {cgltf_type_vec3, cgltf_component_type_r_32f, false, 12};
  1069. return format;
  1070. }
  1071. }
  1072. void compressVertexStream(std::string& bin, const std::string& data, size_t count, size_t stride)
  1073. {
  1074. assert(data.size() == count * stride);
  1075. std::vector<unsigned char> compressed(meshopt_encodeVertexBufferBound(count, stride));
  1076. size_t size = meshopt_encodeVertexBuffer(&compressed[0], compressed.size(), data.c_str(), count, stride);
  1077. bin.append(reinterpret_cast<const char*>(&compressed[0]), size);
  1078. }
  1079. void compressIndexStream(std::string& bin, const std::string& data, size_t count, size_t stride)
  1080. {
  1081. assert(stride == 2 || stride == 4);
  1082. assert(data.size() == count * stride);
  1083. std::vector<unsigned char> compressed(meshopt_encodeIndexBufferBound(count, count * 3));
  1084. size_t size = 0;
  1085. if (stride == 2)
  1086. size = meshopt_encodeIndexBuffer(&compressed[0], compressed.size(), reinterpret_cast<const uint16_t*>(data.c_str()), count);
  1087. else
  1088. size = meshopt_encodeIndexBuffer(&compressed[0], compressed.size(), reinterpret_cast<const uint32_t*>(data.c_str()), count);
  1089. bin.append(reinterpret_cast<const char*>(&compressed[0]), size);
  1090. }
  1091. void comma(std::string& s)
  1092. {
  1093. char ch = s.empty() ? 0 : s[s.size() - 1];
  1094. if (ch != 0 && ch != '[' && ch != '{')
  1095. s += ",";
  1096. }
  1097. void append(std::string& s, size_t v)
  1098. {
  1099. char buf[32];
  1100. sprintf(buf, "%zu", v);
  1101. s += buf;
  1102. }
  1103. void append(std::string& s, float v)
  1104. {
  1105. char buf[512];
  1106. sprintf(buf, "%.9g", v);
  1107. s += buf;
  1108. }
  1109. void append(std::string& s, const char* v)
  1110. {
  1111. s += v;
  1112. }
  1113. void append(std::string& s, const std::string& v)
  1114. {
  1115. s += v;
  1116. }
  1117. const char* componentType(cgltf_component_type type)
  1118. {
  1119. switch (type)
  1120. {
  1121. case cgltf_component_type_r_8:
  1122. return "5120";
  1123. case cgltf_component_type_r_8u:
  1124. return "5121";
  1125. case cgltf_component_type_r_16:
  1126. return "5122";
  1127. case cgltf_component_type_r_16u:
  1128. return "5123";
  1129. case cgltf_component_type_r_32u:
  1130. return "5125";
  1131. case cgltf_component_type_r_32f:
  1132. return "5126";
  1133. default:
  1134. return "0";
  1135. }
  1136. }
  1137. const char* shapeType(cgltf_type type)
  1138. {
  1139. switch (type)
  1140. {
  1141. case cgltf_type_scalar:
  1142. return "SCALAR";
  1143. case cgltf_type_vec2:
  1144. return "VEC2";
  1145. case cgltf_type_vec3:
  1146. return "VEC3";
  1147. case cgltf_type_vec4:
  1148. return "VEC4";
  1149. case cgltf_type_mat2:
  1150. return "MAT2";
  1151. case cgltf_type_mat3:
  1152. return "MAT3";
  1153. case cgltf_type_mat4:
  1154. return "MAT4";
  1155. default:
  1156. return "";
  1157. }
  1158. }
  1159. const char* attributeType(cgltf_attribute_type type)
  1160. {
  1161. switch (type)
  1162. {
  1163. case cgltf_attribute_type_position:
  1164. return "POSITION";
  1165. case cgltf_attribute_type_normal:
  1166. return "NORMAL";
  1167. case cgltf_attribute_type_tangent:
  1168. return "TANGENT";
  1169. case cgltf_attribute_type_texcoord:
  1170. return "TEXCOORD";
  1171. case cgltf_attribute_type_color:
  1172. return "COLOR";
  1173. case cgltf_attribute_type_joints:
  1174. return "JOINTS";
  1175. case cgltf_attribute_type_weights:
  1176. return "WEIGHTS";
  1177. default:
  1178. return "ATTRIBUTE";
  1179. }
  1180. }
  1181. const char* animationPath(cgltf_animation_path_type type)
  1182. {
  1183. switch (type)
  1184. {
  1185. case cgltf_animation_path_type_translation:
  1186. return "translation";
  1187. case cgltf_animation_path_type_rotation:
  1188. return "rotation";
  1189. case cgltf_animation_path_type_scale:
  1190. return "scale";
  1191. case cgltf_animation_path_type_weights:
  1192. return "weights";
  1193. default:
  1194. return "";
  1195. }
  1196. }
  1197. const char* lightType(cgltf_light_type type)
  1198. {
  1199. switch (type)
  1200. {
  1201. case cgltf_light_type_directional:
  1202. return "directional";
  1203. case cgltf_light_type_point:
  1204. return "point";
  1205. case cgltf_light_type_spot:
  1206. return "spot";
  1207. default:
  1208. return "";
  1209. }
  1210. }
  1211. void writeTextureInfo(std::string& json, const cgltf_data* data, const cgltf_texture_view& view, const QuantizationParams& qp)
  1212. {
  1213. assert(view.texture);
  1214. cgltf_texture_transform transform = {};
  1215. if (view.has_transform)
  1216. {
  1217. transform = view.transform;
  1218. }
  1219. else
  1220. {
  1221. transform.scale[0] = transform.scale[1] = 1.f;
  1222. }
  1223. transform.offset[0] += qp.uv_offset[0];
  1224. transform.offset[1] += qp.uv_offset[1];
  1225. transform.scale[0] *= qp.uv_scale[0] / float((1 << qp.uv_bits) - 1);
  1226. transform.scale[1] *= qp.uv_scale[1] / float((1 << qp.uv_bits) - 1);
  1227. append(json, "{\"index\":");
  1228. append(json, size_t(view.texture - data->textures));
  1229. append(json, ",\"texCoord\":");
  1230. append(json, size_t(view.texcoord));
  1231. append(json, ",\"extensions\":{\"KHR_texture_transform\":{");
  1232. append(json, "\"offset\":[");
  1233. append(json, transform.offset[0]);
  1234. append(json, ",");
  1235. append(json, transform.offset[1]);
  1236. append(json, "],\"scale\":[");
  1237. append(json, transform.scale[0]);
  1238. append(json, ",");
  1239. append(json, transform.scale[1]);
  1240. append(json, "]");
  1241. if (transform.rotation != 0.f)
  1242. {
  1243. append(json, ",\"rotation\":");
  1244. append(json, transform.rotation);
  1245. }
  1246. append(json, "}}}");
  1247. }
  1248. void writeMaterialInfo(std::string& json, const cgltf_data* data, const cgltf_material& material, const QuantizationParams& qp)
  1249. {
  1250. static const float white[4] = {1, 1, 1, 1};
  1251. static const float black[4] = {0, 0, 0, 0};
  1252. if (material.has_pbr_metallic_roughness)
  1253. {
  1254. const cgltf_pbr_metallic_roughness& pbr = material.pbr_metallic_roughness;
  1255. comma(json);
  1256. append(json, "\"pbrMetallicRoughness\":{");
  1257. if (memcmp(pbr.base_color_factor, white, 16) != 0)
  1258. {
  1259. comma(json);
  1260. append(json, "\"baseColorFactor\":[");
  1261. append(json, pbr.base_color_factor[0]);
  1262. append(json, ",");
  1263. append(json, pbr.base_color_factor[1]);
  1264. append(json, ",");
  1265. append(json, pbr.base_color_factor[2]);
  1266. append(json, ",");
  1267. append(json, pbr.base_color_factor[3]);
  1268. append(json, "]");
  1269. }
  1270. if (pbr.base_color_texture.texture)
  1271. {
  1272. comma(json);
  1273. append(json, "\"baseColorTexture\":");
  1274. writeTextureInfo(json, data, pbr.base_color_texture, qp);
  1275. }
  1276. if (pbr.metallic_factor != 1)
  1277. {
  1278. comma(json);
  1279. append(json, "\"metallicFactor\":");
  1280. append(json, pbr.metallic_factor);
  1281. }
  1282. if (pbr.roughness_factor != 1)
  1283. {
  1284. comma(json);
  1285. append(json, "\"roughnessFactor\":");
  1286. append(json, pbr.roughness_factor);
  1287. }
  1288. if (pbr.metallic_roughness_texture.texture)
  1289. {
  1290. comma(json);
  1291. append(json, "\"metallicRoughnessTexture\":");
  1292. writeTextureInfo(json, data, pbr.metallic_roughness_texture, qp);
  1293. }
  1294. append(json, "}");
  1295. }
  1296. if (material.normal_texture.texture)
  1297. {
  1298. comma(json);
  1299. append(json, "\"normalTexture\":");
  1300. writeTextureInfo(json, data, material.normal_texture, qp);
  1301. }
  1302. if (material.occlusion_texture.texture)
  1303. {
  1304. comma(json);
  1305. append(json, "\"occlusionTexture\":");
  1306. writeTextureInfo(json, data, material.occlusion_texture, qp);
  1307. }
  1308. if (material.emissive_texture.texture)
  1309. {
  1310. comma(json);
  1311. append(json, "\"emissiveTexture\":");
  1312. writeTextureInfo(json, data, material.emissive_texture, qp);
  1313. }
  1314. if (memcmp(material.emissive_factor, black, 12) != 0)
  1315. {
  1316. comma(json);
  1317. append(json, "\"emissiveFactor\":[");
  1318. append(json, material.emissive_factor[0]);
  1319. append(json, ",");
  1320. append(json, material.emissive_factor[1]);
  1321. append(json, ",");
  1322. append(json, material.emissive_factor[2]);
  1323. append(json, "]");
  1324. }
  1325. if (material.alpha_mode != cgltf_alpha_mode_opaque)
  1326. {
  1327. comma(json);
  1328. append(json, "\"alphaMode\":");
  1329. append(json, (material.alpha_mode == cgltf_alpha_mode_blend) ? "\"BLEND\"" : "\"MASK\"");
  1330. }
  1331. if (material.alpha_cutoff != 0.5f)
  1332. {
  1333. comma(json);
  1334. append(json, "\"alphaCutoff\":");
  1335. append(json, material.alpha_cutoff);
  1336. }
  1337. if (material.double_sided)
  1338. {
  1339. comma(json);
  1340. append(json, "\"doubleSided\":true");
  1341. }
  1342. if (material.has_pbr_specular_glossiness || material.unlit)
  1343. {
  1344. comma(json);
  1345. append(json, "\"extensions\":{");
  1346. if (material.has_pbr_specular_glossiness)
  1347. {
  1348. const cgltf_pbr_specular_glossiness& pbr = material.pbr_specular_glossiness;
  1349. comma(json);
  1350. append(json, "\"KHR_materials_pbrSpecularGlossiness\":{");
  1351. if (pbr.diffuse_texture.texture)
  1352. {
  1353. comma(json);
  1354. append(json, "\"diffuseTexture\":");
  1355. writeTextureInfo(json, data, pbr.diffuse_texture, qp);
  1356. }
  1357. if (pbr.specular_glossiness_texture.texture)
  1358. {
  1359. comma(json);
  1360. append(json, "\"specularGlossinessTexture\":");
  1361. writeTextureInfo(json, data, pbr.specular_glossiness_texture, qp);
  1362. }
  1363. if (memcmp(pbr.diffuse_factor, white, 16) != 0)
  1364. {
  1365. comma(json);
  1366. append(json, "\"diffuseFactor\":[");
  1367. append(json, pbr.diffuse_factor[0]);
  1368. append(json, ",");
  1369. append(json, pbr.diffuse_factor[1]);
  1370. append(json, ",");
  1371. append(json, pbr.diffuse_factor[2]);
  1372. append(json, ",");
  1373. append(json, pbr.diffuse_factor[3]);
  1374. append(json, "]");
  1375. }
  1376. if (memcmp(pbr.specular_factor, white, 12) != 0)
  1377. {
  1378. comma(json);
  1379. append(json, "\"specularFactor\":[");
  1380. append(json, pbr.specular_factor[0]);
  1381. append(json, ",");
  1382. append(json, pbr.specular_factor[1]);
  1383. append(json, ",");
  1384. append(json, pbr.specular_factor[2]);
  1385. append(json, "]");
  1386. }
  1387. if (pbr.glossiness_factor != 1)
  1388. {
  1389. comma(json);
  1390. append(json, "\"glossinessFactor\":");
  1391. append(json, pbr.glossiness_factor);
  1392. }
  1393. append(json, "}");
  1394. }
  1395. if (material.unlit)
  1396. {
  1397. comma(json);
  1398. append(json, "\"KHR_materials_unlit\":{}");
  1399. }
  1400. append(json, "}");
  1401. }
  1402. }
  1403. bool usesTextureSet(const cgltf_material& material, int set)
  1404. {
  1405. if (material.has_pbr_metallic_roughness)
  1406. {
  1407. const cgltf_pbr_metallic_roughness& pbr = material.pbr_metallic_roughness;
  1408. if (pbr.base_color_texture.texture && pbr.base_color_texture.texcoord == set)
  1409. return true;
  1410. if (pbr.metallic_roughness_texture.texture && pbr.metallic_roughness_texture.texcoord == set)
  1411. return true;
  1412. }
  1413. if (material.has_pbr_specular_glossiness)
  1414. {
  1415. const cgltf_pbr_specular_glossiness& pbr = material.pbr_specular_glossiness;
  1416. if (pbr.diffuse_texture.texture && pbr.diffuse_texture.texcoord == set)
  1417. return true;
  1418. if (pbr.specular_glossiness_texture.texture && pbr.specular_glossiness_texture.texcoord == set)
  1419. return true;
  1420. }
  1421. if (material.normal_texture.texture && material.normal_texture.texcoord == set)
  1422. return true;
  1423. if (material.occlusion_texture.texture && material.occlusion_texture.texcoord == set)
  1424. return true;
  1425. if (material.emissive_texture.texture && material.emissive_texture.texcoord == set)
  1426. return true;
  1427. return false;
  1428. }
  1429. size_t getBufferView(std::vector<BufferView>& views, BufferView::Kind kind, int variant, size_t stride, bool compressed)
  1430. {
  1431. if (variant >= 0)
  1432. {
  1433. for (size_t i = 0; i < views.size(); ++i)
  1434. if (views[i].kind == kind && views[i].variant == variant && views[i].stride == stride && views[i].compressed == compressed)
  1435. return i;
  1436. }
  1437. BufferView view = {kind, variant, stride, compressed};
  1438. views.push_back(view);
  1439. return views.size() - 1;
  1440. }
  1441. void writeBufferView(std::string& json, BufferView::Kind kind, size_t count, size_t stride, size_t bin_offset, size_t bin_size, int compression)
  1442. {
  1443. append(json, "{\"buffer\":0");
  1444. append(json, ",\"byteLength\":");
  1445. append(json, bin_size);
  1446. append(json, ",\"byteOffset\":");
  1447. append(json, bin_offset);
  1448. if (kind == BufferView::Kind_Vertex)
  1449. {
  1450. append(json, ",\"byteStride\":");
  1451. append(json, stride);
  1452. }
  1453. if (kind == BufferView::Kind_Vertex || kind == BufferView::Kind_Index)
  1454. {
  1455. append(json, ",\"target\":");
  1456. append(json, (kind == BufferView::Kind_Vertex) ? "34962" : "34963");
  1457. }
  1458. if (compression >= 0)
  1459. {
  1460. append(json, ",\"extensions\":{");
  1461. append(json, "\"MESHOPT_compression\":{");
  1462. append(json, "\"mode\":");
  1463. append(json, size_t(compression));
  1464. append(json, ",\"count\":");
  1465. append(json, count);
  1466. append(json, ",\"byteStride\":");
  1467. append(json, stride);
  1468. append(json, "}}");
  1469. }
  1470. append(json, "}");
  1471. }
  1472. 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)
  1473. {
  1474. append(json, "{\"bufferView\":");
  1475. append(json, view);
  1476. append(json, ",\"byteOffset\":");
  1477. append(json, offset);
  1478. append(json, ",\"componentType\":");
  1479. append(json, componentType(component_type));
  1480. append(json, ",\"count\":");
  1481. append(json, count);
  1482. append(json, ",\"type\":\"");
  1483. append(json, shapeType(type));
  1484. append(json, "\"");
  1485. if (normalized)
  1486. {
  1487. append(json, ",\"normalized\":true");
  1488. }
  1489. if (min && max)
  1490. {
  1491. assert(numminmax);
  1492. append(json, ",\"min\":[");
  1493. for (size_t k = 0; k < numminmax; ++k)
  1494. {
  1495. comma(json);
  1496. append(json, min[k]);
  1497. }
  1498. append(json, "],\"max\":[");
  1499. for (size_t k = 0; k < numminmax; ++k)
  1500. {
  1501. comma(json);
  1502. append(json, max[k]);
  1503. }
  1504. append(json, "]");
  1505. }
  1506. append(json, "}");
  1507. }
  1508. float getDelta(const Attr& l, const Attr& r, cgltf_animation_path_type type)
  1509. {
  1510. if (type == cgltf_animation_path_type_rotation)
  1511. {
  1512. 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]);
  1513. return error;
  1514. }
  1515. else
  1516. {
  1517. float error = 0;
  1518. for (int k = 0; k < 4; ++k)
  1519. error += fabsf(r.f[k] - l.f[k]);
  1520. return error;
  1521. }
  1522. }
  1523. bool isTrackConstant(const cgltf_animation_sampler& sampler, cgltf_animation_path_type type, cgltf_node* target_node)
  1524. {
  1525. const float tolerance = 1e-3f;
  1526. size_t value_stride = (sampler.interpolation == cgltf_interpolation_type_cubic_spline) ? 3 : 1;
  1527. size_t value_offset = (sampler.interpolation == cgltf_interpolation_type_cubic_spline) ? 1 : 0;
  1528. size_t components = (type == cgltf_animation_path_type_weights) ? target_node->mesh->primitives[0].targets_count : 1;
  1529. assert(sampler.input->count * value_stride * components == sampler.output->count);
  1530. for (size_t j = 0; j < components; ++j)
  1531. {
  1532. Attr first = {};
  1533. cgltf_accessor_read_float(sampler.output, j * value_stride + value_offset, first.f, 4);
  1534. for (size_t i = 1; i < sampler.input->count; ++i)
  1535. {
  1536. Attr attr = {};
  1537. cgltf_accessor_read_float(sampler.output, (i * components + j) * value_stride + value_offset, attr.f, 4);
  1538. if (getDelta(first, attr, type) > tolerance)
  1539. return false;
  1540. }
  1541. if (sampler.interpolation == cgltf_interpolation_type_cubic_spline)
  1542. {
  1543. for (size_t i = 0; i < sampler.input->count; ++i)
  1544. {
  1545. for (int k = 0; k < 2; ++k)
  1546. {
  1547. Attr t = {};
  1548. cgltf_accessor_read_float(sampler.output, (i * components + j) * 3 + k * 2, t.f, 4);
  1549. float error = fabsf(t.f[0]) + fabsf(t.f[1]) + fabsf(t.f[2]) + fabsf(t.f[3]);
  1550. if (error > tolerance)
  1551. return false;
  1552. }
  1553. }
  1554. }
  1555. }
  1556. return true;
  1557. }
  1558. Attr interpolateLinear(const Attr& l, const Attr& r, float t, cgltf_animation_path_type type)
  1559. {
  1560. if (type == cgltf_animation_path_type_rotation)
  1561. {
  1562. // Approximating slerp, https://zeux.io/2015/07/23/approximating-slerp/
  1563. // We also handle quaternion double-cover
  1564. 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];
  1565. float d = fabsf(ca);
  1566. float A = 1.0904f + d * (-3.2452f + d * (3.55645f - d * 1.43519f));
  1567. float B = 0.848013f + d * (-1.06021f + d * 0.215638f);
  1568. float k = A * (t - 0.5f) * (t - 0.5f) + B;
  1569. float ot = t + t * (t - 0.5f) * (t - 1) * k;
  1570. float t0 = 1 - ot;
  1571. float t1 = ca > 0 ? ot : -ot;
  1572. Attr lerp = {{
  1573. l.f[0] * t0 + r.f[0] * t1,
  1574. l.f[1] * t0 + r.f[1] * t1,
  1575. l.f[2] * t0 + r.f[2] * t1,
  1576. l.f[3] * t0 + r.f[3] * t1,
  1577. }};
  1578. 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]);
  1579. if (len > 0.f)
  1580. {
  1581. lerp.f[0] /= len;
  1582. lerp.f[1] /= len;
  1583. lerp.f[2] /= len;
  1584. lerp.f[3] /= len;
  1585. }
  1586. return lerp;
  1587. }
  1588. else
  1589. {
  1590. Attr lerp = {{
  1591. l.f[0] * (1 - t) + r.f[0] * t,
  1592. l.f[1] * (1 - t) + r.f[1] * t,
  1593. l.f[2] * (1 - t) + r.f[2] * t,
  1594. l.f[3] * (1 - t) + r.f[3] * t,
  1595. }};
  1596. return lerp;
  1597. }
  1598. }
  1599. Attr interpolateHermite(const Attr& v0, const Attr& t0, const Attr& v1, const Attr& t1, float t, float dt, cgltf_animation_path_type type)
  1600. {
  1601. float s0 = 1 + t * t * (2 * t - 3);
  1602. float s1 = t + t * t * (t - 2);
  1603. float s2 = 1 - s0;
  1604. float s3 = t * t * (t - 1);
  1605. float ts1 = dt * s1;
  1606. float ts3 = dt * s3;
  1607. Attr lerp = {{
  1608. s0 * v0.f[0] + ts1 * t0.f[0] + s2 * v1.f[0] + ts3 * t1.f[0],
  1609. s0 * v0.f[1] + ts1 * t0.f[1] + s2 * v1.f[1] + ts3 * t1.f[1],
  1610. s0 * v0.f[2] + ts1 * t0.f[2] + s2 * v1.f[2] + ts3 * t1.f[2],
  1611. s0 * v0.f[3] + ts1 * t0.f[3] + s2 * v1.f[3] + ts3 * t1.f[3],
  1612. }};
  1613. if (type == cgltf_animation_path_type_rotation)
  1614. {
  1615. 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]);
  1616. if (len > 0.f)
  1617. {
  1618. lerp.f[0] /= len;
  1619. lerp.f[1] /= len;
  1620. lerp.f[2] /= len;
  1621. lerp.f[3] /= len;
  1622. }
  1623. }
  1624. return lerp;
  1625. }
  1626. 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)
  1627. {
  1628. size_t components = (type == cgltf_animation_path_type_weights) ? target_node->mesh->primitives[0].targets_count : 1;
  1629. size_t cursor = 0;
  1630. for (int i = 0; i < frames; ++i)
  1631. {
  1632. float time = mint + float(i) / freq;
  1633. while (cursor + 1 < sampler.input->count)
  1634. {
  1635. float next_time = 0;
  1636. cgltf_accessor_read_float(sampler.input, cursor + 1, &next_time, 1);
  1637. if (next_time > time)
  1638. break;
  1639. cursor++;
  1640. }
  1641. if (cursor + 1 < sampler.input->count)
  1642. {
  1643. float cursor_time = 0;
  1644. float next_time = 0;
  1645. cgltf_accessor_read_float(sampler.input, cursor + 0, &cursor_time, 1);
  1646. cgltf_accessor_read_float(sampler.input, cursor + 1, &next_time, 1);
  1647. float range = next_time - cursor_time;
  1648. float inv_range = (range == 0.f) ? 0.f : 1.f / (next_time - cursor_time);
  1649. float t = std::max(0.f, std::min(1.f, (time - cursor_time) * inv_range));
  1650. for (size_t j = 0; j < components; ++j)
  1651. {
  1652. switch (sampler.interpolation)
  1653. {
  1654. case cgltf_interpolation_type_linear:
  1655. {
  1656. Attr v0 = {};
  1657. Attr v1 = {};
  1658. cgltf_accessor_read_float(sampler.output, (cursor + 0) * components + j, v0.f, 4);
  1659. cgltf_accessor_read_float(sampler.output, (cursor + 1) * components + j, v1.f, 4);
  1660. data.push_back(interpolateLinear(v0, v1, t, type));
  1661. }
  1662. break;
  1663. case cgltf_interpolation_type_step:
  1664. {
  1665. Attr v = {};
  1666. cgltf_accessor_read_float(sampler.output, cursor * components + j, v.f, 4);
  1667. data.push_back(v);
  1668. }
  1669. break;
  1670. case cgltf_interpolation_type_cubic_spline:
  1671. {
  1672. Attr v0 = {};
  1673. Attr b0 = {};
  1674. Attr a1 = {};
  1675. Attr v1 = {};
  1676. cgltf_accessor_read_float(sampler.output, (cursor * 3 + 1) * components + j, v0.f, 4);
  1677. cgltf_accessor_read_float(sampler.output, (cursor * 3 + 2) * components + j, b0.f, 4);
  1678. cgltf_accessor_read_float(sampler.output, (cursor * 3 + 3) * components + j, a1.f, 4);
  1679. cgltf_accessor_read_float(sampler.output, (cursor * 3 + 4) * components + j, v1.f, 4);
  1680. data.push_back(interpolateHermite(v0, b0, v1, a1, t, range, type));
  1681. }
  1682. break;
  1683. default:
  1684. assert(!"Unknown interpolation type");
  1685. }
  1686. }
  1687. }
  1688. else
  1689. {
  1690. size_t offset = (sampler.interpolation == cgltf_interpolation_type_cubic_spline) ? cursor * 3 + 1 : cursor;
  1691. for (size_t j = 0; j < components; ++j)
  1692. {
  1693. Attr v = {};
  1694. cgltf_accessor_read_float(sampler.output, offset * components + j, v.f, 4);
  1695. data.push_back(v);
  1696. }
  1697. }
  1698. }
  1699. }
  1700. void markAnimated(cgltf_data* data, std::vector<NodeInfo>& nodes)
  1701. {
  1702. for (size_t i = 0; i < data->animations_count; ++i)
  1703. {
  1704. const cgltf_animation& animation = data->animations[i];
  1705. for (size_t j = 0; j < animation.channels_count; ++j)
  1706. {
  1707. const cgltf_animation_channel& channel = animation.channels[j];
  1708. const cgltf_animation_sampler& sampler = *channel.sampler;
  1709. if (!channel.target_node)
  1710. continue;
  1711. NodeInfo& ni = nodes[channel.target_node - data->nodes];
  1712. // mark nodes that have animation tracks that change their base transform as animated
  1713. if (!isTrackConstant(sampler, channel.target_path, channel.target_node))
  1714. {
  1715. ni.animated_paths |= (1 << channel.target_path);
  1716. }
  1717. else
  1718. {
  1719. Attr base = {};
  1720. switch (channel.target_path)
  1721. {
  1722. case cgltf_animation_path_type_translation:
  1723. memcpy(base.f, channel.target_node->translation, 3 * sizeof(float));
  1724. break;
  1725. case cgltf_animation_path_type_rotation:
  1726. memcpy(base.f, channel.target_node->rotation, 4 * sizeof(float));
  1727. break;
  1728. case cgltf_animation_path_type_scale:
  1729. memcpy(base.f, channel.target_node->scale, 3 * sizeof(float));
  1730. break;
  1731. default:;
  1732. }
  1733. Attr first = {};
  1734. cgltf_accessor_read_float(sampler.output, 0, first.f, 4);
  1735. const float tolerance = 1e-3f;
  1736. if (getDelta(base, first, channel.target_path) > tolerance)
  1737. {
  1738. ni.animated_paths |= (1 << channel.target_path);
  1739. }
  1740. }
  1741. }
  1742. }
  1743. for (size_t i = 0; i < data->nodes_count; ++i)
  1744. {
  1745. NodeInfo& ni = nodes[i];
  1746. for (cgltf_node* node = &data->nodes[i]; node; node = node->parent)
  1747. ni.animated |= nodes[node - data->nodes].animated_paths != 0;
  1748. }
  1749. }
  1750. void markNeededNodes(cgltf_data* data, std::vector<NodeInfo>& nodes, const std::vector<Mesh>& meshes, const Settings& settings)
  1751. {
  1752. // mark all joints as kept
  1753. for (size_t i = 0; i < data->skins_count; ++i)
  1754. {
  1755. const cgltf_skin& skin = data->skins[i];
  1756. // for now we keep all joints directly referenced by the skin and the entire ancestry tree; we keep names for joints as well
  1757. for (size_t j = 0; j < skin.joints_count; ++j)
  1758. {
  1759. NodeInfo& ni = nodes[skin.joints[j] - data->nodes];
  1760. ni.keep = true;
  1761. }
  1762. }
  1763. // mark all animated nodes as kept
  1764. for (size_t i = 0; i < data->animations_count; ++i)
  1765. {
  1766. const cgltf_animation& animation = data->animations[i];
  1767. for (size_t j = 0; j < animation.channels_count; ++j)
  1768. {
  1769. const cgltf_animation_channel& channel = animation.channels[j];
  1770. if (channel.target_node)
  1771. {
  1772. NodeInfo& ni = nodes[channel.target_node - data->nodes];
  1773. ni.keep = true;
  1774. }
  1775. }
  1776. }
  1777. // mark all mesh nodes as kept
  1778. for (size_t i = 0; i < meshes.size(); ++i)
  1779. {
  1780. const Mesh& mesh = meshes[i];
  1781. if (mesh.node)
  1782. {
  1783. NodeInfo& ni = nodes[mesh.node - data->nodes];
  1784. ni.keep = true;
  1785. }
  1786. }
  1787. // mark all light/camera nodes as kept
  1788. for (size_t i = 0; i < data->nodes_count; ++i)
  1789. {
  1790. const cgltf_node& node = data->nodes[i];
  1791. if (node.light || node.camera)
  1792. {
  1793. nodes[i].keep = true;
  1794. }
  1795. }
  1796. // mark all named nodes as needed (if -kn is specified)
  1797. if (settings.keep_named)
  1798. {
  1799. for (size_t i = 0; i < data->nodes_count; ++i)
  1800. {
  1801. const cgltf_node& node = data->nodes[i];
  1802. if (node.name && *node.name)
  1803. {
  1804. nodes[i].keep = true;
  1805. }
  1806. }
  1807. }
  1808. }
  1809. void markNeededMaterials(cgltf_data* data, std::vector<MaterialInfo>& materials, const std::vector<Mesh>& meshes)
  1810. {
  1811. // mark all used materials as kept
  1812. for (size_t i = 0; i < meshes.size(); ++i)
  1813. {
  1814. const Mesh& mesh = meshes[i];
  1815. if (mesh.material)
  1816. {
  1817. MaterialInfo& mi = materials[mesh.material - data->materials];
  1818. mi.keep = true;
  1819. }
  1820. }
  1821. }
  1822. void remapNodes(cgltf_data* data, std::vector<NodeInfo>& nodes, size_t& node_offset)
  1823. {
  1824. // to keep a node, we currently need to keep the entire ancestry chain
  1825. for (size_t i = 0; i < data->nodes_count; ++i)
  1826. {
  1827. if (!nodes[i].keep)
  1828. continue;
  1829. for (cgltf_node* node = &data->nodes[i]; node; node = node->parent)
  1830. nodes[node - data->nodes].keep = true;
  1831. }
  1832. // generate sequential indices for all nodes; they aren't sorted topologically
  1833. for (size_t i = 0; i < data->nodes_count; ++i)
  1834. {
  1835. NodeInfo& ni = nodes[i];
  1836. if (ni.keep)
  1837. {
  1838. ni.remap = int(node_offset);
  1839. node_offset++;
  1840. }
  1841. }
  1842. }
  1843. bool parseDataUri(const char* uri, std::string& mime_type, std::string& result)
  1844. {
  1845. if (strncmp(uri, "data:", 5) == 0)
  1846. {
  1847. const char* comma = strchr(uri, ',');
  1848. if (comma && comma - uri >= 7 && strncmp(comma - 7, ";base64", 7) == 0)
  1849. {
  1850. const char* base64 = comma + 1;
  1851. size_t base64_size = strlen(base64);
  1852. size_t size = base64_size - base64_size / 4;
  1853. if (base64_size >= 2)
  1854. {
  1855. size -= base64[base64_size - 2] == '=';
  1856. size -= base64[base64_size - 1] == '=';
  1857. }
  1858. void* data = 0;
  1859. cgltf_options options = {};
  1860. cgltf_result res = cgltf_load_buffer_base64(&options, size, base64, &data);
  1861. if (res != cgltf_result_success)
  1862. return false;
  1863. mime_type = std::string(uri + 5, comma - 7);
  1864. result = std::string(static_cast<const char*>(data), size);
  1865. free(data);
  1866. return true;
  1867. }
  1868. }
  1869. return false;
  1870. }
  1871. void writeEmbeddedImage(std::string& json, std::vector<BufferView>& views, const char* data, size_t size, const char* mime_type)
  1872. {
  1873. size_t view = getBufferView(views, BufferView::Kind_Image, -1, 1, false);
  1874. assert(views[view].data.empty());
  1875. views[view].data.assign(data, size);
  1876. append(json, "\"bufferView\":");
  1877. append(json, view);
  1878. append(json, ",\"mimeType\":\"");
  1879. append(json, mime_type);
  1880. append(json, "\"");
  1881. }
  1882. 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)
  1883. {
  1884. std::string scratch;
  1885. for (size_t j = 0; j < mesh.streams.size(); ++j)
  1886. {
  1887. const Stream& stream = mesh.streams[j];
  1888. if (stream.target != target)
  1889. continue;
  1890. if (stream.type == cgltf_attribute_type_texcoord && (!mesh.material || !usesTextureSet(*mesh.material, stream.index)))
  1891. continue;
  1892. if (stream.type == cgltf_attribute_type_tangent && (!mesh.material || !mesh.material->normal_texture.texture))
  1893. continue;
  1894. if ((stream.type == cgltf_attribute_type_joints || stream.type == cgltf_attribute_type_weights) && !mesh.skin)
  1895. continue;
  1896. scratch.clear();
  1897. StreamFormat format = writeVertexStream(scratch, stream, qp, settings, mesh.targets > 0);
  1898. size_t view = getBufferView(views, BufferView::Kind_Vertex, stream.type, format.stride, settings.compress);
  1899. size_t offset = views[view].data.size();
  1900. views[view].data += scratch;
  1901. comma(json_accessors);
  1902. if (stream.type == cgltf_attribute_type_position)
  1903. {
  1904. int min[3] = {};
  1905. int max[3] = {};
  1906. getPositionBounds(min, max, stream, qp);
  1907. float minf[3] = {float(min[0]), float(min[1]), float(min[2])};
  1908. float maxf[3] = {float(max[0]), float(max[1]), float(max[2])};
  1909. writeAccessor(json_accessors, view, offset, format.type, format.component_type, format.normalized, stream.data.size(), minf, maxf, 3);
  1910. }
  1911. else
  1912. {
  1913. writeAccessor(json_accessors, view, offset, format.type, format.component_type, format.normalized, stream.data.size());
  1914. }
  1915. size_t vertex_accr = accr_offset++;
  1916. comma(json);
  1917. append(json, "\"");
  1918. append(json, attributeType(stream.type));
  1919. if (stream.type != cgltf_attribute_type_position && stream.type != cgltf_attribute_type_normal && stream.type != cgltf_attribute_type_tangent)
  1920. {
  1921. append(json, "_");
  1922. append(json, size_t(stream.index));
  1923. }
  1924. append(json, "\":");
  1925. append(json, vertex_accr);
  1926. }
  1927. }
  1928. size_t writeMeshIndices(std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, const Mesh& mesh, const Settings& settings)
  1929. {
  1930. std::string scratch;
  1931. StreamFormat format = writeIndexStream(scratch, mesh.indices);
  1932. // note: we prefer to merge all index streams together; however, index codec currently doesn't handle concatenated index streams well and loses compression ratio
  1933. int variant = settings.compress ? -1 : 0;
  1934. size_t view = getBufferView(views, BufferView::Kind_Index, variant, format.stride, settings.compress);
  1935. size_t offset = views[view].data.size();
  1936. views[view].data += scratch;
  1937. comma(json_accessors);
  1938. writeAccessor(json_accessors, view, offset, format.type, format.component_type, format.normalized, mesh.indices.size());
  1939. size_t index_accr = accr_offset++;
  1940. return index_accr;
  1941. }
  1942. size_t writeAnimationTime(std::vector<BufferView>& views, std::string& json_accessors, size_t& accr_offset, float mint, int frames, const Settings& settings)
  1943. {
  1944. std::vector<float> time(frames);
  1945. for (int j = 0; j < frames; ++j)
  1946. time[j] = mint + float(j) / settings.anim_freq;
  1947. std::string scratch;
  1948. StreamFormat format = writeTimeStream(scratch, time);
  1949. size_t view = getBufferView(views, BufferView::Kind_Time, 0, format.stride, settings.compress);
  1950. size_t offset = views[view].data.size();
  1951. views[view].data += scratch;
  1952. comma(json_accessors);
  1953. writeAccessor(json_accessors, view, offset, cgltf_type_scalar, format.component_type, format.normalized, frames, &time.front(), &time.back(), 1);
  1954. size_t time_accr = accr_offset++;
  1955. return time_accr;
  1956. }
  1957. 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)
  1958. {
  1959. std::string scratch;
  1960. for (size_t j = 0; j < skin.joints_count; ++j)
  1961. {
  1962. float transform[16] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};
  1963. if (skin.inverse_bind_matrices)
  1964. {
  1965. cgltf_accessor_read_float(skin.inverse_bind_matrices, j, transform, 16);
  1966. }
  1967. float node_scale = qp.pos_scale / float((1 << qp.pos_bits) - 1);
  1968. // pos_offset has to be applied first, thus it results in an offset rotated by the bind matrix
  1969. transform[12] += qp.pos_offset[0] * transform[0] + qp.pos_offset[1] * transform[4] + qp.pos_offset[2] * transform[8];
  1970. transform[13] += qp.pos_offset[0] * transform[1] + qp.pos_offset[1] * transform[5] + qp.pos_offset[2] * transform[9];
  1971. transform[14] += qp.pos_offset[0] * transform[2] + qp.pos_offset[1] * transform[6] + qp.pos_offset[2] * transform[10];
  1972. // node_scale will be applied before the rotation/scale from transform
  1973. for (int k = 0; k < 12; ++k)
  1974. transform[k] *= node_scale;
  1975. scratch.append(reinterpret_cast<const char*>(transform), sizeof(transform));
  1976. }
  1977. size_t view = getBufferView(views, BufferView::Kind_Skin, 0, 64, settings.compress);
  1978. size_t offset = views[view].data.size();
  1979. views[view].data += scratch;
  1980. comma(json_accessors);
  1981. writeAccessor(json_accessors, view, offset, cgltf_type_mat4, cgltf_component_type_r_32f, false, skin.joints_count);
  1982. size_t matrix_accr = accr_offset++;
  1983. return matrix_accr;
  1984. }
  1985. void writeMeshNode(std::string& json, size_t mesh_offset, const Mesh& mesh, cgltf_data* data, const QuantizationParams& qp)
  1986. {
  1987. float node_scale = qp.pos_scale / float((1 << qp.pos_bits) - 1);
  1988. comma(json);
  1989. append(json, "{\"mesh\":");
  1990. append(json, mesh_offset);
  1991. if (mesh.skin)
  1992. {
  1993. comma(json);
  1994. append(json, "\"skin\":");
  1995. append(json, size_t(mesh.skin - data->skins));
  1996. }
  1997. append(json, ",\"translation\":[");
  1998. append(json, qp.pos_offset[0]);
  1999. append(json, ",");
  2000. append(json, qp.pos_offset[1]);
  2001. append(json, ",");
  2002. append(json, qp.pos_offset[2]);
  2003. append(json, "],\"scale\":[");
  2004. append(json, node_scale);
  2005. append(json, ",");
  2006. append(json, node_scale);
  2007. append(json, ",");
  2008. append(json, node_scale);
  2009. append(json, "]");
  2010. if (mesh.node && mesh.node->weights_count)
  2011. {
  2012. append(json, ",\"weights\":[");
  2013. for (size_t j = 0; j < mesh.node->weights_count; ++j)
  2014. {
  2015. comma(json);
  2016. append(json, mesh.node->weights[j]);
  2017. }
  2018. append(json, "]");
  2019. }
  2020. append(json, "}");
  2021. }
  2022. void writeNode(std::string& json, const cgltf_node& node, const std::vector<NodeInfo>& nodes, cgltf_data* data)
  2023. {
  2024. const NodeInfo& ni = nodes[&node - data->nodes];
  2025. comma(json);
  2026. append(json, "{");
  2027. if (node.name && *node.name)
  2028. {
  2029. comma(json);
  2030. append(json, "\"name\":\"");
  2031. append(json, node.name);
  2032. append(json, "\"");
  2033. }
  2034. if (node.has_translation)
  2035. {
  2036. comma(json);
  2037. append(json, "\"translation\":[");
  2038. append(json, node.translation[0]);
  2039. append(json, ",");
  2040. append(json, node.translation[1]);
  2041. append(json, ",");
  2042. append(json, node.translation[2]);
  2043. append(json, "]");
  2044. }
  2045. if (node.has_rotation)
  2046. {
  2047. comma(json);
  2048. append(json, "\"rotation\":[");
  2049. append(json, node.rotation[0]);
  2050. append(json, ",");
  2051. append(json, node.rotation[1]);
  2052. append(json, ",");
  2053. append(json, node.rotation[2]);
  2054. append(json, ",");
  2055. append(json, node.rotation[3]);
  2056. append(json, "]");
  2057. }
  2058. if (node.has_scale)
  2059. {
  2060. comma(json);
  2061. append(json, "\"scale\":[");
  2062. append(json, node.scale[0]);
  2063. append(json, ",");
  2064. append(json, node.scale[1]);
  2065. append(json, ",");
  2066. append(json, node.scale[2]);
  2067. append(json, "]");
  2068. }
  2069. if (node.has_matrix)
  2070. {
  2071. comma(json);
  2072. append(json, "\"matrix\":[");
  2073. for (int k = 0; k < 16; ++k)
  2074. {
  2075. comma(json);
  2076. append(json, node.matrix[k]);
  2077. }
  2078. append(json, "]");
  2079. }
  2080. if (node.children_count || !ni.meshes.empty())
  2081. {
  2082. comma(json);
  2083. append(json, "\"children\":[");
  2084. for (size_t j = 0; j < node.children_count; ++j)
  2085. {
  2086. const NodeInfo& ci = nodes[node.children[j] - data->nodes];
  2087. if (ci.keep)
  2088. {
  2089. comma(json);
  2090. append(json, size_t(ci.remap));
  2091. }
  2092. }
  2093. for (size_t j = 0; j < ni.meshes.size(); ++j)
  2094. {
  2095. comma(json);
  2096. append(json, ni.meshes[j]);
  2097. }
  2098. append(json, "]");
  2099. }
  2100. if (node.camera)
  2101. {
  2102. comma(json);
  2103. append(json, "\"camera\":");
  2104. append(json, size_t(node.camera - data->cameras));
  2105. }
  2106. if (node.light)
  2107. {
  2108. comma(json);
  2109. append(json, "\"extensions\":{\"KHR_lights_punctual\":{\"light\":");
  2110. append(json, size_t(node.light - data->lights));
  2111. append(json, "}}");
  2112. }
  2113. append(json, "}");
  2114. }
  2115. 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)
  2116. {
  2117. std::vector<const cgltf_animation_channel*> tracks;
  2118. for (size_t j = 0; j < animation.channels_count; ++j)
  2119. {
  2120. const cgltf_animation_channel& channel = animation.channels[j];
  2121. if (!channel.target_node)
  2122. {
  2123. fprintf(stderr, "Warning: ignoring channel %d of animation %d because it has no target node\n", int(j), int(&animation - data->animations));
  2124. continue;
  2125. }
  2126. const NodeInfo& ni = nodes[channel.target_node - data->nodes];
  2127. if (!ni.keep)
  2128. continue;
  2129. if (!settings.anim_const && (ni.animated_paths & (1 << channel.target_path)) == 0)
  2130. continue;
  2131. tracks.push_back(&channel);
  2132. }
  2133. if (tracks.empty())
  2134. {
  2135. fprintf(stderr, "Warning: ignoring animation %d because it has no valid tracks\n", int(&animation - data->animations));
  2136. return;
  2137. }
  2138. float mint = 0, maxt = 0;
  2139. bool needs_time = false;
  2140. bool needs_pose = false;
  2141. for (size_t j = 0; j < tracks.size(); ++j)
  2142. {
  2143. const cgltf_animation_channel& channel = *tracks[j];
  2144. const cgltf_animation_sampler& sampler = *channel.sampler;
  2145. mint = std::min(mint, sampler.input->min[0]);
  2146. maxt = std::max(maxt, sampler.input->max[0]);
  2147. bool tc = isTrackConstant(sampler, channel.target_path, channel.target_node);
  2148. needs_time = needs_time || !tc;
  2149. needs_pose = needs_pose || tc;
  2150. }
  2151. // round the number of frames to nearest but favor the "up" direction
  2152. // this means that at 10 Hz resampling, we will try to preserve the last frame <10ms
  2153. // but if the last frame is <2ms we favor just removing this data
  2154. int frames = 1 + int((maxt - mint) * settings.anim_freq + 0.8f);
  2155. size_t time_accr = needs_time ? writeAnimationTime(views, json_accessors, accr_offset, mint, frames, settings) : 0;
  2156. size_t pose_accr = needs_pose ? writeAnimationTime(views, json_accessors, accr_offset, mint, 1, settings) : 0;
  2157. std::string json_samplers;
  2158. std::string json_channels;
  2159. size_t track_offset = 0;
  2160. for (size_t j = 0; j < tracks.size(); ++j)
  2161. {
  2162. const cgltf_animation_channel& channel = *tracks[j];
  2163. const cgltf_animation_sampler& sampler = *channel.sampler;
  2164. bool tc = isTrackConstant(sampler, channel.target_path, channel.target_node);
  2165. std::vector<Attr> track;
  2166. resampleKeyframes(track, sampler, channel.target_path, channel.target_node, tc ? 1 : frames, mint, settings.anim_freq);
  2167. std::string scratch;
  2168. StreamFormat format = writeKeyframeStream(scratch, channel.target_path, track);
  2169. size_t view = getBufferView(views, BufferView::Kind_Keyframe, channel.target_path, format.stride, settings.compress && channel.target_path != cgltf_animation_path_type_weights);
  2170. size_t offset = views[view].data.size();
  2171. views[view].data += scratch;
  2172. comma(json_accessors);
  2173. writeAccessor(json_accessors, view, offset, format.type, format.component_type, format.normalized, track.size());
  2174. size_t data_accr = accr_offset++;
  2175. comma(json_samplers);
  2176. append(json_samplers, "{\"input\":");
  2177. append(json_samplers, tc ? pose_accr : time_accr);
  2178. append(json_samplers, ",\"output\":");
  2179. append(json_samplers, data_accr);
  2180. append(json_samplers, "}");
  2181. const NodeInfo& tni = nodes[channel.target_node - data->nodes];
  2182. size_t target_node = size_t(tni.remap);
  2183. if (channel.target_path == cgltf_animation_path_type_weights)
  2184. {
  2185. assert(tni.meshes.size() == 1);
  2186. target_node = tni.meshes[0];
  2187. }
  2188. comma(json_channels);
  2189. append(json_channels, "{\"sampler\":");
  2190. append(json_channels, track_offset);
  2191. append(json_channels, ",\"target\":{\"node\":");
  2192. append(json_channels, target_node);
  2193. append(json_channels, ",\"path\":\"");
  2194. append(json_channels, animationPath(channel.target_path));
  2195. append(json_channels, "\"}}");
  2196. track_offset++;
  2197. }
  2198. comma(json);
  2199. append(json, "{");
  2200. if (animation.name && *animation.name)
  2201. {
  2202. append(json, "\"name\":\"");
  2203. append(json, animation.name);
  2204. append(json, "\",");
  2205. }
  2206. append(json, "\"samplers\":[");
  2207. append(json, json_samplers);
  2208. append(json, "],\"channels\":[");
  2209. append(json, json_channels);
  2210. append(json, "]}");
  2211. }
  2212. void writeCamera(std::string& json, const cgltf_camera& camera)
  2213. {
  2214. comma(json);
  2215. append(json, "{");
  2216. switch (camera.type)
  2217. {
  2218. case cgltf_camera_type_perspective:
  2219. append(json, "\"type\":\"perspective\",\"perspective\":{");
  2220. append(json, "\"yfov\":");
  2221. append(json, camera.perspective.yfov);
  2222. append(json, ",\"znear\":");
  2223. append(json, camera.perspective.znear);
  2224. if (camera.perspective.aspect_ratio != 0.f)
  2225. {
  2226. append(json, ",\"aspectRatio\":");
  2227. append(json, camera.perspective.aspect_ratio);
  2228. }
  2229. if (camera.perspective.zfar != 0.f)
  2230. {
  2231. append(json, ",\"zfar\":");
  2232. append(json, camera.perspective.zfar);
  2233. }
  2234. append(json, "}");
  2235. break;
  2236. case cgltf_camera_type_orthographic:
  2237. append(json, "\"type\":\"orthographic\",\"orthographic\":{");
  2238. append(json, "\"xmag\":");
  2239. append(json, camera.orthographic.xmag);
  2240. append(json, ",\"ymag\":");
  2241. append(json, camera.orthographic.ymag);
  2242. append(json, ",\"znear\":");
  2243. append(json, camera.orthographic.znear);
  2244. append(json, ",\"zfar\":");
  2245. append(json, camera.orthographic.zfar);
  2246. append(json, "}");
  2247. break;
  2248. default:
  2249. fprintf(stderr, "Warning: skipping camera of unknown type\n");
  2250. }
  2251. append(json, "}");
  2252. }
  2253. void writeLight(std::string& json, const cgltf_light& light)
  2254. {
  2255. static const float white[3] = {1, 1, 1};
  2256. comma(json);
  2257. append(json, "{\"type\":\"");
  2258. append(json, lightType(light.type));
  2259. append(json, "\"");
  2260. if (memcmp(light.color, white, sizeof(white)) != 0)
  2261. {
  2262. comma(json);
  2263. append(json, "\"color\":[");
  2264. append(json, light.color[0]);
  2265. append(json, ",");
  2266. append(json, light.color[1]);
  2267. append(json, ",");
  2268. append(json, light.color[2]);
  2269. append(json, "]");
  2270. }
  2271. if (light.intensity != 1.f)
  2272. {
  2273. comma(json);
  2274. append(json, "\"intensity\":");
  2275. append(json, light.intensity);
  2276. }
  2277. if (light.range != 0.f)
  2278. {
  2279. comma(json);
  2280. append(json, "\"range\":");
  2281. append(json, light.range);
  2282. }
  2283. if (light.type == cgltf_light_type_spot)
  2284. {
  2285. comma(json);
  2286. append(json, "\"spot\":{");
  2287. append(json, "\"innerConeAngle\":");
  2288. append(json, light.spot_inner_cone_angle);
  2289. append(json, ",\"outerConeAngle\":");
  2290. append(json, light.spot_outer_cone_angle == 0.f ? 0.78539816339f : light.spot_outer_cone_angle);
  2291. append(json, "}");
  2292. }
  2293. append(json, "}");
  2294. }
  2295. void printStats(const std::vector<BufferView>& views, BufferView::Kind kind, const char* name)
  2296. {
  2297. for (size_t i = 0; i < views.size(); ++i)
  2298. {
  2299. const BufferView& view = views[i];
  2300. if (view.kind != kind)
  2301. continue;
  2302. const char* variant = "unknown";
  2303. switch (kind)
  2304. {
  2305. case BufferView::Kind_Vertex:
  2306. variant = attributeType(cgltf_attribute_type(view.variant));
  2307. break;
  2308. case BufferView::Kind_Index:
  2309. variant = "index";
  2310. break;
  2311. case BufferView::Kind_Keyframe:
  2312. variant = animationPath(cgltf_animation_path_type(view.variant));
  2313. break;
  2314. default:;
  2315. }
  2316. size_t count = view.data.size() / view.stride;
  2317. printf("stats: %s %s: compressed %d bytes (%.1f bits), raw %d bytes (%d bits)\n",
  2318. name,
  2319. variant,
  2320. int(view.bytes),
  2321. double(view.bytes) / double(count) * 8,
  2322. int(view.data.size()),
  2323. int(view.stride * 8));
  2324. }
  2325. }
  2326. void process(cgltf_data* data, std::vector<Mesh>& meshes, const Settings& settings, std::string& json, std::string& bin)
  2327. {
  2328. if (settings.verbose)
  2329. {
  2330. printf("input: %d nodes, %d meshes (%d primitives), %d materials, %d skins, %d animations\n",
  2331. int(data->nodes_count), int(data->meshes_count), int(meshes.size()), int(data->materials_count), int(data->skins_count), int(data->animations_count));
  2332. }
  2333. std::vector<NodeInfo> nodes(data->nodes_count);
  2334. markAnimated(data, nodes);
  2335. for (size_t i = 0; i < meshes.size(); ++i)
  2336. {
  2337. Mesh& mesh = meshes[i];
  2338. // note: when -kn is specified, we keep mesh-node attachment so that named nodes can be transformed
  2339. if (mesh.node && !settings.keep_named)
  2340. {
  2341. NodeInfo& ni = nodes[mesh.node - data->nodes];
  2342. // we transform all non-skinned non-animated meshes to world space
  2343. // this makes sure that quantization doesn't introduce gaps if the original scene was watertight
  2344. if (!ni.animated && !mesh.skin && mesh.targets == 0)
  2345. {
  2346. transformMesh(mesh, mesh.node);
  2347. mesh.node = 0;
  2348. }
  2349. // skinned and animated meshes will be anchored to the same node that they used to be in
  2350. // for animated meshes, this is important since they need to be transformed by the same animation
  2351. // 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
  2352. }
  2353. }
  2354. mergeMeshMaterials(data, meshes);
  2355. mergeMeshes(meshes, settings);
  2356. markNeededNodes(data, nodes, meshes, settings);
  2357. std::vector<MaterialInfo> materials(data->materials_count);
  2358. markNeededMaterials(data, materials, meshes);
  2359. for (size_t i = 0; i < meshes.size(); ++i)
  2360. {
  2361. Mesh& mesh = meshes[i];
  2362. switch (mesh.type)
  2363. {
  2364. case cgltf_primitive_type_points:
  2365. sortPointMesh(mesh);
  2366. break;
  2367. case cgltf_primitive_type_triangles:
  2368. reindexMesh(mesh);
  2369. optimizeMesh(mesh);
  2370. break;
  2371. default:
  2372. assert(!"Unknown primitive type");
  2373. }
  2374. }
  2375. if (settings.verbose)
  2376. {
  2377. size_t triangles = 0;
  2378. size_t vertices = 0;
  2379. for (size_t i = 0; i < meshes.size(); ++i)
  2380. {
  2381. const Mesh& mesh = meshes[i];
  2382. triangles += mesh.indices.size() / 3;
  2383. vertices += mesh.streams.empty() ? 0 : mesh.streams[0].data.size();
  2384. }
  2385. printf("meshes: %d triangles, %d vertices\n", int(triangles), int(vertices));
  2386. }
  2387. QuantizationParams qp = prepareQuantization(meshes, settings);
  2388. std::string json_images;
  2389. std::string json_textures;
  2390. std::string json_materials;
  2391. std::string json_accessors;
  2392. std::string json_meshes;
  2393. std::string json_nodes;
  2394. std::string json_skins;
  2395. std::string json_roots;
  2396. std::string json_animations;
  2397. std::string json_cameras;
  2398. std::string json_lights;
  2399. std::vector<BufferView> views;
  2400. bool ext_pbr_specular_glossiness = false;
  2401. bool ext_unlit = false;
  2402. size_t accr_offset = 0;
  2403. size_t node_offset = 0;
  2404. size_t mesh_offset = 0;
  2405. size_t material_offset = 0;
  2406. for (size_t i = 0; i < data->images_count; ++i)
  2407. {
  2408. const cgltf_image& image = data->images[i];
  2409. comma(json_images);
  2410. append(json_images, "{");
  2411. if (image.uri)
  2412. {
  2413. std::string mime_type;
  2414. std::string img;
  2415. if (parseDataUri(image.uri, mime_type, img))
  2416. {
  2417. writeEmbeddedImage(json_images, views, img.c_str(), img.size(), mime_type.c_str());
  2418. }
  2419. else
  2420. {
  2421. append(json_images, "\"uri\":\"");
  2422. append(json_images, image.uri);
  2423. append(json_images, "\"");
  2424. }
  2425. }
  2426. else if (image.buffer_view && image.buffer_view->buffer->data && image.mime_type)
  2427. {
  2428. const char* img = static_cast<const char*>(image.buffer_view->buffer->data) + image.buffer_view->offset;
  2429. size_t size = image.buffer_view->size;
  2430. writeEmbeddedImage(json_images, views, img, size, image.mime_type);
  2431. }
  2432. else
  2433. {
  2434. fprintf(stderr, "Warning: ignoring image %d since it has no URI and no valid buffer data\n", int(i));
  2435. }
  2436. append(json_images, "}");
  2437. }
  2438. for (size_t i = 0; i < data->textures_count; ++i)
  2439. {
  2440. const cgltf_texture& texture = data->textures[i];
  2441. comma(json_textures);
  2442. append(json_textures, "{");
  2443. if (texture.image)
  2444. {
  2445. append(json_textures, "\"source\":");
  2446. append(json_textures, size_t(texture.image - data->images));
  2447. }
  2448. append(json_textures, "}");
  2449. }
  2450. for (size_t i = 0; i < data->materials_count; ++i)
  2451. {
  2452. MaterialInfo& mi = materials[i];
  2453. if (!mi.keep)
  2454. continue;
  2455. const cgltf_material& material = data->materials[i];
  2456. comma(json_materials);
  2457. append(json_materials, "{");
  2458. writeMaterialInfo(json_materials, data, material, qp);
  2459. append(json_materials, "}");
  2460. mi.remap = int(material_offset);
  2461. material_offset++;
  2462. ext_pbr_specular_glossiness = ext_pbr_specular_glossiness || material.has_pbr_specular_glossiness;
  2463. ext_unlit = ext_unlit || material.unlit;
  2464. }
  2465. for (size_t i = 0; i < meshes.size(); ++i)
  2466. {
  2467. const Mesh& mesh = meshes[i];
  2468. comma(json_meshes);
  2469. append(json_meshes, "{\"primitives\":[");
  2470. size_t pi = i;
  2471. for (; pi < meshes.size(); ++pi)
  2472. {
  2473. const Mesh& prim = meshes[pi];
  2474. if (prim.node != mesh.node || prim.skin != mesh.skin || prim.targets != mesh.targets)
  2475. break;
  2476. if (mesh.weights.size() && (prim.weights.size() != mesh.weights.size() || memcmp(&mesh.weights[0], &prim.weights[0], mesh.weights.size() * sizeof(float)) != 0))
  2477. break;
  2478. comma(json_meshes);
  2479. append(json_meshes, "{\"attributes\":{");
  2480. writeMeshAttributes(json_meshes, views, json_accessors, accr_offset, prim, 0, qp, settings);
  2481. append(json_meshes, "}");
  2482. append(json_meshes, ",\"mode\":");
  2483. append(json_meshes, size_t(prim.type));
  2484. if (mesh.targets)
  2485. {
  2486. append(json_meshes, ",\"targets\":[");
  2487. for (size_t j = 0; j < mesh.targets; ++j)
  2488. {
  2489. comma(json_meshes);
  2490. append(json_meshes, "{");
  2491. writeMeshAttributes(json_meshes, views, json_accessors, accr_offset, prim, int(1 + j), qp, settings);
  2492. append(json_meshes, "}");
  2493. }
  2494. append(json_meshes, "]");
  2495. }
  2496. if (!prim.indices.empty())
  2497. {
  2498. size_t index_accr = writeMeshIndices(views, json_accessors, accr_offset, prim, settings);
  2499. append(json_meshes, ",\"indices\":");
  2500. append(json_meshes, index_accr);
  2501. }
  2502. if (prim.material)
  2503. {
  2504. MaterialInfo& mi = materials[prim.material - data->materials];
  2505. assert(mi.keep);
  2506. append(json_meshes, ",\"material\":");
  2507. append(json_meshes, size_t(mi.remap));
  2508. }
  2509. append(json_meshes, "}");
  2510. }
  2511. append(json_meshes, "]");
  2512. if (mesh.weights.size())
  2513. {
  2514. append(json_meshes, ",\"weights\":[");
  2515. for (size_t j = 0; j < mesh.weights.size(); ++j)
  2516. {
  2517. comma(json_meshes);
  2518. append(json_meshes, mesh.weights[j]);
  2519. }
  2520. append(json_meshes, "]");
  2521. }
  2522. append(json_meshes, "}");
  2523. writeMeshNode(json_nodes, mesh_offset, mesh, data, qp);
  2524. if (mesh.node)
  2525. {
  2526. NodeInfo& ni = nodes[mesh.node - data->nodes];
  2527. assert(ni.keep);
  2528. ni.meshes.push_back(node_offset);
  2529. }
  2530. else
  2531. {
  2532. comma(json_roots);
  2533. append(json_roots, node_offset);
  2534. }
  2535. node_offset++;
  2536. mesh_offset++;
  2537. // skip all meshes that we've written in this iteration
  2538. assert(pi > i);
  2539. i = pi - 1;
  2540. }
  2541. remapNodes(data, nodes, node_offset);
  2542. for (size_t i = 0; i < data->nodes_count; ++i)
  2543. {
  2544. NodeInfo& ni = nodes[i];
  2545. if (!ni.keep)
  2546. continue;
  2547. const cgltf_node& node = data->nodes[i];
  2548. if (!node.parent)
  2549. {
  2550. comma(json_roots);
  2551. append(json_roots, size_t(ni.remap));
  2552. }
  2553. writeNode(json_nodes, node, nodes, data);
  2554. }
  2555. for (size_t i = 0; i < data->skins_count; ++i)
  2556. {
  2557. const cgltf_skin& skin = data->skins[i];
  2558. size_t matrix_accr = writeJointBindMatrices(views, json_accessors, accr_offset, skin, qp, settings);
  2559. comma(json_skins);
  2560. append(json_skins, "{");
  2561. append(json_skins, "\"joints\":[");
  2562. for (size_t j = 0; j < skin.joints_count; ++j)
  2563. {
  2564. comma(json_skins);
  2565. append(json_skins, size_t(nodes[skin.joints[j] - data->nodes].remap));
  2566. }
  2567. append(json_skins, "]");
  2568. append(json_skins, ",\"inverseBindMatrices\":");
  2569. append(json_skins, matrix_accr);
  2570. if (skin.skeleton)
  2571. {
  2572. comma(json_skins);
  2573. append(json_skins, "\"skeleton\":");
  2574. append(json_skins, size_t(nodes[skin.skeleton - data->nodes].remap));
  2575. }
  2576. append(json_skins, "}");
  2577. }
  2578. for (size_t i = 0; i < data->animations_count; ++i)
  2579. {
  2580. const cgltf_animation& animation = data->animations[i];
  2581. writeAnimation(json_animations, views, json_accessors, accr_offset, animation, data, nodes, settings);
  2582. }
  2583. for (size_t i = 0; i < data->cameras_count; ++i)
  2584. {
  2585. const cgltf_camera& camera = data->cameras[i];
  2586. writeCamera(json_cameras, camera);
  2587. }
  2588. for (size_t i = 0; i < data->lights_count; ++i)
  2589. {
  2590. const cgltf_light& light = data->lights[i];
  2591. writeLight(json_lights, light);
  2592. }
  2593. char version[32];
  2594. sprintf(version, "%d.%d", MESHOPTIMIZER_VERSION / 1000, (MESHOPTIMIZER_VERSION % 1000) / 10);
  2595. append(json, "\"asset\":{");
  2596. append(json, "\"version\":\"2.0\",\"generator\":\"gltfpack ");
  2597. append(json, version);
  2598. append(json, "\"");
  2599. if (data->asset.extras.start_offset)
  2600. {
  2601. append(json, ",\"extras\":");
  2602. json.append(data->json + data->asset.extras.start_offset, data->json + data->asset.extras.end_offset);
  2603. }
  2604. append(json, "}");
  2605. append(json, ",\"extensionsUsed\":[");
  2606. append(json, "\"MESHOPT_quantized_geometry\"");
  2607. if (settings.compress)
  2608. {
  2609. comma(json);
  2610. append(json, "\"MESHOPT_compression\"");
  2611. }
  2612. if (!json_textures.empty())
  2613. {
  2614. comma(json);
  2615. append(json, "\"KHR_texture_transform\"");
  2616. }
  2617. if (ext_pbr_specular_glossiness)
  2618. {
  2619. comma(json);
  2620. append(json, "\"KHR_materials_pbrSpecularGlossiness\"");
  2621. }
  2622. if (ext_unlit)
  2623. {
  2624. comma(json);
  2625. append(json, "\"KHR_materials_unlit\"");
  2626. }
  2627. if (data->lights_count)
  2628. {
  2629. comma(json);
  2630. append(json, "\"KHR_lights_punctual\"");
  2631. }
  2632. append(json, "]");
  2633. if (settings.compress)
  2634. {
  2635. append(json, ",\"extensionsRequired\":[");
  2636. // Note: ideally we should include MESHOPT_quantized_geometry in the required extension list (regardless of compression)
  2637. // This extension *only* allows the use of quantized attributes for positions/normals/etc. This happens to be supported
  2638. // by popular JS frameworks, however, Babylon.JS refuses to load files with unsupported required extensions.
  2639. // For now we don't include it in the list, which will be fixed at some point once this extension becomes official.
  2640. append(json, "\"MESHOPT_compression\"");
  2641. append(json, "]");
  2642. }
  2643. size_t bytes[BufferView::Kind_Count] = {};
  2644. if (!views.empty())
  2645. {
  2646. append(json, ",\"bufferViews\":[");
  2647. for (size_t i = 0; i < views.size(); ++i)
  2648. {
  2649. BufferView& view = views[i];
  2650. size_t offset = bin.size();
  2651. size_t count = view.data.size() / view.stride;
  2652. int compression = -1;
  2653. if (view.compressed)
  2654. {
  2655. if (view.kind == BufferView::Kind_Index)
  2656. {
  2657. compressIndexStream(bin, view.data, count, view.stride);
  2658. compression = 1;
  2659. }
  2660. else
  2661. {
  2662. compressVertexStream(bin, view.data, count, view.stride);
  2663. compression = 0;
  2664. }
  2665. }
  2666. else
  2667. {
  2668. bin += view.data;
  2669. }
  2670. comma(json);
  2671. writeBufferView(json, view.kind, count, view.stride, offset, bin.size() - offset, compression);
  2672. view.bytes = bin.size() - offset;
  2673. bytes[view.kind] += view.bytes;
  2674. // align each bufferView by 4 bytes
  2675. bin.resize((bin.size() + 3) & ~3);
  2676. }
  2677. append(json, "]");
  2678. }
  2679. if (!json_accessors.empty())
  2680. {
  2681. append(json, ",\"accessors\":[");
  2682. append(json, json_accessors);
  2683. append(json, "]");
  2684. }
  2685. if (!json_images.empty())
  2686. {
  2687. append(json, ",\"images\":[");
  2688. append(json, json_images);
  2689. append(json, "]");
  2690. }
  2691. if (!json_textures.empty())
  2692. {
  2693. append(json, ",\"textures\":[");
  2694. append(json, json_textures);
  2695. append(json, "]");
  2696. }
  2697. if (!json_materials.empty())
  2698. {
  2699. append(json, ",\"materials\":[");
  2700. append(json, json_materials);
  2701. append(json, "]");
  2702. }
  2703. if (!json_meshes.empty())
  2704. {
  2705. append(json, ",\"meshes\":[");
  2706. append(json, json_meshes);
  2707. append(json, "]");
  2708. }
  2709. if (!json_skins.empty())
  2710. {
  2711. append(json, ",\"skins\":[");
  2712. append(json, json_skins);
  2713. append(json, "]");
  2714. }
  2715. if (!json_animations.empty())
  2716. {
  2717. append(json, ",\"animations\":[");
  2718. append(json, json_animations);
  2719. append(json, "]");
  2720. }
  2721. if (!json_roots.empty())
  2722. {
  2723. append(json, ",\"nodes\":[");
  2724. append(json, json_nodes);
  2725. append(json, "],\"scenes\":[");
  2726. append(json, "{\"nodes\":[");
  2727. append(json, json_roots);
  2728. append(json, "]}]");
  2729. }
  2730. if (!json_cameras.empty())
  2731. {
  2732. append(json, ",\"cameras\":[");
  2733. append(json, json_cameras);
  2734. append(json, "]");
  2735. }
  2736. if (!json_lights.empty())
  2737. {
  2738. append(json, ",\"extensions\":{\"KHR_lights_punctual\":{\"lights\":[");
  2739. append(json, json_lights);
  2740. append(json, "]}}");
  2741. }
  2742. if (!json_roots.empty())
  2743. {
  2744. append(json, ",\"scene\":0");
  2745. }
  2746. if (settings.verbose)
  2747. {
  2748. printf("output: %d nodes, %d meshes (%d primitives), %d materials\n", int(node_offset), int(mesh_offset), int(meshes.size()), int(material_offset));
  2749. printf("output: JSON %d bytes, buffers %d bytes\n", int(json.size()), int(bin.size()));
  2750. printf("output: buffers: vertex %d bytes, index %d bytes, skin %d bytes, time %d bytes, keyframe %d bytes, image %d bytes\n",
  2751. int(bytes[BufferView::Kind_Vertex]), int(bytes[BufferView::Kind_Index]), int(bytes[BufferView::Kind_Skin]),
  2752. int(bytes[BufferView::Kind_Time]), int(bytes[BufferView::Kind_Keyframe]), int(bytes[BufferView::Kind_Image]));
  2753. }
  2754. if (settings.verbose > 1)
  2755. {
  2756. printStats(views, BufferView::Kind_Vertex, "vertex");
  2757. printStats(views, BufferView::Kind_Index, "index");
  2758. printStats(views, BufferView::Kind_Keyframe, "keyframe");
  2759. }
  2760. }
  2761. void writeU32(FILE* out, uint32_t data)
  2762. {
  2763. fwrite(&data, 4, 1, out);
  2764. }
  2765. bool requiresExtension(cgltf_data* data, const char* name)
  2766. {
  2767. for (size_t i = 0; i < data->extensions_required_count; ++i)
  2768. if (strcmp(data->extensions_required[i], name) == 0)
  2769. return true;
  2770. return false;
  2771. }
  2772. int gltfpack(const char* input, const char* output, const Settings& settings)
  2773. {
  2774. cgltf_data* data = 0;
  2775. std::vector<Mesh> meshes;
  2776. const char* iext = strrchr(input, '.');
  2777. if (iext && (strcmp(iext, ".gltf") == 0 || strcmp(iext, ".GLTF") == 0 || strcmp(iext, ".glb") == 0 || strcmp(iext, ".GLB") == 0))
  2778. {
  2779. cgltf_options options = {};
  2780. cgltf_result result = cgltf_parse_file(&options, input, &data);
  2781. result = (result == cgltf_result_success) ? cgltf_validate(data) : result;
  2782. result = (result == cgltf_result_success) ? cgltf_load_buffers(&options, data, input) : result;
  2783. const char* error = NULL;
  2784. if (result != cgltf_result_success)
  2785. error = getError(result);
  2786. else if (requiresExtension(data, "KHR_draco_mesh_compression"))
  2787. error = "file requires Draco mesh compression support";
  2788. else if (requiresExtension(data, "MESHOPT_compression"))
  2789. error = "file has already been compressed using gltfpack";
  2790. if (error)
  2791. {
  2792. fprintf(stderr, "Error loading %s: %s\n", input, error);
  2793. cgltf_free(data);
  2794. return 2;
  2795. }
  2796. parseMeshesGltf(data, meshes);
  2797. }
  2798. else if (iext && (strcmp(iext, ".obj") == 0 || strcmp(iext, ".OBJ") == 0))
  2799. {
  2800. fastObjMesh* obj = fast_obj_read(input);
  2801. if (!obj)
  2802. {
  2803. fprintf(stderr, "Error loading %s: file not found\n", input);
  2804. cgltf_free(data);
  2805. return 2;
  2806. }
  2807. data = parseSceneObj(obj);
  2808. parseMeshesObj(obj, data, meshes);
  2809. fast_obj_destroy(obj);
  2810. }
  2811. else
  2812. {
  2813. fprintf(stderr, "Error loading %s: unknown extension (expected .gltf or .glb or .obj)\n", input);
  2814. return 2;
  2815. }
  2816. std::string json, bin;
  2817. process(data, meshes, settings, json, bin);
  2818. cgltf_free(data);
  2819. if (!output)
  2820. {
  2821. return 0;
  2822. }
  2823. const char* oext = strrchr(output, '.');
  2824. if (oext && (strcmp(oext, ".gltf") == 0 || strcmp(oext, ".GLTF") == 0))
  2825. {
  2826. std::string binpath = output;
  2827. binpath.replace(binpath.size() - 5, 5, ".bin");
  2828. std::string binname = binpath;
  2829. std::string::size_type slash = binname.find_last_of("/\\");
  2830. if (slash != std::string::npos)
  2831. binname.erase(0, slash + 1);
  2832. FILE* outjson = fopen(output, "wb");
  2833. FILE* outbin = fopen(binpath.c_str(), "wb");
  2834. if (!outjson || !outbin)
  2835. {
  2836. fprintf(stderr, "Error saving %s\n", output);
  2837. return 4;
  2838. }
  2839. fprintf(outjson, "{\"buffers\":[{\"uri\":\"%s\",\"byteLength\":%zu}],", binname.c_str(), bin.size());
  2840. fwrite(json.c_str(), json.size(), 1, outjson);
  2841. fprintf(outjson, "}");
  2842. fwrite(bin.c_str(), bin.size(), 1, outbin);
  2843. fclose(outjson);
  2844. fclose(outbin);
  2845. }
  2846. else if (oext && (strcmp(oext, ".glb") == 0 || strcmp(oext, ".GLB") == 0))
  2847. {
  2848. FILE* out = fopen(output, "wb");
  2849. if (!out)
  2850. {
  2851. fprintf(stderr, "Error saving %s\n", output);
  2852. return 4;
  2853. }
  2854. char bufferspec[64];
  2855. sprintf(bufferspec, "{\"buffers\":[{\"byteLength\":%zu}],", bin.size());
  2856. json.insert(0, bufferspec);
  2857. json.push_back('}');
  2858. while (json.size() % 4)
  2859. json.push_back(' ');
  2860. while (bin.size() % 4)
  2861. bin.push_back('\0');
  2862. writeU32(out, 0x46546C67);
  2863. writeU32(out, 2);
  2864. writeU32(out, uint32_t(12 + 8 + json.size() + 8 + bin.size()));
  2865. writeU32(out, uint32_t(json.size()));
  2866. writeU32(out, 0x4E4F534A);
  2867. fwrite(json.c_str(), json.size(), 1, out);
  2868. writeU32(out, uint32_t(bin.size()));
  2869. writeU32(out, 0x004E4942);
  2870. fwrite(bin.c_str(), bin.size(), 1, out);
  2871. fclose(out);
  2872. }
  2873. else
  2874. {
  2875. fprintf(stderr, "Error saving %s: unknown extension (expected .gltf or .glb)\n", output);
  2876. return 4;
  2877. }
  2878. return 0;
  2879. }
  2880. int main(int argc, char** argv)
  2881. {
  2882. Settings settings = {};
  2883. settings.pos_bits = 14;
  2884. settings.tex_bits = 12;
  2885. settings.nrm_bits = 8;
  2886. settings.anim_freq = 30;
  2887. const char* input = 0;
  2888. const char* output = 0;
  2889. bool help = false;
  2890. int test = 0;
  2891. for (int i = 1; i < argc; ++i)
  2892. {
  2893. const char* arg = argv[i];
  2894. if (strcmp(arg, "-vp") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
  2895. {
  2896. settings.pos_bits = atoi(argv[++i]);
  2897. }
  2898. else if (strcmp(arg, "-vt") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
  2899. {
  2900. settings.tex_bits = atoi(argv[++i]);
  2901. }
  2902. else if (strcmp(arg, "-vn") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
  2903. {
  2904. settings.nrm_bits = atoi(argv[++i]);
  2905. }
  2906. else if (strcmp(arg, "-vu") == 0)
  2907. {
  2908. settings.nrm_unit = true;
  2909. }
  2910. else if (strcmp(arg, "-af") == 0 && i + 1 < argc && isdigit(argv[i + 1][0]))
  2911. {
  2912. settings.anim_freq = atoi(argv[++i]);
  2913. }
  2914. else if (strcmp(arg, "-ac") == 0)
  2915. {
  2916. settings.anim_const = true;
  2917. }
  2918. else if (strcmp(arg, "-kn") == 0)
  2919. {
  2920. settings.keep_named = true;
  2921. }
  2922. else if (strcmp(arg, "-i") == 0 && i + 1 < argc && !input)
  2923. {
  2924. input = argv[++i];
  2925. }
  2926. else if (strcmp(arg, "-o") == 0 && i + 1 < argc && !output)
  2927. {
  2928. output = argv[++i];
  2929. }
  2930. else if (strcmp(arg, "-c") == 0)
  2931. {
  2932. settings.compress = true;
  2933. }
  2934. else if (strcmp(arg, "-v") == 0)
  2935. {
  2936. settings.verbose = 1;
  2937. }
  2938. else if (strcmp(arg, "-vv") == 0)
  2939. {
  2940. settings.verbose = 2;
  2941. }
  2942. else if (strcmp(arg, "-h") == 0)
  2943. {
  2944. help = true;
  2945. }
  2946. else if (strcmp(arg, "-test") == 0)
  2947. {
  2948. test = i + 1;
  2949. break;
  2950. }
  2951. else
  2952. {
  2953. fprintf(stderr, "Unrecognized option %s\n", arg);
  2954. return 1;
  2955. }
  2956. }
  2957. if (test)
  2958. {
  2959. for (int i = test; i < argc; ++i)
  2960. {
  2961. printf("%s\n", argv[i]);
  2962. gltfpack(argv[i], NULL, settings);
  2963. }
  2964. return 0;
  2965. }
  2966. if (!input || !output || help)
  2967. {
  2968. fprintf(stderr, "Usage: gltfpack [options] -i input -o output\n");
  2969. fprintf(stderr, "\n");
  2970. fprintf(stderr, "Options:\n");
  2971. fprintf(stderr, "-i file: input file to process, .obj/.gltf/.glb\n");
  2972. fprintf(stderr, "-o file: output file path, .gltf/.glb\n");
  2973. fprintf(stderr, "-vp N: use N-bit quantization for positions (default: 14; N should be between 1 and 16)\n");
  2974. fprintf(stderr, "-vt N: use N-bit quantization for texture corodinates (default: 12; N should be between 1 and 16)\n");
  2975. fprintf(stderr, "-vn N: use N-bit quantization for normals and tangents (default: 8; N should be between 1 and 16)\n");
  2976. fprintf(stderr, "-vu: use unit-length normal/tangent vectors (default: off)\n");
  2977. fprintf(stderr, "-af N: resample animations at N Hz (default: 30)\n");
  2978. fprintf(stderr, "-ac: keep constant animation tracks even if they don't modify the node transform\n");
  2979. fprintf(stderr, "-kn: keep named nodes and meshes attached to named nodes so that named nodes can be transformed externally\n");
  2980. fprintf(stderr, "-c: produce compressed glb files\n");
  2981. fprintf(stderr, "-v: verbose output\n");
  2982. fprintf(stderr, "-h: display this help and exit\n");
  2983. return 1;
  2984. }
  2985. return gltfpack(input, output, settings);
  2986. }