gltfpack.cpp 102 KB

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