gltfpack.cpp 113 KB

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