tiny_gltf.h 265 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483
  1. //
  2. // Header-only tiny glTF 2.0 loader and serializer.
  3. //
  4. //
  5. // The MIT License (MIT)
  6. //
  7. // Copyright (c) 2015 - Present Syoyo Fujita, Aurélien Chatelain and many
  8. // contributors.
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining a copy
  11. // of this software and associated documentation files (the "Software"), to deal
  12. // in the Software without restriction, including without limitation the rights
  13. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14. // copies of the Software, and to permit persons to whom the Software is
  15. // furnished to do so, subject to the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be included in
  18. // all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  21. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  22. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  23. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  24. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  25. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  26. // THE SOFTWARE.
  27. // Version: - v2.8.10
  28. // See https://github.com/syoyo/tinygltf/releases for release history.
  29. //
  30. // Tiny glTF loader is using following third party libraries:
  31. //
  32. // - jsonhpp: C++ JSON library.
  33. // - base64: base64 decode/encode library.
  34. // - stb_image: Image loading library.
  35. //
  36. #ifndef TINY_GLTF_H_
  37. #define TINY_GLTF_H_
  38. #include <array>
  39. #include <cassert>
  40. #include <cmath> // std::fabs
  41. #include <cstdint>
  42. #include <cstdlib>
  43. #include <cstring>
  44. #include <limits>
  45. #include <map>
  46. #include <string>
  47. #include <vector>
  48. // Auto-detect C++14 standard version
  49. #if !defined(TINYGLTF_USE_CPP14) && defined(__cplusplus) && \
  50. (__cplusplus >= 201402L)
  51. #define TINYGLTF_USE_CPP14
  52. #endif
  53. #ifdef __ANDROID__
  54. #ifdef TINYGLTF_ANDROID_LOAD_FROM_ASSETS
  55. #include <android/asset_manager.h>
  56. #endif
  57. #endif
  58. #ifdef __GNUC__
  59. #if (__GNUC__ < 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ <= 8))
  60. #define TINYGLTF_NOEXCEPT
  61. #else
  62. #define TINYGLTF_NOEXCEPT noexcept
  63. #endif
  64. #else
  65. #define TINYGLTF_NOEXCEPT noexcept
  66. #endif
  67. #define DEFAULT_METHODS(x) \
  68. ~x() = default; \
  69. x(const x &) = default; \
  70. x(x &&) TINYGLTF_NOEXCEPT = default; \
  71. x &operator=(const x &) = default; \
  72. x &operator=(x &&) TINYGLTF_NOEXCEPT = default;
  73. namespace tinygltf {
  74. #define TINYGLTF_MODE_POINTS (0)
  75. #define TINYGLTF_MODE_LINE (1)
  76. #define TINYGLTF_MODE_LINE_LOOP (2)
  77. #define TINYGLTF_MODE_LINE_STRIP (3)
  78. #define TINYGLTF_MODE_TRIANGLES (4)
  79. #define TINYGLTF_MODE_TRIANGLE_STRIP (5)
  80. #define TINYGLTF_MODE_TRIANGLE_FAN (6)
  81. #define TINYGLTF_COMPONENT_TYPE_BYTE (5120)
  82. #define TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE (5121)
  83. #define TINYGLTF_COMPONENT_TYPE_SHORT (5122)
  84. #define TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT (5123)
  85. #define TINYGLTF_COMPONENT_TYPE_INT (5124)
  86. #define TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT (5125)
  87. #define TINYGLTF_COMPONENT_TYPE_FLOAT (5126)
  88. #define TINYGLTF_COMPONENT_TYPE_DOUBLE \
  89. (5130) // OpenGL double type. Note that some of glTF 2.0 validator does not
  90. // support double type even the schema seems allow any value of
  91. // integer:
  92. // https://github.com/KhronosGroup/glTF/blob/b9884a2fd45130b4d673dd6c8a706ee21ee5c5f7/specification/2.0/schema/accessor.schema.json#L22
  93. #define TINYGLTF_TEXTURE_FILTER_NEAREST (9728)
  94. #define TINYGLTF_TEXTURE_FILTER_LINEAR (9729)
  95. #define TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_NEAREST (9984)
  96. #define TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_NEAREST (9985)
  97. #define TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_LINEAR (9986)
  98. #define TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_LINEAR (9987)
  99. #define TINYGLTF_TEXTURE_WRAP_REPEAT (10497)
  100. #define TINYGLTF_TEXTURE_WRAP_CLAMP_TO_EDGE (33071)
  101. #define TINYGLTF_TEXTURE_WRAP_MIRRORED_REPEAT (33648)
  102. // Redeclarations of the above for technique.parameters.
  103. #define TINYGLTF_PARAMETER_TYPE_BYTE (5120)
  104. #define TINYGLTF_PARAMETER_TYPE_UNSIGNED_BYTE (5121)
  105. #define TINYGLTF_PARAMETER_TYPE_SHORT (5122)
  106. #define TINYGLTF_PARAMETER_TYPE_UNSIGNED_SHORT (5123)
  107. #define TINYGLTF_PARAMETER_TYPE_INT (5124)
  108. #define TINYGLTF_PARAMETER_TYPE_UNSIGNED_INT (5125)
  109. #define TINYGLTF_PARAMETER_TYPE_FLOAT (5126)
  110. #define TINYGLTF_PARAMETER_TYPE_FLOAT_VEC2 (35664)
  111. #define TINYGLTF_PARAMETER_TYPE_FLOAT_VEC3 (35665)
  112. #define TINYGLTF_PARAMETER_TYPE_FLOAT_VEC4 (35666)
  113. #define TINYGLTF_PARAMETER_TYPE_INT_VEC2 (35667)
  114. #define TINYGLTF_PARAMETER_TYPE_INT_VEC3 (35668)
  115. #define TINYGLTF_PARAMETER_TYPE_INT_VEC4 (35669)
  116. #define TINYGLTF_PARAMETER_TYPE_BOOL (35670)
  117. #define TINYGLTF_PARAMETER_TYPE_BOOL_VEC2 (35671)
  118. #define TINYGLTF_PARAMETER_TYPE_BOOL_VEC3 (35672)
  119. #define TINYGLTF_PARAMETER_TYPE_BOOL_VEC4 (35673)
  120. #define TINYGLTF_PARAMETER_TYPE_FLOAT_MAT2 (35674)
  121. #define TINYGLTF_PARAMETER_TYPE_FLOAT_MAT3 (35675)
  122. #define TINYGLTF_PARAMETER_TYPE_FLOAT_MAT4 (35676)
  123. #define TINYGLTF_PARAMETER_TYPE_SAMPLER_2D (35678)
  124. // End parameter types
  125. #define TINYGLTF_TYPE_VEC2 (2)
  126. #define TINYGLTF_TYPE_VEC3 (3)
  127. #define TINYGLTF_TYPE_VEC4 (4)
  128. #define TINYGLTF_TYPE_MAT2 (32 + 2)
  129. #define TINYGLTF_TYPE_MAT3 (32 + 3)
  130. #define TINYGLTF_TYPE_MAT4 (32 + 4)
  131. #define TINYGLTF_TYPE_SCALAR (64 + 1)
  132. #define TINYGLTF_TYPE_VECTOR (64 + 4)
  133. #define TINYGLTF_TYPE_MATRIX (64 + 16)
  134. #define TINYGLTF_IMAGE_FORMAT_JPEG (0)
  135. #define TINYGLTF_IMAGE_FORMAT_PNG (1)
  136. #define TINYGLTF_IMAGE_FORMAT_BMP (2)
  137. #define TINYGLTF_IMAGE_FORMAT_GIF (3)
  138. #define TINYGLTF_TEXTURE_FORMAT_ALPHA (6406)
  139. #define TINYGLTF_TEXTURE_FORMAT_RGB (6407)
  140. #define TINYGLTF_TEXTURE_FORMAT_RGBA (6408)
  141. #define TINYGLTF_TEXTURE_FORMAT_LUMINANCE (6409)
  142. #define TINYGLTF_TEXTURE_FORMAT_LUMINANCE_ALPHA (6410)
  143. #define TINYGLTF_TEXTURE_TARGET_TEXTURE2D (3553)
  144. #define TINYGLTF_TEXTURE_TYPE_UNSIGNED_BYTE (5121)
  145. #define TINYGLTF_TARGET_ARRAY_BUFFER (34962)
  146. #define TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER (34963)
  147. #define TINYGLTF_SHADER_TYPE_VERTEX_SHADER (35633)
  148. #define TINYGLTF_SHADER_TYPE_FRAGMENT_SHADER (35632)
  149. #define TINYGLTF_DOUBLE_EPS (1.e-12)
  150. #define TINYGLTF_DOUBLE_EQUAL(a, b) (std::fabs((b) - (a)) < TINYGLTF_DOUBLE_EPS)
  151. #ifdef __ANDROID__
  152. #ifdef TINYGLTF_ANDROID_LOAD_FROM_ASSETS
  153. #ifdef TINYGLTF_IMPLEMENTATION
  154. AAssetManager *asset_manager = nullptr;
  155. #else
  156. extern AAssetManager *asset_manager;
  157. #endif
  158. #endif
  159. #endif
  160. typedef enum {
  161. NULL_TYPE,
  162. REAL_TYPE,
  163. INT_TYPE,
  164. BOOL_TYPE,
  165. STRING_TYPE,
  166. ARRAY_TYPE,
  167. BINARY_TYPE,
  168. OBJECT_TYPE
  169. } Type;
  170. typedef enum {
  171. Permissive,
  172. Strict
  173. } ParseStrictness;
  174. static inline int32_t GetComponentSizeInBytes(uint32_t componentType) {
  175. if (componentType == TINYGLTF_COMPONENT_TYPE_BYTE) {
  176. return 1;
  177. } else if (componentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE) {
  178. return 1;
  179. } else if (componentType == TINYGLTF_COMPONENT_TYPE_SHORT) {
  180. return 2;
  181. } else if (componentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT) {
  182. return 2;
  183. } else if (componentType == TINYGLTF_COMPONENT_TYPE_INT) {
  184. return 4;
  185. } else if (componentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT) {
  186. return 4;
  187. } else if (componentType == TINYGLTF_COMPONENT_TYPE_FLOAT) {
  188. return 4;
  189. } else if (componentType == TINYGLTF_COMPONENT_TYPE_DOUBLE) {
  190. return 8;
  191. } else {
  192. // Unknown component type
  193. return -1;
  194. }
  195. }
  196. static inline int32_t GetNumComponentsInType(uint32_t ty) {
  197. if (ty == TINYGLTF_TYPE_SCALAR) {
  198. return 1;
  199. } else if (ty == TINYGLTF_TYPE_VEC2) {
  200. return 2;
  201. } else if (ty == TINYGLTF_TYPE_VEC3) {
  202. return 3;
  203. } else if (ty == TINYGLTF_TYPE_VEC4) {
  204. return 4;
  205. } else if (ty == TINYGLTF_TYPE_MAT2) {
  206. return 4;
  207. } else if (ty == TINYGLTF_TYPE_MAT3) {
  208. return 9;
  209. } else if (ty == TINYGLTF_TYPE_MAT4) {
  210. return 16;
  211. } else {
  212. // Unknown component type
  213. return -1;
  214. }
  215. }
  216. // TODO(syoyo): Move these functions to TinyGLTF class
  217. bool IsDataURI(const std::string &in);
  218. bool DecodeDataURI(std::vector<unsigned char> *out, std::string &mime_type,
  219. const std::string &in, size_t reqBytes, bool checkSize);
  220. #ifdef __clang__
  221. #pragma clang diagnostic push
  222. // Suppress warning for : static Value null_value
  223. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  224. #pragma clang diagnostic ignored "-Wpadded"
  225. #endif
  226. // Simple class to represent JSON object
  227. class Value {
  228. public:
  229. typedef std::vector<Value> Array;
  230. typedef std::map<std::string, Value> Object;
  231. Value() = default;
  232. explicit Value(bool b) : type_(BOOL_TYPE) { boolean_value_ = b; }
  233. explicit Value(int i) : type_(INT_TYPE) {
  234. int_value_ = i;
  235. real_value_ = i;
  236. }
  237. explicit Value(double n) : type_(REAL_TYPE) { real_value_ = n; }
  238. explicit Value(const std::string &s) : type_(STRING_TYPE) {
  239. string_value_ = s;
  240. }
  241. explicit Value(std::string &&s)
  242. : type_(STRING_TYPE), string_value_(std::move(s)) {}
  243. explicit Value(const char *s) : type_(STRING_TYPE) { string_value_ = s; }
  244. explicit Value(const unsigned char *p, size_t n) : type_(BINARY_TYPE) {
  245. binary_value_.resize(n);
  246. memcpy(binary_value_.data(), p, n);
  247. }
  248. explicit Value(std::vector<unsigned char> &&v) noexcept
  249. : type_(BINARY_TYPE),
  250. binary_value_(std::move(v)) {}
  251. explicit Value(const Array &a) : type_(ARRAY_TYPE) { array_value_ = a; }
  252. explicit Value(Array &&a) noexcept : type_(ARRAY_TYPE),
  253. array_value_(std::move(a)) {}
  254. explicit Value(const Object &o) : type_(OBJECT_TYPE) { object_value_ = o; }
  255. explicit Value(Object &&o) noexcept : type_(OBJECT_TYPE),
  256. object_value_(std::move(o)) {}
  257. DEFAULT_METHODS(Value)
  258. char Type() const { return static_cast<char>(type_); }
  259. bool IsBool() const { return (type_ == BOOL_TYPE); }
  260. bool IsInt() const { return (type_ == INT_TYPE); }
  261. bool IsNumber() const { return (type_ == REAL_TYPE) || (type_ == INT_TYPE); }
  262. bool IsReal() const { return (type_ == REAL_TYPE); }
  263. bool IsString() const { return (type_ == STRING_TYPE); }
  264. bool IsBinary() const { return (type_ == BINARY_TYPE); }
  265. bool IsArray() const { return (type_ == ARRAY_TYPE); }
  266. bool IsObject() const { return (type_ == OBJECT_TYPE); }
  267. // Use this function if you want to have number value as double.
  268. double GetNumberAsDouble() const {
  269. if (type_ == INT_TYPE) {
  270. return double(int_value_);
  271. } else {
  272. return real_value_;
  273. }
  274. }
  275. // Use this function if you want to have number value as int.
  276. // TODO(syoyo): Support int value larger than 32 bits
  277. int GetNumberAsInt() const {
  278. if (type_ == REAL_TYPE) {
  279. return int(real_value_);
  280. } else {
  281. return int_value_;
  282. }
  283. }
  284. // Accessor
  285. template <typename T>
  286. const T &Get() const;
  287. template <typename T>
  288. T &Get();
  289. // Lookup value from an array
  290. const Value &Get(int idx) const {
  291. static Value null_value;
  292. assert(IsArray());
  293. assert(idx >= 0);
  294. return (static_cast<size_t>(idx) < array_value_.size())
  295. ? array_value_[static_cast<size_t>(idx)]
  296. : null_value;
  297. }
  298. // Lookup value from a key-value pair
  299. const Value &Get(const std::string &key) const {
  300. static Value null_value;
  301. assert(IsObject());
  302. Object::const_iterator it = object_value_.find(key);
  303. return (it != object_value_.end()) ? it->second : null_value;
  304. }
  305. size_t ArrayLen() const {
  306. if (!IsArray()) return 0;
  307. return array_value_.size();
  308. }
  309. // Valid only for object type.
  310. bool Has(const std::string &key) const {
  311. if (!IsObject()) return false;
  312. Object::const_iterator it = object_value_.find(key);
  313. return (it != object_value_.end()) ? true : false;
  314. }
  315. // List keys
  316. std::vector<std::string> Keys() const {
  317. std::vector<std::string> keys;
  318. if (!IsObject()) return keys; // empty
  319. for (Object::const_iterator it = object_value_.begin();
  320. it != object_value_.end(); ++it) {
  321. keys.push_back(it->first);
  322. }
  323. return keys;
  324. }
  325. size_t Size() const { return (IsArray() ? ArrayLen() : Keys().size()); }
  326. bool operator==(const tinygltf::Value &other) const;
  327. protected:
  328. int type_ = NULL_TYPE;
  329. int int_value_ = 0;
  330. double real_value_ = 0.0;
  331. std::string string_value_;
  332. std::vector<unsigned char> binary_value_;
  333. Array array_value_;
  334. Object object_value_;
  335. bool boolean_value_ = false;
  336. };
  337. #ifdef __clang__
  338. #pragma clang diagnostic pop
  339. #endif
  340. #define TINYGLTF_VALUE_GET(ctype, var) \
  341. template <> \
  342. inline const ctype &Value::Get<ctype>() const { \
  343. return var; \
  344. } \
  345. template <> \
  346. inline ctype &Value::Get<ctype>() { \
  347. return var; \
  348. }
  349. TINYGLTF_VALUE_GET(bool, boolean_value_)
  350. TINYGLTF_VALUE_GET(double, real_value_)
  351. TINYGLTF_VALUE_GET(int, int_value_)
  352. TINYGLTF_VALUE_GET(std::string, string_value_)
  353. TINYGLTF_VALUE_GET(std::vector<unsigned char>, binary_value_)
  354. TINYGLTF_VALUE_GET(Value::Array, array_value_)
  355. TINYGLTF_VALUE_GET(Value::Object, object_value_)
  356. #undef TINYGLTF_VALUE_GET
  357. #ifdef __clang__
  358. #pragma clang diagnostic push
  359. #pragma clang diagnostic ignored "-Wc++98-compat"
  360. #pragma clang diagnostic ignored "-Wpadded"
  361. #endif
  362. /// Aggregate object for representing a color
  363. using ColorValue = std::array<double, 4>;
  364. // === legacy interface ====
  365. // TODO(syoyo): Deprecate `Parameter` class.
  366. struct Parameter {
  367. bool bool_value = false;
  368. bool has_number_value = false;
  369. std::string string_value;
  370. std::vector<double> number_array;
  371. std::map<std::string, double> json_double_value;
  372. double number_value = 0.0;
  373. // context sensitive methods. depending the type of the Parameter you are
  374. // accessing, these are either valid or not
  375. // If this parameter represent a texture map in a material, will return the
  376. // texture index
  377. /// Return the index of a texture if this Parameter is a texture map.
  378. /// Returned value is only valid if the parameter represent a texture from a
  379. /// material
  380. int TextureIndex() const {
  381. const auto it = json_double_value.find("index");
  382. if (it != std::end(json_double_value)) {
  383. return int(it->second);
  384. }
  385. return -1;
  386. }
  387. /// Return the index of a texture coordinate set if this Parameter is a
  388. /// texture map. Returned value is only valid if the parameter represent a
  389. /// texture from a material
  390. int TextureTexCoord() const {
  391. const auto it = json_double_value.find("texCoord");
  392. if (it != std::end(json_double_value)) {
  393. return int(it->second);
  394. }
  395. // As per the spec, if texCoord is omitted, this parameter is 0
  396. return 0;
  397. }
  398. /// Return the scale of a texture if this Parameter is a normal texture map.
  399. /// Returned value is only valid if the parameter represent a normal texture
  400. /// from a material
  401. double TextureScale() const {
  402. const auto it = json_double_value.find("scale");
  403. if (it != std::end(json_double_value)) {
  404. return it->second;
  405. }
  406. // As per the spec, if scale is omitted, this parameter is 1
  407. return 1;
  408. }
  409. /// Return the strength of a texture if this Parameter is a an occlusion map.
  410. /// Returned value is only valid if the parameter represent an occlusion map
  411. /// from a material
  412. double TextureStrength() const {
  413. const auto it = json_double_value.find("strength");
  414. if (it != std::end(json_double_value)) {
  415. return it->second;
  416. }
  417. // As per the spec, if strength is omitted, this parameter is 1
  418. return 1;
  419. }
  420. /// Material factor, like the roughness or metalness of a material
  421. /// Returned value is only valid if the parameter represent a texture from a
  422. /// material
  423. double Factor() const { return number_value; }
  424. /// Return the color of a material
  425. /// Returned value is only valid if the parameter represent a texture from a
  426. /// material
  427. ColorValue ColorFactor() const {
  428. return {
  429. {// this aggregate initialize the std::array object, and uses C++11 RVO.
  430. number_array[0], number_array[1], number_array[2],
  431. (number_array.size() > 3 ? number_array[3] : 1.0)}};
  432. }
  433. Parameter() = default;
  434. DEFAULT_METHODS(Parameter)
  435. bool operator==(const Parameter &) const;
  436. };
  437. #ifdef __clang__
  438. #pragma clang diagnostic pop
  439. #endif
  440. #ifdef __clang__
  441. #pragma clang diagnostic push
  442. #pragma clang diagnostic ignored "-Wpadded"
  443. #endif
  444. typedef std::map<std::string, Parameter> ParameterMap;
  445. typedef std::map<std::string, Value> ExtensionMap;
  446. struct AnimationChannel {
  447. int sampler{-1}; // required
  448. int target_node{-1}; // optional index of the node to target (alternative
  449. // target should be provided by extension)
  450. std::string target_path; // required with standard values of ["translation",
  451. // "rotation", "scale", "weights"]
  452. Value extras;
  453. ExtensionMap extensions;
  454. Value target_extras;
  455. ExtensionMap target_extensions;
  456. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  457. std::string extras_json_string;
  458. std::string extensions_json_string;
  459. std::string target_extras_json_string;
  460. std::string target_extensions_json_string;
  461. AnimationChannel() = default;
  462. DEFAULT_METHODS(AnimationChannel)
  463. bool operator==(const AnimationChannel &) const;
  464. };
  465. struct AnimationSampler {
  466. int input{-1}; // required
  467. int output{-1}; // required
  468. std::string interpolation; // "LINEAR", "STEP","CUBICSPLINE" or user defined
  469. // string. default "LINEAR"
  470. Value extras;
  471. ExtensionMap extensions;
  472. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  473. std::string extras_json_string;
  474. std::string extensions_json_string;
  475. AnimationSampler() : interpolation("LINEAR") {}
  476. DEFAULT_METHODS(AnimationSampler)
  477. bool operator==(const AnimationSampler &) const;
  478. };
  479. struct Animation {
  480. std::string name;
  481. std::vector<AnimationChannel> channels;
  482. std::vector<AnimationSampler> samplers;
  483. Value extras;
  484. ExtensionMap extensions;
  485. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  486. std::string extras_json_string;
  487. std::string extensions_json_string;
  488. Animation() = default;
  489. DEFAULT_METHODS(Animation)
  490. bool operator==(const Animation &) const;
  491. };
  492. struct Skin {
  493. std::string name;
  494. int inverseBindMatrices{-1}; // required here but not in the spec
  495. int skeleton{-1}; // The index of the node used as a skeleton root
  496. std::vector<int> joints; // Indices of skeleton nodes
  497. Value extras;
  498. ExtensionMap extensions;
  499. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  500. std::string extras_json_string;
  501. std::string extensions_json_string;
  502. Skin() = default;
  503. DEFAULT_METHODS(Skin)
  504. bool operator==(const Skin &) const;
  505. };
  506. struct Sampler {
  507. std::string name;
  508. // glTF 2.0 spec does not define default value for `minFilter` and
  509. // `magFilter`. Set -1 in TinyGLTF(issue #186)
  510. int minFilter =
  511. -1; // optional. -1 = no filter defined. ["NEAREST", "LINEAR",
  512. // "NEAREST_MIPMAP_NEAREST", "LINEAR_MIPMAP_NEAREST",
  513. // "NEAREST_MIPMAP_LINEAR", "LINEAR_MIPMAP_LINEAR"]
  514. int magFilter =
  515. -1; // optional. -1 = no filter defined. ["NEAREST", "LINEAR"]
  516. int wrapS =
  517. TINYGLTF_TEXTURE_WRAP_REPEAT; // ["CLAMP_TO_EDGE", "MIRRORED_REPEAT",
  518. // "REPEAT"], default "REPEAT"
  519. int wrapT =
  520. TINYGLTF_TEXTURE_WRAP_REPEAT; // ["CLAMP_TO_EDGE", "MIRRORED_REPEAT",
  521. // "REPEAT"], default "REPEAT"
  522. // int wrapR = TINYGLTF_TEXTURE_WRAP_REPEAT; // TinyGLTF extension. currently
  523. // not used.
  524. Value extras;
  525. ExtensionMap extensions;
  526. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  527. std::string extras_json_string;
  528. std::string extensions_json_string;
  529. Sampler() = default;
  530. DEFAULT_METHODS(Sampler)
  531. bool operator==(const Sampler &) const;
  532. };
  533. struct Image {
  534. std::string name;
  535. int width{-1};
  536. int height{-1};
  537. int component{-1};
  538. int bits{-1}; // bit depth per channel. 8(byte), 16 or 32.
  539. int pixel_type{-1}; // pixel type(TINYGLTF_COMPONENT_TYPE_***). usually
  540. // UBYTE(bits = 8) or USHORT(bits = 16)
  541. std::vector<unsigned char> image;
  542. int bufferView{-1}; // (required if no uri)
  543. std::string mimeType; // (required if no uri) ["image/jpeg", "image/png",
  544. // "image/bmp", "image/gif"]
  545. std::string uri; // (required if no mimeType) uri is not decoded(e.g.
  546. // whitespace may be represented as %20)
  547. Value extras;
  548. ExtensionMap extensions;
  549. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  550. std::string extras_json_string;
  551. std::string extensions_json_string;
  552. // When this flag is true, data is stored to `image` in as-is format(e.g. jpeg
  553. // compressed for "image/jpeg" mime) This feature is good if you use custom
  554. // image loader function. (e.g. delayed decoding of images for faster glTF
  555. // parsing) Default parser for Image does not provide as-is loading feature at
  556. // the moment. (You can manipulate this by providing your own LoadImageData
  557. // function)
  558. bool as_is{false};
  559. Image() = default;
  560. DEFAULT_METHODS(Image)
  561. bool operator==(const Image &) const;
  562. };
  563. struct Texture {
  564. std::string name;
  565. int sampler{-1};
  566. int source{-1};
  567. Value extras;
  568. ExtensionMap extensions;
  569. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  570. std::string extras_json_string;
  571. std::string extensions_json_string;
  572. Texture() = default;
  573. DEFAULT_METHODS(Texture)
  574. bool operator==(const Texture &) const;
  575. };
  576. struct TextureInfo {
  577. int index{-1}; // required.
  578. int texCoord{0}; // The set index of texture's TEXCOORD attribute used for
  579. // texture coordinate mapping.
  580. Value extras;
  581. ExtensionMap extensions;
  582. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  583. std::string extras_json_string;
  584. std::string extensions_json_string;
  585. TextureInfo() = default;
  586. DEFAULT_METHODS(TextureInfo)
  587. bool operator==(const TextureInfo &) const;
  588. };
  589. struct NormalTextureInfo {
  590. int index{-1}; // required
  591. int texCoord{0}; // The set index of texture's TEXCOORD attribute used for
  592. // texture coordinate mapping.
  593. double scale{
  594. 1.0}; // scaledNormal = normalize((<sampled normal texture value>
  595. // * 2.0 - 1.0) * vec3(<normal scale>, <normal scale>, 1.0))
  596. Value extras;
  597. ExtensionMap extensions;
  598. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  599. std::string extras_json_string;
  600. std::string extensions_json_string;
  601. NormalTextureInfo() = default;
  602. DEFAULT_METHODS(NormalTextureInfo)
  603. bool operator==(const NormalTextureInfo &) const;
  604. };
  605. struct OcclusionTextureInfo {
  606. int index{-1}; // required
  607. int texCoord{0}; // The set index of texture's TEXCOORD attribute used for
  608. // texture coordinate mapping.
  609. double strength{1.0}; // occludedColor = lerp(color, color * <sampled
  610. // occlusion texture value>, <occlusion strength>)
  611. Value extras;
  612. ExtensionMap extensions;
  613. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  614. std::string extras_json_string;
  615. std::string extensions_json_string;
  616. OcclusionTextureInfo() = default;
  617. DEFAULT_METHODS(OcclusionTextureInfo)
  618. bool operator==(const OcclusionTextureInfo &) const;
  619. };
  620. // pbrMetallicRoughness class defined in glTF 2.0 spec.
  621. struct PbrMetallicRoughness {
  622. std::vector<double> baseColorFactor; // len = 4. default [1,1,1,1]
  623. TextureInfo baseColorTexture;
  624. double metallicFactor{1.0}; // default 1
  625. double roughnessFactor{1.0}; // default 1
  626. TextureInfo metallicRoughnessTexture;
  627. Value extras;
  628. ExtensionMap extensions;
  629. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  630. std::string extras_json_string;
  631. std::string extensions_json_string;
  632. PbrMetallicRoughness()
  633. : baseColorFactor(std::vector<double>{1.0, 1.0, 1.0, 1.0}) {}
  634. DEFAULT_METHODS(PbrMetallicRoughness)
  635. bool operator==(const PbrMetallicRoughness &) const;
  636. };
  637. // Each extension should be stored in a ParameterMap.
  638. // members not in the values could be included in the ParameterMap
  639. // to keep a single material model
  640. struct Material {
  641. std::string name;
  642. std::vector<double> emissiveFactor; // length 3. default [0, 0, 0]
  643. std::string alphaMode; // default "OPAQUE"
  644. double alphaCutoff{0.5}; // default 0.5
  645. bool doubleSided{false}; // default false;
  646. PbrMetallicRoughness pbrMetallicRoughness;
  647. NormalTextureInfo normalTexture;
  648. OcclusionTextureInfo occlusionTexture;
  649. TextureInfo emissiveTexture;
  650. // For backward compatibility
  651. // TODO(syoyo): Remove `values` and `additionalValues` in the next release.
  652. ParameterMap values;
  653. ParameterMap additionalValues;
  654. ExtensionMap extensions;
  655. Value extras;
  656. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  657. std::string extras_json_string;
  658. std::string extensions_json_string;
  659. Material() : alphaMode("OPAQUE") {}
  660. DEFAULT_METHODS(Material)
  661. bool operator==(const Material &) const;
  662. };
  663. struct BufferView {
  664. std::string name;
  665. int buffer{-1}; // Required
  666. size_t byteOffset{0}; // minimum 0, default 0
  667. size_t byteLength{0}; // required, minimum 1. 0 = invalid
  668. size_t byteStride{0}; // minimum 4, maximum 252 (multiple of 4), default 0 =
  669. // understood to be tightly packed
  670. int target{0}; // ["ARRAY_BUFFER", "ELEMENT_ARRAY_BUFFER"] for vertex indices
  671. // or attribs. Could be 0 for other data
  672. Value extras;
  673. ExtensionMap extensions;
  674. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  675. std::string extras_json_string;
  676. std::string extensions_json_string;
  677. bool dracoDecoded{false}; // Flag indicating this has been draco decoded
  678. BufferView() = default;
  679. DEFAULT_METHODS(BufferView)
  680. bool operator==(const BufferView &) const;
  681. };
  682. struct Accessor {
  683. int bufferView{-1}; // optional in spec but required here since sparse
  684. // accessor are not supported
  685. std::string name;
  686. size_t byteOffset{0};
  687. bool normalized{false}; // optional.
  688. int componentType{-1}; // (required) One of TINYGLTF_COMPONENT_TYPE_***
  689. size_t count{0}; // required
  690. int type{-1}; // (required) One of TINYGLTF_TYPE_*** ..
  691. Value extras;
  692. ExtensionMap extensions;
  693. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  694. std::string extras_json_string;
  695. std::string extensions_json_string;
  696. std::vector<double>
  697. minValues; // optional. integer value is promoted to double
  698. std::vector<double>
  699. maxValues; // optional. integer value is promoted to double
  700. struct Sparse {
  701. int count;
  702. bool isSparse;
  703. struct {
  704. size_t byteOffset;
  705. int bufferView;
  706. int componentType; // a TINYGLTF_COMPONENT_TYPE_ value
  707. Value extras;
  708. ExtensionMap extensions;
  709. std::string extras_json_string;
  710. std::string extensions_json_string;
  711. } indices;
  712. struct {
  713. int bufferView;
  714. size_t byteOffset;
  715. Value extras;
  716. ExtensionMap extensions;
  717. std::string extras_json_string;
  718. std::string extensions_json_string;
  719. } values;
  720. Value extras;
  721. ExtensionMap extensions;
  722. std::string extras_json_string;
  723. std::string extensions_json_string;
  724. };
  725. Sparse sparse;
  726. ///
  727. /// Utility function to compute byteStride for a given bufferView object.
  728. /// Returns -1 upon invalid glTF value or parameter configuration.
  729. ///
  730. int ByteStride(const BufferView &bufferViewObject) const {
  731. if (bufferViewObject.byteStride == 0) {
  732. // Assume data is tightly packed.
  733. int componentSizeInBytes =
  734. GetComponentSizeInBytes(static_cast<uint32_t>(componentType));
  735. if (componentSizeInBytes <= 0) {
  736. return -1;
  737. }
  738. int numComponents = GetNumComponentsInType(static_cast<uint32_t>(type));
  739. if (numComponents <= 0) {
  740. return -1;
  741. }
  742. return componentSizeInBytes * numComponents;
  743. } else {
  744. // Check if byteStride is a multiple of the size of the accessor's
  745. // component type.
  746. int componentSizeInBytes =
  747. GetComponentSizeInBytes(static_cast<uint32_t>(componentType));
  748. if (componentSizeInBytes <= 0) {
  749. return -1;
  750. }
  751. if ((bufferViewObject.byteStride % uint32_t(componentSizeInBytes)) != 0) {
  752. return -1;
  753. }
  754. return static_cast<int>(bufferViewObject.byteStride);
  755. }
  756. // unreachable return 0;
  757. }
  758. Accessor()
  759. {
  760. sparse.isSparse = false;
  761. }
  762. DEFAULT_METHODS(Accessor)
  763. bool operator==(const tinygltf::Accessor &) const;
  764. };
  765. struct PerspectiveCamera {
  766. double aspectRatio{0.0}; // min > 0
  767. double yfov{0.0}; // required. min > 0
  768. double zfar{0.0}; // min > 0
  769. double znear{0.0}; // required. min > 0
  770. PerspectiveCamera() = default;
  771. DEFAULT_METHODS(PerspectiveCamera)
  772. bool operator==(const PerspectiveCamera &) const;
  773. ExtensionMap extensions;
  774. Value extras;
  775. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  776. std::string extras_json_string;
  777. std::string extensions_json_string;
  778. };
  779. struct OrthographicCamera {
  780. double xmag{0.0}; // required. must not be zero.
  781. double ymag{0.0}; // required. must not be zero.
  782. double zfar{0.0}; // required. `zfar` must be greater than `znear`.
  783. double znear{0.0}; // required
  784. OrthographicCamera() = default;
  785. DEFAULT_METHODS(OrthographicCamera)
  786. bool operator==(const OrthographicCamera &) const;
  787. ExtensionMap extensions;
  788. Value extras;
  789. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  790. std::string extras_json_string;
  791. std::string extensions_json_string;
  792. };
  793. struct Camera {
  794. std::string type; // required. "perspective" or "orthographic"
  795. std::string name;
  796. PerspectiveCamera perspective;
  797. OrthographicCamera orthographic;
  798. Camera() = default;
  799. DEFAULT_METHODS(Camera)
  800. bool operator==(const Camera &) const;
  801. ExtensionMap extensions;
  802. Value extras;
  803. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  804. std::string extras_json_string;
  805. std::string extensions_json_string;
  806. };
  807. struct Primitive {
  808. std::map<std::string, int> attributes; // (required) A dictionary object of
  809. // integer, where each integer
  810. // is the index of the accessor
  811. // containing an attribute.
  812. int material{-1}; // The index of the material to apply to this primitive
  813. // when rendering.
  814. int indices{-1}; // The index of the accessor that contains the indices.
  815. int mode{-1}; // one of TINYGLTF_MODE_***
  816. std::vector<std::map<std::string, int> > targets; // array of morph targets,
  817. // where each target is a dict with attributes in ["POSITION, "NORMAL",
  818. // "TANGENT"] pointing
  819. // to their corresponding accessors
  820. ExtensionMap extensions;
  821. Value extras;
  822. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  823. std::string extras_json_string;
  824. std::string extensions_json_string;
  825. Primitive() = default;
  826. DEFAULT_METHODS(Primitive)
  827. bool operator==(const Primitive &) const;
  828. };
  829. struct Mesh {
  830. std::string name;
  831. std::vector<Primitive> primitives;
  832. std::vector<double> weights; // weights to be applied to the Morph Targets
  833. ExtensionMap extensions;
  834. Value extras;
  835. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  836. std::string extras_json_string;
  837. std::string extensions_json_string;
  838. Mesh() = default;
  839. DEFAULT_METHODS(Mesh)
  840. bool operator==(const Mesh &) const;
  841. };
  842. class Node {
  843. public:
  844. Node() = default;
  845. DEFAULT_METHODS(Node)
  846. bool operator==(const Node &) const;
  847. int camera{-1}; // the index of the camera referenced by this node
  848. std::string name;
  849. int skin{-1};
  850. int mesh{-1};
  851. int light{-1}; // light source index (KHR_lights_punctual)
  852. int emitter{-1}; // audio emitter index (KHR_audio)
  853. std::vector<int> children;
  854. std::vector<double> rotation; // length must be 0 or 4
  855. std::vector<double> scale; // length must be 0 or 3
  856. std::vector<double> translation; // length must be 0 or 3
  857. std::vector<double> matrix; // length must be 0 or 16
  858. std::vector<double> weights; // The weights of the instantiated Morph Target
  859. ExtensionMap extensions;
  860. Value extras;
  861. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  862. std::string extras_json_string;
  863. std::string extensions_json_string;
  864. };
  865. struct Buffer {
  866. std::string name;
  867. std::vector<unsigned char> data;
  868. std::string
  869. uri; // considered as required here but not in the spec (need to clarify)
  870. // uri is not decoded(e.g. whitespace may be represented as %20)
  871. Value extras;
  872. ExtensionMap extensions;
  873. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  874. std::string extras_json_string;
  875. std::string extensions_json_string;
  876. Buffer() = default;
  877. DEFAULT_METHODS(Buffer)
  878. bool operator==(const Buffer &) const;
  879. };
  880. struct Asset {
  881. std::string version = "2.0"; // required
  882. std::string generator;
  883. std::string minVersion;
  884. std::string copyright;
  885. ExtensionMap extensions;
  886. Value extras;
  887. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  888. std::string extras_json_string;
  889. std::string extensions_json_string;
  890. Asset() = default;
  891. DEFAULT_METHODS(Asset)
  892. bool operator==(const Asset &) const;
  893. };
  894. struct Scene {
  895. std::string name;
  896. std::vector<int> nodes;
  897. std::vector<int> audioEmitters; // KHR_audio global emitters
  898. ExtensionMap extensions;
  899. Value extras;
  900. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  901. std::string extras_json_string;
  902. std::string extensions_json_string;
  903. Scene() = default;
  904. DEFAULT_METHODS(Scene)
  905. bool operator==(const Scene &) const;
  906. };
  907. struct SpotLight {
  908. double innerConeAngle{0.0};
  909. double outerConeAngle{0.7853981634};
  910. SpotLight() = default;
  911. DEFAULT_METHODS(SpotLight)
  912. bool operator==(const SpotLight &) const;
  913. ExtensionMap extensions;
  914. Value extras;
  915. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  916. std::string extras_json_string;
  917. std::string extensions_json_string;
  918. };
  919. struct Light {
  920. std::string name;
  921. std::vector<double> color;
  922. double intensity{1.0};
  923. std::string type;
  924. double range{0.0}; // 0.0 = infinite
  925. SpotLight spot;
  926. Light() = default;
  927. DEFAULT_METHODS(Light)
  928. bool operator==(const Light &) const;
  929. ExtensionMap extensions;
  930. Value extras;
  931. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  932. std::string extras_json_string;
  933. std::string extensions_json_string;
  934. };
  935. struct PositionalEmitter {
  936. double coneInnerAngle{6.283185307179586};
  937. double coneOuterAngle{6.283185307179586};
  938. double coneOuterGain{0.0};
  939. double maxDistance{100.0};
  940. double refDistance{1.0};
  941. double rolloffFactor{1.0};
  942. PositionalEmitter() = default;
  943. DEFAULT_METHODS(PositionalEmitter)
  944. bool operator==(const PositionalEmitter &) const;
  945. ExtensionMap extensions;
  946. Value extras;
  947. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  948. std::string extras_json_string;
  949. std::string extensions_json_string;
  950. };
  951. struct AudioEmitter {
  952. std::string name;
  953. double gain{1.0};
  954. bool loop{false};
  955. bool playing{false};
  956. std::string
  957. type; // positional - Positional audio emitters. Using sound cones, the
  958. // orientation is +Z having the same front side for a glTF asset.
  959. // global - Global audio emitters are not affected by the position
  960. // of audio listeners. coneInnerAngle, coneOuterAngle,
  961. // coneOuterGain, distanceModel, maxDistance, refDistance, and
  962. // rolloffFactor should all be ignored when set.
  963. std::string
  964. distanceModel; // linear - A linear distance model calculating the
  965. // gain induced by the distance according to: 1.0
  966. // - rolloffFactor * (distance - refDistance) /
  967. // (maxDistance - refDistance)
  968. // inverse - (default) An inverse distance model
  969. // calculating the gain induced by the distance according
  970. // to: refDistance / (refDistance + rolloffFactor *
  971. // (Math.max(distance, refDistance) - refDistance))
  972. // exponential - An exponential distance model calculating
  973. // the gain induced by the distance according to:
  974. // pow((Math.max(distance, refDistance) / refDistance,
  975. // -rolloffFactor))
  976. PositionalEmitter positional;
  977. int source{-1};
  978. AudioEmitter() : type("global"), distanceModel("inverse") {}
  979. DEFAULT_METHODS(AudioEmitter)
  980. bool operator==(const AudioEmitter &) const;
  981. ExtensionMap extensions;
  982. Value extras;
  983. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  984. std::string extras_json_string;
  985. std::string extensions_json_string;
  986. };
  987. struct AudioSource {
  988. std::string name;
  989. std::string uri;
  990. int bufferView{-1}; // (required if no uri)
  991. std::string
  992. mimeType; // (required if no uri) The audio's MIME type. Required if
  993. // bufferView is defined. Unless specified by another
  994. // extension, the only supported mimeType is audio/mpeg.
  995. AudioSource() = default;
  996. DEFAULT_METHODS(AudioSource)
  997. bool operator==(const AudioSource &) const;
  998. Value extras;
  999. ExtensionMap extensions;
  1000. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  1001. std::string extras_json_string;
  1002. std::string extensions_json_string;
  1003. };
  1004. class Model {
  1005. public:
  1006. Model() = default;
  1007. DEFAULT_METHODS(Model)
  1008. bool operator==(const Model &) const;
  1009. std::vector<Accessor> accessors;
  1010. std::vector<Animation> animations;
  1011. std::vector<Buffer> buffers;
  1012. std::vector<BufferView> bufferViews;
  1013. std::vector<Material> materials;
  1014. std::vector<Mesh> meshes;
  1015. std::vector<Node> nodes;
  1016. std::vector<Texture> textures;
  1017. std::vector<Image> images;
  1018. std::vector<Skin> skins;
  1019. std::vector<Sampler> samplers;
  1020. std::vector<Camera> cameras;
  1021. std::vector<Scene> scenes;
  1022. std::vector<Light> lights;
  1023. std::vector<AudioEmitter> audioEmitters;
  1024. std::vector<AudioSource> audioSources;
  1025. int defaultScene{-1};
  1026. std::vector<std::string> extensionsUsed;
  1027. std::vector<std::string> extensionsRequired;
  1028. Asset asset;
  1029. Value extras;
  1030. ExtensionMap extensions;
  1031. // Filled when SetStoreOriginalJSONForExtrasAndExtensions is enabled.
  1032. std::string extras_json_string;
  1033. std::string extensions_json_string;
  1034. };
  1035. enum SectionCheck {
  1036. NO_REQUIRE = 0x00,
  1037. REQUIRE_VERSION = 0x01,
  1038. REQUIRE_SCENE = 0x02,
  1039. REQUIRE_SCENES = 0x04,
  1040. REQUIRE_NODES = 0x08,
  1041. REQUIRE_ACCESSORS = 0x10,
  1042. REQUIRE_BUFFERS = 0x20,
  1043. REQUIRE_BUFFER_VIEWS = 0x40,
  1044. REQUIRE_ALL = 0x7f
  1045. };
  1046. ///
  1047. /// URIEncodeFunction type. Signature for custom URI encoding of external
  1048. /// resources such as .bin and image files. Used by tinygltf to re-encode the
  1049. /// final location of saved files. object_type may be used to encode buffer and
  1050. /// image URIs differently, for example. See
  1051. /// https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#uris
  1052. ///
  1053. typedef bool (*URIEncodeFunction)(const std::string &in_uri,
  1054. const std::string &object_type,
  1055. std::string *out_uri, void *user_data);
  1056. ///
  1057. /// URIDecodeFunction type. Signature for custom URI decoding of external
  1058. /// resources such as .bin and image files. Used by tinygltf when computing
  1059. /// filenames to write resources.
  1060. ///
  1061. typedef bool (*URIDecodeFunction)(const std::string &in_uri,
  1062. std::string *out_uri, void *user_data);
  1063. // Declaration of default uri decode function
  1064. bool URIDecode(const std::string &in_uri, std::string *out_uri,
  1065. void *user_data);
  1066. ///
  1067. /// A structure containing URI callbacks and a pointer to their user data.
  1068. ///
  1069. struct URICallbacks {
  1070. URIEncodeFunction encode; // Optional encode method
  1071. URIDecodeFunction decode; // Required decode method
  1072. void *user_data; // An argument that is passed to all uri callbacks
  1073. };
  1074. ///
  1075. /// LoadImageDataFunction type. Signature for custom image loading callbacks.
  1076. ///
  1077. typedef bool (*LoadImageDataFunction)(Image *, const int, std::string *,
  1078. std::string *, int, int,
  1079. const unsigned char *, int,
  1080. void *user_pointer);
  1081. ///
  1082. /// WriteImageDataFunction type. Signature for custom image writing callbacks.
  1083. /// The out_uri parameter becomes the URI written to the gltf and may reference
  1084. /// a file or contain a data URI.
  1085. ///
  1086. typedef bool (*WriteImageDataFunction)(const std::string *basepath,
  1087. const std::string *filename,
  1088. const Image *image, bool embedImages,
  1089. const URICallbacks *uri_cb,
  1090. std::string *out_uri,
  1091. void *user_pointer);
  1092. #ifndef TINYGLTF_NO_STB_IMAGE
  1093. // Declaration of default image loader callback
  1094. bool LoadImageData(Image *image, const int image_idx, std::string *err,
  1095. std::string *warn, int req_width, int req_height,
  1096. const unsigned char *bytes, int size, void *);
  1097. #endif
  1098. #ifndef TINYGLTF_NO_STB_IMAGE_WRITE
  1099. // Declaration of default image writer callback
  1100. bool WriteImageData(const std::string *basepath, const std::string *filename,
  1101. const Image *image, bool embedImages,
  1102. const URICallbacks *uri_cb, std::string *out_uri, void *);
  1103. #endif
  1104. ///
  1105. /// FilExistsFunction type. Signature for custom filesystem callbacks.
  1106. ///
  1107. typedef bool (*FileExistsFunction)(const std::string &abs_filename, void *);
  1108. ///
  1109. /// ExpandFilePathFunction type. Signature for custom filesystem callbacks.
  1110. ///
  1111. typedef std::string (*ExpandFilePathFunction)(const std::string &, void *);
  1112. ///
  1113. /// ReadWholeFileFunction type. Signature for custom filesystem callbacks.
  1114. ///
  1115. typedef bool (*ReadWholeFileFunction)(std::vector<unsigned char> *,
  1116. std::string *, const std::string &,
  1117. void *);
  1118. ///
  1119. /// WriteWholeFileFunction type. Signature for custom filesystem callbacks.
  1120. ///
  1121. typedef bool (*WriteWholeFileFunction)(std::string *, const std::string &,
  1122. const std::vector<unsigned char> &,
  1123. void *);
  1124. ///
  1125. /// GetFileSizeFunction type. Signature for custom filesystem callbacks.
  1126. ///
  1127. typedef bool (*GetFileSizeFunction)(size_t *filesize_out, std::string *err,
  1128. const std::string &abs_filename,
  1129. void *userdata);
  1130. ///
  1131. /// A structure containing all required filesystem callbacks and a pointer to
  1132. /// their user data.
  1133. ///
  1134. struct FsCallbacks {
  1135. FileExistsFunction FileExists;
  1136. ExpandFilePathFunction ExpandFilePath;
  1137. ReadWholeFileFunction ReadWholeFile;
  1138. WriteWholeFileFunction WriteWholeFile;
  1139. GetFileSizeFunction GetFileSizeInBytes; // To avoid GetFileSize Win32 API,
  1140. // add `InBytes` suffix.
  1141. void *user_data; // An argument that is passed to all fs callbacks
  1142. };
  1143. #ifndef TINYGLTF_NO_FS
  1144. // Declaration of default filesystem callbacks
  1145. bool FileExists(const std::string &abs_filename, void *);
  1146. ///
  1147. /// Expand file path(e.g. `~` to home directory on posix, `%APPDATA%` to
  1148. /// `C:\\Users\\tinygltf\\AppData`)
  1149. ///
  1150. /// @param[in] filepath File path string. Assume UTF-8
  1151. /// @param[in] userdata User data. Set to `nullptr` if you don't need it.
  1152. ///
  1153. std::string ExpandFilePath(const std::string &filepath, void *userdata);
  1154. bool ReadWholeFile(std::vector<unsigned char> *out, std::string *err,
  1155. const std::string &filepath, void *);
  1156. bool WriteWholeFile(std::string *err, const std::string &filepath,
  1157. const std::vector<unsigned char> &contents, void *);
  1158. bool GetFileSizeInBytes(size_t *filesize_out, std::string *err,
  1159. const std::string &filepath, void *);
  1160. #endif
  1161. ///
  1162. /// glTF Parser/Serializer context.
  1163. ///
  1164. class TinyGLTF {
  1165. public:
  1166. #ifdef __clang__
  1167. #pragma clang diagnostic push
  1168. #pragma clang diagnostic ignored "-Wc++98-compat"
  1169. #endif
  1170. TinyGLTF() = default;
  1171. #ifdef __clang__
  1172. #pragma clang diagnostic pop
  1173. #endif
  1174. ~TinyGLTF() = default;
  1175. ///
  1176. /// Loads glTF ASCII asset from a file.
  1177. /// Set warning message to `warn` for example it fails to load asserts.
  1178. /// Returns false and set error string to `err` if there's an error.
  1179. ///
  1180. bool LoadASCIIFromFile(Model *model, std::string *err, std::string *warn,
  1181. const std::string &filename,
  1182. unsigned int check_sections = REQUIRE_VERSION);
  1183. ///
  1184. /// Loads glTF ASCII asset from string(memory).
  1185. /// `length` = strlen(str);
  1186. /// `base_dir` is a search path of glTF asset(e.g. images). Path Must be an
  1187. /// expanded path (e.g. no tilde(`~`), no environment variables). Set warning
  1188. /// message to `warn` for example it fails to load asserts. Returns false and
  1189. /// set error string to `err` if there's an error.
  1190. ///
  1191. bool LoadASCIIFromString(Model *model, std::string *err, std::string *warn,
  1192. const char *str, const unsigned int length,
  1193. const std::string &base_dir,
  1194. unsigned int check_sections = REQUIRE_VERSION);
  1195. ///
  1196. /// Loads glTF binary asset from a file.
  1197. /// Set warning message to `warn` for example it fails to load asserts.
  1198. /// Returns false and set error string to `err` if there's an error.
  1199. ///
  1200. bool LoadBinaryFromFile(Model *model, std::string *err, std::string *warn,
  1201. const std::string &filename,
  1202. unsigned int check_sections = REQUIRE_VERSION);
  1203. ///
  1204. /// Loads glTF binary asset from memory.
  1205. /// `length` = strlen(str);
  1206. /// `base_dir` is a search path of glTF asset(e.g. images). Path Must be an
  1207. /// expanded path (e.g. no tilde(`~`), no environment variables).
  1208. /// Set warning message to `warn` for example it fails to load asserts.
  1209. /// Returns false and set error string to `err` if there's an error.
  1210. ///
  1211. bool LoadBinaryFromMemory(Model *model, std::string *err, std::string *warn,
  1212. const unsigned char *bytes,
  1213. const unsigned int length,
  1214. const std::string &base_dir = "",
  1215. unsigned int check_sections = REQUIRE_VERSION);
  1216. ///
  1217. /// Write glTF to stream, buffers and images will be embedded
  1218. ///
  1219. bool WriteGltfSceneToStream(const Model *model, std::ostream &stream,
  1220. bool prettyPrint, bool writeBinary);
  1221. ///
  1222. /// Write glTF to file.
  1223. ///
  1224. bool WriteGltfSceneToFile(const Model *model, const std::string &filename,
  1225. bool embedImages, bool embedBuffers,
  1226. bool prettyPrint, bool writeBinary);
  1227. ///
  1228. /// Sets the parsing strictness.
  1229. ///
  1230. void SetParseStrictness(ParseStrictness strictness);
  1231. ///
  1232. /// Set callback to use for loading image data
  1233. ///
  1234. void SetImageLoader(LoadImageDataFunction LoadImageData, void *user_data);
  1235. ///
  1236. /// Unset(remove) callback of loading image data
  1237. ///
  1238. void RemoveImageLoader();
  1239. ///
  1240. /// Set callback to use for writing image data
  1241. ///
  1242. void SetImageWriter(WriteImageDataFunction WriteImageData, void *user_data);
  1243. ///
  1244. /// Set callbacks to use for URI encoding and decoding and their user data
  1245. ///
  1246. void SetURICallbacks(URICallbacks callbacks);
  1247. ///
  1248. /// Set callbacks to use for filesystem (fs) access and their user data
  1249. ///
  1250. void SetFsCallbacks(FsCallbacks callbacks);
  1251. ///
  1252. /// Set serializing default values(default = false).
  1253. /// When true, default values are force serialized to .glTF.
  1254. /// This may be helpful if you want to serialize a full description of glTF
  1255. /// data.
  1256. ///
  1257. /// TODO(LTE): Supply parsing option as function arguments to
  1258. /// `LoadASCIIFromFile()` and others, not by a class method
  1259. ///
  1260. void SetSerializeDefaultValues(const bool enabled) {
  1261. serialize_default_values_ = enabled;
  1262. }
  1263. bool GetSerializeDefaultValues() const { return serialize_default_values_; }
  1264. ///
  1265. /// Store original JSON string for `extras` and `extensions`.
  1266. /// This feature will be useful when the user want to reconstruct custom data
  1267. /// structure from JSON string.
  1268. ///
  1269. void SetStoreOriginalJSONForExtrasAndExtensions(const bool enabled) {
  1270. store_original_json_for_extras_and_extensions_ = enabled;
  1271. }
  1272. bool GetStoreOriginalJSONForExtrasAndExtensions() const {
  1273. return store_original_json_for_extras_and_extensions_;
  1274. }
  1275. ///
  1276. /// Specify whether preserve image channels when loading images or not.
  1277. /// (Not effective when the user supplies their own LoadImageData callbacks)
  1278. ///
  1279. void SetPreserveImageChannels(bool onoff) {
  1280. preserve_image_channels_ = onoff;
  1281. }
  1282. ///
  1283. /// Set maximum allowed external file size in bytes.
  1284. /// Default: 2GB
  1285. /// Only effective for built-in ReadWholeFileFunction FS function.
  1286. ///
  1287. void SetMaxExternalFileSize(size_t max_bytes) {
  1288. max_external_file_size_ = max_bytes;
  1289. }
  1290. size_t GetMaxExternalFileSize() const { return max_external_file_size_; }
  1291. bool GetPreserveImageChannels() const { return preserve_image_channels_; }
  1292. private:
  1293. ///
  1294. /// Loads glTF asset from string(memory).
  1295. /// `length` = strlen(str);
  1296. /// Set warning message to `warn` for example it fails to load asserts
  1297. /// Returns false and set error string to `err` if there's an error.
  1298. ///
  1299. bool LoadFromString(Model *model, std::string *err, std::string *warn,
  1300. const char *str, const unsigned int length,
  1301. const std::string &base_dir, unsigned int check_sections);
  1302. const unsigned char *bin_data_ = nullptr;
  1303. size_t bin_size_ = 0;
  1304. bool is_binary_ = false;
  1305. ParseStrictness strictness_ = ParseStrictness::Strict;
  1306. bool serialize_default_values_ = false; ///< Serialize default values?
  1307. bool store_original_json_for_extras_and_extensions_ = false;
  1308. bool preserve_image_channels_ = false; /// Default false(expand channels to
  1309. /// RGBA) for backward compatibility.
  1310. size_t max_external_file_size_{
  1311. size_t((std::numeric_limits<int32_t>::max)())}; // Default 2GB
  1312. // Warning & error messages
  1313. std::string warn_;
  1314. std::string err_;
  1315. FsCallbacks fs = {
  1316. #ifndef TINYGLTF_NO_FS
  1317. &tinygltf::FileExists,
  1318. &tinygltf::ExpandFilePath,
  1319. &tinygltf::ReadWholeFile,
  1320. &tinygltf::WriteWholeFile,
  1321. &tinygltf::GetFileSizeInBytes,
  1322. nullptr // Fs callback user data
  1323. #else
  1324. nullptr, nullptr, nullptr, nullptr, nullptr,
  1325. nullptr // Fs callback user data
  1326. #endif
  1327. };
  1328. URICallbacks uri_cb = {
  1329. // Use paths as-is by default. This will use JSON string escaping.
  1330. nullptr,
  1331. // Decode all URIs before using them as paths as the application may have
  1332. // percent encoded them.
  1333. &tinygltf::URIDecode,
  1334. // URI callback user data
  1335. nullptr};
  1336. LoadImageDataFunction LoadImageData =
  1337. #ifndef TINYGLTF_NO_STB_IMAGE
  1338. &tinygltf::LoadImageData;
  1339. #else
  1340. nullptr;
  1341. #endif
  1342. void *load_image_user_data_{nullptr};
  1343. bool user_image_loader_{false};
  1344. WriteImageDataFunction WriteImageData =
  1345. #ifndef TINYGLTF_NO_STB_IMAGE_WRITE
  1346. &tinygltf::WriteImageData;
  1347. #else
  1348. nullptr;
  1349. #endif
  1350. void *write_image_user_data_{nullptr};
  1351. };
  1352. #ifdef __clang__
  1353. #pragma clang diagnostic pop // -Wpadded
  1354. #endif
  1355. } // namespace tinygltf
  1356. #endif // TINY_GLTF_H_
  1357. #if defined(TINYGLTF_IMPLEMENTATION) || defined(__INTELLISENSE__)
  1358. #include <algorithm>
  1359. // #include <cassert>
  1360. #ifndef TINYGLTF_NO_FS
  1361. #include <sys/stat.h> // for is_directory check
  1362. #include <cstdio>
  1363. #include <fstream>
  1364. #endif
  1365. #include <sstream>
  1366. #ifdef __clang__
  1367. // Disable some warnings for external files.
  1368. #pragma clang diagnostic push
  1369. #pragma clang diagnostic ignored "-Wfloat-equal"
  1370. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  1371. #pragma clang diagnostic ignored "-Wconversion"
  1372. #pragma clang diagnostic ignored "-Wold-style-cast"
  1373. #pragma clang diagnostic ignored "-Wglobal-constructors"
  1374. #if __has_warning("-Wreserved-id-macro")
  1375. #pragma clang diagnostic ignored "-Wreserved-id-macro"
  1376. #endif
  1377. #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
  1378. #pragma clang diagnostic ignored "-Wpadded"
  1379. #pragma clang diagnostic ignored "-Wc++98-compat"
  1380. #pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
  1381. #pragma clang diagnostic ignored "-Wdocumentation-unknown-command"
  1382. #pragma clang diagnostic ignored "-Wswitch-enum"
  1383. #pragma clang diagnostic ignored "-Wimplicit-fallthrough"
  1384. #pragma clang diagnostic ignored "-Wweak-vtables"
  1385. #pragma clang diagnostic ignored "-Wcovered-switch-default"
  1386. #if __has_warning("-Wdouble-promotion")
  1387. #pragma clang diagnostic ignored "-Wdouble-promotion"
  1388. #endif
  1389. #if __has_warning("-Wcomma")
  1390. #pragma clang diagnostic ignored "-Wcomma"
  1391. #endif
  1392. #if __has_warning("-Wzero-as-null-pointer-constant")
  1393. #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
  1394. #endif
  1395. #if __has_warning("-Wcast-qual")
  1396. #pragma clang diagnostic ignored "-Wcast-qual"
  1397. #endif
  1398. #if __has_warning("-Wmissing-variable-declarations")
  1399. #pragma clang diagnostic ignored "-Wmissing-variable-declarations"
  1400. #endif
  1401. #if __has_warning("-Wmissing-prototypes")
  1402. #pragma clang diagnostic ignored "-Wmissing-prototypes"
  1403. #endif
  1404. #if __has_warning("-Wcast-align")
  1405. #pragma clang diagnostic ignored "-Wcast-align"
  1406. #endif
  1407. #if __has_warning("-Wnewline-eof")
  1408. #pragma clang diagnostic ignored "-Wnewline-eof"
  1409. #endif
  1410. #if __has_warning("-Wunused-parameter")
  1411. #pragma clang diagnostic ignored "-Wunused-parameter"
  1412. #endif
  1413. #if __has_warning("-Wmismatched-tags")
  1414. #pragma clang diagnostic ignored "-Wmismatched-tags"
  1415. #endif
  1416. #if __has_warning("-Wextra-semi-stmt")
  1417. #pragma clang diagnostic ignored "-Wextra-semi-stmt"
  1418. #endif
  1419. #endif
  1420. // Disable GCC warnings
  1421. #ifdef __GNUC__
  1422. #pragma GCC diagnostic push
  1423. #pragma GCC diagnostic ignored "-Wtype-limits"
  1424. #endif // __GNUC__
  1425. #ifndef TINYGLTF_NO_INCLUDE_JSON
  1426. #ifndef TINYGLTF_USE_RAPIDJSON
  1427. #include "json.hpp"
  1428. #else
  1429. #ifndef TINYGLTF_NO_INCLUDE_RAPIDJSON
  1430. #include "document.h"
  1431. #include "prettywriter.h"
  1432. #include "rapidjson.h"
  1433. #include "stringbuffer.h"
  1434. #include "writer.h"
  1435. #endif
  1436. #endif
  1437. #endif
  1438. #ifdef TINYGLTF_ENABLE_DRACO
  1439. #include "draco/compression/decode.h"
  1440. #include "draco/core/decoder_buffer.h"
  1441. #endif
  1442. #ifndef TINYGLTF_NO_STB_IMAGE
  1443. #ifndef TINYGLTF_NO_INCLUDE_STB_IMAGE
  1444. #include "stb_image.h"
  1445. #endif
  1446. #endif
  1447. #ifndef TINYGLTF_NO_STB_IMAGE_WRITE
  1448. #ifndef TINYGLTF_NO_INCLUDE_STB_IMAGE_WRITE
  1449. #include "stb_image_write.h"
  1450. #endif
  1451. #endif
  1452. #ifdef __clang__
  1453. #pragma clang diagnostic pop
  1454. #endif
  1455. #ifdef __GNUC__
  1456. #pragma GCC diagnostic pop
  1457. #endif
  1458. #ifdef _WIN32
  1459. // issue 143.
  1460. // Define NOMINMAX to avoid min/max defines,
  1461. // but undef it after included Windows.h
  1462. #ifndef NOMINMAX
  1463. #define TINYGLTF_INTERNAL_NOMINMAX
  1464. #define NOMINMAX
  1465. #endif
  1466. #ifndef WIN32_LEAN_AND_MEAN
  1467. #define WIN32_LEAN_AND_MEAN
  1468. #define TINYGLTF_INTERNAL_WIN32_LEAN_AND_MEAN
  1469. #endif
  1470. #ifndef __MINGW32__
  1471. #include <Windows.h> // include API for expanding a file path
  1472. #else
  1473. #include <windows.h>
  1474. #endif
  1475. #ifdef TINYGLTF_INTERNAL_WIN32_LEAN_AND_MEAN
  1476. #undef WIN32_LEAN_AND_MEAN
  1477. #endif
  1478. #if defined(TINYGLTF_INTERNAL_NOMINMAX)
  1479. #undef NOMINMAX
  1480. #endif
  1481. #if defined(__GLIBCXX__) // mingw
  1482. #include <fcntl.h> // _O_RDONLY
  1483. #include <ext/stdio_filebuf.h> // fstream (all sorts of IO stuff) + stdio_filebuf (=streambuf)
  1484. #endif
  1485. #elif !defined(__ANDROID__) && !defined(__OpenBSD__)
  1486. // #include <wordexp.h>
  1487. #endif
  1488. #if defined(__sparcv9) || defined(__powerpc__)
  1489. // Big endian
  1490. #else
  1491. #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU
  1492. #define TINYGLTF_LITTLE_ENDIAN 1
  1493. #endif
  1494. #endif
  1495. namespace tinygltf {
  1496. namespace detail {
  1497. #ifdef TINYGLTF_USE_RAPIDJSON
  1498. #ifdef TINYGLTF_USE_RAPIDJSON_CRTALLOCATOR
  1499. // This uses the RapidJSON CRTAllocator. It is thread safe and multiple
  1500. // documents may be active at once.
  1501. using json =
  1502. rapidjson::GenericValue<rapidjson::UTF8<>, rapidjson::CrtAllocator>;
  1503. using json_iterator = json::MemberIterator;
  1504. using json_const_iterator = json::ConstMemberIterator;
  1505. using json_const_array_iterator = json const *;
  1506. using JsonDocument =
  1507. rapidjson::GenericDocument<rapidjson::UTF8<>, rapidjson::CrtAllocator>;
  1508. rapidjson::CrtAllocator s_CrtAllocator; // stateless and thread safe
  1509. rapidjson::CrtAllocator &GetAllocator() { return s_CrtAllocator; }
  1510. #else
  1511. // This uses the default RapidJSON MemoryPoolAllocator. It is very fast, but
  1512. // not thread safe. Only a single JsonDocument may be active at any one time,
  1513. // meaning only a single gltf load/save can be active any one time.
  1514. using json = rapidjson::Value;
  1515. using json_iterator = json::MemberIterator;
  1516. using json_const_iterator = json::ConstMemberIterator;
  1517. using json_const_array_iterator = json const *;
  1518. rapidjson::Document *s_pActiveDocument = nullptr;
  1519. rapidjson::Document::AllocatorType &GetAllocator() {
  1520. assert(s_pActiveDocument); // Root json node must be JsonDocument type
  1521. return s_pActiveDocument->GetAllocator();
  1522. }
  1523. #ifdef __clang__
  1524. #pragma clang diagnostic push
  1525. // Suppress JsonDocument(JsonDocument &&rhs) noexcept
  1526. #pragma clang diagnostic ignored "-Wunused-member-function"
  1527. #endif
  1528. struct JsonDocument : public rapidjson::Document {
  1529. JsonDocument() {
  1530. assert(s_pActiveDocument ==
  1531. nullptr); // When using default allocator, only one document can be
  1532. // active at a time, if you need multiple active at once,
  1533. // define TINYGLTF_USE_RAPIDJSON_CRTALLOCATOR
  1534. s_pActiveDocument = this;
  1535. }
  1536. JsonDocument(const JsonDocument &) = delete;
  1537. JsonDocument(JsonDocument &&rhs) noexcept
  1538. : rapidjson::Document(std::move(rhs)) {
  1539. s_pActiveDocument = this;
  1540. rhs.isNil = true;
  1541. }
  1542. ~JsonDocument() {
  1543. if (!isNil) {
  1544. s_pActiveDocument = nullptr;
  1545. }
  1546. }
  1547. private:
  1548. bool isNil = false;
  1549. };
  1550. #ifdef __clang__
  1551. #pragma clang diagnostic pop
  1552. #endif
  1553. #endif // TINYGLTF_USE_RAPIDJSON_CRTALLOCATOR
  1554. #else
  1555. using nlohmann::json;
  1556. using json_iterator = json::iterator;
  1557. using json_const_iterator = json::const_iterator;
  1558. using json_const_array_iterator = json_const_iterator;
  1559. using JsonDocument = json;
  1560. #endif
  1561. void JsonParse(JsonDocument &doc, const char *str, size_t length,
  1562. bool throwExc = false) {
  1563. #ifdef TINYGLTF_USE_RAPIDJSON
  1564. (void)throwExc;
  1565. doc.Parse(str, length);
  1566. #else
  1567. doc = detail::json::parse(str, str + length, nullptr, throwExc);
  1568. #endif
  1569. }
  1570. } // namespace detail
  1571. } // namespace tinygltf
  1572. #ifdef __APPLE__
  1573. #include "TargetConditionals.h"
  1574. #endif
  1575. #ifdef __clang__
  1576. #pragma clang diagnostic push
  1577. #pragma clang diagnostic ignored "-Wc++98-compat"
  1578. #endif
  1579. namespace tinygltf {
  1580. ///
  1581. /// Internal LoadImageDataOption struct.
  1582. /// This struct is passed through `user_pointer` in LoadImageData.
  1583. /// The struct is not passed when the user supply their own LoadImageData
  1584. /// callbacks.
  1585. ///
  1586. struct LoadImageDataOption {
  1587. // true: preserve image channels(e.g. load as RGB image if the image has RGB
  1588. // channels) default `false`(channels are expanded to RGBA for backward
  1589. // compatibility).
  1590. bool preserve_channels{false};
  1591. };
  1592. // Equals function for Value, for recursivity
  1593. static bool Equals(const tinygltf::Value &one, const tinygltf::Value &other) {
  1594. if (one.Type() != other.Type()) return false;
  1595. switch (one.Type()) {
  1596. case NULL_TYPE:
  1597. return true;
  1598. case BOOL_TYPE:
  1599. return one.Get<bool>() == other.Get<bool>();
  1600. case REAL_TYPE:
  1601. return TINYGLTF_DOUBLE_EQUAL(one.Get<double>(), other.Get<double>());
  1602. case INT_TYPE:
  1603. return one.Get<int>() == other.Get<int>();
  1604. case OBJECT_TYPE: {
  1605. auto oneObj = one.Get<tinygltf::Value::Object>();
  1606. auto otherObj = other.Get<tinygltf::Value::Object>();
  1607. if (oneObj.size() != otherObj.size()) return false;
  1608. for (auto &it : oneObj) {
  1609. auto otherIt = otherObj.find(it.first);
  1610. if (otherIt == otherObj.end()) return false;
  1611. if (!Equals(it.second, otherIt->second)) return false;
  1612. }
  1613. return true;
  1614. }
  1615. case ARRAY_TYPE: {
  1616. if (one.Size() != other.Size()) return false;
  1617. for (int i = 0; i < int(one.Size()); ++i)
  1618. if (!Equals(one.Get(i), other.Get(i))) return false;
  1619. return true;
  1620. }
  1621. case STRING_TYPE:
  1622. return one.Get<std::string>() == other.Get<std::string>();
  1623. case BINARY_TYPE:
  1624. return one.Get<std::vector<unsigned char> >() ==
  1625. other.Get<std::vector<unsigned char> >();
  1626. default: {
  1627. // unhandled type
  1628. return false;
  1629. }
  1630. }
  1631. }
  1632. // Equals function for std::vector<double> using TINYGLTF_DOUBLE_EPSILON
  1633. static bool Equals(const std::vector<double> &one,
  1634. const std::vector<double> &other) {
  1635. if (one.size() != other.size()) return false;
  1636. for (int i = 0; i < int(one.size()); ++i) {
  1637. if (!TINYGLTF_DOUBLE_EQUAL(one[size_t(i)], other[size_t(i)])) return false;
  1638. }
  1639. return true;
  1640. }
  1641. bool Accessor::operator==(const Accessor &other) const {
  1642. return this->bufferView == other.bufferView &&
  1643. this->byteOffset == other.byteOffset &&
  1644. this->componentType == other.componentType &&
  1645. this->count == other.count && this->extensions == other.extensions &&
  1646. this->extras == other.extras &&
  1647. Equals(this->maxValues, other.maxValues) &&
  1648. Equals(this->minValues, other.minValues) && this->name == other.name &&
  1649. this->normalized == other.normalized && this->type == other.type;
  1650. }
  1651. bool Animation::operator==(const Animation &other) const {
  1652. return this->channels == other.channels &&
  1653. this->extensions == other.extensions && this->extras == other.extras &&
  1654. this->name == other.name && this->samplers == other.samplers;
  1655. }
  1656. bool AnimationChannel::operator==(const AnimationChannel &other) const {
  1657. return this->extensions == other.extensions && this->extras == other.extras &&
  1658. this->target_node == other.target_node &&
  1659. this->target_path == other.target_path &&
  1660. this->sampler == other.sampler;
  1661. }
  1662. bool AnimationSampler::operator==(const AnimationSampler &other) const {
  1663. return this->extras == other.extras && this->extensions == other.extensions &&
  1664. this->input == other.input &&
  1665. this->interpolation == other.interpolation &&
  1666. this->output == other.output;
  1667. }
  1668. bool Asset::operator==(const Asset &other) const {
  1669. return this->copyright == other.copyright &&
  1670. this->extensions == other.extensions && this->extras == other.extras &&
  1671. this->generator == other.generator &&
  1672. this->minVersion == other.minVersion && this->version == other.version;
  1673. }
  1674. bool Buffer::operator==(const Buffer &other) const {
  1675. return this->data == other.data && this->extensions == other.extensions &&
  1676. this->extras == other.extras && this->name == other.name &&
  1677. this->uri == other.uri;
  1678. }
  1679. bool BufferView::operator==(const BufferView &other) const {
  1680. return this->buffer == other.buffer && this->byteLength == other.byteLength &&
  1681. this->byteOffset == other.byteOffset &&
  1682. this->byteStride == other.byteStride && this->name == other.name &&
  1683. this->target == other.target && this->extensions == other.extensions &&
  1684. this->extras == other.extras &&
  1685. this->dracoDecoded == other.dracoDecoded;
  1686. }
  1687. bool Camera::operator==(const Camera &other) const {
  1688. return this->name == other.name && this->extensions == other.extensions &&
  1689. this->extras == other.extras &&
  1690. this->orthographic == other.orthographic &&
  1691. this->perspective == other.perspective && this->type == other.type;
  1692. }
  1693. bool Image::operator==(const Image &other) const {
  1694. return this->bufferView == other.bufferView &&
  1695. this->component == other.component &&
  1696. this->extensions == other.extensions && this->extras == other.extras &&
  1697. this->height == other.height && this->image == other.image &&
  1698. this->mimeType == other.mimeType && this->name == other.name &&
  1699. this->uri == other.uri && this->width == other.width;
  1700. }
  1701. bool Light::operator==(const Light &other) const {
  1702. return Equals(this->color, other.color) && this->name == other.name &&
  1703. this->type == other.type;
  1704. }
  1705. bool AudioEmitter::operator==(const AudioEmitter &other) const {
  1706. return this->name == other.name &&
  1707. TINYGLTF_DOUBLE_EQUAL(this->gain, other.gain) &&
  1708. this->loop == other.loop && this->playing == other.playing &&
  1709. this->type == other.type &&
  1710. this->distanceModel == other.distanceModel &&
  1711. this->source == other.source;
  1712. }
  1713. bool AudioSource::operator==(const AudioSource &other) const {
  1714. return this->name == other.name && this->uri == other.uri;
  1715. }
  1716. bool Material::operator==(const Material &other) const {
  1717. return (this->pbrMetallicRoughness == other.pbrMetallicRoughness) &&
  1718. (this->normalTexture == other.normalTexture) &&
  1719. (this->occlusionTexture == other.occlusionTexture) &&
  1720. (this->emissiveTexture == other.emissiveTexture) &&
  1721. Equals(this->emissiveFactor, other.emissiveFactor) &&
  1722. (this->alphaMode == other.alphaMode) &&
  1723. TINYGLTF_DOUBLE_EQUAL(this->alphaCutoff, other.alphaCutoff) &&
  1724. (this->doubleSided == other.doubleSided) &&
  1725. (this->extensions == other.extensions) &&
  1726. (this->extras == other.extras) && (this->values == other.values) &&
  1727. (this->additionalValues == other.additionalValues) &&
  1728. (this->name == other.name);
  1729. }
  1730. bool Mesh::operator==(const Mesh &other) const {
  1731. return this->extensions == other.extensions && this->extras == other.extras &&
  1732. this->name == other.name && Equals(this->weights, other.weights) &&
  1733. this->primitives == other.primitives;
  1734. }
  1735. bool Model::operator==(const Model &other) const {
  1736. return this->accessors == other.accessors &&
  1737. this->animations == other.animations && this->asset == other.asset &&
  1738. this->buffers == other.buffers &&
  1739. this->bufferViews == other.bufferViews &&
  1740. this->cameras == other.cameras &&
  1741. this->defaultScene == other.defaultScene &&
  1742. this->extensions == other.extensions &&
  1743. this->extensionsRequired == other.extensionsRequired &&
  1744. this->extensionsUsed == other.extensionsUsed &&
  1745. this->extras == other.extras && this->images == other.images &&
  1746. this->lights == other.lights && this->materials == other.materials &&
  1747. this->meshes == other.meshes && this->nodes == other.nodes &&
  1748. this->samplers == other.samplers && this->scenes == other.scenes &&
  1749. this->skins == other.skins && this->textures == other.textures;
  1750. }
  1751. bool Node::operator==(const Node &other) const {
  1752. return this->camera == other.camera && this->children == other.children &&
  1753. this->extensions == other.extensions && this->extras == other.extras &&
  1754. Equals(this->matrix, other.matrix) && this->mesh == other.mesh &&
  1755. (this->light == other.light) && (this->emitter == other.emitter) &&
  1756. this->name == other.name && Equals(this->rotation, other.rotation) &&
  1757. Equals(this->scale, other.scale) && this->skin == other.skin &&
  1758. Equals(this->translation, other.translation) &&
  1759. Equals(this->weights, other.weights);
  1760. }
  1761. bool SpotLight::operator==(const SpotLight &other) const {
  1762. return this->extensions == other.extensions && this->extras == other.extras &&
  1763. TINYGLTF_DOUBLE_EQUAL(this->innerConeAngle, other.innerConeAngle) &&
  1764. TINYGLTF_DOUBLE_EQUAL(this->outerConeAngle, other.outerConeAngle);
  1765. }
  1766. bool PositionalEmitter::operator==(const PositionalEmitter &other) const {
  1767. return this->extensions == other.extensions && this->extras == other.extras &&
  1768. TINYGLTF_DOUBLE_EQUAL(this->coneInnerAngle, other.coneInnerAngle) &&
  1769. TINYGLTF_DOUBLE_EQUAL(this->coneOuterAngle, other.coneOuterAngle) &&
  1770. TINYGLTF_DOUBLE_EQUAL(this->coneOuterGain, other.coneOuterGain) &&
  1771. TINYGLTF_DOUBLE_EQUAL(this->maxDistance, other.maxDistance) &&
  1772. TINYGLTF_DOUBLE_EQUAL(this->refDistance, other.refDistance) &&
  1773. TINYGLTF_DOUBLE_EQUAL(this->rolloffFactor, other.rolloffFactor);
  1774. }
  1775. bool OrthographicCamera::operator==(const OrthographicCamera &other) const {
  1776. return this->extensions == other.extensions && this->extras == other.extras &&
  1777. TINYGLTF_DOUBLE_EQUAL(this->xmag, other.xmag) &&
  1778. TINYGLTF_DOUBLE_EQUAL(this->ymag, other.ymag) &&
  1779. TINYGLTF_DOUBLE_EQUAL(this->zfar, other.zfar) &&
  1780. TINYGLTF_DOUBLE_EQUAL(this->znear, other.znear);
  1781. }
  1782. bool Parameter::operator==(const Parameter &other) const {
  1783. if (this->bool_value != other.bool_value ||
  1784. this->has_number_value != other.has_number_value)
  1785. return false;
  1786. if (!TINYGLTF_DOUBLE_EQUAL(this->number_value, other.number_value))
  1787. return false;
  1788. if (this->json_double_value.size() != other.json_double_value.size())
  1789. return false;
  1790. for (auto &it : this->json_double_value) {
  1791. auto otherIt = other.json_double_value.find(it.first);
  1792. if (otherIt == other.json_double_value.end()) return false;
  1793. if (!TINYGLTF_DOUBLE_EQUAL(it.second, otherIt->second)) return false;
  1794. }
  1795. if (!Equals(this->number_array, other.number_array)) return false;
  1796. if (this->string_value != other.string_value) return false;
  1797. return true;
  1798. }
  1799. bool PerspectiveCamera::operator==(const PerspectiveCamera &other) const {
  1800. return TINYGLTF_DOUBLE_EQUAL(this->aspectRatio, other.aspectRatio) &&
  1801. this->extensions == other.extensions && this->extras == other.extras &&
  1802. TINYGLTF_DOUBLE_EQUAL(this->yfov, other.yfov) &&
  1803. TINYGLTF_DOUBLE_EQUAL(this->zfar, other.zfar) &&
  1804. TINYGLTF_DOUBLE_EQUAL(this->znear, other.znear);
  1805. }
  1806. bool Primitive::operator==(const Primitive &other) const {
  1807. return this->attributes == other.attributes && this->extras == other.extras &&
  1808. this->indices == other.indices && this->material == other.material &&
  1809. this->mode == other.mode && this->targets == other.targets;
  1810. }
  1811. bool Sampler::operator==(const Sampler &other) const {
  1812. return this->extensions == other.extensions && this->extras == other.extras &&
  1813. this->magFilter == other.magFilter &&
  1814. this->minFilter == other.minFilter && this->name == other.name &&
  1815. this->wrapS == other.wrapS && this->wrapT == other.wrapT;
  1816. // this->wrapR == other.wrapR
  1817. }
  1818. bool Scene::operator==(const Scene &other) const {
  1819. return this->extensions == other.extensions && this->extras == other.extras &&
  1820. this->name == other.name && this->nodes == other.nodes;
  1821. }
  1822. bool Skin::operator==(const Skin &other) const {
  1823. return this->extensions == other.extensions && this->extras == other.extras &&
  1824. this->inverseBindMatrices == other.inverseBindMatrices &&
  1825. this->joints == other.joints && this->name == other.name &&
  1826. this->skeleton == other.skeleton;
  1827. }
  1828. bool Texture::operator==(const Texture &other) const {
  1829. return this->extensions == other.extensions && this->extras == other.extras &&
  1830. this->name == other.name && this->sampler == other.sampler &&
  1831. this->source == other.source;
  1832. }
  1833. bool TextureInfo::operator==(const TextureInfo &other) const {
  1834. return this->extensions == other.extensions && this->extras == other.extras &&
  1835. this->index == other.index && this->texCoord == other.texCoord;
  1836. }
  1837. bool NormalTextureInfo::operator==(const NormalTextureInfo &other) const {
  1838. return this->extensions == other.extensions && this->extras == other.extras &&
  1839. this->index == other.index && this->texCoord == other.texCoord &&
  1840. TINYGLTF_DOUBLE_EQUAL(this->scale, other.scale);
  1841. }
  1842. bool OcclusionTextureInfo::operator==(const OcclusionTextureInfo &other) const {
  1843. return this->extensions == other.extensions && this->extras == other.extras &&
  1844. this->index == other.index && this->texCoord == other.texCoord &&
  1845. TINYGLTF_DOUBLE_EQUAL(this->strength, other.strength);
  1846. }
  1847. bool PbrMetallicRoughness::operator==(const PbrMetallicRoughness &other) const {
  1848. return this->extensions == other.extensions && this->extras == other.extras &&
  1849. (this->baseColorTexture == other.baseColorTexture) &&
  1850. (this->metallicRoughnessTexture == other.metallicRoughnessTexture) &&
  1851. Equals(this->baseColorFactor, other.baseColorFactor) &&
  1852. TINYGLTF_DOUBLE_EQUAL(this->metallicFactor, other.metallicFactor) &&
  1853. TINYGLTF_DOUBLE_EQUAL(this->roughnessFactor, other.roughnessFactor);
  1854. }
  1855. bool Value::operator==(const Value &other) const {
  1856. return Equals(*this, other);
  1857. }
  1858. static void swap4(unsigned int *val) {
  1859. #ifdef TINYGLTF_LITTLE_ENDIAN
  1860. (void)val;
  1861. #else
  1862. unsigned int tmp = *val;
  1863. unsigned char *dst = reinterpret_cast<unsigned char *>(val);
  1864. unsigned char *src = reinterpret_cast<unsigned char *>(&tmp);
  1865. dst[0] = src[3];
  1866. dst[1] = src[2];
  1867. dst[2] = src[1];
  1868. dst[3] = src[0];
  1869. #endif
  1870. }
  1871. static std::string JoinPath(const std::string &path0,
  1872. const std::string &path1) {
  1873. if (path0.empty()) {
  1874. return path1;
  1875. } else {
  1876. // check '/'
  1877. char lastChar = *path0.rbegin();
  1878. if (lastChar != '/') {
  1879. return path0 + std::string("/") + path1;
  1880. } else {
  1881. return path0 + path1;
  1882. }
  1883. }
  1884. }
  1885. static std::string FindFile(const std::vector<std::string> &paths,
  1886. const std::string &filepath, FsCallbacks *fs) {
  1887. if (fs == nullptr || fs->ExpandFilePath == nullptr ||
  1888. fs->FileExists == nullptr) {
  1889. // Error, fs callback[s] missing
  1890. return std::string();
  1891. }
  1892. // https://github.com/syoyo/tinygltf/issues/416
  1893. // Use strlen() since std::string's size/length reports the number of elements
  1894. // in the buffer, not the length of string(null-terminated) strip
  1895. // null-character in the middle of string.
  1896. size_t slength = strlen(filepath.c_str());
  1897. if (slength == 0) {
  1898. return std::string();
  1899. }
  1900. std::string cleaned_filepath = std::string(filepath.c_str());
  1901. for (size_t i = 0; i < paths.size(); i++) {
  1902. std::string absPath =
  1903. fs->ExpandFilePath(JoinPath(paths[i], cleaned_filepath), fs->user_data);
  1904. if (fs->FileExists(absPath, fs->user_data)) {
  1905. return absPath;
  1906. }
  1907. }
  1908. return std::string();
  1909. }
  1910. static std::string GetFilePathExtension(const std::string &FileName) {
  1911. if (FileName.find_last_of(".") != std::string::npos)
  1912. return FileName.substr(FileName.find_last_of(".") + 1);
  1913. return "";
  1914. }
  1915. static std::string GetBaseDir(const std::string &filepath) {
  1916. if (filepath.find_last_of("/\\") != std::string::npos)
  1917. return filepath.substr(0, filepath.find_last_of("/\\"));
  1918. return "";
  1919. }
  1920. static std::string GetBaseFilename(const std::string &filepath) {
  1921. auto idx = filepath.find_last_of("/\\");
  1922. if (idx != std::string::npos) return filepath.substr(idx + 1);
  1923. return filepath;
  1924. }
  1925. std::string base64_encode(unsigned char const *, unsigned int len);
  1926. std::string base64_decode(std::string const &s);
  1927. /*
  1928. base64.cpp and base64.h
  1929. Copyright (C) 2004-2008 René Nyffenegger
  1930. This source code is provided 'as-is', without any express or implied
  1931. warranty. In no event will the author be held liable for any damages
  1932. arising from the use of this software.
  1933. Permission is granted to anyone to use this software for any purpose,
  1934. including commercial applications, and to alter it and redistribute it
  1935. freely, subject to the following restrictions:
  1936. 1. The origin of this source code must not be misrepresented; you must not
  1937. claim that you wrote the original source code. If you use this source code
  1938. in a product, an acknowledgment in the product documentation would be
  1939. appreciated but is not required.
  1940. 2. Altered source versions must be plainly marked as such, and must not be
  1941. misrepresented as being the original source code.
  1942. 3. This notice may not be removed or altered from any source distribution.
  1943. René Nyffenegger [email protected]
  1944. */
  1945. #ifdef __clang__
  1946. #pragma clang diagnostic push
  1947. #pragma clang diagnostic ignored "-Wsign-conversion"
  1948. #pragma clang diagnostic ignored "-Wconversion"
  1949. #endif
  1950. static inline bool is_base64(unsigned char c) {
  1951. return (isalnum(c) || (c == '+') || (c == '/'));
  1952. }
  1953. std::string base64_encode(unsigned char const *bytes_to_encode,
  1954. unsigned int in_len) {
  1955. std::string ret;
  1956. int i = 0;
  1957. int j = 0;
  1958. unsigned char char_array_3[3];
  1959. unsigned char char_array_4[4];
  1960. const char *base64_chars =
  1961. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  1962. "abcdefghijklmnopqrstuvwxyz"
  1963. "0123456789+/";
  1964. while (in_len--) {
  1965. char_array_3[i++] = *(bytes_to_encode++);
  1966. if (i == 3) {
  1967. char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
  1968. char_array_4[1] =
  1969. ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
  1970. char_array_4[2] =
  1971. ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
  1972. char_array_4[3] = char_array_3[2] & 0x3f;
  1973. for (i = 0; (i < 4); i++) ret += base64_chars[char_array_4[i]];
  1974. i = 0;
  1975. }
  1976. }
  1977. if (i) {
  1978. for (j = i; j < 3; j++) char_array_3[j] = '\0';
  1979. char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
  1980. char_array_4[1] =
  1981. ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
  1982. char_array_4[2] =
  1983. ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
  1984. for (j = 0; (j < i + 1); j++) ret += base64_chars[char_array_4[j]];
  1985. while ((i++ < 3)) ret += '=';
  1986. }
  1987. return ret;
  1988. }
  1989. std::string base64_decode(std::string const &encoded_string) {
  1990. int in_len = static_cast<int>(encoded_string.size());
  1991. int i = 0;
  1992. int j = 0;
  1993. int in_ = 0;
  1994. unsigned char char_array_4[4], char_array_3[3];
  1995. std::string ret;
  1996. const std::string base64_chars =
  1997. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  1998. "abcdefghijklmnopqrstuvwxyz"
  1999. "0123456789+/";
  2000. while (in_len-- && (encoded_string[in_] != '=') &&
  2001. is_base64(encoded_string[in_])) {
  2002. char_array_4[i++] = encoded_string[in_];
  2003. in_++;
  2004. if (i == 4) {
  2005. for (i = 0; i < 4; i++)
  2006. char_array_4[i] =
  2007. static_cast<unsigned char>(base64_chars.find(char_array_4[i]));
  2008. char_array_3[0] =
  2009. (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
  2010. char_array_3[1] =
  2011. ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  2012. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  2013. for (i = 0; (i < 3); i++) ret += char_array_3[i];
  2014. i = 0;
  2015. }
  2016. }
  2017. if (i) {
  2018. for (j = i; j < 4; j++) char_array_4[j] = 0;
  2019. for (j = 0; j < 4; j++)
  2020. char_array_4[j] =
  2021. static_cast<unsigned char>(base64_chars.find(char_array_4[j]));
  2022. char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
  2023. char_array_3[1] =
  2024. ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  2025. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  2026. for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
  2027. }
  2028. return ret;
  2029. }
  2030. #ifdef __clang__
  2031. #pragma clang diagnostic pop
  2032. #endif
  2033. // https://github.com/syoyo/tinygltf/issues/228
  2034. // TODO(syoyo): Use uriparser https://uriparser.github.io/ for stricter Uri
  2035. // decoding?
  2036. //
  2037. // Uri Decoding from DLIB
  2038. // http://dlib.net/dlib/server/server_http.cpp.html
  2039. // --- dlib begin ------------------------------------------------------------
  2040. // Copyright (C) 2003 Davis E. King ([email protected])
  2041. // License: Boost Software License
  2042. // Boost Software License - Version 1.0 - August 17th, 2003
  2043. // Permission is hereby granted, free of charge, to any person or organization
  2044. // obtaining a copy of the software and accompanying documentation covered by
  2045. // this license (the "Software") to use, reproduce, display, distribute,
  2046. // execute, and transmit the Software, and to prepare derivative works of the
  2047. // Software, and to permit third-parties to whom the Software is furnished to
  2048. // do so, all subject to the following:
  2049. // The copyright notices in the Software and this entire statement, including
  2050. // the above license grant, this restriction and the following disclaimer,
  2051. // must be included in all copies of the Software, in whole or in part, and
  2052. // all derivative works of the Software, unless such copies or derivative
  2053. // works are solely in the form of machine-executable object code generated by
  2054. // a source language processor.
  2055. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  2056. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  2057. // FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
  2058. // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
  2059. // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
  2060. // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  2061. // DEALINGS IN THE SOFTWARE.
  2062. //
  2063. namespace dlib {
  2064. inline unsigned char from_hex(unsigned char ch) {
  2065. if (ch <= '9' && ch >= '0')
  2066. ch -= '0';
  2067. else if (ch <= 'f' && ch >= 'a')
  2068. ch -= 'a' - 10;
  2069. else if (ch <= 'F' && ch >= 'A')
  2070. ch -= 'A' - 10;
  2071. else
  2072. ch = 0;
  2073. return ch;
  2074. }
  2075. static const std::string urldecode(const std::string &str) {
  2076. using namespace std;
  2077. string result;
  2078. string::size_type i;
  2079. for (i = 0; i < str.size(); ++i) {
  2080. if (str[i] == '+') {
  2081. result += ' ';
  2082. } else if (str[i] == '%' && str.size() > i + 2) {
  2083. const unsigned char ch1 =
  2084. from_hex(static_cast<unsigned char>(str[i + 1]));
  2085. const unsigned char ch2 =
  2086. from_hex(static_cast<unsigned char>(str[i + 2]));
  2087. const unsigned char ch = static_cast<unsigned char>((ch1 << 4) | ch2);
  2088. result += static_cast<char>(ch);
  2089. i += 2;
  2090. } else {
  2091. result += str[i];
  2092. }
  2093. }
  2094. return result;
  2095. }
  2096. } // namespace dlib
  2097. // --- dlib end --------------------------------------------------------------
  2098. bool URIDecode(const std::string &in_uri, std::string *out_uri,
  2099. void *user_data) {
  2100. (void)user_data;
  2101. *out_uri = dlib::urldecode(in_uri);
  2102. return true;
  2103. }
  2104. static bool LoadExternalFile(std::vector<unsigned char> *out, std::string *err,
  2105. std::string *warn, const std::string &filename,
  2106. const std::string &basedir, bool required,
  2107. size_t reqBytes, bool checkSize,
  2108. size_t maxFileSize, FsCallbacks *fs) {
  2109. if (fs == nullptr || fs->FileExists == nullptr ||
  2110. fs->ExpandFilePath == nullptr || fs->ReadWholeFile == nullptr) {
  2111. // This is a developer error, assert() ?
  2112. if (err) {
  2113. (*err) += "FS callback[s] not set\n";
  2114. }
  2115. return false;
  2116. }
  2117. std::string *failMsgOut = required ? err : warn;
  2118. out->clear();
  2119. std::vector<std::string> paths;
  2120. paths.push_back(basedir);
  2121. paths.push_back(".");
  2122. std::string filepath = FindFile(paths, filename, fs);
  2123. if (filepath.empty() || filename.empty()) {
  2124. if (failMsgOut) {
  2125. (*failMsgOut) += "File not found : " + filename + "\n";
  2126. }
  2127. return false;
  2128. }
  2129. // Check file size
  2130. if (fs->GetFileSizeInBytes) {
  2131. size_t file_size{0};
  2132. std::string _err;
  2133. bool ok =
  2134. fs->GetFileSizeInBytes(&file_size, &_err, filepath, fs->user_data);
  2135. if (!ok) {
  2136. if (_err.size()) {
  2137. if (failMsgOut) {
  2138. (*failMsgOut) += "Getting file size failed : " + filename +
  2139. ", err = " + _err + "\n";
  2140. }
  2141. }
  2142. return false;
  2143. }
  2144. if (file_size > maxFileSize) {
  2145. if (failMsgOut) {
  2146. (*failMsgOut) += "File size " + std::to_string(file_size) +
  2147. " exceeds maximum allowed file size " +
  2148. std::to_string(maxFileSize) + " : " + filepath + "\n";
  2149. }
  2150. return false;
  2151. }
  2152. }
  2153. std::vector<unsigned char> buf;
  2154. std::string fileReadErr;
  2155. bool fileRead =
  2156. fs->ReadWholeFile(&buf, &fileReadErr, filepath, fs->user_data);
  2157. if (!fileRead) {
  2158. if (failMsgOut) {
  2159. (*failMsgOut) +=
  2160. "File read error : " + filepath + " : " + fileReadErr + "\n";
  2161. }
  2162. return false;
  2163. }
  2164. size_t sz = buf.size();
  2165. if (sz == 0) {
  2166. if (failMsgOut) {
  2167. (*failMsgOut) += "File is empty : " + filepath + "\n";
  2168. }
  2169. return false;
  2170. }
  2171. if (checkSize) {
  2172. if (reqBytes == sz) {
  2173. out->swap(buf);
  2174. return true;
  2175. } else {
  2176. std::stringstream ss;
  2177. ss << "File size mismatch : " << filepath << ", requestedBytes "
  2178. << reqBytes << ", but got " << sz << std::endl;
  2179. if (failMsgOut) {
  2180. (*failMsgOut) += ss.str();
  2181. }
  2182. return false;
  2183. }
  2184. }
  2185. out->swap(buf);
  2186. return true;
  2187. }
  2188. void TinyGLTF::SetParseStrictness(ParseStrictness strictness) {
  2189. strictness_ = strictness;
  2190. }
  2191. void TinyGLTF::SetImageLoader(LoadImageDataFunction func, void *user_data) {
  2192. LoadImageData = func;
  2193. load_image_user_data_ = user_data;
  2194. user_image_loader_ = true;
  2195. }
  2196. void TinyGLTF::RemoveImageLoader() {
  2197. LoadImageData =
  2198. #ifndef TINYGLTF_NO_STB_IMAGE
  2199. &tinygltf::LoadImageData;
  2200. #else
  2201. nullptr;
  2202. #endif
  2203. load_image_user_data_ = nullptr;
  2204. user_image_loader_ = false;
  2205. }
  2206. #ifndef TINYGLTF_NO_STB_IMAGE
  2207. bool LoadImageData(Image *image, const int image_idx, std::string *err,
  2208. std::string *warn, int req_width, int req_height,
  2209. const unsigned char *bytes, int size, void *user_data) {
  2210. (void)warn;
  2211. LoadImageDataOption option;
  2212. if (user_data) {
  2213. option = *reinterpret_cast<LoadImageDataOption *>(user_data);
  2214. }
  2215. int w = 0, h = 0, comp = 0, req_comp = 0;
  2216. unsigned char *data = nullptr;
  2217. // preserve_channels true: Use channels stored in the image file.
  2218. // false: force 32-bit textures for common Vulkan compatibility. It appears
  2219. // that some GPU drivers do not support 24-bit images for Vulkan
  2220. req_comp = option.preserve_channels ? 0 : 4;
  2221. int bits = 8;
  2222. int pixel_type = TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE;
  2223. // It is possible that the image we want to load is a 16bit per channel image
  2224. // We are going to attempt to load it as 16bit per channel, and if it worked,
  2225. // set the image data accordingly. We are casting the returned pointer into
  2226. // unsigned char, because we are representing "bytes". But we are updating
  2227. // the Image metadata to signal that this image uses 2 bytes (16bits) per
  2228. // channel:
  2229. if (stbi_is_16_bit_from_memory(bytes, size)) {
  2230. data = reinterpret_cast<unsigned char *>(
  2231. stbi_load_16_from_memory(bytes, size, &w, &h, &comp, req_comp));
  2232. if (data) {
  2233. bits = 16;
  2234. pixel_type = TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT;
  2235. }
  2236. }
  2237. // at this point, if data is still NULL, it means that the image wasn't
  2238. // 16bit per channel, we are going to load it as a normal 8bit per channel
  2239. // image as we used to do:
  2240. // if image cannot be decoded, ignore parsing and keep it by its path
  2241. // don't break in this case
  2242. // FIXME we should only enter this function if the image is embedded. If
  2243. // image->uri references
  2244. // an image file, it should be left as it is. Image loading should not be
  2245. // mandatory (to support other formats)
  2246. if (!data) data = stbi_load_from_memory(bytes, size, &w, &h, &comp, req_comp);
  2247. if (!data) {
  2248. // NOTE: you can use `warn` instead of `err`
  2249. if (err) {
  2250. (*err) +=
  2251. "Unknown image format. STB cannot decode image data for image[" +
  2252. std::to_string(image_idx) + "] name = \"" + image->name + "\".\n";
  2253. }
  2254. return false;
  2255. }
  2256. if ((w < 1) || (h < 1)) {
  2257. stbi_image_free(data);
  2258. if (err) {
  2259. (*err) += "Invalid image data for image[" + std::to_string(image_idx) +
  2260. "] name = \"" + image->name + "\"\n";
  2261. }
  2262. return false;
  2263. }
  2264. if (req_width > 0) {
  2265. if (req_width != w) {
  2266. stbi_image_free(data);
  2267. if (err) {
  2268. (*err) += "Image width mismatch for image[" +
  2269. std::to_string(image_idx) + "] name = \"" + image->name +
  2270. "\"\n";
  2271. }
  2272. return false;
  2273. }
  2274. }
  2275. if (req_height > 0) {
  2276. if (req_height != h) {
  2277. stbi_image_free(data);
  2278. if (err) {
  2279. (*err) += "Image height mismatch. for image[" +
  2280. std::to_string(image_idx) + "] name = \"" + image->name +
  2281. "\"\n";
  2282. }
  2283. return false;
  2284. }
  2285. }
  2286. if (req_comp != 0) {
  2287. // loaded data has `req_comp` channels(components)
  2288. comp = req_comp;
  2289. }
  2290. image->width = w;
  2291. image->height = h;
  2292. image->component = comp;
  2293. image->bits = bits;
  2294. image->pixel_type = pixel_type;
  2295. image->image.resize(static_cast<size_t>(w * h * comp) * size_t(bits / 8));
  2296. std::copy(data, data + w * h * comp * (bits / 8), image->image.begin());
  2297. stbi_image_free(data);
  2298. return true;
  2299. }
  2300. #endif
  2301. void TinyGLTF::SetImageWriter(WriteImageDataFunction func, void *user_data) {
  2302. WriteImageData = func;
  2303. write_image_user_data_ = user_data;
  2304. }
  2305. #ifndef TINYGLTF_NO_STB_IMAGE_WRITE
  2306. static void WriteToMemory_stbi(void *context, void *data, int size) {
  2307. std::vector<unsigned char> *buffer =
  2308. reinterpret_cast<std::vector<unsigned char> *>(context);
  2309. unsigned char *pData = reinterpret_cast<unsigned char *>(data);
  2310. buffer->insert(buffer->end(), pData, pData + size);
  2311. }
  2312. bool WriteImageData(const std::string *basepath, const std::string *filename,
  2313. const Image *image, bool embedImages,
  2314. const URICallbacks *uri_cb, std::string *out_uri,
  2315. void *fsPtr) {
  2316. const std::string ext = GetFilePathExtension(*filename);
  2317. // Write image to temporary buffer
  2318. std::string header;
  2319. std::vector<unsigned char> data;
  2320. if (ext == "png") {
  2321. if ((image->bits != 8) ||
  2322. (image->pixel_type != TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE)) {
  2323. // Unsupported pixel format
  2324. return false;
  2325. }
  2326. if (!stbi_write_png_to_func(WriteToMemory_stbi, &data, image->width,
  2327. image->height, image->component,
  2328. &image->image[0], 0)) {
  2329. return false;
  2330. }
  2331. header = "data:image/png;base64,";
  2332. } else if (ext == "jpg") {
  2333. if (!stbi_write_jpg_to_func(WriteToMemory_stbi, &data, image->width,
  2334. image->height, image->component,
  2335. &image->image[0], 100)) {
  2336. return false;
  2337. }
  2338. header = "data:image/jpeg;base64,";
  2339. } else if (ext == "bmp") {
  2340. if (!stbi_write_bmp_to_func(WriteToMemory_stbi, &data, image->width,
  2341. image->height, image->component,
  2342. &image->image[0])) {
  2343. return false;
  2344. }
  2345. header = "data:image/bmp;base64,";
  2346. } else if (!embedImages) {
  2347. // Error: can't output requested format to file
  2348. return false;
  2349. }
  2350. if (embedImages) {
  2351. // Embed base64-encoded image into URI
  2352. if (data.size()) {
  2353. *out_uri = header + base64_encode(&data[0],
  2354. static_cast<unsigned int>(data.size()));
  2355. } else {
  2356. // Throw error?
  2357. }
  2358. } else {
  2359. // Write image to disc
  2360. FsCallbacks *fs = reinterpret_cast<FsCallbacks *>(fsPtr);
  2361. if ((fs != nullptr) && (fs->WriteWholeFile != nullptr)) {
  2362. const std::string imagefilepath = JoinPath(*basepath, *filename);
  2363. std::string writeError;
  2364. if (!fs->WriteWholeFile(&writeError, imagefilepath, data,
  2365. fs->user_data)) {
  2366. // Could not write image file to disc; Throw error ?
  2367. return false;
  2368. }
  2369. } else {
  2370. // Throw error?
  2371. }
  2372. if (uri_cb->encode) {
  2373. if (!uri_cb->encode(*filename, "image", out_uri, uri_cb->user_data)) {
  2374. return false;
  2375. }
  2376. } else {
  2377. *out_uri = *filename;
  2378. }
  2379. }
  2380. return true;
  2381. }
  2382. #endif
  2383. void TinyGLTF::SetURICallbacks(URICallbacks callbacks) {
  2384. assert(callbacks.decode);
  2385. if (callbacks.decode) {
  2386. uri_cb = callbacks;
  2387. }
  2388. }
  2389. void TinyGLTF::SetFsCallbacks(FsCallbacks callbacks) { fs = callbacks; }
  2390. #ifdef _WIN32
  2391. static inline std::wstring UTF8ToWchar(const std::string &str) {
  2392. int wstr_size =
  2393. MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), nullptr, 0);
  2394. std::wstring wstr((size_t)wstr_size, 0);
  2395. MultiByteToWideChar(CP_UTF8, 0, str.data(), (int)str.size(), &wstr[0],
  2396. (int)wstr.size());
  2397. return wstr;
  2398. }
  2399. static inline std::string WcharToUTF8(const std::wstring &wstr) {
  2400. int str_size = WideCharToMultiByte(CP_UTF8, 0, wstr.data(), (int)wstr.size(),
  2401. nullptr, 0, nullptr, nullptr);
  2402. std::string str((size_t)str_size, 0);
  2403. WideCharToMultiByte(CP_UTF8, 0, wstr.data(), (int)wstr.size(), &str[0],
  2404. (int)str.size(), nullptr, nullptr);
  2405. return str;
  2406. }
  2407. #endif
  2408. #ifndef TINYGLTF_NO_FS
  2409. // Default implementations of filesystem functions
  2410. bool FileExists(const std::string &abs_filename, void *) {
  2411. bool ret;
  2412. #ifdef TINYGLTF_ANDROID_LOAD_FROM_ASSETS
  2413. if (asset_manager) {
  2414. AAsset *asset = AAssetManager_open(asset_manager, abs_filename.c_str(),
  2415. AASSET_MODE_STREAMING);
  2416. if (!asset) {
  2417. return false;
  2418. }
  2419. AAsset_close(asset);
  2420. ret = true;
  2421. } else {
  2422. return false;
  2423. }
  2424. #else
  2425. #ifdef _WIN32
  2426. #if defined(_MSC_VER) || defined(_LIBCPP_VERSION)
  2427. // First check if a file is a directory.
  2428. DWORD result = GetFileAttributesW(UTF8ToWchar(abs_filename).c_str());
  2429. if (result == INVALID_FILE_ATTRIBUTES) {
  2430. return false;
  2431. }
  2432. if (result & FILE_ATTRIBUTE_DIRECTORY) {
  2433. return false;
  2434. }
  2435. FILE *fp = nullptr;
  2436. errno_t err = _wfopen_s(&fp, UTF8ToWchar(abs_filename).c_str(), L"rb");
  2437. if (err != 0) {
  2438. return false;
  2439. }
  2440. #elif defined(__GLIBCXX__)
  2441. FILE *fp = fopen(abs_filename.c_str(), "rb");
  2442. if (!fp) {
  2443. return false;
  2444. }
  2445. #else
  2446. // TODO: is_directory check
  2447. FILE *fp = nullptr;
  2448. errno_t err = fopen_s(&fp, abs_filename.c_str(), "rb");
  2449. if (err != 0) {
  2450. return false;
  2451. }
  2452. #endif
  2453. #else
  2454. struct stat sb;
  2455. if (stat(abs_filename.c_str(), &sb)) {
  2456. return false;
  2457. }
  2458. if (S_ISDIR(sb.st_mode)) {
  2459. return false;
  2460. }
  2461. FILE *fp = fopen(abs_filename.c_str(), "rb");
  2462. #endif
  2463. if (fp) {
  2464. ret = true;
  2465. fclose(fp);
  2466. } else {
  2467. ret = false;
  2468. }
  2469. #endif
  2470. return ret;
  2471. }
  2472. std::string ExpandFilePath(const std::string &filepath, void *) {
  2473. // https://github.com/syoyo/tinygltf/issues/368
  2474. //
  2475. // No file path expansion in built-in FS function anymore, since glTF URI
  2476. // should not contain tilde('~') and environment variables, and for security
  2477. // reason(`wordexp`).
  2478. //
  2479. // Users need to supply `base_dir`(in `LoadASCIIFromString`,
  2480. // `LoadBinaryFromMemory`) in expanded absolute path.
  2481. return filepath;
  2482. #if 0
  2483. #ifdef _WIN32
  2484. // Assume input `filepath` is encoded in UTF-8
  2485. std::wstring wfilepath = UTF8ToWchar(filepath);
  2486. DWORD wlen = ExpandEnvironmentStringsW(wfilepath.c_str(), nullptr, 0);
  2487. wchar_t *wstr = new wchar_t[wlen];
  2488. ExpandEnvironmentStringsW(wfilepath.c_str(), wstr, wlen);
  2489. std::wstring ws(wstr);
  2490. delete[] wstr;
  2491. return WcharToUTF8(ws);
  2492. #else
  2493. #if defined(TARGET_OS_IPHONE) || defined(TARGET_IPHONE_SIMULATOR) || \
  2494. defined(__ANDROID__) || defined(__EMSCRIPTEN__) || defined(__OpenBSD__)
  2495. // no expansion
  2496. std::string s = filepath;
  2497. #else
  2498. std::string s;
  2499. wordexp_t p;
  2500. if (filepath.empty()) {
  2501. return "";
  2502. }
  2503. // Quote the string to keep any spaces in filepath intact.
  2504. std::string quoted_path = "\"" + filepath + "\"";
  2505. // char** w;
  2506. int ret = wordexp(quoted_path.c_str(), &p, 0);
  2507. if (ret) {
  2508. // err
  2509. s = filepath;
  2510. return s;
  2511. }
  2512. // Use first element only.
  2513. if (p.we_wordv) {
  2514. s = std::string(p.we_wordv[0]);
  2515. wordfree(&p);
  2516. } else {
  2517. s = filepath;
  2518. }
  2519. #endif
  2520. return s;
  2521. #endif
  2522. #endif
  2523. }
  2524. bool GetFileSizeInBytes(size_t *filesize_out, std::string *err,
  2525. const std::string &filepath, void *userdata) {
  2526. (void)userdata;
  2527. #ifdef TINYGLTF_ANDROID_LOAD_FROM_ASSETS
  2528. if (asset_manager) {
  2529. AAsset *asset = AAssetManager_open(asset_manager, filepath.c_str(),
  2530. AASSET_MODE_STREAMING);
  2531. if (!asset) {
  2532. if (err) {
  2533. (*err) += "File open error : " + filepath + "\n";
  2534. }
  2535. return false;
  2536. }
  2537. size_t size = AAsset_getLength(asset);
  2538. if (size == 0) {
  2539. if (err) {
  2540. (*err) += "Invalid file size : " + filepath +
  2541. " (does the path point to a directory?)";
  2542. }
  2543. return false;
  2544. }
  2545. return true;
  2546. } else {
  2547. if (err) {
  2548. (*err) += "No asset manager specified : " + filepath + "\n";
  2549. }
  2550. return false;
  2551. }
  2552. #else
  2553. #ifdef _WIN32
  2554. #if defined(__GLIBCXX__) // mingw
  2555. int file_descriptor =
  2556. _wopen(UTF8ToWchar(filepath).c_str(), _O_RDONLY | _O_BINARY);
  2557. __gnu_cxx::stdio_filebuf<char> wfile_buf(file_descriptor, std::ios_base::in);
  2558. std::istream f(&wfile_buf);
  2559. #elif defined(_MSC_VER) || defined(_LIBCPP_VERSION)
  2560. // For libcxx, assume _LIBCPP_HAS_OPEN_WITH_WCHAR is defined to accept
  2561. // `wchar_t *`
  2562. std::ifstream f(UTF8ToWchar(filepath).c_str(), std::ifstream::binary);
  2563. #else
  2564. // Unknown compiler/runtime
  2565. std::ifstream f(filepath.c_str(), std::ifstream::binary);
  2566. #endif
  2567. #else
  2568. std::ifstream f(filepath.c_str(), std::ifstream::binary);
  2569. #endif
  2570. if (!f) {
  2571. if (err) {
  2572. (*err) += "File open error : " + filepath + "\n";
  2573. }
  2574. return false;
  2575. }
  2576. // For directory(and pipe?), peek() will fail(Posix gnustl/libc++ only)
  2577. f.peek();
  2578. if (!f) {
  2579. if (err) {
  2580. (*err) +=
  2581. "File read error. Maybe empty file or invalid file : " + filepath +
  2582. "\n";
  2583. }
  2584. return false;
  2585. }
  2586. f.seekg(0, f.end);
  2587. size_t sz = static_cast<size_t>(f.tellg());
  2588. // std::cout << "sz = " << sz << "\n";
  2589. f.seekg(0, f.beg);
  2590. if (int64_t(sz) < 0) {
  2591. if (err) {
  2592. (*err) += "Invalid file size : " + filepath +
  2593. " (does the path point to a directory?)";
  2594. }
  2595. return false;
  2596. } else if (sz == 0) {
  2597. if (err) {
  2598. (*err) += "File is empty : " + filepath + "\n";
  2599. }
  2600. return false;
  2601. } else if (sz >= (std::numeric_limits<std::streamoff>::max)()) {
  2602. if (err) {
  2603. (*err) += "Invalid file size : " + filepath + "\n";
  2604. }
  2605. return false;
  2606. }
  2607. (*filesize_out) = sz;
  2608. return true;
  2609. #endif
  2610. }
  2611. bool ReadWholeFile(std::vector<unsigned char> *out, std::string *err,
  2612. const std::string &filepath, void *) {
  2613. #ifdef TINYGLTF_ANDROID_LOAD_FROM_ASSETS
  2614. if (asset_manager) {
  2615. AAsset *asset = AAssetManager_open(asset_manager, filepath.c_str(),
  2616. AASSET_MODE_STREAMING);
  2617. if (!asset) {
  2618. if (err) {
  2619. (*err) += "File open error : " + filepath + "\n";
  2620. }
  2621. return false;
  2622. }
  2623. size_t size = AAsset_getLength(asset);
  2624. if (size == 0) {
  2625. if (err) {
  2626. (*err) += "Invalid file size : " + filepath +
  2627. " (does the path point to a directory?)";
  2628. }
  2629. return false;
  2630. }
  2631. out->resize(size);
  2632. AAsset_read(asset, reinterpret_cast<char *>(&out->at(0)), size);
  2633. AAsset_close(asset);
  2634. return true;
  2635. } else {
  2636. if (err) {
  2637. (*err) += "No asset manager specified : " + filepath + "\n";
  2638. }
  2639. return false;
  2640. }
  2641. #else
  2642. #ifdef _WIN32
  2643. #if defined(__GLIBCXX__) // mingw
  2644. int file_descriptor =
  2645. _wopen(UTF8ToWchar(filepath).c_str(), _O_RDONLY | _O_BINARY);
  2646. __gnu_cxx::stdio_filebuf<char> wfile_buf(file_descriptor, std::ios_base::in);
  2647. std::istream f(&wfile_buf);
  2648. #elif defined(_MSC_VER) || defined(_LIBCPP_VERSION)
  2649. // For libcxx, assume _LIBCPP_HAS_OPEN_WITH_WCHAR is defined to accept
  2650. // `wchar_t *`
  2651. std::ifstream f(UTF8ToWchar(filepath).c_str(), std::ifstream::binary);
  2652. #else
  2653. // Unknown compiler/runtime
  2654. std::ifstream f(filepath.c_str(), std::ifstream::binary);
  2655. #endif
  2656. #else
  2657. std::ifstream f(filepath.c_str(), std::ifstream::binary);
  2658. #endif
  2659. if (!f) {
  2660. if (err) {
  2661. (*err) += "File open error : " + filepath + "\n";
  2662. }
  2663. return false;
  2664. }
  2665. // For directory(and pipe?), peek() will fail(Posix gnustl/libc++ only)
  2666. f.peek();
  2667. if (!f) {
  2668. if (err) {
  2669. (*err) +=
  2670. "File read error. Maybe empty file or invalid file : " + filepath +
  2671. "\n";
  2672. }
  2673. return false;
  2674. }
  2675. f.seekg(0, f.end);
  2676. size_t sz = static_cast<size_t>(f.tellg());
  2677. // std::cout << "sz = " << sz << "\n";
  2678. f.seekg(0, f.beg);
  2679. if (int64_t(sz) < 0) {
  2680. if (err) {
  2681. (*err) += "Invalid file size : " + filepath +
  2682. " (does the path point to a directory?)";
  2683. }
  2684. return false;
  2685. } else if (sz == 0) {
  2686. if (err) {
  2687. (*err) += "File is empty : " + filepath + "\n";
  2688. }
  2689. return false;
  2690. } else if (sz >= (std::numeric_limits<std::streamoff>::max)()) {
  2691. if (err) {
  2692. (*err) += "Invalid file size : " + filepath + "\n";
  2693. }
  2694. return false;
  2695. }
  2696. out->resize(sz);
  2697. f.read(reinterpret_cast<char *>(&out->at(0)),
  2698. static_cast<std::streamsize>(sz));
  2699. return true;
  2700. #endif
  2701. }
  2702. bool WriteWholeFile(std::string *err, const std::string &filepath,
  2703. const std::vector<unsigned char> &contents, void *) {
  2704. #ifdef _WIN32
  2705. #if defined(__GLIBCXX__) // mingw
  2706. int file_descriptor = _wopen(UTF8ToWchar(filepath).c_str(),
  2707. _O_CREAT | _O_WRONLY | _O_TRUNC | _O_BINARY);
  2708. __gnu_cxx::stdio_filebuf<char> wfile_buf(
  2709. file_descriptor, std::ios_base::out | std::ios_base::binary);
  2710. std::ostream f(&wfile_buf);
  2711. #elif defined(_MSC_VER)
  2712. std::ofstream f(UTF8ToWchar(filepath).c_str(), std::ofstream::binary);
  2713. #else // clang?
  2714. std::ofstream f(filepath.c_str(), std::ofstream::binary);
  2715. #endif
  2716. #else
  2717. std::ofstream f(filepath.c_str(), std::ofstream::binary);
  2718. #endif
  2719. if (!f) {
  2720. if (err) {
  2721. (*err) += "File open error for writing : " + filepath + "\n";
  2722. }
  2723. return false;
  2724. }
  2725. f.write(reinterpret_cast<const char *>(&contents.at(0)),
  2726. static_cast<std::streamsize>(contents.size()));
  2727. if (!f) {
  2728. if (err) {
  2729. (*err) += "File write error: " + filepath + "\n";
  2730. }
  2731. return false;
  2732. }
  2733. return true;
  2734. }
  2735. #endif // TINYGLTF_NO_FS
  2736. static std::string MimeToExt(const std::string &mimeType) {
  2737. if (mimeType == "image/jpeg") {
  2738. return "jpg";
  2739. } else if (mimeType == "image/png") {
  2740. return "png";
  2741. } else if (mimeType == "image/bmp") {
  2742. return "bmp";
  2743. } else if (mimeType == "image/gif") {
  2744. return "gif";
  2745. }
  2746. return "";
  2747. }
  2748. static bool UpdateImageObject(const Image &image, std::string &baseDir,
  2749. int index, bool embedImages,
  2750. const URICallbacks *uri_cb,
  2751. WriteImageDataFunction *WriteImageData,
  2752. void *user_data, std::string *out_uri) {
  2753. std::string filename;
  2754. std::string ext;
  2755. // If image has uri, use it as a filename
  2756. if (image.uri.size()) {
  2757. std::string decoded_uri;
  2758. if (!uri_cb->decode(image.uri, &decoded_uri, uri_cb->user_data)) {
  2759. // A decode failure results in a failure to write the gltf.
  2760. return false;
  2761. }
  2762. filename = GetBaseFilename(decoded_uri);
  2763. ext = GetFilePathExtension(filename);
  2764. } else if (image.bufferView != -1) {
  2765. // If there's no URI and the data exists in a buffer,
  2766. // don't change properties or write images
  2767. } else if (image.name.size()) {
  2768. ext = MimeToExt(image.mimeType);
  2769. // Otherwise use name as filename
  2770. filename = image.name + "." + ext;
  2771. } else {
  2772. ext = MimeToExt(image.mimeType);
  2773. // Fallback to index of image as filename
  2774. filename = std::to_string(index) + "." + ext;
  2775. }
  2776. // If callback is set and image data exists, modify image data object. If
  2777. // image data does not exist, this is not considered a failure and the
  2778. // original uri should be maintained.
  2779. bool imageWritten = false;
  2780. if (*WriteImageData != nullptr && !filename.empty() && !image.image.empty()) {
  2781. imageWritten = (*WriteImageData)(&baseDir, &filename, &image, embedImages,
  2782. uri_cb, out_uri, user_data);
  2783. if (!imageWritten) {
  2784. return false;
  2785. }
  2786. }
  2787. // Use the original uri if the image was not written.
  2788. if (!imageWritten) {
  2789. *out_uri = image.uri;
  2790. }
  2791. return true;
  2792. }
  2793. bool IsDataURI(const std::string &in) {
  2794. std::string header = "data:application/octet-stream;base64,";
  2795. if (in.find(header) == 0) {
  2796. return true;
  2797. }
  2798. header = "data:image/jpeg;base64,";
  2799. if (in.find(header) == 0) {
  2800. return true;
  2801. }
  2802. header = "data:image/png;base64,";
  2803. if (in.find(header) == 0) {
  2804. return true;
  2805. }
  2806. header = "data:image/bmp;base64,";
  2807. if (in.find(header) == 0) {
  2808. return true;
  2809. }
  2810. header = "data:image/gif;base64,";
  2811. if (in.find(header) == 0) {
  2812. return true;
  2813. }
  2814. header = "data:text/plain;base64,";
  2815. if (in.find(header) == 0) {
  2816. return true;
  2817. }
  2818. header = "data:application/gltf-buffer;base64,";
  2819. if (in.find(header) == 0) {
  2820. return true;
  2821. }
  2822. return false;
  2823. }
  2824. bool DecodeDataURI(std::vector<unsigned char> *out, std::string &mime_type,
  2825. const std::string &in, size_t reqBytes, bool checkSize) {
  2826. std::string header = "data:application/octet-stream;base64,";
  2827. std::string data;
  2828. if (in.find(header) == 0) {
  2829. data = base64_decode(in.substr(header.size())); // cut mime string.
  2830. }
  2831. if (data.empty()) {
  2832. header = "data:image/jpeg;base64,";
  2833. if (in.find(header) == 0) {
  2834. mime_type = "image/jpeg";
  2835. data = base64_decode(in.substr(header.size())); // cut mime string.
  2836. }
  2837. }
  2838. if (data.empty()) {
  2839. header = "data:image/png;base64,";
  2840. if (in.find(header) == 0) {
  2841. mime_type = "image/png";
  2842. data = base64_decode(in.substr(header.size())); // cut mime string.
  2843. }
  2844. }
  2845. if (data.empty()) {
  2846. header = "data:image/bmp;base64,";
  2847. if (in.find(header) == 0) {
  2848. mime_type = "image/bmp";
  2849. data = base64_decode(in.substr(header.size())); // cut mime string.
  2850. }
  2851. }
  2852. if (data.empty()) {
  2853. header = "data:image/gif;base64,";
  2854. if (in.find(header) == 0) {
  2855. mime_type = "image/gif";
  2856. data = base64_decode(in.substr(header.size())); // cut mime string.
  2857. }
  2858. }
  2859. if (data.empty()) {
  2860. header = "data:text/plain;base64,";
  2861. if (in.find(header) == 0) {
  2862. mime_type = "text/plain";
  2863. data = base64_decode(in.substr(header.size()));
  2864. }
  2865. }
  2866. if (data.empty()) {
  2867. header = "data:application/gltf-buffer;base64,";
  2868. if (in.find(header) == 0) {
  2869. data = base64_decode(in.substr(header.size()));
  2870. }
  2871. }
  2872. // TODO(syoyo): Allow empty buffer? #229
  2873. if (data.empty()) {
  2874. return false;
  2875. }
  2876. if (checkSize) {
  2877. if (data.size() != reqBytes) {
  2878. return false;
  2879. }
  2880. out->resize(reqBytes);
  2881. } else {
  2882. out->resize(data.size());
  2883. }
  2884. std::copy(data.begin(), data.end(), out->begin());
  2885. return true;
  2886. }
  2887. namespace detail {
  2888. bool GetInt(const detail::json &o, int &val) {
  2889. #ifdef TINYGLTF_USE_RAPIDJSON
  2890. if (!o.IsDouble()) {
  2891. if (o.IsInt()) {
  2892. val = o.GetInt();
  2893. return true;
  2894. } else if (o.IsUint()) {
  2895. val = static_cast<int>(o.GetUint());
  2896. return true;
  2897. } else if (o.IsInt64()) {
  2898. val = static_cast<int>(o.GetInt64());
  2899. return true;
  2900. } else if (o.IsUint64()) {
  2901. val = static_cast<int>(o.GetUint64());
  2902. return true;
  2903. }
  2904. }
  2905. return false;
  2906. #else
  2907. auto type = o.type();
  2908. if ((type == detail::json::value_t::number_integer) ||
  2909. (type == detail::json::value_t::number_unsigned)) {
  2910. val = static_cast<int>(o.get<int64_t>());
  2911. return true;
  2912. }
  2913. return false;
  2914. #endif
  2915. }
  2916. #ifdef TINYGLTF_USE_RAPIDJSON
  2917. bool GetDouble(const detail::json &o, double &val) {
  2918. if (o.IsDouble()) {
  2919. val = o.GetDouble();
  2920. return true;
  2921. }
  2922. return false;
  2923. }
  2924. #endif
  2925. bool GetNumber(const detail::json &o, double &val) {
  2926. #ifdef TINYGLTF_USE_RAPIDJSON
  2927. if (o.IsNumber()) {
  2928. val = o.GetDouble();
  2929. return true;
  2930. }
  2931. return false;
  2932. #else
  2933. if (o.is_number()) {
  2934. val = o.get<double>();
  2935. return true;
  2936. }
  2937. return false;
  2938. #endif
  2939. }
  2940. bool GetString(const detail::json &o, std::string &val) {
  2941. #ifdef TINYGLTF_USE_RAPIDJSON
  2942. if (o.IsString()) {
  2943. val = o.GetString();
  2944. return true;
  2945. }
  2946. return false;
  2947. #else
  2948. if (o.type() == detail::json::value_t::string) {
  2949. val = o.get<std::string>();
  2950. return true;
  2951. }
  2952. return false;
  2953. #endif
  2954. }
  2955. bool IsArray(const detail::json &o) {
  2956. #ifdef TINYGLTF_USE_RAPIDJSON
  2957. return o.IsArray();
  2958. #else
  2959. return o.is_array();
  2960. #endif
  2961. }
  2962. detail::json_const_array_iterator ArrayBegin(const detail::json &o) {
  2963. #ifdef TINYGLTF_USE_RAPIDJSON
  2964. return o.Begin();
  2965. #else
  2966. return o.begin();
  2967. #endif
  2968. }
  2969. detail::json_const_array_iterator ArrayEnd(const detail::json &o) {
  2970. #ifdef TINYGLTF_USE_RAPIDJSON
  2971. return o.End();
  2972. #else
  2973. return o.end();
  2974. #endif
  2975. }
  2976. bool IsObject(const detail::json &o) {
  2977. #ifdef TINYGLTF_USE_RAPIDJSON
  2978. return o.IsObject();
  2979. #else
  2980. return o.is_object();
  2981. #endif
  2982. }
  2983. detail::json_const_iterator ObjectBegin(const detail::json &o) {
  2984. #ifdef TINYGLTF_USE_RAPIDJSON
  2985. return o.MemberBegin();
  2986. #else
  2987. return o.begin();
  2988. #endif
  2989. }
  2990. detail::json_const_iterator ObjectEnd(const detail::json &o) {
  2991. #ifdef TINYGLTF_USE_RAPIDJSON
  2992. return o.MemberEnd();
  2993. #else
  2994. return o.end();
  2995. #endif
  2996. }
  2997. // Making this a const char* results in a pointer to a temporary when
  2998. // TINYGLTF_USE_RAPIDJSON is off.
  2999. std::string GetKey(detail::json_const_iterator &it) {
  3000. #ifdef TINYGLTF_USE_RAPIDJSON
  3001. return it->name.GetString();
  3002. #else
  3003. return it.key().c_str();
  3004. #endif
  3005. }
  3006. bool FindMember(const detail::json &o, const char *member,
  3007. detail::json_const_iterator &it) {
  3008. #ifdef TINYGLTF_USE_RAPIDJSON
  3009. if (!o.IsObject()) {
  3010. return false;
  3011. }
  3012. it = o.FindMember(member);
  3013. return it != o.MemberEnd();
  3014. #else
  3015. it = o.find(member);
  3016. return it != o.end();
  3017. #endif
  3018. }
  3019. bool FindMember(detail::json &o, const char *member,
  3020. detail::json_iterator &it) {
  3021. #ifdef TINYGLTF_USE_RAPIDJSON
  3022. if (!o.IsObject()) {
  3023. return false;
  3024. }
  3025. it = o.FindMember(member);
  3026. return it != o.MemberEnd();
  3027. #else
  3028. it = o.find(member);
  3029. return it != o.end();
  3030. #endif
  3031. }
  3032. void Erase(detail::json &o, detail::json_iterator &it) {
  3033. #ifdef TINYGLTF_USE_RAPIDJSON
  3034. o.EraseMember(it);
  3035. #else
  3036. o.erase(it);
  3037. #endif
  3038. }
  3039. bool IsEmpty(const detail::json &o) {
  3040. #ifdef TINYGLTF_USE_RAPIDJSON
  3041. return o.ObjectEmpty();
  3042. #else
  3043. return o.empty();
  3044. #endif
  3045. }
  3046. const detail::json &GetValue(detail::json_const_iterator &it) {
  3047. #ifdef TINYGLTF_USE_RAPIDJSON
  3048. return it->value;
  3049. #else
  3050. return it.value();
  3051. #endif
  3052. }
  3053. detail::json &GetValue(detail::json_iterator &it) {
  3054. #ifdef TINYGLTF_USE_RAPIDJSON
  3055. return it->value;
  3056. #else
  3057. return it.value();
  3058. #endif
  3059. }
  3060. std::string JsonToString(const detail::json &o, int spacing = -1) {
  3061. #ifdef TINYGLTF_USE_RAPIDJSON
  3062. using namespace rapidjson;
  3063. StringBuffer buffer;
  3064. if (spacing == -1) {
  3065. Writer<StringBuffer> writer(buffer);
  3066. // TODO: Better error handling.
  3067. // https://github.com/syoyo/tinygltf/issues/332
  3068. if (!o.Accept(writer)) {
  3069. return "tiny_gltf::JsonToString() failed rapidjson conversion";
  3070. }
  3071. } else {
  3072. PrettyWriter<StringBuffer> writer(buffer);
  3073. writer.SetIndent(' ', uint32_t(spacing));
  3074. if (!o.Accept(writer)) {
  3075. return "tiny_gltf::JsonToString() failed rapidjson conversion";
  3076. }
  3077. }
  3078. return buffer.GetString();
  3079. #else
  3080. return o.dump(spacing);
  3081. #endif
  3082. }
  3083. } // namespace detail
  3084. static bool ParseJsonAsValue(Value *ret, const detail::json &o) {
  3085. Value val{};
  3086. #ifdef TINYGLTF_USE_RAPIDJSON
  3087. using rapidjson::Type;
  3088. switch (o.GetType()) {
  3089. case Type::kObjectType: {
  3090. Value::Object value_object;
  3091. for (auto it = o.MemberBegin(); it != o.MemberEnd(); ++it) {
  3092. Value entry;
  3093. ParseJsonAsValue(&entry, it->value);
  3094. if (entry.Type() != NULL_TYPE)
  3095. value_object.emplace(detail::GetKey(it), std::move(entry));
  3096. }
  3097. if (value_object.size() > 0) val = Value(std::move(value_object));
  3098. } break;
  3099. case Type::kArrayType: {
  3100. Value::Array value_array;
  3101. value_array.reserve(o.Size());
  3102. for (auto it = o.Begin(); it != o.End(); ++it) {
  3103. Value entry;
  3104. ParseJsonAsValue(&entry, *it);
  3105. if (entry.Type() != NULL_TYPE)
  3106. value_array.emplace_back(std::move(entry));
  3107. }
  3108. if (value_array.size() > 0) val = Value(std::move(value_array));
  3109. } break;
  3110. case Type::kStringType:
  3111. val = Value(std::string(o.GetString()));
  3112. break;
  3113. case Type::kFalseType:
  3114. case Type::kTrueType:
  3115. val = Value(o.GetBool());
  3116. break;
  3117. case Type::kNumberType:
  3118. if (!o.IsDouble()) {
  3119. int i = 0;
  3120. detail::GetInt(o, i);
  3121. val = Value(i);
  3122. } else {
  3123. double d = 0.0;
  3124. detail::GetDouble(o, d);
  3125. val = Value(d);
  3126. }
  3127. break;
  3128. case Type::kNullType:
  3129. break;
  3130. // all types are covered, so no `case default`
  3131. }
  3132. #else
  3133. switch (o.type()) {
  3134. case detail::json::value_t::object: {
  3135. Value::Object value_object;
  3136. for (auto it = o.begin(); it != o.end(); it++) {
  3137. Value entry;
  3138. ParseJsonAsValue(&entry, it.value());
  3139. if (entry.Type() != NULL_TYPE)
  3140. value_object.emplace(it.key(), std::move(entry));
  3141. }
  3142. if (value_object.size() > 0) val = Value(std::move(value_object));
  3143. } break;
  3144. case detail::json::value_t::array: {
  3145. Value::Array value_array;
  3146. value_array.reserve(o.size());
  3147. for (auto it = o.begin(); it != o.end(); it++) {
  3148. Value entry;
  3149. ParseJsonAsValue(&entry, it.value());
  3150. if (entry.Type() != NULL_TYPE)
  3151. value_array.emplace_back(std::move(entry));
  3152. }
  3153. if (value_array.size() > 0) val = Value(std::move(value_array));
  3154. } break;
  3155. case detail::json::value_t::string:
  3156. val = Value(o.get<std::string>());
  3157. break;
  3158. case detail::json::value_t::boolean:
  3159. val = Value(o.get<bool>());
  3160. break;
  3161. case detail::json::value_t::number_integer:
  3162. case detail::json::value_t::number_unsigned:
  3163. val = Value(static_cast<int>(o.get<int64_t>()));
  3164. break;
  3165. case detail::json::value_t::number_float:
  3166. val = Value(o.get<double>());
  3167. break;
  3168. case detail::json::value_t::null:
  3169. case detail::json::value_t::discarded:
  3170. case detail::json::value_t::binary:
  3171. // default:
  3172. break;
  3173. }
  3174. #endif
  3175. const bool isNotNull = val.Type() != NULL_TYPE;
  3176. if (ret) *ret = std::move(val);
  3177. return isNotNull;
  3178. }
  3179. static bool ParseExtrasProperty(Value *ret, const detail::json &o) {
  3180. detail::json_const_iterator it;
  3181. if (!detail::FindMember(o, "extras", it)) {
  3182. return false;
  3183. }
  3184. return ParseJsonAsValue(ret, detail::GetValue(it));
  3185. }
  3186. static bool ParseBooleanProperty(bool *ret, std::string *err,
  3187. const detail::json &o,
  3188. const std::string &property,
  3189. const bool required,
  3190. const std::string &parent_node = "") {
  3191. detail::json_const_iterator it;
  3192. if (!detail::FindMember(o, property.c_str(), it)) {
  3193. if (required) {
  3194. if (err) {
  3195. (*err) += "'" + property + "' property is missing";
  3196. if (!parent_node.empty()) {
  3197. (*err) += " in " + parent_node;
  3198. }
  3199. (*err) += ".\n";
  3200. }
  3201. }
  3202. return false;
  3203. }
  3204. auto &value = detail::GetValue(it);
  3205. bool isBoolean;
  3206. bool boolValue = false;
  3207. #ifdef TINYGLTF_USE_RAPIDJSON
  3208. isBoolean = value.IsBool();
  3209. if (isBoolean) {
  3210. boolValue = value.GetBool();
  3211. }
  3212. #else
  3213. isBoolean = value.is_boolean();
  3214. if (isBoolean) {
  3215. boolValue = value.get<bool>();
  3216. }
  3217. #endif
  3218. if (!isBoolean) {
  3219. if (required) {
  3220. if (err) {
  3221. (*err) += "'" + property + "' property is not a bool type.\n";
  3222. }
  3223. }
  3224. return false;
  3225. }
  3226. if (ret) {
  3227. (*ret) = boolValue;
  3228. }
  3229. return true;
  3230. }
  3231. static bool ParseIntegerProperty(int *ret, std::string *err,
  3232. const detail::json &o,
  3233. const std::string &property,
  3234. const bool required,
  3235. const std::string &parent_node = "") {
  3236. detail::json_const_iterator it;
  3237. if (!detail::FindMember(o, property.c_str(), it)) {
  3238. if (required) {
  3239. if (err) {
  3240. (*err) += "'" + property + "' property is missing";
  3241. if (!parent_node.empty()) {
  3242. (*err) += " in " + parent_node;
  3243. }
  3244. (*err) += ".\n";
  3245. }
  3246. }
  3247. return false;
  3248. }
  3249. int intValue;
  3250. bool isInt = detail::GetInt(detail::GetValue(it), intValue);
  3251. if (!isInt) {
  3252. if (required) {
  3253. if (err) {
  3254. (*err) += "'" + property + "' property is not an integer type.\n";
  3255. }
  3256. }
  3257. return false;
  3258. }
  3259. if (ret) {
  3260. (*ret) = intValue;
  3261. }
  3262. return true;
  3263. }
  3264. static bool ParseUnsignedProperty(size_t *ret, std::string *err,
  3265. const detail::json &o,
  3266. const std::string &property,
  3267. const bool required,
  3268. const std::string &parent_node = "") {
  3269. detail::json_const_iterator it;
  3270. if (!detail::FindMember(o, property.c_str(), it)) {
  3271. if (required) {
  3272. if (err) {
  3273. (*err) += "'" + property + "' property is missing";
  3274. if (!parent_node.empty()) {
  3275. (*err) += " in " + parent_node;
  3276. }
  3277. (*err) += ".\n";
  3278. }
  3279. }
  3280. return false;
  3281. }
  3282. auto &value = detail::GetValue(it);
  3283. size_t uValue = 0;
  3284. bool isUValue;
  3285. #ifdef TINYGLTF_USE_RAPIDJSON
  3286. isUValue = false;
  3287. if (value.IsUint()) {
  3288. uValue = value.GetUint();
  3289. isUValue = true;
  3290. } else if (value.IsUint64()) {
  3291. uValue = value.GetUint64();
  3292. isUValue = true;
  3293. }
  3294. #else
  3295. isUValue = value.is_number_unsigned();
  3296. if (isUValue) {
  3297. uValue = value.get<size_t>();
  3298. }
  3299. #endif
  3300. if (!isUValue) {
  3301. if (required) {
  3302. if (err) {
  3303. (*err) += "'" + property + "' property is not a positive integer.\n";
  3304. }
  3305. }
  3306. return false;
  3307. }
  3308. if (ret) {
  3309. (*ret) = uValue;
  3310. }
  3311. return true;
  3312. }
  3313. static bool ParseNumberProperty(double *ret, std::string *err,
  3314. const detail::json &o,
  3315. const std::string &property,
  3316. const bool required,
  3317. const std::string &parent_node = "") {
  3318. detail::json_const_iterator it;
  3319. if (!detail::FindMember(o, property.c_str(), it)) {
  3320. if (required) {
  3321. if (err) {
  3322. (*err) += "'" + property + "' property is missing";
  3323. if (!parent_node.empty()) {
  3324. (*err) += " in " + parent_node;
  3325. }
  3326. (*err) += ".\n";
  3327. }
  3328. }
  3329. return false;
  3330. }
  3331. double numberValue;
  3332. bool isNumber = detail::GetNumber(detail::GetValue(it), numberValue);
  3333. if (!isNumber) {
  3334. if (required) {
  3335. if (err) {
  3336. (*err) += "'" + property + "' property is not a number type.\n";
  3337. }
  3338. }
  3339. return false;
  3340. }
  3341. if (ret) {
  3342. (*ret) = numberValue;
  3343. }
  3344. return true;
  3345. }
  3346. static bool ParseNumberArrayProperty(std::vector<double> *ret, std::string *err,
  3347. const detail::json &o,
  3348. const std::string &property, bool required,
  3349. const std::string &parent_node = "") {
  3350. detail::json_const_iterator it;
  3351. if (!detail::FindMember(o, property.c_str(), it)) {
  3352. if (required) {
  3353. if (err) {
  3354. (*err) += "'" + property + "' property is missing";
  3355. if (!parent_node.empty()) {
  3356. (*err) += " in " + parent_node;
  3357. }
  3358. (*err) += ".\n";
  3359. }
  3360. }
  3361. return false;
  3362. }
  3363. if (!detail::IsArray(detail::GetValue(it))) {
  3364. if (required) {
  3365. if (err) {
  3366. (*err) += "'" + property + "' property is not an array";
  3367. if (!parent_node.empty()) {
  3368. (*err) += " in " + parent_node;
  3369. }
  3370. (*err) += ".\n";
  3371. }
  3372. }
  3373. return false;
  3374. }
  3375. ret->clear();
  3376. auto end = detail::ArrayEnd(detail::GetValue(it));
  3377. for (auto i = detail::ArrayBegin(detail::GetValue(it)); i != end; ++i) {
  3378. double numberValue;
  3379. const bool isNumber = detail::GetNumber(*i, numberValue);
  3380. if (!isNumber) {
  3381. if (required) {
  3382. if (err) {
  3383. (*err) += "'" + property + "' property is not a number.\n";
  3384. if (!parent_node.empty()) {
  3385. (*err) += " in " + parent_node;
  3386. }
  3387. (*err) += ".\n";
  3388. }
  3389. }
  3390. return false;
  3391. }
  3392. ret->push_back(numberValue);
  3393. }
  3394. return true;
  3395. }
  3396. static bool ParseIntegerArrayProperty(std::vector<int> *ret, std::string *err,
  3397. const detail::json &o,
  3398. const std::string &property,
  3399. bool required,
  3400. const std::string &parent_node = "") {
  3401. detail::json_const_iterator it;
  3402. if (!detail::FindMember(o, property.c_str(), it)) {
  3403. if (required) {
  3404. if (err) {
  3405. (*err) += "'" + property + "' property is missing";
  3406. if (!parent_node.empty()) {
  3407. (*err) += " in " + parent_node;
  3408. }
  3409. (*err) += ".\n";
  3410. }
  3411. }
  3412. return false;
  3413. }
  3414. if (!detail::IsArray(detail::GetValue(it))) {
  3415. if (required) {
  3416. if (err) {
  3417. (*err) += "'" + property + "' property is not an array";
  3418. if (!parent_node.empty()) {
  3419. (*err) += " in " + parent_node;
  3420. }
  3421. (*err) += ".\n";
  3422. }
  3423. }
  3424. return false;
  3425. }
  3426. ret->clear();
  3427. auto end = detail::ArrayEnd(detail::GetValue(it));
  3428. for (auto i = detail::ArrayBegin(detail::GetValue(it)); i != end; ++i) {
  3429. int numberValue;
  3430. bool isNumber = detail::GetInt(*i, numberValue);
  3431. if (!isNumber) {
  3432. if (required) {
  3433. if (err) {
  3434. (*err) += "'" + property + "' property is not an integer type.\n";
  3435. if (!parent_node.empty()) {
  3436. (*err) += " in " + parent_node;
  3437. }
  3438. (*err) += ".\n";
  3439. }
  3440. }
  3441. return false;
  3442. }
  3443. ret->push_back(numberValue);
  3444. }
  3445. return true;
  3446. }
  3447. static bool ParseStringProperty(
  3448. std::string *ret, std::string *err, const detail::json &o,
  3449. const std::string &property, bool required,
  3450. const std::string &parent_node = std::string()) {
  3451. detail::json_const_iterator it;
  3452. if (!detail::FindMember(o, property.c_str(), it)) {
  3453. if (required) {
  3454. if (err) {
  3455. (*err) += "'" + property + "' property is missing";
  3456. if (parent_node.empty()) {
  3457. (*err) += ".\n";
  3458. } else {
  3459. (*err) += " in `" + parent_node + "'.\n";
  3460. }
  3461. }
  3462. }
  3463. return false;
  3464. }
  3465. std::string strValue;
  3466. if (!detail::GetString(detail::GetValue(it), strValue)) {
  3467. if (required) {
  3468. if (err) {
  3469. (*err) += "'" + property + "' property is not a string type.\n";
  3470. }
  3471. }
  3472. return false;
  3473. }
  3474. if (ret) {
  3475. (*ret) = std::move(strValue);
  3476. }
  3477. return true;
  3478. }
  3479. static bool ParseStringIntegerProperty(std::map<std::string, int> *ret,
  3480. std::string *err, const detail::json &o,
  3481. const std::string &property,
  3482. bool required,
  3483. const std::string &parent = "") {
  3484. detail::json_const_iterator it;
  3485. if (!detail::FindMember(o, property.c_str(), it)) {
  3486. if (required) {
  3487. if (err) {
  3488. if (!parent.empty()) {
  3489. (*err) +=
  3490. "'" + property + "' property is missing in " + parent + ".\n";
  3491. } else {
  3492. (*err) += "'" + property + "' property is missing.\n";
  3493. }
  3494. }
  3495. }
  3496. return false;
  3497. }
  3498. const detail::json &dict = detail::GetValue(it);
  3499. // Make sure we are dealing with an object / dictionary.
  3500. if (!detail::IsObject(dict)) {
  3501. if (required) {
  3502. if (err) {
  3503. (*err) += "'" + property + "' property is not an object.\n";
  3504. }
  3505. }
  3506. return false;
  3507. }
  3508. ret->clear();
  3509. detail::json_const_iterator dictIt(detail::ObjectBegin(dict));
  3510. detail::json_const_iterator dictItEnd(detail::ObjectEnd(dict));
  3511. for (; dictIt != dictItEnd; ++dictIt) {
  3512. int intVal;
  3513. if (!detail::GetInt(detail::GetValue(dictIt), intVal)) {
  3514. if (required) {
  3515. if (err) {
  3516. (*err) += "'" + property + "' value is not an integer type.\n";
  3517. }
  3518. }
  3519. return false;
  3520. }
  3521. // Insert into the list.
  3522. (*ret)[detail::GetKey(dictIt)] = intVal;
  3523. }
  3524. return true;
  3525. }
  3526. static bool ParseJSONProperty(std::map<std::string, double> *ret,
  3527. std::string *err, const detail::json &o,
  3528. const std::string &property, bool required) {
  3529. detail::json_const_iterator it;
  3530. if (!detail::FindMember(o, property.c_str(), it)) {
  3531. if (required) {
  3532. if (err) {
  3533. (*err) += "'" + property + "' property is missing. \n'";
  3534. }
  3535. }
  3536. return false;
  3537. }
  3538. const detail::json &obj = detail::GetValue(it);
  3539. if (!detail::IsObject(obj)) {
  3540. if (required) {
  3541. if (err) {
  3542. (*err) += "'" + property + "' property is not a JSON object.\n";
  3543. }
  3544. }
  3545. return false;
  3546. }
  3547. ret->clear();
  3548. detail::json_const_iterator it2(detail::ObjectBegin(obj));
  3549. detail::json_const_iterator itEnd(detail::ObjectEnd(obj));
  3550. for (; it2 != itEnd; ++it2) {
  3551. double numVal;
  3552. if (detail::GetNumber(detail::GetValue(it2), numVal))
  3553. ret->emplace(std::string(detail::GetKey(it2)), numVal);
  3554. }
  3555. return true;
  3556. }
  3557. static bool ParseParameterProperty(Parameter *param, std::string *err,
  3558. const detail::json &o,
  3559. const std::string &prop, bool required) {
  3560. // A parameter value can either be a string or an array of either a boolean or
  3561. // a number. Booleans of any kind aren't supported here. Granted, it
  3562. // complicates the Parameter structure and breaks it semantically in the sense
  3563. // that the client probably works off the assumption that if the string is
  3564. // empty the vector is used, etc. Would a tagged union work?
  3565. if (ParseStringProperty(&param->string_value, err, o, prop, false)) {
  3566. // Found string property.
  3567. return true;
  3568. } else if (ParseNumberArrayProperty(&param->number_array, err, o, prop,
  3569. false)) {
  3570. // Found a number array.
  3571. return true;
  3572. } else if (ParseNumberProperty(&param->number_value, err, o, prop, false)) {
  3573. param->has_number_value = true;
  3574. return true;
  3575. } else if (ParseJSONProperty(&param->json_double_value, err, o, prop,
  3576. false)) {
  3577. return true;
  3578. } else if (ParseBooleanProperty(&param->bool_value, err, o, prop, false)) {
  3579. return true;
  3580. } else {
  3581. if (required) {
  3582. if (err) {
  3583. (*err) += "parameter must be a string or number / number array.\n";
  3584. }
  3585. }
  3586. return false;
  3587. }
  3588. }
  3589. static bool ParseExtensionsProperty(ExtensionMap *ret, std::string *err,
  3590. const detail::json &o) {
  3591. (void)err;
  3592. detail::json_const_iterator it;
  3593. if (!detail::FindMember(o, "extensions", it)) {
  3594. return false;
  3595. }
  3596. auto &obj = detail::GetValue(it);
  3597. if (!detail::IsObject(obj)) {
  3598. return false;
  3599. }
  3600. ExtensionMap extensions;
  3601. detail::json_const_iterator extIt =
  3602. detail::ObjectBegin(obj); // it.value().begin();
  3603. detail::json_const_iterator extEnd = detail::ObjectEnd(obj);
  3604. for (; extIt != extEnd; ++extIt) {
  3605. auto &itObj = detail::GetValue(extIt);
  3606. if (!detail::IsObject(itObj)) continue;
  3607. std::string key(detail::GetKey(extIt));
  3608. if (!ParseJsonAsValue(&extensions[key], itObj)) {
  3609. if (!key.empty()) {
  3610. // create empty object so that an extension object is still of type
  3611. // object
  3612. extensions[key] = Value{Value::Object{}};
  3613. }
  3614. }
  3615. }
  3616. if (ret) {
  3617. (*ret) = std::move(extensions);
  3618. }
  3619. return true;
  3620. }
  3621. template <typename GltfType>
  3622. static bool ParseExtrasAndExtensions(GltfType *target, std::string *err,
  3623. const detail::json &o,
  3624. bool store_json_strings) {
  3625. ParseExtensionsProperty(&target->extensions, err, o);
  3626. ParseExtrasProperty(&target->extras, o);
  3627. if (store_json_strings) {
  3628. {
  3629. detail::json_const_iterator it;
  3630. if (detail::FindMember(o, "extensions", it)) {
  3631. target->extensions_json_string =
  3632. detail::JsonToString(detail::GetValue(it));
  3633. }
  3634. }
  3635. {
  3636. detail::json_const_iterator it;
  3637. if (detail::FindMember(o, "extras", it)) {
  3638. target->extras_json_string = detail::JsonToString(detail::GetValue(it));
  3639. }
  3640. }
  3641. }
  3642. return true;
  3643. }
  3644. static bool ParseAsset(Asset *asset, std::string *err, const detail::json &o,
  3645. bool store_original_json_for_extras_and_extensions) {
  3646. ParseStringProperty(&asset->version, err, o, "version", true, "Asset");
  3647. ParseStringProperty(&asset->generator, err, o, "generator", false, "Asset");
  3648. ParseStringProperty(&asset->minVersion, err, o, "minVersion", false, "Asset");
  3649. ParseStringProperty(&asset->copyright, err, o, "copyright", false, "Asset");
  3650. ParseExtrasAndExtensions(asset, err, o,
  3651. store_original_json_for_extras_and_extensions);
  3652. return true;
  3653. }
  3654. static bool ParseImage(Image *image, const int image_idx, std::string *err,
  3655. std::string *warn, const detail::json &o,
  3656. bool store_original_json_for_extras_and_extensions,
  3657. const std::string &basedir, const size_t max_file_size,
  3658. FsCallbacks *fs, const URICallbacks *uri_cb,
  3659. LoadImageDataFunction *LoadImageData = nullptr,
  3660. void *load_image_user_data = nullptr) {
  3661. // A glTF image must either reference a bufferView or an image uri
  3662. // schema says oneOf [`bufferView`, `uri`]
  3663. // TODO(syoyo): Check the type of each parameters.
  3664. detail::json_const_iterator it;
  3665. bool hasBufferView = detail::FindMember(o, "bufferView", it);
  3666. bool hasURI = detail::FindMember(o, "uri", it);
  3667. ParseStringProperty(&image->name, err, o, "name", false);
  3668. if (hasBufferView && hasURI) {
  3669. // Should not both defined.
  3670. if (err) {
  3671. (*err) +=
  3672. "Only one of `bufferView` or `uri` should be defined, but both are "
  3673. "defined for image[" +
  3674. std::to_string(image_idx) + "] name = \"" + image->name + "\"\n";
  3675. }
  3676. return false;
  3677. }
  3678. if (!hasBufferView && !hasURI) {
  3679. if (err) {
  3680. (*err) += "Neither required `bufferView` nor `uri` defined for image[" +
  3681. std::to_string(image_idx) + "] name = \"" + image->name +
  3682. "\"\n";
  3683. }
  3684. return false;
  3685. }
  3686. ParseExtrasAndExtensions(image, err, o,
  3687. store_original_json_for_extras_and_extensions);
  3688. if (hasBufferView) {
  3689. int bufferView = -1;
  3690. if (!ParseIntegerProperty(&bufferView, err, o, "bufferView", true)) {
  3691. if (err) {
  3692. (*err) += "Failed to parse `bufferView` for image[" +
  3693. std::to_string(image_idx) + "] name = \"" + image->name +
  3694. "\"\n";
  3695. }
  3696. return false;
  3697. }
  3698. std::string mime_type;
  3699. ParseStringProperty(&mime_type, err, o, "mimeType", false);
  3700. int width = 0;
  3701. ParseIntegerProperty(&width, err, o, "width", false);
  3702. int height = 0;
  3703. ParseIntegerProperty(&height, err, o, "height", false);
  3704. // Just only save some information here. Loading actual image data from
  3705. // bufferView is done after this `ParseImage` function.
  3706. image->bufferView = bufferView;
  3707. image->mimeType = mime_type;
  3708. image->width = width;
  3709. image->height = height;
  3710. return true;
  3711. }
  3712. // Parse URI & Load image data.
  3713. std::string uri;
  3714. std::string tmp_err;
  3715. if (!ParseStringProperty(&uri, &tmp_err, o, "uri", true)) {
  3716. if (err) {
  3717. (*err) += "Failed to parse `uri` for image[" + std::to_string(image_idx) +
  3718. "] name = \"" + image->name + "\".\n";
  3719. }
  3720. return false;
  3721. }
  3722. std::vector<unsigned char> img;
  3723. if (IsDataURI(uri)) {
  3724. if (!DecodeDataURI(&img, image->mimeType, uri, 0, false)) {
  3725. if (err) {
  3726. (*err) += "Failed to decode 'uri' for image[" +
  3727. std::to_string(image_idx) + "] name = \"" + image->name +
  3728. "\"\n";
  3729. }
  3730. return false;
  3731. }
  3732. } else {
  3733. // Assume external file
  3734. // Keep texture path (for textures that cannot be decoded)
  3735. image->uri = uri;
  3736. #ifdef TINYGLTF_NO_EXTERNAL_IMAGE
  3737. return true;
  3738. #else
  3739. std::string decoded_uri;
  3740. if (!uri_cb->decode(uri, &decoded_uri, uri_cb->user_data)) {
  3741. if (warn) {
  3742. (*warn) += "Failed to decode 'uri' for image[" +
  3743. std::to_string(image_idx) + "] name = \"" + image->name +
  3744. "\"\n";
  3745. }
  3746. // Image loading failure is not critical to overall gltf loading.
  3747. return true;
  3748. }
  3749. if (!LoadExternalFile(&img, err, warn, decoded_uri, basedir,
  3750. /* required */ false, /* required bytes */ 0,
  3751. /* checksize */ false,
  3752. /* max file size */ max_file_size, fs)) {
  3753. if (warn) {
  3754. (*warn) += "Failed to load external 'uri' for image[" +
  3755. std::to_string(image_idx) + "] name = \"" + decoded_uri +
  3756. "\"\n";
  3757. }
  3758. // If the image cannot be loaded, keep uri as image->uri.
  3759. return true;
  3760. }
  3761. if (img.empty()) {
  3762. if (warn) {
  3763. (*warn) += "Image data is empty for image[" +
  3764. std::to_string(image_idx) + "] name = \"" + image->name +
  3765. "\" \n";
  3766. }
  3767. return false;
  3768. }
  3769. #endif
  3770. }
  3771. if (*LoadImageData == nullptr) {
  3772. if (err) {
  3773. (*err) += "No LoadImageData callback specified.\n";
  3774. }
  3775. return false;
  3776. }
  3777. return (*LoadImageData)(image, image_idx, err, warn, 0, 0, &img.at(0),
  3778. static_cast<int>(img.size()), load_image_user_data);
  3779. }
  3780. static bool ParseTexture(Texture *texture, std::string *err,
  3781. const detail::json &o,
  3782. bool store_original_json_for_extras_and_extensions,
  3783. const std::string &basedir) {
  3784. (void)basedir;
  3785. int sampler = -1;
  3786. int source = -1;
  3787. ParseIntegerProperty(&sampler, err, o, "sampler", false);
  3788. ParseIntegerProperty(&source, err, o, "source", false);
  3789. texture->sampler = sampler;
  3790. texture->source = source;
  3791. ParseExtrasAndExtensions(texture, err, o,
  3792. store_original_json_for_extras_and_extensions);
  3793. ParseStringProperty(&texture->name, err, o, "name", false);
  3794. return true;
  3795. }
  3796. static bool ParseTextureInfo(
  3797. TextureInfo *texinfo, std::string *err, const detail::json &o,
  3798. bool store_original_json_for_extras_and_extensions) {
  3799. if (texinfo == nullptr) {
  3800. return false;
  3801. }
  3802. if (!ParseIntegerProperty(&texinfo->index, err, o, "index",
  3803. /* required */ true, "TextureInfo")) {
  3804. return false;
  3805. }
  3806. ParseIntegerProperty(&texinfo->texCoord, err, o, "texCoord", false);
  3807. ParseExtrasAndExtensions(texinfo, err, o,
  3808. store_original_json_for_extras_and_extensions);
  3809. return true;
  3810. }
  3811. static bool ParseNormalTextureInfo(
  3812. NormalTextureInfo *texinfo, std::string *err, const detail::json &o,
  3813. bool store_original_json_for_extras_and_extensions) {
  3814. if (texinfo == nullptr) {
  3815. return false;
  3816. }
  3817. if (!ParseIntegerProperty(&texinfo->index, err, o, "index",
  3818. /* required */ true, "NormalTextureInfo")) {
  3819. return false;
  3820. }
  3821. ParseIntegerProperty(&texinfo->texCoord, err, o, "texCoord", false);
  3822. ParseNumberProperty(&texinfo->scale, err, o, "scale", false);
  3823. ParseExtrasAndExtensions(texinfo, err, o,
  3824. store_original_json_for_extras_and_extensions);
  3825. return true;
  3826. }
  3827. static bool ParseOcclusionTextureInfo(
  3828. OcclusionTextureInfo *texinfo, std::string *err, const detail::json &o,
  3829. bool store_original_json_for_extras_and_extensions) {
  3830. if (texinfo == nullptr) {
  3831. return false;
  3832. }
  3833. if (!ParseIntegerProperty(&texinfo->index, err, o, "index",
  3834. /* required */ true, "NormalTextureInfo")) {
  3835. return false;
  3836. }
  3837. ParseIntegerProperty(&texinfo->texCoord, err, o, "texCoord", false);
  3838. ParseNumberProperty(&texinfo->strength, err, o, "strength", false);
  3839. ParseExtrasAndExtensions(texinfo, err, o,
  3840. store_original_json_for_extras_and_extensions);
  3841. return true;
  3842. }
  3843. static bool ParseBuffer(Buffer *buffer, std::string *err, const detail::json &o,
  3844. bool store_original_json_for_extras_and_extensions,
  3845. FsCallbacks *fs, const URICallbacks *uri_cb,
  3846. const std::string &basedir,
  3847. const size_t max_buffer_size, bool is_binary = false,
  3848. const unsigned char *bin_data = nullptr,
  3849. size_t bin_size = 0) {
  3850. size_t byteLength;
  3851. if (!ParseUnsignedProperty(&byteLength, err, o, "byteLength", true,
  3852. "Buffer")) {
  3853. return false;
  3854. }
  3855. // In glTF 2.0, uri is not mandatory anymore
  3856. buffer->uri.clear();
  3857. ParseStringProperty(&buffer->uri, err, o, "uri", false, "Buffer");
  3858. // having an empty uri for a non embedded image should not be valid
  3859. if (!is_binary && buffer->uri.empty()) {
  3860. if (err) {
  3861. (*err) += "'uri' is missing from non binary glTF file buffer.\n";
  3862. }
  3863. }
  3864. detail::json_const_iterator type;
  3865. if (detail::FindMember(o, "type", type)) {
  3866. std::string typeStr;
  3867. if (detail::GetString(detail::GetValue(type), typeStr)) {
  3868. if (typeStr.compare("arraybuffer") == 0) {
  3869. // buffer.type = "arraybuffer";
  3870. }
  3871. }
  3872. }
  3873. if (is_binary) {
  3874. // Still binary glTF accepts external dataURI.
  3875. if (!buffer->uri.empty()) {
  3876. // First try embedded data URI.
  3877. if (IsDataURI(buffer->uri)) {
  3878. std::string mime_type;
  3879. if (!DecodeDataURI(&buffer->data, mime_type, buffer->uri, byteLength,
  3880. true)) {
  3881. if (err) {
  3882. (*err) +=
  3883. "Failed to decode 'uri' : " + buffer->uri + " in Buffer\n";
  3884. }
  3885. return false;
  3886. }
  3887. } else {
  3888. // External .bin file.
  3889. std::string decoded_uri;
  3890. if (!uri_cb->decode(buffer->uri, &decoded_uri, uri_cb->user_data)) {
  3891. return false;
  3892. }
  3893. if (!LoadExternalFile(&buffer->data, err, /* warn */ nullptr,
  3894. decoded_uri, basedir, /* required */ true,
  3895. byteLength, /* checkSize */ true,
  3896. /* max_file_size */ max_buffer_size, fs)) {
  3897. return false;
  3898. }
  3899. }
  3900. } else {
  3901. // load data from (embedded) binary data
  3902. if ((bin_size == 0) || (bin_data == nullptr)) {
  3903. if (err) {
  3904. (*err) +=
  3905. "Invalid binary data in `Buffer', or GLB with empty BIN chunk.\n";
  3906. }
  3907. return false;
  3908. }
  3909. if (byteLength > bin_size) {
  3910. if (err) {
  3911. std::stringstream ss;
  3912. ss << "Invalid `byteLength'. Must be equal or less than binary size: "
  3913. "`byteLength' = "
  3914. << byteLength << ", binary size = " << bin_size << std::endl;
  3915. (*err) += ss.str();
  3916. }
  3917. return false;
  3918. }
  3919. // Read buffer data
  3920. buffer->data.resize(static_cast<size_t>(byteLength));
  3921. memcpy(&(buffer->data.at(0)), bin_data, static_cast<size_t>(byteLength));
  3922. }
  3923. } else {
  3924. if (IsDataURI(buffer->uri)) {
  3925. std::string mime_type;
  3926. if (!DecodeDataURI(&buffer->data, mime_type, buffer->uri, byteLength,
  3927. true)) {
  3928. if (err) {
  3929. (*err) += "Failed to decode 'uri' : " + buffer->uri + " in Buffer\n";
  3930. }
  3931. return false;
  3932. }
  3933. } else {
  3934. // Assume external .bin file.
  3935. std::string decoded_uri;
  3936. if (!uri_cb->decode(buffer->uri, &decoded_uri, uri_cb->user_data)) {
  3937. return false;
  3938. }
  3939. if (!LoadExternalFile(&buffer->data, err, /* warn */ nullptr, decoded_uri,
  3940. basedir, /* required */ true, byteLength,
  3941. /* checkSize */ true,
  3942. /* max file size */ max_buffer_size, fs)) {
  3943. return false;
  3944. }
  3945. }
  3946. }
  3947. ParseStringProperty(&buffer->name, err, o, "name", false);
  3948. ParseExtrasAndExtensions(buffer, err, o,
  3949. store_original_json_for_extras_and_extensions);
  3950. return true;
  3951. }
  3952. static bool ParseBufferView(
  3953. BufferView *bufferView, std::string *err, const detail::json &o,
  3954. bool store_original_json_for_extras_and_extensions) {
  3955. int buffer = -1;
  3956. if (!ParseIntegerProperty(&buffer, err, o, "buffer", true, "BufferView")) {
  3957. return false;
  3958. }
  3959. size_t byteOffset = 0;
  3960. ParseUnsignedProperty(&byteOffset, err, o, "byteOffset", false);
  3961. size_t byteLength = 1;
  3962. if (!ParseUnsignedProperty(&byteLength, err, o, "byteLength", true,
  3963. "BufferView")) {
  3964. return false;
  3965. }
  3966. size_t byteStride = 0;
  3967. if (!ParseUnsignedProperty(&byteStride, err, o, "byteStride", false)) {
  3968. // Spec says: When byteStride of referenced bufferView is not defined, it
  3969. // means that accessor elements are tightly packed, i.e., effective stride
  3970. // equals the size of the element.
  3971. // We cannot determine the actual byteStride until Accessor are parsed, thus
  3972. // set 0(= tightly packed) here(as done in OpenGL's VertexAttribPoiner)
  3973. byteStride = 0;
  3974. }
  3975. if ((byteStride > 252) || ((byteStride % 4) != 0)) {
  3976. if (err) {
  3977. std::stringstream ss;
  3978. ss << "Invalid `byteStride' value. `byteStride' must be the multiple of "
  3979. "4 : "
  3980. << byteStride << std::endl;
  3981. (*err) += ss.str();
  3982. }
  3983. return false;
  3984. }
  3985. int target = 0;
  3986. ParseIntegerProperty(&target, err, o, "target", false);
  3987. if ((target == TINYGLTF_TARGET_ARRAY_BUFFER) ||
  3988. (target == TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER)) {
  3989. // OK
  3990. } else {
  3991. target = 0;
  3992. }
  3993. bufferView->target = target;
  3994. ParseStringProperty(&bufferView->name, err, o, "name", false);
  3995. ParseExtrasAndExtensions(bufferView, err, o,
  3996. store_original_json_for_extras_and_extensions);
  3997. bufferView->buffer = buffer;
  3998. bufferView->byteOffset = byteOffset;
  3999. bufferView->byteLength = byteLength;
  4000. bufferView->byteStride = byteStride;
  4001. return true;
  4002. }
  4003. static bool ParseSparseAccessor(
  4004. Accessor::Sparse *sparse, std::string *err, const detail::json &o,
  4005. bool store_original_json_for_extras_and_extensions) {
  4006. sparse->isSparse = true;
  4007. int count = 0;
  4008. if (!ParseIntegerProperty(&count, err, o, "count", true, "SparseAccessor")) {
  4009. return false;
  4010. }
  4011. ParseExtrasAndExtensions(sparse, err, o,
  4012. store_original_json_for_extras_and_extensions);
  4013. detail::json_const_iterator indices_iterator;
  4014. detail::json_const_iterator values_iterator;
  4015. if (!detail::FindMember(o, "indices", indices_iterator)) {
  4016. (*err) = "the sparse object of this accessor doesn't have indices";
  4017. return false;
  4018. }
  4019. if (!detail::FindMember(o, "values", values_iterator)) {
  4020. (*err) = "the sparse object of this accessor doesn't have values";
  4021. return false;
  4022. }
  4023. const detail::json &indices_obj = detail::GetValue(indices_iterator);
  4024. const detail::json &values_obj = detail::GetValue(values_iterator);
  4025. int indices_buffer_view = 0, component_type = 0;
  4026. size_t indices_byte_offset = 0;
  4027. if (!ParseIntegerProperty(&indices_buffer_view, err, indices_obj,
  4028. "bufferView", true, "SparseAccessor")) {
  4029. return false;
  4030. }
  4031. ParseUnsignedProperty(&indices_byte_offset, err, indices_obj, "byteOffset",
  4032. false);
  4033. if (!ParseIntegerProperty(&component_type, err, indices_obj, "componentType",
  4034. true, "SparseAccessor")) {
  4035. return false;
  4036. }
  4037. int values_buffer_view = 0;
  4038. size_t values_byte_offset = 0;
  4039. if (!ParseIntegerProperty(&values_buffer_view, err, values_obj, "bufferView",
  4040. true, "SparseAccessor")) {
  4041. return false;
  4042. }
  4043. ParseUnsignedProperty(&values_byte_offset, err, values_obj, "byteOffset",
  4044. false);
  4045. sparse->count = count;
  4046. sparse->indices.bufferView = indices_buffer_view;
  4047. sparse->indices.byteOffset = indices_byte_offset;
  4048. sparse->indices.componentType = component_type;
  4049. ParseExtrasAndExtensions(&sparse->indices, err, indices_obj,
  4050. store_original_json_for_extras_and_extensions);
  4051. sparse->values.bufferView = values_buffer_view;
  4052. sparse->values.byteOffset = values_byte_offset;
  4053. ParseExtrasAndExtensions(&sparse->values, err, values_obj,
  4054. store_original_json_for_extras_and_extensions);
  4055. return true;
  4056. }
  4057. static bool ParseAccessor(Accessor *accessor, std::string *err,
  4058. const detail::json &o,
  4059. bool store_original_json_for_extras_and_extensions) {
  4060. int bufferView = -1;
  4061. ParseIntegerProperty(&bufferView, err, o, "bufferView", false, "Accessor");
  4062. size_t byteOffset = 0;
  4063. ParseUnsignedProperty(&byteOffset, err, o, "byteOffset", false, "Accessor");
  4064. bool normalized = false;
  4065. ParseBooleanProperty(&normalized, err, o, "normalized", false, "Accessor");
  4066. size_t componentType = 0;
  4067. if (!ParseUnsignedProperty(&componentType, err, o, "componentType", true,
  4068. "Accessor")) {
  4069. return false;
  4070. }
  4071. size_t count = 0;
  4072. if (!ParseUnsignedProperty(&count, err, o, "count", true, "Accessor")) {
  4073. return false;
  4074. }
  4075. std::string type;
  4076. if (!ParseStringProperty(&type, err, o, "type", true, "Accessor")) {
  4077. return false;
  4078. }
  4079. if (type.compare("SCALAR") == 0) {
  4080. accessor->type = TINYGLTF_TYPE_SCALAR;
  4081. } else if (type.compare("VEC2") == 0) {
  4082. accessor->type = TINYGLTF_TYPE_VEC2;
  4083. } else if (type.compare("VEC3") == 0) {
  4084. accessor->type = TINYGLTF_TYPE_VEC3;
  4085. } else if (type.compare("VEC4") == 0) {
  4086. accessor->type = TINYGLTF_TYPE_VEC4;
  4087. } else if (type.compare("MAT2") == 0) {
  4088. accessor->type = TINYGLTF_TYPE_MAT2;
  4089. } else if (type.compare("MAT3") == 0) {
  4090. accessor->type = TINYGLTF_TYPE_MAT3;
  4091. } else if (type.compare("MAT4") == 0) {
  4092. accessor->type = TINYGLTF_TYPE_MAT4;
  4093. } else {
  4094. std::stringstream ss;
  4095. ss << "Unsupported `type` for accessor object. Got \"" << type << "\"\n";
  4096. if (err) {
  4097. (*err) += ss.str();
  4098. }
  4099. return false;
  4100. }
  4101. ParseStringProperty(&accessor->name, err, o, "name", false);
  4102. accessor->minValues.clear();
  4103. accessor->maxValues.clear();
  4104. ParseNumberArrayProperty(&accessor->minValues, err, o, "min", false,
  4105. "Accessor");
  4106. ParseNumberArrayProperty(&accessor->maxValues, err, o, "max", false,
  4107. "Accessor");
  4108. accessor->count = count;
  4109. accessor->bufferView = bufferView;
  4110. accessor->byteOffset = byteOffset;
  4111. accessor->normalized = normalized;
  4112. {
  4113. if (componentType >= TINYGLTF_COMPONENT_TYPE_BYTE &&
  4114. componentType <= TINYGLTF_COMPONENT_TYPE_DOUBLE) {
  4115. // OK
  4116. accessor->componentType = int(componentType);
  4117. } else {
  4118. std::stringstream ss;
  4119. ss << "Invalid `componentType` in accessor. Got " << componentType
  4120. << "\n";
  4121. if (err) {
  4122. (*err) += ss.str();
  4123. }
  4124. return false;
  4125. }
  4126. }
  4127. ParseExtrasAndExtensions(accessor, err, o,
  4128. store_original_json_for_extras_and_extensions);
  4129. // check if accessor has a "sparse" object:
  4130. detail::json_const_iterator iterator;
  4131. if (detail::FindMember(o, "sparse", iterator)) {
  4132. // here this accessor has a "sparse" subobject
  4133. return ParseSparseAccessor(&accessor->sparse, err,
  4134. detail::GetValue(iterator),
  4135. store_original_json_for_extras_and_extensions);
  4136. }
  4137. return true;
  4138. }
  4139. #ifdef TINYGLTF_ENABLE_DRACO
  4140. static void DecodeIndexBuffer(draco::Mesh *mesh, size_t componentSize,
  4141. std::vector<uint8_t> &outBuffer) {
  4142. if (componentSize == 4) {
  4143. assert(sizeof(mesh->face(draco::FaceIndex(0))[0]) == componentSize);
  4144. memcpy(outBuffer.data(), &mesh->face(draco::FaceIndex(0))[0],
  4145. outBuffer.size());
  4146. } else {
  4147. size_t faceStride = componentSize * 3;
  4148. for (draco::FaceIndex f(0); f < mesh->num_faces(); ++f) {
  4149. const draco::Mesh::Face &face = mesh->face(f);
  4150. if (componentSize == 2) {
  4151. uint16_t indices[3] = {(uint16_t)face[0].value(),
  4152. (uint16_t)face[1].value(),
  4153. (uint16_t)face[2].value()};
  4154. memcpy(outBuffer.data() + f.value() * faceStride, &indices[0],
  4155. faceStride);
  4156. } else {
  4157. uint8_t indices[3] = {(uint8_t)face[0].value(),
  4158. (uint8_t)face[1].value(),
  4159. (uint8_t)face[2].value()};
  4160. memcpy(outBuffer.data() + f.value() * faceStride, &indices[0],
  4161. faceStride);
  4162. }
  4163. }
  4164. }
  4165. }
  4166. template <typename T>
  4167. static bool GetAttributeForAllPoints(draco::Mesh *mesh,
  4168. const draco::PointAttribute *pAttribute,
  4169. std::vector<uint8_t> &outBuffer) {
  4170. size_t byteOffset = 0;
  4171. T values[4] = {0, 0, 0, 0};
  4172. for (draco::PointIndex i(0); i < mesh->num_points(); ++i) {
  4173. const draco::AttributeValueIndex val_index = pAttribute->mapped_index(i);
  4174. if (!pAttribute->ConvertValue<T>(val_index, pAttribute->num_components(),
  4175. values))
  4176. return false;
  4177. memcpy(outBuffer.data() + byteOffset, &values[0],
  4178. sizeof(T) * pAttribute->num_components());
  4179. byteOffset += sizeof(T) * pAttribute->num_components();
  4180. }
  4181. return true;
  4182. }
  4183. static bool GetAttributeForAllPoints(uint32_t componentType, draco::Mesh *mesh,
  4184. const draco::PointAttribute *pAttribute,
  4185. std::vector<uint8_t> &outBuffer) {
  4186. bool decodeResult = false;
  4187. switch (componentType) {
  4188. case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE:
  4189. decodeResult =
  4190. GetAttributeForAllPoints<uint8_t>(mesh, pAttribute, outBuffer);
  4191. break;
  4192. case TINYGLTF_COMPONENT_TYPE_BYTE:
  4193. decodeResult =
  4194. GetAttributeForAllPoints<int8_t>(mesh, pAttribute, outBuffer);
  4195. break;
  4196. case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT:
  4197. decodeResult =
  4198. GetAttributeForAllPoints<uint16_t>(mesh, pAttribute, outBuffer);
  4199. break;
  4200. case TINYGLTF_COMPONENT_TYPE_SHORT:
  4201. decodeResult =
  4202. GetAttributeForAllPoints<int16_t>(mesh, pAttribute, outBuffer);
  4203. break;
  4204. case TINYGLTF_COMPONENT_TYPE_INT:
  4205. decodeResult =
  4206. GetAttributeForAllPoints<int32_t>(mesh, pAttribute, outBuffer);
  4207. break;
  4208. case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT:
  4209. decodeResult =
  4210. GetAttributeForAllPoints<uint32_t>(mesh, pAttribute, outBuffer);
  4211. break;
  4212. case TINYGLTF_COMPONENT_TYPE_FLOAT:
  4213. decodeResult =
  4214. GetAttributeForAllPoints<float>(mesh, pAttribute, outBuffer);
  4215. break;
  4216. case TINYGLTF_COMPONENT_TYPE_DOUBLE:
  4217. decodeResult =
  4218. GetAttributeForAllPoints<double>(mesh, pAttribute, outBuffer);
  4219. break;
  4220. default:
  4221. return false;
  4222. }
  4223. return decodeResult;
  4224. }
  4225. static bool ParseDracoExtension(Primitive *primitive, Model *model,
  4226. std::string *err, std::string *warn,
  4227. const Value &dracoExtensionValue,
  4228. ParseStrictness strictness) {
  4229. (void)err;
  4230. auto bufferViewValue = dracoExtensionValue.Get("bufferView");
  4231. if (!bufferViewValue.IsInt()) return false;
  4232. auto attributesValue = dracoExtensionValue.Get("attributes");
  4233. if (!attributesValue.IsObject()) return false;
  4234. auto attributesObject = attributesValue.Get<Value::Object>();
  4235. int bufferView = bufferViewValue.Get<int>();
  4236. BufferView &view = model->bufferViews[bufferView];
  4237. Buffer &buffer = model->buffers[view.buffer];
  4238. // BufferView has already been decoded
  4239. if (view.dracoDecoded) return true;
  4240. view.dracoDecoded = true;
  4241. const char *bufferViewData =
  4242. reinterpret_cast<const char *>(buffer.data.data() + view.byteOffset);
  4243. size_t bufferViewSize = view.byteLength;
  4244. // decode draco
  4245. draco::DecoderBuffer decoderBuffer;
  4246. decoderBuffer.Init(bufferViewData, bufferViewSize);
  4247. draco::Decoder decoder;
  4248. auto decodeResult = decoder.DecodeMeshFromBuffer(&decoderBuffer);
  4249. if (!decodeResult.ok()) {
  4250. return false;
  4251. }
  4252. const std::unique_ptr<draco::Mesh> &mesh = decodeResult.value();
  4253. // create new bufferView for indices
  4254. if (primitive->indices >= 0) {
  4255. if (strictness == ParseStrictness::Permissive) {
  4256. const draco::PointIndex::ValueType numPoint = mesh->num_points();
  4257. // handle the situation where the stored component type does not match the
  4258. // required type for the actual number of stored points
  4259. int supposedComponentType = TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE;
  4260. if (numPoint < static_cast<draco::PointIndex::ValueType>(
  4261. std::numeric_limits<uint8_t>::max())) {
  4262. supposedComponentType = TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE;
  4263. } else if (
  4264. numPoint < static_cast<draco::PointIndex::ValueType>(
  4265. std::numeric_limits<uint16_t>::max())) {
  4266. supposedComponentType = TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT;
  4267. } else {
  4268. supposedComponentType = TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT;
  4269. }
  4270. if (supposedComponentType > model->accessors[primitive->indices].componentType) {
  4271. if (warn) {
  4272. (*warn) +=
  4273. "GLTF component type " + std::to_string(model->accessors[primitive->indices].componentType) +
  4274. " is not sufficient for number of stored points,"
  4275. " treating as " + std::to_string(supposedComponentType) + "\n";
  4276. }
  4277. model->accessors[primitive->indices].componentType = supposedComponentType;
  4278. }
  4279. }
  4280. int32_t componentSize = GetComponentSizeInBytes(
  4281. model->accessors[primitive->indices].componentType);
  4282. Buffer decodedIndexBuffer;
  4283. decodedIndexBuffer.data.resize(mesh->num_faces() * 3 * componentSize);
  4284. DecodeIndexBuffer(mesh.get(), componentSize, decodedIndexBuffer.data);
  4285. model->buffers.emplace_back(std::move(decodedIndexBuffer));
  4286. BufferView decodedIndexBufferView;
  4287. decodedIndexBufferView.buffer = int(model->buffers.size() - 1);
  4288. decodedIndexBufferView.byteLength =
  4289. int(mesh->num_faces() * 3 * componentSize);
  4290. decodedIndexBufferView.byteOffset = 0;
  4291. decodedIndexBufferView.byteStride = 0;
  4292. decodedIndexBufferView.target = TINYGLTF_TARGET_ARRAY_BUFFER;
  4293. model->bufferViews.emplace_back(std::move(decodedIndexBufferView));
  4294. model->accessors[primitive->indices].bufferView =
  4295. int(model->bufferViews.size() - 1);
  4296. model->accessors[primitive->indices].count = int(mesh->num_faces() * 3);
  4297. }
  4298. for (const auto &attribute : attributesObject) {
  4299. if (!attribute.second.IsInt()) return false;
  4300. auto primitiveAttribute = primitive->attributes.find(attribute.first);
  4301. if (primitiveAttribute == primitive->attributes.end()) return false;
  4302. int dracoAttributeIndex = attribute.second.Get<int>();
  4303. const auto pAttribute = mesh->GetAttributeByUniqueId(dracoAttributeIndex);
  4304. const auto componentType =
  4305. model->accessors[primitiveAttribute->second].componentType;
  4306. // Create a new buffer for this decoded buffer
  4307. Buffer decodedBuffer;
  4308. size_t bufferSize = mesh->num_points() * pAttribute->num_components() *
  4309. GetComponentSizeInBytes(componentType);
  4310. decodedBuffer.data.resize(bufferSize);
  4311. if (!GetAttributeForAllPoints(componentType, mesh.get(), pAttribute,
  4312. decodedBuffer.data))
  4313. return false;
  4314. model->buffers.emplace_back(std::move(decodedBuffer));
  4315. BufferView decodedBufferView;
  4316. decodedBufferView.buffer = int(model->buffers.size() - 1);
  4317. decodedBufferView.byteLength = bufferSize;
  4318. decodedBufferView.byteOffset = pAttribute->byte_offset();
  4319. decodedBufferView.byteStride = pAttribute->byte_stride();
  4320. decodedBufferView.target = primitive->indices >= 0
  4321. ? TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER
  4322. : TINYGLTF_TARGET_ARRAY_BUFFER;
  4323. model->bufferViews.emplace_back(std::move(decodedBufferView));
  4324. model->accessors[primitiveAttribute->second].bufferView =
  4325. int(model->bufferViews.size() - 1);
  4326. model->accessors[primitiveAttribute->second].count =
  4327. int(mesh->num_points());
  4328. }
  4329. return true;
  4330. }
  4331. #endif
  4332. static bool ParsePrimitive(Primitive *primitive, Model *model,
  4333. std::string *err, std::string *warn,
  4334. const detail::json &o,
  4335. bool store_original_json_for_extras_and_extensions,
  4336. ParseStrictness strictness) {
  4337. int material = -1;
  4338. ParseIntegerProperty(&material, err, o, "material", false);
  4339. primitive->material = material;
  4340. int mode = TINYGLTF_MODE_TRIANGLES;
  4341. ParseIntegerProperty(&mode, err, o, "mode", false);
  4342. primitive->mode = mode; // Why only triangles were supported ?
  4343. int indices = -1;
  4344. ParseIntegerProperty(&indices, err, o, "indices", false);
  4345. primitive->indices = indices;
  4346. if (!ParseStringIntegerProperty(&primitive->attributes, err, o, "attributes",
  4347. true, "Primitive")) {
  4348. return false;
  4349. }
  4350. // Look for morph targets
  4351. detail::json_const_iterator targetsObject;
  4352. if (detail::FindMember(o, "targets", targetsObject) &&
  4353. detail::IsArray(detail::GetValue(targetsObject))) {
  4354. auto targetsObjectEnd = detail::ArrayEnd(detail::GetValue(targetsObject));
  4355. for (detail::json_const_array_iterator i =
  4356. detail::ArrayBegin(detail::GetValue(targetsObject));
  4357. i != targetsObjectEnd; ++i) {
  4358. std::map<std::string, int> targetAttribues;
  4359. const detail::json &dict = *i;
  4360. if (detail::IsObject(dict)) {
  4361. detail::json_const_iterator dictIt(detail::ObjectBegin(dict));
  4362. detail::json_const_iterator dictItEnd(detail::ObjectEnd(dict));
  4363. for (; dictIt != dictItEnd; ++dictIt) {
  4364. int iVal;
  4365. if (detail::GetInt(detail::GetValue(dictIt), iVal))
  4366. targetAttribues[detail::GetKey(dictIt)] = iVal;
  4367. }
  4368. primitive->targets.emplace_back(std::move(targetAttribues));
  4369. }
  4370. }
  4371. }
  4372. ParseExtrasAndExtensions(primitive, err, o,
  4373. store_original_json_for_extras_and_extensions);
  4374. #ifdef TINYGLTF_ENABLE_DRACO
  4375. auto dracoExtension =
  4376. primitive->extensions.find("KHR_draco_mesh_compression");
  4377. if (dracoExtension != primitive->extensions.end()) {
  4378. ParseDracoExtension(primitive, model, err, warn, dracoExtension->second, strictness);
  4379. }
  4380. #else
  4381. (void)model;
  4382. (void)warn;
  4383. (void)strictness;
  4384. #endif
  4385. return true;
  4386. }
  4387. static bool ParseMesh(Mesh *mesh, Model *model,
  4388. std::string *err, std::string *warn,
  4389. const detail::json &o,
  4390. bool store_original_json_for_extras_and_extensions,
  4391. ParseStrictness strictness) {
  4392. ParseStringProperty(&mesh->name, err, o, "name", false);
  4393. mesh->primitives.clear();
  4394. detail::json_const_iterator primObject;
  4395. if (detail::FindMember(o, "primitives", primObject) &&
  4396. detail::IsArray(detail::GetValue(primObject))) {
  4397. detail::json_const_array_iterator primEnd =
  4398. detail::ArrayEnd(detail::GetValue(primObject));
  4399. for (detail::json_const_array_iterator i =
  4400. detail::ArrayBegin(detail::GetValue(primObject));
  4401. i != primEnd; ++i) {
  4402. Primitive primitive;
  4403. if (ParsePrimitive(&primitive, model, err, warn, *i,
  4404. store_original_json_for_extras_and_extensions,
  4405. strictness)) {
  4406. // Only add the primitive if the parsing succeeds.
  4407. mesh->primitives.emplace_back(std::move(primitive));
  4408. }
  4409. }
  4410. }
  4411. // Should probably check if has targets and if dimensions fit
  4412. ParseNumberArrayProperty(&mesh->weights, err, o, "weights", false);
  4413. ParseExtrasAndExtensions(mesh, err, o,
  4414. store_original_json_for_extras_and_extensions);
  4415. return true;
  4416. }
  4417. static bool ParseNode(Node *node, std::string *err, const detail::json &o,
  4418. bool store_original_json_for_extras_and_extensions) {
  4419. ParseStringProperty(&node->name, err, o, "name", false);
  4420. int skin = -1;
  4421. ParseIntegerProperty(&skin, err, o, "skin", false);
  4422. node->skin = skin;
  4423. // Matrix and T/R/S are exclusive
  4424. if (!ParseNumberArrayProperty(&node->matrix, err, o, "matrix", false)) {
  4425. ParseNumberArrayProperty(&node->rotation, err, o, "rotation", false);
  4426. ParseNumberArrayProperty(&node->scale, err, o, "scale", false);
  4427. ParseNumberArrayProperty(&node->translation, err, o, "translation", false);
  4428. }
  4429. int camera = -1;
  4430. ParseIntegerProperty(&camera, err, o, "camera", false);
  4431. node->camera = camera;
  4432. int mesh = -1;
  4433. ParseIntegerProperty(&mesh, err, o, "mesh", false);
  4434. node->mesh = mesh;
  4435. node->children.clear();
  4436. ParseIntegerArrayProperty(&node->children, err, o, "children", false);
  4437. ParseNumberArrayProperty(&node->weights, err, o, "weights", false);
  4438. ParseExtrasAndExtensions(node, err, o,
  4439. store_original_json_for_extras_and_extensions);
  4440. // KHR_lights_punctual: parse light source reference
  4441. int light = -1;
  4442. if (node->extensions.count("KHR_lights_punctual") != 0) {
  4443. auto const &light_ext = node->extensions["KHR_lights_punctual"];
  4444. if (light_ext.Has("light")) {
  4445. light = light_ext.Get("light").GetNumberAsInt();
  4446. } else {
  4447. if (err) {
  4448. *err +=
  4449. "Node has extension KHR_lights_punctual, but does not reference "
  4450. "a light source.\n";
  4451. }
  4452. return false;
  4453. }
  4454. }
  4455. node->light = light;
  4456. // KHR_audio: parse audio source reference
  4457. int emitter = -1;
  4458. if (node->extensions.count("KHR_audio") != 0) {
  4459. auto const &audio_ext = node->extensions["KHR_audio"];
  4460. if (audio_ext.Has("emitter")) {
  4461. emitter = audio_ext.Get("emitter").GetNumberAsInt();
  4462. } else {
  4463. if (err) {
  4464. *err +=
  4465. "Node has extension KHR_audio, but does not reference "
  4466. "a audio emitter.\n";
  4467. }
  4468. return false;
  4469. }
  4470. }
  4471. node->emitter = emitter;
  4472. return true;
  4473. }
  4474. static bool ParseScene(Scene *scene, std::string *err, const detail::json &o,
  4475. bool store_original_json_for_extras_and_extensions) {
  4476. ParseStringProperty(&scene->name, err, o, "name", false);
  4477. ParseIntegerArrayProperty(&scene->nodes, err, o, "nodes", false);
  4478. ParseExtrasAndExtensions(scene, err, o,
  4479. store_original_json_for_extras_and_extensions);
  4480. // Parse KHR_audio global emitters
  4481. if (scene->extensions.count("KHR_audio") != 0) {
  4482. auto const &audio_ext = scene->extensions["KHR_audio"];
  4483. if (audio_ext.Has("emitters")) {
  4484. auto emittersArr = audio_ext.Get("emitters");
  4485. for (size_t i = 0; i < emittersArr.ArrayLen(); ++i) {
  4486. scene->audioEmitters.emplace_back(emittersArr.Get(i).GetNumberAsInt());
  4487. }
  4488. } else {
  4489. if (err) {
  4490. *err +=
  4491. "Node has extension KHR_audio, but does not reference "
  4492. "a audio emitter.\n";
  4493. }
  4494. return false;
  4495. }
  4496. }
  4497. return true;
  4498. }
  4499. static bool ParsePbrMetallicRoughness(
  4500. PbrMetallicRoughness *pbr, std::string *err, const detail::json &o,
  4501. bool store_original_json_for_extras_and_extensions) {
  4502. if (pbr == nullptr) {
  4503. return false;
  4504. }
  4505. std::vector<double> baseColorFactor;
  4506. if (ParseNumberArrayProperty(&baseColorFactor, err, o, "baseColorFactor",
  4507. /* required */ false)) {
  4508. if (baseColorFactor.size() != 4) {
  4509. if (err) {
  4510. (*err) +=
  4511. "Array length of `baseColorFactor` parameter in "
  4512. "pbrMetallicRoughness must be 4, but got " +
  4513. std::to_string(baseColorFactor.size()) + "\n";
  4514. }
  4515. return false;
  4516. }
  4517. pbr->baseColorFactor = baseColorFactor;
  4518. }
  4519. {
  4520. detail::json_const_iterator it;
  4521. if (detail::FindMember(o, "baseColorTexture", it)) {
  4522. ParseTextureInfo(&pbr->baseColorTexture, err, detail::GetValue(it),
  4523. store_original_json_for_extras_and_extensions);
  4524. }
  4525. }
  4526. {
  4527. detail::json_const_iterator it;
  4528. if (detail::FindMember(o, "metallicRoughnessTexture", it)) {
  4529. ParseTextureInfo(&pbr->metallicRoughnessTexture, err,
  4530. detail::GetValue(it),
  4531. store_original_json_for_extras_and_extensions);
  4532. }
  4533. }
  4534. ParseNumberProperty(&pbr->metallicFactor, err, o, "metallicFactor", false);
  4535. ParseNumberProperty(&pbr->roughnessFactor, err, o, "roughnessFactor", false);
  4536. ParseExtrasAndExtensions(pbr, err, o,
  4537. store_original_json_for_extras_and_extensions);
  4538. return true;
  4539. }
  4540. static bool ParseMaterial(Material *material, std::string *err, std::string *warn,
  4541. const detail::json &o,
  4542. bool store_original_json_for_extras_and_extensions,
  4543. ParseStrictness strictness) {
  4544. ParseStringProperty(&material->name, err, o, "name", /* required */ false);
  4545. if (ParseNumberArrayProperty(&material->emissiveFactor, err, o,
  4546. "emissiveFactor",
  4547. /* required */ false)) {
  4548. if (strictness==ParseStrictness::Permissive && material->emissiveFactor.size() == 4) {
  4549. if (warn) {
  4550. (*warn) +=
  4551. "Array length of `emissiveFactor` parameter in "
  4552. "material must be 3, but got 4\n";
  4553. }
  4554. material->emissiveFactor.resize(3);
  4555. }
  4556. else if (material->emissiveFactor.size() != 3) {
  4557. if (err) {
  4558. (*err) +=
  4559. "Array length of `emissiveFactor` parameter in "
  4560. "material must be 3, but got " +
  4561. std::to_string(material->emissiveFactor.size()) + "\n";
  4562. }
  4563. return false;
  4564. }
  4565. } else {
  4566. // fill with default values
  4567. material->emissiveFactor = {0.0, 0.0, 0.0};
  4568. }
  4569. ParseStringProperty(&material->alphaMode, err, o, "alphaMode",
  4570. /* required */ false);
  4571. ParseNumberProperty(&material->alphaCutoff, err, o, "alphaCutoff",
  4572. /* required */ false);
  4573. ParseBooleanProperty(&material->doubleSided, err, o, "doubleSided",
  4574. /* required */ false);
  4575. {
  4576. detail::json_const_iterator it;
  4577. if (detail::FindMember(o, "pbrMetallicRoughness", it)) {
  4578. ParsePbrMetallicRoughness(&material->pbrMetallicRoughness, err,
  4579. detail::GetValue(it),
  4580. store_original_json_for_extras_and_extensions);
  4581. }
  4582. }
  4583. {
  4584. detail::json_const_iterator it;
  4585. if (detail::FindMember(o, "normalTexture", it)) {
  4586. ParseNormalTextureInfo(&material->normalTexture, err,
  4587. detail::GetValue(it),
  4588. store_original_json_for_extras_and_extensions);
  4589. }
  4590. }
  4591. {
  4592. detail::json_const_iterator it;
  4593. if (detail::FindMember(o, "occlusionTexture", it)) {
  4594. ParseOcclusionTextureInfo(&material->occlusionTexture, err,
  4595. detail::GetValue(it),
  4596. store_original_json_for_extras_and_extensions);
  4597. }
  4598. }
  4599. {
  4600. detail::json_const_iterator it;
  4601. if (detail::FindMember(o, "emissiveTexture", it)) {
  4602. ParseTextureInfo(&material->emissiveTexture, err, detail::GetValue(it),
  4603. store_original_json_for_extras_and_extensions);
  4604. }
  4605. }
  4606. // Old code path. For backward compatibility, we still store material values
  4607. // as Parameter. This will create duplicated information for
  4608. // example(pbrMetallicRoughness), but should be negligible in terms of memory
  4609. // consumption.
  4610. // TODO(syoyo): Remove in the next major release.
  4611. material->values.clear();
  4612. material->additionalValues.clear();
  4613. detail::json_const_iterator it(detail::ObjectBegin(o));
  4614. detail::json_const_iterator itEnd(detail::ObjectEnd(o));
  4615. for (; it != itEnd; ++it) {
  4616. std::string key(detail::GetKey(it));
  4617. if (key == "pbrMetallicRoughness") {
  4618. if (detail::IsObject(detail::GetValue(it))) {
  4619. const detail::json &values_object = detail::GetValue(it);
  4620. detail::json_const_iterator itVal(detail::ObjectBegin(values_object));
  4621. detail::json_const_iterator itValEnd(detail::ObjectEnd(values_object));
  4622. for (; itVal != itValEnd; ++itVal) {
  4623. Parameter param;
  4624. if (ParseParameterProperty(&param, err, values_object,
  4625. detail::GetKey(itVal), false)) {
  4626. material->values.emplace(detail::GetKey(itVal), std::move(param));
  4627. }
  4628. }
  4629. }
  4630. } else if (key == "extensions" || key == "extras") {
  4631. // done later, skip, otherwise poorly parsed contents will be saved in the
  4632. // parametermap and serialized again later
  4633. } else {
  4634. Parameter param;
  4635. if (ParseParameterProperty(&param, err, o, key, false)) {
  4636. // names of materials have already been parsed. Putting it in this map
  4637. // doesn't correctly reflect the glTF specification
  4638. if (key != "name")
  4639. material->additionalValues.emplace(std::move(key), std::move(param));
  4640. }
  4641. }
  4642. }
  4643. material->extensions.clear(); // Note(agnat): Why?
  4644. ParseExtrasAndExtensions(material, err, o,
  4645. store_original_json_for_extras_and_extensions);
  4646. return true;
  4647. }
  4648. static bool ParseAnimationChannel(
  4649. AnimationChannel *channel, std::string *err, const detail::json &o,
  4650. bool store_original_json_for_extras_and_extensions) {
  4651. int samplerIndex = -1;
  4652. int targetIndex = -1;
  4653. if (!ParseIntegerProperty(&samplerIndex, err, o, "sampler", true,
  4654. "AnimationChannel")) {
  4655. if (err) {
  4656. (*err) += "`sampler` field is missing in animation channels\n";
  4657. }
  4658. return false;
  4659. }
  4660. detail::json_const_iterator targetIt;
  4661. if (detail::FindMember(o, "target", targetIt) &&
  4662. detail::IsObject(detail::GetValue(targetIt))) {
  4663. const detail::json &target_object = detail::GetValue(targetIt);
  4664. ParseIntegerProperty(&targetIndex, err, target_object, "node", false);
  4665. if (!ParseStringProperty(&channel->target_path, err, target_object, "path",
  4666. true)) {
  4667. if (err) {
  4668. (*err) += "`path` field is missing in animation.channels.target\n";
  4669. }
  4670. return false;
  4671. }
  4672. ParseExtensionsProperty(&channel->target_extensions, err, target_object);
  4673. ParseExtrasProperty(&channel->target_extras, target_object);
  4674. if (store_original_json_for_extras_and_extensions) {
  4675. {
  4676. detail::json_const_iterator it;
  4677. if (detail::FindMember(target_object, "extensions", it)) {
  4678. channel->target_extensions_json_string =
  4679. detail::JsonToString(detail::GetValue(it));
  4680. }
  4681. }
  4682. {
  4683. detail::json_const_iterator it;
  4684. if (detail::FindMember(target_object, "extras", it)) {
  4685. channel->target_extras_json_string =
  4686. detail::JsonToString(detail::GetValue(it));
  4687. }
  4688. }
  4689. }
  4690. }
  4691. channel->sampler = samplerIndex;
  4692. channel->target_node = targetIndex;
  4693. ParseExtrasAndExtensions(channel, err, o,
  4694. store_original_json_for_extras_and_extensions);
  4695. return true;
  4696. }
  4697. static bool ParseAnimation(Animation *animation, std::string *err,
  4698. const detail::json &o,
  4699. bool store_original_json_for_extras_and_extensions) {
  4700. {
  4701. detail::json_const_iterator channelsIt;
  4702. if (detail::FindMember(o, "channels", channelsIt) &&
  4703. detail::IsArray(detail::GetValue(channelsIt))) {
  4704. detail::json_const_array_iterator channelEnd =
  4705. detail::ArrayEnd(detail::GetValue(channelsIt));
  4706. for (detail::json_const_array_iterator i =
  4707. detail::ArrayBegin(detail::GetValue(channelsIt));
  4708. i != channelEnd; ++i) {
  4709. AnimationChannel channel;
  4710. if (ParseAnimationChannel(
  4711. &channel, err, *i,
  4712. store_original_json_for_extras_and_extensions)) {
  4713. // Only add the channel if the parsing succeeds.
  4714. animation->channels.emplace_back(std::move(channel));
  4715. }
  4716. }
  4717. }
  4718. }
  4719. {
  4720. detail::json_const_iterator samplerIt;
  4721. if (detail::FindMember(o, "samplers", samplerIt) &&
  4722. detail::IsArray(detail::GetValue(samplerIt))) {
  4723. const detail::json &sampler_array = detail::GetValue(samplerIt);
  4724. detail::json_const_array_iterator it = detail::ArrayBegin(sampler_array);
  4725. detail::json_const_array_iterator itEnd = detail::ArrayEnd(sampler_array);
  4726. for (; it != itEnd; ++it) {
  4727. const detail::json &s = *it;
  4728. AnimationSampler sampler;
  4729. int inputIndex = -1;
  4730. int outputIndex = -1;
  4731. if (!ParseIntegerProperty(&inputIndex, err, s, "input", true)) {
  4732. if (err) {
  4733. (*err) += "`input` field is missing in animation.sampler\n";
  4734. }
  4735. return false;
  4736. }
  4737. ParseStringProperty(&sampler.interpolation, err, s, "interpolation",
  4738. false);
  4739. if (!ParseIntegerProperty(&outputIndex, err, s, "output", true)) {
  4740. if (err) {
  4741. (*err) += "`output` field is missing in animation.sampler\n";
  4742. }
  4743. return false;
  4744. }
  4745. sampler.input = inputIndex;
  4746. sampler.output = outputIndex;
  4747. ParseExtrasAndExtensions(&sampler, err, o,
  4748. store_original_json_for_extras_and_extensions);
  4749. animation->samplers.emplace_back(std::move(sampler));
  4750. }
  4751. }
  4752. }
  4753. ParseStringProperty(&animation->name, err, o, "name", false);
  4754. ParseExtrasAndExtensions(animation, err, o,
  4755. store_original_json_for_extras_and_extensions);
  4756. return true;
  4757. }
  4758. static bool ParseSampler(Sampler *sampler, std::string *err,
  4759. const detail::json &o,
  4760. bool store_original_json_for_extras_and_extensions) {
  4761. ParseStringProperty(&sampler->name, err, o, "name", false);
  4762. int minFilter = -1;
  4763. int magFilter = -1;
  4764. int wrapS = TINYGLTF_TEXTURE_WRAP_REPEAT;
  4765. int wrapT = TINYGLTF_TEXTURE_WRAP_REPEAT;
  4766. // int wrapR = TINYGLTF_TEXTURE_WRAP_REPEAT;
  4767. ParseIntegerProperty(&minFilter, err, o, "minFilter", false);
  4768. ParseIntegerProperty(&magFilter, err, o, "magFilter", false);
  4769. ParseIntegerProperty(&wrapS, err, o, "wrapS", false);
  4770. ParseIntegerProperty(&wrapT, err, o, "wrapT", false);
  4771. // ParseIntegerProperty(&wrapR, err, o, "wrapR", false); // tinygltf
  4772. // extension
  4773. // TODO(syoyo): Check the value is allowed one.
  4774. // (e.g. we allow 9728(NEAREST), but don't allow 9727)
  4775. sampler->minFilter = minFilter;
  4776. sampler->magFilter = magFilter;
  4777. sampler->wrapS = wrapS;
  4778. sampler->wrapT = wrapT;
  4779. // sampler->wrapR = wrapR;
  4780. ParseExtrasAndExtensions(sampler, err, o,
  4781. store_original_json_for_extras_and_extensions);
  4782. return true;
  4783. }
  4784. static bool ParseSkin(Skin *skin, std::string *err, const detail::json &o,
  4785. bool store_original_json_for_extras_and_extensions) {
  4786. ParseStringProperty(&skin->name, err, o, "name", false, "Skin");
  4787. std::vector<int> joints;
  4788. if (!ParseIntegerArrayProperty(&joints, err, o, "joints", false, "Skin")) {
  4789. return false;
  4790. }
  4791. skin->joints = std::move(joints);
  4792. int skeleton = -1;
  4793. ParseIntegerProperty(&skeleton, err, o, "skeleton", false, "Skin");
  4794. skin->skeleton = skeleton;
  4795. int invBind = -1;
  4796. ParseIntegerProperty(&invBind, err, o, "inverseBindMatrices", true, "Skin");
  4797. skin->inverseBindMatrices = invBind;
  4798. ParseExtrasAndExtensions(skin, err, o,
  4799. store_original_json_for_extras_and_extensions);
  4800. return true;
  4801. }
  4802. static bool ParsePerspectiveCamera(
  4803. PerspectiveCamera *camera, std::string *err, const detail::json &o,
  4804. bool store_original_json_for_extras_and_extensions) {
  4805. double yfov = 0.0;
  4806. if (!ParseNumberProperty(&yfov, err, o, "yfov", true, "OrthographicCamera")) {
  4807. return false;
  4808. }
  4809. double znear = 0.0;
  4810. if (!ParseNumberProperty(&znear, err, o, "znear", true,
  4811. "PerspectiveCamera")) {
  4812. return false;
  4813. }
  4814. double aspectRatio = 0.0; // = invalid
  4815. ParseNumberProperty(&aspectRatio, err, o, "aspectRatio", false,
  4816. "PerspectiveCamera");
  4817. double zfar = 0.0; // = invalid
  4818. ParseNumberProperty(&zfar, err, o, "zfar", false, "PerspectiveCamera");
  4819. camera->aspectRatio = aspectRatio;
  4820. camera->zfar = zfar;
  4821. camera->yfov = yfov;
  4822. camera->znear = znear;
  4823. ParseExtrasAndExtensions(camera, err, o,
  4824. store_original_json_for_extras_and_extensions);
  4825. // TODO(syoyo): Validate parameter values.
  4826. return true;
  4827. }
  4828. static bool ParseSpotLight(SpotLight *light, std::string *err,
  4829. const detail::json &o,
  4830. bool store_original_json_for_extras_and_extensions) {
  4831. ParseNumberProperty(&light->innerConeAngle, err, o, "innerConeAngle", false);
  4832. ParseNumberProperty(&light->outerConeAngle, err, o, "outerConeAngle", false);
  4833. ParseExtrasAndExtensions(light, err, o,
  4834. store_original_json_for_extras_and_extensions);
  4835. // TODO(syoyo): Validate parameter values.
  4836. return true;
  4837. }
  4838. static bool ParseOrthographicCamera(
  4839. OrthographicCamera *camera, std::string *err, const detail::json &o,
  4840. bool store_original_json_for_extras_and_extensions) {
  4841. double xmag = 0.0;
  4842. if (!ParseNumberProperty(&xmag, err, o, "xmag", true, "OrthographicCamera")) {
  4843. return false;
  4844. }
  4845. double ymag = 0.0;
  4846. if (!ParseNumberProperty(&ymag, err, o, "ymag", true, "OrthographicCamera")) {
  4847. return false;
  4848. }
  4849. double zfar = 0.0;
  4850. if (!ParseNumberProperty(&zfar, err, o, "zfar", true, "OrthographicCamera")) {
  4851. return false;
  4852. }
  4853. double znear = 0.0;
  4854. if (!ParseNumberProperty(&znear, err, o, "znear", true,
  4855. "OrthographicCamera")) {
  4856. return false;
  4857. }
  4858. ParseExtrasAndExtensions(camera, err, o,
  4859. store_original_json_for_extras_and_extensions);
  4860. camera->xmag = xmag;
  4861. camera->ymag = ymag;
  4862. camera->zfar = zfar;
  4863. camera->znear = znear;
  4864. // TODO(syoyo): Validate parameter values.
  4865. return true;
  4866. }
  4867. static bool ParseCamera(Camera *camera, std::string *err, const detail::json &o,
  4868. bool store_original_json_for_extras_and_extensions) {
  4869. if (!ParseStringProperty(&camera->type, err, o, "type", true, "Camera")) {
  4870. return false;
  4871. }
  4872. if (camera->type.compare("orthographic") == 0) {
  4873. detail::json_const_iterator orthoIt;
  4874. if (!detail::FindMember(o, "orthographic", orthoIt)) {
  4875. if (err) {
  4876. std::stringstream ss;
  4877. ss << "Orthographic camera description not found." << std::endl;
  4878. (*err) += ss.str();
  4879. }
  4880. return false;
  4881. }
  4882. const detail::json &v = detail::GetValue(orthoIt);
  4883. if (!detail::IsObject(v)) {
  4884. if (err) {
  4885. std::stringstream ss;
  4886. ss << "\"orthographic\" is not a JSON object." << std::endl;
  4887. (*err) += ss.str();
  4888. }
  4889. return false;
  4890. }
  4891. if (!ParseOrthographicCamera(
  4892. &camera->orthographic, err, v,
  4893. store_original_json_for_extras_and_extensions)) {
  4894. return false;
  4895. }
  4896. } else if (camera->type.compare("perspective") == 0) {
  4897. detail::json_const_iterator perspIt;
  4898. if (!detail::FindMember(o, "perspective", perspIt)) {
  4899. if (err) {
  4900. std::stringstream ss;
  4901. ss << "Perspective camera description not found." << std::endl;
  4902. (*err) += ss.str();
  4903. }
  4904. return false;
  4905. }
  4906. const detail::json &v = detail::GetValue(perspIt);
  4907. if (!detail::IsObject(v)) {
  4908. if (err) {
  4909. std::stringstream ss;
  4910. ss << "\"perspective\" is not a JSON object." << std::endl;
  4911. (*err) += ss.str();
  4912. }
  4913. return false;
  4914. }
  4915. if (!ParsePerspectiveCamera(
  4916. &camera->perspective, err, v,
  4917. store_original_json_for_extras_and_extensions)) {
  4918. return false;
  4919. }
  4920. } else {
  4921. if (err) {
  4922. std::stringstream ss;
  4923. ss << "Invalid camera type: \"" << camera->type
  4924. << "\". Must be \"perspective\" or \"orthographic\"" << std::endl;
  4925. (*err) += ss.str();
  4926. }
  4927. return false;
  4928. }
  4929. ParseStringProperty(&camera->name, err, o, "name", false);
  4930. ParseExtrasAndExtensions(camera, err, o,
  4931. store_original_json_for_extras_and_extensions);
  4932. return true;
  4933. }
  4934. static bool ParseLight(Light *light, std::string *err, const detail::json &o,
  4935. bool store_original_json_for_extras_and_extensions) {
  4936. if (!ParseStringProperty(&light->type, err, o, "type", true)) {
  4937. return false;
  4938. }
  4939. if (light->type == "spot") {
  4940. detail::json_const_iterator spotIt;
  4941. if (!detail::FindMember(o, "spot", spotIt)) {
  4942. if (err) {
  4943. std::stringstream ss;
  4944. ss << "Spot light description not found." << std::endl;
  4945. (*err) += ss.str();
  4946. }
  4947. return false;
  4948. }
  4949. const detail::json &v = detail::GetValue(spotIt);
  4950. if (!detail::IsObject(v)) {
  4951. if (err) {
  4952. std::stringstream ss;
  4953. ss << "\"spot\" is not a JSON object." << std::endl;
  4954. (*err) += ss.str();
  4955. }
  4956. return false;
  4957. }
  4958. if (!ParseSpotLight(&light->spot, err, v,
  4959. store_original_json_for_extras_and_extensions)) {
  4960. return false;
  4961. }
  4962. }
  4963. ParseStringProperty(&light->name, err, o, "name", false);
  4964. ParseNumberArrayProperty(&light->color, err, o, "color", false);
  4965. ParseNumberProperty(&light->range, err, o, "range", false);
  4966. ParseNumberProperty(&light->intensity, err, o, "intensity", false);
  4967. ParseExtrasAndExtensions(light, err, o,
  4968. store_original_json_for_extras_and_extensions);
  4969. return true;
  4970. }
  4971. static bool ParsePositionalEmitter(
  4972. PositionalEmitter *positional, std::string *err, const detail::json &o,
  4973. bool store_original_json_for_extras_and_extensions) {
  4974. ParseNumberProperty(&positional->coneInnerAngle, err, o, "coneInnerAngle",
  4975. false);
  4976. ParseNumberProperty(&positional->coneOuterAngle, err, o, "coneOuterAngle",
  4977. false);
  4978. ParseNumberProperty(&positional->coneOuterGain, err, o, "coneOuterGain",
  4979. false);
  4980. ParseNumberProperty(&positional->maxDistance, err, o, "maxDistance", false);
  4981. ParseNumberProperty(&positional->refDistance, err, o, "refDistance", false);
  4982. ParseNumberProperty(&positional->rolloffFactor, err, o, "rolloffFactor",
  4983. false);
  4984. ParseExtrasAndExtensions(positional, err, o,
  4985. store_original_json_for_extras_and_extensions);
  4986. return true;
  4987. }
  4988. static bool ParseAudioEmitter(
  4989. AudioEmitter *emitter, std::string *err, const detail::json &o,
  4990. bool store_original_json_for_extras_and_extensions) {
  4991. if (!ParseStringProperty(&emitter->type, err, o, "type", true)) {
  4992. return false;
  4993. }
  4994. if (emitter->type == "positional") {
  4995. detail::json_const_iterator positionalIt;
  4996. if (!detail::FindMember(o, "positional", positionalIt)) {
  4997. if (err) {
  4998. std::stringstream ss;
  4999. ss << "Positional emitter description not found." << std::endl;
  5000. (*err) += ss.str();
  5001. }
  5002. return false;
  5003. }
  5004. const detail::json &v = detail::GetValue(positionalIt);
  5005. if (!detail::IsObject(v)) {
  5006. if (err) {
  5007. std::stringstream ss;
  5008. ss << "\"positional\" is not a JSON object." << std::endl;
  5009. (*err) += ss.str();
  5010. }
  5011. return false;
  5012. }
  5013. if (!ParsePositionalEmitter(
  5014. &emitter->positional, err, v,
  5015. store_original_json_for_extras_and_extensions)) {
  5016. return false;
  5017. }
  5018. }
  5019. ParseStringProperty(&emitter->name, err, o, "name", false);
  5020. ParseNumberProperty(&emitter->gain, err, o, "gain", false);
  5021. ParseBooleanProperty(&emitter->loop, err, o, "loop", false);
  5022. ParseBooleanProperty(&emitter->playing, err, o, "playing", false);
  5023. ParseStringProperty(&emitter->distanceModel, err, o, "distanceModel", false);
  5024. ParseIntegerProperty(&emitter->source, err, o, "source", true);
  5025. ParseExtrasAndExtensions(emitter, err, o,
  5026. store_original_json_for_extras_and_extensions);
  5027. return true;
  5028. }
  5029. static bool ParseAudioSource(
  5030. AudioSource *source, std::string *err, const detail::json &o,
  5031. bool store_original_json_for_extras_and_extensions) {
  5032. ParseStringProperty(&source->name, err, o, "name", false);
  5033. ParseStringProperty(&source->uri, err, o, "uri", false);
  5034. if (source->uri.empty()) {
  5035. ParseIntegerProperty(&source->bufferView, err, o, "bufferView", true);
  5036. ParseStringProperty(&source->mimeType, err, o, "mimeType", true);
  5037. }
  5038. ParseExtrasAndExtensions(source, err, o,
  5039. store_original_json_for_extras_and_extensions);
  5040. return true;
  5041. }
  5042. namespace detail {
  5043. template <typename Callback>
  5044. bool ForEachInArray(const detail::json &_v, const char *member, Callback &&cb) {
  5045. detail::json_const_iterator itm;
  5046. if (detail::FindMember(_v, member, itm) &&
  5047. detail::IsArray(detail::GetValue(itm))) {
  5048. const detail::json &root = detail::GetValue(itm);
  5049. auto it = detail::ArrayBegin(root);
  5050. auto end = detail::ArrayEnd(root);
  5051. for (; it != end; ++it) {
  5052. if (!cb(*it)) return false;
  5053. }
  5054. }
  5055. return true;
  5056. };
  5057. } // end of namespace detail
  5058. bool TinyGLTF::LoadFromString(Model *model, std::string *err, std::string *warn,
  5059. const char *json_str,
  5060. unsigned int json_str_length,
  5061. const std::string &base_dir,
  5062. unsigned int check_sections) {
  5063. if (json_str_length < 4) {
  5064. if (err) {
  5065. (*err) = "JSON string too short.\n";
  5066. }
  5067. return false;
  5068. }
  5069. detail::JsonDocument v;
  5070. #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || \
  5071. defined(_CPPUNWIND)) && \
  5072. !defined(TINYGLTF_NOEXCEPTION)
  5073. try {
  5074. detail::JsonParse(v, json_str, json_str_length, true);
  5075. } catch (const std::exception &e) {
  5076. if (err) {
  5077. (*err) = e.what();
  5078. }
  5079. return false;
  5080. }
  5081. #else
  5082. {
  5083. detail::JsonParse(v, json_str, json_str_length);
  5084. if (!detail::IsObject(v)) {
  5085. // Assume parsing was failed.
  5086. if (err) {
  5087. (*err) = "Failed to parse JSON object\n";
  5088. }
  5089. return false;
  5090. }
  5091. }
  5092. #endif
  5093. if (!detail::IsObject(v)) {
  5094. // root is not an object.
  5095. if (err) {
  5096. (*err) = "Root element is not a JSON object\n";
  5097. }
  5098. return false;
  5099. }
  5100. {
  5101. bool version_found = false;
  5102. detail::json_const_iterator it;
  5103. if (detail::FindMember(v, "asset", it) &&
  5104. detail::IsObject(detail::GetValue(it))) {
  5105. auto &itObj = detail::GetValue(it);
  5106. detail::json_const_iterator version_it;
  5107. std::string versionStr;
  5108. if (detail::FindMember(itObj, "version", version_it) &&
  5109. detail::GetString(detail::GetValue(version_it), versionStr)) {
  5110. version_found = true;
  5111. }
  5112. }
  5113. if (version_found) {
  5114. // OK
  5115. } else if (check_sections & REQUIRE_VERSION) {
  5116. if (err) {
  5117. (*err) += "\"asset\" object not found in .gltf or not an object type\n";
  5118. }
  5119. return false;
  5120. }
  5121. }
  5122. // scene is not mandatory.
  5123. // FIXME Maybe a better way to handle it than removing the code
  5124. auto IsArrayMemberPresent = [](const detail::json &_v,
  5125. const char *name) -> bool {
  5126. detail::json_const_iterator it;
  5127. return detail::FindMember(_v, name, it) &&
  5128. detail::IsArray(detail::GetValue(it));
  5129. };
  5130. {
  5131. if ((check_sections & REQUIRE_SCENES) &&
  5132. !IsArrayMemberPresent(v, "scenes")) {
  5133. if (err) {
  5134. (*err) += "\"scenes\" object not found in .gltf or not an array type\n";
  5135. }
  5136. return false;
  5137. }
  5138. }
  5139. {
  5140. if ((check_sections & REQUIRE_NODES) && !IsArrayMemberPresent(v, "nodes")) {
  5141. if (err) {
  5142. (*err) += "\"nodes\" object not found in .gltf\n";
  5143. }
  5144. return false;
  5145. }
  5146. }
  5147. {
  5148. if ((check_sections & REQUIRE_ACCESSORS) &&
  5149. !IsArrayMemberPresent(v, "accessors")) {
  5150. if (err) {
  5151. (*err) += "\"accessors\" object not found in .gltf\n";
  5152. }
  5153. return false;
  5154. }
  5155. }
  5156. {
  5157. if ((check_sections & REQUIRE_BUFFERS) &&
  5158. !IsArrayMemberPresent(v, "buffers")) {
  5159. if (err) {
  5160. (*err) += "\"buffers\" object not found in .gltf\n";
  5161. }
  5162. return false;
  5163. }
  5164. }
  5165. {
  5166. if ((check_sections & REQUIRE_BUFFER_VIEWS) &&
  5167. !IsArrayMemberPresent(v, "bufferViews")) {
  5168. if (err) {
  5169. (*err) += "\"bufferViews\" object not found in .gltf\n";
  5170. }
  5171. return false;
  5172. }
  5173. }
  5174. model->buffers.clear();
  5175. model->bufferViews.clear();
  5176. model->accessors.clear();
  5177. model->meshes.clear();
  5178. model->cameras.clear();
  5179. model->nodes.clear();
  5180. model->extensionsUsed.clear();
  5181. model->extensionsRequired.clear();
  5182. model->extensions.clear();
  5183. model->defaultScene = -1;
  5184. // 1. Parse Asset
  5185. {
  5186. detail::json_const_iterator it;
  5187. if (detail::FindMember(v, "asset", it) &&
  5188. detail::IsObject(detail::GetValue(it))) {
  5189. const detail::json &root = detail::GetValue(it);
  5190. ParseAsset(&model->asset, err, root,
  5191. store_original_json_for_extras_and_extensions_);
  5192. }
  5193. }
  5194. using detail::ForEachInArray;
  5195. // 2. Parse extensionUsed
  5196. {
  5197. ForEachInArray(v, "extensionsUsed", [&](const detail::json &o) {
  5198. std::string str;
  5199. detail::GetString(o, str);
  5200. model->extensionsUsed.emplace_back(std::move(str));
  5201. return true;
  5202. });
  5203. }
  5204. {
  5205. ForEachInArray(v, "extensionsRequired", [&](const detail::json &o) {
  5206. std::string str;
  5207. detail::GetString(o, str);
  5208. model->extensionsRequired.emplace_back(std::move(str));
  5209. return true;
  5210. });
  5211. }
  5212. // 3. Parse Buffer
  5213. {
  5214. bool success = ForEachInArray(v, "buffers", [&](const detail::json &o) {
  5215. if (!detail::IsObject(o)) {
  5216. if (err) {
  5217. (*err) += "`buffers' does not contain an JSON object.";
  5218. }
  5219. return false;
  5220. }
  5221. Buffer buffer;
  5222. if (!ParseBuffer(&buffer, err, o,
  5223. store_original_json_for_extras_and_extensions_, &fs,
  5224. &uri_cb, base_dir, max_external_file_size_, is_binary_,
  5225. bin_data_, bin_size_)) {
  5226. return false;
  5227. }
  5228. model->buffers.emplace_back(std::move(buffer));
  5229. return true;
  5230. });
  5231. if (!success) {
  5232. return false;
  5233. }
  5234. }
  5235. // 4. Parse BufferView
  5236. {
  5237. bool success = ForEachInArray(v, "bufferViews", [&](const detail::json &o) {
  5238. if (!detail::IsObject(o)) {
  5239. if (err) {
  5240. (*err) += "`bufferViews' does not contain an JSON object.";
  5241. }
  5242. return false;
  5243. }
  5244. BufferView bufferView;
  5245. if (!ParseBufferView(&bufferView, err, o,
  5246. store_original_json_for_extras_and_extensions_)) {
  5247. return false;
  5248. }
  5249. model->bufferViews.emplace_back(std::move(bufferView));
  5250. return true;
  5251. });
  5252. if (!success) {
  5253. return false;
  5254. }
  5255. }
  5256. // 5. Parse Accessor
  5257. {
  5258. bool success = ForEachInArray(v, "accessors", [&](const detail::json &o) {
  5259. if (!detail::IsObject(o)) {
  5260. if (err) {
  5261. (*err) += "`accessors' does not contain an JSON object.";
  5262. }
  5263. return false;
  5264. }
  5265. Accessor accessor;
  5266. if (!ParseAccessor(&accessor, err, o,
  5267. store_original_json_for_extras_and_extensions_)) {
  5268. return false;
  5269. }
  5270. model->accessors.emplace_back(std::move(accessor));
  5271. return true;
  5272. });
  5273. if (!success) {
  5274. return false;
  5275. }
  5276. }
  5277. // 6. Parse Mesh
  5278. {
  5279. bool success = ForEachInArray(v, "meshes", [&](const detail::json &o) {
  5280. if (!detail::IsObject(o)) {
  5281. if (err) {
  5282. (*err) += "`meshes' does not contain an JSON object.";
  5283. }
  5284. return false;
  5285. }
  5286. Mesh mesh;
  5287. if (!ParseMesh(&mesh, model, err, warn, o,
  5288. store_original_json_for_extras_and_extensions_,
  5289. strictness_)) {
  5290. return false;
  5291. }
  5292. model->meshes.emplace_back(std::move(mesh));
  5293. return true;
  5294. });
  5295. if (!success) {
  5296. return false;
  5297. }
  5298. }
  5299. // Assign missing bufferView target types
  5300. // - Look for missing Mesh indices
  5301. // - Look for missing Mesh attributes
  5302. for (auto &mesh : model->meshes) {
  5303. for (auto &primitive : mesh.primitives) {
  5304. if (primitive.indices >
  5305. -1) // has indices from parsing step, must be Element Array Buffer
  5306. {
  5307. if (size_t(primitive.indices) >= model->accessors.size()) {
  5308. if (err) {
  5309. (*err) += "primitive indices accessor out of bounds";
  5310. }
  5311. return false;
  5312. }
  5313. auto bufferView =
  5314. model->accessors[size_t(primitive.indices)].bufferView;
  5315. if (bufferView < 0 || size_t(bufferView) >= model->bufferViews.size()) {
  5316. if (err) {
  5317. (*err) += "accessor[" + std::to_string(primitive.indices) +
  5318. "] invalid bufferView";
  5319. }
  5320. return false;
  5321. }
  5322. model->bufferViews[size_t(bufferView)].target =
  5323. TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER;
  5324. // we could optionally check if accessors' bufferView type is Scalar, as
  5325. // it should be
  5326. }
  5327. for (auto &attribute : primitive.attributes) {
  5328. const auto accessorsIndex = size_t(attribute.second);
  5329. if (accessorsIndex < model->accessors.size()) {
  5330. const auto bufferView = model->accessors[accessorsIndex].bufferView;
  5331. // bufferView could be null(-1) for sparse morph target
  5332. if (bufferView >= 0 && bufferView < (int)model->bufferViews.size()) {
  5333. model->bufferViews[size_t(bufferView)].target =
  5334. TINYGLTF_TARGET_ARRAY_BUFFER;
  5335. }
  5336. }
  5337. }
  5338. for (auto &target : primitive.targets) {
  5339. for (auto &attribute : target) {
  5340. const auto accessorsIndex = size_t(attribute.second);
  5341. if (accessorsIndex < model->accessors.size()) {
  5342. const auto bufferView = model->accessors[accessorsIndex].bufferView;
  5343. // bufferView could be null(-1) for sparse morph target
  5344. if (bufferView >= 0 &&
  5345. bufferView < (int)model->bufferViews.size()) {
  5346. model->bufferViews[size_t(bufferView)].target =
  5347. TINYGLTF_TARGET_ARRAY_BUFFER;
  5348. }
  5349. }
  5350. }
  5351. }
  5352. }
  5353. }
  5354. // 7. Parse Node
  5355. {
  5356. bool success = ForEachInArray(v, "nodes", [&](const detail::json &o) {
  5357. if (!detail::IsObject(o)) {
  5358. if (err) {
  5359. (*err) += "`nodes' does not contain an JSON object.";
  5360. }
  5361. return false;
  5362. }
  5363. Node node;
  5364. if (!ParseNode(&node, err, o,
  5365. store_original_json_for_extras_and_extensions_)) {
  5366. return false;
  5367. }
  5368. model->nodes.emplace_back(std::move(node));
  5369. return true;
  5370. });
  5371. if (!success) {
  5372. return false;
  5373. }
  5374. }
  5375. // 8. Parse scenes.
  5376. {
  5377. bool success = ForEachInArray(v, "scenes", [&](const detail::json &o) {
  5378. if (!detail::IsObject(o)) {
  5379. if (err) {
  5380. (*err) += "`scenes' does not contain an JSON object.";
  5381. }
  5382. return false;
  5383. }
  5384. Scene scene;
  5385. if (!ParseScene(&scene, err, o,
  5386. store_original_json_for_extras_and_extensions_)) {
  5387. return false;
  5388. }
  5389. model->scenes.emplace_back(std::move(scene));
  5390. return true;
  5391. });
  5392. if (!success) {
  5393. return false;
  5394. }
  5395. }
  5396. // 9. Parse default scenes.
  5397. {
  5398. detail::json_const_iterator rootIt;
  5399. int iVal;
  5400. if (detail::FindMember(v, "scene", rootIt) &&
  5401. detail::GetInt(detail::GetValue(rootIt), iVal)) {
  5402. model->defaultScene = iVal;
  5403. }
  5404. }
  5405. // 10. Parse Material
  5406. {
  5407. bool success = ForEachInArray(v, "materials", [&](const detail::json &o) {
  5408. if (!detail::IsObject(o)) {
  5409. if (err) {
  5410. (*err) += "`materials' does not contain an JSON object.";
  5411. }
  5412. return false;
  5413. }
  5414. Material material;
  5415. ParseStringProperty(&material.name, err, o, "name", false);
  5416. if (!ParseMaterial(&material, err, warn, o,
  5417. store_original_json_for_extras_and_extensions_,
  5418. strictness_)) {
  5419. return false;
  5420. }
  5421. model->materials.emplace_back(std::move(material));
  5422. return true;
  5423. });
  5424. if (!success) {
  5425. return false;
  5426. }
  5427. }
  5428. // 11. Parse Image
  5429. void *load_image_user_data{nullptr};
  5430. LoadImageDataOption load_image_option;
  5431. if (user_image_loader_) {
  5432. // Use user supplied pointer
  5433. load_image_user_data = load_image_user_data_;
  5434. } else {
  5435. load_image_option.preserve_channels = preserve_image_channels_;
  5436. load_image_user_data = reinterpret_cast<void *>(&load_image_option);
  5437. }
  5438. {
  5439. int idx = 0;
  5440. bool success = ForEachInArray(v, "images", [&](const detail::json &o) {
  5441. if (!detail::IsObject(o)) {
  5442. if (err) {
  5443. (*err) += "image[" + std::to_string(idx) + "] is not a JSON object.";
  5444. }
  5445. return false;
  5446. }
  5447. Image image;
  5448. if (!ParseImage(&image, idx, err, warn, o,
  5449. store_original_json_for_extras_and_extensions_, base_dir,
  5450. max_external_file_size_, &fs, &uri_cb,
  5451. &this->LoadImageData, load_image_user_data)) {
  5452. return false;
  5453. }
  5454. if (image.bufferView != -1) {
  5455. // Load image from the buffer view.
  5456. if (size_t(image.bufferView) >= model->bufferViews.size()) {
  5457. if (err) {
  5458. std::stringstream ss;
  5459. ss << "image[" << idx << "] bufferView \"" << image.bufferView
  5460. << "\" not found in the scene." << std::endl;
  5461. (*err) += ss.str();
  5462. }
  5463. return false;
  5464. }
  5465. const BufferView &bufferView =
  5466. model->bufferViews[size_t(image.bufferView)];
  5467. if (size_t(bufferView.buffer) >= model->buffers.size()) {
  5468. if (err) {
  5469. std::stringstream ss;
  5470. ss << "image[" << idx << "] buffer \"" << bufferView.buffer
  5471. << "\" not found in the scene." << std::endl;
  5472. (*err) += ss.str();
  5473. }
  5474. return false;
  5475. }
  5476. const Buffer &buffer = model->buffers[size_t(bufferView.buffer)];
  5477. if (*LoadImageData == nullptr) {
  5478. if (err) {
  5479. (*err) += "No LoadImageData callback specified.\n";
  5480. }
  5481. return false;
  5482. }
  5483. bool ret = LoadImageData(
  5484. &image, idx, err, warn, image.width, image.height,
  5485. &buffer.data[bufferView.byteOffset],
  5486. static_cast<int>(bufferView.byteLength), load_image_user_data);
  5487. if (!ret) {
  5488. return false;
  5489. }
  5490. }
  5491. model->images.emplace_back(std::move(image));
  5492. ++idx;
  5493. return true;
  5494. });
  5495. if (!success) {
  5496. return false;
  5497. }
  5498. }
  5499. // 12. Parse Texture
  5500. {
  5501. bool success = ForEachInArray(v, "textures", [&](const detail::json &o) {
  5502. if (!detail::IsObject(o)) {
  5503. if (err) {
  5504. (*err) += "`textures' does not contain an JSON object.";
  5505. }
  5506. return false;
  5507. }
  5508. Texture texture;
  5509. if (!ParseTexture(&texture, err, o,
  5510. store_original_json_for_extras_and_extensions_,
  5511. base_dir)) {
  5512. return false;
  5513. }
  5514. model->textures.emplace_back(std::move(texture));
  5515. return true;
  5516. });
  5517. if (!success) {
  5518. return false;
  5519. }
  5520. }
  5521. // 13. Parse Animation
  5522. {
  5523. bool success = ForEachInArray(v, "animations", [&](const detail::json &o) {
  5524. if (!detail::IsObject(o)) {
  5525. if (err) {
  5526. (*err) += "`animations' does not contain an JSON object.";
  5527. }
  5528. return false;
  5529. }
  5530. Animation animation;
  5531. if (!ParseAnimation(&animation, err, o,
  5532. store_original_json_for_extras_and_extensions_)) {
  5533. return false;
  5534. }
  5535. model->animations.emplace_back(std::move(animation));
  5536. return true;
  5537. });
  5538. if (!success) {
  5539. return false;
  5540. }
  5541. }
  5542. // 14. Parse Skin
  5543. {
  5544. bool success = ForEachInArray(v, "skins", [&](const detail::json &o) {
  5545. if (!detail::IsObject(o)) {
  5546. if (err) {
  5547. (*err) += "`skins' does not contain an JSON object.";
  5548. }
  5549. return false;
  5550. }
  5551. Skin skin;
  5552. if (!ParseSkin(&skin, err, o,
  5553. store_original_json_for_extras_and_extensions_)) {
  5554. return false;
  5555. }
  5556. model->skins.emplace_back(std::move(skin));
  5557. return true;
  5558. });
  5559. if (!success) {
  5560. return false;
  5561. }
  5562. }
  5563. // 15. Parse Sampler
  5564. {
  5565. bool success = ForEachInArray(v, "samplers", [&](const detail::json &o) {
  5566. if (!detail::IsObject(o)) {
  5567. if (err) {
  5568. (*err) += "`samplers' does not contain an JSON object.";
  5569. }
  5570. return false;
  5571. }
  5572. Sampler sampler;
  5573. if (!ParseSampler(&sampler, err, o,
  5574. store_original_json_for_extras_and_extensions_)) {
  5575. return false;
  5576. }
  5577. model->samplers.emplace_back(std::move(sampler));
  5578. return true;
  5579. });
  5580. if (!success) {
  5581. return false;
  5582. }
  5583. }
  5584. // 16. Parse Camera
  5585. {
  5586. bool success = ForEachInArray(v, "cameras", [&](const detail::json &o) {
  5587. if (!detail::IsObject(o)) {
  5588. if (err) {
  5589. (*err) += "`cameras' does not contain an JSON object.";
  5590. }
  5591. return false;
  5592. }
  5593. Camera camera;
  5594. if (!ParseCamera(&camera, err, o,
  5595. store_original_json_for_extras_and_extensions_)) {
  5596. return false;
  5597. }
  5598. model->cameras.emplace_back(std::move(camera));
  5599. return true;
  5600. });
  5601. if (!success) {
  5602. return false;
  5603. }
  5604. }
  5605. // 17. Parse Extras & Extensions
  5606. ParseExtrasAndExtensions(model, err, v,
  5607. store_original_json_for_extras_and_extensions_);
  5608. // 18. Specific extension implementations
  5609. {
  5610. detail::json_const_iterator rootIt;
  5611. if (detail::FindMember(v, "extensions", rootIt) &&
  5612. detail::IsObject(detail::GetValue(rootIt))) {
  5613. const detail::json &root = detail::GetValue(rootIt);
  5614. detail::json_const_iterator it(detail::ObjectBegin(root));
  5615. detail::json_const_iterator itEnd(detail::ObjectEnd(root));
  5616. for (; it != itEnd; ++it) {
  5617. // parse KHR_lights_punctual extension
  5618. std::string key(detail::GetKey(it));
  5619. if ((key == "KHR_lights_punctual") &&
  5620. detail::IsObject(detail::GetValue(it))) {
  5621. const detail::json &object = detail::GetValue(it);
  5622. detail::json_const_iterator itLight;
  5623. if (detail::FindMember(object, "lights", itLight)) {
  5624. const detail::json &lights = detail::GetValue(itLight);
  5625. if (!detail::IsArray(lights)) {
  5626. continue;
  5627. }
  5628. auto arrayIt(detail::ArrayBegin(lights));
  5629. auto arrayItEnd(detail::ArrayEnd(lights));
  5630. for (; arrayIt != arrayItEnd; ++arrayIt) {
  5631. Light light;
  5632. if (!ParseLight(&light, err, *arrayIt,
  5633. store_original_json_for_extras_and_extensions_)) {
  5634. return false;
  5635. }
  5636. model->lights.emplace_back(std::move(light));
  5637. }
  5638. }
  5639. }
  5640. // parse KHR_audio extension
  5641. if ((key == "KHR_audio") && detail::IsObject(detail::GetValue(it))) {
  5642. const detail::json &object = detail::GetValue(it);
  5643. detail::json_const_iterator itKhrAudio;
  5644. if (detail::FindMember(object, "emitters", itKhrAudio)) {
  5645. const detail::json &emitters = detail::GetValue(itKhrAudio);
  5646. if (!detail::IsArray(emitters)) {
  5647. continue;
  5648. }
  5649. auto arrayIt(detail::ArrayBegin(emitters));
  5650. auto arrayItEnd(detail::ArrayEnd(emitters));
  5651. for (; arrayIt != arrayItEnd; ++arrayIt) {
  5652. AudioEmitter emitter;
  5653. if (!ParseAudioEmitter(
  5654. &emitter, err, *arrayIt,
  5655. store_original_json_for_extras_and_extensions_)) {
  5656. return false;
  5657. }
  5658. model->audioEmitters.emplace_back(std::move(emitter));
  5659. }
  5660. }
  5661. if (detail::FindMember(object, "sources", itKhrAudio)) {
  5662. const detail::json &sources = detail::GetValue(itKhrAudio);
  5663. if (!detail::IsArray(sources)) {
  5664. continue;
  5665. }
  5666. auto arrayIt(detail::ArrayBegin(sources));
  5667. auto arrayItEnd(detail::ArrayEnd(sources));
  5668. for (; arrayIt != arrayItEnd; ++arrayIt) {
  5669. AudioSource source;
  5670. if (!ParseAudioSource(
  5671. &source, err, *arrayIt,
  5672. store_original_json_for_extras_and_extensions_)) {
  5673. return false;
  5674. }
  5675. model->audioSources.emplace_back(std::move(source));
  5676. }
  5677. }
  5678. }
  5679. }
  5680. }
  5681. }
  5682. return true;
  5683. }
  5684. bool TinyGLTF::LoadASCIIFromString(Model *model, std::string *err,
  5685. std::string *warn, const char *str,
  5686. unsigned int length,
  5687. const std::string &base_dir,
  5688. unsigned int check_sections) {
  5689. is_binary_ = false;
  5690. bin_data_ = nullptr;
  5691. bin_size_ = 0;
  5692. return LoadFromString(model, err, warn, str, length, base_dir,
  5693. check_sections);
  5694. }
  5695. bool TinyGLTF::LoadASCIIFromFile(Model *model, std::string *err,
  5696. std::string *warn, const std::string &filename,
  5697. unsigned int check_sections) {
  5698. std::stringstream ss;
  5699. if (fs.ReadWholeFile == nullptr) {
  5700. // Programmer error, assert() ?
  5701. ss << "Failed to read file: " << filename
  5702. << ": one or more FS callback not set" << std::endl;
  5703. if (err) {
  5704. (*err) = ss.str();
  5705. }
  5706. return false;
  5707. }
  5708. std::vector<unsigned char> data;
  5709. std::string fileerr;
  5710. bool fileread = fs.ReadWholeFile(&data, &fileerr, filename, fs.user_data);
  5711. if (!fileread) {
  5712. ss << "Failed to read file: " << filename << ": " << fileerr << std::endl;
  5713. if (err) {
  5714. (*err) = ss.str();
  5715. }
  5716. return false;
  5717. }
  5718. size_t sz = data.size();
  5719. if (sz == 0) {
  5720. if (err) {
  5721. (*err) = "Empty file.";
  5722. }
  5723. return false;
  5724. }
  5725. std::string basedir = GetBaseDir(filename);
  5726. bool ret = LoadASCIIFromString(
  5727. model, err, warn, reinterpret_cast<const char *>(&data.at(0)),
  5728. static_cast<unsigned int>(data.size()), basedir, check_sections);
  5729. return ret;
  5730. }
  5731. bool TinyGLTF::LoadBinaryFromMemory(Model *model, std::string *err,
  5732. std::string *warn,
  5733. const unsigned char *bytes,
  5734. unsigned int size,
  5735. const std::string &base_dir,
  5736. unsigned int check_sections) {
  5737. if (size < 20) {
  5738. if (err) {
  5739. (*err) = "Too short data size for glTF Binary.";
  5740. }
  5741. return false;
  5742. }
  5743. if (bytes[0] == 'g' && bytes[1] == 'l' && bytes[2] == 'T' &&
  5744. bytes[3] == 'F') {
  5745. // ok
  5746. } else {
  5747. if (err) {
  5748. (*err) = "Invalid magic.";
  5749. }
  5750. return false;
  5751. }
  5752. unsigned int version; // 4 bytes
  5753. unsigned int length; // 4 bytes
  5754. unsigned int chunk0_length; // 4 bytes
  5755. unsigned int chunk0_format; // 4 bytes;
  5756. memcpy(&version, bytes + 4, 4);
  5757. swap4(&version);
  5758. memcpy(&length, bytes + 8, 4);
  5759. swap4(&length);
  5760. memcpy(&chunk0_length, bytes + 12, 4); // JSON data length
  5761. swap4(&chunk0_length);
  5762. memcpy(&chunk0_format, bytes + 16, 4);
  5763. swap4(&chunk0_format);
  5764. // https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#binary-gltf-layout
  5765. //
  5766. // In case the Bin buffer is not present, the size is exactly 20 + size of
  5767. // JSON contents,
  5768. // so use "greater than" operator.
  5769. //
  5770. // https://github.com/syoyo/tinygltf/issues/372
  5771. // Use 64bit uint to avoid integer overflow.
  5772. uint64_t header_and_json_size = 20ull + uint64_t(chunk0_length);
  5773. if (header_and_json_size > std::numeric_limits<uint32_t>::max()) {
  5774. // Do not allow 4GB or more GLB data.
  5775. (*err) = "Invalid glTF binary. GLB data exceeds 4GB.";
  5776. }
  5777. if ((header_and_json_size > uint64_t(size)) || (chunk0_length < 1) ||
  5778. (length > size) || (header_and_json_size > uint64_t(length)) ||
  5779. (chunk0_format != 0x4E4F534A)) { // 0x4E4F534A = JSON format.
  5780. if (err) {
  5781. (*err) = "Invalid glTF binary.";
  5782. }
  5783. return false;
  5784. }
  5785. // Padding check
  5786. // The start and the end of each chunk must be aligned to a 4-byte boundary.
  5787. // No padding check for chunk0 start since its 4byte-boundary is ensured.
  5788. if ((header_and_json_size % 4) != 0) {
  5789. if (err) {
  5790. (*err) = "JSON Chunk end does not aligned to a 4-byte boundary.";
  5791. }
  5792. }
  5793. // std::cout << "header_and_json_size = " << header_and_json_size << "\n";
  5794. // std::cout << "length = " << length << "\n";
  5795. // Chunk1(BIN) data
  5796. // The spec says: When the binary buffer is empty or when it is stored by
  5797. // other means, this chunk SHOULD be omitted. So when header + JSON data ==
  5798. // binary size, Chunk1 is omitted.
  5799. if (header_and_json_size == uint64_t(length)) {
  5800. bin_data_ = nullptr;
  5801. bin_size_ = 0;
  5802. } else {
  5803. // Read Chunk1 info(BIN data)
  5804. // At least Chunk1 should have 12 bytes(8 bytes(header) + 4 bytes(bin
  5805. // payload could be 1~3 bytes, but need to be aligned to 4 bytes)
  5806. if ((header_and_json_size + 12ull) > uint64_t(length)) {
  5807. if (err) {
  5808. (*err) =
  5809. "Insufficient storage space for Chunk1(BIN data). At least Chunk1 "
  5810. "Must have 4 or more bytes, but got " +
  5811. std::to_string((header_and_json_size + 8ull) - uint64_t(length)) +
  5812. ".\n";
  5813. }
  5814. return false;
  5815. }
  5816. unsigned int chunk1_length; // 4 bytes
  5817. unsigned int chunk1_format; // 4 bytes;
  5818. memcpy(&chunk1_length, bytes + header_and_json_size,
  5819. 4); // JSON data length
  5820. swap4(&chunk1_length);
  5821. memcpy(&chunk1_format, bytes + header_and_json_size + 4, 4);
  5822. swap4(&chunk1_format);
  5823. // std::cout << "chunk1_length = " << chunk1_length << "\n";
  5824. if (chunk1_length < 4) {
  5825. if (err) {
  5826. (*err) = "Insufficient Chunk1(BIN) data size.";
  5827. }
  5828. return false;
  5829. }
  5830. if ((chunk1_length % 4) != 0) {
  5831. if (strictness_==ParseStrictness::Permissive) {
  5832. if (warn) {
  5833. (*warn) += "BIN Chunk end is not aligned to a 4-byte boundary.\n";
  5834. }
  5835. }
  5836. else {
  5837. if (err) {
  5838. (*err) = "BIN Chunk end is not aligned to a 4-byte boundary.";
  5839. }
  5840. return false;
  5841. }
  5842. }
  5843. if (uint64_t(chunk1_length) + header_and_json_size > uint64_t(length)) {
  5844. if (err) {
  5845. (*err) = "BIN Chunk data length exceeds the GLB size.";
  5846. }
  5847. return false;
  5848. }
  5849. if (chunk1_format != 0x004e4942) {
  5850. if (err) {
  5851. (*err) = "Invalid type for chunk1 data.";
  5852. }
  5853. return false;
  5854. }
  5855. // std::cout << "chunk1_length = " << chunk1_length << "\n";
  5856. bin_data_ = bytes + header_and_json_size +
  5857. 8; // 4 bytes (bin_buffer_length) + 4 bytes(bin_buffer_format)
  5858. bin_size_ = size_t(chunk1_length);
  5859. }
  5860. is_binary_ = true;
  5861. bool ret = LoadFromString(model, err, warn,
  5862. reinterpret_cast<const char *>(&bytes[20]),
  5863. chunk0_length, base_dir, check_sections);
  5864. if (!ret) {
  5865. return ret;
  5866. }
  5867. return true;
  5868. }
  5869. bool TinyGLTF::LoadBinaryFromFile(Model *model, std::string *err,
  5870. std::string *warn,
  5871. const std::string &filename,
  5872. unsigned int check_sections) {
  5873. std::stringstream ss;
  5874. if (fs.ReadWholeFile == nullptr) {
  5875. // Programmer error, assert() ?
  5876. ss << "Failed to read file: " << filename
  5877. << ": one or more FS callback not set" << std::endl;
  5878. if (err) {
  5879. (*err) = ss.str();
  5880. }
  5881. return false;
  5882. }
  5883. std::vector<unsigned char> data;
  5884. std::string fileerr;
  5885. bool fileread = fs.ReadWholeFile(&data, &fileerr, filename, fs.user_data);
  5886. if (!fileread) {
  5887. ss << "Failed to read file: " << filename << ": " << fileerr << std::endl;
  5888. if (err) {
  5889. (*err) = ss.str();
  5890. }
  5891. return false;
  5892. }
  5893. std::string basedir = GetBaseDir(filename);
  5894. bool ret = LoadBinaryFromMemory(model, err, warn, &data.at(0),
  5895. static_cast<unsigned int>(data.size()),
  5896. basedir, check_sections);
  5897. return ret;
  5898. }
  5899. ///////////////////////
  5900. // GLTF Serialization
  5901. ///////////////////////
  5902. namespace detail {
  5903. detail::json JsonFromString(const char *s) {
  5904. #ifdef TINYGLTF_USE_RAPIDJSON
  5905. return detail::json(s, detail::GetAllocator());
  5906. #else
  5907. return detail::json(s);
  5908. #endif
  5909. }
  5910. void JsonAssign(detail::json &dest, const detail::json &src) {
  5911. #ifdef TINYGLTF_USE_RAPIDJSON
  5912. dest.CopyFrom(src, detail::GetAllocator());
  5913. #else
  5914. dest = src;
  5915. #endif
  5916. }
  5917. void JsonAddMember(detail::json &o, const char *key, detail::json &&value) {
  5918. #ifdef TINYGLTF_USE_RAPIDJSON
  5919. if (!o.IsObject()) {
  5920. o.SetObject();
  5921. }
  5922. // Issue 420.
  5923. // AddMember may create duplicated key, so use [] API when a key already
  5924. // exists.
  5925. // https://github.com/Tencent/rapidjson/issues/771#issuecomment-254386863
  5926. detail::json_const_iterator it;
  5927. if (detail::FindMember(o, key, it)) {
  5928. o[key] = std::move(value); // replace
  5929. } else {
  5930. o.AddMember(detail::json(key, detail::GetAllocator()), std::move(value),
  5931. detail::GetAllocator());
  5932. }
  5933. #else
  5934. o[key] = std::move(value);
  5935. #endif
  5936. }
  5937. void JsonPushBack(detail::json &o, detail::json &&value) {
  5938. #ifdef TINYGLTF_USE_RAPIDJSON
  5939. o.PushBack(std::move(value), detail::GetAllocator());
  5940. #else
  5941. o.push_back(std::move(value));
  5942. #endif
  5943. }
  5944. bool JsonIsNull(const detail::json &o) {
  5945. #ifdef TINYGLTF_USE_RAPIDJSON
  5946. return o.IsNull();
  5947. #else
  5948. return o.is_null();
  5949. #endif
  5950. }
  5951. void JsonSetObject(detail::json &o) {
  5952. #ifdef TINYGLTF_USE_RAPIDJSON
  5953. o.SetObject();
  5954. #else
  5955. o = o.object({});
  5956. #endif
  5957. }
  5958. void JsonReserveArray(detail::json &o, size_t s) {
  5959. #ifdef TINYGLTF_USE_RAPIDJSON
  5960. o.SetArray();
  5961. o.Reserve(static_cast<rapidjson::SizeType>(s), detail::GetAllocator());
  5962. #endif
  5963. (void)(o);
  5964. (void)(s);
  5965. }
  5966. } // namespace detail
  5967. // typedef std::pair<std::string, detail::json> json_object_pair;
  5968. template <typename T>
  5969. static void SerializeNumberProperty(const std::string &key, T number,
  5970. detail::json &obj) {
  5971. // obj.insert(
  5972. // json_object_pair(key, detail::json(static_cast<double>(number))));
  5973. // obj[key] = static_cast<double>(number);
  5974. detail::JsonAddMember(obj, key.c_str(), detail::json(number));
  5975. }
  5976. #ifdef TINYGLTF_USE_RAPIDJSON
  5977. template <>
  5978. void SerializeNumberProperty(const std::string &key, size_t number,
  5979. detail::json &obj) {
  5980. detail::JsonAddMember(obj, key.c_str(),
  5981. detail::json(static_cast<uint64_t>(number)));
  5982. }
  5983. #endif
  5984. template <typename T>
  5985. static void SerializeNumberArrayProperty(const std::string &key,
  5986. const std::vector<T> &value,
  5987. detail::json &obj) {
  5988. if (value.empty()) return;
  5989. detail::json ary;
  5990. detail::JsonReserveArray(ary, value.size());
  5991. for (const auto &s : value) {
  5992. detail::JsonPushBack(ary, detail::json(s));
  5993. }
  5994. detail::JsonAddMember(obj, key.c_str(), std::move(ary));
  5995. }
  5996. static void SerializeStringProperty(const std::string &key,
  5997. const std::string &value,
  5998. detail::json &obj) {
  5999. detail::JsonAddMember(obj, key.c_str(),
  6000. detail::JsonFromString(value.c_str()));
  6001. }
  6002. static void SerializeStringArrayProperty(const std::string &key,
  6003. const std::vector<std::string> &value,
  6004. detail::json &obj) {
  6005. detail::json ary;
  6006. detail::JsonReserveArray(ary, value.size());
  6007. for (auto &s : value) {
  6008. detail::JsonPushBack(ary, detail::JsonFromString(s.c_str()));
  6009. }
  6010. detail::JsonAddMember(obj, key.c_str(), std::move(ary));
  6011. }
  6012. static bool ValueToJson(const Value &value, detail::json *ret) {
  6013. detail::json obj;
  6014. #ifdef TINYGLTF_USE_RAPIDJSON
  6015. switch (value.Type()) {
  6016. case REAL_TYPE:
  6017. obj.SetDouble(value.Get<double>());
  6018. break;
  6019. case INT_TYPE:
  6020. obj.SetInt(value.Get<int>());
  6021. break;
  6022. case BOOL_TYPE:
  6023. obj.SetBool(value.Get<bool>());
  6024. break;
  6025. case STRING_TYPE:
  6026. obj.SetString(value.Get<std::string>().c_str(), detail::GetAllocator());
  6027. break;
  6028. case ARRAY_TYPE: {
  6029. obj.SetArray();
  6030. obj.Reserve(static_cast<rapidjson::SizeType>(value.ArrayLen()),
  6031. detail::GetAllocator());
  6032. for (unsigned int i = 0; i < value.ArrayLen(); ++i) {
  6033. Value elementValue = value.Get(int(i));
  6034. detail::json elementJson;
  6035. if (ValueToJson(value.Get(int(i)), &elementJson))
  6036. obj.PushBack(std::move(elementJson), detail::GetAllocator());
  6037. }
  6038. break;
  6039. }
  6040. case BINARY_TYPE:
  6041. // TODO
  6042. // obj = detail::json(value.Get<std::vector<unsigned char>>());
  6043. return false;
  6044. break;
  6045. case OBJECT_TYPE: {
  6046. obj.SetObject();
  6047. Value::Object objMap = value.Get<Value::Object>();
  6048. for (auto &it : objMap) {
  6049. detail::json elementJson;
  6050. if (ValueToJson(it.second, &elementJson)) {
  6051. obj.AddMember(detail::json(it.first.c_str(), detail::GetAllocator()),
  6052. std::move(elementJson), detail::GetAllocator());
  6053. }
  6054. }
  6055. break;
  6056. }
  6057. case NULL_TYPE:
  6058. default:
  6059. return false;
  6060. }
  6061. #else
  6062. switch (value.Type()) {
  6063. case REAL_TYPE:
  6064. obj = detail::json(value.Get<double>());
  6065. break;
  6066. case INT_TYPE:
  6067. obj = detail::json(value.Get<int>());
  6068. break;
  6069. case BOOL_TYPE:
  6070. obj = detail::json(value.Get<bool>());
  6071. break;
  6072. case STRING_TYPE:
  6073. obj = detail::json(value.Get<std::string>());
  6074. break;
  6075. case ARRAY_TYPE: {
  6076. for (unsigned int i = 0; i < value.ArrayLen(); ++i) {
  6077. Value elementValue = value.Get(int(i));
  6078. detail::json elementJson;
  6079. if (ValueToJson(value.Get(int(i)), &elementJson))
  6080. obj.push_back(elementJson);
  6081. }
  6082. break;
  6083. }
  6084. case BINARY_TYPE:
  6085. // TODO
  6086. // obj = json(value.Get<std::vector<unsigned char>>());
  6087. return false;
  6088. break;
  6089. case OBJECT_TYPE: {
  6090. Value::Object objMap = value.Get<Value::Object>();
  6091. for (auto &it : objMap) {
  6092. detail::json elementJson;
  6093. if (ValueToJson(it.second, &elementJson)) obj[it.first] = elementJson;
  6094. }
  6095. break;
  6096. }
  6097. case NULL_TYPE:
  6098. default:
  6099. return false;
  6100. }
  6101. #endif
  6102. if (ret) *ret = std::move(obj);
  6103. return true;
  6104. }
  6105. static void SerializeValue(const std::string &key, const Value &value,
  6106. detail::json &obj) {
  6107. detail::json ret;
  6108. if (ValueToJson(value, &ret)) {
  6109. detail::JsonAddMember(obj, key.c_str(), std::move(ret));
  6110. }
  6111. }
  6112. static void SerializeGltfBufferData(const std::vector<unsigned char> &data,
  6113. detail::json &o) {
  6114. std::string header = "data:application/octet-stream;base64,";
  6115. if (data.size() > 0) {
  6116. std::string encodedData =
  6117. base64_encode(&data[0], static_cast<unsigned int>(data.size()));
  6118. SerializeStringProperty("uri", header + encodedData, o);
  6119. } else {
  6120. // Issue #229
  6121. // size 0 is allowed. Just emit mime header.
  6122. SerializeStringProperty("uri", header, o);
  6123. }
  6124. }
  6125. static bool SerializeGltfBufferData(const std::vector<unsigned char> &data,
  6126. const std::string &binFilename) {
  6127. #ifdef _WIN32
  6128. #if defined(__GLIBCXX__) // mingw
  6129. int file_descriptor = _wopen(UTF8ToWchar(binFilename).c_str(),
  6130. _O_CREAT | _O_WRONLY | _O_TRUNC | _O_BINARY);
  6131. __gnu_cxx::stdio_filebuf<char> wfile_buf(
  6132. file_descriptor, std::ios_base::out | std::ios_base::binary);
  6133. std::ostream output(&wfile_buf);
  6134. if (!wfile_buf.is_open()) return false;
  6135. #elif defined(_MSC_VER)
  6136. std::ofstream output(UTF8ToWchar(binFilename).c_str(), std::ofstream::binary);
  6137. if (!output.is_open()) return false;
  6138. #else
  6139. std::ofstream output(binFilename.c_str(), std::ofstream::binary);
  6140. if (!output.is_open()) return false;
  6141. #endif
  6142. #else
  6143. std::ofstream output(binFilename.c_str(), std::ofstream::binary);
  6144. if (!output.is_open()) return false;
  6145. #endif
  6146. if (data.size() > 0) {
  6147. output.write(reinterpret_cast<const char *>(&data[0]),
  6148. std::streamsize(data.size()));
  6149. } else {
  6150. // Issue #229
  6151. // size 0 will be still valid buffer data.
  6152. // write empty file.
  6153. }
  6154. return true;
  6155. }
  6156. #if 0 // FIXME(syoyo): not used. will be removed in the future release.
  6157. static void SerializeParameterMap(ParameterMap &param, detail::json &o) {
  6158. for (ParameterMap::iterator paramIt = param.begin(); paramIt != param.end();
  6159. ++paramIt) {
  6160. if (paramIt->second.number_array.size()) {
  6161. SerializeNumberArrayProperty<double>(paramIt->first,
  6162. paramIt->second.number_array, o);
  6163. } else if (paramIt->second.json_double_value.size()) {
  6164. detail::json json_double_value;
  6165. for (std::map<std::string, double>::iterator it =
  6166. paramIt->second.json_double_value.begin();
  6167. it != paramIt->second.json_double_value.end(); ++it) {
  6168. if (it->first == "index") {
  6169. json_double_value[it->first] = paramIt->second.TextureIndex();
  6170. } else {
  6171. json_double_value[it->first] = it->second;
  6172. }
  6173. }
  6174. o[paramIt->first] = json_double_value;
  6175. } else if (!paramIt->second.string_value.empty()) {
  6176. SerializeStringProperty(paramIt->first, paramIt->second.string_value, o);
  6177. } else if (paramIt->second.has_number_value) {
  6178. o[paramIt->first] = paramIt->second.number_value;
  6179. } else {
  6180. o[paramIt->first] = paramIt->second.bool_value;
  6181. }
  6182. }
  6183. }
  6184. #endif
  6185. static void SerializeExtensionMap(const ExtensionMap &extensions,
  6186. detail::json &o) {
  6187. if (!extensions.size()) return;
  6188. detail::json extMap;
  6189. for (ExtensionMap::const_iterator extIt = extensions.begin();
  6190. extIt != extensions.end(); ++extIt) {
  6191. // Allow an empty object for extension(#97)
  6192. detail::json ret;
  6193. bool isNull = true;
  6194. if (ValueToJson(extIt->second, &ret)) {
  6195. isNull = detail::JsonIsNull(ret);
  6196. detail::JsonAddMember(extMap, extIt->first.c_str(), std::move(ret));
  6197. }
  6198. if (isNull) {
  6199. if (!(extIt->first.empty())) { // name should not be empty, but for sure
  6200. // create empty object so that an extension name is still included in
  6201. // json.
  6202. detail::json empty;
  6203. detail::JsonSetObject(empty);
  6204. detail::JsonAddMember(extMap, extIt->first.c_str(), std::move(empty));
  6205. }
  6206. }
  6207. }
  6208. detail::JsonAddMember(o, "extensions", std::move(extMap));
  6209. }
  6210. static void SerializeExtras(const Value &extras, detail::json &o) {
  6211. if (extras.Type() != NULL_TYPE) SerializeValue("extras", extras, o);
  6212. }
  6213. template <typename GltfType>
  6214. void SerializeExtrasAndExtensions(const GltfType &obj, detail::json &o) {
  6215. SerializeExtensionMap(obj.extensions, o);
  6216. SerializeExtras(obj.extras, o);
  6217. }
  6218. static void SerializeGltfAccessor(const Accessor &accessor, detail::json &o) {
  6219. if (accessor.bufferView >= 0)
  6220. SerializeNumberProperty<int>("bufferView", accessor.bufferView, o);
  6221. if (accessor.byteOffset != 0)
  6222. SerializeNumberProperty<size_t>("byteOffset", accessor.byteOffset, o);
  6223. SerializeNumberProperty<int>("componentType", accessor.componentType, o);
  6224. SerializeNumberProperty<size_t>("count", accessor.count, o);
  6225. if ((accessor.componentType == TINYGLTF_COMPONENT_TYPE_FLOAT) ||
  6226. (accessor.componentType == TINYGLTF_COMPONENT_TYPE_DOUBLE)) {
  6227. SerializeNumberArrayProperty<double>("min", accessor.minValues, o);
  6228. SerializeNumberArrayProperty<double>("max", accessor.maxValues, o);
  6229. } else {
  6230. // Issue #301. Serialize as integer.
  6231. // Assume int value is within [-2**31-1, 2**31-1]
  6232. {
  6233. std::vector<int> values;
  6234. std::transform(accessor.minValues.begin(), accessor.minValues.end(),
  6235. std::back_inserter(values),
  6236. [](double v) { return static_cast<int>(v); });
  6237. SerializeNumberArrayProperty<int>("min", values, o);
  6238. }
  6239. {
  6240. std::vector<int> values;
  6241. std::transform(accessor.maxValues.begin(), accessor.maxValues.end(),
  6242. std::back_inserter(values),
  6243. [](double v) { return static_cast<int>(v); });
  6244. SerializeNumberArrayProperty<int>("max", values, o);
  6245. }
  6246. }
  6247. if (accessor.normalized)
  6248. SerializeValue("normalized", Value(accessor.normalized), o);
  6249. std::string type;
  6250. switch (accessor.type) {
  6251. case TINYGLTF_TYPE_SCALAR:
  6252. type = "SCALAR";
  6253. break;
  6254. case TINYGLTF_TYPE_VEC2:
  6255. type = "VEC2";
  6256. break;
  6257. case TINYGLTF_TYPE_VEC3:
  6258. type = "VEC3";
  6259. break;
  6260. case TINYGLTF_TYPE_VEC4:
  6261. type = "VEC4";
  6262. break;
  6263. case TINYGLTF_TYPE_MAT2:
  6264. type = "MAT2";
  6265. break;
  6266. case TINYGLTF_TYPE_MAT3:
  6267. type = "MAT3";
  6268. break;
  6269. case TINYGLTF_TYPE_MAT4:
  6270. type = "MAT4";
  6271. break;
  6272. }
  6273. SerializeStringProperty("type", type, o);
  6274. if (!accessor.name.empty()) SerializeStringProperty("name", accessor.name, o);
  6275. SerializeExtrasAndExtensions(accessor, o);
  6276. // sparse
  6277. if (accessor.sparse.isSparse) {
  6278. detail::json sparse;
  6279. SerializeNumberProperty<int>("count", accessor.sparse.count, sparse);
  6280. {
  6281. detail::json indices;
  6282. SerializeNumberProperty<int>("bufferView",
  6283. accessor.sparse.indices.bufferView, indices);
  6284. SerializeNumberProperty<size_t>("byteOffset",
  6285. accessor.sparse.indices.byteOffset, indices);
  6286. SerializeNumberProperty<int>(
  6287. "componentType", accessor.sparse.indices.componentType, indices);
  6288. SerializeExtrasAndExtensions(accessor.sparse.indices, indices);
  6289. detail::JsonAddMember(sparse, "indices", std::move(indices));
  6290. }
  6291. {
  6292. detail::json values;
  6293. SerializeNumberProperty<int>("bufferView",
  6294. accessor.sparse.values.bufferView, values);
  6295. SerializeNumberProperty<size_t>("byteOffset",
  6296. accessor.sparse.values.byteOffset, values);
  6297. SerializeExtrasAndExtensions(accessor.sparse.values, values);
  6298. detail::JsonAddMember(sparse, "values", std::move(values));
  6299. }
  6300. SerializeExtrasAndExtensions(accessor.sparse, sparse);
  6301. detail::JsonAddMember(o, "sparse", std::move(sparse));
  6302. }
  6303. }
  6304. static void SerializeGltfAnimationChannel(const AnimationChannel &channel,
  6305. detail::json &o) {
  6306. SerializeNumberProperty("sampler", channel.sampler, o);
  6307. {
  6308. detail::json target;
  6309. if (channel.target_node >= 0) {
  6310. SerializeNumberProperty("node", channel.target_node, target);
  6311. }
  6312. SerializeStringProperty("path", channel.target_path, target);
  6313. SerializeExtensionMap(channel.target_extensions, target);
  6314. SerializeExtras(channel.target_extras, target);
  6315. detail::JsonAddMember(o, "target", std::move(target));
  6316. }
  6317. SerializeExtrasAndExtensions(channel, o);
  6318. }
  6319. static void SerializeGltfAnimationSampler(const AnimationSampler &sampler,
  6320. detail::json &o) {
  6321. SerializeNumberProperty("input", sampler.input, o);
  6322. SerializeNumberProperty("output", sampler.output, o);
  6323. SerializeStringProperty("interpolation", sampler.interpolation, o);
  6324. SerializeExtrasAndExtensions(sampler, o);
  6325. }
  6326. static void SerializeGltfAnimation(const Animation &animation,
  6327. detail::json &o) {
  6328. if (!animation.name.empty())
  6329. SerializeStringProperty("name", animation.name, o);
  6330. {
  6331. detail::json channels;
  6332. detail::JsonReserveArray(channels, animation.channels.size());
  6333. for (unsigned int i = 0; i < animation.channels.size(); ++i) {
  6334. detail::json channel;
  6335. AnimationChannel gltfChannel = animation.channels[i];
  6336. SerializeGltfAnimationChannel(gltfChannel, channel);
  6337. detail::JsonPushBack(channels, std::move(channel));
  6338. }
  6339. detail::JsonAddMember(o, "channels", std::move(channels));
  6340. }
  6341. {
  6342. detail::json samplers;
  6343. detail::JsonReserveArray(samplers, animation.samplers.size());
  6344. for (unsigned int i = 0; i < animation.samplers.size(); ++i) {
  6345. detail::json sampler;
  6346. AnimationSampler gltfSampler = animation.samplers[i];
  6347. SerializeGltfAnimationSampler(gltfSampler, sampler);
  6348. detail::JsonPushBack(samplers, std::move(sampler));
  6349. }
  6350. detail::JsonAddMember(o, "samplers", std::move(samplers));
  6351. }
  6352. SerializeExtrasAndExtensions(animation, o);
  6353. }
  6354. static void SerializeGltfAsset(const Asset &asset, detail::json &o) {
  6355. if (!asset.generator.empty()) {
  6356. SerializeStringProperty("generator", asset.generator, o);
  6357. }
  6358. if (!asset.copyright.empty()) {
  6359. SerializeStringProperty("copyright", asset.copyright, o);
  6360. }
  6361. auto version = asset.version;
  6362. if (version.empty()) {
  6363. // Just in case
  6364. // `version` must be defined
  6365. version = "2.0";
  6366. }
  6367. // TODO(syoyo): Do we need to check if `version` is greater or equal to 2.0?
  6368. SerializeStringProperty("version", version, o);
  6369. SerializeExtrasAndExtensions(asset, o);
  6370. }
  6371. static void SerializeGltfBufferBin(const Buffer &buffer, detail::json &o,
  6372. std::vector<unsigned char> &binBuffer) {
  6373. SerializeNumberProperty("byteLength", buffer.data.size(), o);
  6374. binBuffer = buffer.data;
  6375. if (buffer.name.size()) SerializeStringProperty("name", buffer.name, o);
  6376. SerializeExtrasAndExtensions(buffer, o);
  6377. }
  6378. static void SerializeGltfBuffer(const Buffer &buffer, detail::json &o) {
  6379. SerializeNumberProperty("byteLength", buffer.data.size(), o);
  6380. SerializeGltfBufferData(buffer.data, o);
  6381. if (buffer.name.size()) SerializeStringProperty("name", buffer.name, o);
  6382. SerializeExtrasAndExtensions(buffer, o);
  6383. }
  6384. static bool SerializeGltfBuffer(const Buffer &buffer, detail::json &o,
  6385. const std::string &binFilename,
  6386. const std::string &binUri) {
  6387. if (!SerializeGltfBufferData(buffer.data, binFilename)) return false;
  6388. SerializeNumberProperty("byteLength", buffer.data.size(), o);
  6389. SerializeStringProperty("uri", binUri, o);
  6390. if (buffer.name.size()) SerializeStringProperty("name", buffer.name, o);
  6391. SerializeExtrasAndExtensions(buffer, o);
  6392. return true;
  6393. }
  6394. static void SerializeGltfBufferView(const BufferView &bufferView,
  6395. detail::json &o) {
  6396. SerializeNumberProperty("buffer", bufferView.buffer, o);
  6397. SerializeNumberProperty<size_t>("byteLength", bufferView.byteLength, o);
  6398. // byteStride is optional, minimum allowed is 4
  6399. if (bufferView.byteStride >= 4) {
  6400. SerializeNumberProperty<size_t>("byteStride", bufferView.byteStride, o);
  6401. }
  6402. // byteOffset is optional, default is 0
  6403. if (bufferView.byteOffset > 0) {
  6404. SerializeNumberProperty<size_t>("byteOffset", bufferView.byteOffset, o);
  6405. }
  6406. // Target is optional, check if it contains a valid value
  6407. if (bufferView.target == TINYGLTF_TARGET_ARRAY_BUFFER ||
  6408. bufferView.target == TINYGLTF_TARGET_ELEMENT_ARRAY_BUFFER) {
  6409. SerializeNumberProperty("target", bufferView.target, o);
  6410. }
  6411. if (bufferView.name.size()) {
  6412. SerializeStringProperty("name", bufferView.name, o);
  6413. }
  6414. SerializeExtrasAndExtensions(bufferView, o);
  6415. }
  6416. static void SerializeGltfImage(const Image &image, const std::string &uri,
  6417. detail::json &o) {
  6418. // From 2.7.0, we look for `uri` parameter, not `Image.uri`
  6419. // if uri is empty, the mimeType and bufferview should be set
  6420. if (uri.empty()) {
  6421. SerializeStringProperty("mimeType", image.mimeType, o);
  6422. SerializeNumberProperty<int>("bufferView", image.bufferView, o);
  6423. } else {
  6424. SerializeStringProperty("uri", uri, o);
  6425. }
  6426. if (image.name.size()) {
  6427. SerializeStringProperty("name", image.name, o);
  6428. }
  6429. SerializeExtrasAndExtensions(image, o);
  6430. }
  6431. static void SerializeGltfTextureInfo(const TextureInfo &texinfo,
  6432. detail::json &o) {
  6433. SerializeNumberProperty("index", texinfo.index, o);
  6434. if (texinfo.texCoord != 0) {
  6435. SerializeNumberProperty("texCoord", texinfo.texCoord, o);
  6436. }
  6437. SerializeExtrasAndExtensions(texinfo, o);
  6438. }
  6439. static void SerializeGltfNormalTextureInfo(const NormalTextureInfo &texinfo,
  6440. detail::json &o) {
  6441. SerializeNumberProperty("index", texinfo.index, o);
  6442. if (texinfo.texCoord != 0) {
  6443. SerializeNumberProperty("texCoord", texinfo.texCoord, o);
  6444. }
  6445. if (!TINYGLTF_DOUBLE_EQUAL(texinfo.scale, 1.0)) {
  6446. SerializeNumberProperty("scale", texinfo.scale, o);
  6447. }
  6448. SerializeExtrasAndExtensions(texinfo, o);
  6449. }
  6450. static void SerializeGltfOcclusionTextureInfo(
  6451. const OcclusionTextureInfo &texinfo, detail::json &o) {
  6452. SerializeNumberProperty("index", texinfo.index, o);
  6453. if (texinfo.texCoord != 0) {
  6454. SerializeNumberProperty("texCoord", texinfo.texCoord, o);
  6455. }
  6456. if (!TINYGLTF_DOUBLE_EQUAL(texinfo.strength, 1.0)) {
  6457. SerializeNumberProperty("strength", texinfo.strength, o);
  6458. }
  6459. SerializeExtrasAndExtensions(texinfo, o);
  6460. }
  6461. static void SerializeGltfPbrMetallicRoughness(const PbrMetallicRoughness &pbr,
  6462. detail::json &o) {
  6463. std::vector<double> default_baseColorFactor = {1.0, 1.0, 1.0, 1.0};
  6464. if (!Equals(pbr.baseColorFactor, default_baseColorFactor)) {
  6465. SerializeNumberArrayProperty<double>("baseColorFactor", pbr.baseColorFactor,
  6466. o);
  6467. }
  6468. if (!TINYGLTF_DOUBLE_EQUAL(pbr.metallicFactor, 1.0)) {
  6469. SerializeNumberProperty("metallicFactor", pbr.metallicFactor, o);
  6470. }
  6471. if (!TINYGLTF_DOUBLE_EQUAL(pbr.roughnessFactor, 1.0)) {
  6472. SerializeNumberProperty("roughnessFactor", pbr.roughnessFactor, o);
  6473. }
  6474. if (pbr.baseColorTexture.index > -1) {
  6475. detail::json texinfo;
  6476. SerializeGltfTextureInfo(pbr.baseColorTexture, texinfo);
  6477. detail::JsonAddMember(o, "baseColorTexture", std::move(texinfo));
  6478. }
  6479. if (pbr.metallicRoughnessTexture.index > -1) {
  6480. detail::json texinfo;
  6481. SerializeGltfTextureInfo(pbr.metallicRoughnessTexture, texinfo);
  6482. detail::JsonAddMember(o, "metallicRoughnessTexture", std::move(texinfo));
  6483. }
  6484. SerializeExtrasAndExtensions(pbr, o);
  6485. }
  6486. static void SerializeGltfMaterial(const Material &material, detail::json &o) {
  6487. if (material.name.size()) {
  6488. SerializeStringProperty("name", material.name, o);
  6489. }
  6490. // QUESTION(syoyo): Write material parameters regardless of its default value?
  6491. if (!TINYGLTF_DOUBLE_EQUAL(material.alphaCutoff, 0.5)) {
  6492. SerializeNumberProperty("alphaCutoff", material.alphaCutoff, o);
  6493. }
  6494. if (material.alphaMode.compare("OPAQUE") != 0) {
  6495. SerializeStringProperty("alphaMode", material.alphaMode, o);
  6496. }
  6497. if (material.doubleSided != false)
  6498. detail::JsonAddMember(o, "doubleSided", detail::json(material.doubleSided));
  6499. if (material.normalTexture.index > -1) {
  6500. detail::json texinfo;
  6501. SerializeGltfNormalTextureInfo(material.normalTexture, texinfo);
  6502. detail::JsonAddMember(o, "normalTexture", std::move(texinfo));
  6503. }
  6504. if (material.occlusionTexture.index > -1) {
  6505. detail::json texinfo;
  6506. SerializeGltfOcclusionTextureInfo(material.occlusionTexture, texinfo);
  6507. detail::JsonAddMember(o, "occlusionTexture", std::move(texinfo));
  6508. }
  6509. if (material.emissiveTexture.index > -1) {
  6510. detail::json texinfo;
  6511. SerializeGltfTextureInfo(material.emissiveTexture, texinfo);
  6512. detail::JsonAddMember(o, "emissiveTexture", std::move(texinfo));
  6513. }
  6514. std::vector<double> default_emissiveFactor = {0.0, 0.0, 0.0};
  6515. if (!Equals(material.emissiveFactor, default_emissiveFactor)) {
  6516. SerializeNumberArrayProperty<double>("emissiveFactor",
  6517. material.emissiveFactor, o);
  6518. }
  6519. {
  6520. detail::json pbrMetallicRoughness;
  6521. SerializeGltfPbrMetallicRoughness(material.pbrMetallicRoughness,
  6522. pbrMetallicRoughness);
  6523. // Issue 204
  6524. // Do not serialize `pbrMetallicRoughness` if pbrMetallicRoughness has all
  6525. // default values(json is null). Otherwise it will serialize to
  6526. // `pbrMetallicRoughness : null`, which cannot be read by other glTF
  6527. // importers (and validators).
  6528. //
  6529. if (!detail::JsonIsNull(pbrMetallicRoughness)) {
  6530. detail::JsonAddMember(o, "pbrMetallicRoughness",
  6531. std::move(pbrMetallicRoughness));
  6532. }
  6533. }
  6534. #if 0 // legacy way. just for the record.
  6535. if (material.values.size()) {
  6536. detail::json pbrMetallicRoughness;
  6537. SerializeParameterMap(material.values, pbrMetallicRoughness);
  6538. detail::JsonAddMember(o, "pbrMetallicRoughness", std::move(pbrMetallicRoughness));
  6539. }
  6540. SerializeParameterMap(material.additionalValues, o);
  6541. #else
  6542. #endif
  6543. SerializeExtrasAndExtensions(material, o);
  6544. }
  6545. static void SerializeGltfMesh(const Mesh &mesh, detail::json &o) {
  6546. detail::json primitives;
  6547. detail::JsonReserveArray(primitives, mesh.primitives.size());
  6548. for (unsigned int i = 0; i < mesh.primitives.size(); ++i) {
  6549. detail::json primitive;
  6550. const Primitive &gltfPrimitive = mesh.primitives[i]; // don't make a copy
  6551. {
  6552. detail::json attributes;
  6553. for (auto attrIt = gltfPrimitive.attributes.begin();
  6554. attrIt != gltfPrimitive.attributes.end(); ++attrIt) {
  6555. SerializeNumberProperty<int>(attrIt->first, attrIt->second, attributes);
  6556. }
  6557. detail::JsonAddMember(primitive, "attributes", std::move(attributes));
  6558. }
  6559. // Indices is optional
  6560. if (gltfPrimitive.indices > -1) {
  6561. SerializeNumberProperty<int>("indices", gltfPrimitive.indices, primitive);
  6562. }
  6563. // Material is optional
  6564. if (gltfPrimitive.material > -1) {
  6565. SerializeNumberProperty<int>("material", gltfPrimitive.material,
  6566. primitive);
  6567. }
  6568. SerializeNumberProperty<int>("mode", gltfPrimitive.mode, primitive);
  6569. // Morph targets
  6570. if (gltfPrimitive.targets.size()) {
  6571. detail::json targets;
  6572. detail::JsonReserveArray(targets, gltfPrimitive.targets.size());
  6573. for (unsigned int k = 0; k < gltfPrimitive.targets.size(); ++k) {
  6574. detail::json targetAttributes;
  6575. std::map<std::string, int> targetData = gltfPrimitive.targets[k];
  6576. for (std::map<std::string, int>::iterator attrIt = targetData.begin();
  6577. attrIt != targetData.end(); ++attrIt) {
  6578. SerializeNumberProperty<int>(attrIt->first, attrIt->second,
  6579. targetAttributes);
  6580. }
  6581. detail::JsonPushBack(targets, std::move(targetAttributes));
  6582. }
  6583. detail::JsonAddMember(primitive, "targets", std::move(targets));
  6584. }
  6585. SerializeExtrasAndExtensions(gltfPrimitive, primitive);
  6586. detail::JsonPushBack(primitives, std::move(primitive));
  6587. }
  6588. detail::JsonAddMember(o, "primitives", std::move(primitives));
  6589. if (mesh.weights.size()) {
  6590. SerializeNumberArrayProperty<double>("weights", mesh.weights, o);
  6591. }
  6592. if (mesh.name.size()) {
  6593. SerializeStringProperty("name", mesh.name, o);
  6594. }
  6595. SerializeExtrasAndExtensions(mesh, o);
  6596. }
  6597. static void SerializeSpotLight(const SpotLight &spot, detail::json &o) {
  6598. SerializeNumberProperty("innerConeAngle", spot.innerConeAngle, o);
  6599. SerializeNumberProperty("outerConeAngle", spot.outerConeAngle, o);
  6600. SerializeExtrasAndExtensions(spot, o);
  6601. }
  6602. static void SerializeGltfLight(const Light &light, detail::json &o) {
  6603. if (!light.name.empty()) SerializeStringProperty("name", light.name, o);
  6604. SerializeNumberProperty("intensity", light.intensity, o);
  6605. if (light.range > 0.0) {
  6606. SerializeNumberProperty("range", light.range, o);
  6607. }
  6608. SerializeNumberArrayProperty("color", light.color, o);
  6609. SerializeStringProperty("type", light.type, o);
  6610. if (light.type == "spot") {
  6611. detail::json spot;
  6612. SerializeSpotLight(light.spot, spot);
  6613. detail::JsonAddMember(o, "spot", std::move(spot));
  6614. }
  6615. SerializeExtrasAndExtensions(light, o);
  6616. }
  6617. static void SerializeGltfPositionalEmitter(const PositionalEmitter &positional,
  6618. detail::json &o) {
  6619. if (!TINYGLTF_DOUBLE_EQUAL(positional.coneInnerAngle, 6.283185307179586))
  6620. SerializeNumberProperty("coneInnerAngle", positional.coneInnerAngle, o);
  6621. if (!TINYGLTF_DOUBLE_EQUAL(positional.coneOuterAngle, 6.283185307179586))
  6622. SerializeNumberProperty("coneOuterAngle", positional.coneOuterAngle, o);
  6623. if (positional.coneOuterGain > 0.0)
  6624. SerializeNumberProperty("coneOuterGain", positional.coneOuterGain, o);
  6625. if (!TINYGLTF_DOUBLE_EQUAL(positional.maxDistance, 100.0))
  6626. SerializeNumberProperty("maxDistance", positional.maxDistance, o);
  6627. if (!TINYGLTF_DOUBLE_EQUAL(positional.refDistance, 1.0))
  6628. SerializeNumberProperty("refDistance", positional.refDistance, o);
  6629. if (!TINYGLTF_DOUBLE_EQUAL(positional.rolloffFactor, 1.0))
  6630. SerializeNumberProperty("rolloffFactor", positional.rolloffFactor, o);
  6631. SerializeExtrasAndExtensions(positional, o);
  6632. }
  6633. static void SerializeGltfAudioEmitter(const AudioEmitter &emitter,
  6634. detail::json &o) {
  6635. if (!emitter.name.empty()) SerializeStringProperty("name", emitter.name, o);
  6636. if (!TINYGLTF_DOUBLE_EQUAL(emitter.gain, 1.0))
  6637. SerializeNumberProperty("gain", emitter.gain, o);
  6638. if (emitter.loop) SerializeNumberProperty("loop", emitter.loop, o);
  6639. if (emitter.playing) SerializeNumberProperty("playing", emitter.playing, o);
  6640. if (!emitter.type.empty()) SerializeStringProperty("type", emitter.type, o);
  6641. if (!emitter.distanceModel.empty())
  6642. SerializeStringProperty("distanceModel", emitter.distanceModel, o);
  6643. if (emitter.type == "positional") {
  6644. detail::json positional;
  6645. SerializeGltfPositionalEmitter(emitter.positional, positional);
  6646. detail::JsonAddMember(o, "positional", std::move(positional));
  6647. }
  6648. SerializeNumberProperty("source", emitter.source, o);
  6649. SerializeExtrasAndExtensions(emitter, o);
  6650. }
  6651. static void SerializeGltfAudioSource(const AudioSource &source,
  6652. detail::json &o) {
  6653. std::string name;
  6654. std::string uri;
  6655. std::string mimeType; // (required if no uri) ["audio/mp3", "audio/ogg",
  6656. // "audio/wav", "audio/m4a"]
  6657. if (!source.name.empty()) SerializeStringProperty("name", source.name, o);
  6658. if (source.uri.empty()) {
  6659. SerializeStringProperty("mimeType", source.mimeType, o);
  6660. SerializeNumberProperty<int>("bufferView", source.bufferView, o);
  6661. } else {
  6662. SerializeStringProperty("uri", source.uri, o);
  6663. }
  6664. SerializeExtrasAndExtensions(source, o);
  6665. }
  6666. static void SerializeGltfNode(const Node &node, detail::json &o) {
  6667. if (node.translation.size() > 0) {
  6668. SerializeNumberArrayProperty<double>("translation", node.translation, o);
  6669. }
  6670. if (node.rotation.size() > 0) {
  6671. SerializeNumberArrayProperty<double>("rotation", node.rotation, o);
  6672. }
  6673. if (node.scale.size() > 0) {
  6674. SerializeNumberArrayProperty<double>("scale", node.scale, o);
  6675. }
  6676. if (node.matrix.size() > 0) {
  6677. SerializeNumberArrayProperty<double>("matrix", node.matrix, o);
  6678. }
  6679. if (node.mesh != -1) {
  6680. SerializeNumberProperty<int>("mesh", node.mesh, o);
  6681. }
  6682. if (node.skin != -1) {
  6683. SerializeNumberProperty<int>("skin", node.skin, o);
  6684. }
  6685. if (node.camera != -1) {
  6686. SerializeNumberProperty<int>("camera", node.camera, o);
  6687. }
  6688. if (node.weights.size() > 0) {
  6689. SerializeNumberArrayProperty<double>("weights", node.weights, o);
  6690. }
  6691. SerializeExtrasAndExtensions(node, o);
  6692. // Note(agnat): If the asset was loaded from disk, the node may already
  6693. // contain the KHR_lights_punctual extension. If it was constructed in
  6694. // memory it does not. In any case we update the JSON property using
  6695. // the value from the struct. Last, if the node does not have a light
  6696. // reference but the extension is still present, we remove it.
  6697. if (node.light != -1) {
  6698. detail::json_iterator it;
  6699. if (!detail::FindMember(o, "extensions", it)) {
  6700. detail::json extensions;
  6701. detail::JsonSetObject(extensions);
  6702. detail::JsonAddMember(o, "extensions", std::move(extensions));
  6703. detail::FindMember(o, "extensions", it);
  6704. }
  6705. auto &extensions = detail::GetValue(it);
  6706. if (!detail::FindMember(extensions, "KHR_lights_punctual", it)) {
  6707. detail::json lights_punctual;
  6708. detail::JsonSetObject(lights_punctual);
  6709. detail::JsonAddMember(extensions, "KHR_lights_punctual",
  6710. std::move(lights_punctual));
  6711. detail::FindMember(o, "KHR_lights_punctual", it);
  6712. }
  6713. SerializeNumberProperty("light", node.light, detail::GetValue(it));
  6714. } else {
  6715. // node has no light ref (any longer)... so we clean up
  6716. detail::json_iterator ext_it;
  6717. if (detail::FindMember(o, "extensions", ext_it)) {
  6718. auto &extensions = detail::GetValue(ext_it);
  6719. detail::json_iterator lp_it;
  6720. if (detail::FindMember(extensions, "KHR_lights_punctual", lp_it)) {
  6721. detail::Erase(extensions, lp_it);
  6722. }
  6723. if (detail::IsEmpty(extensions)) {
  6724. detail::Erase(o, ext_it);
  6725. }
  6726. }
  6727. }
  6728. // KHR_audio
  6729. if (node.emitter != -1) {
  6730. detail::json_iterator it;
  6731. if (!detail::FindMember(o, "extensions", it)) {
  6732. detail::json extensions;
  6733. detail::JsonSetObject(extensions);
  6734. detail::JsonAddMember(o, "extensions", std::move(extensions));
  6735. detail::FindMember(o, "extensions", it);
  6736. }
  6737. auto &extensions = detail::GetValue(it);
  6738. if (!detail::FindMember(extensions, "KHR_audio", it)) {
  6739. detail::json audio;
  6740. detail::JsonSetObject(audio);
  6741. detail::JsonAddMember(extensions, "KHR_audio", std::move(audio));
  6742. detail::FindMember(o, "KHR_audio", it);
  6743. }
  6744. SerializeNumberProperty("emitter", node.emitter, detail::GetValue(it));
  6745. } else {
  6746. detail::json_iterator ext_it;
  6747. if (detail::FindMember(o, "extensions", ext_it)) {
  6748. auto &extensions = detail::GetValue(ext_it);
  6749. detail::json_iterator lp_it;
  6750. if (detail::FindMember(extensions, "KHR_audio", lp_it)) {
  6751. detail::Erase(extensions, lp_it);
  6752. }
  6753. if (detail::IsEmpty(extensions)) {
  6754. detail::Erase(o, ext_it);
  6755. }
  6756. }
  6757. }
  6758. if (!node.name.empty()) SerializeStringProperty("name", node.name, o);
  6759. SerializeNumberArrayProperty<int>("children", node.children, o);
  6760. }
  6761. static void SerializeGltfSampler(const Sampler &sampler, detail::json &o) {
  6762. if (!sampler.name.empty()) {
  6763. SerializeStringProperty("name", sampler.name, o);
  6764. }
  6765. if (sampler.magFilter != -1) {
  6766. SerializeNumberProperty("magFilter", sampler.magFilter, o);
  6767. }
  6768. if (sampler.minFilter != -1) {
  6769. SerializeNumberProperty("minFilter", sampler.minFilter, o);
  6770. }
  6771. // SerializeNumberProperty("wrapR", sampler.wrapR, o);
  6772. SerializeNumberProperty("wrapS", sampler.wrapS, o);
  6773. SerializeNumberProperty("wrapT", sampler.wrapT, o);
  6774. SerializeExtrasAndExtensions(sampler, o);
  6775. }
  6776. static void SerializeGltfOrthographicCamera(const OrthographicCamera &camera,
  6777. detail::json &o) {
  6778. SerializeNumberProperty("zfar", camera.zfar, o);
  6779. SerializeNumberProperty("znear", camera.znear, o);
  6780. SerializeNumberProperty("xmag", camera.xmag, o);
  6781. SerializeNumberProperty("ymag", camera.ymag, o);
  6782. SerializeExtrasAndExtensions(camera, o);
  6783. }
  6784. static void SerializeGltfPerspectiveCamera(const PerspectiveCamera &camera,
  6785. detail::json &o) {
  6786. SerializeNumberProperty("zfar", camera.zfar, o);
  6787. SerializeNumberProperty("znear", camera.znear, o);
  6788. if (camera.aspectRatio > 0) {
  6789. SerializeNumberProperty("aspectRatio", camera.aspectRatio, o);
  6790. }
  6791. if (camera.yfov > 0) {
  6792. SerializeNumberProperty("yfov", camera.yfov, o);
  6793. }
  6794. SerializeExtrasAndExtensions(camera, o);
  6795. }
  6796. static void SerializeGltfCamera(const Camera &camera, detail::json &o) {
  6797. SerializeStringProperty("type", camera.type, o);
  6798. if (!camera.name.empty()) {
  6799. SerializeStringProperty("name", camera.name, o);
  6800. }
  6801. if (camera.type.compare("orthographic") == 0) {
  6802. detail::json orthographic;
  6803. SerializeGltfOrthographicCamera(camera.orthographic, orthographic);
  6804. detail::JsonAddMember(o, "orthographic", std::move(orthographic));
  6805. } else if (camera.type.compare("perspective") == 0) {
  6806. detail::json perspective;
  6807. SerializeGltfPerspectiveCamera(camera.perspective, perspective);
  6808. detail::JsonAddMember(o, "perspective", std::move(perspective));
  6809. } else {
  6810. // ???
  6811. }
  6812. SerializeExtrasAndExtensions(camera, o);
  6813. }
  6814. static void SerializeGltfScene(const Scene &scene, detail::json &o) {
  6815. SerializeNumberArrayProperty<int>("nodes", scene.nodes, o);
  6816. if (scene.name.size()) {
  6817. SerializeStringProperty("name", scene.name, o);
  6818. }
  6819. SerializeExtrasAndExtensions(scene, o);
  6820. // KHR_audio
  6821. if (!scene.audioEmitters.empty()) {
  6822. detail::json_iterator it;
  6823. if (!detail::FindMember(o, "extensions", it)) {
  6824. detail::json extensions;
  6825. detail::JsonSetObject(extensions);
  6826. detail::JsonAddMember(o, "extensions", std::move(extensions));
  6827. detail::FindMember(o, "extensions", it);
  6828. }
  6829. auto &extensions = detail::GetValue(it);
  6830. if (!detail::FindMember(extensions, "KHR_audio", it)) {
  6831. detail::json audio;
  6832. detail::JsonSetObject(audio);
  6833. detail::JsonAddMember(extensions, "KHR_audio", std::move(audio));
  6834. detail::FindMember(o, "KHR_audio", it);
  6835. }
  6836. SerializeNumberArrayProperty("emitters", scene.audioEmitters,
  6837. detail::GetValue(it));
  6838. } else {
  6839. detail::json_iterator ext_it;
  6840. if (detail::FindMember(o, "extensions", ext_it)) {
  6841. auto &extensions = detail::GetValue(ext_it);
  6842. detail::json_iterator lp_it;
  6843. if (detail::FindMember(extensions, "KHR_audio", lp_it)) {
  6844. detail::Erase(extensions, lp_it);
  6845. }
  6846. if (detail::IsEmpty(extensions)) {
  6847. detail::Erase(o, ext_it);
  6848. }
  6849. }
  6850. }
  6851. }
  6852. static void SerializeGltfSkin(const Skin &skin, detail::json &o) {
  6853. // required
  6854. SerializeNumberArrayProperty<int>("joints", skin.joints, o);
  6855. if (skin.inverseBindMatrices >= 0) {
  6856. SerializeNumberProperty("inverseBindMatrices", skin.inverseBindMatrices, o);
  6857. }
  6858. if (skin.skeleton >= 0) {
  6859. SerializeNumberProperty("skeleton", skin.skeleton, o);
  6860. }
  6861. if (skin.name.size()) {
  6862. SerializeStringProperty("name", skin.name, o);
  6863. }
  6864. SerializeExtrasAndExtensions(skin, o);
  6865. }
  6866. static void SerializeGltfTexture(const Texture &texture, detail::json &o) {
  6867. if (texture.sampler > -1) {
  6868. SerializeNumberProperty("sampler", texture.sampler, o);
  6869. }
  6870. if (texture.source > -1) {
  6871. SerializeNumberProperty("source", texture.source, o);
  6872. }
  6873. if (texture.name.size()) {
  6874. SerializeStringProperty("name", texture.name, o);
  6875. }
  6876. SerializeExtrasAndExtensions(texture, o);
  6877. }
  6878. ///
  6879. /// Serialize all properties except buffers and images.
  6880. ///
  6881. static void SerializeGltfModel(const Model *model, detail::json &o) {
  6882. // ACCESSORS
  6883. if (model->accessors.size()) {
  6884. detail::json accessors;
  6885. detail::JsonReserveArray(accessors, model->accessors.size());
  6886. for (unsigned int i = 0; i < model->accessors.size(); ++i) {
  6887. detail::json accessor;
  6888. SerializeGltfAccessor(model->accessors[i], accessor);
  6889. detail::JsonPushBack(accessors, std::move(accessor));
  6890. }
  6891. detail::JsonAddMember(o, "accessors", std::move(accessors));
  6892. }
  6893. // ANIMATIONS
  6894. if (model->animations.size()) {
  6895. detail::json animations;
  6896. detail::JsonReserveArray(animations, model->animations.size());
  6897. for (unsigned int i = 0; i < model->animations.size(); ++i) {
  6898. if (model->animations[i].channels.size()) {
  6899. detail::json animation;
  6900. SerializeGltfAnimation(model->animations[i], animation);
  6901. detail::JsonPushBack(animations, std::move(animation));
  6902. }
  6903. }
  6904. detail::JsonAddMember(o, "animations", std::move(animations));
  6905. }
  6906. // ASSET
  6907. detail::json asset;
  6908. SerializeGltfAsset(model->asset, asset);
  6909. detail::JsonAddMember(o, "asset", std::move(asset));
  6910. // BUFFERVIEWS
  6911. if (model->bufferViews.size()) {
  6912. detail::json bufferViews;
  6913. detail::JsonReserveArray(bufferViews, model->bufferViews.size());
  6914. for (unsigned int i = 0; i < model->bufferViews.size(); ++i) {
  6915. detail::json bufferView;
  6916. SerializeGltfBufferView(model->bufferViews[i], bufferView);
  6917. detail::JsonPushBack(bufferViews, std::move(bufferView));
  6918. }
  6919. detail::JsonAddMember(o, "bufferViews", std::move(bufferViews));
  6920. }
  6921. // Extensions required
  6922. if (model->extensionsRequired.size()) {
  6923. SerializeStringArrayProperty("extensionsRequired",
  6924. model->extensionsRequired, o);
  6925. }
  6926. // MATERIALS
  6927. if (model->materials.size()) {
  6928. detail::json materials;
  6929. detail::JsonReserveArray(materials, model->materials.size());
  6930. for (unsigned int i = 0; i < model->materials.size(); ++i) {
  6931. detail::json material;
  6932. SerializeGltfMaterial(model->materials[i], material);
  6933. if (detail::JsonIsNull(material)) {
  6934. // Issue 294.
  6935. // `material` does not have any required parameters
  6936. // so the result may be null(unmodified) when all material parameters
  6937. // have default value.
  6938. //
  6939. // null is not allowed thus we create an empty JSON object.
  6940. detail::JsonSetObject(material);
  6941. }
  6942. detail::JsonPushBack(materials, std::move(material));
  6943. }
  6944. detail::JsonAddMember(o, "materials", std::move(materials));
  6945. }
  6946. // MESHES
  6947. if (model->meshes.size()) {
  6948. detail::json meshes;
  6949. detail::JsonReserveArray(meshes, model->meshes.size());
  6950. for (unsigned int i = 0; i < model->meshes.size(); ++i) {
  6951. detail::json mesh;
  6952. SerializeGltfMesh(model->meshes[i], mesh);
  6953. detail::JsonPushBack(meshes, std::move(mesh));
  6954. }
  6955. detail::JsonAddMember(o, "meshes", std::move(meshes));
  6956. }
  6957. // NODES
  6958. if (model->nodes.size()) {
  6959. detail::json nodes;
  6960. detail::JsonReserveArray(nodes, model->nodes.size());
  6961. for (unsigned int i = 0; i < model->nodes.size(); ++i) {
  6962. detail::json node;
  6963. SerializeGltfNode(model->nodes[i], node);
  6964. detail::JsonPushBack(nodes, std::move(node));
  6965. }
  6966. detail::JsonAddMember(o, "nodes", std::move(nodes));
  6967. }
  6968. // SCENE
  6969. if (model->defaultScene > -1) {
  6970. SerializeNumberProperty<int>("scene", model->defaultScene, o);
  6971. }
  6972. // SCENES
  6973. if (model->scenes.size()) {
  6974. detail::json scenes;
  6975. detail::JsonReserveArray(scenes, model->scenes.size());
  6976. for (unsigned int i = 0; i < model->scenes.size(); ++i) {
  6977. detail::json currentScene;
  6978. SerializeGltfScene(model->scenes[i], currentScene);
  6979. detail::JsonPushBack(scenes, std::move(currentScene));
  6980. }
  6981. detail::JsonAddMember(o, "scenes", std::move(scenes));
  6982. }
  6983. // SKINS
  6984. if (model->skins.size()) {
  6985. detail::json skins;
  6986. detail::JsonReserveArray(skins, model->skins.size());
  6987. for (unsigned int i = 0; i < model->skins.size(); ++i) {
  6988. detail::json skin;
  6989. SerializeGltfSkin(model->skins[i], skin);
  6990. detail::JsonPushBack(skins, std::move(skin));
  6991. }
  6992. detail::JsonAddMember(o, "skins", std::move(skins));
  6993. }
  6994. // TEXTURES
  6995. if (model->textures.size()) {
  6996. detail::json textures;
  6997. detail::JsonReserveArray(textures, model->textures.size());
  6998. for (unsigned int i = 0; i < model->textures.size(); ++i) {
  6999. detail::json texture;
  7000. SerializeGltfTexture(model->textures[i], texture);
  7001. detail::JsonPushBack(textures, std::move(texture));
  7002. }
  7003. detail::JsonAddMember(o, "textures", std::move(textures));
  7004. }
  7005. // SAMPLERS
  7006. if (model->samplers.size()) {
  7007. detail::json samplers;
  7008. detail::JsonReserveArray(samplers, model->samplers.size());
  7009. for (unsigned int i = 0; i < model->samplers.size(); ++i) {
  7010. detail::json sampler;
  7011. SerializeGltfSampler(model->samplers[i], sampler);
  7012. detail::JsonPushBack(samplers, std::move(sampler));
  7013. }
  7014. detail::JsonAddMember(o, "samplers", std::move(samplers));
  7015. }
  7016. // CAMERAS
  7017. if (model->cameras.size()) {
  7018. detail::json cameras;
  7019. detail::JsonReserveArray(cameras, model->cameras.size());
  7020. for (unsigned int i = 0; i < model->cameras.size(); ++i) {
  7021. detail::json camera;
  7022. SerializeGltfCamera(model->cameras[i], camera);
  7023. detail::JsonPushBack(cameras, std::move(camera));
  7024. }
  7025. detail::JsonAddMember(o, "cameras", std::move(cameras));
  7026. }
  7027. // EXTRAS & EXTENSIONS
  7028. SerializeExtrasAndExtensions(*model, o);
  7029. auto extensionsUsed = model->extensionsUsed;
  7030. // LIGHTS as KHR_lights_punctual
  7031. if (model->lights.size()) {
  7032. detail::json lights;
  7033. detail::JsonReserveArray(lights, model->lights.size());
  7034. for (unsigned int i = 0; i < model->lights.size(); ++i) {
  7035. detail::json light;
  7036. SerializeGltfLight(model->lights[i], light);
  7037. detail::JsonPushBack(lights, std::move(light));
  7038. }
  7039. detail::json khr_lights_cmn;
  7040. detail::JsonAddMember(khr_lights_cmn, "lights", std::move(lights));
  7041. detail::json ext_j;
  7042. {
  7043. detail::json_const_iterator it;
  7044. if (detail::FindMember(o, "extensions", it)) {
  7045. detail::JsonAssign(ext_j, detail::GetValue(it));
  7046. }
  7047. }
  7048. detail::JsonAddMember(ext_j, "KHR_lights_punctual",
  7049. std::move(khr_lights_cmn));
  7050. detail::JsonAddMember(o, "extensions", std::move(ext_j));
  7051. // Also add "KHR_lights_punctual" to `extensionsUsed`
  7052. {
  7053. auto has_khr_lights_punctual =
  7054. std::find_if(extensionsUsed.begin(), extensionsUsed.end(),
  7055. [](const std::string &s) {
  7056. return (s.compare("KHR_lights_punctual") == 0);
  7057. });
  7058. if (has_khr_lights_punctual == extensionsUsed.end()) {
  7059. extensionsUsed.push_back("KHR_lights_punctual");
  7060. }
  7061. }
  7062. }
  7063. // KHR_audio
  7064. if (!model->audioEmitters.empty() || !model->audioSources.empty()) {
  7065. detail::json emitters;
  7066. detail::JsonReserveArray(emitters, model->audioEmitters.size());
  7067. for (unsigned int i = 0; i < model->audioEmitters.size(); ++i) {
  7068. detail::json emitter;
  7069. SerializeGltfAudioEmitter(model->audioEmitters[i], emitter);
  7070. detail::JsonPushBack(emitters, std::move(emitter));
  7071. }
  7072. detail::json khr_audio_cmn;
  7073. detail::JsonAddMember(khr_audio_cmn, "emitters", std::move(emitters));
  7074. detail::json sources;
  7075. detail::JsonReserveArray(sources, model->audioSources.size());
  7076. for (unsigned int i = 0; i < model->audioSources.size(); ++i) {
  7077. detail::json source;
  7078. SerializeGltfAudioSource(model->audioSources[i], source);
  7079. detail::JsonPushBack(sources, std::move(source));
  7080. }
  7081. detail::JsonAddMember(khr_audio_cmn, "sources", std::move(sources));
  7082. detail::json ext_j;
  7083. {
  7084. detail::json_const_iterator it;
  7085. if (detail::FindMember(o, "extensions", it)) {
  7086. detail::JsonAssign(ext_j, detail::GetValue(it));
  7087. }
  7088. }
  7089. detail::JsonAddMember(ext_j, "KHR_audio", std::move(khr_audio_cmn));
  7090. detail::JsonAddMember(o, "extensions", std::move(ext_j));
  7091. // Also add "KHR_audio" to `extensionsUsed`
  7092. {
  7093. auto has_khr_audio = std::find_if(
  7094. extensionsUsed.begin(), extensionsUsed.end(),
  7095. [](const std::string &s) { return (s.compare("KHR_audio") == 0); });
  7096. if (has_khr_audio == extensionsUsed.end()) {
  7097. extensionsUsed.push_back("KHR_audio");
  7098. }
  7099. }
  7100. }
  7101. // Extensions used
  7102. if (extensionsUsed.size()) {
  7103. SerializeStringArrayProperty("extensionsUsed", extensionsUsed, o);
  7104. }
  7105. }
  7106. static bool WriteGltfStream(std::ostream &stream, const std::string &content) {
  7107. stream << content << std::endl;
  7108. return stream.good();
  7109. }
  7110. static bool WriteGltfFile(const std::string &output,
  7111. const std::string &content) {
  7112. #ifdef _WIN32
  7113. #if defined(_MSC_VER)
  7114. std::ofstream gltfFile(UTF8ToWchar(output).c_str());
  7115. #elif defined(__GLIBCXX__)
  7116. int file_descriptor = _wopen(UTF8ToWchar(output).c_str(),
  7117. _O_CREAT | _O_WRONLY | _O_TRUNC | _O_BINARY);
  7118. __gnu_cxx::stdio_filebuf<char> wfile_buf(
  7119. file_descriptor, std::ios_base::out | std::ios_base::binary);
  7120. std::ostream gltfFile(&wfile_buf);
  7121. if (!wfile_buf.is_open()) return false;
  7122. #else
  7123. std::ofstream gltfFile(output.c_str());
  7124. if (!gltfFile.is_open()) return false;
  7125. #endif
  7126. #else
  7127. std::ofstream gltfFile(output.c_str());
  7128. if (!gltfFile.is_open()) return false;
  7129. #endif
  7130. return WriteGltfStream(gltfFile, content);
  7131. }
  7132. static bool WriteBinaryGltfStream(std::ostream &stream,
  7133. const std::string &content,
  7134. const std::vector<unsigned char> &binBuffer) {
  7135. const std::string header = "glTF";
  7136. const int version = 2;
  7137. const uint32_t content_size = uint32_t(content.size());
  7138. const uint32_t binBuffer_size = uint32_t(binBuffer.size());
  7139. // determine number of padding bytes required to ensure 4 byte alignment
  7140. const uint32_t content_padding_size =
  7141. content_size % 4 == 0 ? 0 : 4 - content_size % 4;
  7142. const uint32_t bin_padding_size =
  7143. binBuffer_size % 4 == 0 ? 0 : 4 - binBuffer_size % 4;
  7144. // 12 bytes for header, JSON content length, 8 bytes for JSON chunk info.
  7145. // Chunk data must be located at 4-byte boundary, which may require padding
  7146. const uint32_t length =
  7147. 12 + 8 + content_size + content_padding_size +
  7148. (binBuffer_size ? (8 + binBuffer_size + bin_padding_size) : 0);
  7149. stream.write(header.c_str(), std::streamsize(header.size()));
  7150. stream.write(reinterpret_cast<const char *>(&version), sizeof(version));
  7151. stream.write(reinterpret_cast<const char *>(&length), sizeof(length));
  7152. // JSON chunk info, then JSON data
  7153. const uint32_t model_length = uint32_t(content.size()) + content_padding_size;
  7154. const uint32_t model_format = 0x4E4F534A;
  7155. stream.write(reinterpret_cast<const char *>(&model_length),
  7156. sizeof(model_length));
  7157. stream.write(reinterpret_cast<const char *>(&model_format),
  7158. sizeof(model_format));
  7159. stream.write(content.c_str(), std::streamsize(content.size()));
  7160. // Chunk must be multiplies of 4, so pad with spaces
  7161. if (content_padding_size > 0) {
  7162. const std::string padding = std::string(size_t(content_padding_size), ' ');
  7163. stream.write(padding.c_str(), std::streamsize(padding.size()));
  7164. }
  7165. if (binBuffer.size() > 0) {
  7166. // BIN chunk info, then BIN data
  7167. const uint32_t bin_length = uint32_t(binBuffer.size()) + bin_padding_size;
  7168. const uint32_t bin_format = 0x004e4942;
  7169. stream.write(reinterpret_cast<const char *>(&bin_length),
  7170. sizeof(bin_length));
  7171. stream.write(reinterpret_cast<const char *>(&bin_format),
  7172. sizeof(bin_format));
  7173. stream.write(reinterpret_cast<const char *>(binBuffer.data()),
  7174. std::streamsize(binBuffer.size()));
  7175. // Chunksize must be multiplies of 4, so pad with zeroes
  7176. if (bin_padding_size > 0) {
  7177. const std::vector<unsigned char> padding =
  7178. std::vector<unsigned char>(size_t(bin_padding_size), 0);
  7179. stream.write(reinterpret_cast<const char *>(padding.data()),
  7180. std::streamsize(padding.size()));
  7181. }
  7182. }
  7183. stream.flush();
  7184. return stream.good();
  7185. }
  7186. static bool WriteBinaryGltfFile(const std::string &output,
  7187. const std::string &content,
  7188. const std::vector<unsigned char> &binBuffer) {
  7189. #ifdef _WIN32
  7190. #if defined(_MSC_VER)
  7191. std::ofstream gltfFile(UTF8ToWchar(output).c_str(), std::ios::binary);
  7192. #elif defined(__GLIBCXX__)
  7193. int file_descriptor = _wopen(UTF8ToWchar(output).c_str(),
  7194. _O_CREAT | _O_WRONLY | _O_TRUNC | _O_BINARY);
  7195. __gnu_cxx::stdio_filebuf<char> wfile_buf(
  7196. file_descriptor, std::ios_base::out | std::ios_base::binary);
  7197. std::ostream gltfFile(&wfile_buf);
  7198. #else
  7199. std::ofstream gltfFile(output.c_str(), std::ios::binary);
  7200. #endif
  7201. #else
  7202. std::ofstream gltfFile(output.c_str(), std::ios::binary);
  7203. #endif
  7204. return WriteBinaryGltfStream(gltfFile, content, binBuffer);
  7205. }
  7206. bool TinyGLTF::WriteGltfSceneToStream(const Model *model, std::ostream &stream,
  7207. bool prettyPrint = true,
  7208. bool writeBinary = false) {
  7209. detail::JsonDocument output;
  7210. /// Serialize all properties except buffers and images.
  7211. SerializeGltfModel(model, output);
  7212. // BUFFERS
  7213. std::vector<unsigned char> binBuffer;
  7214. if (model->buffers.size()) {
  7215. detail::json buffers;
  7216. detail::JsonReserveArray(buffers, model->buffers.size());
  7217. for (unsigned int i = 0; i < model->buffers.size(); ++i) {
  7218. detail::json buffer;
  7219. if (writeBinary && i == 0 && model->buffers[i].uri.empty()) {
  7220. SerializeGltfBufferBin(model->buffers[i], buffer, binBuffer);
  7221. } else {
  7222. SerializeGltfBuffer(model->buffers[i], buffer);
  7223. }
  7224. detail::JsonPushBack(buffers, std::move(buffer));
  7225. }
  7226. detail::JsonAddMember(output, "buffers", std::move(buffers));
  7227. }
  7228. // IMAGES
  7229. if (model->images.size()) {
  7230. detail::json images;
  7231. detail::JsonReserveArray(images, model->images.size());
  7232. for (unsigned int i = 0; i < model->images.size(); ++i) {
  7233. detail::json image;
  7234. std::string dummystring;
  7235. // UpdateImageObject need baseDir but only uses it if embeddedImages is
  7236. // enabled, since we won't write separate images when writing to a stream
  7237. // we
  7238. std::string uri;
  7239. if (!UpdateImageObject(model->images[i], dummystring, int(i), true,
  7240. &uri_cb, &this->WriteImageData,
  7241. this->write_image_user_data_, &uri)) {
  7242. return false;
  7243. }
  7244. SerializeGltfImage(model->images[i], uri, image);
  7245. detail::JsonPushBack(images, std::move(image));
  7246. }
  7247. detail::JsonAddMember(output, "images", std::move(images));
  7248. }
  7249. if (writeBinary) {
  7250. return WriteBinaryGltfStream(stream, detail::JsonToString(output),
  7251. binBuffer);
  7252. } else {
  7253. return WriteGltfStream(stream,
  7254. detail::JsonToString(output, prettyPrint ? 2 : -1));
  7255. }
  7256. }
  7257. bool TinyGLTF::WriteGltfSceneToFile(const Model *model,
  7258. const std::string &filename,
  7259. bool embedImages = false,
  7260. bool embedBuffers = false,
  7261. bool prettyPrint = true,
  7262. bool writeBinary = false) {
  7263. detail::JsonDocument output;
  7264. std::string defaultBinFilename = GetBaseFilename(filename);
  7265. std::string defaultBinFileExt = ".bin";
  7266. std::string::size_type pos =
  7267. defaultBinFilename.rfind('.', defaultBinFilename.length());
  7268. if (pos != std::string::npos) {
  7269. defaultBinFilename = defaultBinFilename.substr(0, pos);
  7270. }
  7271. std::string baseDir = GetBaseDir(filename);
  7272. if (baseDir.empty()) {
  7273. baseDir = "./";
  7274. }
  7275. /// Serialize all properties except buffers and images.
  7276. SerializeGltfModel(model, output);
  7277. // BUFFERS
  7278. std::vector<std::string> usedFilenames;
  7279. std::vector<unsigned char> binBuffer;
  7280. if (model->buffers.size()) {
  7281. detail::json buffers;
  7282. detail::JsonReserveArray(buffers, model->buffers.size());
  7283. for (unsigned int i = 0; i < model->buffers.size(); ++i) {
  7284. detail::json buffer;
  7285. if (writeBinary && i == 0 && model->buffers[i].uri.empty()) {
  7286. SerializeGltfBufferBin(model->buffers[i], buffer, binBuffer);
  7287. } else if (embedBuffers) {
  7288. SerializeGltfBuffer(model->buffers[i], buffer);
  7289. } else {
  7290. std::string binSavePath;
  7291. std::string binFilename;
  7292. std::string binUri;
  7293. if (!model->buffers[i].uri.empty() &&
  7294. !IsDataURI(model->buffers[i].uri)) {
  7295. binUri = model->buffers[i].uri;
  7296. if (!uri_cb.decode(binUri, &binFilename, uri_cb.user_data)) {
  7297. return false;
  7298. }
  7299. } else {
  7300. binFilename = defaultBinFilename + defaultBinFileExt;
  7301. bool inUse = true;
  7302. int numUsed = 0;
  7303. while (inUse) {
  7304. inUse = false;
  7305. for (const std::string &usedName : usedFilenames) {
  7306. if (binFilename.compare(usedName) != 0) continue;
  7307. inUse = true;
  7308. binFilename = defaultBinFilename + std::to_string(numUsed++) +
  7309. defaultBinFileExt;
  7310. break;
  7311. }
  7312. }
  7313. if (uri_cb.encode) {
  7314. if (!uri_cb.encode(binFilename, "buffer", &binUri,
  7315. uri_cb.user_data)) {
  7316. return false;
  7317. }
  7318. } else {
  7319. binUri = binFilename;
  7320. }
  7321. }
  7322. usedFilenames.push_back(binFilename);
  7323. binSavePath = JoinPath(baseDir, binFilename);
  7324. if (!SerializeGltfBuffer(model->buffers[i], buffer, binSavePath,
  7325. binUri)) {
  7326. return false;
  7327. }
  7328. }
  7329. detail::JsonPushBack(buffers, std::move(buffer));
  7330. }
  7331. detail::JsonAddMember(output, "buffers", std::move(buffers));
  7332. }
  7333. // IMAGES
  7334. if (model->images.size()) {
  7335. detail::json images;
  7336. detail::JsonReserveArray(images, model->images.size());
  7337. for (unsigned int i = 0; i < model->images.size(); ++i) {
  7338. detail::json image;
  7339. std::string uri;
  7340. if (!UpdateImageObject(model->images[i], baseDir, int(i), embedImages,
  7341. &uri_cb, &this->WriteImageData,
  7342. this->write_image_user_data_, &uri)) {
  7343. return false;
  7344. }
  7345. SerializeGltfImage(model->images[i], uri, image);
  7346. detail::JsonPushBack(images, std::move(image));
  7347. }
  7348. detail::JsonAddMember(output, "images", std::move(images));
  7349. }
  7350. if (writeBinary) {
  7351. return WriteBinaryGltfFile(filename, detail::JsonToString(output),
  7352. binBuffer);
  7353. } else {
  7354. return WriteGltfFile(filename,
  7355. detail::JsonToString(output, (prettyPrint ? 2 : -1)));
  7356. }
  7357. }
  7358. } // namespace tinygltf
  7359. #ifdef __clang__
  7360. #pragma clang diagnostic pop
  7361. #endif
  7362. #endif // TINYGLTF_IMPLEMENTATION