index.es.js 217 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984
  1. var __pow = Math.pow;
  2. var __async = (__this, __arguments, generator) => {
  3. return new Promise((resolve, reject) => {
  4. var fulfilled = (value) => {
  5. try {
  6. step(generator.next(value));
  7. } catch (e) {
  8. reject(e);
  9. }
  10. };
  11. var rejected = (value) => {
  12. try {
  13. step(generator.throw(value));
  14. } catch (e) {
  15. reject(e);
  16. }
  17. };
  18. var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
  19. step((generator = generator.apply(__this, __arguments)).next());
  20. });
  21. };
  22. import { EventEmitter, url } from "@pixi/utils";
  23. import { Matrix, Transform, Point, ObservablePoint } from "@pixi/math";
  24. import { Texture } from "@pixi/core";
  25. import { Container } from "@pixi/display";
  26. const LOGICAL_WIDTH = 2;
  27. const LOGICAL_HEIGHT = 2;
  28. var CubismConfig;
  29. ((CubismConfig2) => {
  30. CubismConfig2.supportMoreMaskDivisions = true;
  31. CubismConfig2.setOpacityFromMotion = false;
  32. })(CubismConfig || (CubismConfig = {}));
  33. var config;
  34. ((config2) => {
  35. config2.LOG_LEVEL_VERBOSE = 0;
  36. config2.LOG_LEVEL_WARNING = 1;
  37. config2.LOG_LEVEL_ERROR = 2;
  38. config2.LOG_LEVEL_NONE = 999;
  39. config2.logLevel = config2.LOG_LEVEL_WARNING;
  40. config2.sound = true;
  41. config2.motionSync = true;
  42. config2.motionFadingDuration = 500;
  43. config2.idleMotionFadingDuration = 2e3;
  44. config2.expressionFadingDuration = 500;
  45. config2.preserveExpressionOnMotion = true;
  46. config2.cubism4 = CubismConfig;
  47. })(config || (config = {}));
  48. const VERSION = "0.4.0";
  49. const logger = {
  50. log(tag, ...messages) {
  51. if (config.logLevel <= config.LOG_LEVEL_VERBOSE) {
  52. console.log(`[${tag}]`, ...messages);
  53. }
  54. },
  55. warn(tag, ...messages) {
  56. if (config.logLevel <= config.LOG_LEVEL_WARNING) {
  57. console.warn(`[${tag}]`, ...messages);
  58. }
  59. },
  60. error(tag, ...messages) {
  61. if (config.logLevel <= config.LOG_LEVEL_ERROR) {
  62. console.error(`[${tag}]`, ...messages);
  63. }
  64. }
  65. };
  66. function clamp(num, lower, upper) {
  67. return num < lower ? lower : num > upper ? upper : num;
  68. }
  69. function rand(min, max) {
  70. return Math.random() * (max - min) + min;
  71. }
  72. function copyProperty(type, from, to, fromKey, toKey) {
  73. const value = from[fromKey];
  74. if (value !== null && typeof value === type) {
  75. to[toKey] = value;
  76. }
  77. }
  78. function copyArray(type, from, to, fromKey, toKey) {
  79. const array = from[fromKey];
  80. if (Array.isArray(array)) {
  81. to[toKey] = array.filter((item) => item !== null && typeof item === type);
  82. }
  83. }
  84. function applyMixins(derivedCtor, baseCtors) {
  85. baseCtors.forEach((baseCtor) => {
  86. Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
  87. if (name !== "constructor") {
  88. Object.defineProperty(derivedCtor.prototype, name, Object.getOwnPropertyDescriptor(baseCtor.prototype, name));
  89. }
  90. });
  91. });
  92. }
  93. function folderName(url2) {
  94. let lastSlashIndex = url2.lastIndexOf("/");
  95. if (lastSlashIndex != -1) {
  96. url2 = url2.slice(0, lastSlashIndex);
  97. }
  98. lastSlashIndex = url2.lastIndexOf("/");
  99. if (lastSlashIndex !== -1) {
  100. url2 = url2.slice(lastSlashIndex + 1);
  101. }
  102. return url2;
  103. }
  104. function remove(array, item) {
  105. const index = array.indexOf(item);
  106. if (index !== -1) {
  107. array.splice(index, 1);
  108. }
  109. }
  110. class ExpressionManager extends EventEmitter {
  111. constructor(settings, options) {
  112. super();
  113. this.expressions = [];
  114. this.reserveExpressionIndex = -1;
  115. this.destroyed = false;
  116. this.settings = settings;
  117. this.tag = `ExpressionManager(${settings.name})`;
  118. }
  119. init() {
  120. this.defaultExpression = this.createExpression({}, void 0);
  121. this.currentExpression = this.defaultExpression;
  122. this.stopAllExpressions();
  123. }
  124. loadExpression(index) {
  125. return __async(this, null, function* () {
  126. if (!this.definitions[index]) {
  127. logger.warn(this.tag, `Undefined expression at [${index}]`);
  128. return void 0;
  129. }
  130. if (this.expressions[index] === null) {
  131. logger.warn(this.tag, `Cannot set expression at [${index}] because it's already failed in loading.`);
  132. return void 0;
  133. }
  134. if (this.expressions[index]) {
  135. return this.expressions[index];
  136. }
  137. const expression = yield this._loadExpression(index);
  138. this.expressions[index] = expression;
  139. return expression;
  140. });
  141. }
  142. _loadExpression(index) {
  143. throw new Error("Not implemented.");
  144. }
  145. setRandomExpression() {
  146. return __async(this, null, function* () {
  147. if (this.definitions.length) {
  148. const availableIndices = [];
  149. for (let i = 0; i < this.definitions.length; i++) {
  150. if (this.expressions[i] !== null && this.expressions[i] !== this.currentExpression && i !== this.reserveExpressionIndex) {
  151. availableIndices.push(i);
  152. }
  153. }
  154. if (availableIndices.length) {
  155. const index = Math.floor(Math.random() * availableIndices.length);
  156. return this.setExpression(index);
  157. }
  158. }
  159. return false;
  160. });
  161. }
  162. resetExpression() {
  163. this._setExpression(this.defaultExpression);
  164. }
  165. restoreExpression() {
  166. this._setExpression(this.currentExpression);
  167. }
  168. setExpression(index) {
  169. return __async(this, null, function* () {
  170. if (typeof index !== "number") {
  171. index = this.getExpressionIndex(index);
  172. }
  173. if (!(index > -1 && index < this.definitions.length)) {
  174. return false;
  175. }
  176. if (index === this.expressions.indexOf(this.currentExpression)) {
  177. return false;
  178. }
  179. this.reserveExpressionIndex = index;
  180. const expression = yield this.loadExpression(index);
  181. if (!expression || this.reserveExpressionIndex !== index) {
  182. return false;
  183. }
  184. this.reserveExpressionIndex = -1;
  185. this.currentExpression = expression;
  186. this._setExpression(expression);
  187. return true;
  188. });
  189. }
  190. update(model, now) {
  191. if (!this.isFinished()) {
  192. return this.updateParameters(model, now);
  193. }
  194. return false;
  195. }
  196. destroy() {
  197. this.destroyed = true;
  198. this.emit("destroy");
  199. const self = this;
  200. self.definitions = void 0;
  201. self.expressions = void 0;
  202. }
  203. }
  204. const EPSILON = 0.01;
  205. const MAX_SPEED = 40 / 7.5;
  206. const ACCELERATION_TIME = 1 / (0.15 * 1e3);
  207. class FocusController {
  208. constructor() {
  209. this.targetX = 0;
  210. this.targetY = 0;
  211. this.x = 0;
  212. this.y = 0;
  213. this.vx = 0;
  214. this.vy = 0;
  215. }
  216. focus(x, y, instant = false) {
  217. this.targetX = clamp(x, -1, 1);
  218. this.targetY = clamp(y, -1, 1);
  219. if (instant) {
  220. this.x = this.targetX;
  221. this.y = this.targetY;
  222. }
  223. }
  224. update(dt) {
  225. const dx = this.targetX - this.x;
  226. const dy = this.targetY - this.y;
  227. if (Math.abs(dx) < EPSILON && Math.abs(dy) < EPSILON)
  228. return;
  229. const d = Math.sqrt(__pow(dx, 2) + __pow(dy, 2));
  230. const maxSpeed = MAX_SPEED / (1e3 / dt);
  231. let ax = maxSpeed * (dx / d) - this.vx;
  232. let ay = maxSpeed * (dy / d) - this.vy;
  233. const a = Math.sqrt(__pow(ax, 2) + __pow(ay, 2));
  234. const maxA = maxSpeed * ACCELERATION_TIME * dt;
  235. if (a > maxA) {
  236. ax *= maxA / a;
  237. ay *= maxA / a;
  238. }
  239. this.vx += ax;
  240. this.vy += ay;
  241. const v = Math.sqrt(__pow(this.vx, 2) + __pow(this.vy, 2));
  242. const maxV = 0.5 * (Math.sqrt(__pow(maxA, 2) + 8 * maxA * d) - maxA);
  243. if (v > maxV) {
  244. this.vx *= maxV / v;
  245. this.vy *= maxV / v;
  246. }
  247. this.x += this.vx;
  248. this.y += this.vy;
  249. }
  250. }
  251. class ModelSettings {
  252. constructor(json) {
  253. this.json = json;
  254. let url2 = json.url;
  255. if (typeof url2 !== "string") {
  256. throw new TypeError("The `url` field in settings JSON must be defined as a string.");
  257. }
  258. this.url = url2;
  259. this.name = folderName(this.url);
  260. }
  261. resolveURL(path) {
  262. return url.resolve(this.url, path);
  263. }
  264. replaceFiles(replacer) {
  265. this.moc = replacer(this.moc, "moc");
  266. if (this.pose !== void 0) {
  267. this.pose = replacer(this.pose, "pose");
  268. }
  269. if (this.physics !== void 0) {
  270. this.physics = replacer(this.physics, "physics");
  271. }
  272. for (let i = 0; i < this.textures.length; i++) {
  273. this.textures[i] = replacer(this.textures[i], `textures[${i}]`);
  274. }
  275. }
  276. getDefinedFiles() {
  277. const files = [];
  278. this.replaceFiles((file) => {
  279. files.push(file);
  280. return file;
  281. });
  282. return files;
  283. }
  284. validateFiles(files) {
  285. const assertFileExists = (expectedFile, shouldThrow) => {
  286. const actualPath = this.resolveURL(expectedFile);
  287. if (!files.includes(actualPath)) {
  288. if (shouldThrow) {
  289. throw new Error(`File "${expectedFile}" is defined in settings, but doesn't exist in given files`);
  290. }
  291. return false;
  292. }
  293. return true;
  294. };
  295. const essentialFiles = [this.moc, ...this.textures];
  296. essentialFiles.forEach((texture) => assertFileExists(texture, true));
  297. const definedFiles = this.getDefinedFiles();
  298. return definedFiles.filter((file) => assertFileExists(file, false));
  299. }
  300. }
  301. var MotionPriority = /* @__PURE__ */ ((MotionPriority2) => {
  302. MotionPriority2[MotionPriority2["NONE"] = 0] = "NONE";
  303. MotionPriority2[MotionPriority2["IDLE"] = 1] = "IDLE";
  304. MotionPriority2[MotionPriority2["NORMAL"] = 2] = "NORMAL";
  305. MotionPriority2[MotionPriority2["FORCE"] = 3] = "FORCE";
  306. return MotionPriority2;
  307. })(MotionPriority || {});
  308. class MotionState {
  309. constructor() {
  310. this.debug = false;
  311. this.currentPriority = 0;
  312. this.reservePriority = 0;
  313. }
  314. reserve(group, index, priority) {
  315. if (priority <= 0) {
  316. logger.log(this.tag, `Cannot start a motion with MotionPriority.NONE.`);
  317. return false;
  318. }
  319. if (group === this.currentGroup && index === this.currentIndex) {
  320. logger.log(this.tag, `Motion is already playing.`, this.dump(group, index));
  321. return false;
  322. }
  323. if (group === this.reservedGroup && index === this.reservedIndex || group === this.reservedIdleGroup && index === this.reservedIdleIndex) {
  324. logger.log(this.tag, `Motion is already reserved.`, this.dump(group, index));
  325. return false;
  326. }
  327. if (priority === 1) {
  328. if (this.currentPriority !== 0) {
  329. logger.log(this.tag, `Cannot start idle motion because another motion is playing.`, this.dump(group, index));
  330. return false;
  331. }
  332. if (this.reservedIdleGroup !== void 0) {
  333. logger.log(this.tag, `Cannot start idle motion because another idle motion has reserved.`, this.dump(group, index));
  334. return false;
  335. }
  336. this.setReservedIdle(group, index);
  337. } else {
  338. if (priority < 3) {
  339. if (priority <= this.currentPriority) {
  340. logger.log(this.tag, "Cannot start motion because another motion is playing as an equivalent or higher priority.", this.dump(group, index));
  341. return false;
  342. }
  343. if (priority <= this.reservePriority) {
  344. logger.log(this.tag, "Cannot start motion because another motion has reserved as an equivalent or higher priority.", this.dump(group, index));
  345. return false;
  346. }
  347. }
  348. this.setReserved(group, index, priority);
  349. }
  350. return true;
  351. }
  352. start(motion, group, index, priority) {
  353. if (priority === 1) {
  354. this.setReservedIdle(void 0, void 0);
  355. if (this.currentPriority !== 0) {
  356. logger.log(this.tag, "Cannot start idle motion because another motion is playing.", this.dump(group, index));
  357. return false;
  358. }
  359. } else {
  360. if (group !== this.reservedGroup || index !== this.reservedIndex) {
  361. logger.log(this.tag, "Cannot start motion because another motion has taken the place.", this.dump(group, index));
  362. return false;
  363. }
  364. this.setReserved(void 0, void 0, 0);
  365. }
  366. if (!motion) {
  367. return false;
  368. }
  369. this.setCurrent(group, index, priority);
  370. return true;
  371. }
  372. complete() {
  373. this.setCurrent(void 0, void 0, 0);
  374. }
  375. setCurrent(group, index, priority) {
  376. this.currentPriority = priority;
  377. this.currentGroup = group;
  378. this.currentIndex = index;
  379. }
  380. setReserved(group, index, priority) {
  381. this.reservePriority = priority;
  382. this.reservedGroup = group;
  383. this.reservedIndex = index;
  384. }
  385. setReservedIdle(group, index) {
  386. this.reservedIdleGroup = group;
  387. this.reservedIdleIndex = index;
  388. }
  389. isActive(group, index) {
  390. return group === this.currentGroup && index === this.currentIndex || group === this.reservedGroup && index === this.reservedIndex || group === this.reservedIdleGroup && index === this.reservedIdleIndex;
  391. }
  392. reset() {
  393. this.setCurrent(void 0, void 0, 0);
  394. this.setReserved(void 0, void 0, 0);
  395. this.setReservedIdle(void 0, void 0);
  396. }
  397. shouldRequestIdleMotion() {
  398. return this.currentGroup === void 0 && this.reservedIdleGroup === void 0;
  399. }
  400. shouldOverrideExpression() {
  401. return !config.preserveExpressionOnMotion && this.currentPriority > 1;
  402. }
  403. dump(requestedGroup, requestedIndex) {
  404. if (this.debug) {
  405. const keys = [
  406. "currentPriority",
  407. "reservePriority",
  408. "currentGroup",
  409. "currentIndex",
  410. "reservedGroup",
  411. "reservedIndex",
  412. "reservedIdleGroup",
  413. "reservedIdleIndex"
  414. ];
  415. return `
  416. <Requested> group = "${requestedGroup}", index = ${requestedIndex}
  417. ` + keys.map((key) => "[" + key + "] " + this[key]).join("\n");
  418. }
  419. return "";
  420. }
  421. }
  422. const TAG$2 = "SoundManager";
  423. const VOLUME = 0.5;
  424. class SoundManager {
  425. static get volume() {
  426. return this._volume;
  427. }
  428. static set volume(value) {
  429. this._volume = (value > 1 ? 1 : value < 0 ? 0 : value) || 0;
  430. this.audios.forEach((audio) => audio.volume = this._volume);
  431. }
  432. static add(file, onFinish, onError) {
  433. const audio = new Audio(file);
  434. audio.volume = this._volume;
  435. audio.preload = "auto";
  436. audio.addEventListener("ended", () => {
  437. this.dispose(audio);
  438. onFinish == null ? void 0 : onFinish();
  439. });
  440. audio.addEventListener("error", (e) => {
  441. this.dispose(audio);
  442. logger.warn(TAG$2, `Error occurred on "${file}"`, e.error);
  443. onError == null ? void 0 : onError(e.error);
  444. });
  445. this.audios.push(audio);
  446. return audio;
  447. }
  448. static play(audio) {
  449. return new Promise((resolve, reject) => {
  450. var _a;
  451. (_a = audio.play()) == null ? void 0 : _a.catch((e) => {
  452. audio.dispatchEvent(new ErrorEvent("error", { error: e }));
  453. reject(e);
  454. });
  455. if (audio.readyState === audio.HAVE_ENOUGH_DATA) {
  456. resolve();
  457. } else {
  458. audio.addEventListener("canplaythrough", resolve);
  459. }
  460. });
  461. }
  462. static dispose(audio) {
  463. audio.pause();
  464. audio.removeAttribute("src");
  465. remove(this.audios, audio);
  466. }
  467. static destroy() {
  468. for (let i = this.audios.length - 1; i >= 0; i--) {
  469. this.dispose(this.audios[i]);
  470. }
  471. }
  472. }
  473. SoundManager.audios = [];
  474. SoundManager._volume = VOLUME;
  475. var MotionPreloadStrategy = /* @__PURE__ */ ((MotionPreloadStrategy2) => {
  476. MotionPreloadStrategy2["ALL"] = "ALL";
  477. MotionPreloadStrategy2["IDLE"] = "IDLE";
  478. MotionPreloadStrategy2["NONE"] = "NONE";
  479. return MotionPreloadStrategy2;
  480. })(MotionPreloadStrategy || {});
  481. class MotionManager extends EventEmitter {
  482. constructor(settings, options) {
  483. super();
  484. this.motionGroups = {};
  485. this.state = new MotionState();
  486. this.playing = false;
  487. this.destroyed = false;
  488. this.settings = settings;
  489. this.tag = `MotionManager(${settings.name})`;
  490. this.state.tag = this.tag;
  491. }
  492. init(options) {
  493. if (options == null ? void 0 : options.idleMotionGroup) {
  494. this.groups.idle = options.idleMotionGroup;
  495. }
  496. this.setupMotions(options);
  497. this.stopAllMotions();
  498. }
  499. setupMotions(options) {
  500. for (const group of Object.keys(this.definitions)) {
  501. this.motionGroups[group] = [];
  502. }
  503. let groups;
  504. switch (options == null ? void 0 : options.motionPreload) {
  505. case "NONE":
  506. return;
  507. case "ALL":
  508. groups = Object.keys(this.definitions);
  509. break;
  510. case "IDLE":
  511. default:
  512. groups = [this.groups.idle];
  513. break;
  514. }
  515. for (const group of groups) {
  516. if (this.definitions[group]) {
  517. for (let i = 0; i < this.definitions[group].length; i++) {
  518. this.loadMotion(group, i).then();
  519. }
  520. }
  521. }
  522. }
  523. loadMotion(group, index) {
  524. return __async(this, null, function* () {
  525. var _a;
  526. if (!((_a = this.definitions[group]) == null ? void 0 : _a[index])) {
  527. logger.warn(this.tag, `Undefined motion at "${group}"[${index}]`);
  528. return void 0;
  529. }
  530. if (this.motionGroups[group][index] === null) {
  531. logger.warn(this.tag, `Cannot start motion at "${group}"[${index}] because it's already failed in loading.`);
  532. return void 0;
  533. }
  534. if (this.motionGroups[group][index]) {
  535. return this.motionGroups[group][index];
  536. }
  537. const motion = yield this._loadMotion(group, index);
  538. if (this.destroyed) {
  539. return;
  540. }
  541. this.motionGroups[group][index] = motion != null ? motion : null;
  542. return motion;
  543. });
  544. }
  545. _loadMotion(group, index) {
  546. throw new Error("Not implemented.");
  547. }
  548. startMotion(_0, _1) {
  549. return __async(this, arguments, function* (group, index, priority = MotionPriority.NORMAL) {
  550. var _a;
  551. if (!this.state.reserve(group, index, priority)) {
  552. return false;
  553. }
  554. const definition = (_a = this.definitions[group]) == null ? void 0 : _a[index];
  555. if (!definition) {
  556. return false;
  557. }
  558. if (this.currentAudio) {
  559. SoundManager.dispose(this.currentAudio);
  560. }
  561. let audio;
  562. if (config.sound) {
  563. const soundURL = this.getSoundFile(definition);
  564. if (soundURL) {
  565. try {
  566. audio = SoundManager.add(this.settings.resolveURL(soundURL), () => this.currentAudio = void 0, () => this.currentAudio = void 0);
  567. this.currentAudio = audio;
  568. } catch (e) {
  569. logger.warn(this.tag, "Failed to create audio", soundURL, e);
  570. }
  571. }
  572. }
  573. const motion = yield this.loadMotion(group, index);
  574. if (audio) {
  575. const readyToPlay = SoundManager.play(audio).catch((e) => logger.warn(this.tag, "Failed to play audio", audio.src, e));
  576. if (config.motionSync) {
  577. yield readyToPlay;
  578. }
  579. }
  580. if (!this.state.start(motion, group, index, priority)) {
  581. if (audio) {
  582. SoundManager.dispose(audio);
  583. this.currentAudio = void 0;
  584. }
  585. return false;
  586. }
  587. logger.log(this.tag, "Start motion:", this.getMotionName(definition));
  588. this.emit("motionStart", group, index, audio);
  589. if (this.state.shouldOverrideExpression()) {
  590. this.expressionManager && this.expressionManager.resetExpression();
  591. }
  592. this.playing = true;
  593. this._startMotion(motion);
  594. return true;
  595. });
  596. }
  597. startRandomMotion(group, priority) {
  598. return __async(this, null, function* () {
  599. const groupDefs = this.definitions[group];
  600. if (groupDefs == null ? void 0 : groupDefs.length) {
  601. const availableIndices = [];
  602. for (let i = 0; i < groupDefs.length; i++) {
  603. if (this.motionGroups[group][i] !== null && !this.state.isActive(group, i)) {
  604. availableIndices.push(i);
  605. }
  606. }
  607. if (availableIndices.length) {
  608. const index = Math.floor(Math.random() * availableIndices.length);
  609. return this.startMotion(group, availableIndices[index], priority);
  610. }
  611. }
  612. return false;
  613. });
  614. }
  615. stopAllMotions() {
  616. this._stopAllMotions();
  617. this.state.reset();
  618. if (this.currentAudio) {
  619. SoundManager.dispose(this.currentAudio);
  620. this.currentAudio = void 0;
  621. }
  622. }
  623. update(model, now) {
  624. var _a;
  625. if (this.isFinished()) {
  626. if (this.playing) {
  627. this.playing = false;
  628. this.emit("motionFinish");
  629. }
  630. if (this.state.shouldOverrideExpression()) {
  631. (_a = this.expressionManager) == null ? void 0 : _a.restoreExpression();
  632. }
  633. this.state.complete();
  634. if (this.state.shouldRequestIdleMotion()) {
  635. this.startRandomMotion(this.groups.idle, MotionPriority.IDLE);
  636. }
  637. }
  638. return this.updateParameters(model, now);
  639. }
  640. destroy() {
  641. var _a;
  642. this.destroyed = true;
  643. this.emit("destroy");
  644. this.stopAllMotions();
  645. (_a = this.expressionManager) == null ? void 0 : _a.destroy();
  646. const self = this;
  647. self.definitions = void 0;
  648. self.motionGroups = void 0;
  649. }
  650. }
  651. const tempBounds = { x: 0, y: 0, width: 0, height: 0 };
  652. class InternalModel extends EventEmitter {
  653. constructor() {
  654. super(...arguments);
  655. this.focusController = new FocusController();
  656. this.originalWidth = 0;
  657. this.originalHeight = 0;
  658. this.width = 0;
  659. this.height = 0;
  660. this.localTransform = new Matrix();
  661. this.drawingMatrix = new Matrix();
  662. this.hitAreas = {};
  663. this.textureFlipY = false;
  664. this.viewport = [0, 0, 0, 0];
  665. this.destroyed = false;
  666. }
  667. init() {
  668. this.setupLayout();
  669. this.setupHitAreas();
  670. }
  671. setupLayout() {
  672. const self = this;
  673. const size = this.getSize();
  674. self.originalWidth = size[0];
  675. self.originalHeight = size[1];
  676. const layout = Object.assign({
  677. width: LOGICAL_WIDTH,
  678. height: LOGICAL_HEIGHT
  679. }, this.getLayout());
  680. this.localTransform.scale(layout.width / LOGICAL_WIDTH, layout.height / LOGICAL_HEIGHT);
  681. self.width = this.originalWidth * this.localTransform.a;
  682. self.height = this.originalHeight * this.localTransform.d;
  683. const offsetX = layout.x !== void 0 && layout.x - layout.width / 2 || layout.centerX !== void 0 && layout.centerX || layout.left !== void 0 && layout.left - layout.width / 2 || layout.right !== void 0 && layout.right + layout.width / 2 || 0;
  684. const offsetY = layout.y !== void 0 && layout.y - layout.height / 2 || layout.centerY !== void 0 && layout.centerY || layout.top !== void 0 && layout.top - layout.height / 2 || layout.bottom !== void 0 && layout.bottom + layout.height / 2 || 0;
  685. this.localTransform.translate(this.width * offsetX, -this.height * offsetY);
  686. }
  687. setupHitAreas() {
  688. const definitions = this.getHitAreaDefs().filter((hitArea) => hitArea.index >= 0);
  689. for (const def of definitions) {
  690. this.hitAreas[def.name] = def;
  691. }
  692. }
  693. hitTest(x, y) {
  694. return Object.keys(this.hitAreas).filter((hitAreaName) => this.isHit(hitAreaName, x, y));
  695. }
  696. isHit(hitAreaName, x, y) {
  697. if (!this.hitAreas[hitAreaName]) {
  698. return false;
  699. }
  700. const drawIndex = this.hitAreas[hitAreaName].index;
  701. const bounds = this.getDrawableBounds(drawIndex, tempBounds);
  702. return bounds.x <= x && x <= bounds.x + bounds.width && bounds.y <= y && y <= bounds.y + bounds.height;
  703. }
  704. getDrawableBounds(index, bounds) {
  705. const vertices = this.getDrawableVertices(index);
  706. let left = vertices[0];
  707. let right = vertices[0];
  708. let top = vertices[1];
  709. let bottom = vertices[1];
  710. for (let i = 0; i < vertices.length; i += 2) {
  711. const vx = vertices[i];
  712. const vy = vertices[i + 1];
  713. left = Math.min(vx, left);
  714. right = Math.max(vx, right);
  715. top = Math.min(vy, top);
  716. bottom = Math.max(vy, bottom);
  717. }
  718. bounds != null ? bounds : bounds = {};
  719. bounds.x = left;
  720. bounds.y = top;
  721. bounds.width = right - left;
  722. bounds.height = bottom - top;
  723. return bounds;
  724. }
  725. updateTransform(transform) {
  726. this.drawingMatrix.copyFrom(transform).append(this.localTransform);
  727. }
  728. update(dt, now) {
  729. this.focusController.update(dt);
  730. }
  731. destroy() {
  732. this.destroyed = true;
  733. this.emit("destroy");
  734. this.motionManager.destroy();
  735. this.motionManager = void 0;
  736. }
  737. }
  738. const TAG$1 = "XHRLoader";
  739. class NetworkError extends Error {
  740. constructor(message, url2, status, aborted = false) {
  741. super(message);
  742. this.url = url2;
  743. this.status = status;
  744. this.aborted = aborted;
  745. }
  746. }
  747. const _XHRLoader = class {
  748. static createXHR(target, url2, type, onload, onerror) {
  749. const xhr = new XMLHttpRequest();
  750. _XHRLoader.allXhrSet.add(xhr);
  751. if (target) {
  752. let xhrSet = _XHRLoader.xhrMap.get(target);
  753. if (!xhrSet) {
  754. xhrSet = /* @__PURE__ */ new Set([xhr]);
  755. _XHRLoader.xhrMap.set(target, xhrSet);
  756. } else {
  757. xhrSet.add(xhr);
  758. }
  759. if (!target.listeners("destroy").includes(_XHRLoader.cancelXHRs)) {
  760. target.once("destroy", _XHRLoader.cancelXHRs);
  761. }
  762. }
  763. xhr.open("GET", url2);
  764. xhr.responseType = type;
  765. xhr.onload = () => {
  766. if ((xhr.status === 200 || xhr.status === 0) && xhr.response) {
  767. onload(xhr.response);
  768. } else {
  769. xhr.onerror();
  770. }
  771. };
  772. xhr.onerror = () => {
  773. logger.warn(TAG$1, `Failed to load resource as ${xhr.responseType} (Status ${xhr.status}): ${url2}`);
  774. onerror(new NetworkError("Network error.", url2, xhr.status));
  775. };
  776. xhr.onabort = () => onerror(new NetworkError("Aborted.", url2, xhr.status, true));
  777. xhr.onloadend = () => {
  778. var _a;
  779. _XHRLoader.allXhrSet.delete(xhr);
  780. if (target) {
  781. (_a = _XHRLoader.xhrMap.get(target)) == null ? void 0 : _a.delete(xhr);
  782. }
  783. };
  784. return xhr;
  785. }
  786. static cancelXHRs() {
  787. var _a;
  788. (_a = _XHRLoader.xhrMap.get(this)) == null ? void 0 : _a.forEach((xhr) => {
  789. xhr.abort();
  790. _XHRLoader.allXhrSet.delete(xhr);
  791. });
  792. _XHRLoader.xhrMap.delete(this);
  793. }
  794. static release() {
  795. _XHRLoader.allXhrSet.forEach((xhr) => xhr.abort());
  796. _XHRLoader.allXhrSet.clear();
  797. _XHRLoader.xhrMap = /* @__PURE__ */ new WeakMap();
  798. }
  799. };
  800. let XHRLoader = _XHRLoader;
  801. XHRLoader.xhrMap = /* @__PURE__ */ new WeakMap();
  802. XHRLoader.allXhrSet = /* @__PURE__ */ new Set();
  803. XHRLoader.loader = (context, next) => {
  804. return new Promise((resolve, reject) => {
  805. const xhr = _XHRLoader.createXHR(context.target, context.settings ? context.settings.resolveURL(context.url) : context.url, context.type, (data) => {
  806. context.result = data;
  807. resolve();
  808. }, reject);
  809. xhr.send();
  810. });
  811. };
  812. function runMiddlewares(middleware, context) {
  813. let index = -1;
  814. return dispatch(0);
  815. function dispatch(i, err) {
  816. if (err)
  817. return Promise.reject(err);
  818. if (i <= index)
  819. return Promise.reject(new Error("next() called multiple times"));
  820. index = i;
  821. const fn = middleware[i];
  822. if (!fn)
  823. return Promise.resolve();
  824. try {
  825. return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));
  826. } catch (err2) {
  827. return Promise.reject(err2);
  828. }
  829. }
  830. }
  831. class Live2DLoader {
  832. static load(context) {
  833. return runMiddlewares(this.middlewares, context).then(() => context.result);
  834. }
  835. }
  836. Live2DLoader.middlewares = [XHRLoader.loader];
  837. function createTexture(url2, options = {}) {
  838. var _a;
  839. const textureOptions = { resourceOptions: { crossorigin: options.crossOrigin } };
  840. if (Texture.fromURL) {
  841. return Texture.fromURL(url2, textureOptions).catch((e) => {
  842. if (e instanceof Error) {
  843. throw e;
  844. }
  845. const err = new Error("Texture loading error");
  846. err.event = e;
  847. throw err;
  848. });
  849. }
  850. textureOptions.resourceOptions.autoLoad = false;
  851. const texture = Texture.from(url2, textureOptions);
  852. if (texture.baseTexture.valid) {
  853. return Promise.resolve(texture);
  854. }
  855. const resource = texture.baseTexture.resource;
  856. (_a = resource._live2d_load) != null ? _a : resource._live2d_load = new Promise((resolve, reject) => {
  857. const errorHandler = (event) => {
  858. resource.source.removeEventListener("error", errorHandler);
  859. const err = new Error("Texture loading error");
  860. err.event = event;
  861. reject(err);
  862. };
  863. resource.source.addEventListener("error", errorHandler);
  864. resource.load().then(() => resolve(texture)).catch(errorHandler);
  865. });
  866. return resource._live2d_load;
  867. }
  868. const TAG = "Live2DFactory";
  869. const urlToJSON = (context, next) => __async(void 0, null, function* () {
  870. if (typeof context.source === "string") {
  871. const data = yield Live2DLoader.load({
  872. url: context.source,
  873. type: "json",
  874. target: context.live2dModel
  875. });
  876. data.url = context.source;
  877. context.source = data;
  878. context.live2dModel.emit("settingsJSONLoaded", data);
  879. }
  880. return next();
  881. });
  882. const jsonToSettings = (context, next) => __async(void 0, null, function* () {
  883. if (context.source instanceof ModelSettings) {
  884. context.settings = context.source;
  885. return next();
  886. } else if (typeof context.source === "object") {
  887. const runtime = Live2DFactory.findRuntime(context.source);
  888. if (runtime) {
  889. const settings = runtime.createModelSettings(context.source);
  890. context.settings = settings;
  891. context.live2dModel.emit("settingsLoaded", settings);
  892. return next();
  893. }
  894. }
  895. throw new TypeError("Unknown settings format.");
  896. });
  897. const waitUntilReady = (context, next) => {
  898. if (context.settings) {
  899. const runtime = Live2DFactory.findRuntime(context.settings);
  900. if (runtime) {
  901. return runtime.ready().then(next);
  902. }
  903. }
  904. return next();
  905. };
  906. const setupOptionals = (context, next) => __async(void 0, null, function* () {
  907. yield next();
  908. const internalModel = context.internalModel;
  909. if (internalModel) {
  910. const settings = context.settings;
  911. const runtime = Live2DFactory.findRuntime(settings);
  912. if (runtime) {
  913. const tasks = [];
  914. if (settings.pose) {
  915. tasks.push(Live2DLoader.load({
  916. settings,
  917. url: settings.pose,
  918. type: "json",
  919. target: internalModel
  920. }).then((data) => {
  921. internalModel.pose = runtime.createPose(internalModel.coreModel, data);
  922. context.live2dModel.emit("poseLoaded", internalModel.pose);
  923. }).catch((e) => {
  924. context.live2dModel.emit("poseLoadError", e);
  925. logger.warn(TAG, "Failed to load pose.", e);
  926. }));
  927. }
  928. if (settings.physics) {
  929. tasks.push(Live2DLoader.load({
  930. settings,
  931. url: settings.physics,
  932. type: "json",
  933. target: internalModel
  934. }).then((data) => {
  935. internalModel.physics = runtime.createPhysics(internalModel.coreModel, data);
  936. context.live2dModel.emit("physicsLoaded", internalModel.physics);
  937. }).catch((e) => {
  938. context.live2dModel.emit("physicsLoadError", e);
  939. logger.warn(TAG, "Failed to load physics.", e);
  940. }));
  941. }
  942. if (tasks.length) {
  943. yield Promise.all(tasks);
  944. }
  945. }
  946. }
  947. });
  948. const setupEssentials = (context, next) => __async(void 0, null, function* () {
  949. if (context.settings) {
  950. const live2DModel = context.live2dModel;
  951. const textureLoadings = context.settings.textures.map((tex) => {
  952. const url2 = context.settings.resolveURL(tex);
  953. return createTexture(url2, { crossOrigin: context.options.crossOrigin });
  954. });
  955. yield next();
  956. if (context.internalModel) {
  957. live2DModel.internalModel = context.internalModel;
  958. live2DModel.emit("modelLoaded", context.internalModel);
  959. } else {
  960. throw new TypeError("Missing internal model.");
  961. }
  962. live2DModel.textures = yield Promise.all(textureLoadings);
  963. live2DModel.emit("textureLoaded", live2DModel.textures);
  964. } else {
  965. throw new TypeError("Missing settings.");
  966. }
  967. });
  968. const createInternalModel = (context, next) => __async(void 0, null, function* () {
  969. const settings = context.settings;
  970. if (settings instanceof ModelSettings) {
  971. const runtime = Live2DFactory.findRuntime(settings);
  972. if (!runtime) {
  973. throw new TypeError("Unknown model settings.");
  974. }
  975. const modelData = yield Live2DLoader.load({
  976. settings,
  977. url: settings.moc,
  978. type: "arraybuffer",
  979. target: context.live2dModel
  980. });
  981. if (!runtime.isValidMoc(modelData)) {
  982. throw new Error("Invalid moc data");
  983. }
  984. const coreModel = runtime.createCoreModel(modelData);
  985. context.internalModel = runtime.createInternalModel(coreModel, settings, context.options);
  986. return next();
  987. }
  988. throw new TypeError("Missing settings.");
  989. });
  990. const _Live2DFactory = class {
  991. static registerRuntime(runtime) {
  992. _Live2DFactory.runtimes.push(runtime);
  993. _Live2DFactory.runtimes.sort((a, b) => b.version - a.version);
  994. }
  995. static findRuntime(source) {
  996. for (const runtime of _Live2DFactory.runtimes) {
  997. if (runtime.test(source)) {
  998. return runtime;
  999. }
  1000. }
  1001. }
  1002. static setupLive2DModel(live2dModel, source, options) {
  1003. return __async(this, null, function* () {
  1004. const textureLoaded = new Promise((resolve) => live2dModel.once("textureLoaded", resolve));
  1005. const modelLoaded = new Promise((resolve) => live2dModel.once("modelLoaded", resolve));
  1006. const readyEventEmitted = Promise.all([textureLoaded, modelLoaded]).then(() => live2dModel.emit("ready"));
  1007. yield runMiddlewares(_Live2DFactory.live2DModelMiddlewares, {
  1008. live2dModel,
  1009. source,
  1010. options: options || {}
  1011. });
  1012. yield readyEventEmitted;
  1013. live2dModel.emit("load");
  1014. });
  1015. }
  1016. static loadMotion(motionManager, group, index) {
  1017. var _a, _b;
  1018. const handleError = (e) => motionManager.emit("motionLoadError", group, index, e);
  1019. try {
  1020. const definition = (_a = motionManager.definitions[group]) == null ? void 0 : _a[index];
  1021. if (!definition) {
  1022. return Promise.resolve(void 0);
  1023. }
  1024. if (!motionManager.listeners("destroy").includes(_Live2DFactory.releaseTasks)) {
  1025. motionManager.once("destroy", _Live2DFactory.releaseTasks);
  1026. }
  1027. let tasks = _Live2DFactory.motionTasksMap.get(motionManager);
  1028. if (!tasks) {
  1029. tasks = {};
  1030. _Live2DFactory.motionTasksMap.set(motionManager, tasks);
  1031. }
  1032. let taskGroup = tasks[group];
  1033. if (!taskGroup) {
  1034. taskGroup = [];
  1035. tasks[group] = taskGroup;
  1036. }
  1037. const path = motionManager.getMotionFile(definition);
  1038. (_b = taskGroup[index]) != null ? _b : taskGroup[index] = Live2DLoader.load({
  1039. url: path,
  1040. settings: motionManager.settings,
  1041. type: motionManager.motionDataType,
  1042. target: motionManager
  1043. }).then((data) => {
  1044. var _a2;
  1045. const taskGroup2 = (_a2 = _Live2DFactory.motionTasksMap.get(motionManager)) == null ? void 0 : _a2[group];
  1046. if (taskGroup2) {
  1047. delete taskGroup2[index];
  1048. }
  1049. const motion = motionManager.createMotion(data, group, definition);
  1050. motionManager.emit("motionLoaded", group, index, motion);
  1051. return motion;
  1052. }).catch((e) => {
  1053. logger.warn(motionManager.tag, `Failed to load motion: ${path}
  1054. `, e);
  1055. handleError(e);
  1056. });
  1057. return taskGroup[index];
  1058. } catch (e) {
  1059. logger.warn(motionManager.tag, `Failed to load motion at "${group}"[${index}]
  1060. `, e);
  1061. handleError(e);
  1062. }
  1063. return Promise.resolve(void 0);
  1064. }
  1065. static loadExpression(expressionManager, index) {
  1066. var _a;
  1067. const handleError = (e) => expressionManager.emit("expressionLoadError", index, e);
  1068. try {
  1069. const definition = expressionManager.definitions[index];
  1070. if (!definition) {
  1071. return Promise.resolve(void 0);
  1072. }
  1073. if (!expressionManager.listeners("destroy").includes(_Live2DFactory.releaseTasks)) {
  1074. expressionManager.once("destroy", _Live2DFactory.releaseTasks);
  1075. }
  1076. let tasks = _Live2DFactory.expressionTasksMap.get(expressionManager);
  1077. if (!tasks) {
  1078. tasks = [];
  1079. _Live2DFactory.expressionTasksMap.set(expressionManager, tasks);
  1080. }
  1081. const path = expressionManager.getExpressionFile(definition);
  1082. (_a = tasks[index]) != null ? _a : tasks[index] = Live2DLoader.load({
  1083. url: path,
  1084. settings: expressionManager.settings,
  1085. type: "json",
  1086. target: expressionManager
  1087. }).then((data) => {
  1088. const tasks2 = _Live2DFactory.expressionTasksMap.get(expressionManager);
  1089. if (tasks2) {
  1090. delete tasks2[index];
  1091. }
  1092. const expression = expressionManager.createExpression(data, definition);
  1093. expressionManager.emit("expressionLoaded", index, expression);
  1094. return expression;
  1095. }).catch((e) => {
  1096. logger.warn(expressionManager.tag, `Failed to load expression: ${path}
  1097. `, e);
  1098. handleError(e);
  1099. });
  1100. return tasks[index];
  1101. } catch (e) {
  1102. logger.warn(expressionManager.tag, `Failed to load expression at [${index}]
  1103. `, e);
  1104. handleError(e);
  1105. }
  1106. return Promise.resolve(void 0);
  1107. }
  1108. static releaseTasks() {
  1109. if (this instanceof MotionManager) {
  1110. _Live2DFactory.motionTasksMap.delete(this);
  1111. } else {
  1112. _Live2DFactory.expressionTasksMap.delete(this);
  1113. }
  1114. }
  1115. };
  1116. let Live2DFactory = _Live2DFactory;
  1117. Live2DFactory.runtimes = [];
  1118. Live2DFactory.urlToJSON = urlToJSON;
  1119. Live2DFactory.jsonToSettings = jsonToSettings;
  1120. Live2DFactory.waitUntilReady = waitUntilReady;
  1121. Live2DFactory.setupOptionals = setupOptionals;
  1122. Live2DFactory.setupEssentials = setupEssentials;
  1123. Live2DFactory.createInternalModel = createInternalModel;
  1124. Live2DFactory.live2DModelMiddlewares = [
  1125. urlToJSON,
  1126. jsonToSettings,
  1127. waitUntilReady,
  1128. setupOptionals,
  1129. setupEssentials,
  1130. createInternalModel
  1131. ];
  1132. Live2DFactory.motionTasksMap = /* @__PURE__ */ new WeakMap();
  1133. Live2DFactory.expressionTasksMap = /* @__PURE__ */ new WeakMap();
  1134. MotionManager.prototype["_loadMotion"] = function(group, index) {
  1135. return Live2DFactory.loadMotion(this, group, index);
  1136. };
  1137. ExpressionManager.prototype["_loadExpression"] = function(index) {
  1138. return Live2DFactory.loadExpression(this, index);
  1139. };
  1140. class InteractionMixin {
  1141. constructor() {
  1142. this._autoInteract = false;
  1143. }
  1144. get autoInteract() {
  1145. return this._autoInteract;
  1146. }
  1147. set autoInteract(autoInteract) {
  1148. if (autoInteract !== this._autoInteract) {
  1149. if (autoInteract) {
  1150. this.on("pointertap", onTap, this);
  1151. } else {
  1152. this.off("pointertap", onTap, this);
  1153. }
  1154. this._autoInteract = autoInteract;
  1155. }
  1156. }
  1157. registerInteraction(manager) {
  1158. if (manager !== this.interactionManager) {
  1159. this.unregisterInteraction();
  1160. if (this._autoInteract && manager) {
  1161. this.interactionManager = manager;
  1162. manager.on("pointermove", onPointerMove, this);
  1163. }
  1164. }
  1165. }
  1166. unregisterInteraction() {
  1167. var _a;
  1168. if (this.interactionManager) {
  1169. (_a = this.interactionManager) == null ? void 0 : _a.off("pointermove", onPointerMove, this);
  1170. this.interactionManager = void 0;
  1171. }
  1172. }
  1173. }
  1174. function onTap(event) {
  1175. this.tap(event.data.global.x, event.data.global.y);
  1176. }
  1177. function onPointerMove(event) {
  1178. this.focus(event.data.global.x, event.data.global.y);
  1179. }
  1180. class Live2DTransform extends Transform {
  1181. }
  1182. const tempPoint = new Point();
  1183. const tempMatrix$1 = new Matrix();
  1184. let tickerRef;
  1185. class Live2DModel extends Container {
  1186. constructor(options) {
  1187. super();
  1188. this.tag = "Live2DModel(uninitialized)";
  1189. this.textures = [];
  1190. this.transform = new Live2DTransform();
  1191. this.anchor = new ObservablePoint(this.onAnchorChange, this, 0, 0);
  1192. this.glContextID = -1;
  1193. this.elapsedTime = performance.now();
  1194. this.deltaTime = 0;
  1195. this._autoUpdate = false;
  1196. this.once("modelLoaded", () => this.init(options));
  1197. }
  1198. static from(source, options) {
  1199. const model = new this(options);
  1200. return Live2DFactory.setupLive2DModel(model, source, options).then(() => model);
  1201. }
  1202. static fromSync(source, options) {
  1203. const model = new this(options);
  1204. Live2DFactory.setupLive2DModel(model, source, options).then(options == null ? void 0 : options.onLoad).catch(options == null ? void 0 : options.onError);
  1205. return model;
  1206. }
  1207. static registerTicker(tickerClass) {
  1208. tickerRef = tickerClass;
  1209. }
  1210. get autoUpdate() {
  1211. return this._autoUpdate;
  1212. }
  1213. set autoUpdate(autoUpdate) {
  1214. var _a;
  1215. tickerRef || (tickerRef = (_a = window.PIXI) == null ? void 0 : _a.Ticker);
  1216. if (autoUpdate) {
  1217. if (!this._destroyed) {
  1218. if (tickerRef) {
  1219. tickerRef.shared.add(this.onTickerUpdate, this);
  1220. this._autoUpdate = true;
  1221. } else {
  1222. logger.warn(this.tag, "No Ticker registered, please call Live2DModel.registerTicker(Ticker).");
  1223. }
  1224. }
  1225. } else {
  1226. tickerRef == null ? void 0 : tickerRef.shared.remove(this.onTickerUpdate, this);
  1227. this._autoUpdate = false;
  1228. }
  1229. }
  1230. init(options) {
  1231. this.tag = `Live2DModel(${this.internalModel.settings.name})`;
  1232. const _options = Object.assign({
  1233. autoUpdate: true,
  1234. autoInteract: true
  1235. }, options);
  1236. if (_options.autoInteract) {
  1237. this.interactive = true;
  1238. }
  1239. this.autoInteract = _options.autoInteract;
  1240. this.autoUpdate = _options.autoUpdate;
  1241. }
  1242. onAnchorChange() {
  1243. this.pivot.set(this.anchor.x * this.internalModel.width, this.anchor.y * this.internalModel.height);
  1244. }
  1245. motion(group, index, priority) {
  1246. return index === void 0 ? this.internalModel.motionManager.startRandomMotion(group, priority) : this.internalModel.motionManager.startMotion(group, index, priority);
  1247. }
  1248. expression(id) {
  1249. if (this.internalModel.motionManager.expressionManager) {
  1250. return id === void 0 ? this.internalModel.motionManager.expressionManager.setRandomExpression() : this.internalModel.motionManager.expressionManager.setExpression(id);
  1251. }
  1252. return Promise.resolve(false);
  1253. }
  1254. focus(x, y, instant = false) {
  1255. tempPoint.x = x;
  1256. tempPoint.y = y;
  1257. this.toModelPosition(tempPoint, tempPoint, true);
  1258. let tx = tempPoint.x / this.internalModel.originalWidth * 2 - 1;
  1259. let ty = tempPoint.y / this.internalModel.originalHeight * 2 - 1;
  1260. let radian = Math.atan2(ty, tx);
  1261. this.internalModel.focusController.focus(Math.cos(radian), -Math.sin(radian), instant);
  1262. }
  1263. tap(x, y) {
  1264. const hitAreaNames = this.hitTest(x, y);
  1265. if (hitAreaNames.length) {
  1266. logger.log(this.tag, `Hit`, hitAreaNames);
  1267. this.emit("hit", hitAreaNames);
  1268. }
  1269. }
  1270. hitTest(x, y) {
  1271. tempPoint.x = x;
  1272. tempPoint.y = y;
  1273. this.toModelPosition(tempPoint, tempPoint);
  1274. return this.internalModel.hitTest(tempPoint.x, tempPoint.y);
  1275. }
  1276. toModelPosition(position, result = position.clone(), skipUpdate) {
  1277. if (!skipUpdate) {
  1278. this._recursivePostUpdateTransform();
  1279. if (!this.parent) {
  1280. this.parent = this._tempDisplayObjectParent;
  1281. this.displayObjectUpdateTransform();
  1282. this.parent = null;
  1283. } else {
  1284. this.displayObjectUpdateTransform();
  1285. }
  1286. }
  1287. this.transform.worldTransform.applyInverse(position, result);
  1288. this.internalModel.localTransform.applyInverse(result, result);
  1289. return result;
  1290. }
  1291. containsPoint(point) {
  1292. return this.getBounds(true).contains(point.x, point.y);
  1293. }
  1294. _calculateBounds() {
  1295. this._bounds.addFrame(this.transform, 0, 0, this.internalModel.width, this.internalModel.height);
  1296. }
  1297. onTickerUpdate() {
  1298. this.update(tickerRef.shared.deltaMS);
  1299. }
  1300. update(dt) {
  1301. this.deltaTime += dt;
  1302. this.elapsedTime += dt;
  1303. }
  1304. _render(renderer) {
  1305. this.registerInteraction(renderer.plugins.interaction);
  1306. renderer.batch.reset();
  1307. renderer.geometry.reset();
  1308. renderer.shader.reset();
  1309. renderer.state.reset();
  1310. let shouldUpdateTexture = false;
  1311. if (this.glContextID !== renderer.CONTEXT_UID) {
  1312. this.glContextID = renderer.CONTEXT_UID;
  1313. this.internalModel.updateWebGLContext(renderer.gl, this.glContextID);
  1314. shouldUpdateTexture = true;
  1315. }
  1316. for (let i = 0; i < this.textures.length; i++) {
  1317. const texture = this.textures[i];
  1318. if (!texture.valid) {
  1319. continue;
  1320. }
  1321. if (shouldUpdateTexture || !texture.baseTexture._glTextures[this.glContextID]) {
  1322. renderer.gl.pixelStorei(WebGLRenderingContext.UNPACK_FLIP_Y_WEBGL, this.internalModel.textureFlipY);
  1323. renderer.texture.bind(texture.baseTexture, 0);
  1324. }
  1325. this.internalModel.bindTexture(i, texture.baseTexture._glTextures[this.glContextID].texture);
  1326. texture.baseTexture.touched = renderer.textureGC.count;
  1327. }
  1328. const viewport = renderer.framebuffer.viewport;
  1329. this.internalModel.viewport = [viewport.x, viewport.y, viewport.width, viewport.height];
  1330. if (this.deltaTime) {
  1331. this.internalModel.update(this.deltaTime, this.elapsedTime);
  1332. this.deltaTime = 0;
  1333. }
  1334. const internalTransform = tempMatrix$1.copyFrom(renderer.globalUniforms.uniforms.projectionMatrix).append(this.worldTransform);
  1335. this.internalModel.updateTransform(internalTransform);
  1336. this.internalModel.draw(renderer.gl);
  1337. renderer.state.reset();
  1338. renderer.texture.reset();
  1339. }
  1340. destroy(options) {
  1341. this.emit("destroy");
  1342. this.autoUpdate = false;
  1343. this.unregisterInteraction();
  1344. if (options == null ? void 0 : options.texture) {
  1345. this.textures.forEach((texture) => texture.destroy(options.baseTexture));
  1346. }
  1347. this.internalModel.destroy();
  1348. super.destroy(options);
  1349. }
  1350. }
  1351. applyMixins(Live2DModel, [InteractionMixin]);
  1352. const _FileLoader = class {
  1353. static resolveURL(settingsURL, filePath) {
  1354. var _a;
  1355. const resolved = (_a = _FileLoader.filesMap[settingsURL]) == null ? void 0 : _a[filePath];
  1356. if (resolved === void 0) {
  1357. throw new Error("Cannot find this file from uploaded files: " + filePath);
  1358. }
  1359. return resolved;
  1360. }
  1361. static upload(files, settings) {
  1362. return __async(this, null, function* () {
  1363. const fileMap = {};
  1364. for (const definedFile of settings.getDefinedFiles()) {
  1365. const actualPath = decodeURI(url.resolve(settings.url, definedFile));
  1366. const actualFile = files.find((file) => file.webkitRelativePath === actualPath);
  1367. if (actualFile) {
  1368. fileMap[definedFile] = URL.createObjectURL(actualFile);
  1369. }
  1370. }
  1371. _FileLoader.filesMap[settings._objectURL] = fileMap;
  1372. });
  1373. }
  1374. static createSettings(files) {
  1375. return __async(this, null, function* () {
  1376. const settingsFile = files.find((file) => file.name.endsWith("model.json") || file.name.endsWith("model3.json"));
  1377. if (!settingsFile) {
  1378. throw new TypeError("Settings file not found");
  1379. }
  1380. const settingsText = yield _FileLoader.readText(settingsFile);
  1381. const settingsJSON = JSON.parse(settingsText);
  1382. settingsJSON.url = settingsFile.webkitRelativePath;
  1383. const runtime = Live2DFactory.findRuntime(settingsJSON);
  1384. if (!runtime) {
  1385. throw new Error("Unknown settings JSON");
  1386. }
  1387. const settings = runtime.createModelSettings(settingsJSON);
  1388. settings._objectURL = URL.createObjectURL(settingsFile);
  1389. return settings;
  1390. });
  1391. }
  1392. static readText(file) {
  1393. return __async(this, null, function* () {
  1394. return new Promise((resolve, reject) => {
  1395. const reader = new FileReader();
  1396. reader.onload = () => resolve(reader.result);
  1397. reader.onerror = reject;
  1398. reader.readAsText(file, "utf8");
  1399. });
  1400. });
  1401. }
  1402. };
  1403. let FileLoader = _FileLoader;
  1404. FileLoader.filesMap = {};
  1405. FileLoader.factory = (context, next) => __async(void 0, null, function* () {
  1406. if (Array.isArray(context.source) && context.source[0] instanceof File) {
  1407. const files = context.source;
  1408. let settings = files.settings;
  1409. if (!settings) {
  1410. settings = yield _FileLoader.createSettings(files);
  1411. } else if (!settings._objectURL) {
  1412. throw new Error('"_objectURL" must be specified in ModelSettings');
  1413. }
  1414. settings.validateFiles(files.map((file) => encodeURI(file.webkitRelativePath)));
  1415. yield _FileLoader.upload(files, settings);
  1416. settings.resolveURL = function(url2) {
  1417. return _FileLoader.resolveURL(this._objectURL, url2);
  1418. };
  1419. context.source = settings;
  1420. context.live2dModel.once("modelLoaded", (internalModel) => {
  1421. internalModel.once("destroy", function() {
  1422. const objectURL = this.settings._objectURL;
  1423. URL.revokeObjectURL(objectURL);
  1424. if (_FileLoader.filesMap[objectURL]) {
  1425. for (const resourceObjectURL of Object.values(_FileLoader.filesMap[objectURL])) {
  1426. URL.revokeObjectURL(resourceObjectURL);
  1427. }
  1428. }
  1429. delete _FileLoader.filesMap[objectURL];
  1430. });
  1431. });
  1432. }
  1433. return next();
  1434. });
  1435. Live2DFactory.live2DModelMiddlewares.unshift(FileLoader.factory);
  1436. const _ZipLoader = class {
  1437. static unzip(reader, settings) {
  1438. return __async(this, null, function* () {
  1439. const filePaths = yield _ZipLoader.getFilePaths(reader);
  1440. const requiredFilePaths = [];
  1441. for (const definedFile of settings.getDefinedFiles()) {
  1442. const actualPath = decodeURI(url.resolve(settings.url, definedFile));
  1443. if (filePaths.includes(actualPath)) {
  1444. requiredFilePaths.push(actualPath);
  1445. }
  1446. }
  1447. const files = yield _ZipLoader.getFiles(reader, requiredFilePaths);
  1448. for (let i = 0; i < files.length; i++) {
  1449. const path = requiredFilePaths[i];
  1450. const file = files[i];
  1451. Object.defineProperty(file, "webkitRelativePath", {
  1452. value: path
  1453. });
  1454. }
  1455. return files;
  1456. });
  1457. }
  1458. static createSettings(reader) {
  1459. return __async(this, null, function* () {
  1460. const filePaths = yield _ZipLoader.getFilePaths(reader);
  1461. const settingsFilePath = filePaths.find((path) => path.endsWith("model.json") || path.endsWith("model3.json"));
  1462. if (!settingsFilePath) {
  1463. throw new Error("Settings file not found");
  1464. }
  1465. const settingsText = yield _ZipLoader.readText(reader, settingsFilePath);
  1466. if (!settingsText) {
  1467. throw new Error("Empty settings file: " + settingsFilePath);
  1468. }
  1469. const settingsJSON = JSON.parse(settingsText);
  1470. settingsJSON.url = settingsFilePath;
  1471. const runtime = Live2DFactory.findRuntime(settingsJSON);
  1472. if (!runtime) {
  1473. throw new Error("Unknown settings JSON");
  1474. }
  1475. return runtime.createModelSettings(settingsJSON);
  1476. });
  1477. }
  1478. static zipReader(data, url2) {
  1479. return __async(this, null, function* () {
  1480. throw new Error("Not implemented");
  1481. });
  1482. }
  1483. static getFilePaths(reader) {
  1484. return __async(this, null, function* () {
  1485. throw new Error("Not implemented");
  1486. });
  1487. }
  1488. static getFiles(reader, paths) {
  1489. return __async(this, null, function* () {
  1490. throw new Error("Not implemented");
  1491. });
  1492. }
  1493. static readText(reader, path) {
  1494. return __async(this, null, function* () {
  1495. throw new Error("Not implemented");
  1496. });
  1497. }
  1498. static releaseReader(reader) {
  1499. }
  1500. };
  1501. let ZipLoader = _ZipLoader;
  1502. ZipLoader.ZIP_PROTOCOL = "zip://";
  1503. ZipLoader.uid = 0;
  1504. ZipLoader.factory = (context, next) => __async(void 0, null, function* () {
  1505. const source = context.source;
  1506. let sourceURL;
  1507. let zipBlob;
  1508. let settings;
  1509. if (typeof source === "string" && (source.endsWith(".zip") || source.startsWith(_ZipLoader.ZIP_PROTOCOL))) {
  1510. if (source.startsWith(_ZipLoader.ZIP_PROTOCOL)) {
  1511. sourceURL = source.slice(_ZipLoader.ZIP_PROTOCOL.length);
  1512. } else {
  1513. sourceURL = source;
  1514. }
  1515. zipBlob = yield Live2DLoader.load({
  1516. url: sourceURL,
  1517. type: "blob",
  1518. target: context.live2dModel
  1519. });
  1520. } else if (Array.isArray(source) && source.length === 1 && source[0] instanceof File && source[0].name.endsWith(".zip")) {
  1521. zipBlob = source[0];
  1522. sourceURL = URL.createObjectURL(zipBlob);
  1523. settings = source.settings;
  1524. }
  1525. if (zipBlob) {
  1526. if (!zipBlob.size) {
  1527. throw new Error("Empty zip file");
  1528. }
  1529. const reader = yield _ZipLoader.zipReader(zipBlob, sourceURL);
  1530. if (!settings) {
  1531. settings = yield _ZipLoader.createSettings(reader);
  1532. }
  1533. settings._objectURL = _ZipLoader.ZIP_PROTOCOL + _ZipLoader.uid + "/" + settings.url;
  1534. const files = yield _ZipLoader.unzip(reader, settings);
  1535. files.settings = settings;
  1536. context.source = files;
  1537. if (sourceURL.startsWith("blob:")) {
  1538. context.live2dModel.once("modelLoaded", (internalModel) => {
  1539. internalModel.once("destroy", function() {
  1540. URL.revokeObjectURL(sourceURL);
  1541. });
  1542. });
  1543. }
  1544. _ZipLoader.releaseReader(reader);
  1545. }
  1546. return next();
  1547. });
  1548. Live2DFactory.live2DModelMiddlewares.unshift(ZipLoader.factory);
  1549. if (!window.Live2D) {
  1550. throw new Error("Could not find Cubism 2 runtime. This plugin requires live2d.min.js to be loaded.");
  1551. }
  1552. const originalUpdateParam = Live2DMotion.prototype.updateParam;
  1553. Live2DMotion.prototype.updateParam = function(model, entry) {
  1554. originalUpdateParam.call(this, model, entry);
  1555. if (entry.isFinished() && this.onFinishHandler) {
  1556. this.onFinishHandler(this);
  1557. delete this.onFinishHandler;
  1558. }
  1559. };
  1560. class Live2DExpression extends AMotion {
  1561. constructor(json) {
  1562. super();
  1563. this.params = [];
  1564. this.setFadeIn(json.fade_in > 0 ? json.fade_in : config.expressionFadingDuration);
  1565. this.setFadeOut(json.fade_out > 0 ? json.fade_out : config.expressionFadingDuration);
  1566. if (Array.isArray(json.params)) {
  1567. json.params.forEach((param) => {
  1568. const calc = param.calc || "add";
  1569. if (calc === "add") {
  1570. const defaultValue = param.def || 0;
  1571. param.val -= defaultValue;
  1572. } else if (calc === "mult") {
  1573. const defaultValue = param.def || 1;
  1574. param.val /= defaultValue;
  1575. }
  1576. this.params.push({
  1577. calc,
  1578. val: param.val,
  1579. id: param.id
  1580. });
  1581. });
  1582. }
  1583. }
  1584. updateParamExe(model, time, weight, motionQueueEnt) {
  1585. this.params.forEach((param) => {
  1586. model.setParamFloat(param.id, param.val * weight);
  1587. });
  1588. }
  1589. }
  1590. class Cubism2ExpressionManager extends ExpressionManager {
  1591. constructor(settings, options) {
  1592. var _a;
  1593. super(settings, options);
  1594. this.queueManager = new MotionQueueManager();
  1595. this.definitions = (_a = this.settings.expressions) != null ? _a : [];
  1596. this.init();
  1597. }
  1598. isFinished() {
  1599. return this.queueManager.isFinished();
  1600. }
  1601. getExpressionIndex(name) {
  1602. return this.definitions.findIndex((def) => def.name === name);
  1603. }
  1604. getExpressionFile(definition) {
  1605. return definition.file;
  1606. }
  1607. createExpression(data, definition) {
  1608. return new Live2DExpression(data);
  1609. }
  1610. _setExpression(motion) {
  1611. return this.queueManager.startMotion(motion);
  1612. }
  1613. stopAllExpressions() {
  1614. this.queueManager.stopAllMotions();
  1615. }
  1616. updateParameters(model, dt) {
  1617. return this.queueManager.updateParam(model);
  1618. }
  1619. }
  1620. class Cubism2MotionManager extends MotionManager {
  1621. constructor(settings, options) {
  1622. super(settings, options);
  1623. this.groups = { idle: "idle" };
  1624. this.motionDataType = "arraybuffer";
  1625. this.queueManager = new MotionQueueManager();
  1626. this.definitions = this.settings.motions;
  1627. this.init(options);
  1628. }
  1629. init(options) {
  1630. super.init(options);
  1631. if (this.settings.expressions) {
  1632. this.expressionManager = new Cubism2ExpressionManager(this.settings, options);
  1633. }
  1634. }
  1635. isFinished() {
  1636. return this.queueManager.isFinished();
  1637. }
  1638. createMotion(data, group, definition) {
  1639. const motion = Live2DMotion.loadMotion(data);
  1640. const defaultFadingDuration = group === this.groups.idle ? config.idleMotionFadingDuration : config.motionFadingDuration;
  1641. motion.setFadeIn(definition.fade_in > 0 ? definition.fade_in : defaultFadingDuration);
  1642. motion.setFadeOut(definition.fade_out > 0 ? definition.fade_out : defaultFadingDuration);
  1643. return motion;
  1644. }
  1645. getMotionFile(definition) {
  1646. return definition.file;
  1647. }
  1648. getMotionName(definition) {
  1649. return definition.file;
  1650. }
  1651. getSoundFile(definition) {
  1652. return definition.sound;
  1653. }
  1654. _startMotion(motion, onFinish) {
  1655. motion.onFinishHandler = onFinish;
  1656. this.queueManager.stopAllMotions();
  1657. return this.queueManager.startMotion(motion);
  1658. }
  1659. _stopAllMotions() {
  1660. this.queueManager.stopAllMotions();
  1661. }
  1662. updateParameters(model, now) {
  1663. return this.queueManager.updateParam(model);
  1664. }
  1665. destroy() {
  1666. super.destroy();
  1667. this.queueManager = void 0;
  1668. }
  1669. }
  1670. class Live2DEyeBlink {
  1671. constructor(coreModel) {
  1672. this.coreModel = coreModel;
  1673. this.blinkInterval = 4e3;
  1674. this.closingDuration = 100;
  1675. this.closedDuration = 50;
  1676. this.openingDuration = 150;
  1677. this.eyeState = 0;
  1678. this.eyeParamValue = 1;
  1679. this.closedTimer = 0;
  1680. this.nextBlinkTimeLeft = this.blinkInterval;
  1681. this.leftParam = coreModel.getParamIndex("PARAM_EYE_L_OPEN");
  1682. this.rightParam = coreModel.getParamIndex("PARAM_EYE_R_OPEN");
  1683. }
  1684. setEyeParams(value) {
  1685. this.eyeParamValue = clamp(value, 0, 1);
  1686. this.coreModel.setParamFloat(this.leftParam, this.eyeParamValue);
  1687. this.coreModel.setParamFloat(this.rightParam, this.eyeParamValue);
  1688. }
  1689. update(dt) {
  1690. switch (this.eyeState) {
  1691. case 0:
  1692. this.nextBlinkTimeLeft -= dt;
  1693. if (this.nextBlinkTimeLeft < 0) {
  1694. this.eyeState = 1;
  1695. this.nextBlinkTimeLeft = this.blinkInterval + this.closingDuration + this.closedDuration + this.openingDuration + rand(0, 2e3);
  1696. }
  1697. break;
  1698. case 1:
  1699. this.setEyeParams(this.eyeParamValue + dt / this.closingDuration);
  1700. if (this.eyeParamValue <= 0) {
  1701. this.eyeState = 2;
  1702. this.closedTimer = 0;
  1703. }
  1704. break;
  1705. case 2:
  1706. this.closedTimer += dt;
  1707. if (this.closedTimer >= this.closedDuration) {
  1708. this.eyeState = 3;
  1709. }
  1710. break;
  1711. case 3:
  1712. this.setEyeParams(this.eyeParamValue + dt / this.openingDuration);
  1713. if (this.eyeParamValue >= 1) {
  1714. this.eyeState = 0;
  1715. }
  1716. }
  1717. }
  1718. }
  1719. const tempMatrixArray = new Float32Array([
  1720. 1,
  1721. 0,
  1722. 0,
  1723. 0,
  1724. 0,
  1725. 1,
  1726. 0,
  1727. 0,
  1728. 0,
  1729. 0,
  1730. 1,
  1731. 0,
  1732. 0,
  1733. 0,
  1734. 0,
  1735. 1
  1736. ]);
  1737. class Cubism2InternalModel extends InternalModel {
  1738. constructor(coreModel, settings, options) {
  1739. super();
  1740. this.textureFlipY = true;
  1741. this.drawDataCount = 0;
  1742. this.disableCulling = false;
  1743. this.coreModel = coreModel;
  1744. this.settings = settings;
  1745. this.motionManager = new Cubism2MotionManager(settings, options);
  1746. this.eyeBlink = new Live2DEyeBlink(coreModel);
  1747. this.eyeballXParamIndex = coreModel.getParamIndex("PARAM_EYE_BALL_X");
  1748. this.eyeballYParamIndex = coreModel.getParamIndex("PARAM_EYE_BALL_Y");
  1749. this.angleXParamIndex = coreModel.getParamIndex("PARAM_ANGLE_X");
  1750. this.angleYParamIndex = coreModel.getParamIndex("PARAM_ANGLE_Y");
  1751. this.angleZParamIndex = coreModel.getParamIndex("PARAM_ANGLE_Z");
  1752. this.bodyAngleXParamIndex = coreModel.getParamIndex("PARAM_BODY_ANGLE_X");
  1753. this.breathParamIndex = coreModel.getParamIndex("PARAM_BREATH");
  1754. this.init();
  1755. }
  1756. init() {
  1757. super.init();
  1758. if (this.settings.initParams) {
  1759. this.settings.initParams.forEach(({ id, value }) => this.coreModel.setParamFloat(id, value));
  1760. }
  1761. if (this.settings.initOpacities) {
  1762. this.settings.initOpacities.forEach(({ id, value }) => this.coreModel.setPartsOpacity(id, value));
  1763. }
  1764. this.coreModel.saveParam();
  1765. const arr = this.coreModel.getModelContext()._$aS;
  1766. if (arr == null ? void 0 : arr.length) {
  1767. this.drawDataCount = arr.length;
  1768. }
  1769. let culling = this.coreModel.drawParamWebGL.culling;
  1770. Object.defineProperty(this.coreModel.drawParamWebGL, "culling", {
  1771. set: (v) => culling = v,
  1772. get: () => this.disableCulling ? false : culling
  1773. });
  1774. const clipManager = this.coreModel.getModelContext().clipManager;
  1775. const originalSetupClip = clipManager.setupClip;
  1776. clipManager.setupClip = (modelContext, drawParam) => {
  1777. originalSetupClip.call(clipManager, modelContext, drawParam);
  1778. drawParam.gl.viewport(...this.viewport);
  1779. };
  1780. }
  1781. getSize() {
  1782. return [this.coreModel.getCanvasWidth(), this.coreModel.getCanvasHeight()];
  1783. }
  1784. getLayout() {
  1785. const layout = {};
  1786. if (this.settings.layout) {
  1787. for (const key of Object.keys(this.settings.layout)) {
  1788. let commonKey = key;
  1789. if (key === "center_x") {
  1790. commonKey = "centerX";
  1791. } else if (key === "center_y") {
  1792. commonKey = "centerY";
  1793. }
  1794. layout[commonKey] = this.settings.layout[key];
  1795. }
  1796. }
  1797. return layout;
  1798. }
  1799. updateWebGLContext(gl, glContextID) {
  1800. const drawParamWebGL = this.coreModel.drawParamWebGL;
  1801. drawParamWebGL.firstDraw = true;
  1802. drawParamWebGL.setGL(gl);
  1803. drawParamWebGL.glno = glContextID;
  1804. for (const prop in drawParamWebGL) {
  1805. if (drawParamWebGL.hasOwnProperty(prop) && drawParamWebGL[prop] instanceof WebGLBuffer) {
  1806. drawParamWebGL[prop] = null;
  1807. }
  1808. }
  1809. const clipManager = this.coreModel.getModelContext().clipManager;
  1810. clipManager.curFrameNo = glContextID;
  1811. const framebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  1812. clipManager.getMaskRenderTexture();
  1813. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  1814. }
  1815. bindTexture(index, texture) {
  1816. this.coreModel.setTexture(index, texture);
  1817. }
  1818. getHitAreaDefs() {
  1819. var _a;
  1820. return ((_a = this.settings.hitAreas) == null ? void 0 : _a.map((hitArea) => ({
  1821. id: hitArea.id,
  1822. name: hitArea.name,
  1823. index: this.coreModel.getDrawDataIndex(hitArea.id)
  1824. }))) || [];
  1825. }
  1826. getDrawableIDs() {
  1827. const modelContext = this.coreModel.getModelContext();
  1828. const ids = [];
  1829. for (let i = 0; i < this.drawDataCount; i++) {
  1830. const drawData = modelContext.getDrawData(i);
  1831. if (drawData) {
  1832. ids.push(drawData.getDrawDataID().id);
  1833. }
  1834. }
  1835. return ids;
  1836. }
  1837. getDrawableIndex(id) {
  1838. return this.coreModel.getDrawDataIndex(id);
  1839. }
  1840. getDrawableVertices(drawIndex) {
  1841. if (typeof drawIndex === "string") {
  1842. drawIndex = this.coreModel.getDrawDataIndex(drawIndex);
  1843. if (drawIndex === -1)
  1844. throw new TypeError("Unable to find drawable ID: " + drawIndex);
  1845. }
  1846. return this.coreModel.getTransformedPoints(drawIndex).slice();
  1847. }
  1848. update(dt, now) {
  1849. var _a, _b, _c, _d;
  1850. super.update(dt, now);
  1851. const model = this.coreModel;
  1852. this.emit("beforeMotionUpdate");
  1853. const motionUpdated = this.motionManager.update(this.coreModel, now);
  1854. this.emit("afterMotionUpdate");
  1855. model.saveParam();
  1856. (_a = this.motionManager.expressionManager) == null ? void 0 : _a.update(model, now);
  1857. if (!motionUpdated) {
  1858. (_b = this.eyeBlink) == null ? void 0 : _b.update(dt);
  1859. }
  1860. this.updateFocus();
  1861. this.updateNaturalMovements(dt, now);
  1862. (_c = this.physics) == null ? void 0 : _c.update(now);
  1863. (_d = this.pose) == null ? void 0 : _d.update(dt);
  1864. this.emit("beforeModelUpdate");
  1865. model.update();
  1866. model.loadParam();
  1867. }
  1868. updateFocus() {
  1869. this.coreModel.addToParamFloat(this.eyeballXParamIndex, this.focusController.x);
  1870. this.coreModel.addToParamFloat(this.eyeballYParamIndex, this.focusController.y);
  1871. this.coreModel.addToParamFloat(this.angleXParamIndex, this.focusController.x * 30);
  1872. this.coreModel.addToParamFloat(this.angleYParamIndex, this.focusController.y * 30);
  1873. this.coreModel.addToParamFloat(this.angleZParamIndex, this.focusController.x * this.focusController.y * -30);
  1874. this.coreModel.addToParamFloat(this.bodyAngleXParamIndex, this.focusController.x * 10);
  1875. }
  1876. updateNaturalMovements(dt, now) {
  1877. const t = now / 1e3 * 2 * Math.PI;
  1878. this.coreModel.addToParamFloat(this.angleXParamIndex, 15 * Math.sin(t / 6.5345) * 0.5);
  1879. this.coreModel.addToParamFloat(this.angleYParamIndex, 8 * Math.sin(t / 3.5345) * 0.5);
  1880. this.coreModel.addToParamFloat(this.angleZParamIndex, 10 * Math.sin(t / 5.5345) * 0.5);
  1881. this.coreModel.addToParamFloat(this.bodyAngleXParamIndex, 4 * Math.sin(t / 15.5345) * 0.5);
  1882. this.coreModel.setParamFloat(this.breathParamIndex, 0.5 + 0.5 * Math.sin(t / 3.2345));
  1883. }
  1884. draw(gl) {
  1885. const disableCulling = this.disableCulling;
  1886. if (gl.getParameter(gl.FRAMEBUFFER_BINDING)) {
  1887. this.disableCulling = true;
  1888. }
  1889. const matrix = this.drawingMatrix;
  1890. tempMatrixArray[0] = matrix.a;
  1891. tempMatrixArray[1] = matrix.b;
  1892. tempMatrixArray[4] = matrix.c;
  1893. tempMatrixArray[5] = matrix.d;
  1894. tempMatrixArray[12] = matrix.tx;
  1895. tempMatrixArray[13] = matrix.ty;
  1896. this.coreModel.setMatrix(tempMatrixArray);
  1897. this.coreModel.draw();
  1898. this.disableCulling = disableCulling;
  1899. }
  1900. destroy() {
  1901. super.destroy();
  1902. this.coreModel = void 0;
  1903. }
  1904. }
  1905. class Cubism2ModelSettings extends ModelSettings {
  1906. constructor(json) {
  1907. super(json);
  1908. this.motions = {};
  1909. if (!Cubism2ModelSettings.isValidJSON(json)) {
  1910. throw new TypeError("Invalid JSON.");
  1911. }
  1912. this.moc = json.model;
  1913. copyArray("string", json, this, "textures", "textures");
  1914. this.copy(json);
  1915. }
  1916. static isValidJSON(json) {
  1917. var _a;
  1918. return !!json && typeof json.model === "string" && ((_a = json.textures) == null ? void 0 : _a.length) > 0 && json.textures.every((item) => typeof item === "string");
  1919. }
  1920. copy(json) {
  1921. copyProperty("string", json, this, "name", "name");
  1922. copyProperty("string", json, this, "pose", "pose");
  1923. copyProperty("string", json, this, "physics", "physics");
  1924. copyProperty("object", json, this, "layout", "layout");
  1925. copyProperty("object", json, this, "motions", "motions");
  1926. copyArray("object", json, this, "hit_areas", "hitAreas");
  1927. copyArray("object", json, this, "expressions", "expressions");
  1928. copyArray("object", json, this, "init_params", "initParams");
  1929. copyArray("object", json, this, "init_opacities", "initOpacities");
  1930. }
  1931. replaceFiles(replace) {
  1932. super.replaceFiles(replace);
  1933. for (const [group, motions] of Object.entries(this.motions)) {
  1934. for (let i = 0; i < motions.length; i++) {
  1935. motions[i].file = replace(motions[i].file, `motions.${group}[${i}].file`);
  1936. if (motions[i].sound !== void 0) {
  1937. motions[i].sound = replace(motions[i].sound, `motions.${group}[${i}].sound`);
  1938. }
  1939. }
  1940. }
  1941. if (this.expressions) {
  1942. for (let i = 0; i < this.expressions.length; i++) {
  1943. this.expressions[i].file = replace(this.expressions[i].file, `expressions[${i}].file`);
  1944. }
  1945. }
  1946. }
  1947. }
  1948. const SRC_TYPE_MAP = {
  1949. x: PhysicsHair.Src.SRC_TO_X,
  1950. y: PhysicsHair.Src.SRC_TO_Y,
  1951. angle: PhysicsHair.Src.SRC_TO_G_ANGLE
  1952. };
  1953. const TARGET_TYPE_MAP = {
  1954. x: PhysicsHair.Src.SRC_TO_X,
  1955. y: PhysicsHair.Src.SRC_TO_Y,
  1956. angle: PhysicsHair.Src.SRC_TO_G_ANGLE
  1957. };
  1958. class Live2DPhysics {
  1959. constructor(coreModel, json) {
  1960. this.coreModel = coreModel;
  1961. this.physicsHairs = [];
  1962. if (json.physics_hair) {
  1963. this.physicsHairs = json.physics_hair.map((definition) => {
  1964. const physicsHair = new PhysicsHair();
  1965. physicsHair.setup(definition.setup.length, definition.setup.regist, definition.setup.mass);
  1966. definition.src.forEach(({ id, ptype, scale, weight }) => {
  1967. const type = SRC_TYPE_MAP[ptype];
  1968. if (type) {
  1969. physicsHair.addSrcParam(type, id, scale, weight);
  1970. }
  1971. });
  1972. definition.targets.forEach(({ id, ptype, scale, weight }) => {
  1973. const type = TARGET_TYPE_MAP[ptype];
  1974. if (type) {
  1975. physicsHair.addTargetParam(type, id, scale, weight);
  1976. }
  1977. });
  1978. return physicsHair;
  1979. });
  1980. }
  1981. }
  1982. update(elapsed) {
  1983. this.physicsHairs.forEach((physicsHair) => physicsHair.update(this.coreModel, elapsed));
  1984. }
  1985. }
  1986. class Live2DPartsParam {
  1987. constructor(id) {
  1988. this.id = id;
  1989. this.paramIndex = -1;
  1990. this.partsIndex = -1;
  1991. this.link = [];
  1992. }
  1993. initIndex(model) {
  1994. this.paramIndex = model.getParamIndex("VISIBLE:" + this.id);
  1995. this.partsIndex = model.getPartsDataIndex(PartsDataID.getID(this.id));
  1996. model.setParamFloat(this.paramIndex, 1);
  1997. }
  1998. }
  1999. class Live2DPose {
  2000. constructor(coreModel, json) {
  2001. this.coreModel = coreModel;
  2002. this.opacityAnimDuration = 500;
  2003. this.partsGroups = [];
  2004. if (json.parts_visible) {
  2005. this.partsGroups = json.parts_visible.map(({ group }) => group.map(({ id, link }) => {
  2006. const parts = new Live2DPartsParam(id);
  2007. if (link) {
  2008. parts.link = link.map((l) => new Live2DPartsParam(l));
  2009. }
  2010. return parts;
  2011. }));
  2012. this.init();
  2013. }
  2014. }
  2015. init() {
  2016. this.partsGroups.forEach((group) => {
  2017. group.forEach((parts) => {
  2018. parts.initIndex(this.coreModel);
  2019. if (parts.paramIndex >= 0) {
  2020. const visible = this.coreModel.getParamFloat(parts.paramIndex) !== 0;
  2021. this.coreModel.setPartsOpacity(parts.partsIndex, visible ? 1 : 0);
  2022. this.coreModel.setParamFloat(parts.paramIndex, visible ? 1 : 0);
  2023. if (parts.link.length > 0) {
  2024. parts.link.forEach((p) => p.initIndex(this.coreModel));
  2025. }
  2026. }
  2027. });
  2028. });
  2029. }
  2030. normalizePartsOpacityGroup(partsGroup, dt) {
  2031. const model = this.coreModel;
  2032. const phi = 0.5;
  2033. const maxBackOpacity = 0.15;
  2034. let visibleOpacity = 1;
  2035. let visibleIndex = partsGroup.findIndex(({ paramIndex, partsIndex }) => partsIndex >= 0 && model.getParamFloat(paramIndex) !== 0);
  2036. if (visibleIndex >= 0) {
  2037. const originalOpacity = model.getPartsOpacity(partsGroup[visibleIndex].partsIndex);
  2038. visibleOpacity = clamp(originalOpacity + dt / this.opacityAnimDuration, 0, 1);
  2039. } else {
  2040. visibleIndex = 0;
  2041. visibleOpacity = 1;
  2042. }
  2043. partsGroup.forEach(({ partsIndex }, index) => {
  2044. if (partsIndex >= 0) {
  2045. if (visibleIndex == index) {
  2046. model.setPartsOpacity(partsIndex, visibleOpacity);
  2047. } else {
  2048. let opacity = model.getPartsOpacity(partsIndex);
  2049. let a1;
  2050. if (visibleOpacity < phi) {
  2051. a1 = visibleOpacity * (phi - 1) / phi + 1;
  2052. } else {
  2053. a1 = (1 - visibleOpacity) * phi / (1 - phi);
  2054. }
  2055. let backOp = (1 - a1) * (1 - visibleOpacity);
  2056. if (backOp > maxBackOpacity) {
  2057. a1 = 1 - maxBackOpacity / (1 - visibleOpacity);
  2058. }
  2059. if (opacity > a1) {
  2060. opacity = a1;
  2061. }
  2062. model.setPartsOpacity(partsIndex, opacity);
  2063. }
  2064. }
  2065. });
  2066. }
  2067. copyOpacity(partsGroup) {
  2068. const model = this.coreModel;
  2069. partsGroup.forEach(({ partsIndex, link }) => {
  2070. if (partsIndex >= 0 && link) {
  2071. const opacity = model.getPartsOpacity(partsIndex);
  2072. link.forEach(({ partsIndex: partsIndex2 }) => {
  2073. if (partsIndex2 >= 0) {
  2074. model.setPartsOpacity(partsIndex2, opacity);
  2075. }
  2076. });
  2077. }
  2078. });
  2079. }
  2080. update(dt) {
  2081. this.partsGroups.forEach((partGroup) => {
  2082. this.normalizePartsOpacityGroup(partGroup, dt);
  2083. this.copyOpacity(partGroup);
  2084. });
  2085. }
  2086. }
  2087. Live2DFactory.registerRuntime({
  2088. version: 2,
  2089. test(source) {
  2090. return source instanceof Cubism2ModelSettings || Cubism2ModelSettings.isValidJSON(source);
  2091. },
  2092. ready() {
  2093. return Promise.resolve();
  2094. },
  2095. isValidMoc(modelData) {
  2096. if (modelData.byteLength < 3) {
  2097. return false;
  2098. }
  2099. const view = new Int8Array(modelData, 0, 3);
  2100. return String.fromCharCode(...view) === "moc";
  2101. },
  2102. createModelSettings(json) {
  2103. return new Cubism2ModelSettings(json);
  2104. },
  2105. createCoreModel(data) {
  2106. const model = Live2DModelWebGL.loadModel(data);
  2107. const error = Live2D.getError();
  2108. if (error)
  2109. throw error;
  2110. return model;
  2111. },
  2112. createInternalModel(coreModel, settings, options) {
  2113. return new Cubism2InternalModel(coreModel, settings, options);
  2114. },
  2115. createPose(coreModel, data) {
  2116. return new Live2DPose(coreModel, data);
  2117. },
  2118. createPhysics(coreModel, data) {
  2119. return new Live2DPhysics(coreModel, data);
  2120. }
  2121. });
  2122. if (!window.Live2DCubismCore) {
  2123. throw new Error("Could not find Cubism 4 runtime. This plugin requires live2dcubismcore.js to be loaded.");
  2124. }
  2125. class CubismVector2 {
  2126. constructor(x, y) {
  2127. this.x = x || 0;
  2128. this.y = y || 0;
  2129. }
  2130. add(vector2) {
  2131. const ret = new CubismVector2(0, 0);
  2132. ret.x = this.x + vector2.x;
  2133. ret.y = this.y + vector2.y;
  2134. return ret;
  2135. }
  2136. substract(vector2) {
  2137. const ret = new CubismVector2(0, 0);
  2138. ret.x = this.x - vector2.x;
  2139. ret.y = this.y - vector2.y;
  2140. return ret;
  2141. }
  2142. multiply(vector2) {
  2143. const ret = new CubismVector2(0, 0);
  2144. ret.x = this.x * vector2.x;
  2145. ret.y = this.y * vector2.y;
  2146. return ret;
  2147. }
  2148. multiplyByScaler(scalar) {
  2149. return this.multiply(new CubismVector2(scalar, scalar));
  2150. }
  2151. division(vector2) {
  2152. const ret = new CubismVector2(0, 0);
  2153. ret.x = this.x / vector2.x;
  2154. ret.y = this.y / vector2.y;
  2155. return ret;
  2156. }
  2157. divisionByScalar(scalar) {
  2158. return this.division(new CubismVector2(scalar, scalar));
  2159. }
  2160. getLength() {
  2161. return Math.sqrt(this.x * this.x + this.y * this.y);
  2162. }
  2163. getDistanceWith(a) {
  2164. return Math.sqrt((this.x - a.x) * (this.x - a.x) + (this.y - a.y) * (this.y - a.y));
  2165. }
  2166. dot(a) {
  2167. return this.x * a.x + this.y * a.y;
  2168. }
  2169. normalize() {
  2170. const length = Math.pow(this.x * this.x + this.y * this.y, 0.5);
  2171. this.x = this.x / length;
  2172. this.y = this.y / length;
  2173. }
  2174. isEqual(rhs) {
  2175. return this.x == rhs.x && this.y == rhs.y;
  2176. }
  2177. isNotEqual(rhs) {
  2178. return !this.isEqual(rhs);
  2179. }
  2180. }
  2181. const _CubismMath = class {
  2182. static range(value, min, max) {
  2183. if (value < min) {
  2184. value = min;
  2185. } else if (value > max) {
  2186. value = max;
  2187. }
  2188. return value;
  2189. }
  2190. static sin(x) {
  2191. return Math.sin(x);
  2192. }
  2193. static cos(x) {
  2194. return Math.cos(x);
  2195. }
  2196. static abs(x) {
  2197. return Math.abs(x);
  2198. }
  2199. static sqrt(x) {
  2200. return Math.sqrt(x);
  2201. }
  2202. static cbrt(x) {
  2203. if (x === 0) {
  2204. return x;
  2205. }
  2206. let cx = x;
  2207. const isNegativeNumber = cx < 0;
  2208. if (isNegativeNumber) {
  2209. cx = -cx;
  2210. }
  2211. let ret;
  2212. if (cx === Infinity) {
  2213. ret = Infinity;
  2214. } else {
  2215. ret = Math.exp(Math.log(cx) / 3);
  2216. ret = (cx / (ret * ret) + 2 * ret) / 3;
  2217. }
  2218. return isNegativeNumber ? -ret : ret;
  2219. }
  2220. static getEasingSine(value) {
  2221. if (value < 0) {
  2222. return 0;
  2223. } else if (value > 1) {
  2224. return 1;
  2225. }
  2226. return 0.5 - 0.5 * this.cos(value * Math.PI);
  2227. }
  2228. static max(left, right) {
  2229. return left > right ? left : right;
  2230. }
  2231. static min(left, right) {
  2232. return left > right ? right : left;
  2233. }
  2234. static degreesToRadian(degrees) {
  2235. return degrees / 180 * Math.PI;
  2236. }
  2237. static radianToDegrees(radian) {
  2238. return radian * 180 / Math.PI;
  2239. }
  2240. static directionToRadian(from, to) {
  2241. const q1 = Math.atan2(to.y, to.x);
  2242. const q2 = Math.atan2(from.y, from.x);
  2243. let ret = q1 - q2;
  2244. while (ret < -Math.PI) {
  2245. ret += Math.PI * 2;
  2246. }
  2247. while (ret > Math.PI) {
  2248. ret -= Math.PI * 2;
  2249. }
  2250. return ret;
  2251. }
  2252. static directionToDegrees(from, to) {
  2253. const radian = this.directionToRadian(from, to);
  2254. let degree = this.radianToDegrees(radian);
  2255. if (to.x - from.x > 0) {
  2256. degree = -degree;
  2257. }
  2258. return degree;
  2259. }
  2260. static radianToDirection(totalAngle) {
  2261. const ret = new CubismVector2();
  2262. ret.x = this.sin(totalAngle);
  2263. ret.y = this.cos(totalAngle);
  2264. return ret;
  2265. }
  2266. static quadraticEquation(a, b, c) {
  2267. if (this.abs(a) < _CubismMath.Epsilon) {
  2268. if (this.abs(b) < _CubismMath.Epsilon) {
  2269. return -c;
  2270. }
  2271. return -c / b;
  2272. }
  2273. return -(b + this.sqrt(b * b - 4 * a * c)) / (2 * a);
  2274. }
  2275. static cardanoAlgorithmForBezier(a, b, c, d) {
  2276. if (this.sqrt(a) < _CubismMath.Epsilon) {
  2277. return this.range(this.quadraticEquation(b, c, d), 0, 1);
  2278. }
  2279. const ba = b / a;
  2280. const ca = c / a;
  2281. const da = d / a;
  2282. const p = (3 * ca - ba * ba) / 3;
  2283. const p3 = p / 3;
  2284. const q = (2 * ba * ba * ba - 9 * ba * ca + 27 * da) / 27;
  2285. const q2 = q / 2;
  2286. const discriminant = q2 * q2 + p3 * p3 * p3;
  2287. const center = 0.5;
  2288. const threshold = center + 0.01;
  2289. if (discriminant < 0) {
  2290. const mp3 = -p / 3;
  2291. const mp33 = mp3 * mp3 * mp3;
  2292. const r = this.sqrt(mp33);
  2293. const t = -q / (2 * r);
  2294. const cosphi = this.range(t, -1, 1);
  2295. const phi = Math.acos(cosphi);
  2296. const crtr = this.cbrt(r);
  2297. const t1 = 2 * crtr;
  2298. const root12 = t1 * this.cos(phi / 3) - ba / 3;
  2299. if (this.abs(root12 - center) < threshold) {
  2300. return this.range(root12, 0, 1);
  2301. }
  2302. const root2 = t1 * this.cos((phi + 2 * Math.PI) / 3) - ba / 3;
  2303. if (this.abs(root2 - center) < threshold) {
  2304. return this.range(root2, 0, 1);
  2305. }
  2306. const root3 = t1 * this.cos((phi + 4 * Math.PI) / 3) - ba / 3;
  2307. return this.range(root3, 0, 1);
  2308. }
  2309. if (discriminant == 0) {
  2310. let u12;
  2311. if (q2 < 0) {
  2312. u12 = this.cbrt(-q2);
  2313. } else {
  2314. u12 = -this.cbrt(q2);
  2315. }
  2316. const root12 = 2 * u12 - ba / 3;
  2317. if (this.abs(root12 - center) < threshold) {
  2318. return this.range(root12, 0, 1);
  2319. }
  2320. const root2 = -u12 - ba / 3;
  2321. return this.range(root2, 0, 1);
  2322. }
  2323. const sd = this.sqrt(discriminant);
  2324. const u1 = this.cbrt(sd - q2);
  2325. const v1 = this.cbrt(sd + q2);
  2326. const root1 = u1 - v1 - ba / 3;
  2327. return this.range(root1, 0, 1);
  2328. }
  2329. constructor() {
  2330. }
  2331. };
  2332. let CubismMath = _CubismMath;
  2333. CubismMath.Epsilon = 1e-5;
  2334. class CubismMatrix44 {
  2335. constructor() {
  2336. this._tr = new Float32Array(16);
  2337. this.loadIdentity();
  2338. }
  2339. static multiply(a, b, dst) {
  2340. const c = new Float32Array([
  2341. 0,
  2342. 0,
  2343. 0,
  2344. 0,
  2345. 0,
  2346. 0,
  2347. 0,
  2348. 0,
  2349. 0,
  2350. 0,
  2351. 0,
  2352. 0,
  2353. 0,
  2354. 0,
  2355. 0,
  2356. 0
  2357. ]);
  2358. const n = 4;
  2359. for (let i = 0; i < n; ++i) {
  2360. for (let j = 0; j < n; ++j) {
  2361. for (let k = 0; k < n; ++k) {
  2362. c[j + i * 4] += a[k + i * 4] * b[j + k * 4];
  2363. }
  2364. }
  2365. }
  2366. for (let i = 0; i < 16; ++i) {
  2367. dst[i] = c[i];
  2368. }
  2369. }
  2370. loadIdentity() {
  2371. const c = new Float32Array([
  2372. 1,
  2373. 0,
  2374. 0,
  2375. 0,
  2376. 0,
  2377. 1,
  2378. 0,
  2379. 0,
  2380. 0,
  2381. 0,
  2382. 1,
  2383. 0,
  2384. 0,
  2385. 0,
  2386. 0,
  2387. 1
  2388. ]);
  2389. this.setMatrix(c);
  2390. }
  2391. setMatrix(tr) {
  2392. for (let i = 0; i < 16; ++i) {
  2393. this._tr[i] = tr[i];
  2394. }
  2395. }
  2396. getArray() {
  2397. return this._tr;
  2398. }
  2399. getScaleX() {
  2400. return this._tr[0];
  2401. }
  2402. getScaleY() {
  2403. return this._tr[5];
  2404. }
  2405. getTranslateX() {
  2406. return this._tr[12];
  2407. }
  2408. getTranslateY() {
  2409. return this._tr[13];
  2410. }
  2411. transformX(src) {
  2412. return this._tr[0] * src + this._tr[12];
  2413. }
  2414. transformY(src) {
  2415. return this._tr[5] * src + this._tr[13];
  2416. }
  2417. invertTransformX(src) {
  2418. return (src - this._tr[12]) / this._tr[0];
  2419. }
  2420. invertTransformY(src) {
  2421. return (src - this._tr[13]) / this._tr[5];
  2422. }
  2423. translateRelative(x, y) {
  2424. const tr1 = new Float32Array([
  2425. 1,
  2426. 0,
  2427. 0,
  2428. 0,
  2429. 0,
  2430. 1,
  2431. 0,
  2432. 0,
  2433. 0,
  2434. 0,
  2435. 1,
  2436. 0,
  2437. x,
  2438. y,
  2439. 0,
  2440. 1
  2441. ]);
  2442. CubismMatrix44.multiply(tr1, this._tr, this._tr);
  2443. }
  2444. translate(x, y) {
  2445. this._tr[12] = x;
  2446. this._tr[13] = y;
  2447. }
  2448. translateX(x) {
  2449. this._tr[12] = x;
  2450. }
  2451. translateY(y) {
  2452. this._tr[13] = y;
  2453. }
  2454. scaleRelative(x, y) {
  2455. const tr1 = new Float32Array([
  2456. x,
  2457. 0,
  2458. 0,
  2459. 0,
  2460. 0,
  2461. y,
  2462. 0,
  2463. 0,
  2464. 0,
  2465. 0,
  2466. 1,
  2467. 0,
  2468. 0,
  2469. 0,
  2470. 0,
  2471. 1
  2472. ]);
  2473. CubismMatrix44.multiply(tr1, this._tr, this._tr);
  2474. }
  2475. scale(x, y) {
  2476. this._tr[0] = x;
  2477. this._tr[5] = y;
  2478. }
  2479. multiplyByMatrix(m) {
  2480. CubismMatrix44.multiply(m.getArray(), this._tr, this._tr);
  2481. }
  2482. clone() {
  2483. const cloneMatrix = new CubismMatrix44();
  2484. for (let i = 0; i < this._tr.length; i++) {
  2485. cloneMatrix._tr[i] = this._tr[i];
  2486. }
  2487. return cloneMatrix;
  2488. }
  2489. }
  2490. class CubismRenderer {
  2491. initialize(model) {
  2492. this._model = model;
  2493. }
  2494. drawModel() {
  2495. if (this.getModel() == null)
  2496. return;
  2497. this.doDrawModel();
  2498. }
  2499. setMvpMatrix(matrix44) {
  2500. this._mvpMatrix4x4.setMatrix(matrix44.getArray());
  2501. }
  2502. getMvpMatrix() {
  2503. return this._mvpMatrix4x4;
  2504. }
  2505. setModelColor(red, green, blue, alpha) {
  2506. if (red < 0) {
  2507. red = 0;
  2508. } else if (red > 1) {
  2509. red = 1;
  2510. }
  2511. if (green < 0) {
  2512. green = 0;
  2513. } else if (green > 1) {
  2514. green = 1;
  2515. }
  2516. if (blue < 0) {
  2517. blue = 0;
  2518. } else if (blue > 1) {
  2519. blue = 1;
  2520. }
  2521. if (alpha < 0) {
  2522. alpha = 0;
  2523. } else if (alpha > 1) {
  2524. alpha = 1;
  2525. }
  2526. this._modelColor.R = red;
  2527. this._modelColor.G = green;
  2528. this._modelColor.B = blue;
  2529. this._modelColor.A = alpha;
  2530. }
  2531. getModelColor() {
  2532. return Object.assign({}, this._modelColor);
  2533. }
  2534. setIsPremultipliedAlpha(enable) {
  2535. this._isPremultipliedAlpha = enable;
  2536. }
  2537. isPremultipliedAlpha() {
  2538. return this._isPremultipliedAlpha;
  2539. }
  2540. setIsCulling(culling) {
  2541. this._isCulling = culling;
  2542. }
  2543. isCulling() {
  2544. return this._isCulling;
  2545. }
  2546. setAnisotropy(n) {
  2547. this._anisortopy = n;
  2548. }
  2549. getAnisotropy() {
  2550. return this._anisortopy;
  2551. }
  2552. getModel() {
  2553. return this._model;
  2554. }
  2555. constructor() {
  2556. this._isCulling = false;
  2557. this._isPremultipliedAlpha = false;
  2558. this._anisortopy = 0;
  2559. this._modelColor = new CubismTextureColor();
  2560. this._mvpMatrix4x4 = new CubismMatrix44();
  2561. this._mvpMatrix4x4.loadIdentity();
  2562. }
  2563. }
  2564. var CubismBlendMode = /* @__PURE__ */ ((CubismBlendMode2) => {
  2565. CubismBlendMode2[CubismBlendMode2["CubismBlendMode_Normal"] = 0] = "CubismBlendMode_Normal";
  2566. CubismBlendMode2[CubismBlendMode2["CubismBlendMode_Additive"] = 1] = "CubismBlendMode_Additive";
  2567. CubismBlendMode2[CubismBlendMode2["CubismBlendMode_Multiplicative"] = 2] = "CubismBlendMode_Multiplicative";
  2568. return CubismBlendMode2;
  2569. })(CubismBlendMode || {});
  2570. class CubismTextureColor {
  2571. constructor() {
  2572. this.R = 1;
  2573. this.G = 1;
  2574. this.B = 1;
  2575. this.A = 1;
  2576. }
  2577. }
  2578. let s_isStarted = false;
  2579. let s_isInitialized = false;
  2580. let s_option = void 0;
  2581. const Constant = {
  2582. vertexOffset: 0,
  2583. vertexStep: 2
  2584. };
  2585. class CubismFramework {
  2586. static startUp(option) {
  2587. if (s_isStarted) {
  2588. CubismLogInfo("CubismFramework.startUp() is already done.");
  2589. return s_isStarted;
  2590. }
  2591. if (Live2DCubismCore._isStarted) {
  2592. s_isStarted = true;
  2593. return true;
  2594. }
  2595. Live2DCubismCore._isStarted = true;
  2596. s_option = option;
  2597. if (s_option) {
  2598. Live2DCubismCore.Logging.csmSetLogFunction(s_option.logFunction);
  2599. }
  2600. s_isStarted = true;
  2601. if (s_isStarted) {
  2602. const version = Live2DCubismCore.Version.csmGetVersion();
  2603. const major = (version & 4278190080) >> 24;
  2604. const minor = (version & 16711680) >> 16;
  2605. const patch = version & 65535;
  2606. const versionNumber = version;
  2607. CubismLogInfo(`Live2D Cubism Core version: {0}.{1}.{2} ({3})`, ("00" + major).slice(-2), ("00" + minor).slice(-2), ("0000" + patch).slice(-4), versionNumber);
  2608. }
  2609. CubismLogInfo("CubismFramework.startUp() is complete.");
  2610. return s_isStarted;
  2611. }
  2612. static cleanUp() {
  2613. s_isStarted = false;
  2614. s_isInitialized = false;
  2615. s_option = void 0;
  2616. }
  2617. static initialize() {
  2618. if (!s_isStarted) {
  2619. CubismLogWarning("CubismFramework is not started.");
  2620. return;
  2621. }
  2622. if (s_isInitialized) {
  2623. CubismLogWarning("CubismFramework.initialize() skipped, already initialized.");
  2624. return;
  2625. }
  2626. s_isInitialized = true;
  2627. CubismLogInfo("CubismFramework.initialize() is complete.");
  2628. }
  2629. static dispose() {
  2630. if (!s_isStarted) {
  2631. CubismLogWarning("CubismFramework is not started.");
  2632. return;
  2633. }
  2634. if (!s_isInitialized) {
  2635. CubismLogWarning("CubismFramework.dispose() skipped, not initialized.");
  2636. return;
  2637. }
  2638. CubismRenderer.staticRelease();
  2639. s_isInitialized = false;
  2640. CubismLogInfo("CubismFramework.dispose() is complete.");
  2641. }
  2642. static isStarted() {
  2643. return s_isStarted;
  2644. }
  2645. static isInitialized() {
  2646. return s_isInitialized;
  2647. }
  2648. static coreLogFunction(message) {
  2649. if (!Live2DCubismCore.Logging.csmGetLogFunction()) {
  2650. return;
  2651. }
  2652. Live2DCubismCore.Logging.csmGetLogFunction()(message);
  2653. }
  2654. static getLoggingLevel() {
  2655. if (s_option != null) {
  2656. return s_option.loggingLevel;
  2657. }
  2658. return LogLevel.LogLevel_Off;
  2659. }
  2660. constructor() {
  2661. }
  2662. }
  2663. var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
  2664. LogLevel2[LogLevel2["LogLevel_Verbose"] = 0] = "LogLevel_Verbose";
  2665. LogLevel2[LogLevel2["LogLevel_Debug"] = 1] = "LogLevel_Debug";
  2666. LogLevel2[LogLevel2["LogLevel_Info"] = 2] = "LogLevel_Info";
  2667. LogLevel2[LogLevel2["LogLevel_Warning"] = 3] = "LogLevel_Warning";
  2668. LogLevel2[LogLevel2["LogLevel_Error"] = 4] = "LogLevel_Error";
  2669. LogLevel2[LogLevel2["LogLevel_Off"] = 5] = "LogLevel_Off";
  2670. return LogLevel2;
  2671. })(LogLevel || {});
  2672. const CSM_ASSERT = () => {
  2673. };
  2674. function CubismLogDebug(fmt, ...args) {
  2675. CubismDebug.print(LogLevel.LogLevel_Debug, "[CSM][D]" + fmt + "\n", args);
  2676. }
  2677. function CubismLogInfo(fmt, ...args) {
  2678. CubismDebug.print(LogLevel.LogLevel_Info, "[CSM][I]" + fmt + "\n", args);
  2679. }
  2680. function CubismLogWarning(fmt, ...args) {
  2681. CubismDebug.print(LogLevel.LogLevel_Warning, "[CSM][W]" + fmt + "\n", args);
  2682. }
  2683. function CubismLogError(fmt, ...args) {
  2684. CubismDebug.print(LogLevel.LogLevel_Error, "[CSM][E]" + fmt + "\n", args);
  2685. }
  2686. class CubismDebug {
  2687. static print(logLevel, format, args) {
  2688. if (logLevel < CubismFramework.getLoggingLevel()) {
  2689. return;
  2690. }
  2691. const logPrint = CubismFramework.coreLogFunction;
  2692. if (!logPrint)
  2693. return;
  2694. const buffer = format.replace(/{(\d+)}/g, (m, k) => {
  2695. return args[k];
  2696. });
  2697. logPrint(buffer);
  2698. }
  2699. static dumpBytes(logLevel, data, length) {
  2700. for (let i = 0; i < length; i++) {
  2701. if (i % 16 == 0 && i > 0)
  2702. this.print(logLevel, "\n");
  2703. else if (i % 8 == 0 && i > 0)
  2704. this.print(logLevel, " ");
  2705. this.print(logLevel, "{0} ", [data[i] & 255]);
  2706. }
  2707. this.print(logLevel, "\n");
  2708. }
  2709. constructor() {
  2710. }
  2711. }
  2712. class ACubismMotion {
  2713. constructor() {
  2714. this._fadeInSeconds = -1;
  2715. this._fadeOutSeconds = -1;
  2716. this._weight = 1;
  2717. this._offsetSeconds = 0;
  2718. this._firedEventValues = [];
  2719. }
  2720. release() {
  2721. this._weight = 0;
  2722. }
  2723. updateParameters(model, motionQueueEntry, userTimeSeconds) {
  2724. if (!motionQueueEntry.isAvailable() || motionQueueEntry.isFinished()) {
  2725. return;
  2726. }
  2727. if (!motionQueueEntry.isStarted()) {
  2728. motionQueueEntry.setIsStarted(true);
  2729. motionQueueEntry.setStartTime(userTimeSeconds - this._offsetSeconds);
  2730. motionQueueEntry.setFadeInStartTime(userTimeSeconds);
  2731. const duration = this.getDuration();
  2732. if (motionQueueEntry.getEndTime() < 0) {
  2733. motionQueueEntry.setEndTime(duration <= 0 ? -1 : motionQueueEntry.getStartTime() + duration);
  2734. }
  2735. }
  2736. let fadeWeight = this._weight;
  2737. const fadeIn = this._fadeInSeconds == 0 ? 1 : CubismMath.getEasingSine((userTimeSeconds - motionQueueEntry.getFadeInStartTime()) / this._fadeInSeconds);
  2738. const fadeOut = this._fadeOutSeconds == 0 || motionQueueEntry.getEndTime() < 0 ? 1 : CubismMath.getEasingSine((motionQueueEntry.getEndTime() - userTimeSeconds) / this._fadeOutSeconds);
  2739. fadeWeight = fadeWeight * fadeIn * fadeOut;
  2740. motionQueueEntry.setState(userTimeSeconds, fadeWeight);
  2741. this.doUpdateParameters(model, userTimeSeconds, fadeWeight, motionQueueEntry);
  2742. if (motionQueueEntry.getEndTime() > 0 && motionQueueEntry.getEndTime() < userTimeSeconds) {
  2743. motionQueueEntry.setIsFinished(true);
  2744. }
  2745. }
  2746. setFadeInTime(fadeInSeconds) {
  2747. this._fadeInSeconds = fadeInSeconds;
  2748. }
  2749. setFadeOutTime(fadeOutSeconds) {
  2750. this._fadeOutSeconds = fadeOutSeconds;
  2751. }
  2752. getFadeOutTime() {
  2753. return this._fadeOutSeconds;
  2754. }
  2755. getFadeInTime() {
  2756. return this._fadeInSeconds;
  2757. }
  2758. setWeight(weight) {
  2759. this._weight = weight;
  2760. }
  2761. getWeight() {
  2762. return this._weight;
  2763. }
  2764. getDuration() {
  2765. return -1;
  2766. }
  2767. getLoopDuration() {
  2768. return -1;
  2769. }
  2770. setOffsetTime(offsetSeconds) {
  2771. this._offsetSeconds = offsetSeconds;
  2772. }
  2773. getFiredEvent(beforeCheckTimeSeconds, motionTimeSeconds) {
  2774. return this._firedEventValues;
  2775. }
  2776. setFinishedMotionHandler(onFinishedMotionHandler) {
  2777. this._onFinishedMotion = onFinishedMotionHandler;
  2778. }
  2779. getFinishedMotionHandler() {
  2780. return this._onFinishedMotion;
  2781. }
  2782. }
  2783. const DefaultFadeTime = 1;
  2784. class CubismExpressionMotion extends ACubismMotion {
  2785. constructor() {
  2786. super();
  2787. this._parameters = [];
  2788. }
  2789. static create(json) {
  2790. const expression = new CubismExpressionMotion();
  2791. const fadeInTime = json.FadeInTime;
  2792. const fadeOutTime = json.FadeOutTime;
  2793. expression.setFadeInTime(fadeInTime !== void 0 ? fadeInTime : DefaultFadeTime);
  2794. expression.setFadeOutTime(fadeOutTime !== void 0 ? fadeOutTime : DefaultFadeTime);
  2795. const parameters = json.Parameters || [];
  2796. for (let i = 0; i < parameters.length; ++i) {
  2797. const param = parameters[i];
  2798. const parameterId = param.Id;
  2799. const value = param.Value;
  2800. let blendType;
  2801. switch (param.Blend) {
  2802. case "Multiply":
  2803. blendType = ExpressionBlendType.ExpressionBlendType_Multiply;
  2804. break;
  2805. case "Overwrite":
  2806. blendType = ExpressionBlendType.ExpressionBlendType_Overwrite;
  2807. break;
  2808. case "Add":
  2809. default:
  2810. blendType = ExpressionBlendType.ExpressionBlendType_Add;
  2811. break;
  2812. }
  2813. const item = {
  2814. parameterId,
  2815. blendType,
  2816. value
  2817. };
  2818. expression._parameters.push(item);
  2819. }
  2820. return expression;
  2821. }
  2822. doUpdateParameters(model, userTimeSeconds, weight, motionQueueEntry) {
  2823. for (let i = 0; i < this._parameters.length; ++i) {
  2824. const parameter = this._parameters[i];
  2825. switch (parameter.blendType) {
  2826. case ExpressionBlendType.ExpressionBlendType_Add: {
  2827. model.addParameterValueById(parameter.parameterId, parameter.value, weight);
  2828. break;
  2829. }
  2830. case ExpressionBlendType.ExpressionBlendType_Multiply: {
  2831. model.multiplyParameterValueById(parameter.parameterId, parameter.value, weight);
  2832. break;
  2833. }
  2834. case ExpressionBlendType.ExpressionBlendType_Overwrite: {
  2835. model.setParameterValueById(parameter.parameterId, parameter.value, weight);
  2836. break;
  2837. }
  2838. }
  2839. }
  2840. }
  2841. }
  2842. var ExpressionBlendType = /* @__PURE__ */ ((ExpressionBlendType2) => {
  2843. ExpressionBlendType2[ExpressionBlendType2["ExpressionBlendType_Add"] = 0] = "ExpressionBlendType_Add";
  2844. ExpressionBlendType2[ExpressionBlendType2["ExpressionBlendType_Multiply"] = 1] = "ExpressionBlendType_Multiply";
  2845. ExpressionBlendType2[ExpressionBlendType2["ExpressionBlendType_Overwrite"] = 2] = "ExpressionBlendType_Overwrite";
  2846. return ExpressionBlendType2;
  2847. })(ExpressionBlendType || {});
  2848. class CubismMotionQueueEntry {
  2849. constructor() {
  2850. this._autoDelete = false;
  2851. this._available = true;
  2852. this._finished = false;
  2853. this._started = false;
  2854. this._startTimeSeconds = -1;
  2855. this._fadeInStartTimeSeconds = 0;
  2856. this._endTimeSeconds = -1;
  2857. this._stateTimeSeconds = 0;
  2858. this._stateWeight = 0;
  2859. this._lastEventCheckSeconds = 0;
  2860. this._motionQueueEntryHandle = this;
  2861. this._fadeOutSeconds = 0;
  2862. this._isTriggeredFadeOut = false;
  2863. }
  2864. release() {
  2865. if (this._autoDelete && this._motion) {
  2866. this._motion.release();
  2867. }
  2868. }
  2869. setFadeOut(fadeOutSeconds) {
  2870. this._fadeOutSeconds = fadeOutSeconds;
  2871. this._isTriggeredFadeOut = true;
  2872. }
  2873. startFadeOut(fadeOutSeconds, userTimeSeconds) {
  2874. const newEndTimeSeconds = userTimeSeconds + fadeOutSeconds;
  2875. this._isTriggeredFadeOut = true;
  2876. if (this._endTimeSeconds < 0 || newEndTimeSeconds < this._endTimeSeconds) {
  2877. this._endTimeSeconds = newEndTimeSeconds;
  2878. }
  2879. }
  2880. isFinished() {
  2881. return this._finished;
  2882. }
  2883. isStarted() {
  2884. return this._started;
  2885. }
  2886. getStartTime() {
  2887. return this._startTimeSeconds;
  2888. }
  2889. getFadeInStartTime() {
  2890. return this._fadeInStartTimeSeconds;
  2891. }
  2892. getEndTime() {
  2893. return this._endTimeSeconds;
  2894. }
  2895. setStartTime(startTime) {
  2896. this._startTimeSeconds = startTime;
  2897. }
  2898. setFadeInStartTime(startTime) {
  2899. this._fadeInStartTimeSeconds = startTime;
  2900. }
  2901. setEndTime(endTime) {
  2902. this._endTimeSeconds = endTime;
  2903. }
  2904. setIsFinished(f) {
  2905. this._finished = f;
  2906. }
  2907. setIsStarted(f) {
  2908. this._started = f;
  2909. }
  2910. isAvailable() {
  2911. return this._available;
  2912. }
  2913. setIsAvailable(v) {
  2914. this._available = v;
  2915. }
  2916. setState(timeSeconds, weight) {
  2917. this._stateTimeSeconds = timeSeconds;
  2918. this._stateWeight = weight;
  2919. }
  2920. getStateTime() {
  2921. return this._stateTimeSeconds;
  2922. }
  2923. getStateWeight() {
  2924. return this._stateWeight;
  2925. }
  2926. getLastCheckEventSeconds() {
  2927. return this._lastEventCheckSeconds;
  2928. }
  2929. setLastCheckEventSeconds(checkSeconds) {
  2930. this._lastEventCheckSeconds = checkSeconds;
  2931. }
  2932. isTriggeredFadeOut() {
  2933. return this._isTriggeredFadeOut;
  2934. }
  2935. getFadeOutSeconds() {
  2936. return this._fadeOutSeconds;
  2937. }
  2938. }
  2939. class CubismMotionQueueManager {
  2940. constructor() {
  2941. this._userTimeSeconds = 0;
  2942. this._eventCustomData = null;
  2943. this._motions = [];
  2944. }
  2945. release() {
  2946. for (let i = 0; i < this._motions.length; ++i) {
  2947. if (this._motions[i]) {
  2948. this._motions[i].release();
  2949. }
  2950. }
  2951. this._motions = void 0;
  2952. }
  2953. startMotion(motion, autoDelete, userTimeSeconds) {
  2954. if (motion == null) {
  2955. return InvalidMotionQueueEntryHandleValue;
  2956. }
  2957. let motionQueueEntry;
  2958. for (let i = 0; i < this._motions.length; ++i) {
  2959. motionQueueEntry = this._motions[i];
  2960. if (motionQueueEntry == null) {
  2961. continue;
  2962. }
  2963. motionQueueEntry.setFadeOut(motionQueueEntry._motion.getFadeOutTime());
  2964. }
  2965. motionQueueEntry = new CubismMotionQueueEntry();
  2966. motionQueueEntry._autoDelete = autoDelete;
  2967. motionQueueEntry._motion = motion;
  2968. this._motions.push(motionQueueEntry);
  2969. return motionQueueEntry._motionQueueEntryHandle;
  2970. }
  2971. isFinished() {
  2972. let i = 0;
  2973. while (i < this._motions.length) {
  2974. const motionQueueEntry = this._motions[i];
  2975. if (motionQueueEntry == null) {
  2976. this._motions.splice(i, 1);
  2977. continue;
  2978. }
  2979. const motion = motionQueueEntry._motion;
  2980. if (motion == null) {
  2981. motionQueueEntry.release();
  2982. this._motions.splice(i, 1);
  2983. continue;
  2984. }
  2985. if (!motionQueueEntry.isFinished()) {
  2986. return false;
  2987. }
  2988. i++;
  2989. }
  2990. return true;
  2991. }
  2992. isFinishedByHandle(motionQueueEntryNumber) {
  2993. for (let i = 0; i < this._motions.length; i++) {
  2994. const motionQueueEntry = this._motions[i];
  2995. if (motionQueueEntry == null) {
  2996. continue;
  2997. }
  2998. if (motionQueueEntry._motionQueueEntryHandle == motionQueueEntryNumber && !motionQueueEntry.isFinished()) {
  2999. return false;
  3000. }
  3001. }
  3002. return true;
  3003. }
  3004. stopAllMotions() {
  3005. for (let i = 0; i < this._motions.length; i++) {
  3006. const motionQueueEntry = this._motions[i];
  3007. if (motionQueueEntry != null) {
  3008. motionQueueEntry.release();
  3009. }
  3010. }
  3011. this._motions = [];
  3012. }
  3013. getCubismMotionQueueEntry(motionQueueEntryNumber) {
  3014. return this._motions.find((entry) => entry != null && entry._motionQueueEntryHandle == motionQueueEntryNumber);
  3015. }
  3016. setEventCallback(callback, customData = null) {
  3017. this._eventCallBack = callback;
  3018. this._eventCustomData = customData;
  3019. }
  3020. doUpdateMotion(model, userTimeSeconds) {
  3021. let updated = false;
  3022. let i = 0;
  3023. while (i < this._motions.length) {
  3024. const motionQueueEntry = this._motions[i];
  3025. if (motionQueueEntry == null) {
  3026. this._motions.splice(i, 1);
  3027. continue;
  3028. }
  3029. const motion = motionQueueEntry._motion;
  3030. if (motion == null) {
  3031. motionQueueEntry.release();
  3032. this._motions.splice(i, 1);
  3033. continue;
  3034. }
  3035. motion.updateParameters(model, motionQueueEntry, userTimeSeconds);
  3036. updated = true;
  3037. const firedList = motion.getFiredEvent(motionQueueEntry.getLastCheckEventSeconds() - motionQueueEntry.getStartTime(), userTimeSeconds - motionQueueEntry.getStartTime());
  3038. for (let i2 = 0; i2 < firedList.length; ++i2) {
  3039. this._eventCallBack(this, firedList[i2], this._eventCustomData);
  3040. }
  3041. motionQueueEntry.setLastCheckEventSeconds(userTimeSeconds);
  3042. if (motionQueueEntry.isFinished()) {
  3043. motionQueueEntry.release();
  3044. this._motions.splice(i, 1);
  3045. } else {
  3046. if (motionQueueEntry.isTriggeredFadeOut()) {
  3047. motionQueueEntry.startFadeOut(motionQueueEntry.getFadeOutSeconds(), userTimeSeconds);
  3048. }
  3049. i++;
  3050. }
  3051. }
  3052. return updated;
  3053. }
  3054. }
  3055. const InvalidMotionQueueEntryHandleValue = -1;
  3056. class Cubism4ExpressionManager extends ExpressionManager {
  3057. constructor(settings, options) {
  3058. var _a;
  3059. super(settings, options);
  3060. this.queueManager = new CubismMotionQueueManager();
  3061. this.definitions = (_a = settings.expressions) != null ? _a : [];
  3062. this.init();
  3063. }
  3064. isFinished() {
  3065. return this.queueManager.isFinished();
  3066. }
  3067. getExpressionIndex(name) {
  3068. return this.definitions.findIndex((def) => def.Name === name);
  3069. }
  3070. getExpressionFile(definition) {
  3071. return definition.File;
  3072. }
  3073. createExpression(data, definition) {
  3074. return CubismExpressionMotion.create(data);
  3075. }
  3076. _setExpression(motion) {
  3077. return this.queueManager.startMotion(motion, false, performance.now());
  3078. }
  3079. stopAllExpressions() {
  3080. this.queueManager.stopAllMotions();
  3081. }
  3082. updateParameters(model, now) {
  3083. return this.queueManager.doUpdateMotion(model, now);
  3084. }
  3085. }
  3086. class CubismModelSettingsJson {
  3087. constructor(json) {
  3088. this.groups = json.Groups;
  3089. this.hitAreas = json.HitAreas;
  3090. this.layout = json.Layout;
  3091. this.moc = json.FileReferences.Moc;
  3092. this.expressions = json.FileReferences.Expressions;
  3093. this.motions = json.FileReferences.Motions;
  3094. this.textures = json.FileReferences.Textures;
  3095. this.physics = json.FileReferences.Physics;
  3096. this.pose = json.FileReferences.Pose;
  3097. }
  3098. getEyeBlinkParameters() {
  3099. var _a, _b;
  3100. return (_b = (_a = this.groups) == null ? void 0 : _a.find((group) => group.Name === "EyeBlink")) == null ? void 0 : _b.Ids;
  3101. }
  3102. getLipSyncParameters() {
  3103. var _a, _b;
  3104. return (_b = (_a = this.groups) == null ? void 0 : _a.find((group) => group.Name === "LipSync")) == null ? void 0 : _b.Ids;
  3105. }
  3106. }
  3107. class Cubism4ModelSettings extends ModelSettings {
  3108. constructor(json) {
  3109. super(json);
  3110. if (!Cubism4ModelSettings.isValidJSON(json)) {
  3111. throw new TypeError("Invalid JSON.");
  3112. }
  3113. Object.assign(this, new CubismModelSettingsJson(json));
  3114. }
  3115. static isValidJSON(json) {
  3116. var _a;
  3117. return !!(json == null ? void 0 : json.FileReferences) && typeof json.FileReferences.Moc === "string" && ((_a = json.FileReferences.Textures) == null ? void 0 : _a.length) > 0 && json.FileReferences.Textures.every((item) => typeof item === "string");
  3118. }
  3119. replaceFiles(replace) {
  3120. super.replaceFiles(replace);
  3121. if (this.motions) {
  3122. for (const [group, motions] of Object.entries(this.motions)) {
  3123. for (let i = 0; i < motions.length; i++) {
  3124. motions[i].File = replace(motions[i].File, `motions.${group}[${i}].File`);
  3125. if (motions[i].Sound !== void 0) {
  3126. motions[i].Sound = replace(motions[i].Sound, `motions.${group}[${i}].Sound`);
  3127. }
  3128. }
  3129. }
  3130. }
  3131. if (this.expressions) {
  3132. for (let i = 0; i < this.expressions.length; i++) {
  3133. this.expressions[i].File = replace(this.expressions[i].File, `expressions[${i}].File`);
  3134. }
  3135. }
  3136. }
  3137. }
  3138. applyMixins(Cubism4ModelSettings, [CubismModelSettingsJson]);
  3139. var CubismMotionCurveTarget = /* @__PURE__ */ ((CubismMotionCurveTarget2) => {
  3140. CubismMotionCurveTarget2[CubismMotionCurveTarget2["CubismMotionCurveTarget_Model"] = 0] = "CubismMotionCurveTarget_Model";
  3141. CubismMotionCurveTarget2[CubismMotionCurveTarget2["CubismMotionCurveTarget_Parameter"] = 1] = "CubismMotionCurveTarget_Parameter";
  3142. CubismMotionCurveTarget2[CubismMotionCurveTarget2["CubismMotionCurveTarget_PartOpacity"] = 2] = "CubismMotionCurveTarget_PartOpacity";
  3143. return CubismMotionCurveTarget2;
  3144. })(CubismMotionCurveTarget || {});
  3145. var CubismMotionSegmentType = /* @__PURE__ */ ((CubismMotionSegmentType2) => {
  3146. CubismMotionSegmentType2[CubismMotionSegmentType2["CubismMotionSegmentType_Linear"] = 0] = "CubismMotionSegmentType_Linear";
  3147. CubismMotionSegmentType2[CubismMotionSegmentType2["CubismMotionSegmentType_Bezier"] = 1] = "CubismMotionSegmentType_Bezier";
  3148. CubismMotionSegmentType2[CubismMotionSegmentType2["CubismMotionSegmentType_Stepped"] = 2] = "CubismMotionSegmentType_Stepped";
  3149. CubismMotionSegmentType2[CubismMotionSegmentType2["CubismMotionSegmentType_InverseStepped"] = 3] = "CubismMotionSegmentType_InverseStepped";
  3150. return CubismMotionSegmentType2;
  3151. })(CubismMotionSegmentType || {});
  3152. class CubismMotionPoint {
  3153. constructor(time = 0, value = 0) {
  3154. this.time = time;
  3155. this.value = value;
  3156. }
  3157. }
  3158. class CubismMotionSegment {
  3159. constructor() {
  3160. this.basePointIndex = 0;
  3161. this.segmentType = 0;
  3162. }
  3163. }
  3164. class CubismMotionCurve {
  3165. constructor() {
  3166. this.id = "";
  3167. this.type = 0;
  3168. this.segmentCount = 0;
  3169. this.baseSegmentIndex = 0;
  3170. this.fadeInTime = 0;
  3171. this.fadeOutTime = 0;
  3172. }
  3173. }
  3174. class CubismMotionEvent {
  3175. constructor() {
  3176. this.fireTime = 0;
  3177. this.value = "";
  3178. }
  3179. }
  3180. class CubismMotionData {
  3181. constructor() {
  3182. this.duration = 0;
  3183. this.loop = false;
  3184. this.curveCount = 0;
  3185. this.eventCount = 0;
  3186. this.fps = 0;
  3187. this.curves = [];
  3188. this.segments = [];
  3189. this.points = [];
  3190. this.events = [];
  3191. }
  3192. }
  3193. class CubismMotionJson {
  3194. constructor(json) {
  3195. this._json = json;
  3196. }
  3197. release() {
  3198. this._json = void 0;
  3199. }
  3200. getMotionDuration() {
  3201. return this._json.Meta.Duration;
  3202. }
  3203. isMotionLoop() {
  3204. return this._json.Meta.Loop || false;
  3205. }
  3206. getEvaluationOptionFlag(flagType) {
  3207. if (EvaluationOptionFlag.EvaluationOptionFlag_AreBeziersRistricted == flagType) {
  3208. return !!this._json.Meta.AreBeziersRestricted;
  3209. }
  3210. return false;
  3211. }
  3212. getMotionCurveCount() {
  3213. return this._json.Meta.CurveCount;
  3214. }
  3215. getMotionFps() {
  3216. return this._json.Meta.Fps;
  3217. }
  3218. getMotionTotalSegmentCount() {
  3219. return this._json.Meta.TotalSegmentCount;
  3220. }
  3221. getMotionTotalPointCount() {
  3222. return this._json.Meta.TotalPointCount;
  3223. }
  3224. getMotionFadeInTime() {
  3225. return this._json.Meta.FadeInTime;
  3226. }
  3227. getMotionFadeOutTime() {
  3228. return this._json.Meta.FadeOutTime;
  3229. }
  3230. getMotionCurveTarget(curveIndex) {
  3231. return this._json.Curves[curveIndex].Target;
  3232. }
  3233. getMotionCurveId(curveIndex) {
  3234. return this._json.Curves[curveIndex].Id;
  3235. }
  3236. getMotionCurveFadeInTime(curveIndex) {
  3237. return this._json.Curves[curveIndex].FadeInTime;
  3238. }
  3239. getMotionCurveFadeOutTime(curveIndex) {
  3240. return this._json.Curves[curveIndex].FadeOutTime;
  3241. }
  3242. getMotionCurveSegmentCount(curveIndex) {
  3243. return this._json.Curves[curveIndex].Segments.length;
  3244. }
  3245. getMotionCurveSegment(curveIndex, segmentIndex) {
  3246. return this._json.Curves[curveIndex].Segments[segmentIndex];
  3247. }
  3248. getEventCount() {
  3249. return this._json.Meta.UserDataCount || 0;
  3250. }
  3251. getTotalEventValueSize() {
  3252. return this._json.Meta.TotalUserDataSize;
  3253. }
  3254. getEventTime(userDataIndex) {
  3255. return this._json.UserData[userDataIndex].Time;
  3256. }
  3257. getEventValue(userDataIndex) {
  3258. return this._json.UserData[userDataIndex].Value;
  3259. }
  3260. }
  3261. var EvaluationOptionFlag = /* @__PURE__ */ ((EvaluationOptionFlag2) => {
  3262. EvaluationOptionFlag2[EvaluationOptionFlag2["EvaluationOptionFlag_AreBeziersRistricted"] = 0] = "EvaluationOptionFlag_AreBeziersRistricted";
  3263. return EvaluationOptionFlag2;
  3264. })(EvaluationOptionFlag || {});
  3265. const EffectNameEyeBlink = "EyeBlink";
  3266. const EffectNameLipSync = "LipSync";
  3267. const TargetNameModel = "Model";
  3268. const TargetNameParameter = "Parameter";
  3269. const TargetNamePartOpacity = "PartOpacity";
  3270. const UseOldBeziersCurveMotion = false;
  3271. function lerpPoints(a, b, t) {
  3272. const result = new CubismMotionPoint();
  3273. result.time = a.time + (b.time - a.time) * t;
  3274. result.value = a.value + (b.value - a.value) * t;
  3275. return result;
  3276. }
  3277. function linearEvaluate(points, time) {
  3278. let t = (time - points[0].time) / (points[1].time - points[0].time);
  3279. if (t < 0) {
  3280. t = 0;
  3281. }
  3282. return points[0].value + (points[1].value - points[0].value) * t;
  3283. }
  3284. function bezierEvaluate(points, time) {
  3285. let t = (time - points[0].time) / (points[3].time - points[0].time);
  3286. if (t < 0) {
  3287. t = 0;
  3288. }
  3289. const p01 = lerpPoints(points[0], points[1], t);
  3290. const p12 = lerpPoints(points[1], points[2], t);
  3291. const p23 = lerpPoints(points[2], points[3], t);
  3292. const p012 = lerpPoints(p01, p12, t);
  3293. const p123 = lerpPoints(p12, p23, t);
  3294. return lerpPoints(p012, p123, t).value;
  3295. }
  3296. function bezierEvaluateCardanoInterpretation(points, time) {
  3297. const x = time;
  3298. const x1 = points[0].time;
  3299. const x2 = points[3].time;
  3300. const cx1 = points[1].time;
  3301. const cx2 = points[2].time;
  3302. const a = x2 - 3 * cx2 + 3 * cx1 - x1;
  3303. const b = 3 * cx2 - 6 * cx1 + 3 * x1;
  3304. const c = 3 * cx1 - 3 * x1;
  3305. const d = x1 - x;
  3306. const t = CubismMath.cardanoAlgorithmForBezier(a, b, c, d);
  3307. const p01 = lerpPoints(points[0], points[1], t);
  3308. const p12 = lerpPoints(points[1], points[2], t);
  3309. const p23 = lerpPoints(points[2], points[3], t);
  3310. const p012 = lerpPoints(p01, p12, t);
  3311. const p123 = lerpPoints(p12, p23, t);
  3312. return lerpPoints(p012, p123, t).value;
  3313. }
  3314. function steppedEvaluate(points, time) {
  3315. return points[0].value;
  3316. }
  3317. function inverseSteppedEvaluate(points, time) {
  3318. return points[1].value;
  3319. }
  3320. function evaluateCurve(motionData, index, time) {
  3321. const curve = motionData.curves[index];
  3322. let target = -1;
  3323. const totalSegmentCount = curve.baseSegmentIndex + curve.segmentCount;
  3324. let pointPosition = 0;
  3325. for (let i = curve.baseSegmentIndex; i < totalSegmentCount; ++i) {
  3326. pointPosition = motionData.segments[i].basePointIndex + (motionData.segments[i].segmentType == CubismMotionSegmentType.CubismMotionSegmentType_Bezier ? 3 : 1);
  3327. if (motionData.points[pointPosition].time > time) {
  3328. target = i;
  3329. break;
  3330. }
  3331. }
  3332. if (target == -1) {
  3333. return motionData.points[pointPosition].value;
  3334. }
  3335. const segment = motionData.segments[target];
  3336. return segment.evaluate(motionData.points.slice(segment.basePointIndex), time);
  3337. }
  3338. class CubismMotion extends ACubismMotion {
  3339. constructor() {
  3340. super();
  3341. this._eyeBlinkParameterIds = [];
  3342. this._lipSyncParameterIds = [];
  3343. this._sourceFrameRate = 30;
  3344. this._loopDurationSeconds = -1;
  3345. this._isLoop = false;
  3346. this._isLoopFadeIn = true;
  3347. this._lastWeight = 0;
  3348. }
  3349. static create(json, onFinishedMotionHandler) {
  3350. const ret = new CubismMotion();
  3351. ret.parse(json);
  3352. ret._sourceFrameRate = ret._motionData.fps;
  3353. ret._loopDurationSeconds = ret._motionData.duration;
  3354. ret._onFinishedMotion = onFinishedMotionHandler;
  3355. return ret;
  3356. }
  3357. doUpdateParameters(model, userTimeSeconds, fadeWeight, motionQueueEntry) {
  3358. if (this._modelCurveIdEyeBlink == null) {
  3359. this._modelCurveIdEyeBlink = EffectNameEyeBlink;
  3360. }
  3361. if (this._modelCurveIdLipSync == null) {
  3362. this._modelCurveIdLipSync = EffectNameLipSync;
  3363. }
  3364. let timeOffsetSeconds = userTimeSeconds - motionQueueEntry.getStartTime();
  3365. if (timeOffsetSeconds < 0) {
  3366. timeOffsetSeconds = 0;
  3367. }
  3368. let lipSyncValue = Number.MAX_VALUE;
  3369. let eyeBlinkValue = Number.MAX_VALUE;
  3370. const MaxTargetSize = 64;
  3371. let lipSyncFlags = 0;
  3372. let eyeBlinkFlags = 0;
  3373. if (this._eyeBlinkParameterIds.length > MaxTargetSize) {
  3374. CubismLogDebug("too many eye blink targets : {0}", this._eyeBlinkParameterIds.length);
  3375. }
  3376. if (this._lipSyncParameterIds.length > MaxTargetSize) {
  3377. CubismLogDebug("too many lip sync targets : {0}", this._lipSyncParameterIds.length);
  3378. }
  3379. const tmpFadeIn = this._fadeInSeconds <= 0 ? 1 : CubismMath.getEasingSine((userTimeSeconds - motionQueueEntry.getFadeInStartTime()) / this._fadeInSeconds);
  3380. const tmpFadeOut = this._fadeOutSeconds <= 0 || motionQueueEntry.getEndTime() < 0 ? 1 : CubismMath.getEasingSine((motionQueueEntry.getEndTime() - userTimeSeconds) / this._fadeOutSeconds);
  3381. let value;
  3382. let c, parameterIndex;
  3383. let time = timeOffsetSeconds;
  3384. if (this._isLoop) {
  3385. while (time > this._motionData.duration) {
  3386. time -= this._motionData.duration;
  3387. }
  3388. }
  3389. const curves = this._motionData.curves;
  3390. for (c = 0; c < this._motionData.curveCount && curves[c].type == CubismMotionCurveTarget.CubismMotionCurveTarget_Model; ++c) {
  3391. value = evaluateCurve(this._motionData, c, time);
  3392. if (curves[c].id == this._modelCurveIdEyeBlink) {
  3393. eyeBlinkValue = value;
  3394. } else if (curves[c].id == this._modelCurveIdLipSync) {
  3395. lipSyncValue = value;
  3396. }
  3397. }
  3398. for (; c < this._motionData.curveCount && curves[c].type == CubismMotionCurveTarget.CubismMotionCurveTarget_Parameter; ++c) {
  3399. parameterIndex = model.getParameterIndex(curves[c].id);
  3400. if (parameterIndex == -1) {
  3401. continue;
  3402. }
  3403. const sourceValue = model.getParameterValueByIndex(parameterIndex);
  3404. value = evaluateCurve(this._motionData, c, time);
  3405. if (eyeBlinkValue != Number.MAX_VALUE) {
  3406. for (let i = 0; i < this._eyeBlinkParameterIds.length && i < MaxTargetSize; ++i) {
  3407. if (this._eyeBlinkParameterIds[i] == curves[c].id) {
  3408. value *= eyeBlinkValue;
  3409. eyeBlinkFlags |= 1 << i;
  3410. break;
  3411. }
  3412. }
  3413. }
  3414. if (lipSyncValue != Number.MAX_VALUE) {
  3415. for (let i = 0; i < this._lipSyncParameterIds.length && i < MaxTargetSize; ++i) {
  3416. if (this._lipSyncParameterIds[i] == curves[c].id) {
  3417. value += lipSyncValue;
  3418. lipSyncFlags |= 1 << i;
  3419. break;
  3420. }
  3421. }
  3422. }
  3423. let v;
  3424. if (curves[c].fadeInTime < 0 && curves[c].fadeOutTime < 0) {
  3425. v = sourceValue + (value - sourceValue) * fadeWeight;
  3426. } else {
  3427. let fin;
  3428. let fout;
  3429. if (curves[c].fadeInTime < 0) {
  3430. fin = tmpFadeIn;
  3431. } else {
  3432. fin = curves[c].fadeInTime == 0 ? 1 : CubismMath.getEasingSine((userTimeSeconds - motionQueueEntry.getFadeInStartTime()) / curves[c].fadeInTime);
  3433. }
  3434. if (curves[c].fadeOutTime < 0) {
  3435. fout = tmpFadeOut;
  3436. } else {
  3437. fout = curves[c].fadeOutTime == 0 || motionQueueEntry.getEndTime() < 0 ? 1 : CubismMath.getEasingSine((motionQueueEntry.getEndTime() - userTimeSeconds) / curves[c].fadeOutTime);
  3438. }
  3439. const paramWeight = this._weight * fin * fout;
  3440. v = sourceValue + (value - sourceValue) * paramWeight;
  3441. }
  3442. model.setParameterValueByIndex(parameterIndex, v, 1);
  3443. }
  3444. {
  3445. if (eyeBlinkValue != Number.MAX_VALUE) {
  3446. for (let i = 0; i < this._eyeBlinkParameterIds.length && i < MaxTargetSize; ++i) {
  3447. const sourceValue = model.getParameterValueById(this._eyeBlinkParameterIds[i]);
  3448. if (eyeBlinkFlags >> i & 1) {
  3449. continue;
  3450. }
  3451. const v = sourceValue + (eyeBlinkValue - sourceValue) * fadeWeight;
  3452. model.setParameterValueById(this._eyeBlinkParameterIds[i], v);
  3453. }
  3454. }
  3455. if (lipSyncValue != Number.MAX_VALUE) {
  3456. for (let i = 0; i < this._lipSyncParameterIds.length && i < MaxTargetSize; ++i) {
  3457. const sourceValue = model.getParameterValueById(this._lipSyncParameterIds[i]);
  3458. if (lipSyncFlags >> i & 1) {
  3459. continue;
  3460. }
  3461. const v = sourceValue + (lipSyncValue - sourceValue) * fadeWeight;
  3462. model.setParameterValueById(this._lipSyncParameterIds[i], v);
  3463. }
  3464. }
  3465. }
  3466. for (; c < this._motionData.curveCount && curves[c].type == CubismMotionCurveTarget.CubismMotionCurveTarget_PartOpacity; ++c) {
  3467. value = evaluateCurve(this._motionData, c, time);
  3468. if (CubismConfig.setOpacityFromMotion) {
  3469. model.setPartOpacityById(curves[c].id, value);
  3470. } else {
  3471. parameterIndex = model.getParameterIndex(curves[c].id);
  3472. if (parameterIndex == -1) {
  3473. continue;
  3474. }
  3475. model.setParameterValueByIndex(parameterIndex, value);
  3476. }
  3477. }
  3478. if (timeOffsetSeconds >= this._motionData.duration) {
  3479. if (this._isLoop) {
  3480. motionQueueEntry.setStartTime(userTimeSeconds);
  3481. if (this._isLoopFadeIn) {
  3482. motionQueueEntry.setFadeInStartTime(userTimeSeconds);
  3483. }
  3484. } else {
  3485. if (this._onFinishedMotion) {
  3486. this._onFinishedMotion(this);
  3487. }
  3488. motionQueueEntry.setIsFinished(true);
  3489. }
  3490. }
  3491. this._lastWeight = fadeWeight;
  3492. }
  3493. setIsLoop(loop) {
  3494. this._isLoop = loop;
  3495. }
  3496. isLoop() {
  3497. return this._isLoop;
  3498. }
  3499. setIsLoopFadeIn(loopFadeIn) {
  3500. this._isLoopFadeIn = loopFadeIn;
  3501. }
  3502. isLoopFadeIn() {
  3503. return this._isLoopFadeIn;
  3504. }
  3505. getDuration() {
  3506. return this._isLoop ? -1 : this._loopDurationSeconds;
  3507. }
  3508. getLoopDuration() {
  3509. return this._loopDurationSeconds;
  3510. }
  3511. setParameterFadeInTime(parameterId, value) {
  3512. const curves = this._motionData.curves;
  3513. for (let i = 0; i < this._motionData.curveCount; ++i) {
  3514. if (parameterId == curves[i].id) {
  3515. curves[i].fadeInTime = value;
  3516. return;
  3517. }
  3518. }
  3519. }
  3520. setParameterFadeOutTime(parameterId, value) {
  3521. const curves = this._motionData.curves;
  3522. for (let i = 0; i < this._motionData.curveCount; ++i) {
  3523. if (parameterId == curves[i].id) {
  3524. curves[i].fadeOutTime = value;
  3525. return;
  3526. }
  3527. }
  3528. }
  3529. getParameterFadeInTime(parameterId) {
  3530. const curves = this._motionData.curves;
  3531. for (let i = 0; i < this._motionData.curveCount; ++i) {
  3532. if (parameterId == curves[i].id) {
  3533. return curves[i].fadeInTime;
  3534. }
  3535. }
  3536. return -1;
  3537. }
  3538. getParameterFadeOutTime(parameterId) {
  3539. const curves = this._motionData.curves;
  3540. for (let i = 0; i < this._motionData.curveCount; ++i) {
  3541. if (parameterId == curves[i].id) {
  3542. return curves[i].fadeOutTime;
  3543. }
  3544. }
  3545. return -1;
  3546. }
  3547. setEffectIds(eyeBlinkParameterIds, lipSyncParameterIds) {
  3548. this._eyeBlinkParameterIds = eyeBlinkParameterIds;
  3549. this._lipSyncParameterIds = lipSyncParameterIds;
  3550. }
  3551. release() {
  3552. this._motionData = void 0;
  3553. }
  3554. parse(motionJson) {
  3555. this._motionData = new CubismMotionData();
  3556. let json = new CubismMotionJson(motionJson);
  3557. this._motionData.duration = json.getMotionDuration();
  3558. this._motionData.loop = json.isMotionLoop();
  3559. this._motionData.curveCount = json.getMotionCurveCount();
  3560. this._motionData.fps = json.getMotionFps();
  3561. this._motionData.eventCount = json.getEventCount();
  3562. const areBeziersRestructed = json.getEvaluationOptionFlag(EvaluationOptionFlag.EvaluationOptionFlag_AreBeziersRistricted);
  3563. const fadeInSeconds = json.getMotionFadeInTime();
  3564. const fadeOutSeconds = json.getMotionFadeOutTime();
  3565. if (fadeInSeconds !== void 0) {
  3566. this._fadeInSeconds = fadeInSeconds < 0 ? 1 : fadeInSeconds;
  3567. } else {
  3568. this._fadeInSeconds = 1;
  3569. }
  3570. if (fadeOutSeconds !== void 0) {
  3571. this._fadeOutSeconds = fadeOutSeconds < 0 ? 1 : fadeOutSeconds;
  3572. } else {
  3573. this._fadeOutSeconds = 1;
  3574. }
  3575. this._motionData.curves = Array.from({ length: this._motionData.curveCount }).map(() => new CubismMotionCurve());
  3576. this._motionData.segments = Array.from({ length: json.getMotionTotalSegmentCount() }).map(() => new CubismMotionSegment());
  3577. this._motionData.events = Array.from({ length: this._motionData.eventCount }).map(() => new CubismMotionEvent());
  3578. this._motionData.points = [];
  3579. let totalPointCount = 0;
  3580. let totalSegmentCount = 0;
  3581. for (let curveCount = 0; curveCount < this._motionData.curveCount; ++curveCount) {
  3582. const curve = this._motionData.curves[curveCount];
  3583. switch (json.getMotionCurveTarget(curveCount)) {
  3584. case TargetNameModel:
  3585. curve.type = CubismMotionCurveTarget.CubismMotionCurveTarget_Model;
  3586. break;
  3587. case TargetNameParameter:
  3588. curve.type = CubismMotionCurveTarget.CubismMotionCurveTarget_Parameter;
  3589. break;
  3590. case TargetNamePartOpacity:
  3591. curve.type = CubismMotionCurveTarget.CubismMotionCurveTarget_PartOpacity;
  3592. break;
  3593. default:
  3594. CubismLogWarning('Warning : Unable to get segment type from Curve! The number of "CurveCount" may be incorrect!');
  3595. }
  3596. curve.id = json.getMotionCurveId(curveCount);
  3597. curve.baseSegmentIndex = totalSegmentCount;
  3598. const fadeInTime = json.getMotionCurveFadeInTime(curveCount);
  3599. const fadeOutTime = json.getMotionCurveFadeOutTime(curveCount);
  3600. curve.fadeInTime = fadeInTime !== void 0 ? fadeInTime : -1;
  3601. curve.fadeOutTime = fadeOutTime !== void 0 ? fadeOutTime : -1;
  3602. for (let segmentPosition = 0; segmentPosition < json.getMotionCurveSegmentCount(curveCount); ) {
  3603. if (segmentPosition == 0) {
  3604. this._motionData.segments[totalSegmentCount].basePointIndex = totalPointCount;
  3605. this._motionData.points[totalPointCount] = new CubismMotionPoint(json.getMotionCurveSegment(curveCount, segmentPosition), json.getMotionCurveSegment(curveCount, segmentPosition + 1));
  3606. totalPointCount += 1;
  3607. segmentPosition += 2;
  3608. } else {
  3609. this._motionData.segments[totalSegmentCount].basePointIndex = totalPointCount - 1;
  3610. }
  3611. const segment = json.getMotionCurveSegment(curveCount, segmentPosition);
  3612. switch (segment) {
  3613. case CubismMotionSegmentType.CubismMotionSegmentType_Linear: {
  3614. this._motionData.segments[totalSegmentCount].segmentType = CubismMotionSegmentType.CubismMotionSegmentType_Linear;
  3615. this._motionData.segments[totalSegmentCount].evaluate = linearEvaluate;
  3616. this._motionData.points[totalPointCount] = new CubismMotionPoint(json.getMotionCurveSegment(curveCount, segmentPosition + 1), json.getMotionCurveSegment(curveCount, segmentPosition + 2));
  3617. totalPointCount += 1;
  3618. segmentPosition += 3;
  3619. break;
  3620. }
  3621. case CubismMotionSegmentType.CubismMotionSegmentType_Bezier: {
  3622. this._motionData.segments[totalSegmentCount].segmentType = CubismMotionSegmentType.CubismMotionSegmentType_Bezier;
  3623. if (areBeziersRestructed || UseOldBeziersCurveMotion) {
  3624. this._motionData.segments[totalSegmentCount].evaluate = bezierEvaluate;
  3625. } else {
  3626. this._motionData.segments[totalSegmentCount].evaluate = bezierEvaluateCardanoInterpretation;
  3627. }
  3628. this._motionData.points[totalPointCount] = new CubismMotionPoint(json.getMotionCurveSegment(curveCount, segmentPosition + 1), json.getMotionCurveSegment(curveCount, segmentPosition + 2));
  3629. this._motionData.points[totalPointCount + 1] = new CubismMotionPoint(json.getMotionCurveSegment(curveCount, segmentPosition + 3), json.getMotionCurveSegment(curveCount, segmentPosition + 4));
  3630. this._motionData.points[totalPointCount + 2] = new CubismMotionPoint(json.getMotionCurveSegment(curveCount, segmentPosition + 5), json.getMotionCurveSegment(curveCount, segmentPosition + 6));
  3631. totalPointCount += 3;
  3632. segmentPosition += 7;
  3633. break;
  3634. }
  3635. case CubismMotionSegmentType.CubismMotionSegmentType_Stepped: {
  3636. this._motionData.segments[totalSegmentCount].segmentType = CubismMotionSegmentType.CubismMotionSegmentType_Stepped;
  3637. this._motionData.segments[totalSegmentCount].evaluate = steppedEvaluate;
  3638. this._motionData.points[totalPointCount] = new CubismMotionPoint(json.getMotionCurveSegment(curveCount, segmentPosition + 1), json.getMotionCurveSegment(curveCount, segmentPosition + 2));
  3639. totalPointCount += 1;
  3640. segmentPosition += 3;
  3641. break;
  3642. }
  3643. case CubismMotionSegmentType.CubismMotionSegmentType_InverseStepped: {
  3644. this._motionData.segments[totalSegmentCount].segmentType = CubismMotionSegmentType.CubismMotionSegmentType_InverseStepped;
  3645. this._motionData.segments[totalSegmentCount].evaluate = inverseSteppedEvaluate;
  3646. this._motionData.points[totalPointCount] = new CubismMotionPoint(json.getMotionCurveSegment(curveCount, segmentPosition + 1), json.getMotionCurveSegment(curveCount, segmentPosition + 2));
  3647. totalPointCount += 1;
  3648. segmentPosition += 3;
  3649. break;
  3650. }
  3651. }
  3652. ++curve.segmentCount;
  3653. ++totalSegmentCount;
  3654. }
  3655. this._motionData.curves.push(curve);
  3656. }
  3657. for (let userdatacount = 0; userdatacount < json.getEventCount(); ++userdatacount) {
  3658. this._motionData.events[userdatacount].fireTime = json.getEventTime(userdatacount);
  3659. this._motionData.events[userdatacount].value = json.getEventValue(userdatacount);
  3660. }
  3661. json.release();
  3662. }
  3663. getFiredEvent(beforeCheckTimeSeconds, motionTimeSeconds) {
  3664. this._firedEventValues.length = 0;
  3665. for (let u = 0; u < this._motionData.eventCount; ++u) {
  3666. if (this._motionData.events[u].fireTime > beforeCheckTimeSeconds && this._motionData.events[u].fireTime <= motionTimeSeconds) {
  3667. this._firedEventValues.push(this._motionData.events[u].value);
  3668. }
  3669. }
  3670. return this._firedEventValues;
  3671. }
  3672. }
  3673. class Cubism4MotionManager extends MotionManager {
  3674. constructor(settings, options) {
  3675. var _a;
  3676. super(settings, options);
  3677. this.groups = { idle: "Idle" };
  3678. this.motionDataType = "json";
  3679. this.queueManager = new CubismMotionQueueManager();
  3680. this.definitions = (_a = settings.motions) != null ? _a : {};
  3681. this.eyeBlinkIds = settings.getEyeBlinkParameters() || [];
  3682. this.lipSyncIds = settings.getLipSyncParameters() || [];
  3683. this.init(options);
  3684. }
  3685. init(options) {
  3686. super.init(options);
  3687. if (this.settings.expressions) {
  3688. this.expressionManager = new Cubism4ExpressionManager(this.settings, options);
  3689. }
  3690. this.queueManager.setEventCallback((caller, eventValue, customData) => {
  3691. this.emit("motion:" + eventValue);
  3692. });
  3693. }
  3694. isFinished() {
  3695. return this.queueManager.isFinished();
  3696. }
  3697. _startMotion(motion, onFinish) {
  3698. motion.setFinishedMotionHandler(onFinish);
  3699. this.queueManager.stopAllMotions();
  3700. return this.queueManager.startMotion(motion, false, performance.now());
  3701. }
  3702. _stopAllMotions() {
  3703. this.queueManager.stopAllMotions();
  3704. }
  3705. createMotion(data, group, definition) {
  3706. const motion = CubismMotion.create(data);
  3707. const json = new CubismMotionJson(data);
  3708. const defaultFadingDuration = (group === this.groups.idle ? config.idleMotionFadingDuration : config.motionFadingDuration) / 1e3;
  3709. if (json.getMotionFadeInTime() === void 0) {
  3710. motion.setFadeInTime(definition.FadeInTime > 0 ? definition.FadeInTime : defaultFadingDuration);
  3711. }
  3712. if (json.getMotionFadeOutTime() === void 0) {
  3713. motion.setFadeOutTime(definition.FadeOutTime > 0 ? definition.FadeOutTime : defaultFadingDuration);
  3714. }
  3715. motion.setEffectIds(this.eyeBlinkIds, this.lipSyncIds);
  3716. return motion;
  3717. }
  3718. getMotionFile(definition) {
  3719. return definition.File;
  3720. }
  3721. getMotionName(definition) {
  3722. return definition.File;
  3723. }
  3724. getSoundFile(definition) {
  3725. return definition.Sound;
  3726. }
  3727. updateParameters(model, now) {
  3728. return this.queueManager.doUpdateMotion(model, now);
  3729. }
  3730. destroy() {
  3731. super.destroy();
  3732. this.queueManager.release();
  3733. this.queueManager = void 0;
  3734. }
  3735. }
  3736. const ParamAngleX = "ParamAngleX";
  3737. const ParamAngleY = "ParamAngleY";
  3738. const ParamAngleZ = "ParamAngleZ";
  3739. const ParamEyeBallX = "ParamEyeBallX";
  3740. const ParamEyeBallY = "ParamEyeBallY";
  3741. const ParamBodyAngleX = "ParamBodyAngleX";
  3742. const ParamBreath = "ParamBreath";
  3743. class CubismBreath {
  3744. constructor() {
  3745. this._breathParameters = [];
  3746. this._currentTime = 0;
  3747. }
  3748. static create() {
  3749. return new CubismBreath();
  3750. }
  3751. setParameters(breathParameters) {
  3752. this._breathParameters = breathParameters;
  3753. }
  3754. getParameters() {
  3755. return this._breathParameters;
  3756. }
  3757. updateParameters(model, deltaTimeSeconds) {
  3758. this._currentTime += deltaTimeSeconds;
  3759. const t = this._currentTime * 2 * 3.14159;
  3760. for (let i = 0; i < this._breathParameters.length; ++i) {
  3761. const data = this._breathParameters[i];
  3762. model.addParameterValueById(data.parameterId, data.offset + data.peak * Math.sin(t / data.cycle), data.weight);
  3763. }
  3764. }
  3765. }
  3766. class BreathParameterData {
  3767. constructor(parameterId, offset, peak, cycle, weight) {
  3768. this.parameterId = parameterId == void 0 ? void 0 : parameterId;
  3769. this.offset = offset == void 0 ? 0 : offset;
  3770. this.peak = peak == void 0 ? 0 : peak;
  3771. this.cycle = cycle == void 0 ? 0 : cycle;
  3772. this.weight = weight == void 0 ? 0 : weight;
  3773. }
  3774. }
  3775. const _CubismEyeBlink = class {
  3776. static create(modelSetting) {
  3777. return new _CubismEyeBlink(modelSetting);
  3778. }
  3779. setBlinkingInterval(blinkingInterval) {
  3780. this._blinkingIntervalSeconds = blinkingInterval;
  3781. }
  3782. setBlinkingSetting(closing, closed, opening) {
  3783. this._closingSeconds = closing;
  3784. this._closedSeconds = closed;
  3785. this._openingSeconds = opening;
  3786. }
  3787. setParameterIds(parameterIds) {
  3788. this._parameterIds = parameterIds;
  3789. }
  3790. getParameterIds() {
  3791. return this._parameterIds;
  3792. }
  3793. updateParameters(model, deltaTimeSeconds) {
  3794. this._userTimeSeconds += deltaTimeSeconds;
  3795. let parameterValue;
  3796. let t = 0;
  3797. switch (this._blinkingState) {
  3798. case EyeState.EyeState_Closing:
  3799. t = (this._userTimeSeconds - this._stateStartTimeSeconds) / this._closingSeconds;
  3800. if (t >= 1) {
  3801. t = 1;
  3802. this._blinkingState = EyeState.EyeState_Closed;
  3803. this._stateStartTimeSeconds = this._userTimeSeconds;
  3804. }
  3805. parameterValue = 1 - t;
  3806. break;
  3807. case EyeState.EyeState_Closed:
  3808. t = (this._userTimeSeconds - this._stateStartTimeSeconds) / this._closedSeconds;
  3809. if (t >= 1) {
  3810. this._blinkingState = EyeState.EyeState_Opening;
  3811. this._stateStartTimeSeconds = this._userTimeSeconds;
  3812. }
  3813. parameterValue = 0;
  3814. break;
  3815. case EyeState.EyeState_Opening:
  3816. t = (this._userTimeSeconds - this._stateStartTimeSeconds) / this._openingSeconds;
  3817. if (t >= 1) {
  3818. t = 1;
  3819. this._blinkingState = EyeState.EyeState_Interval;
  3820. this._nextBlinkingTime = this.determinNextBlinkingTiming();
  3821. }
  3822. parameterValue = t;
  3823. break;
  3824. case EyeState.EyeState_Interval:
  3825. if (this._nextBlinkingTime < this._userTimeSeconds) {
  3826. this._blinkingState = EyeState.EyeState_Closing;
  3827. this._stateStartTimeSeconds = this._userTimeSeconds;
  3828. }
  3829. parameterValue = 1;
  3830. break;
  3831. case EyeState.EyeState_First:
  3832. default:
  3833. this._blinkingState = EyeState.EyeState_Interval;
  3834. this._nextBlinkingTime = this.determinNextBlinkingTiming();
  3835. parameterValue = 1;
  3836. break;
  3837. }
  3838. if (!_CubismEyeBlink.CloseIfZero) {
  3839. parameterValue = -parameterValue;
  3840. }
  3841. for (let i = 0; i < this._parameterIds.length; ++i) {
  3842. model.setParameterValueById(this._parameterIds[i], parameterValue);
  3843. }
  3844. }
  3845. constructor(modelSetting) {
  3846. var _a, _b;
  3847. this._blinkingState = EyeState.EyeState_First;
  3848. this._nextBlinkingTime = 0;
  3849. this._stateStartTimeSeconds = 0;
  3850. this._blinkingIntervalSeconds = 4;
  3851. this._closingSeconds = 0.1;
  3852. this._closedSeconds = 0.05;
  3853. this._openingSeconds = 0.15;
  3854. this._userTimeSeconds = 0;
  3855. this._parameterIds = [];
  3856. if (modelSetting == null) {
  3857. return;
  3858. }
  3859. this._parameterIds = (_b = (_a = modelSetting.getEyeBlinkParameters()) == null ? void 0 : _a.slice()) != null ? _b : this._parameterIds;
  3860. }
  3861. determinNextBlinkingTiming() {
  3862. const r = Math.random();
  3863. return this._userTimeSeconds + r * (2 * this._blinkingIntervalSeconds - 1);
  3864. }
  3865. };
  3866. let CubismEyeBlink = _CubismEyeBlink;
  3867. CubismEyeBlink.CloseIfZero = true;
  3868. var EyeState = /* @__PURE__ */ ((EyeState2) => {
  3869. EyeState2[EyeState2["EyeState_First"] = 0] = "EyeState_First";
  3870. EyeState2[EyeState2["EyeState_Interval"] = 1] = "EyeState_Interval";
  3871. EyeState2[EyeState2["EyeState_Closing"] = 2] = "EyeState_Closing";
  3872. EyeState2[EyeState2["EyeState_Closed"] = 3] = "EyeState_Closed";
  3873. EyeState2[EyeState2["EyeState_Opening"] = 4] = "EyeState_Opening";
  3874. return EyeState2;
  3875. })(EyeState || {});
  3876. class csmRect {
  3877. constructor(x = 0, y = 0, w = 0, h = 0) {
  3878. this.x = x;
  3879. this.y = y;
  3880. this.width = w;
  3881. this.height = h;
  3882. }
  3883. getCenterX() {
  3884. return this.x + 0.5 * this.width;
  3885. }
  3886. getCenterY() {
  3887. return this.y + 0.5 * this.height;
  3888. }
  3889. getRight() {
  3890. return this.x + this.width;
  3891. }
  3892. getBottom() {
  3893. return this.y + this.height;
  3894. }
  3895. setRect(r) {
  3896. this.x = r.x;
  3897. this.y = r.y;
  3898. this.width = r.width;
  3899. this.height = r.height;
  3900. }
  3901. expand(w, h) {
  3902. this.x -= w;
  3903. this.y -= h;
  3904. this.width += w * 2;
  3905. this.height += h * 2;
  3906. }
  3907. }
  3908. const ColorChannelCount = 4;
  3909. const shaderCount = 10;
  3910. let s_instance;
  3911. let s_viewport;
  3912. let s_fbo;
  3913. class CubismClippingManager_WebGL {
  3914. getChannelFlagAsColor(channelNo) {
  3915. return this._channelColors[channelNo];
  3916. }
  3917. getMaskRenderTexture() {
  3918. let ret = 0;
  3919. if (this._maskTexture && this._maskTexture.texture != 0) {
  3920. this._maskTexture.frameNo = this._currentFrameNo;
  3921. ret = this._maskTexture.texture;
  3922. }
  3923. if (ret == 0) {
  3924. const size = this._clippingMaskBufferSize;
  3925. this._colorBuffer = this.gl.createTexture();
  3926. this.gl.bindTexture(this.gl.TEXTURE_2D, this._colorBuffer);
  3927. this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, size, size, 0, this.gl.RGBA, this.gl.UNSIGNED_BYTE, null);
  3928. this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, this.gl.CLAMP_TO_EDGE);
  3929. this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, this.gl.CLAMP_TO_EDGE);
  3930. this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this.gl.LINEAR);
  3931. this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, this.gl.LINEAR);
  3932. this.gl.bindTexture(this.gl.TEXTURE_2D, null);
  3933. ret = this.gl.createFramebuffer();
  3934. this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, ret);
  3935. this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER, this.gl.COLOR_ATTACHMENT0, this.gl.TEXTURE_2D, this._colorBuffer, 0);
  3936. this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, s_fbo);
  3937. this._maskTexture = new CubismRenderTextureResource(this._currentFrameNo, ret);
  3938. }
  3939. return ret;
  3940. }
  3941. setGL(gl) {
  3942. this.gl = gl;
  3943. }
  3944. calcClippedDrawTotalBounds(model, clippingContext) {
  3945. let clippedDrawTotalMinX = Number.MAX_VALUE;
  3946. let clippedDrawTotalMinY = Number.MAX_VALUE;
  3947. let clippedDrawTotalMaxX = Number.MIN_VALUE;
  3948. let clippedDrawTotalMaxY = Number.MIN_VALUE;
  3949. const clippedDrawCount = clippingContext._clippedDrawableIndexList.length;
  3950. for (let clippedDrawableIndex = 0; clippedDrawableIndex < clippedDrawCount; clippedDrawableIndex++) {
  3951. const drawableIndex = clippingContext._clippedDrawableIndexList[clippedDrawableIndex];
  3952. const drawableVertexCount = model.getDrawableVertexCount(drawableIndex);
  3953. const drawableVertexes = model.getDrawableVertices(drawableIndex);
  3954. let minX = Number.MAX_VALUE;
  3955. let minY = Number.MAX_VALUE;
  3956. let maxX = Number.MIN_VALUE;
  3957. let maxY = Number.MIN_VALUE;
  3958. const loop = drawableVertexCount * Constant.vertexStep;
  3959. for (let pi = Constant.vertexOffset; pi < loop; pi += Constant.vertexStep) {
  3960. const x = drawableVertexes[pi];
  3961. const y = drawableVertexes[pi + 1];
  3962. if (x < minX) {
  3963. minX = x;
  3964. }
  3965. if (x > maxX) {
  3966. maxX = x;
  3967. }
  3968. if (y < minY) {
  3969. minY = y;
  3970. }
  3971. if (y > maxY) {
  3972. maxY = y;
  3973. }
  3974. }
  3975. if (minX == Number.MAX_VALUE) {
  3976. continue;
  3977. }
  3978. if (minX < clippedDrawTotalMinX) {
  3979. clippedDrawTotalMinX = minX;
  3980. }
  3981. if (minY < clippedDrawTotalMinY) {
  3982. clippedDrawTotalMinY = minY;
  3983. }
  3984. if (maxX > clippedDrawTotalMaxX) {
  3985. clippedDrawTotalMaxX = maxX;
  3986. }
  3987. if (maxY > clippedDrawTotalMaxY) {
  3988. clippedDrawTotalMaxY = maxY;
  3989. }
  3990. if (clippedDrawTotalMinX == Number.MAX_VALUE) {
  3991. clippingContext._allClippedDrawRect.x = 0;
  3992. clippingContext._allClippedDrawRect.y = 0;
  3993. clippingContext._allClippedDrawRect.width = 0;
  3994. clippingContext._allClippedDrawRect.height = 0;
  3995. clippingContext._isUsing = false;
  3996. } else {
  3997. clippingContext._isUsing = true;
  3998. const w = clippedDrawTotalMaxX - clippedDrawTotalMinX;
  3999. const h = clippedDrawTotalMaxY - clippedDrawTotalMinY;
  4000. clippingContext._allClippedDrawRect.x = clippedDrawTotalMinX;
  4001. clippingContext._allClippedDrawRect.y = clippedDrawTotalMinY;
  4002. clippingContext._allClippedDrawRect.width = w;
  4003. clippingContext._allClippedDrawRect.height = h;
  4004. }
  4005. }
  4006. }
  4007. constructor() {
  4008. this._maskRenderTexture = null;
  4009. this._colorBuffer = null;
  4010. this._currentFrameNo = 0;
  4011. this._clippingMaskBufferSize = 256;
  4012. this._clippingContextListForMask = [];
  4013. this._clippingContextListForDraw = [];
  4014. this._channelColors = [];
  4015. this._tmpBoundsOnModel = new csmRect();
  4016. this._tmpMatrix = new CubismMatrix44();
  4017. this._tmpMatrixForMask = new CubismMatrix44();
  4018. this._tmpMatrixForDraw = new CubismMatrix44();
  4019. let tmp = new CubismTextureColor();
  4020. tmp.R = 1;
  4021. tmp.G = 0;
  4022. tmp.B = 0;
  4023. tmp.A = 0;
  4024. this._channelColors.push(tmp);
  4025. tmp = new CubismTextureColor();
  4026. tmp.R = 0;
  4027. tmp.G = 1;
  4028. tmp.B = 0;
  4029. tmp.A = 0;
  4030. this._channelColors.push(tmp);
  4031. tmp = new CubismTextureColor();
  4032. tmp.R = 0;
  4033. tmp.G = 0;
  4034. tmp.B = 1;
  4035. tmp.A = 0;
  4036. this._channelColors.push(tmp);
  4037. tmp = new CubismTextureColor();
  4038. tmp.R = 0;
  4039. tmp.G = 0;
  4040. tmp.B = 0;
  4041. tmp.A = 1;
  4042. this._channelColors.push(tmp);
  4043. }
  4044. release() {
  4045. var _a, _b, _c;
  4046. const self = this;
  4047. for (let i = 0; i < this._clippingContextListForMask.length; i++) {
  4048. if (this._clippingContextListForMask[i]) {
  4049. (_a = this._clippingContextListForMask[i]) == null ? void 0 : _a.release();
  4050. }
  4051. }
  4052. self._clippingContextListForMask = void 0;
  4053. self._clippingContextListForDraw = void 0;
  4054. if (this._maskTexture) {
  4055. (_b = this.gl) == null ? void 0 : _b.deleteFramebuffer(this._maskTexture.texture);
  4056. self._maskTexture = void 0;
  4057. }
  4058. self._channelColors = void 0;
  4059. (_c = this.gl) == null ? void 0 : _c.deleteTexture(this._colorBuffer);
  4060. this._colorBuffer = null;
  4061. }
  4062. initialize(model, drawableCount, drawableMasks, drawableMaskCounts) {
  4063. for (let i = 0; i < drawableCount; i++) {
  4064. if (drawableMaskCounts[i] <= 0) {
  4065. this._clippingContextListForDraw.push(null);
  4066. continue;
  4067. }
  4068. let clippingContext = this.findSameClip(drawableMasks[i], drawableMaskCounts[i]);
  4069. if (clippingContext == null) {
  4070. clippingContext = new CubismClippingContext(this, drawableMasks[i], drawableMaskCounts[i]);
  4071. this._clippingContextListForMask.push(clippingContext);
  4072. }
  4073. clippingContext.addClippedDrawable(i);
  4074. this._clippingContextListForDraw.push(clippingContext);
  4075. }
  4076. }
  4077. setupClippingContext(model, renderer) {
  4078. this._currentFrameNo++;
  4079. let usingClipCount = 0;
  4080. for (let clipIndex = 0; clipIndex < this._clippingContextListForMask.length; clipIndex++) {
  4081. const cc = this._clippingContextListForMask[clipIndex];
  4082. this.calcClippedDrawTotalBounds(model, cc);
  4083. if (cc._isUsing) {
  4084. usingClipCount++;
  4085. }
  4086. }
  4087. if (usingClipCount > 0) {
  4088. this.gl.viewport(0, 0, this._clippingMaskBufferSize, this._clippingMaskBufferSize);
  4089. this._maskRenderTexture = this.getMaskRenderTexture();
  4090. renderer.getMvpMatrix();
  4091. renderer.preDraw();
  4092. this.setupLayoutBounds(usingClipCount);
  4093. this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, this._maskRenderTexture);
  4094. this.gl.clearColor(1, 1, 1, 1);
  4095. this.gl.clear(this.gl.COLOR_BUFFER_BIT);
  4096. for (let clipIndex = 0; clipIndex < this._clippingContextListForMask.length; clipIndex++) {
  4097. const clipContext = this._clippingContextListForMask[clipIndex];
  4098. const allClipedDrawRect = clipContext._allClippedDrawRect;
  4099. const layoutBoundsOnTex01 = clipContext._layoutBounds;
  4100. const MARGIN = 0.05;
  4101. this._tmpBoundsOnModel.setRect(allClipedDrawRect);
  4102. this._tmpBoundsOnModel.expand(allClipedDrawRect.width * MARGIN, allClipedDrawRect.height * MARGIN);
  4103. const scaleX = layoutBoundsOnTex01.width / this._tmpBoundsOnModel.width;
  4104. const scaleY = layoutBoundsOnTex01.height / this._tmpBoundsOnModel.height;
  4105. {
  4106. this._tmpMatrix.loadIdentity();
  4107. {
  4108. this._tmpMatrix.translateRelative(-1, -1);
  4109. this._tmpMatrix.scaleRelative(2, 2);
  4110. }
  4111. {
  4112. this._tmpMatrix.translateRelative(layoutBoundsOnTex01.x, layoutBoundsOnTex01.y);
  4113. this._tmpMatrix.scaleRelative(scaleX, scaleY);
  4114. this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x, -this._tmpBoundsOnModel.y);
  4115. }
  4116. this._tmpMatrixForMask.setMatrix(this._tmpMatrix.getArray());
  4117. }
  4118. {
  4119. this._tmpMatrix.loadIdentity();
  4120. {
  4121. this._tmpMatrix.translateRelative(layoutBoundsOnTex01.x, layoutBoundsOnTex01.y);
  4122. this._tmpMatrix.scaleRelative(scaleX, scaleY);
  4123. this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x, -this._tmpBoundsOnModel.y);
  4124. }
  4125. this._tmpMatrixForDraw.setMatrix(this._tmpMatrix.getArray());
  4126. }
  4127. clipContext._matrixForMask.setMatrix(this._tmpMatrixForMask.getArray());
  4128. clipContext._matrixForDraw.setMatrix(this._tmpMatrixForDraw.getArray());
  4129. const clipDrawCount = clipContext._clippingIdCount;
  4130. for (let i = 0; i < clipDrawCount; i++) {
  4131. const clipDrawIndex = clipContext._clippingIdList[i];
  4132. if (!model.getDrawableDynamicFlagVertexPositionsDidChange(clipDrawIndex)) {
  4133. continue;
  4134. }
  4135. renderer.setIsCulling(model.getDrawableCulling(clipDrawIndex) != false);
  4136. renderer.setClippingContextBufferForMask(clipContext);
  4137. renderer.drawMesh(model.getDrawableTextureIndices(clipDrawIndex), model.getDrawableVertexIndexCount(clipDrawIndex), model.getDrawableVertexCount(clipDrawIndex), model.getDrawableVertexIndices(clipDrawIndex), model.getDrawableVertices(clipDrawIndex), model.getDrawableVertexUvs(clipDrawIndex), model.getDrawableOpacity(clipDrawIndex), CubismBlendMode.CubismBlendMode_Normal, false);
  4138. }
  4139. }
  4140. this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, s_fbo);
  4141. renderer.setClippingContextBufferForMask(null);
  4142. this.gl.viewport(s_viewport[0], s_viewport[1], s_viewport[2], s_viewport[3]);
  4143. }
  4144. }
  4145. findSameClip(drawableMasks, drawableMaskCounts) {
  4146. for (let i = 0; i < this._clippingContextListForMask.length; i++) {
  4147. const clippingContext = this._clippingContextListForMask[i];
  4148. const count = clippingContext._clippingIdCount;
  4149. if (count != drawableMaskCounts) {
  4150. continue;
  4151. }
  4152. let sameCount = 0;
  4153. for (let j = 0; j < count; j++) {
  4154. const clipId = clippingContext._clippingIdList[j];
  4155. for (let k = 0; k < count; k++) {
  4156. if (drawableMasks[k] == clipId) {
  4157. sameCount++;
  4158. break;
  4159. }
  4160. }
  4161. }
  4162. if (sameCount == count) {
  4163. return clippingContext;
  4164. }
  4165. }
  4166. return null;
  4167. }
  4168. setupLayoutBounds(usingClipCount) {
  4169. let div = usingClipCount / ColorChannelCount;
  4170. let mod = usingClipCount % ColorChannelCount;
  4171. div = ~~div;
  4172. mod = ~~mod;
  4173. let curClipIndex = 0;
  4174. for (let channelNo = 0; channelNo < ColorChannelCount; channelNo++) {
  4175. const layoutCount = div + (channelNo < mod ? 1 : 0);
  4176. if (layoutCount == 0)
  4177. ;
  4178. else if (layoutCount == 1) {
  4179. const clipContext = this._clippingContextListForMask[curClipIndex++];
  4180. clipContext._layoutChannelNo = channelNo;
  4181. clipContext._layoutBounds.x = 0;
  4182. clipContext._layoutBounds.y = 0;
  4183. clipContext._layoutBounds.width = 1;
  4184. clipContext._layoutBounds.height = 1;
  4185. } else if (layoutCount == 2) {
  4186. for (let i = 0; i < layoutCount; i++) {
  4187. let xpos = i % 2;
  4188. xpos = ~~xpos;
  4189. const cc = this._clippingContextListForMask[curClipIndex++];
  4190. cc._layoutChannelNo = channelNo;
  4191. cc._layoutBounds.x = xpos * 0.5;
  4192. cc._layoutBounds.y = 0;
  4193. cc._layoutBounds.width = 0.5;
  4194. cc._layoutBounds.height = 1;
  4195. }
  4196. } else if (layoutCount <= 4) {
  4197. for (let i = 0; i < layoutCount; i++) {
  4198. let xpos = i % 2;
  4199. let ypos = i / 2;
  4200. xpos = ~~xpos;
  4201. ypos = ~~ypos;
  4202. const cc = this._clippingContextListForMask[curClipIndex++];
  4203. cc._layoutChannelNo = channelNo;
  4204. cc._layoutBounds.x = xpos * 0.5;
  4205. cc._layoutBounds.y = ypos * 0.5;
  4206. cc._layoutBounds.width = 0.5;
  4207. cc._layoutBounds.height = 0.5;
  4208. }
  4209. } else if (layoutCount <= 9) {
  4210. for (let i = 0; i < layoutCount; i++) {
  4211. let xpos = i % 3;
  4212. let ypos = i / 3;
  4213. xpos = ~~xpos;
  4214. ypos = ~~ypos;
  4215. const cc = this._clippingContextListForMask[curClipIndex++];
  4216. cc._layoutChannelNo = channelNo;
  4217. cc._layoutBounds.x = xpos / 3;
  4218. cc._layoutBounds.y = ypos / 3;
  4219. cc._layoutBounds.width = 1 / 3;
  4220. cc._layoutBounds.height = 1 / 3;
  4221. }
  4222. } else if (CubismConfig.supportMoreMaskDivisions && layoutCount <= 16) {
  4223. for (let i = 0; i < layoutCount; i++) {
  4224. let xpos = i % 4;
  4225. let ypos = i / 4;
  4226. xpos = ~~xpos;
  4227. ypos = ~~ypos;
  4228. const cc = this._clippingContextListForMask[curClipIndex++];
  4229. cc._layoutChannelNo = channelNo;
  4230. cc._layoutBounds.x = xpos / 4;
  4231. cc._layoutBounds.y = ypos / 4;
  4232. cc._layoutBounds.width = 1 / 4;
  4233. cc._layoutBounds.height = 1 / 4;
  4234. }
  4235. } else {
  4236. CubismLogError("not supported mask count : {0}", layoutCount);
  4237. }
  4238. }
  4239. }
  4240. getColorBuffer() {
  4241. return this._colorBuffer;
  4242. }
  4243. getClippingContextListForDraw() {
  4244. return this._clippingContextListForDraw;
  4245. }
  4246. setClippingMaskBufferSize(size) {
  4247. this._clippingMaskBufferSize = size;
  4248. }
  4249. getClippingMaskBufferSize() {
  4250. return this._clippingMaskBufferSize;
  4251. }
  4252. }
  4253. class CubismRenderTextureResource {
  4254. constructor(frameNo, texture) {
  4255. this.frameNo = frameNo;
  4256. this.texture = texture;
  4257. }
  4258. }
  4259. class CubismClippingContext {
  4260. constructor(manager, clippingDrawableIndices, clipCount) {
  4261. this._isUsing = false;
  4262. this._owner = manager;
  4263. this._clippingIdList = clippingDrawableIndices;
  4264. this._clippingIdCount = clipCount;
  4265. this._allClippedDrawRect = new csmRect();
  4266. this._layoutBounds = new csmRect();
  4267. this._clippedDrawableIndexList = [];
  4268. this._matrixForMask = new CubismMatrix44();
  4269. this._matrixForDraw = new CubismMatrix44();
  4270. }
  4271. release() {
  4272. const self = this;
  4273. self._layoutBounds = void 0;
  4274. self._allClippedDrawRect = void 0;
  4275. self._clippedDrawableIndexList = void 0;
  4276. }
  4277. addClippedDrawable(drawableIndex) {
  4278. this._clippedDrawableIndexList.push(drawableIndex);
  4279. }
  4280. getClippingManager() {
  4281. return this._owner;
  4282. }
  4283. setGl(gl) {
  4284. this._owner.setGL(gl);
  4285. }
  4286. }
  4287. class CubismShader_WebGL {
  4288. static getInstance() {
  4289. if (s_instance == null) {
  4290. s_instance = new CubismShader_WebGL();
  4291. return s_instance;
  4292. }
  4293. return s_instance;
  4294. }
  4295. static deleteInstance() {
  4296. if (s_instance) {
  4297. s_instance.release();
  4298. s_instance = void 0;
  4299. }
  4300. }
  4301. constructor() {
  4302. this._shaderSets = [];
  4303. }
  4304. release() {
  4305. this.releaseShaderProgram();
  4306. }
  4307. setupShaderProgram(renderer, textureId, vertexCount, vertexArray, indexArray, uvArray, bufferData, opacity, colorBlendMode, baseColor, isPremultipliedAlpha, matrix4x4, invertedMask) {
  4308. if (!isPremultipliedAlpha) {
  4309. CubismLogError("NoPremultipliedAlpha is not allowed");
  4310. }
  4311. if (this._shaderSets.length == 0) {
  4312. this.generateShaders();
  4313. }
  4314. let SRC_COLOR;
  4315. let DST_COLOR;
  4316. let SRC_ALPHA;
  4317. let DST_ALPHA;
  4318. const clippingContextBufferForMask = renderer.getClippingContextBufferForMask();
  4319. if (clippingContextBufferForMask != null) {
  4320. const shaderSet = this._shaderSets[ShaderNames.ShaderNames_SetupMask];
  4321. this.gl.useProgram(shaderSet.shaderProgram);
  4322. this.gl.activeTexture(this.gl.TEXTURE0);
  4323. this.gl.bindTexture(this.gl.TEXTURE_2D, textureId);
  4324. this.gl.uniform1i(shaderSet.samplerTexture0Location, 0);
  4325. if (bufferData.vertex == null) {
  4326. bufferData.vertex = this.gl.createBuffer();
  4327. }
  4328. this.gl.bindBuffer(this.gl.ARRAY_BUFFER, bufferData.vertex);
  4329. this.gl.bufferData(this.gl.ARRAY_BUFFER, vertexArray, this.gl.DYNAMIC_DRAW);
  4330. this.gl.enableVertexAttribArray(shaderSet.attributePositionLocation);
  4331. this.gl.vertexAttribPointer(shaderSet.attributePositionLocation, 2, this.gl.FLOAT, false, 0, 0);
  4332. if (bufferData.uv == null) {
  4333. bufferData.uv = this.gl.createBuffer();
  4334. }
  4335. this.gl.bindBuffer(this.gl.ARRAY_BUFFER, bufferData.uv);
  4336. this.gl.bufferData(this.gl.ARRAY_BUFFER, uvArray, this.gl.DYNAMIC_DRAW);
  4337. this.gl.enableVertexAttribArray(shaderSet.attributeTexCoordLocation);
  4338. this.gl.vertexAttribPointer(shaderSet.attributeTexCoordLocation, 2, this.gl.FLOAT, false, 0, 0);
  4339. const channelNo = clippingContextBufferForMask._layoutChannelNo;
  4340. const colorChannel = clippingContextBufferForMask.getClippingManager().getChannelFlagAsColor(channelNo);
  4341. this.gl.uniform4f(shaderSet.uniformChannelFlagLocation, colorChannel.R, colorChannel.G, colorChannel.B, colorChannel.A);
  4342. this.gl.uniformMatrix4fv(shaderSet.uniformClipMatrixLocation, false, clippingContextBufferForMask._matrixForMask.getArray());
  4343. const rect = clippingContextBufferForMask._layoutBounds;
  4344. this.gl.uniform4f(shaderSet.uniformBaseColorLocation, rect.x * 2 - 1, rect.y * 2 - 1, rect.getRight() * 2 - 1, rect.getBottom() * 2 - 1);
  4345. SRC_COLOR = this.gl.ZERO;
  4346. DST_COLOR = this.gl.ONE_MINUS_SRC_COLOR;
  4347. SRC_ALPHA = this.gl.ZERO;
  4348. DST_ALPHA = this.gl.ONE_MINUS_SRC_ALPHA;
  4349. } else {
  4350. const clippingContextBufferForDraw = renderer.getClippingContextBufferForDraw();
  4351. const masked = clippingContextBufferForDraw != null;
  4352. const offset = masked ? invertedMask ? 2 : 1 : 0;
  4353. let shaderSet;
  4354. switch (colorBlendMode) {
  4355. case CubismBlendMode.CubismBlendMode_Normal:
  4356. default:
  4357. shaderSet = this._shaderSets[ShaderNames.ShaderNames_NormalPremultipliedAlpha + offset];
  4358. SRC_COLOR = this.gl.ONE;
  4359. DST_COLOR = this.gl.ONE_MINUS_SRC_ALPHA;
  4360. SRC_ALPHA = this.gl.ONE;
  4361. DST_ALPHA = this.gl.ONE_MINUS_SRC_ALPHA;
  4362. break;
  4363. case CubismBlendMode.CubismBlendMode_Additive:
  4364. shaderSet = this._shaderSets[ShaderNames.ShaderNames_AddPremultipliedAlpha + offset];
  4365. SRC_COLOR = this.gl.ONE;
  4366. DST_COLOR = this.gl.ONE;
  4367. SRC_ALPHA = this.gl.ZERO;
  4368. DST_ALPHA = this.gl.ONE;
  4369. break;
  4370. case CubismBlendMode.CubismBlendMode_Multiplicative:
  4371. shaderSet = this._shaderSets[ShaderNames.ShaderNames_MultPremultipliedAlpha + offset];
  4372. SRC_COLOR = this.gl.DST_COLOR;
  4373. DST_COLOR = this.gl.ONE_MINUS_SRC_ALPHA;
  4374. SRC_ALPHA = this.gl.ZERO;
  4375. DST_ALPHA = this.gl.ONE;
  4376. break;
  4377. }
  4378. this.gl.useProgram(shaderSet.shaderProgram);
  4379. if (bufferData.vertex == null) {
  4380. bufferData.vertex = this.gl.createBuffer();
  4381. }
  4382. this.gl.bindBuffer(this.gl.ARRAY_BUFFER, bufferData.vertex);
  4383. this.gl.bufferData(this.gl.ARRAY_BUFFER, vertexArray, this.gl.DYNAMIC_DRAW);
  4384. this.gl.enableVertexAttribArray(shaderSet.attributePositionLocation);
  4385. this.gl.vertexAttribPointer(shaderSet.attributePositionLocation, 2, this.gl.FLOAT, false, 0, 0);
  4386. if (bufferData.uv == null) {
  4387. bufferData.uv = this.gl.createBuffer();
  4388. }
  4389. this.gl.bindBuffer(this.gl.ARRAY_BUFFER, bufferData.uv);
  4390. this.gl.bufferData(this.gl.ARRAY_BUFFER, uvArray, this.gl.DYNAMIC_DRAW);
  4391. this.gl.enableVertexAttribArray(shaderSet.attributeTexCoordLocation);
  4392. this.gl.vertexAttribPointer(shaderSet.attributeTexCoordLocation, 2, this.gl.FLOAT, false, 0, 0);
  4393. if (clippingContextBufferForDraw != null) {
  4394. this.gl.activeTexture(this.gl.TEXTURE1);
  4395. const tex = clippingContextBufferForDraw.getClippingManager().getColorBuffer();
  4396. this.gl.bindTexture(this.gl.TEXTURE_2D, tex);
  4397. this.gl.uniform1i(shaderSet.samplerTexture1Location, 1);
  4398. this.gl.uniformMatrix4fv(shaderSet.uniformClipMatrixLocation, false, clippingContextBufferForDraw._matrixForDraw.getArray());
  4399. const channelNo = clippingContextBufferForDraw._layoutChannelNo;
  4400. const colorChannel = clippingContextBufferForDraw.getClippingManager().getChannelFlagAsColor(channelNo);
  4401. this.gl.uniform4f(shaderSet.uniformChannelFlagLocation, colorChannel.R, colorChannel.G, colorChannel.B, colorChannel.A);
  4402. }
  4403. this.gl.activeTexture(this.gl.TEXTURE0);
  4404. this.gl.bindTexture(this.gl.TEXTURE_2D, textureId);
  4405. this.gl.uniform1i(shaderSet.samplerTexture0Location, 0);
  4406. this.gl.uniformMatrix4fv(shaderSet.uniformMatrixLocation, false, matrix4x4.getArray());
  4407. this.gl.uniform4f(shaderSet.uniformBaseColorLocation, baseColor.R, baseColor.G, baseColor.B, baseColor.A);
  4408. }
  4409. if (bufferData.index == null) {
  4410. bufferData.index = this.gl.createBuffer();
  4411. }
  4412. this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, bufferData.index);
  4413. this.gl.bufferData(this.gl.ELEMENT_ARRAY_BUFFER, indexArray, this.gl.DYNAMIC_DRAW);
  4414. this.gl.blendFuncSeparate(SRC_COLOR, DST_COLOR, SRC_ALPHA, DST_ALPHA);
  4415. }
  4416. releaseShaderProgram() {
  4417. for (let i = 0; i < this._shaderSets.length; i++) {
  4418. this.gl.deleteProgram(this._shaderSets[i].shaderProgram);
  4419. this._shaderSets[i].shaderProgram = 0;
  4420. }
  4421. this._shaderSets = [];
  4422. }
  4423. generateShaders() {
  4424. for (let i = 0; i < shaderCount; i++) {
  4425. this._shaderSets.push({});
  4426. }
  4427. this._shaderSets[0].shaderProgram = this.loadShaderProgram(vertexShaderSrcSetupMask, fragmentShaderSrcsetupMask);
  4428. this._shaderSets[1].shaderProgram = this.loadShaderProgram(vertexShaderSrc, fragmentShaderSrcPremultipliedAlpha);
  4429. this._shaderSets[2].shaderProgram = this.loadShaderProgram(vertexShaderSrcMasked, fragmentShaderSrcMaskPremultipliedAlpha);
  4430. this._shaderSets[3].shaderProgram = this.loadShaderProgram(vertexShaderSrcMasked, fragmentShaderSrcMaskInvertedPremultipliedAlpha);
  4431. this._shaderSets[4].shaderProgram = this._shaderSets[1].shaderProgram;
  4432. this._shaderSets[5].shaderProgram = this._shaderSets[2].shaderProgram;
  4433. this._shaderSets[6].shaderProgram = this._shaderSets[3].shaderProgram;
  4434. this._shaderSets[7].shaderProgram = this._shaderSets[1].shaderProgram;
  4435. this._shaderSets[8].shaderProgram = this._shaderSets[2].shaderProgram;
  4436. this._shaderSets[9].shaderProgram = this._shaderSets[3].shaderProgram;
  4437. this._shaderSets[0].attributePositionLocation = this.gl.getAttribLocation(this._shaderSets[0].shaderProgram, "a_position");
  4438. this._shaderSets[0].attributeTexCoordLocation = this.gl.getAttribLocation(this._shaderSets[0].shaderProgram, "a_texCoord");
  4439. this._shaderSets[0].samplerTexture0Location = this.gl.getUniformLocation(this._shaderSets[0].shaderProgram, "s_texture0");
  4440. this._shaderSets[0].uniformClipMatrixLocation = this.gl.getUniformLocation(this._shaderSets[0].shaderProgram, "u_clipMatrix");
  4441. this._shaderSets[0].uniformChannelFlagLocation = this.gl.getUniformLocation(this._shaderSets[0].shaderProgram, "u_channelFlag");
  4442. this._shaderSets[0].uniformBaseColorLocation = this.gl.getUniformLocation(this._shaderSets[0].shaderProgram, "u_baseColor");
  4443. this._shaderSets[1].attributePositionLocation = this.gl.getAttribLocation(this._shaderSets[1].shaderProgram, "a_position");
  4444. this._shaderSets[1].attributeTexCoordLocation = this.gl.getAttribLocation(this._shaderSets[1].shaderProgram, "a_texCoord");
  4445. this._shaderSets[1].samplerTexture0Location = this.gl.getUniformLocation(this._shaderSets[1].shaderProgram, "s_texture0");
  4446. this._shaderSets[1].uniformMatrixLocation = this.gl.getUniformLocation(this._shaderSets[1].shaderProgram, "u_matrix");
  4447. this._shaderSets[1].uniformBaseColorLocation = this.gl.getUniformLocation(this._shaderSets[1].shaderProgram, "u_baseColor");
  4448. this._shaderSets[2].attributePositionLocation = this.gl.getAttribLocation(this._shaderSets[2].shaderProgram, "a_position");
  4449. this._shaderSets[2].attributeTexCoordLocation = this.gl.getAttribLocation(this._shaderSets[2].shaderProgram, "a_texCoord");
  4450. this._shaderSets[2].samplerTexture0Location = this.gl.getUniformLocation(this._shaderSets[2].shaderProgram, "s_texture0");
  4451. this._shaderSets[2].samplerTexture1Location = this.gl.getUniformLocation(this._shaderSets[2].shaderProgram, "s_texture1");
  4452. this._shaderSets[2].uniformMatrixLocation = this.gl.getUniformLocation(this._shaderSets[2].shaderProgram, "u_matrix");
  4453. this._shaderSets[2].uniformClipMatrixLocation = this.gl.getUniformLocation(this._shaderSets[2].shaderProgram, "u_clipMatrix");
  4454. this._shaderSets[2].uniformChannelFlagLocation = this.gl.getUniformLocation(this._shaderSets[2].shaderProgram, "u_channelFlag");
  4455. this._shaderSets[2].uniformBaseColorLocation = this.gl.getUniformLocation(this._shaderSets[2].shaderProgram, "u_baseColor");
  4456. this._shaderSets[3].attributePositionLocation = this.gl.getAttribLocation(this._shaderSets[3].shaderProgram, "a_position");
  4457. this._shaderSets[3].attributeTexCoordLocation = this.gl.getAttribLocation(this._shaderSets[3].shaderProgram, "a_texCoord");
  4458. this._shaderSets[3].samplerTexture0Location = this.gl.getUniformLocation(this._shaderSets[3].shaderProgram, "s_texture0");
  4459. this._shaderSets[3].samplerTexture1Location = this.gl.getUniformLocation(this._shaderSets[3].shaderProgram, "s_texture1");
  4460. this._shaderSets[3].uniformMatrixLocation = this.gl.getUniformLocation(this._shaderSets[3].shaderProgram, "u_matrix");
  4461. this._shaderSets[3].uniformClipMatrixLocation = this.gl.getUniformLocation(this._shaderSets[3].shaderProgram, "u_clipMatrix");
  4462. this._shaderSets[3].uniformChannelFlagLocation = this.gl.getUniformLocation(this._shaderSets[3].shaderProgram, "u_channelFlag");
  4463. this._shaderSets[3].uniformBaseColorLocation = this.gl.getUniformLocation(this._shaderSets[3].shaderProgram, "u_baseColor");
  4464. this._shaderSets[4].attributePositionLocation = this.gl.getAttribLocation(this._shaderSets[4].shaderProgram, "a_position");
  4465. this._shaderSets[4].attributeTexCoordLocation = this.gl.getAttribLocation(this._shaderSets[4].shaderProgram, "a_texCoord");
  4466. this._shaderSets[4].samplerTexture0Location = this.gl.getUniformLocation(this._shaderSets[4].shaderProgram, "s_texture0");
  4467. this._shaderSets[4].uniformMatrixLocation = this.gl.getUniformLocation(this._shaderSets[4].shaderProgram, "u_matrix");
  4468. this._shaderSets[4].uniformBaseColorLocation = this.gl.getUniformLocation(this._shaderSets[4].shaderProgram, "u_baseColor");
  4469. this._shaderSets[5].attributePositionLocation = this.gl.getAttribLocation(this._shaderSets[5].shaderProgram, "a_position");
  4470. this._shaderSets[5].attributeTexCoordLocation = this.gl.getAttribLocation(this._shaderSets[5].shaderProgram, "a_texCoord");
  4471. this._shaderSets[5].samplerTexture0Location = this.gl.getUniformLocation(this._shaderSets[5].shaderProgram, "s_texture0");
  4472. this._shaderSets[5].samplerTexture1Location = this.gl.getUniformLocation(this._shaderSets[5].shaderProgram, "s_texture1");
  4473. this._shaderSets[5].uniformMatrixLocation = this.gl.getUniformLocation(this._shaderSets[5].shaderProgram, "u_matrix");
  4474. this._shaderSets[5].uniformClipMatrixLocation = this.gl.getUniformLocation(this._shaderSets[5].shaderProgram, "u_clipMatrix");
  4475. this._shaderSets[5].uniformChannelFlagLocation = this.gl.getUniformLocation(this._shaderSets[5].shaderProgram, "u_channelFlag");
  4476. this._shaderSets[5].uniformBaseColorLocation = this.gl.getUniformLocation(this._shaderSets[5].shaderProgram, "u_baseColor");
  4477. this._shaderSets[6].attributePositionLocation = this.gl.getAttribLocation(this._shaderSets[6].shaderProgram, "a_position");
  4478. this._shaderSets[6].attributeTexCoordLocation = this.gl.getAttribLocation(this._shaderSets[6].shaderProgram, "a_texCoord");
  4479. this._shaderSets[6].samplerTexture0Location = this.gl.getUniformLocation(this._shaderSets[6].shaderProgram, "s_texture0");
  4480. this._shaderSets[6].samplerTexture1Location = this.gl.getUniformLocation(this._shaderSets[6].shaderProgram, "s_texture1");
  4481. this._shaderSets[6].uniformMatrixLocation = this.gl.getUniformLocation(this._shaderSets[6].shaderProgram, "u_matrix");
  4482. this._shaderSets[6].uniformClipMatrixLocation = this.gl.getUniformLocation(this._shaderSets[6].shaderProgram, "u_clipMatrix");
  4483. this._shaderSets[6].uniformChannelFlagLocation = this.gl.getUniformLocation(this._shaderSets[6].shaderProgram, "u_channelFlag");
  4484. this._shaderSets[6].uniformBaseColorLocation = this.gl.getUniformLocation(this._shaderSets[6].shaderProgram, "u_baseColor");
  4485. this._shaderSets[7].attributePositionLocation = this.gl.getAttribLocation(this._shaderSets[7].shaderProgram, "a_position");
  4486. this._shaderSets[7].attributeTexCoordLocation = this.gl.getAttribLocation(this._shaderSets[7].shaderProgram, "a_texCoord");
  4487. this._shaderSets[7].samplerTexture0Location = this.gl.getUniformLocation(this._shaderSets[7].shaderProgram, "s_texture0");
  4488. this._shaderSets[7].uniformMatrixLocation = this.gl.getUniformLocation(this._shaderSets[7].shaderProgram, "u_matrix");
  4489. this._shaderSets[7].uniformBaseColorLocation = this.gl.getUniformLocation(this._shaderSets[7].shaderProgram, "u_baseColor");
  4490. this._shaderSets[8].attributePositionLocation = this.gl.getAttribLocation(this._shaderSets[8].shaderProgram, "a_position");
  4491. this._shaderSets[8].attributeTexCoordLocation = this.gl.getAttribLocation(this._shaderSets[8].shaderProgram, "a_texCoord");
  4492. this._shaderSets[8].samplerTexture0Location = this.gl.getUniformLocation(this._shaderSets[8].shaderProgram, "s_texture0");
  4493. this._shaderSets[8].samplerTexture1Location = this.gl.getUniformLocation(this._shaderSets[8].shaderProgram, "s_texture1");
  4494. this._shaderSets[8].uniformMatrixLocation = this.gl.getUniformLocation(this._shaderSets[8].shaderProgram, "u_matrix");
  4495. this._shaderSets[8].uniformClipMatrixLocation = this.gl.getUniformLocation(this._shaderSets[8].shaderProgram, "u_clipMatrix");
  4496. this._shaderSets[8].uniformChannelFlagLocation = this.gl.getUniformLocation(this._shaderSets[8].shaderProgram, "u_channelFlag");
  4497. this._shaderSets[8].uniformBaseColorLocation = this.gl.getUniformLocation(this._shaderSets[8].shaderProgram, "u_baseColor");
  4498. this._shaderSets[9].attributePositionLocation = this.gl.getAttribLocation(this._shaderSets[9].shaderProgram, "a_position");
  4499. this._shaderSets[9].attributeTexCoordLocation = this.gl.getAttribLocation(this._shaderSets[9].shaderProgram, "a_texCoord");
  4500. this._shaderSets[9].samplerTexture0Location = this.gl.getUniformLocation(this._shaderSets[9].shaderProgram, "s_texture0");
  4501. this._shaderSets[9].samplerTexture1Location = this.gl.getUniformLocation(this._shaderSets[9].shaderProgram, "s_texture1");
  4502. this._shaderSets[9].uniformMatrixLocation = this.gl.getUniformLocation(this._shaderSets[9].shaderProgram, "u_matrix");
  4503. this._shaderSets[9].uniformClipMatrixLocation = this.gl.getUniformLocation(this._shaderSets[9].shaderProgram, "u_clipMatrix");
  4504. this._shaderSets[9].uniformChannelFlagLocation = this.gl.getUniformLocation(this._shaderSets[9].shaderProgram, "u_channelFlag");
  4505. this._shaderSets[9].uniformBaseColorLocation = this.gl.getUniformLocation(this._shaderSets[9].shaderProgram, "u_baseColor");
  4506. }
  4507. loadShaderProgram(vertexShaderSource, fragmentShaderSource) {
  4508. let shaderProgram = this.gl.createProgram();
  4509. let vertShader = this.compileShaderSource(this.gl.VERTEX_SHADER, vertexShaderSource);
  4510. if (!vertShader) {
  4511. CubismLogError("Vertex shader compile error!");
  4512. return 0;
  4513. }
  4514. let fragShader = this.compileShaderSource(this.gl.FRAGMENT_SHADER, fragmentShaderSource);
  4515. if (!fragShader) {
  4516. CubismLogError("Vertex shader compile error!");
  4517. return 0;
  4518. }
  4519. this.gl.attachShader(shaderProgram, vertShader);
  4520. this.gl.attachShader(shaderProgram, fragShader);
  4521. this.gl.linkProgram(shaderProgram);
  4522. const linkStatus = this.gl.getProgramParameter(shaderProgram, this.gl.LINK_STATUS);
  4523. if (!linkStatus) {
  4524. CubismLogError("Failed to link program: {0}", shaderProgram);
  4525. this.gl.deleteShader(vertShader);
  4526. this.gl.deleteShader(fragShader);
  4527. if (shaderProgram) {
  4528. this.gl.deleteProgram(shaderProgram);
  4529. }
  4530. return 0;
  4531. }
  4532. this.gl.deleteShader(vertShader);
  4533. this.gl.deleteShader(fragShader);
  4534. return shaderProgram;
  4535. }
  4536. compileShaderSource(shaderType, shaderSource) {
  4537. const source = shaderSource;
  4538. const shader = this.gl.createShader(shaderType);
  4539. this.gl.shaderSource(shader, source);
  4540. this.gl.compileShader(shader);
  4541. if (!shader) {
  4542. const log = this.gl.getShaderInfoLog(shader);
  4543. CubismLogError("Shader compile log: {0} ", log);
  4544. }
  4545. const status = this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS);
  4546. if (!status) {
  4547. this.gl.deleteShader(shader);
  4548. return null;
  4549. }
  4550. return shader;
  4551. }
  4552. setGl(gl) {
  4553. this.gl = gl;
  4554. }
  4555. }
  4556. var ShaderNames = /* @__PURE__ */ ((ShaderNames2) => {
  4557. ShaderNames2[ShaderNames2["ShaderNames_SetupMask"] = 0] = "ShaderNames_SetupMask";
  4558. ShaderNames2[ShaderNames2["ShaderNames_NormalPremultipliedAlpha"] = 1] = "ShaderNames_NormalPremultipliedAlpha";
  4559. ShaderNames2[ShaderNames2["ShaderNames_NormalMaskedPremultipliedAlpha"] = 2] = "ShaderNames_NormalMaskedPremultipliedAlpha";
  4560. ShaderNames2[ShaderNames2["ShaderNames_NomralMaskedInvertedPremultipliedAlpha"] = 3] = "ShaderNames_NomralMaskedInvertedPremultipliedAlpha";
  4561. ShaderNames2[ShaderNames2["ShaderNames_AddPremultipliedAlpha"] = 4] = "ShaderNames_AddPremultipliedAlpha";
  4562. ShaderNames2[ShaderNames2["ShaderNames_AddMaskedPremultipliedAlpha"] = 5] = "ShaderNames_AddMaskedPremultipliedAlpha";
  4563. ShaderNames2[ShaderNames2["ShaderNames_AddMaskedPremultipliedAlphaInverted"] = 6] = "ShaderNames_AddMaskedPremultipliedAlphaInverted";
  4564. ShaderNames2[ShaderNames2["ShaderNames_MultPremultipliedAlpha"] = 7] = "ShaderNames_MultPremultipliedAlpha";
  4565. ShaderNames2[ShaderNames2["ShaderNames_MultMaskedPremultipliedAlpha"] = 8] = "ShaderNames_MultMaskedPremultipliedAlpha";
  4566. ShaderNames2[ShaderNames2["ShaderNames_MultMaskedPremultipliedAlphaInverted"] = 9] = "ShaderNames_MultMaskedPremultipliedAlphaInverted";
  4567. return ShaderNames2;
  4568. })(ShaderNames || {});
  4569. const vertexShaderSrcSetupMask = "attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;varying vec4 v_myPos;uniform mat4 u_clipMatrix;void main(){ gl_Position = u_clipMatrix * a_position; v_myPos = u_clipMatrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}";
  4570. const fragmentShaderSrcsetupMask = "precision mediump float;varying vec2 v_texCoord;varying vec4 v_myPos;uniform vec4 u_baseColor;uniform vec4 u_channelFlag;uniform sampler2D s_texture0;void main(){ float isInside = step(u_baseColor.x, v_myPos.x/v_myPos.w) * step(u_baseColor.y, v_myPos.y/v_myPos.w) * step(v_myPos.x/v_myPos.w, u_baseColor.z) * step(v_myPos.y/v_myPos.w, u_baseColor.w); gl_FragColor = u_channelFlag * texture2D(s_texture0, v_texCoord).a * isInside;}";
  4571. const vertexShaderSrc = "attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;uniform mat4 u_matrix;void main(){ gl_Position = u_matrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}";
  4572. const vertexShaderSrcMasked = "attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform mat4 u_matrix;uniform mat4 u_clipMatrix;void main(){ gl_Position = u_matrix * a_position; v_clipPos = u_clipMatrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}";
  4573. const fragmentShaderSrcPremultipliedAlpha = "precision mediump float;varying vec2 v_texCoord;uniform vec4 u_baseColor;uniform sampler2D s_texture0;void main(){ gl_FragColor = texture2D(s_texture0 , v_texCoord) * u_baseColor;}";
  4574. const fragmentShaderSrcMaskPremultipliedAlpha = "precision mediump float;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform vec4 u_baseColor;uniform vec4 u_channelFlag;uniform sampler2D s_texture0;uniform sampler2D s_texture1;void main(){ vec4 col_formask = texture2D(s_texture0 , v_texCoord) * u_baseColor; vec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag; float maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a; col_formask = col_formask * maskVal; gl_FragColor = col_formask;}";
  4575. const fragmentShaderSrcMaskInvertedPremultipliedAlpha = "precision mediump float;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform sampler2D s_texture0;uniform sampler2D s_texture1;uniform vec4 u_channelFlag;uniform vec4 u_baseColor;void main(){vec4 col_formask = texture2D(s_texture0, v_texCoord) * u_baseColor;vec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag;float maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a;col_formask = col_formask * (1.0 - maskVal);gl_FragColor = col_formask;}";
  4576. class CubismRenderer_WebGL extends CubismRenderer {
  4577. constructor() {
  4578. super();
  4579. this._clippingContextBufferForMask = null;
  4580. this._clippingContextBufferForDraw = null;
  4581. this._clippingManager = new CubismClippingManager_WebGL();
  4582. this.firstDraw = true;
  4583. this._textures = {};
  4584. this._sortedDrawableIndexList = [];
  4585. this._bufferData = {
  4586. vertex: null,
  4587. uv: null,
  4588. index: null
  4589. };
  4590. }
  4591. initialize(model) {
  4592. if (model.isUsingMasking()) {
  4593. this._clippingManager = new CubismClippingManager_WebGL();
  4594. this._clippingManager.initialize(model, model.getDrawableCount(), model.getDrawableMasks(), model.getDrawableMaskCounts());
  4595. }
  4596. for (let i = model.getDrawableCount() - 1; i >= 0; i--) {
  4597. this._sortedDrawableIndexList[i] = 0;
  4598. }
  4599. super.initialize(model);
  4600. }
  4601. bindTexture(modelTextureNo, glTexture) {
  4602. this._textures[modelTextureNo] = glTexture;
  4603. }
  4604. getBindedTextures() {
  4605. return this._textures;
  4606. }
  4607. setClippingMaskBufferSize(size) {
  4608. this._clippingManager.release();
  4609. this._clippingManager = new CubismClippingManager_WebGL();
  4610. this._clippingManager.setClippingMaskBufferSize(size);
  4611. this._clippingManager.initialize(this.getModel(), this.getModel().getDrawableCount(), this.getModel().getDrawableMasks(), this.getModel().getDrawableMaskCounts());
  4612. }
  4613. getClippingMaskBufferSize() {
  4614. return this._clippingManager.getClippingMaskBufferSize();
  4615. }
  4616. release() {
  4617. var _a, _b, _c;
  4618. const self = this;
  4619. this._clippingManager.release();
  4620. self._clippingManager = void 0;
  4621. (_a = this.gl) == null ? void 0 : _a.deleteBuffer(this._bufferData.vertex);
  4622. this._bufferData.vertex = null;
  4623. (_b = this.gl) == null ? void 0 : _b.deleteBuffer(this._bufferData.uv);
  4624. this._bufferData.uv = null;
  4625. (_c = this.gl) == null ? void 0 : _c.deleteBuffer(this._bufferData.index);
  4626. this._bufferData.index = null;
  4627. self._bufferData = void 0;
  4628. self._textures = void 0;
  4629. }
  4630. doDrawModel() {
  4631. this.preDraw();
  4632. if (this._clippingManager != null) {
  4633. this._clippingManager.setupClippingContext(this.getModel(), this);
  4634. }
  4635. const drawableCount = this.getModel().getDrawableCount();
  4636. const renderOrder = this.getModel().getDrawableRenderOrders();
  4637. for (let i = 0; i < drawableCount; ++i) {
  4638. const order = renderOrder[i];
  4639. this._sortedDrawableIndexList[order] = i;
  4640. }
  4641. for (let i = 0; i < drawableCount; ++i) {
  4642. const drawableIndex = this._sortedDrawableIndexList[i];
  4643. if (!this.getModel().getDrawableDynamicFlagIsVisible(drawableIndex)) {
  4644. continue;
  4645. }
  4646. this.setClippingContextBufferForDraw(this._clippingManager != null ? this._clippingManager.getClippingContextListForDraw()[drawableIndex] : null);
  4647. this.setIsCulling(this.getModel().getDrawableCulling(drawableIndex));
  4648. this.drawMesh(this.getModel().getDrawableTextureIndices(drawableIndex), this.getModel().getDrawableVertexIndexCount(drawableIndex), this.getModel().getDrawableVertexCount(drawableIndex), this.getModel().getDrawableVertexIndices(drawableIndex), this.getModel().getDrawableVertices(drawableIndex), this.getModel().getDrawableVertexUvs(drawableIndex), this.getModel().getDrawableOpacity(drawableIndex), this.getModel().getDrawableBlendMode(drawableIndex), this.getModel().getDrawableInvertedMaskBit(drawableIndex));
  4649. }
  4650. }
  4651. drawMesh(textureNo, indexCount, vertexCount, indexArray, vertexArray, uvArray, opacity, colorBlendMode, invertedMask) {
  4652. if (this.isCulling()) {
  4653. this.gl.enable(this.gl.CULL_FACE);
  4654. } else {
  4655. this.gl.disable(this.gl.CULL_FACE);
  4656. }
  4657. this.gl.frontFace(this.gl.CCW);
  4658. const modelColorRGBA = this.getModelColor();
  4659. if (this.getClippingContextBufferForMask() == null) {
  4660. modelColorRGBA.A *= opacity;
  4661. if (this.isPremultipliedAlpha()) {
  4662. modelColorRGBA.R *= modelColorRGBA.A;
  4663. modelColorRGBA.G *= modelColorRGBA.A;
  4664. modelColorRGBA.B *= modelColorRGBA.A;
  4665. }
  4666. }
  4667. let drawtexture = null;
  4668. if (this._textures[textureNo] != null) {
  4669. drawtexture = this._textures[textureNo];
  4670. }
  4671. CubismShader_WebGL.getInstance().setupShaderProgram(this, drawtexture, vertexCount, vertexArray, indexArray, uvArray, this._bufferData, opacity, colorBlendMode, modelColorRGBA, this.isPremultipliedAlpha(), this.getMvpMatrix(), invertedMask);
  4672. this.gl.drawElements(this.gl.TRIANGLES, indexCount, this.gl.UNSIGNED_SHORT, 0);
  4673. this.gl.useProgram(null);
  4674. this.setClippingContextBufferForDraw(null);
  4675. this.setClippingContextBufferForMask(null);
  4676. }
  4677. static doStaticRelease() {
  4678. CubismShader_WebGL.deleteInstance();
  4679. }
  4680. setRenderState(fbo, viewport) {
  4681. s_fbo = fbo;
  4682. s_viewport = viewport;
  4683. }
  4684. preDraw() {
  4685. if (this.firstDraw) {
  4686. this.firstDraw = false;
  4687. this._anisortopy = this.gl.getExtension("EXT_texture_filter_anisotropic") || this.gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic") || this.gl.getExtension("MOZ_EXT_texture_filter_anisotropic");
  4688. }
  4689. this.gl.disable(this.gl.SCISSOR_TEST);
  4690. this.gl.disable(this.gl.STENCIL_TEST);
  4691. this.gl.disable(this.gl.DEPTH_TEST);
  4692. this.gl.frontFace(this.gl.CW);
  4693. this.gl.enable(this.gl.BLEND);
  4694. this.gl.colorMask(true, true, true, true);
  4695. this.gl.bindBuffer(this.gl.ARRAY_BUFFER, null);
  4696. this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER, null);
  4697. }
  4698. setClippingContextBufferForMask(clip) {
  4699. this._clippingContextBufferForMask = clip;
  4700. }
  4701. getClippingContextBufferForMask() {
  4702. return this._clippingContextBufferForMask;
  4703. }
  4704. setClippingContextBufferForDraw(clip) {
  4705. this._clippingContextBufferForDraw = clip;
  4706. }
  4707. getClippingContextBufferForDraw() {
  4708. return this._clippingContextBufferForDraw;
  4709. }
  4710. startUp(gl) {
  4711. this.gl = gl;
  4712. this._clippingManager.setGL(gl);
  4713. CubismShader_WebGL.getInstance().setGl(gl);
  4714. }
  4715. }
  4716. CubismRenderer.staticRelease = () => {
  4717. CubismRenderer_WebGL.doStaticRelease();
  4718. };
  4719. const tempMatrix = new CubismMatrix44();
  4720. class Cubism4InternalModel extends InternalModel {
  4721. constructor(coreModel, settings, options) {
  4722. super();
  4723. this.lipSync = true;
  4724. this.breath = CubismBreath.create();
  4725. this.renderer = new CubismRenderer_WebGL();
  4726. this.idParamAngleX = ParamAngleX;
  4727. this.idParamAngleY = ParamAngleY;
  4728. this.idParamAngleZ = ParamAngleZ;
  4729. this.idParamEyeBallX = ParamEyeBallX;
  4730. this.idParamEyeBallY = ParamEyeBallY;
  4731. this.idParamBodyAngleX = ParamBodyAngleX;
  4732. this.idParamBreath = ParamBreath;
  4733. this.pixelsPerUnit = 1;
  4734. this.centeringTransform = new Matrix();
  4735. this.coreModel = coreModel;
  4736. this.settings = settings;
  4737. this.motionManager = new Cubism4MotionManager(settings, options);
  4738. this.init();
  4739. }
  4740. init() {
  4741. var _a;
  4742. super.init();
  4743. if (((_a = this.settings.getEyeBlinkParameters()) == null ? void 0 : _a.length) > 0) {
  4744. this.eyeBlink = CubismEyeBlink.create(this.settings);
  4745. }
  4746. this.breath.setParameters([
  4747. new BreathParameterData(this.idParamAngleX, 0, 15, 6.5345, 0.5),
  4748. new BreathParameterData(this.idParamAngleY, 0, 8, 3.5345, 0.5),
  4749. new BreathParameterData(this.idParamAngleZ, 0, 10, 5.5345, 0.5),
  4750. new BreathParameterData(this.idParamBodyAngleX, 0, 4, 15.5345, 0.5),
  4751. new BreathParameterData(this.idParamBreath, 0, 0.5, 3.2345, 0.5)
  4752. ]);
  4753. this.renderer.initialize(this.coreModel);
  4754. this.renderer.setIsPremultipliedAlpha(true);
  4755. }
  4756. getSize() {
  4757. return [this.coreModel.getModel().canvasinfo.CanvasWidth, this.coreModel.getModel().canvasinfo.CanvasHeight];
  4758. }
  4759. getLayout() {
  4760. const layout = {};
  4761. if (this.settings.layout) {
  4762. for (const key of Object.keys(this.settings.layout)) {
  4763. const commonKey = key.charAt(0).toLowerCase() + key.slice(1);
  4764. layout[commonKey] = this.settings.layout[key];
  4765. }
  4766. }
  4767. return layout;
  4768. }
  4769. setupLayout() {
  4770. super.setupLayout();
  4771. this.pixelsPerUnit = this.coreModel.getModel().canvasinfo.PixelsPerUnit;
  4772. this.centeringTransform.scale(this.pixelsPerUnit, this.pixelsPerUnit).translate(this.originalWidth / 2, this.originalHeight / 2);
  4773. }
  4774. updateWebGLContext(gl, glContextID) {
  4775. this.renderer.firstDraw = true;
  4776. this.renderer._bufferData = {
  4777. vertex: null,
  4778. uv: null,
  4779. index: null
  4780. };
  4781. this.renderer.startUp(gl);
  4782. this.renderer._clippingManager._currentFrameNo = glContextID;
  4783. this.renderer._clippingManager._maskTexture = void 0;
  4784. CubismShader_WebGL.getInstance()._shaderSets = [];
  4785. }
  4786. bindTexture(index, texture) {
  4787. this.renderer.bindTexture(index, texture);
  4788. }
  4789. getHitAreaDefs() {
  4790. var _a, _b;
  4791. return (_b = (_a = this.settings.hitAreas) == null ? void 0 : _a.map((hitArea) => ({
  4792. id: hitArea.Id,
  4793. name: hitArea.Name,
  4794. index: this.coreModel.getDrawableIndex(hitArea.Id)
  4795. }))) != null ? _b : [];
  4796. }
  4797. getDrawableIDs() {
  4798. return this.coreModel.getDrawableIds();
  4799. }
  4800. getDrawableIndex(id) {
  4801. return this.coreModel.getDrawableIndex(id);
  4802. }
  4803. getDrawableVertices(drawIndex) {
  4804. if (typeof drawIndex === "string") {
  4805. drawIndex = this.coreModel.getDrawableIndex(drawIndex);
  4806. if (drawIndex === -1)
  4807. throw new TypeError("Unable to find drawable ID: " + drawIndex);
  4808. }
  4809. const arr = this.coreModel.getDrawableVertices(drawIndex).slice();
  4810. for (let i = 0; i < arr.length; i += 2) {
  4811. arr[i] = arr[i] * this.pixelsPerUnit + this.originalWidth / 2;
  4812. arr[i + 1] = -arr[i + 1] * this.pixelsPerUnit + this.originalHeight / 2;
  4813. }
  4814. return arr;
  4815. }
  4816. updateTransform(transform) {
  4817. this.drawingMatrix.copyFrom(this.centeringTransform).prepend(this.localTransform).prepend(transform);
  4818. }
  4819. update(dt, now) {
  4820. var _a, _b, _c, _d;
  4821. super.update(dt, now);
  4822. dt /= 1e3;
  4823. now /= 1e3;
  4824. const model = this.coreModel;
  4825. this.emit("beforeMotionUpdate");
  4826. const motionUpdated = this.motionManager.update(this.coreModel, now);
  4827. this.emit("afterMotionUpdate");
  4828. model.saveParameters();
  4829. (_a = this.motionManager.expressionManager) == null ? void 0 : _a.update(model, now);
  4830. if (!motionUpdated) {
  4831. (_b = this.eyeBlink) == null ? void 0 : _b.updateParameters(model, dt);
  4832. }
  4833. this.updateFocus();
  4834. this.updateNaturalMovements(dt * 1e3, now * 1e3);
  4835. (_c = this.physics) == null ? void 0 : _c.evaluate(model, dt);
  4836. (_d = this.pose) == null ? void 0 : _d.updateParameters(model, dt);
  4837. this.emit("beforeModelUpdate");
  4838. model.update();
  4839. model.loadParameters();
  4840. }
  4841. updateFocus() {
  4842. this.coreModel.addParameterValueById(this.idParamEyeBallX, this.focusController.x);
  4843. this.coreModel.addParameterValueById(this.idParamEyeBallY, this.focusController.y);
  4844. this.coreModel.addParameterValueById(this.idParamAngleX, this.focusController.x * 30);
  4845. this.coreModel.addParameterValueById(this.idParamAngleY, this.focusController.y * 30);
  4846. this.coreModel.addParameterValueById(this.idParamAngleZ, this.focusController.x * this.focusController.y * -30);
  4847. this.coreModel.addParameterValueById(this.idParamBodyAngleX, this.focusController.x * 10);
  4848. }
  4849. updateNaturalMovements(dt, now) {
  4850. var _a;
  4851. (_a = this.breath) == null ? void 0 : _a.updateParameters(this.coreModel, dt / 1e3);
  4852. }
  4853. draw(gl) {
  4854. const matrix = this.drawingMatrix;
  4855. const array = tempMatrix.getArray();
  4856. array[0] = matrix.a;
  4857. array[1] = matrix.b;
  4858. array[4] = -matrix.c;
  4859. array[5] = -matrix.d;
  4860. array[12] = matrix.tx;
  4861. array[13] = matrix.ty;
  4862. this.renderer.setMvpMatrix(tempMatrix);
  4863. this.renderer.setRenderState(gl.getParameter(gl.FRAMEBUFFER_BINDING), this.viewport);
  4864. this.renderer.drawModel();
  4865. }
  4866. destroy() {
  4867. super.destroy();
  4868. this.renderer.release();
  4869. this.coreModel.release();
  4870. this.renderer = void 0;
  4871. this.coreModel = void 0;
  4872. }
  4873. }
  4874. let startupPromise;
  4875. let startupRetries = 20;
  4876. function cubism4Ready() {
  4877. if (CubismFramework.isStarted()) {
  4878. return Promise.resolve();
  4879. }
  4880. startupPromise != null ? startupPromise : startupPromise = new Promise((resolve, reject) => {
  4881. function startUpWithRetry() {
  4882. try {
  4883. startUpCubism4();
  4884. resolve();
  4885. } catch (e) {
  4886. startupRetries--;
  4887. if (startupRetries < 0) {
  4888. const err = new Error("Failed to start up Cubism 4 framework.");
  4889. err.cause = e;
  4890. reject(err);
  4891. return;
  4892. }
  4893. logger.log("Cubism4", "Startup failed, retrying 10ms later...");
  4894. setTimeout(startUpWithRetry, 10);
  4895. }
  4896. }
  4897. startUpWithRetry();
  4898. });
  4899. return startupPromise;
  4900. }
  4901. function startUpCubism4(options) {
  4902. options = Object.assign({
  4903. logFunction: console.log,
  4904. loggingLevel: LogLevel.LogLevel_Verbose
  4905. }, options);
  4906. CubismFramework.startUp(options);
  4907. CubismFramework.initialize();
  4908. }
  4909. const Epsilon = 1e-3;
  4910. const DefaultFadeInSeconds = 0.5;
  4911. class CubismPose {
  4912. static create(pose3json) {
  4913. const ret = new CubismPose();
  4914. if (typeof pose3json.FadeInTime === "number") {
  4915. ret._fadeTimeSeconds = pose3json.FadeInTime;
  4916. if (ret._fadeTimeSeconds <= 0) {
  4917. ret._fadeTimeSeconds = DefaultFadeInSeconds;
  4918. }
  4919. }
  4920. const poseListInfo = pose3json.Groups;
  4921. const poseCount = poseListInfo.length;
  4922. for (let poseIndex = 0; poseIndex < poseCount; ++poseIndex) {
  4923. const idListInfo = poseListInfo[poseIndex];
  4924. const idCount = idListInfo.length;
  4925. let groupCount = 0;
  4926. for (let groupIndex = 0; groupIndex < idCount; ++groupIndex) {
  4927. const partInfo = idListInfo[groupIndex];
  4928. const partData = new PartData();
  4929. partData.partId = partInfo.Id;
  4930. const linkListInfo = partInfo.Link;
  4931. if (linkListInfo) {
  4932. const linkCount = linkListInfo.length;
  4933. for (let linkIndex = 0; linkIndex < linkCount; ++linkIndex) {
  4934. const linkPart = new PartData();
  4935. linkPart.partId = linkListInfo[linkIndex];
  4936. partData.link.push(linkPart);
  4937. }
  4938. }
  4939. ret._partGroups.push(partData);
  4940. ++groupCount;
  4941. }
  4942. ret._partGroupCounts.push(groupCount);
  4943. }
  4944. return ret;
  4945. }
  4946. updateParameters(model, deltaTimeSeconds) {
  4947. if (model != this._lastModel) {
  4948. this.reset(model);
  4949. }
  4950. this._lastModel = model;
  4951. if (deltaTimeSeconds < 0) {
  4952. deltaTimeSeconds = 0;
  4953. }
  4954. let beginIndex = 0;
  4955. for (let i = 0; i < this._partGroupCounts.length; i++) {
  4956. const partGroupCount = this._partGroupCounts[i];
  4957. this.doFade(model, deltaTimeSeconds, beginIndex, partGroupCount);
  4958. beginIndex += partGroupCount;
  4959. }
  4960. this.copyPartOpacities(model);
  4961. }
  4962. reset(model) {
  4963. let beginIndex = 0;
  4964. for (let i = 0; i < this._partGroupCounts.length; ++i) {
  4965. const groupCount = this._partGroupCounts[i];
  4966. for (let j = beginIndex; j < beginIndex + groupCount; ++j) {
  4967. this._partGroups[j].initialize(model);
  4968. const partsIndex = this._partGroups[j].partIndex;
  4969. const paramIndex = this._partGroups[j].parameterIndex;
  4970. if (partsIndex < 0) {
  4971. continue;
  4972. }
  4973. model.setPartOpacityByIndex(partsIndex, j == beginIndex ? 1 : 0);
  4974. model.setParameterValueByIndex(paramIndex, j == beginIndex ? 1 : 0);
  4975. for (let k = 0; k < this._partGroups[j].link.length; ++k) {
  4976. this._partGroups[j].link[k].initialize(model);
  4977. }
  4978. }
  4979. beginIndex += groupCount;
  4980. }
  4981. }
  4982. copyPartOpacities(model) {
  4983. for (let groupIndex = 0; groupIndex < this._partGroups.length; ++groupIndex) {
  4984. const partData = this._partGroups[groupIndex];
  4985. if (partData.link.length == 0) {
  4986. continue;
  4987. }
  4988. const partIndex = this._partGroups[groupIndex].partIndex;
  4989. const opacity = model.getPartOpacityByIndex(partIndex);
  4990. for (let linkIndex = 0; linkIndex < partData.link.length; ++linkIndex) {
  4991. const linkPart = partData.link[linkIndex];
  4992. const linkPartIndex = linkPart.partIndex;
  4993. if (linkPartIndex < 0) {
  4994. continue;
  4995. }
  4996. model.setPartOpacityByIndex(linkPartIndex, opacity);
  4997. }
  4998. }
  4999. }
  5000. doFade(model, deltaTimeSeconds, beginIndex, partGroupCount) {
  5001. let visiblePartIndex = -1;
  5002. let newOpacity = 1;
  5003. const phi = 0.5;
  5004. const backOpacityThreshold = 0.15;
  5005. for (let i = beginIndex; i < beginIndex + partGroupCount; ++i) {
  5006. const partIndex = this._partGroups[i].partIndex;
  5007. const paramIndex = this._partGroups[i].parameterIndex;
  5008. if (model.getParameterValueByIndex(paramIndex) > Epsilon) {
  5009. if (visiblePartIndex >= 0) {
  5010. break;
  5011. }
  5012. visiblePartIndex = i;
  5013. newOpacity = model.getPartOpacityByIndex(partIndex);
  5014. newOpacity += deltaTimeSeconds / this._fadeTimeSeconds;
  5015. if (newOpacity > 1) {
  5016. newOpacity = 1;
  5017. }
  5018. }
  5019. }
  5020. if (visiblePartIndex < 0) {
  5021. visiblePartIndex = 0;
  5022. newOpacity = 1;
  5023. }
  5024. for (let i = beginIndex; i < beginIndex + partGroupCount; ++i) {
  5025. const partsIndex = this._partGroups[i].partIndex;
  5026. if (visiblePartIndex == i) {
  5027. model.setPartOpacityByIndex(partsIndex, newOpacity);
  5028. } else {
  5029. let opacity = model.getPartOpacityByIndex(partsIndex);
  5030. let a1;
  5031. if (newOpacity < phi) {
  5032. a1 = newOpacity * (phi - 1) / phi + 1;
  5033. } else {
  5034. a1 = (1 - newOpacity) * phi / (1 - phi);
  5035. }
  5036. const backOpacity = (1 - a1) * (1 - newOpacity);
  5037. if (backOpacity > backOpacityThreshold) {
  5038. a1 = 1 - backOpacityThreshold / (1 - newOpacity);
  5039. }
  5040. if (opacity > a1) {
  5041. opacity = a1;
  5042. }
  5043. model.setPartOpacityByIndex(partsIndex, opacity);
  5044. }
  5045. }
  5046. }
  5047. constructor() {
  5048. this._fadeTimeSeconds = DefaultFadeInSeconds;
  5049. this._lastModel = void 0;
  5050. this._partGroups = [];
  5051. this._partGroupCounts = [];
  5052. }
  5053. }
  5054. class PartData {
  5055. constructor(v) {
  5056. this.parameterIndex = 0;
  5057. this.partIndex = 0;
  5058. this.partId = "";
  5059. this.link = [];
  5060. if (v != void 0) {
  5061. this.assignment(v);
  5062. }
  5063. }
  5064. assignment(v) {
  5065. this.partId = v.partId;
  5066. this.link = v.link.map((link) => link.clone());
  5067. return this;
  5068. }
  5069. initialize(model) {
  5070. this.parameterIndex = model.getParameterIndex(this.partId);
  5071. this.partIndex = model.getPartIndex(this.partId);
  5072. model.setParameterValueByIndex(this.parameterIndex, 1);
  5073. }
  5074. clone() {
  5075. const clonePartData = new PartData();
  5076. clonePartData.partId = this.partId;
  5077. clonePartData.parameterIndex = this.parameterIndex;
  5078. clonePartData.partIndex = this.partIndex;
  5079. clonePartData.link = this.link.map((link) => link.clone());
  5080. return clonePartData;
  5081. }
  5082. }
  5083. class CubismModel {
  5084. update() {
  5085. this._model.update();
  5086. this._model.drawables.resetDynamicFlags();
  5087. }
  5088. getCanvasWidth() {
  5089. if (this._model == null) {
  5090. return 0;
  5091. }
  5092. return this._model.canvasinfo.CanvasWidth / this._model.canvasinfo.PixelsPerUnit;
  5093. }
  5094. getCanvasHeight() {
  5095. if (this._model == null) {
  5096. return 0;
  5097. }
  5098. return this._model.canvasinfo.CanvasHeight / this._model.canvasinfo.PixelsPerUnit;
  5099. }
  5100. saveParameters() {
  5101. const parameterCount = this._model.parameters.count;
  5102. const savedParameterCount = this._savedParameters.length;
  5103. for (let i = 0; i < parameterCount; ++i) {
  5104. if (i < savedParameterCount) {
  5105. this._savedParameters[i] = this._parameterValues[i];
  5106. } else {
  5107. this._savedParameters.push(this._parameterValues[i]);
  5108. }
  5109. }
  5110. }
  5111. getModel() {
  5112. return this._model;
  5113. }
  5114. getPartIndex(partId) {
  5115. let partIndex;
  5116. const partCount = this._model.parts.count;
  5117. for (partIndex = 0; partIndex < partCount; ++partIndex) {
  5118. if (partId == this._partIds[partIndex]) {
  5119. return partIndex;
  5120. }
  5121. }
  5122. if (partId in this._notExistPartId) {
  5123. return this._notExistPartId[partId];
  5124. }
  5125. partIndex = partCount + this._notExistPartId.length;
  5126. this._notExistPartId[partId] = partIndex;
  5127. this._notExistPartOpacities[partIndex] = 0;
  5128. return partIndex;
  5129. }
  5130. getPartCount() {
  5131. return this._model.parts.count;
  5132. }
  5133. setPartOpacityByIndex(partIndex, opacity) {
  5134. if (partIndex in this._notExistPartOpacities) {
  5135. this._notExistPartOpacities[partIndex] = opacity;
  5136. return;
  5137. }
  5138. CSM_ASSERT(0 <= partIndex && partIndex < this.getPartCount());
  5139. this._partOpacities[partIndex] = opacity;
  5140. }
  5141. setPartOpacityById(partId, opacity) {
  5142. const index = this.getPartIndex(partId);
  5143. if (index < 0) {
  5144. return;
  5145. }
  5146. this.setPartOpacityByIndex(index, opacity);
  5147. }
  5148. getPartOpacityByIndex(partIndex) {
  5149. if (partIndex in this._notExistPartOpacities) {
  5150. return this._notExistPartOpacities[partIndex];
  5151. }
  5152. CSM_ASSERT(0 <= partIndex && partIndex < this.getPartCount());
  5153. return this._partOpacities[partIndex];
  5154. }
  5155. getPartOpacityById(partId) {
  5156. const index = this.getPartIndex(partId);
  5157. if (index < 0) {
  5158. return 0;
  5159. }
  5160. return this.getPartOpacityByIndex(index);
  5161. }
  5162. getParameterIndex(parameterId) {
  5163. let parameterIndex;
  5164. const idCount = this._model.parameters.count;
  5165. for (parameterIndex = 0; parameterIndex < idCount; ++parameterIndex) {
  5166. if (parameterId != this._parameterIds[parameterIndex]) {
  5167. continue;
  5168. }
  5169. return parameterIndex;
  5170. }
  5171. if (parameterId in this._notExistParameterId) {
  5172. return this._notExistParameterId[parameterId];
  5173. }
  5174. parameterIndex = this._model.parameters.count + Object.keys(this._notExistParameterId).length;
  5175. this._notExistParameterId[parameterId] = parameterIndex;
  5176. this._notExistParameterValues[parameterIndex] = 0;
  5177. return parameterIndex;
  5178. }
  5179. getParameterCount() {
  5180. return this._model.parameters.count;
  5181. }
  5182. getParameterMaximumValue(parameterIndex) {
  5183. return this._model.parameters.maximumValues[parameterIndex];
  5184. }
  5185. getParameterMinimumValue(parameterIndex) {
  5186. return this._model.parameters.minimumValues[parameterIndex];
  5187. }
  5188. getParameterDefaultValue(parameterIndex) {
  5189. return this._model.parameters.defaultValues[parameterIndex];
  5190. }
  5191. getParameterValueByIndex(parameterIndex) {
  5192. if (parameterIndex in this._notExistParameterValues) {
  5193. return this._notExistParameterValues[parameterIndex];
  5194. }
  5195. CSM_ASSERT(0 <= parameterIndex && parameterIndex < this.getParameterCount());
  5196. return this._parameterValues[parameterIndex];
  5197. }
  5198. getParameterValueById(parameterId) {
  5199. const parameterIndex = this.getParameterIndex(parameterId);
  5200. return this.getParameterValueByIndex(parameterIndex);
  5201. }
  5202. setParameterValueByIndex(parameterIndex, value, weight = 1) {
  5203. if (parameterIndex in this._notExistParameterValues) {
  5204. this._notExistParameterValues[parameterIndex] = weight == 1 ? value : this._notExistParameterValues[parameterIndex] * (1 - weight) + value * weight;
  5205. return;
  5206. }
  5207. CSM_ASSERT(0 <= parameterIndex && parameterIndex < this.getParameterCount());
  5208. if (this._model.parameters.maximumValues[parameterIndex] < value) {
  5209. value = this._model.parameters.maximumValues[parameterIndex];
  5210. }
  5211. if (this._model.parameters.minimumValues[parameterIndex] > value) {
  5212. value = this._model.parameters.minimumValues[parameterIndex];
  5213. }
  5214. this._parameterValues[parameterIndex] = weight == 1 ? value : this._parameterValues[parameterIndex] = this._parameterValues[parameterIndex] * (1 - weight) + value * weight;
  5215. }
  5216. setParameterValueById(parameterId, value, weight = 1) {
  5217. const index = this.getParameterIndex(parameterId);
  5218. this.setParameterValueByIndex(index, value, weight);
  5219. }
  5220. addParameterValueByIndex(parameterIndex, value, weight = 1) {
  5221. this.setParameterValueByIndex(parameterIndex, this.getParameterValueByIndex(parameterIndex) + value * weight);
  5222. }
  5223. addParameterValueById(parameterId, value, weight = 1) {
  5224. const index = this.getParameterIndex(parameterId);
  5225. this.addParameterValueByIndex(index, value, weight);
  5226. }
  5227. multiplyParameterValueById(parameterId, value, weight = 1) {
  5228. const index = this.getParameterIndex(parameterId);
  5229. this.multiplyParameterValueByIndex(index, value, weight);
  5230. }
  5231. multiplyParameterValueByIndex(parameterIndex, value, weight = 1) {
  5232. this.setParameterValueByIndex(parameterIndex, this.getParameterValueByIndex(parameterIndex) * (1 + (value - 1) * weight));
  5233. }
  5234. getDrawableIds() {
  5235. return this._drawableIds.slice();
  5236. }
  5237. getDrawableIndex(drawableId) {
  5238. const drawableCount = this._model.drawables.count;
  5239. for (let drawableIndex = 0; drawableIndex < drawableCount; ++drawableIndex) {
  5240. if (this._drawableIds[drawableIndex] == drawableId) {
  5241. return drawableIndex;
  5242. }
  5243. }
  5244. return -1;
  5245. }
  5246. getDrawableCount() {
  5247. return this._model.drawables.count;
  5248. }
  5249. getDrawableId(drawableIndex) {
  5250. return this._model.drawables.ids[drawableIndex];
  5251. }
  5252. getDrawableRenderOrders() {
  5253. return this._model.drawables.renderOrders;
  5254. }
  5255. getDrawableTextureIndices(drawableIndex) {
  5256. return this._model.drawables.textureIndices[drawableIndex];
  5257. }
  5258. getDrawableDynamicFlagVertexPositionsDidChange(drawableIndex) {
  5259. const dynamicFlags = this._model.drawables.dynamicFlags;
  5260. return Live2DCubismCore.Utils.hasVertexPositionsDidChangeBit(dynamicFlags[drawableIndex]);
  5261. }
  5262. getDrawableVertexIndexCount(drawableIndex) {
  5263. return this._model.drawables.indexCounts[drawableIndex];
  5264. }
  5265. getDrawableVertexCount(drawableIndex) {
  5266. return this._model.drawables.vertexCounts[drawableIndex];
  5267. }
  5268. getDrawableVertices(drawableIndex) {
  5269. return this.getDrawableVertexPositions(drawableIndex);
  5270. }
  5271. getDrawableVertexIndices(drawableIndex) {
  5272. return this._model.drawables.indices[drawableIndex];
  5273. }
  5274. getDrawableVertexPositions(drawableIndex) {
  5275. return this._model.drawables.vertexPositions[drawableIndex];
  5276. }
  5277. getDrawableVertexUvs(drawableIndex) {
  5278. return this._model.drawables.vertexUvs[drawableIndex];
  5279. }
  5280. getDrawableOpacity(drawableIndex) {
  5281. return this._model.drawables.opacities[drawableIndex];
  5282. }
  5283. getDrawableCulling(drawableIndex) {
  5284. const constantFlags = this._model.drawables.constantFlags;
  5285. return !Live2DCubismCore.Utils.hasIsDoubleSidedBit(constantFlags[drawableIndex]);
  5286. }
  5287. getDrawableBlendMode(drawableIndex) {
  5288. const constantFlags = this._model.drawables.constantFlags;
  5289. return Live2DCubismCore.Utils.hasBlendAdditiveBit(constantFlags[drawableIndex]) ? CubismBlendMode.CubismBlendMode_Additive : Live2DCubismCore.Utils.hasBlendMultiplicativeBit(constantFlags[drawableIndex]) ? CubismBlendMode.CubismBlendMode_Multiplicative : CubismBlendMode.CubismBlendMode_Normal;
  5290. }
  5291. getDrawableInvertedMaskBit(drawableIndex) {
  5292. const constantFlags = this._model.drawables.constantFlags;
  5293. return Live2DCubismCore.Utils.hasIsInvertedMaskBit(constantFlags[drawableIndex]);
  5294. }
  5295. getDrawableMasks() {
  5296. return this._model.drawables.masks;
  5297. }
  5298. getDrawableMaskCounts() {
  5299. return this._model.drawables.maskCounts;
  5300. }
  5301. isUsingMasking() {
  5302. for (let d = 0; d < this._model.drawables.count; ++d) {
  5303. if (this._model.drawables.maskCounts[d] <= 0) {
  5304. continue;
  5305. }
  5306. return true;
  5307. }
  5308. return false;
  5309. }
  5310. getDrawableDynamicFlagIsVisible(drawableIndex) {
  5311. const dynamicFlags = this._model.drawables.dynamicFlags;
  5312. return Live2DCubismCore.Utils.hasIsVisibleBit(dynamicFlags[drawableIndex]);
  5313. }
  5314. getDrawableDynamicFlagVisibilityDidChange(drawableIndex) {
  5315. const dynamicFlags = this._model.drawables.dynamicFlags;
  5316. return Live2DCubismCore.Utils.hasVisibilityDidChangeBit(dynamicFlags[drawableIndex]);
  5317. }
  5318. getDrawableDynamicFlagOpacityDidChange(drawableIndex) {
  5319. const dynamicFlags = this._model.drawables.dynamicFlags;
  5320. return Live2DCubismCore.Utils.hasOpacityDidChangeBit(dynamicFlags[drawableIndex]);
  5321. }
  5322. getDrawableDynamicFlagRenderOrderDidChange(drawableIndex) {
  5323. const dynamicFlags = this._model.drawables.dynamicFlags;
  5324. return Live2DCubismCore.Utils.hasRenderOrderDidChangeBit(dynamicFlags[drawableIndex]);
  5325. }
  5326. loadParameters() {
  5327. let parameterCount = this._model.parameters.count;
  5328. const savedParameterCount = this._savedParameters.length;
  5329. if (parameterCount > savedParameterCount) {
  5330. parameterCount = savedParameterCount;
  5331. }
  5332. for (let i = 0; i < parameterCount; ++i) {
  5333. this._parameterValues[i] = this._savedParameters[i];
  5334. }
  5335. }
  5336. initialize() {
  5337. this._parameterValues = this._model.parameters.values;
  5338. this._partOpacities = this._model.parts.opacities;
  5339. this._parameterMaximumValues = this._model.parameters.maximumValues;
  5340. this._parameterMinimumValues = this._model.parameters.minimumValues;
  5341. {
  5342. const parameterIds = this._model.parameters.ids;
  5343. const parameterCount = this._model.parameters.count;
  5344. for (let i = 0; i < parameterCount; ++i) {
  5345. this._parameterIds.push(parameterIds[i]);
  5346. }
  5347. }
  5348. {
  5349. const partIds = this._model.parts.ids;
  5350. const partCount = this._model.parts.count;
  5351. for (let i = 0; i < partCount; ++i) {
  5352. this._partIds.push(partIds[i]);
  5353. }
  5354. }
  5355. {
  5356. const drawableIds = this._model.drawables.ids;
  5357. const drawableCount = this._model.drawables.count;
  5358. for (let i = 0; i < drawableCount; ++i) {
  5359. this._drawableIds.push(drawableIds[i]);
  5360. }
  5361. }
  5362. }
  5363. constructor(model) {
  5364. this._model = model;
  5365. this._savedParameters = [];
  5366. this._parameterIds = [];
  5367. this._drawableIds = [];
  5368. this._partIds = [];
  5369. this._notExistPartId = {};
  5370. this._notExistParameterId = {};
  5371. this._notExistParameterValues = {};
  5372. this._notExistPartOpacities = {};
  5373. this.initialize();
  5374. }
  5375. release() {
  5376. this._model.release();
  5377. this._model = void 0;
  5378. }
  5379. }
  5380. class CubismMoc {
  5381. static create(mocBytes) {
  5382. const moc = Live2DCubismCore.Moc.fromArrayBuffer(mocBytes);
  5383. if (moc) {
  5384. return new CubismMoc(moc);
  5385. }
  5386. throw new Error("Unknown error");
  5387. }
  5388. createModel() {
  5389. let cubismModel;
  5390. const model = Live2DCubismCore.Model.fromMoc(this._moc);
  5391. if (model) {
  5392. cubismModel = new CubismModel(model);
  5393. ++this._modelCount;
  5394. return cubismModel;
  5395. }
  5396. throw new Error("Unknown error");
  5397. }
  5398. deleteModel(model) {
  5399. if (model != null) {
  5400. --this._modelCount;
  5401. }
  5402. }
  5403. constructor(moc) {
  5404. this._moc = moc;
  5405. this._modelCount = 0;
  5406. }
  5407. release() {
  5408. this._moc._release();
  5409. this._moc = void 0;
  5410. }
  5411. }
  5412. var CubismPhysicsTargetType = /* @__PURE__ */ ((CubismPhysicsTargetType2) => {
  5413. CubismPhysicsTargetType2[CubismPhysicsTargetType2["CubismPhysicsTargetType_Parameter"] = 0] = "CubismPhysicsTargetType_Parameter";
  5414. return CubismPhysicsTargetType2;
  5415. })(CubismPhysicsTargetType || {});
  5416. var CubismPhysicsSource = /* @__PURE__ */ ((CubismPhysicsSource2) => {
  5417. CubismPhysicsSource2[CubismPhysicsSource2["CubismPhysicsSource_X"] = 0] = "CubismPhysicsSource_X";
  5418. CubismPhysicsSource2[CubismPhysicsSource2["CubismPhysicsSource_Y"] = 1] = "CubismPhysicsSource_Y";
  5419. CubismPhysicsSource2[CubismPhysicsSource2["CubismPhysicsSource_Angle"] = 2] = "CubismPhysicsSource_Angle";
  5420. return CubismPhysicsSource2;
  5421. })(CubismPhysicsSource || {});
  5422. class CubismPhysicsParticle {
  5423. constructor() {
  5424. this.initialPosition = new CubismVector2(0, 0);
  5425. this.position = new CubismVector2(0, 0);
  5426. this.lastPosition = new CubismVector2(0, 0);
  5427. this.lastGravity = new CubismVector2(0, 0);
  5428. this.force = new CubismVector2(0, 0);
  5429. this.velocity = new CubismVector2(0, 0);
  5430. }
  5431. }
  5432. class CubismPhysicsSubRig {
  5433. constructor() {
  5434. this.normalizationPosition = {};
  5435. this.normalizationAngle = {};
  5436. }
  5437. }
  5438. class CubismPhysicsInput {
  5439. constructor() {
  5440. this.source = {};
  5441. }
  5442. }
  5443. class CubismPhysicsOutput {
  5444. constructor() {
  5445. this.destination = {};
  5446. this.translationScale = new CubismVector2(0, 0);
  5447. }
  5448. }
  5449. class CubismPhysicsRig {
  5450. constructor() {
  5451. this.settings = [];
  5452. this.inputs = [];
  5453. this.outputs = [];
  5454. this.particles = [];
  5455. this.gravity = new CubismVector2(0, 0);
  5456. this.wind = new CubismVector2(0, 0);
  5457. }
  5458. }
  5459. class CubismPhysicsJson {
  5460. constructor(json) {
  5461. this._json = json;
  5462. }
  5463. release() {
  5464. this._json = void 0;
  5465. }
  5466. getGravity() {
  5467. const ret = new CubismVector2(0, 0);
  5468. ret.x = this._json.Meta.EffectiveForces.Gravity.X;
  5469. ret.y = this._json.Meta.EffectiveForces.Gravity.Y;
  5470. return ret;
  5471. }
  5472. getWind() {
  5473. const ret = new CubismVector2(0, 0);
  5474. ret.x = this._json.Meta.EffectiveForces.Wind.X;
  5475. ret.y = this._json.Meta.EffectiveForces.Wind.Y;
  5476. return ret;
  5477. }
  5478. getSubRigCount() {
  5479. return this._json.Meta.PhysicsSettingCount;
  5480. }
  5481. getTotalInputCount() {
  5482. return this._json.Meta.TotalInputCount;
  5483. }
  5484. getTotalOutputCount() {
  5485. return this._json.Meta.TotalOutputCount;
  5486. }
  5487. getVertexCount() {
  5488. return this._json.Meta.VertexCount;
  5489. }
  5490. getNormalizationPositionMinimumValue(physicsSettingIndex) {
  5491. return this._json.PhysicsSettings[physicsSettingIndex].Normalization.Position.Minimum;
  5492. }
  5493. getNormalizationPositionMaximumValue(physicsSettingIndex) {
  5494. return this._json.PhysicsSettings[physicsSettingIndex].Normalization.Position.Maximum;
  5495. }
  5496. getNormalizationPositionDefaultValue(physicsSettingIndex) {
  5497. return this._json.PhysicsSettings[physicsSettingIndex].Normalization.Position.Default;
  5498. }
  5499. getNormalizationAngleMinimumValue(physicsSettingIndex) {
  5500. return this._json.PhysicsSettings[physicsSettingIndex].Normalization.Angle.Minimum;
  5501. }
  5502. getNormalizationAngleMaximumValue(physicsSettingIndex) {
  5503. return this._json.PhysicsSettings[physicsSettingIndex].Normalization.Angle.Maximum;
  5504. }
  5505. getNormalizationAngleDefaultValue(physicsSettingIndex) {
  5506. return this._json.PhysicsSettings[physicsSettingIndex].Normalization.Angle.Default;
  5507. }
  5508. getInputCount(physicsSettingIndex) {
  5509. return this._json.PhysicsSettings[physicsSettingIndex].Input.length;
  5510. }
  5511. getInputWeight(physicsSettingIndex, inputIndex) {
  5512. return this._json.PhysicsSettings[physicsSettingIndex].Input[inputIndex].Weight;
  5513. }
  5514. getInputReflect(physicsSettingIndex, inputIndex) {
  5515. return this._json.PhysicsSettings[physicsSettingIndex].Input[inputIndex].Reflect;
  5516. }
  5517. getInputType(physicsSettingIndex, inputIndex) {
  5518. return this._json.PhysicsSettings[physicsSettingIndex].Input[inputIndex].Type;
  5519. }
  5520. getInputSourceId(physicsSettingIndex, inputIndex) {
  5521. return this._json.PhysicsSettings[physicsSettingIndex].Input[inputIndex].Source.Id;
  5522. }
  5523. getOutputCount(physicsSettingIndex) {
  5524. return this._json.PhysicsSettings[physicsSettingIndex].Output.length;
  5525. }
  5526. getOutputVertexIndex(physicsSettingIndex, outputIndex) {
  5527. return this._json.PhysicsSettings[physicsSettingIndex].Output[outputIndex].VertexIndex;
  5528. }
  5529. getOutputAngleScale(physicsSettingIndex, outputIndex) {
  5530. return this._json.PhysicsSettings[physicsSettingIndex].Output[outputIndex].Scale;
  5531. }
  5532. getOutputWeight(physicsSettingIndex, outputIndex) {
  5533. return this._json.PhysicsSettings[physicsSettingIndex].Output[outputIndex].Weight;
  5534. }
  5535. getOutputDestinationId(physicsSettingIndex, outputIndex) {
  5536. return this._json.PhysicsSettings[physicsSettingIndex].Output[outputIndex].Destination.Id;
  5537. }
  5538. getOutputType(physicsSettingIndex, outputIndex) {
  5539. return this._json.PhysicsSettings[physicsSettingIndex].Output[outputIndex].Type;
  5540. }
  5541. getOutputReflect(physicsSettingIndex, outputIndex) {
  5542. return this._json.PhysicsSettings[physicsSettingIndex].Output[outputIndex].Reflect;
  5543. }
  5544. getParticleCount(physicsSettingIndex) {
  5545. return this._json.PhysicsSettings[physicsSettingIndex].Vertices.length;
  5546. }
  5547. getParticleMobility(physicsSettingIndex, vertexIndex) {
  5548. return this._json.PhysicsSettings[physicsSettingIndex].Vertices[vertexIndex].Mobility;
  5549. }
  5550. getParticleDelay(physicsSettingIndex, vertexIndex) {
  5551. return this._json.PhysicsSettings[physicsSettingIndex].Vertices[vertexIndex].Delay;
  5552. }
  5553. getParticleAcceleration(physicsSettingIndex, vertexIndex) {
  5554. return this._json.PhysicsSettings[physicsSettingIndex].Vertices[vertexIndex].Acceleration;
  5555. }
  5556. getParticleRadius(physicsSettingIndex, vertexIndex) {
  5557. return this._json.PhysicsSettings[physicsSettingIndex].Vertices[vertexIndex].Radius;
  5558. }
  5559. getParticlePosition(physicsSettingIndex, vertexIndex) {
  5560. const ret = new CubismVector2(0, 0);
  5561. ret.x = this._json.PhysicsSettings[physicsSettingIndex].Vertices[vertexIndex].Position.X;
  5562. ret.y = this._json.PhysicsSettings[physicsSettingIndex].Vertices[vertexIndex].Position.Y;
  5563. return ret;
  5564. }
  5565. }
  5566. const PhysicsTypeTagX = "X";
  5567. const PhysicsTypeTagY = "Y";
  5568. const PhysicsTypeTagAngle = "Angle";
  5569. const AirResistance = 5;
  5570. const MaximumWeight = 100;
  5571. const MovementThreshold = 1e-3;
  5572. class CubismPhysics {
  5573. static create(json) {
  5574. const ret = new CubismPhysics();
  5575. ret.parse(json);
  5576. ret._physicsRig.gravity.y = 0;
  5577. return ret;
  5578. }
  5579. evaluate(model, deltaTimeSeconds) {
  5580. let totalAngle;
  5581. let weight;
  5582. let radAngle;
  5583. let outputValue;
  5584. const totalTranslation = new CubismVector2();
  5585. let currentSetting;
  5586. let currentInput;
  5587. let currentOutput;
  5588. let currentParticles;
  5589. let parameterValue;
  5590. let parameterMaximumValue;
  5591. let parameterMinimumValue;
  5592. let parameterDefaultValue;
  5593. parameterValue = model.getModel().parameters.values;
  5594. parameterMaximumValue = model.getModel().parameters.maximumValues;
  5595. parameterMinimumValue = model.getModel().parameters.minimumValues;
  5596. parameterDefaultValue = model.getModel().parameters.defaultValues;
  5597. for (let settingIndex = 0; settingIndex < this._physicsRig.subRigCount; ++settingIndex) {
  5598. totalAngle = { angle: 0 };
  5599. totalTranslation.x = 0;
  5600. totalTranslation.y = 0;
  5601. currentSetting = this._physicsRig.settings[settingIndex];
  5602. currentInput = this._physicsRig.inputs.slice(currentSetting.baseInputIndex);
  5603. currentOutput = this._physicsRig.outputs.slice(currentSetting.baseOutputIndex);
  5604. currentParticles = this._physicsRig.particles.slice(currentSetting.baseParticleIndex);
  5605. for (let i = 0; i < currentSetting.inputCount; ++i) {
  5606. weight = currentInput[i].weight / MaximumWeight;
  5607. if (currentInput[i].sourceParameterIndex == -1) {
  5608. currentInput[i].sourceParameterIndex = model.getParameterIndex(currentInput[i].source.id);
  5609. }
  5610. currentInput[i].getNormalizedParameterValue(totalTranslation, totalAngle, parameterValue[currentInput[i].sourceParameterIndex], parameterMinimumValue[currentInput[i].sourceParameterIndex], parameterMaximumValue[currentInput[i].sourceParameterIndex], parameterDefaultValue[currentInput[i].sourceParameterIndex], currentSetting.normalizationPosition, currentSetting.normalizationAngle, currentInput[i].reflect, weight);
  5611. }
  5612. radAngle = CubismMath.degreesToRadian(-totalAngle.angle);
  5613. totalTranslation.x = totalTranslation.x * CubismMath.cos(radAngle) - totalTranslation.y * CubismMath.sin(radAngle);
  5614. totalTranslation.y = totalTranslation.x * CubismMath.sin(radAngle) + totalTranslation.y * CubismMath.cos(radAngle);
  5615. updateParticles(currentParticles, currentSetting.particleCount, totalTranslation, totalAngle.angle, this._options.wind, MovementThreshold * currentSetting.normalizationPosition.maximum, deltaTimeSeconds, AirResistance);
  5616. for (let i = 0; i < currentSetting.outputCount; ++i) {
  5617. const particleIndex = currentOutput[i].vertexIndex;
  5618. if (particleIndex < 1 || particleIndex >= currentSetting.particleCount) {
  5619. break;
  5620. }
  5621. if (currentOutput[i].destinationParameterIndex == -1) {
  5622. currentOutput[i].destinationParameterIndex = model.getParameterIndex(currentOutput[i].destination.id);
  5623. }
  5624. const translation = new CubismVector2();
  5625. translation.x = currentParticles[particleIndex].position.x - currentParticles[particleIndex - 1].position.x;
  5626. translation.y = currentParticles[particleIndex].position.y - currentParticles[particleIndex - 1].position.y;
  5627. outputValue = currentOutput[i].getValue(translation, currentParticles, particleIndex, currentOutput[i].reflect, this._options.gravity);
  5628. const destinationParameterIndex = currentOutput[i].destinationParameterIndex;
  5629. const outParameterValue = !Float32Array.prototype.slice && "subarray" in Float32Array.prototype ? JSON.parse(JSON.stringify(parameterValue.subarray(destinationParameterIndex))) : parameterValue.slice(destinationParameterIndex);
  5630. updateOutputParameterValue(outParameterValue, parameterMinimumValue[destinationParameterIndex], parameterMaximumValue[destinationParameterIndex], outputValue, currentOutput[i]);
  5631. for (let offset = destinationParameterIndex, outParamIndex = 0; offset < parameterValue.length; offset++, outParamIndex++) {
  5632. parameterValue[offset] = outParameterValue[outParamIndex];
  5633. }
  5634. }
  5635. }
  5636. }
  5637. setOptions(options) {
  5638. this._options = options;
  5639. }
  5640. getOption() {
  5641. return this._options;
  5642. }
  5643. constructor() {
  5644. this._options = new Options();
  5645. this._options.gravity.y = -1;
  5646. this._options.gravity.x = 0;
  5647. this._options.wind.x = 0;
  5648. this._options.wind.y = 0;
  5649. }
  5650. release() {
  5651. this._physicsRig = void 0;
  5652. }
  5653. parse(physicsJson) {
  5654. this._physicsRig = new CubismPhysicsRig();
  5655. let json = new CubismPhysicsJson(physicsJson);
  5656. this._physicsRig.gravity = json.getGravity();
  5657. this._physicsRig.wind = json.getWind();
  5658. this._physicsRig.subRigCount = json.getSubRigCount();
  5659. let inputIndex = 0, outputIndex = 0, particleIndex = 0;
  5660. for (let i = 0; i < this._physicsRig.subRigCount; ++i) {
  5661. const setting = new CubismPhysicsSubRig();
  5662. setting.normalizationPosition.minimum = json.getNormalizationPositionMinimumValue(i);
  5663. setting.normalizationPosition.maximum = json.getNormalizationPositionMaximumValue(i);
  5664. setting.normalizationPosition.defalut = json.getNormalizationPositionDefaultValue(i);
  5665. setting.normalizationAngle.minimum = json.getNormalizationAngleMinimumValue(i);
  5666. setting.normalizationAngle.maximum = json.getNormalizationAngleMaximumValue(i);
  5667. setting.normalizationAngle.defalut = json.getNormalizationAngleDefaultValue(i);
  5668. setting.inputCount = json.getInputCount(i);
  5669. setting.baseInputIndex = inputIndex;
  5670. inputIndex += setting.inputCount;
  5671. for (let j = 0; j < setting.inputCount; ++j) {
  5672. const input = new CubismPhysicsInput();
  5673. input.sourceParameterIndex = -1;
  5674. input.weight = json.getInputWeight(i, j);
  5675. input.reflect = json.getInputReflect(i, j);
  5676. switch (json.getInputType(i, j)) {
  5677. case PhysicsTypeTagX:
  5678. input.type = CubismPhysicsSource.CubismPhysicsSource_X;
  5679. input.getNormalizedParameterValue = getInputTranslationXFromNormalizedParameterValue;
  5680. break;
  5681. case PhysicsTypeTagY:
  5682. input.type = CubismPhysicsSource.CubismPhysicsSource_Y;
  5683. input.getNormalizedParameterValue = getInputTranslationYFromNormalizedParamterValue;
  5684. break;
  5685. case PhysicsTypeTagAngle:
  5686. input.type = CubismPhysicsSource.CubismPhysicsSource_Angle;
  5687. input.getNormalizedParameterValue = getInputAngleFromNormalizedParameterValue;
  5688. break;
  5689. }
  5690. input.source.targetType = CubismPhysicsTargetType.CubismPhysicsTargetType_Parameter;
  5691. input.source.id = json.getInputSourceId(i, j);
  5692. this._physicsRig.inputs.push(input);
  5693. }
  5694. setting.outputCount = json.getOutputCount(i);
  5695. setting.baseOutputIndex = outputIndex;
  5696. outputIndex += setting.outputCount;
  5697. for (let j = 0; j < setting.outputCount; ++j) {
  5698. const output = new CubismPhysicsOutput();
  5699. output.destinationParameterIndex = -1;
  5700. output.vertexIndex = json.getOutputVertexIndex(i, j);
  5701. output.angleScale = json.getOutputAngleScale(i, j);
  5702. output.weight = json.getOutputWeight(i, j);
  5703. output.destination.targetType = CubismPhysicsTargetType.CubismPhysicsTargetType_Parameter;
  5704. output.destination.id = json.getOutputDestinationId(i, j);
  5705. switch (json.getOutputType(i, j)) {
  5706. case PhysicsTypeTagX:
  5707. output.type = CubismPhysicsSource.CubismPhysicsSource_X;
  5708. output.getValue = getOutputTranslationX;
  5709. output.getScale = getOutputScaleTranslationX;
  5710. break;
  5711. case PhysicsTypeTagY:
  5712. output.type = CubismPhysicsSource.CubismPhysicsSource_Y;
  5713. output.getValue = getOutputTranslationY;
  5714. output.getScale = getOutputScaleTranslationY;
  5715. break;
  5716. case PhysicsTypeTagAngle:
  5717. output.type = CubismPhysicsSource.CubismPhysicsSource_Angle;
  5718. output.getValue = getOutputAngle;
  5719. output.getScale = getOutputScaleAngle;
  5720. break;
  5721. }
  5722. output.reflect = json.getOutputReflect(i, j);
  5723. this._physicsRig.outputs.push(output);
  5724. }
  5725. setting.particleCount = json.getParticleCount(i);
  5726. setting.baseParticleIndex = particleIndex;
  5727. particleIndex += setting.particleCount;
  5728. for (let j = 0; j < setting.particleCount; ++j) {
  5729. const particle = new CubismPhysicsParticle();
  5730. particle.mobility = json.getParticleMobility(i, j);
  5731. particle.delay = json.getParticleDelay(i, j);
  5732. particle.acceleration = json.getParticleAcceleration(i, j);
  5733. particle.radius = json.getParticleRadius(i, j);
  5734. particle.position = json.getParticlePosition(i, j);
  5735. this._physicsRig.particles.push(particle);
  5736. }
  5737. this._physicsRig.settings.push(setting);
  5738. }
  5739. this.initialize();
  5740. json.release();
  5741. }
  5742. initialize() {
  5743. let strand;
  5744. let currentSetting;
  5745. let radius;
  5746. for (let settingIndex = 0; settingIndex < this._physicsRig.subRigCount; ++settingIndex) {
  5747. currentSetting = this._physicsRig.settings[settingIndex];
  5748. strand = this._physicsRig.particles.slice(currentSetting.baseParticleIndex);
  5749. strand[0].initialPosition = new CubismVector2(0, 0);
  5750. strand[0].lastPosition = new CubismVector2(strand[0].initialPosition.x, strand[0].initialPosition.y);
  5751. strand[0].lastGravity = new CubismVector2(0, -1);
  5752. strand[0].lastGravity.y *= -1;
  5753. strand[0].velocity = new CubismVector2(0, 0);
  5754. strand[0].force = new CubismVector2(0, 0);
  5755. for (let i = 1; i < currentSetting.particleCount; ++i) {
  5756. radius = new CubismVector2(0, 0);
  5757. radius.y = strand[i].radius;
  5758. strand[i].initialPosition = new CubismVector2(strand[i - 1].initialPosition.x + radius.x, strand[i - 1].initialPosition.y + radius.y);
  5759. strand[i].position = new CubismVector2(strand[i].initialPosition.x, strand[i].initialPosition.y);
  5760. strand[i].lastPosition = new CubismVector2(strand[i].initialPosition.x, strand[i].initialPosition.y);
  5761. strand[i].lastGravity = new CubismVector2(0, -1);
  5762. strand[i].lastGravity.y *= -1;
  5763. strand[i].velocity = new CubismVector2(0, 0);
  5764. strand[i].force = new CubismVector2(0, 0);
  5765. }
  5766. }
  5767. }
  5768. }
  5769. class Options {
  5770. constructor() {
  5771. this.gravity = new CubismVector2(0, 0);
  5772. this.wind = new CubismVector2(0, 0);
  5773. }
  5774. }
  5775. function getInputTranslationXFromNormalizedParameterValue(targetTranslation, targetAngle, value, parameterMinimumValue, parameterMaximumValue, parameterDefaultValue, normalizationPosition, normalizationAngle, isInverted, weight) {
  5776. targetTranslation.x += normalizeParameterValue(value, parameterMinimumValue, parameterMaximumValue, parameterDefaultValue, normalizationPosition.minimum, normalizationPosition.maximum, normalizationPosition.defalut, isInverted) * weight;
  5777. }
  5778. function getInputTranslationYFromNormalizedParamterValue(targetTranslation, targetAngle, value, parameterMinimumValue, parameterMaximumValue, parameterDefaultValue, normalizationPosition, normalizationAngle, isInverted, weight) {
  5779. targetTranslation.y += normalizeParameterValue(value, parameterMinimumValue, parameterMaximumValue, parameterDefaultValue, normalizationPosition.minimum, normalizationPosition.maximum, normalizationPosition.defalut, isInverted) * weight;
  5780. }
  5781. function getInputAngleFromNormalizedParameterValue(targetTranslation, targetAngle, value, parameterMinimumValue, parameterMaximumValue, parameterDefaultValue, normalizaitionPosition, normalizationAngle, isInverted, weight) {
  5782. targetAngle.angle += normalizeParameterValue(value, parameterMinimumValue, parameterMaximumValue, parameterDefaultValue, normalizationAngle.minimum, normalizationAngle.maximum, normalizationAngle.defalut, isInverted) * weight;
  5783. }
  5784. function getOutputTranslationX(translation, particles, particleIndex, isInverted, parentGravity) {
  5785. let outputValue = translation.x;
  5786. if (isInverted) {
  5787. outputValue *= -1;
  5788. }
  5789. return outputValue;
  5790. }
  5791. function getOutputTranslationY(translation, particles, particleIndex, isInverted, parentGravity) {
  5792. let outputValue = translation.y;
  5793. if (isInverted) {
  5794. outputValue *= -1;
  5795. }
  5796. return outputValue;
  5797. }
  5798. function getOutputAngle(translation, particles, particleIndex, isInverted, parentGravity) {
  5799. let outputValue;
  5800. if (particleIndex >= 2) {
  5801. parentGravity = particles[particleIndex - 1].position.substract(particles[particleIndex - 2].position);
  5802. } else {
  5803. parentGravity = parentGravity.multiplyByScaler(-1);
  5804. }
  5805. outputValue = CubismMath.directionToRadian(parentGravity, translation);
  5806. if (isInverted) {
  5807. outputValue *= -1;
  5808. }
  5809. return outputValue;
  5810. }
  5811. function getRangeValue(min, max) {
  5812. return Math.abs(Math.max(min, max) - Math.min(min, max));
  5813. }
  5814. function getDefaultValue(min, max) {
  5815. const minValue = Math.min(min, max);
  5816. return minValue + getRangeValue(min, max) / 2;
  5817. }
  5818. function getOutputScaleTranslationX(translationScale, angleScale) {
  5819. return translationScale.x;
  5820. }
  5821. function getOutputScaleTranslationY(translationScale, angleScale) {
  5822. return translationScale.y;
  5823. }
  5824. function getOutputScaleAngle(translationScale, angleScale) {
  5825. return angleScale;
  5826. }
  5827. function updateParticles(strand, strandCount, totalTranslation, totalAngle, windDirection, thresholdValue, deltaTimeSeconds, airResistance) {
  5828. let totalRadian;
  5829. let delay;
  5830. let radian;
  5831. let currentGravity;
  5832. let direction = new CubismVector2(0, 0);
  5833. let velocity = new CubismVector2(0, 0);
  5834. let force = new CubismVector2(0, 0);
  5835. let newDirection = new CubismVector2(0, 0);
  5836. strand[0].position = new CubismVector2(totalTranslation.x, totalTranslation.y);
  5837. totalRadian = CubismMath.degreesToRadian(totalAngle);
  5838. currentGravity = CubismMath.radianToDirection(totalRadian);
  5839. currentGravity.normalize();
  5840. for (let i = 1; i < strandCount; ++i) {
  5841. strand[i].force = currentGravity.multiplyByScaler(strand[i].acceleration).add(windDirection);
  5842. strand[i].lastPosition = new CubismVector2(strand[i].position.x, strand[i].position.y);
  5843. delay = strand[i].delay * deltaTimeSeconds * 30;
  5844. direction = strand[i].position.substract(strand[i - 1].position);
  5845. radian = CubismMath.directionToRadian(strand[i].lastGravity, currentGravity) / airResistance;
  5846. direction.x = CubismMath.cos(radian) * direction.x - direction.y * CubismMath.sin(radian);
  5847. direction.y = CubismMath.sin(radian) * direction.x + direction.y * CubismMath.cos(radian);
  5848. strand[i].position = strand[i - 1].position.add(direction);
  5849. velocity = strand[i].velocity.multiplyByScaler(delay);
  5850. force = strand[i].force.multiplyByScaler(delay).multiplyByScaler(delay);
  5851. strand[i].position = strand[i].position.add(velocity).add(force);
  5852. newDirection = strand[i].position.substract(strand[i - 1].position);
  5853. newDirection.normalize();
  5854. strand[i].position = strand[i - 1].position.add(newDirection.multiplyByScaler(strand[i].radius));
  5855. if (CubismMath.abs(strand[i].position.x) < thresholdValue) {
  5856. strand[i].position.x = 0;
  5857. }
  5858. if (delay != 0) {
  5859. strand[i].velocity = strand[i].position.substract(strand[i].lastPosition);
  5860. strand[i].velocity = strand[i].velocity.divisionByScalar(delay);
  5861. strand[i].velocity = strand[i].velocity.multiplyByScaler(strand[i].mobility);
  5862. }
  5863. strand[i].force = new CubismVector2(0, 0);
  5864. strand[i].lastGravity = new CubismVector2(currentGravity.x, currentGravity.y);
  5865. }
  5866. }
  5867. function updateOutputParameterValue(parameterValue, parameterValueMinimum, parameterValueMaximum, translation, output) {
  5868. let outputScale;
  5869. let value;
  5870. let weight;
  5871. outputScale = output.getScale(output.translationScale, output.angleScale);
  5872. value = translation * outputScale;
  5873. if (value < parameterValueMinimum) {
  5874. if (value < output.valueBelowMinimum) {
  5875. output.valueBelowMinimum = value;
  5876. }
  5877. value = parameterValueMinimum;
  5878. } else if (value > parameterValueMaximum) {
  5879. if (value > output.valueExceededMaximum) {
  5880. output.valueExceededMaximum = value;
  5881. }
  5882. value = parameterValueMaximum;
  5883. }
  5884. weight = output.weight / MaximumWeight;
  5885. if (weight >= 1) {
  5886. parameterValue[0] = value;
  5887. } else {
  5888. value = parameterValue[0] * (1 - weight) + value * weight;
  5889. parameterValue[0] = value;
  5890. }
  5891. }
  5892. function normalizeParameterValue(value, parameterMinimum, parameterMaximum, parameterDefault, normalizedMinimum, normalizedMaximum, normalizedDefault, isInverted) {
  5893. let result = 0;
  5894. const maxValue = CubismMath.max(parameterMaximum, parameterMinimum);
  5895. if (maxValue < value) {
  5896. value = maxValue;
  5897. }
  5898. const minValue = CubismMath.min(parameterMaximum, parameterMinimum);
  5899. if (minValue > value) {
  5900. value = minValue;
  5901. }
  5902. const minNormValue = CubismMath.min(normalizedMinimum, normalizedMaximum);
  5903. const maxNormValue = CubismMath.max(normalizedMinimum, normalizedMaximum);
  5904. const middleNormValue = normalizedDefault;
  5905. const middleValue = getDefaultValue(minValue, maxValue);
  5906. const paramValue = value - middleValue;
  5907. switch (Math.sign(paramValue)) {
  5908. case 1: {
  5909. const nLength = maxNormValue - middleNormValue;
  5910. const pLength = maxValue - middleValue;
  5911. if (pLength != 0) {
  5912. result = paramValue * (nLength / pLength);
  5913. result += middleNormValue;
  5914. }
  5915. break;
  5916. }
  5917. case -1: {
  5918. const nLength = minNormValue - middleNormValue;
  5919. const pLength = minValue - middleValue;
  5920. if (pLength != 0) {
  5921. result = paramValue * (nLength / pLength);
  5922. result += middleNormValue;
  5923. }
  5924. break;
  5925. }
  5926. case 0: {
  5927. result = middleNormValue;
  5928. break;
  5929. }
  5930. }
  5931. return isInverted ? result : result * -1;
  5932. }
  5933. Live2DFactory.registerRuntime({
  5934. version: 4,
  5935. ready: cubism4Ready,
  5936. test(source) {
  5937. return source instanceof Cubism4ModelSettings || Cubism4ModelSettings.isValidJSON(source);
  5938. },
  5939. isValidMoc(modelData) {
  5940. if (modelData.byteLength < 4) {
  5941. return false;
  5942. }
  5943. const view = new Int8Array(modelData, 0, 4);
  5944. return String.fromCharCode(...view) === "MOC3";
  5945. },
  5946. createModelSettings(json) {
  5947. return new Cubism4ModelSettings(json);
  5948. },
  5949. createCoreModel(data) {
  5950. const moc = CubismMoc.create(data);
  5951. try {
  5952. const model = moc.createModel();
  5953. model.__moc = moc;
  5954. return model;
  5955. } catch (e) {
  5956. try {
  5957. moc.release();
  5958. } catch (ignored) {
  5959. }
  5960. throw e;
  5961. }
  5962. },
  5963. createInternalModel(coreModel, settings, options) {
  5964. const model = new Cubism4InternalModel(coreModel, settings, options);
  5965. const coreModelWithMoc = coreModel;
  5966. if (coreModelWithMoc.__moc) {
  5967. model.__moc = coreModelWithMoc.__moc;
  5968. delete coreModelWithMoc.__moc;
  5969. model.once("destroy", releaseMoc);
  5970. }
  5971. return model;
  5972. },
  5973. createPhysics(coreModel, data) {
  5974. return CubismPhysics.create(data);
  5975. },
  5976. createPose(coreModel, data) {
  5977. return CubismPose.create(data);
  5978. }
  5979. });
  5980. function releaseMoc() {
  5981. var _a;
  5982. (_a = this.__moc) == null ? void 0 : _a.release();
  5983. }
  5984. export { Cubism2ExpressionManager, Cubism2InternalModel, Cubism2ModelSettings, Cubism2MotionManager, Cubism4ExpressionManager, Cubism4InternalModel, Cubism4ModelSettings, Cubism4MotionManager, ExpressionManager, FileLoader, FocusController, InteractionMixin, InternalModel, LOGICAL_HEIGHT, LOGICAL_WIDTH, Live2DExpression, Live2DEyeBlink, Live2DFactory, Live2DLoader, Live2DModel, Live2DPhysics, Live2DPose, Live2DTransform, ModelSettings, MotionManager, MotionPreloadStrategy, MotionPriority, MotionState, SoundManager, VERSION, XHRLoader, ZipLoader, applyMixins, clamp, config, copyArray, copyProperty, cubism4Ready, folderName, logger, rand, remove, startUpCubism4 };