laya.d3.js 1.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840
  1. (function (exports, Laya) {
  2. 'use strict';
  3. class MathUtils3D {
  4. constructor() {
  5. }
  6. static isZero(v) {
  7. return Math.abs(v) < MathUtils3D.zeroTolerance;
  8. }
  9. static nearEqual(n1, n2) {
  10. if (MathUtils3D.isZero(n1 - n2))
  11. return true;
  12. return false;
  13. }
  14. static fastInvSqrt(value) {
  15. if (MathUtils3D.isZero(value))
  16. return value;
  17. return 1.0 / Math.sqrt(value);
  18. }
  19. }
  20. MathUtils3D.zeroTolerance = 1e-6;
  21. MathUtils3D.MaxValue = 3.40282347e+38;
  22. MathUtils3D.MinValue = -3.40282347e+38;
  23. MathUtils3D.Deg2Rad = Math.PI / 180;
  24. class Vector2 {
  25. constructor(x = 0, y = 0) {
  26. this.x = x;
  27. this.y = y;
  28. }
  29. setValue(x, y) {
  30. this.x = x;
  31. this.y = y;
  32. }
  33. static scale(a, b, out) {
  34. out.x = a.x * b;
  35. out.y = a.y * b;
  36. }
  37. fromArray(array, offset = 0) {
  38. this.x = array[offset + 0];
  39. this.y = array[offset + 1];
  40. }
  41. cloneTo(destObject) {
  42. var destVector2 = destObject;
  43. destVector2.x = this.x;
  44. destVector2.y = this.y;
  45. }
  46. static dot(a, b) {
  47. return (a.x * b.x) + (a.y * b.y);
  48. }
  49. static normalize(s, out) {
  50. var x = s.x, y = s.y;
  51. var len = x * x + y * y;
  52. if (len > 0) {
  53. len = 1 / Math.sqrt(len);
  54. out.x = x * len;
  55. out.y = y * len;
  56. }
  57. }
  58. static scalarLength(a) {
  59. var x = a.x, y = a.y;
  60. return Math.sqrt(x * x + y * y);
  61. }
  62. clone() {
  63. var destVector2 = new Vector2();
  64. this.cloneTo(destVector2);
  65. return destVector2;
  66. }
  67. forNativeElement(nativeElements = null) {
  68. if (nativeElements) {
  69. this.elements = nativeElements;
  70. this.elements[0] = this.x;
  71. this.elements[1] = this.y;
  72. }
  73. else {
  74. this.elements = new Float32Array([this.x, this.y]);
  75. }
  76. Vector2.rewriteNumProperty(this, "x", 0);
  77. Vector2.rewriteNumProperty(this, "y", 1);
  78. }
  79. static rewriteNumProperty(proto, name, index) {
  80. Object["defineProperty"](proto, name, {
  81. "get": function () {
  82. return this.elements[index];
  83. },
  84. "set": function (v) {
  85. this.elements[index] = v;
  86. }
  87. });
  88. }
  89. }
  90. Vector2.ZERO = new Vector2(0.0, 0.0);
  91. Vector2.ONE = new Vector2(1.0, 1.0);
  92. class Vector4 {
  93. constructor(x = 0, y = 0, z = 0, w = 0) {
  94. this.x = x;
  95. this.y = y;
  96. this.z = z;
  97. this.w = w;
  98. }
  99. setValue(x, y, z, w) {
  100. this.x = x;
  101. this.y = y;
  102. this.z = z;
  103. this.w = w;
  104. }
  105. fromArray(array, offset = 0) {
  106. this.x = array[offset + 0];
  107. this.y = array[offset + 1];
  108. this.z = array[offset + 2];
  109. this.w = array[offset + 3];
  110. }
  111. cloneTo(destObject) {
  112. var destVector4 = destObject;
  113. destVector4.x = this.x;
  114. destVector4.y = this.y;
  115. destVector4.z = this.z;
  116. destVector4.w = this.w;
  117. }
  118. clone() {
  119. var destVector4 = new Vector4();
  120. this.cloneTo(destVector4);
  121. return destVector4;
  122. }
  123. static lerp(a, b, t, out) {
  124. var ax = a.x, ay = a.y, az = a.z, aw = a.w;
  125. out.x = ax + t * (b.x - ax);
  126. out.y = ay + t * (b.y - ay);
  127. out.z = az + t * (b.z - az);
  128. out.w = aw + t * (b.w - aw);
  129. }
  130. static transformByM4x4(vector4, m4x4, out) {
  131. var vx = vector4.x;
  132. var vy = vector4.y;
  133. var vz = vector4.z;
  134. var vw = vector4.w;
  135. var me = m4x4.elements;
  136. out.x = vx * me[0] + vy * me[4] + vz * me[8] + vw * me[12];
  137. out.y = vx * me[1] + vy * me[5] + vz * me[9] + vw * me[13];
  138. out.z = vx * me[2] + vy * me[6] + vz * me[10] + vw * me[14];
  139. out.w = vx * me[3] + vy * me[7] + vz * me[11] + vw * me[15];
  140. }
  141. static equals(a, b) {
  142. return MathUtils3D.nearEqual(Math.abs(a.x), Math.abs(b.x)) && MathUtils3D.nearEqual(Math.abs(a.y), Math.abs(b.y)) && MathUtils3D.nearEqual(Math.abs(a.z), Math.abs(b.z)) && MathUtils3D.nearEqual(Math.abs(a.w), Math.abs(b.w));
  143. }
  144. length() {
  145. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  146. }
  147. lengthSquared() {
  148. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  149. }
  150. static normalize(s, out) {
  151. var len = s.length();
  152. if (len > 0) {
  153. var inverse = 1.0 / len;
  154. out.x = s.x * inverse;
  155. out.y = s.y * inverse;
  156. out.z = s.z * inverse;
  157. out.w = s.w * inverse;
  158. }
  159. }
  160. static add(a, b, out) {
  161. out.x = a.x + b.x;
  162. out.y = a.y + b.y;
  163. out.z = a.z + b.z;
  164. out.w = a.w + b.w;
  165. }
  166. static subtract(a, b, out) {
  167. out.x = a.x - b.x;
  168. out.y = a.y - b.y;
  169. out.z = a.z - b.z;
  170. out.w = a.w - b.w;
  171. }
  172. static multiply(a, b, out) {
  173. out.x = a.x * b.x;
  174. out.y = a.y * b.y;
  175. out.z = a.z * b.z;
  176. out.w = a.w * b.w;
  177. }
  178. static scale(a, b, out) {
  179. out.x = a.x * b;
  180. out.y = a.y * b;
  181. out.z = a.z * b;
  182. out.w = a.w * b;
  183. }
  184. static Clamp(value, min, max, out) {
  185. var x = value.x;
  186. var y = value.y;
  187. var z = value.z;
  188. var w = value.w;
  189. var mineX = min.x;
  190. var mineY = min.y;
  191. var mineZ = min.z;
  192. var mineW = min.w;
  193. var maxeX = max.x;
  194. var maxeY = max.y;
  195. var maxeZ = max.z;
  196. var maxeW = max.w;
  197. x = (x > maxeX) ? maxeX : x;
  198. x = (x < mineX) ? mineX : x;
  199. y = (y > maxeY) ? maxeY : y;
  200. y = (y < mineY) ? mineY : y;
  201. z = (z > maxeZ) ? maxeZ : z;
  202. z = (z < mineZ) ? mineZ : z;
  203. w = (w > maxeW) ? maxeW : w;
  204. w = (w < mineW) ? mineW : w;
  205. out.x = x;
  206. out.y = y;
  207. out.z = z;
  208. out.w = w;
  209. }
  210. static distanceSquared(value1, value2) {
  211. var x = value1.x - value2.x;
  212. var y = value1.y - value2.y;
  213. var z = value1.z - value2.z;
  214. var w = value1.w - value2.w;
  215. return (x * x) + (y * y) + (z * z) + (w * w);
  216. }
  217. static distance(value1, value2) {
  218. var x = value1.x - value2.x;
  219. var y = value1.y - value2.y;
  220. var z = value1.z - value2.z;
  221. var w = value1.w - value2.w;
  222. return Math.sqrt((x * x) + (y * y) + (z * z) + (w * w));
  223. }
  224. static dot(a, b) {
  225. return (a.x * b.x) + (a.y * b.y) + (a.z * b.z) + (a.w * b.w);
  226. }
  227. static min(a, b, out) {
  228. out.x = Math.min(a.x, b.x);
  229. out.y = Math.min(a.y, b.y);
  230. out.z = Math.min(a.z, b.z);
  231. out.w = Math.min(a.w, b.w);
  232. }
  233. static max(a, b, out) {
  234. out.x = Math.max(a.x, b.x);
  235. out.y = Math.max(a.y, b.y);
  236. out.z = Math.max(a.z, b.z);
  237. out.w = Math.max(a.w, b.w);
  238. }
  239. forNativeElement(nativeElements = null) {
  240. if (nativeElements) {
  241. this.elements = nativeElements;
  242. this.elements[0] = this.x;
  243. this.elements[1] = this.y;
  244. this.elements[2] = this.z;
  245. this.elements[3] = this.w;
  246. }
  247. else {
  248. this.elements = new Float32Array([this.x, this.y, this.z, this.w]);
  249. }
  250. Vector2.rewriteNumProperty(this, "x", 0);
  251. Vector2.rewriteNumProperty(this, "y", 1);
  252. Vector2.rewriteNumProperty(this, "z", 2);
  253. Vector2.rewriteNumProperty(this, "w", 3);
  254. }
  255. }
  256. Vector4.ZERO = new Vector4();
  257. Vector4.ONE = new Vector4(1.0, 1.0, 1.0, 1.0);
  258. Vector4.UnitX = new Vector4(1.0, 0.0, 0.0, 0.0);
  259. Vector4.UnitY = new Vector4(0.0, 1.0, 0.0, 0.0);
  260. Vector4.UnitZ = new Vector4(0.0, 0.0, 1.0, 0.0);
  261. Vector4.UnitW = new Vector4(0.0, 0.0, 0.0, 1.0);
  262. class Vector3 {
  263. constructor(x = 0, y = 0, z = 0, nativeElements = null) {
  264. this.x = x;
  265. this.y = y;
  266. this.z = z;
  267. }
  268. static distanceSquared(value1, value2) {
  269. var x = value1.x - value2.x;
  270. var y = value1.y - value2.y;
  271. var z = value1.z - value2.z;
  272. return (x * x) + (y * y) + (z * z);
  273. }
  274. static distance(value1, value2) {
  275. var x = value1.x - value2.x;
  276. var y = value1.y - value2.y;
  277. var z = value1.z - value2.z;
  278. return Math.sqrt((x * x) + (y * y) + (z * z));
  279. }
  280. static min(a, b, out) {
  281. out.x = Math.min(a.x, b.x);
  282. out.y = Math.min(a.y, b.y);
  283. out.z = Math.min(a.z, b.z);
  284. }
  285. static max(a, b, out) {
  286. out.x = Math.max(a.x, b.x);
  287. out.y = Math.max(a.y, b.y);
  288. out.z = Math.max(a.z, b.z);
  289. }
  290. static transformQuat(source, rotation, out) {
  291. var x = source.x, y = source.y, z = source.z, qx = rotation.x, qy = rotation.y, qz = rotation.z, qw = rotation.w, ix = qw * x + qy * z - qz * y, iy = qw * y + qz * x - qx * z, iz = qw * z + qx * y - qy * x, iw = -qx * x - qy * y - qz * z;
  292. out.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  293. out.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  294. out.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  295. }
  296. static scalarLength(a) {
  297. var x = a.x, y = a.y, z = a.z;
  298. return Math.sqrt(x * x + y * y + z * z);
  299. }
  300. static scalarLengthSquared(a) {
  301. var x = a.x, y = a.y, z = a.z;
  302. return x * x + y * y + z * z;
  303. }
  304. static normalize(s, out) {
  305. var x = s.x, y = s.y, z = s.z;
  306. var len = x * x + y * y + z * z;
  307. if (len > 0) {
  308. len = 1 / Math.sqrt(len);
  309. out.x = x * len;
  310. out.y = y * len;
  311. out.z = z * len;
  312. }
  313. }
  314. static multiply(a, b, out) {
  315. out.x = a.x * b.x;
  316. out.y = a.y * b.y;
  317. out.z = a.z * b.z;
  318. }
  319. static scale(a, b, out) {
  320. out.x = a.x * b;
  321. out.y = a.y * b;
  322. out.z = a.z * b;
  323. }
  324. static lerp(a, b, t, out) {
  325. var ax = a.x, ay = a.y, az = a.z;
  326. out.x = ax + t * (b.x - ax);
  327. out.y = ay + t * (b.y - ay);
  328. out.z = az + t * (b.z - az);
  329. }
  330. static transformV3ToV3(vector, transform, result) {
  331. var intermediate = Vector3._tempVector4;
  332. Vector3.transformV3ToV4(vector, transform, intermediate);
  333. result.x = intermediate.x;
  334. result.y = intermediate.y;
  335. result.z = intermediate.z;
  336. }
  337. static transformV3ToV4(vector, transform, result) {
  338. var vectorX = vector.x;
  339. var vectorY = vector.y;
  340. var vectorZ = vector.z;
  341. var transformElem = transform.elements;
  342. result.x = (vectorX * transformElem[0]) + (vectorY * transformElem[4]) + (vectorZ * transformElem[8]) + transformElem[12];
  343. result.y = (vectorX * transformElem[1]) + (vectorY * transformElem[5]) + (vectorZ * transformElem[9]) + transformElem[13];
  344. result.z = (vectorX * transformElem[2]) + (vectorY * transformElem[6]) + (vectorZ * transformElem[10]) + transformElem[14];
  345. result.w = (vectorX * transformElem[3]) + (vectorY * transformElem[7]) + (vectorZ * transformElem[11]) + transformElem[15];
  346. }
  347. static TransformNormal(normal, transform, result) {
  348. var normalX = normal.x;
  349. var normalY = normal.y;
  350. var normalZ = normal.z;
  351. var transformElem = transform.elements;
  352. result.x = (normalX * transformElem[0]) + (normalY * transformElem[4]) + (normalZ * transformElem[8]);
  353. result.y = (normalX * transformElem[1]) + (normalY * transformElem[5]) + (normalZ * transformElem[9]);
  354. result.z = (normalX * transformElem[2]) + (normalY * transformElem[6]) + (normalZ * transformElem[10]);
  355. }
  356. static transformCoordinate(coordinate, transform, result) {
  357. var coordinateX = coordinate.x;
  358. var coordinateY = coordinate.y;
  359. var coordinateZ = coordinate.z;
  360. var transformElem = transform.elements;
  361. var w = coordinateX * transformElem[3] + coordinateY * transformElem[7] + coordinateZ * transformElem[11] + transformElem[15];
  362. result.x = (coordinateX * transformElem[0] + coordinateY * transformElem[4] + coordinateZ * transformElem[8] + transformElem[12]) / w;
  363. result.y = (coordinateX * transformElem[1] + coordinateY * transformElem[5] + coordinateZ * transformElem[9] + transformElem[13]) / w;
  364. result.z = (coordinateX * transformElem[2] + coordinateY * transformElem[6] + coordinateZ * transformElem[10] + transformElem[14]) / w;
  365. }
  366. static Clamp(value, min, max, out) {
  367. var x = value.x;
  368. var y = value.y;
  369. var z = value.z;
  370. var mineX = min.x;
  371. var mineY = min.y;
  372. var mineZ = min.z;
  373. var maxeX = max.x;
  374. var maxeY = max.y;
  375. var maxeZ = max.z;
  376. x = (x > maxeX) ? maxeX : x;
  377. x = (x < mineX) ? mineX : x;
  378. y = (y > maxeY) ? maxeY : y;
  379. y = (y < mineY) ? mineY : y;
  380. z = (z > maxeZ) ? maxeZ : z;
  381. z = (z < mineZ) ? mineZ : z;
  382. out.x = x;
  383. out.y = y;
  384. out.z = z;
  385. }
  386. static add(a, b, out) {
  387. out.x = a.x + b.x;
  388. out.y = a.y + b.y;
  389. out.z = a.z + b.z;
  390. }
  391. static subtract(a, b, o) {
  392. o.x = a.x - b.x;
  393. o.y = a.y - b.y;
  394. o.z = a.z - b.z;
  395. }
  396. static cross(a, b, o) {
  397. var ax = a.x, ay = a.y, az = a.z, bx = b.x, by = b.y, bz = b.z;
  398. o.x = ay * bz - az * by;
  399. o.y = az * bx - ax * bz;
  400. o.z = ax * by - ay * bx;
  401. }
  402. static dot(a, b) {
  403. return (a.x * b.x) + (a.y * b.y) + (a.z * b.z);
  404. }
  405. static equals(a, b) {
  406. return MathUtils3D.nearEqual(a.x, b.x) && MathUtils3D.nearEqual(a.y, b.y) && MathUtils3D.nearEqual(a.z, b.z);
  407. }
  408. setValue(x, y, z) {
  409. this.x = x;
  410. this.y = y;
  411. this.z = z;
  412. }
  413. fromArray(array, offset = 0) {
  414. this.x = array[offset + 0];
  415. this.y = array[offset + 1];
  416. this.z = array[offset + 2];
  417. }
  418. cloneTo(destObject) {
  419. var destVector3 = destObject;
  420. destVector3.x = this.x;
  421. destVector3.y = this.y;
  422. destVector3.z = this.z;
  423. }
  424. clone() {
  425. var destVector3 = new Vector3();
  426. this.cloneTo(destVector3);
  427. return destVector3;
  428. }
  429. toDefault() {
  430. this.x = 0;
  431. this.y = 0;
  432. this.z = 0;
  433. }
  434. forNativeElement(nativeElements = null) {
  435. if (nativeElements) {
  436. this.elements = nativeElements;
  437. this.elements[0] = this.x;
  438. this.elements[1] = this.y;
  439. this.elements[2] = this.z;
  440. }
  441. else {
  442. this.elements = new Float32Array([this.x, this.y, this.z]);
  443. }
  444. Vector2.rewriteNumProperty(this, "x", 0);
  445. Vector2.rewriteNumProperty(this, "y", 1);
  446. Vector2.rewriteNumProperty(this, "z", 2);
  447. }
  448. }
  449. Vector3._tempVector4 = new Vector4();
  450. Vector3._ZERO = new Vector3(0.0, 0.0, 0.0);
  451. Vector3._ONE = new Vector3(1.0, 1.0, 1.0);
  452. Vector3._NegativeUnitX = new Vector3(-1, 0, 0);
  453. Vector3._UnitX = new Vector3(1, 0, 0);
  454. Vector3._UnitY = new Vector3(0, 1, 0);
  455. Vector3._UnitZ = new Vector3(0, 0, 1);
  456. Vector3._ForwardRH = new Vector3(0, 0, -1);
  457. Vector3._ForwardLH = new Vector3(0, 0, 1);
  458. Vector3._Up = new Vector3(0, 1, 0);
  459. (function (PBRRenderQuality) {
  460. PBRRenderQuality[PBRRenderQuality["High"] = 0] = "High";
  461. PBRRenderQuality[PBRRenderQuality["Low"] = 1] = "Low";
  462. })(exports.PBRRenderQuality || (exports.PBRRenderQuality = {}));
  463. class Matrix3x3 {
  464. constructor() {
  465. var e = this.elements = new Float32Array(9);
  466. e[0] = 1;
  467. e[1] = 0;
  468. e[2] = 0;
  469. e[3] = 0;
  470. e[4] = 1;
  471. e[5] = 0;
  472. e[6] = 0;
  473. e[7] = 0;
  474. e[8] = 1;
  475. }
  476. static createRotationQuaternion(rotation, out) {
  477. var rotX = rotation.x;
  478. var rotY = rotation.y;
  479. var rotZ = rotation.z;
  480. var rotW = rotation.w;
  481. var xx = rotX * rotX;
  482. var yy = rotY * rotY;
  483. var zz = rotZ * rotZ;
  484. var xy = rotX * rotY;
  485. var zw = rotZ * rotW;
  486. var zx = rotZ * rotX;
  487. var yw = rotY * rotW;
  488. var yz = rotY * rotZ;
  489. var xw = rotX * rotW;
  490. var resultE = out.elements;
  491. resultE[0] = 1.0 - (2.0 * (yy + zz));
  492. resultE[1] = 2.0 * (xy + zw);
  493. resultE[2] = 2.0 * (zx - yw);
  494. resultE[3] = 2.0 * (xy - zw);
  495. resultE[4] = 1.0 - (2.0 * (zz + xx));
  496. resultE[5] = 2.0 * (yz + xw);
  497. resultE[6] = 2.0 * (zx + yw);
  498. resultE[7] = 2.0 * (yz - xw);
  499. resultE[8] = 1.0 - (2.0 * (yy + xx));
  500. }
  501. static createFromTranslation(trans, out) {
  502. var e = out.elements;
  503. e[0] = 1;
  504. e[1] = 0;
  505. e[2] = 0;
  506. e[3] = 0;
  507. e[4] = 1;
  508. e[5] = 0;
  509. e[6] = trans.x;
  510. e[7] = trans.y;
  511. e[8] = 1;
  512. }
  513. static createFromRotation(rad, out) {
  514. var e = out.elements;
  515. var s = Math.sin(rad), c = Math.cos(rad);
  516. e[0] = c;
  517. e[1] = s;
  518. e[2] = 0;
  519. e[3] = -s;
  520. e[4] = c;
  521. e[5] = 0;
  522. e[6] = 0;
  523. e[7] = 0;
  524. e[8] = 1;
  525. }
  526. static createFromScaling(scale, out) {
  527. var e = out.elements;
  528. e[0] = scale.x;
  529. e[1] = 0;
  530. e[2] = 0;
  531. e[3] = 0;
  532. e[4] = scale.y;
  533. e[5] = 0;
  534. e[6] = 0;
  535. e[7] = 0;
  536. e[8] = scale.z;
  537. }
  538. static createFromMatrix4x4(sou, out) {
  539. var souE = sou.elements;
  540. var outE = out.elements;
  541. outE[0] = souE[0];
  542. outE[1] = souE[1];
  543. outE[2] = souE[2];
  544. outE[3] = souE[4];
  545. outE[4] = souE[5];
  546. outE[5] = souE[6];
  547. outE[6] = souE[8];
  548. outE[7] = souE[9];
  549. outE[8] = souE[10];
  550. }
  551. static multiply(left, right, out) {
  552. var l = left.elements;
  553. var r = right.elements;
  554. var e = out.elements;
  555. var l11 = l[0], l12 = l[1], l13 = l[2];
  556. var l21 = l[3], l22 = l[4], l23 = l[5];
  557. var l31 = l[6], l32 = l[7], l33 = l[8];
  558. var r11 = r[0], r12 = r[1], r13 = r[2];
  559. var r21 = r[3], r22 = r[4], r23 = r[5];
  560. var r31 = r[6], r32 = r[7], r33 = r[8];
  561. e[0] = r11 * l11 + r12 * l21 + r13 * l31;
  562. e[1] = r11 * l12 + r12 * l22 + r13 * r32;
  563. e[2] = r11 * l13 + r12 * l23 + r13 * l33;
  564. e[3] = r21 * l11 + r22 * l21 + r23 * l31;
  565. e[4] = r21 * l12 + r22 * l22 + r23 * l32;
  566. e[5] = r21 * l13 + r22 * l23 + r23 * l33;
  567. e[6] = r31 * l11 + r32 * l21 + r33 * l31;
  568. e[7] = r31 * l12 + r32 * l22 + r33 * l32;
  569. e[8] = r31 * l13 + r32 * l23 + r33 * l33;
  570. }
  571. determinant() {
  572. var f = this.elements;
  573. var a00 = f[0], a01 = f[1], a02 = f[2];
  574. var a10 = f[3], a11 = f[4], a12 = f[5];
  575. var a20 = f[6], a21 = f[7], a22 = f[8];
  576. return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
  577. }
  578. translate(trans, out) {
  579. var e = out.elements;
  580. var f = this.elements;
  581. var a00 = f[0], a01 = f[1], a02 = f[2];
  582. var a10 = f[3], a11 = f[4], a12 = f[5];
  583. var a20 = f[6], a21 = f[7], a22 = f[8];
  584. var x = trans.x, y = trans.y;
  585. e[0] = a00;
  586. e[1] = a01;
  587. e[2] = a02;
  588. e[3] = a10;
  589. e[4] = a11;
  590. e[5] = a12;
  591. e[6] = x * a00 + y * a10 + a20;
  592. e[7] = x * a01 + y * a11 + a21;
  593. e[8] = x * a02 + y * a12 + a22;
  594. }
  595. rotate(rad, out) {
  596. var e = out.elements;
  597. var f = this.elements;
  598. var a00 = f[0], a01 = f[1], a02 = f[2];
  599. var a10 = f[3], a11 = f[4], a12 = f[5];
  600. var a20 = f[6], a21 = f[7], a22 = f[8];
  601. var s = Math.sin(rad);
  602. var c = Math.cos(rad);
  603. e[0] = c * a00 + s * a10;
  604. e[1] = c * a01 + s * a11;
  605. e[2] = c * a02 + s * a12;
  606. e[3] = c * a10 - s * a00;
  607. e[4] = c * a11 - s * a01;
  608. e[5] = c * a12 - s * a02;
  609. e[6] = a20;
  610. e[7] = a21;
  611. e[8] = a22;
  612. }
  613. scale(scale, out) {
  614. var e = out.elements;
  615. var f = this.elements;
  616. var x = scale.x, y = scale.y;
  617. e[0] = x * f[0];
  618. e[1] = x * f[1];
  619. e[2] = x * f[2];
  620. e[3] = y * f[3];
  621. e[4] = y * f[4];
  622. e[5] = y * f[5];
  623. e[6] = f[6];
  624. e[7] = f[7];
  625. e[8] = f[8];
  626. }
  627. invert(out) {
  628. var e = out.elements;
  629. var f = this.elements;
  630. var a00 = f[0], a01 = f[1], a02 = f[2];
  631. var a10 = f[3], a11 = f[4], a12 = f[5];
  632. var a20 = f[6], a21 = f[7], a22 = f[8];
  633. var b01 = a22 * a11 - a12 * a21;
  634. var b11 = -a22 * a10 + a12 * a20;
  635. var b21 = a21 * a10 - a11 * a20;
  636. var det = a00 * b01 + a01 * b11 + a02 * b21;
  637. if (!det) {
  638. return;
  639. }
  640. det = 1.0 / det;
  641. e[0] = b01 * det;
  642. e[1] = (-a22 * a01 + a02 * a21) * det;
  643. e[2] = (a12 * a01 - a02 * a11) * det;
  644. e[3] = b11 * det;
  645. e[4] = (a22 * a00 - a02 * a20) * det;
  646. e[5] = (-a12 * a00 + a02 * a10) * det;
  647. e[6] = b21 * det;
  648. e[7] = (-a21 * a00 + a01 * a20) * det;
  649. e[8] = (a11 * a00 - a01 * a10) * det;
  650. }
  651. transpose(out) {
  652. var e = out.elements;
  653. var f = this.elements;
  654. if (out === this) {
  655. var a01 = f[1], a02 = f[2], a12 = f[5];
  656. e[1] = f[3];
  657. e[2] = f[6];
  658. e[3] = a01;
  659. e[5] = f[7];
  660. e[6] = a02;
  661. e[7] = a12;
  662. }
  663. else {
  664. e[0] = f[0];
  665. e[1] = f[3];
  666. e[2] = f[6];
  667. e[3] = f[1];
  668. e[4] = f[4];
  669. e[5] = f[7];
  670. e[6] = f[2];
  671. e[7] = f[5];
  672. e[8] = f[8];
  673. }
  674. }
  675. identity() {
  676. var e = this.elements;
  677. e[0] = 1;
  678. e[1] = 0;
  679. e[2] = 0;
  680. e[3] = 0;
  681. e[4] = 1;
  682. e[5] = 0;
  683. e[6] = 0;
  684. e[7] = 0;
  685. e[8] = 1;
  686. }
  687. cloneTo(destObject) {
  688. var i, s, d;
  689. s = this.elements;
  690. d = destObject.elements;
  691. if (s === d) {
  692. return;
  693. }
  694. for (i = 0; i < 9; ++i) {
  695. d[i] = s[i];
  696. }
  697. }
  698. clone() {
  699. var dest = new Matrix3x3();
  700. this.cloneTo(dest);
  701. return dest;
  702. }
  703. static lookAt(eye, target, up, out) {
  704. Vector3.subtract(eye, target, Matrix3x3._tempV30);
  705. Vector3.normalize(Matrix3x3._tempV30, Matrix3x3._tempV30);
  706. Vector3.cross(up, Matrix3x3._tempV30, Matrix3x3._tempV31);
  707. Vector3.normalize(Matrix3x3._tempV31, Matrix3x3._tempV31);
  708. Vector3.cross(Matrix3x3._tempV30, Matrix3x3._tempV31, Matrix3x3._tempV32);
  709. var v0 = Matrix3x3._tempV30;
  710. var v1 = Matrix3x3._tempV31;
  711. var v2 = Matrix3x3._tempV32;
  712. var me = out.elements;
  713. me[0] = v1.x;
  714. me[3] = v1.y;
  715. me[6] = v1.z;
  716. me[1] = v2.x;
  717. me[4] = v2.y;
  718. me[7] = v2.z;
  719. me[2] = v0.x;
  720. me[5] = v0.y;
  721. me[8] = v0.z;
  722. }
  723. }
  724. Matrix3x3.DEFAULT = new Matrix3x3();
  725. Matrix3x3._tempV30 = new Vector3();
  726. Matrix3x3._tempV31 = new Vector3();
  727. Matrix3x3._tempV32 = new Vector3();
  728. class ILaya3D {
  729. }
  730. ILaya3D.Shader3D = null;
  731. ILaya3D.Scene3D = null;
  732. ILaya3D.MeshRenderStaticBatchManager = null;
  733. ILaya3D.MeshRenderDynamicBatchManager = null;
  734. ILaya3D.SubMeshDynamicBatch = null;
  735. ILaya3D.Laya3D = null;
  736. ILaya3D.Matrix4x4 = null;
  737. ILaya3D.Physics3D = null;
  738. ILaya3D.ShadowLightType = null;
  739. class Quaternion {
  740. constructor(x = 0, y = 0, z = 0, w = 1, nativeElements = null) {
  741. this.x = x;
  742. this.y = y;
  743. this.z = z;
  744. this.w = w;
  745. }
  746. static createFromYawPitchRoll(yaw, pitch, roll, out) {
  747. var halfRoll = roll * 0.5;
  748. var halfPitch = pitch * 0.5;
  749. var halfYaw = yaw * 0.5;
  750. var sinRoll = Math.sin(halfRoll);
  751. var cosRoll = Math.cos(halfRoll);
  752. var sinPitch = Math.sin(halfPitch);
  753. var cosPitch = Math.cos(halfPitch);
  754. var sinYaw = Math.sin(halfYaw);
  755. var cosYaw = Math.cos(halfYaw);
  756. out.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  757. out.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  758. out.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  759. out.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  760. }
  761. static multiply(left, right, out) {
  762. var lx = left.x;
  763. var ly = left.y;
  764. var lz = left.z;
  765. var lw = left.w;
  766. var rx = right.x;
  767. var ry = right.y;
  768. var rz = right.z;
  769. var rw = right.w;
  770. var a = (ly * rz - lz * ry);
  771. var b = (lz * rx - lx * rz);
  772. var c = (lx * ry - ly * rx);
  773. var d = (lx * rx + ly * ry + lz * rz);
  774. out.x = (lx * rw + rx * lw) + a;
  775. out.y = (ly * rw + ry * lw) + b;
  776. out.z = (lz * rw + rz * lw) + c;
  777. out.w = lw * rw - d;
  778. }
  779. static arcTanAngle(x, y) {
  780. if (x == 0) {
  781. if (y == 1)
  782. return Math.PI / 2;
  783. return -Math.PI / 2;
  784. }
  785. if (x > 0)
  786. return Math.atan(y / x);
  787. if (x < 0) {
  788. if (y > 0)
  789. return Math.atan(y / x) + Math.PI;
  790. return Math.atan(y / x) - Math.PI;
  791. }
  792. return 0;
  793. }
  794. static angleTo(from, location, angle) {
  795. Vector3.subtract(location, from, Quaternion.TEMPVector30);
  796. Vector3.normalize(Quaternion.TEMPVector30, Quaternion.TEMPVector30);
  797. angle.x = Math.asin(Quaternion.TEMPVector30.y);
  798. angle.y = Quaternion.arcTanAngle(-Quaternion.TEMPVector30.z, -Quaternion.TEMPVector30.x);
  799. }
  800. static createFromAxisAngle(axis, rad, out) {
  801. rad = rad * 0.5;
  802. var s = Math.sin(rad);
  803. out.x = s * axis.x;
  804. out.y = s * axis.y;
  805. out.z = s * axis.z;
  806. out.w = Math.cos(rad);
  807. }
  808. static createFromMatrix4x4(mat, out) {
  809. var me = mat.elements;
  810. var sqrt;
  811. var half;
  812. var scale = me[0] + me[5] + me[10];
  813. if (scale > 0.0) {
  814. sqrt = Math.sqrt(scale + 1.0);
  815. out.w = sqrt * 0.5;
  816. sqrt = 0.5 / sqrt;
  817. out.x = (me[6] - me[9]) * sqrt;
  818. out.y = (me[8] - me[2]) * sqrt;
  819. out.z = (me[1] - me[4]) * sqrt;
  820. }
  821. else if ((me[0] >= me[5]) && (me[0] >= me[10])) {
  822. sqrt = Math.sqrt(1.0 + me[0] - me[5] - me[10]);
  823. half = 0.5 / sqrt;
  824. out.x = 0.5 * sqrt;
  825. out.y = (me[1] + me[4]) * half;
  826. out.z = (me[2] + me[8]) * half;
  827. out.w = (me[6] - me[9]) * half;
  828. }
  829. else if (me[5] > me[10]) {
  830. sqrt = Math.sqrt(1.0 + me[5] - me[0] - me[10]);
  831. half = 0.5 / sqrt;
  832. out.x = (me[4] + me[1]) * half;
  833. out.y = 0.5 * sqrt;
  834. out.z = (me[9] + me[6]) * half;
  835. out.w = (me[8] - me[2]) * half;
  836. }
  837. else {
  838. sqrt = Math.sqrt(1.0 + me[10] - me[0] - me[5]);
  839. half = 0.5 / sqrt;
  840. out.x = (me[8] + me[2]) * half;
  841. out.y = (me[9] + me[6]) * half;
  842. out.z = 0.5 * sqrt;
  843. out.w = (me[1] - me[4]) * half;
  844. }
  845. }
  846. static slerp(left, right, t, out) {
  847. var ax = left.x, ay = left.y, az = left.z, aw = left.w, bx = right.x, by = right.y, bz = right.z, bw = right.w;
  848. var omega, cosom, sinom, scale0, scale1;
  849. cosom = ax * bx + ay * by + az * bz + aw * bw;
  850. if (cosom < 0.0) {
  851. cosom = -cosom;
  852. bx = -bx;
  853. by = -by;
  854. bz = -bz;
  855. bw = -bw;
  856. }
  857. if ((1.0 - cosom) > 0.000001) {
  858. omega = Math.acos(cosom);
  859. sinom = Math.sin(omega);
  860. scale0 = Math.sin((1.0 - t) * omega) / sinom;
  861. scale1 = Math.sin(t * omega) / sinom;
  862. }
  863. else {
  864. scale0 = 1.0 - t;
  865. scale1 = t;
  866. }
  867. out.x = scale0 * ax + scale1 * bx;
  868. out.y = scale0 * ay + scale1 * by;
  869. out.z = scale0 * az + scale1 * bz;
  870. out.w = scale0 * aw + scale1 * bw;
  871. return out;
  872. }
  873. static lerp(left, right, amount, out) {
  874. var inverse = 1.0 - amount;
  875. if (Quaternion.dot(left, right) >= 0) {
  876. out.x = (inverse * left.x) + (amount * right.x);
  877. out.y = (inverse * left.y) + (amount * right.y);
  878. out.z = (inverse * left.z) + (amount * right.z);
  879. out.w = (inverse * left.w) + (amount * right.w);
  880. }
  881. else {
  882. out.x = (inverse * left.x) - (amount * right.x);
  883. out.y = (inverse * left.y) - (amount * right.y);
  884. out.z = (inverse * left.z) - (amount * right.z);
  885. out.w = (inverse * left.w) - (amount * right.w);
  886. }
  887. out.normalize(out);
  888. }
  889. static add(left, right, out) {
  890. out.x = left.x + right.x;
  891. out.y = left.y + right.y;
  892. out.z = left.z + right.z;
  893. out.w = left.w + right.w;
  894. }
  895. static dot(left, right) {
  896. return left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w;
  897. }
  898. scaling(scaling, out) {
  899. out.x = this.x * scaling;
  900. out.y = this.y * scaling;
  901. out.z = this.z * scaling;
  902. out.w = this.w * scaling;
  903. }
  904. normalize(out) {
  905. var len = this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  906. if (len > 0) {
  907. len = 1 / Math.sqrt(len);
  908. out.x = this.x * len;
  909. out.y = this.y * len;
  910. out.z = this.z * len;
  911. out.w = this.w * len;
  912. }
  913. }
  914. length() {
  915. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  916. }
  917. rotateX(rad, out) {
  918. rad *= 0.5;
  919. var bx = Math.sin(rad), bw = Math.cos(rad);
  920. out.x = this.x * bw + this.w * bx;
  921. out.y = this.y * bw + this.z * bx;
  922. out.z = this.z * bw - this.y * bx;
  923. out.w = this.w * bw - this.x * bx;
  924. }
  925. rotateY(rad, out) {
  926. rad *= 0.5;
  927. var by = Math.sin(rad), bw = Math.cos(rad);
  928. out.x = this.x * bw - this.z * by;
  929. out.y = this.y * bw + this.w * by;
  930. out.z = this.z * bw + this.x * by;
  931. out.w = this.w * bw - this.y * by;
  932. }
  933. rotateZ(rad, out) {
  934. rad *= 0.5;
  935. var bz = Math.sin(rad), bw = Math.cos(rad);
  936. out.x = this.x * bw + this.y * bz;
  937. out.y = this.y * bw - this.x * bz;
  938. out.z = this.z * bw + this.w * bz;
  939. out.w = this.w * bw - this.z * bz;
  940. }
  941. getYawPitchRoll(out) {
  942. Vector3.transformQuat(Vector3._ForwardRH, this, Quaternion.TEMPVector31);
  943. Vector3.transformQuat(Vector3._Up, this, Quaternion.TEMPVector32);
  944. var upe = Quaternion.TEMPVector32;
  945. Quaternion.angleTo(Vector3._ZERO, Quaternion.TEMPVector31, Quaternion.TEMPVector33);
  946. var angle = Quaternion.TEMPVector33;
  947. if (angle.x == Math.PI / 2) {
  948. angle.y = Quaternion.arcTanAngle(upe.z, upe.x);
  949. angle.z = 0;
  950. }
  951. else if (angle.x == -Math.PI / 2) {
  952. angle.y = Quaternion.arcTanAngle(-upe.z, -upe.x);
  953. angle.z = 0;
  954. }
  955. else {
  956. ILaya3D.Matrix4x4.createRotationY(-angle.y, ILaya3D.Matrix4x4.TEMPMatrix0);
  957. ILaya3D.Matrix4x4.createRotationX(-angle.x, ILaya3D.Matrix4x4.TEMPMatrix1);
  958. Vector3.transformCoordinate(Quaternion.TEMPVector32, ILaya3D.Matrix4x4.TEMPMatrix0, Quaternion.TEMPVector32);
  959. Vector3.transformCoordinate(Quaternion.TEMPVector32, ILaya3D.Matrix4x4.TEMPMatrix1, Quaternion.TEMPVector32);
  960. angle.z = Quaternion.arcTanAngle(upe.y, -upe.x);
  961. }
  962. if (angle.y <= -Math.PI)
  963. angle.y = Math.PI;
  964. if (angle.z <= -Math.PI)
  965. angle.z = Math.PI;
  966. if (angle.y >= Math.PI && angle.z >= Math.PI) {
  967. angle.y = 0;
  968. angle.z = 0;
  969. angle.x = Math.PI - angle.x;
  970. }
  971. var oe = out;
  972. oe.x = angle.y;
  973. oe.y = angle.x;
  974. oe.z = angle.z;
  975. }
  976. invert(out) {
  977. var a0 = this.x, a1 = this.y, a2 = this.z, a3 = this.w;
  978. var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
  979. var invDot = dot ? 1.0 / dot : 0;
  980. out.x = -a0 * invDot;
  981. out.y = -a1 * invDot;
  982. out.z = -a2 * invDot;
  983. out.w = a3 * invDot;
  984. }
  985. identity() {
  986. this.x = 0;
  987. this.y = 0;
  988. this.z = 0;
  989. this.w = 1;
  990. }
  991. fromArray(array, offset = 0) {
  992. this.x = array[offset + 0];
  993. this.y = array[offset + 1];
  994. this.z = array[offset + 2];
  995. this.w = array[offset + 3];
  996. }
  997. cloneTo(destObject) {
  998. if (this === destObject) {
  999. return;
  1000. }
  1001. destObject.x = this.x;
  1002. destObject.y = this.y;
  1003. destObject.z = this.z;
  1004. destObject.w = this.w;
  1005. }
  1006. clone() {
  1007. var dest = new Quaternion();
  1008. this.cloneTo(dest);
  1009. return dest;
  1010. }
  1011. equals(b) {
  1012. return MathUtils3D.nearEqual(this.x, b.x) && MathUtils3D.nearEqual(this.y, b.y) && MathUtils3D.nearEqual(this.z, b.z) && MathUtils3D.nearEqual(this.w, b.w);
  1013. }
  1014. static rotationLookAt(forward, up, out) {
  1015. Quaternion.lookAt(Vector3._ZERO, forward, up, out);
  1016. }
  1017. static lookAt(eye, target, up, out) {
  1018. Matrix3x3.lookAt(eye, target, up, Quaternion._tempMatrix3x3);
  1019. Quaternion.rotationMatrix(Quaternion._tempMatrix3x3, out);
  1020. }
  1021. lengthSquared() {
  1022. return (this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w);
  1023. }
  1024. static invert(value, out) {
  1025. var lengthSq = value.lengthSquared();
  1026. if (!MathUtils3D.isZero(lengthSq)) {
  1027. lengthSq = 1.0 / lengthSq;
  1028. out.x = -value.x * lengthSq;
  1029. out.y = -value.y * lengthSq;
  1030. out.z = -value.z * lengthSq;
  1031. out.w = value.w * lengthSq;
  1032. }
  1033. }
  1034. static rotationMatrix(matrix3x3, out) {
  1035. var me = matrix3x3.elements;
  1036. var m11 = me[0];
  1037. var m12 = me[1];
  1038. var m13 = me[2];
  1039. var m21 = me[3];
  1040. var m22 = me[4];
  1041. var m23 = me[5];
  1042. var m31 = me[6];
  1043. var m32 = me[7];
  1044. var m33 = me[8];
  1045. var sqrt, half;
  1046. var scale = m11 + m22 + m33;
  1047. if (scale > 0) {
  1048. sqrt = Math.sqrt(scale + 1);
  1049. out.w = sqrt * 0.5;
  1050. sqrt = 0.5 / sqrt;
  1051. out.x = (m23 - m32) * sqrt;
  1052. out.y = (m31 - m13) * sqrt;
  1053. out.z = (m12 - m21) * sqrt;
  1054. }
  1055. else if ((m11 >= m22) && (m11 >= m33)) {
  1056. sqrt = Math.sqrt(1 + m11 - m22 - m33);
  1057. half = 0.5 / sqrt;
  1058. out.x = 0.5 * sqrt;
  1059. out.y = (m12 + m21) * half;
  1060. out.z = (m13 + m31) * half;
  1061. out.w = (m23 - m32) * half;
  1062. }
  1063. else if (m22 > m33) {
  1064. sqrt = Math.sqrt(1 + m22 - m11 - m33);
  1065. half = 0.5 / sqrt;
  1066. out.x = (m21 + m12) * half;
  1067. out.y = 0.5 * sqrt;
  1068. out.z = (m32 + m23) * half;
  1069. out.w = (m31 - m13) * half;
  1070. }
  1071. else {
  1072. sqrt = Math.sqrt(1 + m33 - m11 - m22);
  1073. half = 0.5 / sqrt;
  1074. out.x = (m31 + m13) * half;
  1075. out.y = (m32 + m23) * half;
  1076. out.z = 0.5 * sqrt;
  1077. out.w = (m12 - m21) * half;
  1078. }
  1079. }
  1080. forNativeElement(nativeElements = null) {
  1081. if (nativeElements) {
  1082. this.elements = nativeElements;
  1083. this.elements[0] = this.x;
  1084. this.elements[1] = this.y;
  1085. this.elements[2] = this.z;
  1086. this.elements[3] = this.w;
  1087. }
  1088. else {
  1089. this.elements = new Float32Array([this.x, this.y, this.z, this.w]);
  1090. }
  1091. Vector2.rewriteNumProperty(this, "x", 0);
  1092. Vector2.rewriteNumProperty(this, "y", 1);
  1093. Vector2.rewriteNumProperty(this, "z", 2);
  1094. Vector2.rewriteNumProperty(this, "w", 3);
  1095. }
  1096. }
  1097. Quaternion.TEMPVector30 = new Vector3();
  1098. Quaternion.TEMPVector31 = new Vector3();
  1099. Quaternion.TEMPVector32 = new Vector3();
  1100. Quaternion.TEMPVector33 = new Vector3();
  1101. Quaternion._tempMatrix3x3 = new Matrix3x3();
  1102. Quaternion.DEFAULT = new Quaternion();
  1103. Quaternion.NAN = new Quaternion(NaN, NaN, NaN, NaN);
  1104. class Matrix4x4 {
  1105. constructor(m11 = 1, m12 = 0, m13 = 0, m14 = 0, m21 = 0, m22 = 1, m23 = 0, m24 = 0, m31 = 0, m32 = 0, m33 = 1, m34 = 0, m41 = 0, m42 = 0, m43 = 0, m44 = 1, elements = null) {
  1106. var e = elements ? this.elements = elements : this.elements = new Float32Array(16);
  1107. e[0] = m11;
  1108. e[1] = m12;
  1109. e[2] = m13;
  1110. e[3] = m14;
  1111. e[4] = m21;
  1112. e[5] = m22;
  1113. e[6] = m23;
  1114. e[7] = m24;
  1115. e[8] = m31;
  1116. e[9] = m32;
  1117. e[10] = m33;
  1118. e[11] = m34;
  1119. e[12] = m41;
  1120. e[13] = m42;
  1121. e[14] = m43;
  1122. e[15] = m44;
  1123. }
  1124. static createRotationX(rad, out) {
  1125. var oe = out.elements;
  1126. var s = Math.sin(rad), c = Math.cos(rad);
  1127. oe[1] = oe[2] = oe[3] = oe[4] = oe[7] = oe[8] = oe[11] = oe[12] = oe[13] = oe[14] = 0;
  1128. oe[0] = oe[15] = 1;
  1129. oe[5] = oe[10] = c;
  1130. oe[6] = s;
  1131. oe[9] = -s;
  1132. }
  1133. static createRotationY(rad, out) {
  1134. var oe = out.elements;
  1135. var s = Math.sin(rad), c = Math.cos(rad);
  1136. oe[1] = oe[3] = oe[4] = oe[6] = oe[7] = oe[9] = oe[11] = oe[12] = oe[13] = oe[14] = 0;
  1137. oe[5] = oe[15] = 1;
  1138. oe[0] = oe[10] = c;
  1139. oe[2] = -s;
  1140. oe[8] = s;
  1141. }
  1142. static createRotationZ(rad, out) {
  1143. var oe = out.elements;
  1144. var s = Math.sin(rad), c = Math.cos(rad);
  1145. oe[2] = oe[3] = oe[6] = oe[7] = oe[8] = oe[9] = oe[11] = oe[12] = oe[13] = oe[14] = 0;
  1146. oe[10] = oe[15] = 1;
  1147. oe[0] = oe[5] = c;
  1148. oe[1] = s;
  1149. oe[4] = -s;
  1150. }
  1151. static createRotationYawPitchRoll(yaw, pitch, roll, result) {
  1152. Quaternion.createFromYawPitchRoll(yaw, pitch, roll, Matrix4x4._tempQuaternion);
  1153. Matrix4x4.createRotationQuaternion(Matrix4x4._tempQuaternion, result);
  1154. }
  1155. static createRotationAxis(axis, angle, result) {
  1156. var x = axis.x;
  1157. var y = axis.y;
  1158. var z = axis.z;
  1159. var cos = Math.cos(angle);
  1160. var sin = Math.sin(angle);
  1161. var xx = x * x;
  1162. var yy = y * y;
  1163. var zz = z * z;
  1164. var xy = x * y;
  1165. var xz = x * z;
  1166. var yz = y * z;
  1167. var resultE = result.elements;
  1168. resultE[3] = resultE[7] = resultE[11] = resultE[12] = resultE[13] = resultE[14] = 0;
  1169. resultE[15] = 1.0;
  1170. resultE[0] = xx + (cos * (1.0 - xx));
  1171. resultE[1] = (xy - (cos * xy)) + (sin * z);
  1172. resultE[2] = (xz - (cos * xz)) - (sin * y);
  1173. resultE[4] = (xy - (cos * xy)) - (sin * z);
  1174. resultE[5] = yy + (cos * (1.0 - yy));
  1175. resultE[6] = (yz - (cos * yz)) + (sin * x);
  1176. resultE[8] = (xz - (cos * xz)) + (sin * y);
  1177. resultE[9] = (yz - (cos * yz)) - (sin * x);
  1178. resultE[10] = zz + (cos * (1.0 - zz));
  1179. }
  1180. setRotation(rotation) {
  1181. var rotationX = rotation.x;
  1182. var rotationY = rotation.y;
  1183. var rotationZ = rotation.z;
  1184. var rotationW = rotation.w;
  1185. var xx = rotationX * rotationX;
  1186. var yy = rotationY * rotationY;
  1187. var zz = rotationZ * rotationZ;
  1188. var xy = rotationX * rotationY;
  1189. var zw = rotationZ * rotationW;
  1190. var zx = rotationZ * rotationX;
  1191. var yw = rotationY * rotationW;
  1192. var yz = rotationY * rotationZ;
  1193. var xw = rotationX * rotationW;
  1194. var e = this.elements;
  1195. e[0] = 1.0 - (2.0 * (yy + zz));
  1196. e[1] = 2.0 * (xy + zw);
  1197. e[2] = 2.0 * (zx - yw);
  1198. e[4] = 2.0 * (xy - zw);
  1199. e[5] = 1.0 - (2.0 * (zz + xx));
  1200. e[6] = 2.0 * (yz + xw);
  1201. e[8] = 2.0 * (zx + yw);
  1202. e[9] = 2.0 * (yz - xw);
  1203. e[10] = 1.0 - (2.0 * (yy + xx));
  1204. }
  1205. setPosition(position) {
  1206. var e = this.elements;
  1207. e[12] = position.x;
  1208. e[13] = position.y;
  1209. e[14] = position.z;
  1210. }
  1211. static createRotationQuaternion(rotation, result) {
  1212. var resultE = result.elements;
  1213. var rotationX = rotation.x;
  1214. var rotationY = rotation.y;
  1215. var rotationZ = rotation.z;
  1216. var rotationW = rotation.w;
  1217. var xx = rotationX * rotationX;
  1218. var yy = rotationY * rotationY;
  1219. var zz = rotationZ * rotationZ;
  1220. var xy = rotationX * rotationY;
  1221. var zw = rotationZ * rotationW;
  1222. var zx = rotationZ * rotationX;
  1223. var yw = rotationY * rotationW;
  1224. var yz = rotationY * rotationZ;
  1225. var xw = rotationX * rotationW;
  1226. resultE[3] = resultE[7] = resultE[11] = resultE[12] = resultE[13] = resultE[14] = 0;
  1227. resultE[15] = 1.0;
  1228. resultE[0] = 1.0 - (2.0 * (yy + zz));
  1229. resultE[1] = 2.0 * (xy + zw);
  1230. resultE[2] = 2.0 * (zx - yw);
  1231. resultE[4] = 2.0 * (xy - zw);
  1232. resultE[5] = 1.0 - (2.0 * (zz + xx));
  1233. resultE[6] = 2.0 * (yz + xw);
  1234. resultE[8] = 2.0 * (zx + yw);
  1235. resultE[9] = 2.0 * (yz - xw);
  1236. resultE[10] = 1.0 - (2.0 * (yy + xx));
  1237. }
  1238. static createTranslate(trans, out) {
  1239. var oe = out.elements;
  1240. oe[4] = oe[8] = oe[1] = oe[9] = oe[2] = oe[6] = oe[3] = oe[7] = oe[11] = 0;
  1241. oe[0] = oe[5] = oe[10] = oe[15] = 1;
  1242. oe[12] = trans.x;
  1243. oe[13] = trans.y;
  1244. oe[14] = trans.z;
  1245. }
  1246. static createScaling(scale, out) {
  1247. var oe = out.elements;
  1248. oe[0] = scale.x;
  1249. oe[5] = scale.y;
  1250. oe[10] = scale.z;
  1251. oe[1] = oe[4] = oe[8] = oe[12] = oe[9] = oe[13] = oe[2] = oe[6] = oe[14] = oe[3] = oe[7] = oe[11] = 0;
  1252. oe[15] = 1;
  1253. }
  1254. static multiply(left, right, out) {
  1255. var l = right.elements;
  1256. var r = left.elements;
  1257. var e = out.elements;
  1258. var l11 = l[0], l12 = l[1], l13 = l[2], l14 = l[3];
  1259. var l21 = l[4], l22 = l[5], l23 = l[6], l24 = l[7];
  1260. var l31 = l[8], l32 = l[9], l33 = l[10], l34 = l[11];
  1261. var l41 = l[12], l42 = l[13], l43 = l[14], l44 = l[15];
  1262. var r11 = r[0], r12 = r[1], r13 = r[2], r14 = r[3];
  1263. var r21 = r[4], r22 = r[5], r23 = r[6], r24 = r[7];
  1264. var r31 = r[8], r32 = r[9], r33 = r[10], r34 = r[11];
  1265. var r41 = r[12], r42 = r[13], r43 = r[14], r44 = r[15];
  1266. e[0] = (l11 * r11) + (l12 * r21) + (l13 * r31) + (l14 * r41);
  1267. e[1] = (l11 * r12) + (l12 * r22) + (l13 * r32) + (l14 * r42);
  1268. e[2] = (l11 * r13) + (l12 * r23) + (l13 * r33) + (l14 * r43);
  1269. e[3] = (l11 * r14) + (l12 * r24) + (l13 * r34) + (l14 * r44);
  1270. e[4] = (l21 * r11) + (l22 * r21) + (l23 * r31) + (l24 * r41);
  1271. e[5] = (l21 * r12) + (l22 * r22) + (l23 * r32) + (l24 * r42);
  1272. e[6] = (l21 * r13) + (l22 * r23) + (l23 * r33) + (l24 * r43);
  1273. e[7] = (l21 * r14) + (l22 * r24) + (l23 * r34) + (l24 * r44);
  1274. e[8] = (l31 * r11) + (l32 * r21) + (l33 * r31) + (l34 * r41);
  1275. e[9] = (l31 * r12) + (l32 * r22) + (l33 * r32) + (l34 * r42);
  1276. e[10] = (l31 * r13) + (l32 * r23) + (l33 * r33) + (l34 * r43);
  1277. e[11] = (l31 * r14) + (l32 * r24) + (l33 * r34) + (l34 * r44);
  1278. e[12] = (l41 * r11) + (l42 * r21) + (l43 * r31) + (l44 * r41);
  1279. e[13] = (l41 * r12) + (l42 * r22) + (l43 * r32) + (l44 * r42);
  1280. e[14] = (l41 * r13) + (l42 * r23) + (l43 * r33) + (l44 * r43);
  1281. e[15] = (l41 * r14) + (l42 * r24) + (l43 * r34) + (l44 * r44);
  1282. }
  1283. static multiplyForNative(left, right, out) {
  1284. Laya.LayaGL.instance.matrix4x4Multiply(left.elements, right.elements, out.elements);
  1285. }
  1286. static createFromQuaternion(rotation, out) {
  1287. var e = out.elements;
  1288. var x = rotation.x, y = rotation.y, z = rotation.z, w = rotation.w;
  1289. var x2 = x + x;
  1290. var y2 = y + y;
  1291. var z2 = z + z;
  1292. var xx = x * x2;
  1293. var yx = y * x2;
  1294. var yy = y * y2;
  1295. var zx = z * x2;
  1296. var zy = z * y2;
  1297. var zz = z * z2;
  1298. var wx = w * x2;
  1299. var wy = w * y2;
  1300. var wz = w * z2;
  1301. e[0] = 1 - yy - zz;
  1302. e[1] = yx + wz;
  1303. e[2] = zx - wy;
  1304. e[3] = 0;
  1305. e[4] = yx - wz;
  1306. e[5] = 1 - xx - zz;
  1307. e[6] = zy + wx;
  1308. e[7] = 0;
  1309. e[8] = zx + wy;
  1310. e[9] = zy - wx;
  1311. e[10] = 1 - xx - yy;
  1312. e[11] = 0;
  1313. e[12] = 0;
  1314. e[13] = 0;
  1315. e[14] = 0;
  1316. e[15] = 1;
  1317. }
  1318. static createAffineTransformation(trans, rot, scale, out) {
  1319. var oe = out.elements;
  1320. var x = rot.x, y = rot.y, z = rot.z, w = rot.w, x2 = x + x, y2 = y + y, z2 = z + z;
  1321. var xx = x * x2, xy = x * y2, xz = x * z2, yy = y * y2, yz = y * z2, zz = z * z2;
  1322. var wx = w * x2, wy = w * y2, wz = w * z2, sx = scale.x, sy = scale.y, sz = scale.z;
  1323. oe[0] = (1 - (yy + zz)) * sx;
  1324. oe[1] = (xy + wz) * sx;
  1325. oe[2] = (xz - wy) * sx;
  1326. oe[3] = 0;
  1327. oe[4] = (xy - wz) * sy;
  1328. oe[5] = (1 - (xx + zz)) * sy;
  1329. oe[6] = (yz + wx) * sy;
  1330. oe[7] = 0;
  1331. oe[8] = (xz + wy) * sz;
  1332. oe[9] = (yz - wx) * sz;
  1333. oe[10] = (1 - (xx + yy)) * sz;
  1334. oe[11] = 0;
  1335. oe[12] = trans.x;
  1336. oe[13] = trans.y;
  1337. oe[14] = trans.z;
  1338. oe[15] = 1;
  1339. }
  1340. static createLookAt(eye, target, up, out) {
  1341. var oE = out.elements;
  1342. var xaxis = Matrix4x4._tempVector0;
  1343. var yaxis = Matrix4x4._tempVector1;
  1344. var zaxis = Matrix4x4._tempVector2;
  1345. Vector3.subtract(eye, target, zaxis);
  1346. Vector3.normalize(zaxis, zaxis);
  1347. Vector3.cross(up, zaxis, xaxis);
  1348. Vector3.normalize(xaxis, xaxis);
  1349. Vector3.cross(zaxis, xaxis, yaxis);
  1350. oE[3] = oE[7] = oE[11] = 0;
  1351. oE[15] = 1;
  1352. oE[0] = xaxis.x;
  1353. oE[4] = xaxis.y;
  1354. oE[8] = xaxis.z;
  1355. oE[1] = yaxis.x;
  1356. oE[5] = yaxis.y;
  1357. oE[9] = yaxis.z;
  1358. oE[2] = zaxis.x;
  1359. oE[6] = zaxis.y;
  1360. oE[10] = zaxis.z;
  1361. oE[12] = -Vector3.dot(xaxis, eye);
  1362. oE[13] = -Vector3.dot(yaxis, eye);
  1363. oE[14] = -Vector3.dot(zaxis, eye);
  1364. }
  1365. static createPerspective(fov, aspect, znear, zfar, out) {
  1366. var yScale = 1.0 / Math.tan(fov * 0.5);
  1367. var xScale = yScale / aspect;
  1368. var halfWidth = znear / xScale;
  1369. var halfHeight = znear / yScale;
  1370. Matrix4x4.createPerspectiveOffCenter(-halfWidth, halfWidth, -halfHeight, halfHeight, znear, zfar, out);
  1371. }
  1372. static createPerspectiveOffCenter(left, right, bottom, top, znear, zfar, out) {
  1373. var oe = out.elements;
  1374. var zRange = zfar / (zfar - znear);
  1375. oe[1] = oe[2] = oe[3] = oe[4] = oe[6] = oe[7] = oe[12] = oe[13] = oe[15] = 0;
  1376. oe[0] = 2.0 * znear / (right - left);
  1377. oe[5] = 2.0 * znear / (top - bottom);
  1378. oe[8] = (left + right) / (right - left);
  1379. oe[9] = (top + bottom) / (top - bottom);
  1380. oe[10] = -zRange;
  1381. oe[11] = -1.0;
  1382. oe[14] = -znear * zRange;
  1383. }
  1384. static createOrthoOffCenter(left, right, bottom, top, znear, zfar, out) {
  1385. var oe = out.elements;
  1386. var zRange = 1.0 / (zfar - znear);
  1387. oe[1] = oe[2] = oe[3] = oe[4] = oe[6] = oe[8] = oe[7] = oe[9] = oe[11] = 0;
  1388. oe[15] = 1;
  1389. oe[0] = 2.0 / (right - left);
  1390. oe[5] = 2.0 / (top - bottom);
  1391. oe[10] = -zRange;
  1392. oe[12] = (left + right) / (left - right);
  1393. oe[13] = (top + bottom) / (bottom - top);
  1394. oe[14] = -znear * zRange;
  1395. }
  1396. getElementByRowColumn(row, column) {
  1397. if (row < 0 || row > 3)
  1398. throw new Error("row Rows and columns for matrices run from 0 to 3, inclusive.");
  1399. if (column < 0 || column > 3)
  1400. throw new Error("column Rows and columns for matrices run from 0 to 3, inclusive.");
  1401. return this.elements[(row * 4) + column];
  1402. }
  1403. setElementByRowColumn(row, column, value) {
  1404. if (row < 0 || row > 3)
  1405. throw new Error("row Rows and columns for matrices run from 0 to 3, inclusive.");
  1406. if (column < 0 || column > 3)
  1407. throw new Error("column Rows and columns for matrices run from 0 to 3, inclusive.");
  1408. this.elements[(row * 4) + column] = value;
  1409. }
  1410. equalsOtherMatrix(other) {
  1411. var e = this.elements;
  1412. var oe = other.elements;
  1413. return (MathUtils3D.nearEqual(e[0], oe[0]) && MathUtils3D.nearEqual(e[1], oe[1]) && MathUtils3D.nearEqual(e[2], oe[2]) && MathUtils3D.nearEqual(e[3], oe[3]) && MathUtils3D.nearEqual(e[4], oe[4]) && MathUtils3D.nearEqual(e[5], oe[5]) && MathUtils3D.nearEqual(e[6], oe[6]) && MathUtils3D.nearEqual(e[7], oe[7]) && MathUtils3D.nearEqual(e[8], oe[8]) && MathUtils3D.nearEqual(e[9], oe[9]) && MathUtils3D.nearEqual(e[10], oe[10]) && MathUtils3D.nearEqual(e[11], oe[11]) && MathUtils3D.nearEqual(e[12], oe[12]) && MathUtils3D.nearEqual(e[13], oe[13]) && MathUtils3D.nearEqual(e[14], oe[14]) && MathUtils3D.nearEqual(e[15], oe[15]));
  1414. }
  1415. decomposeTransRotScale(translation, rotation, scale) {
  1416. var rotationMatrix = Matrix4x4._tempMatrix4x4;
  1417. if (this.decomposeTransRotMatScale(translation, rotationMatrix, scale)) {
  1418. Quaternion.createFromMatrix4x4(rotationMatrix, rotation);
  1419. return true;
  1420. }
  1421. else {
  1422. rotation.identity();
  1423. return false;
  1424. }
  1425. }
  1426. decomposeTransRotMatScale(translation, rotationMatrix, scale) {
  1427. var e = this.elements;
  1428. var te = translation;
  1429. var re = rotationMatrix.elements;
  1430. var se = scale;
  1431. te.x = e[12];
  1432. te.y = e[13];
  1433. te.z = e[14];
  1434. var m11 = e[0], m12 = e[1], m13 = e[2];
  1435. var m21 = e[4], m22 = e[5], m23 = e[6];
  1436. var m31 = e[8], m32 = e[9], m33 = e[10];
  1437. var sX = se.x = Math.sqrt((m11 * m11) + (m12 * m12) + (m13 * m13));
  1438. var sY = se.y = Math.sqrt((m21 * m21) + (m22 * m22) + (m23 * m23));
  1439. var sZ = se.z = Math.sqrt((m31 * m31) + (m32 * m32) + (m33 * m33));
  1440. if (MathUtils3D.isZero(sX) || MathUtils3D.isZero(sY) || MathUtils3D.isZero(sZ)) {
  1441. re[1] = re[2] = re[3] = re[4] = re[6] = re[7] = re[8] = re[9] = re[11] = re[12] = re[13] = re[14] = 0;
  1442. re[0] = re[5] = re[10] = re[15] = 1;
  1443. return false;
  1444. }
  1445. var at = Matrix4x4._tempVector0;
  1446. at.x = m31 / sZ;
  1447. at.y = m32 / sZ;
  1448. at.z = m33 / sZ;
  1449. var tempRight = Matrix4x4._tempVector1;
  1450. tempRight.x = m11 / sX;
  1451. tempRight.y = m12 / sX;
  1452. tempRight.z = m13 / sX;
  1453. var up = Matrix4x4._tempVector2;
  1454. Vector3.cross(at, tempRight, up);
  1455. var right = Matrix4x4._tempVector1;
  1456. Vector3.cross(up, at, right);
  1457. re[3] = re[7] = re[11] = re[12] = re[13] = re[14] = 0;
  1458. re[15] = 1;
  1459. re[0] = right.x;
  1460. re[1] = right.y;
  1461. re[2] = right.z;
  1462. re[4] = up.x;
  1463. re[5] = up.y;
  1464. re[6] = up.z;
  1465. re[8] = at.x;
  1466. re[9] = at.y;
  1467. re[10] = at.z;
  1468. ((re[0] * m11 + re[1] * m12 + re[2] * m13) < 0.0) && (se.x = -sX);
  1469. ((re[4] * m21 + re[5] * m22 + re[6] * m23) < 0.0) && (se.y = -sY);
  1470. ((re[8] * m31 + re[9] * m32 + re[10] * m33) < 0.0) && (se.z = -sZ);
  1471. return true;
  1472. }
  1473. decomposeYawPitchRoll(yawPitchRoll) {
  1474. var pitch = Math.asin(-this.elements[9]);
  1475. yawPitchRoll.y = pitch;
  1476. var test = Math.cos(pitch);
  1477. if (test > MathUtils3D.zeroTolerance) {
  1478. yawPitchRoll.z = Math.atan2(this.elements[1], this.elements[5]);
  1479. yawPitchRoll.x = Math.atan2(this.elements[8], this.elements[10]);
  1480. }
  1481. else {
  1482. yawPitchRoll.z = Math.atan2(-this.elements[4], this.elements[0]);
  1483. yawPitchRoll.x = 0.0;
  1484. }
  1485. }
  1486. normalize() {
  1487. var v = this.elements;
  1488. var c = v[0], d = v[1], e = v[2], g = Math.sqrt(c * c + d * d + e * e);
  1489. if (g) {
  1490. if (g == 1)
  1491. return;
  1492. }
  1493. else {
  1494. v[0] = 0;
  1495. v[1] = 0;
  1496. v[2] = 0;
  1497. return;
  1498. }
  1499. g = 1 / g;
  1500. v[0] = c * g;
  1501. v[1] = d * g;
  1502. v[2] = e * g;
  1503. }
  1504. transpose() {
  1505. var e, t;
  1506. e = this.elements;
  1507. t = e[1];
  1508. e[1] = e[4];
  1509. e[4] = t;
  1510. t = e[2];
  1511. e[2] = e[8];
  1512. e[8] = t;
  1513. t = e[3];
  1514. e[3] = e[12];
  1515. e[12] = t;
  1516. t = e[6];
  1517. e[6] = e[9];
  1518. e[9] = t;
  1519. t = e[7];
  1520. e[7] = e[13];
  1521. e[13] = t;
  1522. t = e[11];
  1523. e[11] = e[14];
  1524. e[14] = t;
  1525. return this;
  1526. }
  1527. invert(out) {
  1528. var ae = this.elements;
  1529. var oe = out.elements;
  1530. var a00 = ae[0], a01 = ae[1], a02 = ae[2], a03 = ae[3], a10 = ae[4], a11 = ae[5], a12 = ae[6], a13 = ae[7], a20 = ae[8], a21 = ae[9], a22 = ae[10], a23 = ae[11], a30 = ae[12], a31 = ae[13], a32 = ae[14], a33 = ae[15], b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12, b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32, det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  1531. if (Math.abs(det) === 0.0) {
  1532. return;
  1533. }
  1534. det = 1.0 / det;
  1535. oe[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  1536. oe[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  1537. oe[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  1538. oe[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  1539. oe[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  1540. oe[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  1541. oe[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  1542. oe[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  1543. oe[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  1544. oe[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  1545. oe[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  1546. oe[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  1547. oe[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  1548. oe[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  1549. oe[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  1550. oe[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  1551. }
  1552. static billboard(objectPosition, cameraPosition, cameraRight, cameraUp, cameraForward, mat) {
  1553. Vector3.subtract(objectPosition, cameraPosition, Matrix4x4._tempVector0);
  1554. var lengthSq = Vector3.scalarLengthSquared(Matrix4x4._tempVector0);
  1555. if (MathUtils3D.isZero(lengthSq)) {
  1556. Vector3.scale(cameraForward, -1, Matrix4x4._tempVector1);
  1557. Matrix4x4._tempVector1.cloneTo(Matrix4x4._tempVector0);
  1558. }
  1559. else {
  1560. Vector3.scale(Matrix4x4._tempVector0, 1 / Math.sqrt(lengthSq), Matrix4x4._tempVector0);
  1561. }
  1562. Vector3.cross(cameraUp, Matrix4x4._tempVector0, Matrix4x4._tempVector2);
  1563. Vector3.normalize(Matrix4x4._tempVector2, Matrix4x4._tempVector2);
  1564. Vector3.cross(Matrix4x4._tempVector0, Matrix4x4._tempVector2, Matrix4x4._tempVector3);
  1565. var crosse = Matrix4x4._tempVector2;
  1566. var finale = Matrix4x4._tempVector3;
  1567. var diffee = Matrix4x4._tempVector0;
  1568. var obpose = objectPosition;
  1569. var mate = mat.elements;
  1570. mate[0] = crosse.x;
  1571. mate[1] = crosse.y;
  1572. mate[2] = crosse.z;
  1573. mate[3] = 0.0;
  1574. mate[4] = finale.x;
  1575. mate[5] = finale.y;
  1576. mate[6] = finale.z;
  1577. mate[7] = 0.0;
  1578. mate[8] = diffee.x;
  1579. mate[9] = diffee.y;
  1580. mate[10] = diffee.z;
  1581. mate[11] = 0.0;
  1582. mate[12] = obpose.x;
  1583. mate[13] = obpose.y;
  1584. mate[14] = obpose.z;
  1585. mate[15] = 1.0;
  1586. }
  1587. identity() {
  1588. var e = this.elements;
  1589. e[1] = e[2] = e[3] = e[4] = e[6] = e[7] = e[8] = e[9] = e[11] = e[12] = e[13] = e[14] = 0;
  1590. e[0] = e[5] = e[10] = e[15] = 1;
  1591. }
  1592. cloneTo(destObject) {
  1593. var i, s, d;
  1594. s = this.elements;
  1595. d = destObject.elements;
  1596. if (s === d) {
  1597. return;
  1598. }
  1599. for (i = 0; i < 16; ++i) {
  1600. d[i] = s[i];
  1601. }
  1602. }
  1603. clone() {
  1604. var dest = new Matrix4x4();
  1605. this.cloneTo(dest);
  1606. return dest;
  1607. }
  1608. static translation(v3, out) {
  1609. var oe = out.elements;
  1610. oe[0] = oe[5] = oe[10] = oe[15] = 1;
  1611. oe[12] = v3.x;
  1612. oe[13] = v3.y;
  1613. oe[14] = v3.z;
  1614. }
  1615. getTranslationVector(out) {
  1616. var me = this.elements;
  1617. out.x = me[12];
  1618. out.y = me[13];
  1619. out.z = me[14];
  1620. }
  1621. setTranslationVector(translate) {
  1622. var me = this.elements;
  1623. var ve = translate;
  1624. me[12] = ve.x;
  1625. me[13] = ve.y;
  1626. me[14] = ve.z;
  1627. }
  1628. getForward(out) {
  1629. var me = this.elements;
  1630. out.x = -me[8];
  1631. out.y = -me[9];
  1632. out.z = -me[10];
  1633. }
  1634. setForward(forward) {
  1635. var me = this.elements;
  1636. me[8] = -forward.x;
  1637. me[9] = -forward.y;
  1638. me[10] = -forward.z;
  1639. }
  1640. getInvertFront() {
  1641. this.decomposeTransRotScale(Matrix4x4._tempVector0, Matrix4x4._tempQuaternion, Matrix4x4._tempVector1);
  1642. var scale = Matrix4x4._tempVector1;
  1643. var isInvert = scale.x < 0;
  1644. (scale.y < 0) && (isInvert = !isInvert);
  1645. (scale.z < 0) && (isInvert = !isInvert);
  1646. return isInvert;
  1647. }
  1648. }
  1649. Matrix4x4._tempMatrix4x4 = new Matrix4x4();
  1650. Matrix4x4.TEMPMatrix0 = new Matrix4x4();
  1651. Matrix4x4.TEMPMatrix1 = new Matrix4x4();
  1652. Matrix4x4._tempVector0 = new Vector3();
  1653. Matrix4x4._tempVector1 = new Vector3();
  1654. Matrix4x4._tempVector2 = new Vector3();
  1655. Matrix4x4._tempVector3 = new Vector3();
  1656. Matrix4x4._tempQuaternion = new Quaternion();
  1657. Matrix4x4.DEFAULT = new Matrix4x4();
  1658. Matrix4x4.ZERO = new Matrix4x4(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1659. class ColliderShape {
  1660. constructor() {
  1661. this._scale = new Vector3(1, 1, 1);
  1662. this._centerMatrix = new Matrix4x4();
  1663. this._attatched = false;
  1664. this._indexInCompound = -1;
  1665. this._compoundParent = null;
  1666. this._attatchedCollisionObject = null;
  1667. this._referenceCount = 0;
  1668. this._localOffset = new Vector3(0, 0, 0);
  1669. this._localRotation = new Quaternion(0, 0, 0, 1);
  1670. this.needsCustomCollisionCallback = false;
  1671. }
  1672. static __init__() {
  1673. var bt = ILaya3D.Physics3D._bullet;
  1674. ColliderShape._btScale = bt.btVector3_create(1, 1, 1);
  1675. ColliderShape._btVector30 = bt.btVector3_create(0, 0, 0);
  1676. ColliderShape._btQuaternion0 = bt.btQuaternion_create(0, 0, 0, 1);
  1677. ColliderShape._btTransform0 = bt.btTransform_create();
  1678. }
  1679. static _createAffineTransformation(trans, rot, outE) {
  1680. var x = rot.x, y = rot.y, z = rot.z, w = rot.w, x2 = x + x, y2 = y + y, z2 = z + z;
  1681. var xx = x * x2, xy = x * y2, xz = x * z2, yy = y * y2, yz = y * z2, zz = z * z2;
  1682. var wx = w * x2, wy = w * y2, wz = w * z2;
  1683. outE[0] = (1 - (yy + zz));
  1684. outE[1] = (xy + wz);
  1685. outE[2] = (xz - wy);
  1686. outE[3] = 0;
  1687. outE[4] = (xy - wz);
  1688. outE[5] = (1 - (xx + zz));
  1689. outE[6] = (yz + wx);
  1690. outE[7] = 0;
  1691. outE[8] = (xz + wy);
  1692. outE[9] = (yz - wx);
  1693. outE[10] = (1 - (xx + yy));
  1694. outE[11] = 0;
  1695. outE[12] = trans.x;
  1696. outE[13] = trans.y;
  1697. outE[14] = trans.z;
  1698. outE[15] = 1;
  1699. }
  1700. get type() {
  1701. return this._type;
  1702. }
  1703. get localOffset() {
  1704. return this._localOffset;
  1705. }
  1706. set localOffset(value) {
  1707. this._localOffset = value;
  1708. if (this._compoundParent)
  1709. this._compoundParent._updateChildTransform(this);
  1710. }
  1711. get localRotation() {
  1712. return this._localRotation;
  1713. }
  1714. set localRotation(value) {
  1715. this._localRotation = value;
  1716. if (this._compoundParent)
  1717. this._compoundParent._updateChildTransform(this);
  1718. }
  1719. _setScale(value) {
  1720. if (this._compoundParent) {
  1721. this.updateLocalTransformations();
  1722. }
  1723. else {
  1724. var bt = ILaya3D.Physics3D._bullet;
  1725. bt.btVector3_setValue(ColliderShape._btScale, value.x, value.y, value.z);
  1726. bt.btCollisionShape_setLocalScaling(this._btShape, ColliderShape._btScale);
  1727. }
  1728. }
  1729. _addReference() {
  1730. this._referenceCount++;
  1731. }
  1732. _removeReference() {
  1733. this._referenceCount--;
  1734. }
  1735. updateLocalTransformations() {
  1736. if (this._compoundParent) {
  1737. var offset = ColliderShape._tempVector30;
  1738. Vector3.multiply(this.localOffset, this._scale, offset);
  1739. ColliderShape._createAffineTransformation(offset, this.localRotation, this._centerMatrix.elements);
  1740. }
  1741. else {
  1742. ColliderShape._createAffineTransformation(this.localOffset, this.localRotation, this._centerMatrix.elements);
  1743. }
  1744. }
  1745. cloneTo(destObject) {
  1746. var destColliderShape = destObject;
  1747. this._localOffset.cloneTo(destColliderShape.localOffset);
  1748. this._localRotation.cloneTo(destColliderShape.localRotation);
  1749. destColliderShape.localOffset = destColliderShape.localOffset;
  1750. destColliderShape.localRotation = destColliderShape.localRotation;
  1751. }
  1752. clone() {
  1753. return null;
  1754. }
  1755. destroy() {
  1756. if (this._btShape) {
  1757. ILaya3D.Physics3D._bullet.btCollisionShape_destroy(this._btShape);
  1758. this._btShape = null;
  1759. }
  1760. }
  1761. }
  1762. ColliderShape.SHAPEORIENTATION_UPX = 0;
  1763. ColliderShape.SHAPEORIENTATION_UPY = 1;
  1764. ColliderShape.SHAPEORIENTATION_UPZ = 2;
  1765. ColliderShape.SHAPETYPES_BOX = 0;
  1766. ColliderShape.SHAPETYPES_SPHERE = 1;
  1767. ColliderShape.SHAPETYPES_CYLINDER = 2;
  1768. ColliderShape.SHAPETYPES_CAPSULE = 3;
  1769. ColliderShape.SHAPETYPES_CONVEXHULL = 4;
  1770. ColliderShape.SHAPETYPES_COMPOUND = 5;
  1771. ColliderShape.SHAPETYPES_STATICPLANE = 6;
  1772. ColliderShape.SHAPETYPES_CONE = 7;
  1773. ColliderShape._tempVector30 = new Vector3();
  1774. class StaticPlaneColliderShape extends ColliderShape {
  1775. constructor(normal, offset) {
  1776. super();
  1777. this._normal = normal;
  1778. this._offset = offset;
  1779. this._type = ColliderShape.SHAPETYPES_STATICPLANE;
  1780. var bt = ILaya3D.Physics3D._bullet;
  1781. bt.btVector3_setValue(StaticPlaneColliderShape._btNormal, -normal.x, normal.y, normal.z);
  1782. this._btShape = bt.btStaticPlaneShape_create(StaticPlaneColliderShape._btNormal, offset);
  1783. }
  1784. static __init__() {
  1785. StaticPlaneColliderShape._btNormal = ILaya3D.Physics3D._bullet.btVector3_create(0, 0, 0);
  1786. }
  1787. clone() {
  1788. var dest = new StaticPlaneColliderShape(this._normal, this._offset);
  1789. this.cloneTo(dest);
  1790. return dest;
  1791. }
  1792. }
  1793. class CompoundColliderShape extends ColliderShape {
  1794. constructor() {
  1795. super();
  1796. this._childColliderShapes = [];
  1797. this._type = ColliderShape.SHAPETYPES_COMPOUND;
  1798. this._btShape = ILaya3D.Physics3D._bullet.btCompoundShape_create();
  1799. }
  1800. static __init__() {
  1801. var bt = ILaya3D.Physics3D._bullet;
  1802. CompoundColliderShape._btVector3One = bt.btVector3_create(1, 1, 1);
  1803. CompoundColliderShape._btTransform = bt.btTransform_create();
  1804. CompoundColliderShape._btOffset = bt.btVector3_create(0, 0, 0);
  1805. CompoundColliderShape._btRotation = bt.btQuaternion_create(0, 0, 0, 1);
  1806. }
  1807. _clearChildShape(shape) {
  1808. shape._attatched = false;
  1809. shape._compoundParent = null;
  1810. shape._indexInCompound = -1;
  1811. }
  1812. _addReference() {
  1813. }
  1814. _removeReference() {
  1815. }
  1816. _updateChildTransform(shape) {
  1817. var bt = ILaya3D.Physics3D._bullet;
  1818. var offset = shape.localOffset;
  1819. var rotation = shape.localRotation;
  1820. var btOffset = ColliderShape._btVector30;
  1821. var btQuaternion = ColliderShape._btQuaternion0;
  1822. var btTransform = ColliderShape._btTransform0;
  1823. bt.btVector3_setValue(btOffset, -offset.x, offset.y, offset.z);
  1824. bt.btQuaternion_setValue(btQuaternion, -rotation.x, rotation.y, rotation.z, -rotation.w);
  1825. bt.btTransform_setOrigin(btTransform, btOffset);
  1826. bt.btTransform_setRotation(btTransform, btQuaternion);
  1827. bt.btCompoundShape_updateChildTransform(this._btShape, shape._indexInCompound, btTransform, true);
  1828. }
  1829. addChildShape(shape) {
  1830. if (shape._attatched)
  1831. throw "CompoundColliderShape: this shape has attatched to other entity.";
  1832. shape._attatched = true;
  1833. shape._compoundParent = this;
  1834. shape._indexInCompound = this._childColliderShapes.length;
  1835. this._childColliderShapes.push(shape);
  1836. var offset = shape.localOffset;
  1837. var rotation = shape.localRotation;
  1838. var bt = ILaya3D.Physics3D._bullet;
  1839. bt.btVector3_setValue(CompoundColliderShape._btOffset, -offset.x, offset.y, offset.z);
  1840. bt.btQuaternion_setValue(CompoundColliderShape._btRotation, -rotation.x, rotation.y, rotation.z, -rotation.w);
  1841. bt.btTransform_setOrigin(CompoundColliderShape._btTransform, CompoundColliderShape._btOffset);
  1842. bt.btTransform_setRotation(CompoundColliderShape._btTransform, CompoundColliderShape._btRotation);
  1843. var btScale = bt.btCollisionShape_getLocalScaling(this._btShape);
  1844. bt.btCollisionShape_setLocalScaling(this._btShape, CompoundColliderShape._btVector3One);
  1845. bt.btCompoundShape_addChildShape(this._btShape, CompoundColliderShape._btTransform, shape._btShape);
  1846. bt.btCollisionShape_setLocalScaling(this._btShape, btScale);
  1847. (this._attatchedCollisionObject) && (this._attatchedCollisionObject.colliderShape = this);
  1848. }
  1849. removeChildShape(shape) {
  1850. if (shape._compoundParent === this) {
  1851. var index = shape._indexInCompound;
  1852. this._clearChildShape(shape);
  1853. var endShape = this._childColliderShapes[this._childColliderShapes.length - 1];
  1854. endShape._indexInCompound = index;
  1855. this._childColliderShapes[index] = endShape;
  1856. this._childColliderShapes.pop();
  1857. ILaya3D.Physics3D._bullet.btCompoundShape_removeChildShapeByIndex(this._btShape, index);
  1858. }
  1859. }
  1860. clearChildShape() {
  1861. for (var i = 0, n = this._childColliderShapes.length; i < n; i++) {
  1862. this._clearChildShape(this._childColliderShapes[i]);
  1863. ILaya3D.Physics3D._bullet.btCompoundShape_removeChildShapeByIndex(this._btShape, 0);
  1864. }
  1865. this._childColliderShapes.length = 0;
  1866. }
  1867. getChildShapeCount() {
  1868. return this._childColliderShapes.length;
  1869. }
  1870. cloneTo(destObject) {
  1871. var destCompoundColliderShape = destObject;
  1872. destCompoundColliderShape.clearChildShape();
  1873. for (var i = 0, n = this._childColliderShapes.length; i < n; i++)
  1874. destCompoundColliderShape.addChildShape(this._childColliderShapes[i].clone());
  1875. }
  1876. clone() {
  1877. var dest = new CompoundColliderShape();
  1878. this.cloneTo(dest);
  1879. return dest;
  1880. }
  1881. destroy() {
  1882. super.destroy();
  1883. for (var i = 0, n = this._childColliderShapes.length; i < n; i++) {
  1884. var childShape = this._childColliderShapes[i];
  1885. if (childShape._referenceCount === 0)
  1886. childShape.destroy();
  1887. }
  1888. }
  1889. }
  1890. class Transform3D extends Laya.EventDispatcher {
  1891. constructor(owner) {
  1892. super();
  1893. this._localPosition = new Vector3(0, 0, 0);
  1894. this._localRotation = new Quaternion(0, 0, 0, 1);
  1895. this._localScale = new Vector3(1, 1, 1);
  1896. this._localRotationEuler = new Vector3(0, 0, 0);
  1897. this._localMatrix = new Matrix4x4();
  1898. this._position = new Vector3(0, 0, 0);
  1899. this._rotation = new Quaternion(0, 0, 0, 1);
  1900. this._scale = new Vector3(1, 1, 1);
  1901. this._rotationEuler = new Vector3(0, 0, 0);
  1902. this._worldMatrix = new Matrix4x4();
  1903. this._children = null;
  1904. this._parent = null;
  1905. this._dummy = null;
  1906. this._transformFlag = 0;
  1907. this._owner = owner;
  1908. this._children = [];
  1909. this._setTransformFlag(Transform3D.TRANSFORM_LOCALQUATERNION | Transform3D.TRANSFORM_LOCALEULER | Transform3D.TRANSFORM_LOCALMATRIX, false);
  1910. this._setTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDEULER | Transform3D.TRANSFORM_WORLDSCALE | Transform3D.TRANSFORM_WORLDMATRIX, true);
  1911. }
  1912. get _isFrontFaceInvert() {
  1913. var scale = this.getWorldLossyScale();
  1914. var isInvert = scale.x < 0;
  1915. (scale.y < 0) && (isInvert = !isInvert);
  1916. (scale.z < 0) && (isInvert = !isInvert);
  1917. return isInvert;
  1918. }
  1919. get owner() {
  1920. return this._owner;
  1921. }
  1922. get worldNeedUpdate() {
  1923. return this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX);
  1924. }
  1925. get localPositionX() {
  1926. return this._localPosition.x;
  1927. }
  1928. set localPositionX(x) {
  1929. this._localPosition.x = x;
  1930. this.localPosition = this._localPosition;
  1931. }
  1932. get localPositionY() {
  1933. return this._localPosition.y;
  1934. }
  1935. set localPositionY(y) {
  1936. this._localPosition.y = y;
  1937. this.localPosition = this._localPosition;
  1938. }
  1939. get localPositionZ() {
  1940. return this._localPosition.z;
  1941. }
  1942. set localPositionZ(z) {
  1943. this._localPosition.z = z;
  1944. this.localPosition = this._localPosition;
  1945. }
  1946. get localPosition() {
  1947. return this._localPosition;
  1948. }
  1949. set localPosition(value) {
  1950. if (this._localPosition !== value)
  1951. value.cloneTo(this._localPosition);
  1952. this._setTransformFlag(Transform3D.TRANSFORM_LOCALMATRIX, true);
  1953. this._onWorldPositionTransform();
  1954. }
  1955. get localRotationX() {
  1956. return this.localRotation.x;
  1957. }
  1958. set localRotationX(x) {
  1959. this._localRotation.x = x;
  1960. this.localRotation = this._localRotation;
  1961. }
  1962. get localRotationY() {
  1963. return this.localRotation.y;
  1964. }
  1965. set localRotationY(y) {
  1966. this._localRotation.y = y;
  1967. this.localRotation = this._localRotation;
  1968. }
  1969. get localRotationZ() {
  1970. return this.localRotation.z;
  1971. }
  1972. set localRotationZ(z) {
  1973. this._localRotation.z = z;
  1974. this.localRotation = this._localRotation;
  1975. }
  1976. get localRotationW() {
  1977. return this.localRotation.w;
  1978. }
  1979. set localRotationW(w) {
  1980. this._localRotation.w = w;
  1981. this.localRotation = this._localRotation;
  1982. }
  1983. get localRotation() {
  1984. if (this._getTransformFlag(Transform3D.TRANSFORM_LOCALQUATERNION)) {
  1985. var eulerE = this._localRotationEuler;
  1986. Quaternion.createFromYawPitchRoll(eulerE.y / Transform3D._angleToRandin, eulerE.x / Transform3D._angleToRandin, eulerE.z / Transform3D._angleToRandin, this._localRotation);
  1987. this._setTransformFlag(Transform3D.TRANSFORM_LOCALQUATERNION, false);
  1988. }
  1989. return this._localRotation;
  1990. }
  1991. set localRotation(value) {
  1992. if (this._localRotation !== value)
  1993. value.cloneTo(this._localRotation);
  1994. this._localRotation.normalize(this._localRotation);
  1995. this._setTransformFlag(Transform3D.TRANSFORM_LOCALEULER | Transform3D.TRANSFORM_LOCALMATRIX, true);
  1996. this._setTransformFlag(Transform3D.TRANSFORM_LOCALQUATERNION, false);
  1997. this._onWorldRotationTransform();
  1998. }
  1999. get localScaleX() {
  2000. return this._localScale.x;
  2001. }
  2002. set localScaleX(value) {
  2003. this._localScale.x = value;
  2004. this.localScale = this._localScale;
  2005. }
  2006. get localScaleY() {
  2007. return this._localScale.y;
  2008. }
  2009. set localScaleY(value) {
  2010. this._localScale.y = value;
  2011. this.localScale = this._localScale;
  2012. }
  2013. get localScaleZ() {
  2014. return this._localScale.z;
  2015. }
  2016. set localScaleZ(value) {
  2017. this._localScale.z = value;
  2018. this.localScale = this._localScale;
  2019. }
  2020. get localScale() {
  2021. return this._localScale;
  2022. }
  2023. set localScale(value) {
  2024. if (this._localScale !== value)
  2025. value.cloneTo(this._localScale);
  2026. this._setTransformFlag(Transform3D.TRANSFORM_LOCALMATRIX, true);
  2027. this._onWorldScaleTransform();
  2028. }
  2029. get localRotationEulerX() {
  2030. return this.localRotationEuler.x;
  2031. }
  2032. set localRotationEulerX(value) {
  2033. this._localRotationEuler.x = value;
  2034. this.localRotationEuler = this._localRotationEuler;
  2035. }
  2036. get localRotationEulerY() {
  2037. return this.localRotationEuler.y;
  2038. }
  2039. set localRotationEulerY(value) {
  2040. this._localRotationEuler.y = value;
  2041. this.localRotationEuler = this._localRotationEuler;
  2042. }
  2043. get localRotationEulerZ() {
  2044. return this.localRotationEuler.z;
  2045. }
  2046. set localRotationEulerZ(value) {
  2047. this._localRotationEuler.z = value;
  2048. this.localRotationEuler = this._localRotationEuler;
  2049. }
  2050. get localRotationEuler() {
  2051. if (this._getTransformFlag(Transform3D.TRANSFORM_LOCALEULER)) {
  2052. this._localRotation.getYawPitchRoll(Transform3D._tempVector30);
  2053. var euler = Transform3D._tempVector30;
  2054. var localRotationEuler = this._localRotationEuler;
  2055. localRotationEuler.x = euler.y * Transform3D._angleToRandin;
  2056. localRotationEuler.y = euler.x * Transform3D._angleToRandin;
  2057. localRotationEuler.z = euler.z * Transform3D._angleToRandin;
  2058. this._setTransformFlag(Transform3D.TRANSFORM_LOCALEULER, false);
  2059. }
  2060. return this._localRotationEuler;
  2061. }
  2062. set localRotationEuler(value) {
  2063. if (this._localRotationEuler !== value)
  2064. value.cloneTo(this._localRotationEuler);
  2065. this._setTransformFlag(Transform3D.TRANSFORM_LOCALEULER, false);
  2066. this._setTransformFlag(Transform3D.TRANSFORM_LOCALQUATERNION | Transform3D.TRANSFORM_LOCALMATRIX, true);
  2067. this._onWorldRotationTransform();
  2068. }
  2069. get localMatrix() {
  2070. if (this._getTransformFlag(Transform3D.TRANSFORM_LOCALMATRIX)) {
  2071. Matrix4x4.createAffineTransformation(this._localPosition, this.localRotation, this._localScale, this._localMatrix);
  2072. this._setTransformFlag(Transform3D.TRANSFORM_LOCALMATRIX, false);
  2073. }
  2074. return this._localMatrix;
  2075. }
  2076. set localMatrix(value) {
  2077. if (this._localMatrix !== value)
  2078. value.cloneTo(this._localMatrix);
  2079. this._localMatrix.decomposeTransRotScale(this._localPosition, this._localRotation, this._localScale);
  2080. this._setTransformFlag(Transform3D.TRANSFORM_LOCALEULER, true);
  2081. this._setTransformFlag(Transform3D.TRANSFORM_LOCALMATRIX, false);
  2082. this._onWorldTransform();
  2083. }
  2084. get position() {
  2085. if (this._getTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION)) {
  2086. if (this._parent != null) {
  2087. var worldMatE = this.worldMatrix.elements;
  2088. this._position.x = worldMatE[12];
  2089. this._position.y = worldMatE[13];
  2090. this._position.z = worldMatE[14];
  2091. }
  2092. else {
  2093. this._localPosition.cloneTo(this._position);
  2094. }
  2095. this._setTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION, false);
  2096. }
  2097. return this._position;
  2098. }
  2099. set position(value) {
  2100. if (this._parent != null) {
  2101. var parentInvMat = Transform3D._tempMatrix0;
  2102. this._parent.worldMatrix.invert(parentInvMat);
  2103. Vector3.transformCoordinate(value, parentInvMat, this._localPosition);
  2104. }
  2105. else {
  2106. value.cloneTo(this._localPosition);
  2107. }
  2108. this.localPosition = this._localPosition;
  2109. if (this._position !== value)
  2110. value.cloneTo(this._position);
  2111. this._setTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION, false);
  2112. }
  2113. get rotation() {
  2114. if (this._getTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION)) {
  2115. if (this._parent != null)
  2116. Quaternion.multiply(this._parent.rotation, this.localRotation, this._rotation);
  2117. else
  2118. this.localRotation.cloneTo(this._rotation);
  2119. this._setTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION, false);
  2120. }
  2121. return this._rotation;
  2122. }
  2123. set rotation(value) {
  2124. if (this._parent != null) {
  2125. this._parent.rotation.invert(Transform3D._tempQuaternion0);
  2126. Quaternion.multiply(Transform3D._tempQuaternion0, value, this._localRotation);
  2127. }
  2128. else {
  2129. value.cloneTo(this._localRotation);
  2130. }
  2131. this.localRotation = this._localRotation;
  2132. if (value !== this._rotation)
  2133. value.cloneTo(this._rotation);
  2134. this._setTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION, false);
  2135. }
  2136. get rotationEuler() {
  2137. if (this._getTransformFlag(Transform3D.TRANSFORM_WORLDEULER)) {
  2138. this.rotation.getYawPitchRoll(Transform3D._tempVector30);
  2139. var eulerE = Transform3D._tempVector30;
  2140. var rotationEulerE = this._rotationEuler;
  2141. rotationEulerE.x = eulerE.y * Transform3D._angleToRandin;
  2142. rotationEulerE.y = eulerE.x * Transform3D._angleToRandin;
  2143. rotationEulerE.z = eulerE.z * Transform3D._angleToRandin;
  2144. this._setTransformFlag(Transform3D.TRANSFORM_WORLDEULER, false);
  2145. }
  2146. return this._rotationEuler;
  2147. }
  2148. set rotationEuler(value) {
  2149. Quaternion.createFromYawPitchRoll(value.y / Transform3D._angleToRandin, value.x / Transform3D._angleToRandin, value.z / Transform3D._angleToRandin, this._rotation);
  2150. this.rotation = this._rotation;
  2151. if (this._rotationEuler !== value)
  2152. value.cloneTo(this._rotationEuler);
  2153. this._setTransformFlag(Transform3D.TRANSFORM_WORLDEULER, false);
  2154. }
  2155. get worldMatrix() {
  2156. if (this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX)) {
  2157. if (this._parent != null)
  2158. Matrix4x4.multiply(this._parent.worldMatrix, this.localMatrix, this._worldMatrix);
  2159. else
  2160. this.localMatrix.cloneTo(this._worldMatrix);
  2161. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX, false);
  2162. }
  2163. return this._worldMatrix;
  2164. }
  2165. set worldMatrix(value) {
  2166. if (this._parent === null) {
  2167. value.cloneTo(this._localMatrix);
  2168. }
  2169. else {
  2170. this._parent.worldMatrix.invert(this._localMatrix);
  2171. Matrix4x4.multiply(this._localMatrix, value, this._localMatrix);
  2172. }
  2173. this.localMatrix = this._localMatrix;
  2174. if (this._worldMatrix !== value)
  2175. value.cloneTo(this._worldMatrix);
  2176. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX, false);
  2177. }
  2178. _getScaleMatrix() {
  2179. var invRotation = Transform3D._tempQuaternion0;
  2180. var invRotationMat = Transform3D._tempMatrix3x30;
  2181. var worldRotScaMat = Transform3D._tempMatrix3x31;
  2182. var scaMat = Transform3D._tempMatrix3x32;
  2183. Matrix3x3.createFromMatrix4x4(this.worldMatrix, worldRotScaMat);
  2184. this.rotation.invert(invRotation);
  2185. Matrix3x3.createRotationQuaternion(invRotation, invRotationMat);
  2186. Matrix3x3.multiply(invRotationMat, worldRotScaMat, scaMat);
  2187. return scaMat;
  2188. }
  2189. _setTransformFlag(type, value) {
  2190. if (value)
  2191. this._transformFlag |= type;
  2192. else
  2193. this._transformFlag &= ~type;
  2194. }
  2195. _getTransformFlag(type) {
  2196. return (this._transformFlag & type) != 0;
  2197. }
  2198. _setParent(value) {
  2199. if (this._parent !== value) {
  2200. if (this._parent) {
  2201. var parentChilds = this._parent._children;
  2202. var index = parentChilds.indexOf(this);
  2203. parentChilds.splice(index, 1);
  2204. }
  2205. if (value) {
  2206. value._children.push(this);
  2207. (value) && (this._onWorldTransform());
  2208. }
  2209. this._parent = value;
  2210. }
  2211. }
  2212. _onWorldPositionRotationTransform() {
  2213. if (!this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDEULER)) {
  2214. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDEULER, true);
  2215. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  2216. for (var i = 0, n = this._children.length; i < n; i++)
  2217. this._children[i]._onWorldPositionRotationTransform();
  2218. }
  2219. }
  2220. _onWorldPositionScaleTransform() {
  2221. if (!this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDSCALE)) {
  2222. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDSCALE, true);
  2223. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  2224. for (var i = 0, n = this._children.length; i < n; i++)
  2225. this._children[i]._onWorldPositionScaleTransform();
  2226. }
  2227. }
  2228. _onWorldPositionTransform() {
  2229. if (!this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION)) {
  2230. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDPOSITION, true);
  2231. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  2232. for (var i = 0, n = this._children.length; i < n; i++)
  2233. this._children[i]._onWorldPositionTransform();
  2234. }
  2235. }
  2236. _onWorldRotationTransform() {
  2237. if (!this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDEULER)) {
  2238. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDEULER, true);
  2239. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  2240. for (var i = 0, n = this._children.length; i < n; i++)
  2241. this._children[i]._onWorldPositionRotationTransform();
  2242. }
  2243. }
  2244. _onWorldScaleTransform() {
  2245. if (!this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDSCALE)) {
  2246. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDSCALE, true);
  2247. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  2248. for (var i = 0, n = this._children.length; i < n; i++)
  2249. this._children[i]._onWorldPositionScaleTransform();
  2250. }
  2251. }
  2252. _onWorldTransform() {
  2253. if (!this._getTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDEULER) || !this._getTransformFlag(Transform3D.TRANSFORM_WORLDSCALE)) {
  2254. this._setTransformFlag(Transform3D.TRANSFORM_WORLDMATRIX | Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDEULER | Transform3D.TRANSFORM_WORLDSCALE, true);
  2255. this.event(Laya.Event.TRANSFORM_CHANGED, this._transformFlag);
  2256. for (var i = 0, n = this._children.length; i < n; i++)
  2257. this._children[i]._onWorldTransform();
  2258. }
  2259. }
  2260. translate(translation, isLocal = true) {
  2261. if (isLocal) {
  2262. Matrix4x4.createFromQuaternion(this.localRotation, Transform3D._tempMatrix0);
  2263. Vector3.transformCoordinate(translation, Transform3D._tempMatrix0, Transform3D._tempVector30);
  2264. Vector3.add(this.localPosition, Transform3D._tempVector30, this._localPosition);
  2265. this.localPosition = this._localPosition;
  2266. }
  2267. else {
  2268. Vector3.add(this.position, translation, this._position);
  2269. this.position = this._position;
  2270. }
  2271. }
  2272. rotate(rotation, isLocal = true, isRadian = true) {
  2273. var rot;
  2274. if (isRadian) {
  2275. rot = rotation;
  2276. }
  2277. else {
  2278. Vector3.scale(rotation, Math.PI / 180.0, Transform3D._tempVector30);
  2279. rot = Transform3D._tempVector30;
  2280. }
  2281. Quaternion.createFromYawPitchRoll(rot.y, rot.x, rot.z, Transform3D._tempQuaternion0);
  2282. if (isLocal) {
  2283. Quaternion.multiply(this._localRotation, Transform3D._tempQuaternion0, this._localRotation);
  2284. this.localRotation = this._localRotation;
  2285. }
  2286. else {
  2287. Quaternion.multiply(Transform3D._tempQuaternion0, this.rotation, this._rotation);
  2288. this.rotation = this._rotation;
  2289. }
  2290. }
  2291. getForward(forward) {
  2292. var worldMatElem = this.worldMatrix.elements;
  2293. forward.x = -worldMatElem[8];
  2294. forward.y = -worldMatElem[9];
  2295. forward.z = -worldMatElem[10];
  2296. }
  2297. getUp(up) {
  2298. var worldMatElem = this.worldMatrix.elements;
  2299. up.x = worldMatElem[4];
  2300. up.y = worldMatElem[5];
  2301. up.z = worldMatElem[6];
  2302. }
  2303. getRight(right) {
  2304. var worldMatElem = this.worldMatrix.elements;
  2305. right.x = worldMatElem[0];
  2306. right.y = worldMatElem[1];
  2307. right.z = worldMatElem[2];
  2308. }
  2309. lookAt(target, up, isLocal = false) {
  2310. var eye;
  2311. if (isLocal) {
  2312. eye = this._localPosition;
  2313. if (Math.abs(eye.x - target.x) < MathUtils3D.zeroTolerance && Math.abs(eye.y - target.y) < MathUtils3D.zeroTolerance && Math.abs(eye.z - target.z) < MathUtils3D.zeroTolerance)
  2314. return;
  2315. Quaternion.lookAt(this._localPosition, target, up, this._localRotation);
  2316. this._localRotation.invert(this._localRotation);
  2317. this.localRotation = this._localRotation;
  2318. }
  2319. else {
  2320. var worldPosition = this.position;
  2321. eye = worldPosition;
  2322. if (Math.abs(eye.x - target.x) < MathUtils3D.zeroTolerance && Math.abs(eye.y - target.y) < MathUtils3D.zeroTolerance && Math.abs(eye.z - target.z) < MathUtils3D.zeroTolerance)
  2323. return;
  2324. Quaternion.lookAt(worldPosition, target, up, this._rotation);
  2325. this._rotation.invert(this._rotation);
  2326. this.rotation = this._rotation;
  2327. }
  2328. }
  2329. getWorldLossyScale() {
  2330. if (this._getTransformFlag(Transform3D.TRANSFORM_WORLDSCALE)) {
  2331. if (this._parent !== null) {
  2332. var scaMatE = this._getScaleMatrix().elements;
  2333. this._scale.x = scaMatE[0];
  2334. this._scale.y = scaMatE[4];
  2335. this._scale.z = scaMatE[8];
  2336. }
  2337. else {
  2338. this._localScale.cloneTo(this._scale);
  2339. }
  2340. this._setTransformFlag(Transform3D.TRANSFORM_WORLDSCALE, false);
  2341. }
  2342. return this._scale;
  2343. }
  2344. setWorldLossyScale(value) {
  2345. if (this._parent !== null) {
  2346. var scaleMat = Transform3D._tempMatrix3x33;
  2347. var localScaleMat = Transform3D._tempMatrix3x33;
  2348. var localScaleMatE = localScaleMat.elements;
  2349. var parInvScaleMat = this._parent._getScaleMatrix();
  2350. parInvScaleMat.invert(parInvScaleMat);
  2351. Matrix3x3.createFromScaling(value, scaleMat);
  2352. Matrix3x3.multiply(parInvScaleMat, scaleMat, localScaleMat);
  2353. this._localScale.x = localScaleMatE[0];
  2354. this._localScale.y = localScaleMatE[4];
  2355. this._localScale.z = localScaleMatE[8];
  2356. }
  2357. else {
  2358. value.cloneTo(this._localScale);
  2359. }
  2360. this.localScale = this._localScale;
  2361. if (this._scale !== value)
  2362. value.cloneTo(this._scale);
  2363. this._setTransformFlag(Transform3D.TRANSFORM_WORLDSCALE, false);
  2364. }
  2365. get scale() {
  2366. console.warn("Transfrm3D: discard function,please use getWorldLossyScale instead.");
  2367. return this.getWorldLossyScale();
  2368. }
  2369. set scale(value) {
  2370. console.warn("Transfrm3D: discard function,please use setWorldLossyScale instead.");
  2371. this.setWorldLossyScale(value);
  2372. }
  2373. }
  2374. Transform3D._tempVector30 = new Vector3();
  2375. Transform3D._tempQuaternion0 = new Quaternion();
  2376. Transform3D._tempMatrix0 = new Matrix4x4();
  2377. Transform3D._tempMatrix3x30 = new Matrix3x3();
  2378. Transform3D._tempMatrix3x31 = new Matrix3x3();
  2379. Transform3D._tempMatrix3x32 = new Matrix3x3();
  2380. Transform3D._tempMatrix3x33 = new Matrix3x3();
  2381. Transform3D.TRANSFORM_LOCALQUATERNION = 0x01;
  2382. Transform3D.TRANSFORM_LOCALEULER = 0x02;
  2383. Transform3D.TRANSFORM_LOCALMATRIX = 0x04;
  2384. Transform3D.TRANSFORM_WORLDPOSITION = 0x08;
  2385. Transform3D.TRANSFORM_WORLDQUATERNION = 0x10;
  2386. Transform3D.TRANSFORM_WORLDSCALE = 0x20;
  2387. Transform3D.TRANSFORM_WORLDMATRIX = 0x40;
  2388. Transform3D.TRANSFORM_WORLDEULER = 0x80;
  2389. Transform3D._angleToRandin = 180 / Math.PI;
  2390. class Physics3DUtils {
  2391. constructor() {
  2392. }
  2393. static setColliderCollision(collider1, collider2, collsion) {
  2394. }
  2395. static getIColliderCollision(collider1, collider2) {
  2396. return false;
  2397. }
  2398. }
  2399. Physics3DUtils.COLLISIONFILTERGROUP_DEFAULTFILTER = 0x1;
  2400. Physics3DUtils.COLLISIONFILTERGROUP_STATICFILTER = 0x2;
  2401. Physics3DUtils.COLLISIONFILTERGROUP_KINEMATICFILTER = 0x4;
  2402. Physics3DUtils.COLLISIONFILTERGROUP_DEBRISFILTER = 0x8;
  2403. Physics3DUtils.COLLISIONFILTERGROUP_SENSORTRIGGER = 0x10;
  2404. Physics3DUtils.COLLISIONFILTERGROUP_CHARACTERFILTER = 0x20;
  2405. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER1 = 0x40;
  2406. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER2 = 0x80;
  2407. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER3 = 0x100;
  2408. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER4 = 0x200;
  2409. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER5 = 0x400;
  2410. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER6 = 0x800;
  2411. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER7 = 0x1000;
  2412. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER8 = 0x2000;
  2413. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER9 = 0x4000;
  2414. Physics3DUtils.COLLISIONFILTERGROUP_CUSTOMFILTER10 = 0x8000;
  2415. Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER = -1;
  2416. Physics3DUtils.gravity = new Vector3(0, -9.81, 0);
  2417. class BoxColliderShape extends ColliderShape {
  2418. constructor(sizeX = 1.0, sizeY = 1.0, sizeZ = 1.0) {
  2419. super();
  2420. this._sizeX = sizeX;
  2421. this._sizeY = sizeY;
  2422. this._sizeZ = sizeZ;
  2423. this._type = ColliderShape.SHAPETYPES_BOX;
  2424. var bt = ILaya3D.Physics3D._bullet;
  2425. bt.btVector3_setValue(BoxColliderShape._btSize, sizeX / 2, sizeY / 2, sizeZ / 2);
  2426. this._btShape = bt.btBoxShape_create(BoxColliderShape._btSize);
  2427. }
  2428. static __init__() {
  2429. BoxColliderShape._btSize = ILaya3D.Physics3D._bullet.btVector3_create(0, 0, 0);
  2430. }
  2431. get sizeX() {
  2432. return this._sizeX;
  2433. }
  2434. get sizeY() {
  2435. return this._sizeY;
  2436. }
  2437. get sizeZ() {
  2438. return this._sizeZ;
  2439. }
  2440. clone() {
  2441. var dest = new BoxColliderShape(this._sizeX, this._sizeY, this._sizeZ);
  2442. this.cloneTo(dest);
  2443. return dest;
  2444. }
  2445. }
  2446. class CapsuleColliderShape extends ColliderShape {
  2447. constructor(radius = 0.5, length = 1.25, orientation = ColliderShape.SHAPEORIENTATION_UPY) {
  2448. super();
  2449. this._radius = radius;
  2450. this._length = length;
  2451. this._orientation = orientation;
  2452. this._type = ColliderShape.SHAPETYPES_CAPSULE;
  2453. var bt = ILaya3D.Physics3D._bullet;
  2454. switch (orientation) {
  2455. case ColliderShape.SHAPEORIENTATION_UPX:
  2456. this._btShape = bt.btCapsuleShapeX_create(radius, length - radius * 2);
  2457. break;
  2458. case ColliderShape.SHAPEORIENTATION_UPY:
  2459. this._btShape = bt.btCapsuleShape_create(radius, length - radius * 2);
  2460. break;
  2461. case ColliderShape.SHAPEORIENTATION_UPZ:
  2462. this._btShape = bt.btCapsuleShapeZ_create(radius, length - radius * 2);
  2463. break;
  2464. default:
  2465. throw "CapsuleColliderShape:unknown orientation.";
  2466. }
  2467. }
  2468. get radius() {
  2469. return this._radius;
  2470. }
  2471. get length() {
  2472. return this._length;
  2473. }
  2474. get orientation() {
  2475. return this._orientation;
  2476. }
  2477. _setScale(value) {
  2478. var fixScale = CapsuleColliderShape._tempVector30;
  2479. switch (this.orientation) {
  2480. case ColliderShape.SHAPEORIENTATION_UPX:
  2481. fixScale.x = value.x;
  2482. fixScale.y = fixScale.z = Math.max(value.y, value.z);
  2483. break;
  2484. case ColliderShape.SHAPEORIENTATION_UPY:
  2485. fixScale.y = value.y;
  2486. fixScale.x = fixScale.z = Math.max(value.x, value.z);
  2487. break;
  2488. case ColliderShape.SHAPEORIENTATION_UPZ:
  2489. fixScale.z = value.z;
  2490. fixScale.x = fixScale.y = Math.max(value.x, value.y);
  2491. break;
  2492. default:
  2493. throw "CapsuleColliderShape:unknown orientation.";
  2494. }
  2495. super._setScale(fixScale);
  2496. }
  2497. clone() {
  2498. var dest = new CapsuleColliderShape(this._radius, this._length, this._orientation);
  2499. this.cloneTo(dest);
  2500. return dest;
  2501. }
  2502. }
  2503. CapsuleColliderShape._tempVector30 = new Vector3();
  2504. class ConeColliderShape extends ColliderShape {
  2505. constructor(radius = 0.5, height = 1.0, orientation = ColliderShape.SHAPEORIENTATION_UPY) {
  2506. super();
  2507. this._radius = 1;
  2508. this._height = 0.5;
  2509. this._radius = radius;
  2510. this._height = height;
  2511. this._orientation = orientation;
  2512. this._type = ColliderShape.SHAPETYPES_CYLINDER;
  2513. var bt = ILaya3D.Physics3D._bullet;
  2514. switch (orientation) {
  2515. case ColliderShape.SHAPEORIENTATION_UPX:
  2516. this._btShape = bt.btConeShapeX_create(radius, height);
  2517. break;
  2518. case ColliderShape.SHAPEORIENTATION_UPY:
  2519. this._btShape = bt.btConeShape_create(radius, height);
  2520. break;
  2521. case ColliderShape.SHAPEORIENTATION_UPZ:
  2522. this._btShape = bt.btConeShapeZ_create(radius, height);
  2523. break;
  2524. default:
  2525. throw "ConeColliderShape:unknown orientation.";
  2526. }
  2527. }
  2528. get radius() {
  2529. return this._radius;
  2530. }
  2531. get height() {
  2532. return this._height;
  2533. }
  2534. get orientation() {
  2535. return this._orientation;
  2536. }
  2537. clone() {
  2538. var dest = new ConeColliderShape(this._radius, this._height, this._orientation);
  2539. this.cloneTo(dest);
  2540. return dest;
  2541. }
  2542. }
  2543. class CylinderColliderShape extends ColliderShape {
  2544. constructor(radius = 0.5, height = 1.0, orientation = ColliderShape.SHAPEORIENTATION_UPY) {
  2545. super();
  2546. this._radius = 1;
  2547. this._height = 0.5;
  2548. this._radius = radius;
  2549. this._height = height;
  2550. this._orientation = orientation;
  2551. this._type = ColliderShape.SHAPETYPES_CYLINDER;
  2552. var bt = ILaya3D.Physics3D._bullet;
  2553. switch (orientation) {
  2554. case ColliderShape.SHAPEORIENTATION_UPX:
  2555. bt.btVector3_setValue(CylinderColliderShape._btSize, height / 2, radius, radius);
  2556. this._btShape = bt.btCylinderShapeX_create(CylinderColliderShape._btSize);
  2557. break;
  2558. case ColliderShape.SHAPEORIENTATION_UPY:
  2559. bt.btVector3_setValue(CylinderColliderShape._btSize, radius, height / 2, radius);
  2560. this._btShape = bt.btCylinderShape_create(CylinderColliderShape._btSize);
  2561. break;
  2562. case ColliderShape.SHAPEORIENTATION_UPZ:
  2563. bt.btVector3_setValue(CylinderColliderShape._btSize, radius, radius, height / 2);
  2564. this._btShape = bt.btCylinderShapeZ_create(CylinderColliderShape._btSize);
  2565. break;
  2566. default:
  2567. throw "CapsuleColliderShape:unknown orientation.";
  2568. }
  2569. }
  2570. static __init__() {
  2571. CylinderColliderShape._btSize = ILaya3D.Physics3D._bullet.btVector3_create(0, 0, 0);
  2572. }
  2573. get radius() {
  2574. return this._radius;
  2575. }
  2576. get height() {
  2577. return this._height;
  2578. }
  2579. get orientation() {
  2580. return this._orientation;
  2581. }
  2582. clone() {
  2583. var dest = new CylinderColliderShape(this._radius, this._height, this._orientation);
  2584. this.cloneTo(dest);
  2585. return dest;
  2586. }
  2587. }
  2588. class MeshColliderShape extends ColliderShape {
  2589. constructor() {
  2590. super();
  2591. this._mesh = null;
  2592. this._convex = false;
  2593. }
  2594. get mesh() {
  2595. return this._mesh;
  2596. }
  2597. set mesh(value) {
  2598. if (this._mesh !== value) {
  2599. var bt = ILaya3D.Physics3D._bullet;
  2600. if (this._mesh) {
  2601. bt.btCollisionShape_destroy(this._btShape);
  2602. }
  2603. if (value) {
  2604. this._btShape = bt.btGImpactMeshShape_create(value._getPhysicMesh());
  2605. bt.btGImpactShapeInterface_updateBound(this._btShape);
  2606. }
  2607. this._mesh = value;
  2608. }
  2609. }
  2610. get convex() {
  2611. return this._convex;
  2612. }
  2613. set convex(value) {
  2614. this._convex = value;
  2615. }
  2616. _setScale(value) {
  2617. if (this._compoundParent) {
  2618. this.updateLocalTransformations();
  2619. }
  2620. else {
  2621. var bt = ILaya3D.Physics3D._bullet;
  2622. bt.btVector3_setValue(ColliderShape._btScale, value.x, value.y, value.z);
  2623. bt.btCollisionShape_setLocalScaling(this._btShape, ColliderShape._btScale);
  2624. bt.btGImpactShapeInterface_updateBound(this._btShape);
  2625. }
  2626. }
  2627. cloneTo(destObject) {
  2628. var destMeshCollider = destObject;
  2629. destMeshCollider.convex = this._convex;
  2630. destMeshCollider.mesh = this._mesh;
  2631. super.cloneTo(destObject);
  2632. }
  2633. clone() {
  2634. var dest = new MeshColliderShape();
  2635. this.cloneTo(dest);
  2636. return dest;
  2637. }
  2638. destroy() {
  2639. if (this._btShape) {
  2640. ILaya3D.Physics3D._bullet.btCollisionShape_destroy(this._btShape);
  2641. this._btShape = null;
  2642. }
  2643. }
  2644. }
  2645. class SphereColliderShape extends ColliderShape {
  2646. constructor(radius = 0.5) {
  2647. super();
  2648. this._radius = radius;
  2649. this._type = ColliderShape.SHAPETYPES_SPHERE;
  2650. this._btShape = ILaya3D.Physics3D._bullet.btSphereShape_create(radius);
  2651. }
  2652. get radius() {
  2653. return this._radius;
  2654. }
  2655. clone() {
  2656. var dest = new SphereColliderShape(this._radius);
  2657. this.cloneTo(dest);
  2658. return dest;
  2659. }
  2660. }
  2661. class PhysicsComponent extends Laya.Component {
  2662. constructor(collisionGroup, canCollideWith) {
  2663. super();
  2664. this._restitution = 0.0;
  2665. this._friction = 0.5;
  2666. this._rollingFriction = 0.0;
  2667. this._ccdMotionThreshold = 0.0;
  2668. this._ccdSweptSphereRadius = 0.0;
  2669. this._collisionGroup = Physics3DUtils.COLLISIONFILTERGROUP_DEFAULTFILTER;
  2670. this._canCollideWith = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER;
  2671. this._colliderShape = null;
  2672. this._transformFlag = 2147483647;
  2673. this._controlBySimulation = false;
  2674. this._enableProcessCollisions = true;
  2675. this._inPhysicUpdateListIndex = -1;
  2676. this.canScaleShape = true;
  2677. this._collisionGroup = collisionGroup;
  2678. this._canCollideWith = canCollideWith;
  2679. PhysicsComponent._physicObjectsMap[this.id] = this;
  2680. }
  2681. static __init__() {
  2682. var bt = ILaya3D.Physics3D._bullet;
  2683. PhysicsComponent._btVector30 = bt.btVector3_create(0, 0, 0);
  2684. PhysicsComponent._btQuaternion0 = bt.btQuaternion_create(0, 0, 0, 1);
  2685. }
  2686. static _createAffineTransformationArray(tranX, tranY, tranZ, rotX, rotY, rotZ, rotW, scale, outE) {
  2687. var x2 = rotX + rotX, y2 = rotY + rotY, z2 = rotZ + rotZ;
  2688. var xx = rotX * x2, xy = rotX * y2, xz = rotX * z2, yy = rotY * y2, yz = rotY * z2, zz = rotZ * z2;
  2689. var wx = rotW * x2, wy = rotW * y2, wz = rotW * z2, sx = scale[0], sy = scale[1], sz = scale[2];
  2690. outE[0] = (1 - (yy + zz)) * sx;
  2691. outE[1] = (xy + wz) * sx;
  2692. outE[2] = (xz - wy) * sx;
  2693. outE[3] = 0;
  2694. outE[4] = (xy - wz) * sy;
  2695. outE[5] = (1 - (xx + zz)) * sy;
  2696. outE[6] = (yz + wx) * sy;
  2697. outE[7] = 0;
  2698. outE[8] = (xz + wy) * sz;
  2699. outE[9] = (yz - wx) * sz;
  2700. outE[10] = (1 - (xx + yy)) * sz;
  2701. outE[11] = 0;
  2702. outE[12] = tranX;
  2703. outE[13] = tranY;
  2704. outE[14] = tranZ;
  2705. outE[15] = 1;
  2706. }
  2707. static _creatShape(shapeData) {
  2708. var colliderShape;
  2709. switch (shapeData.type) {
  2710. case "BoxColliderShape":
  2711. var sizeData = shapeData.size;
  2712. colliderShape = sizeData ? new BoxColliderShape(sizeData[0], sizeData[1], sizeData[2]) : new BoxColliderShape();
  2713. break;
  2714. case "SphereColliderShape":
  2715. colliderShape = new SphereColliderShape(shapeData.radius);
  2716. break;
  2717. case "CapsuleColliderShape":
  2718. colliderShape = new CapsuleColliderShape(shapeData.radius, shapeData.height, shapeData.orientation);
  2719. break;
  2720. case "MeshColliderShape":
  2721. var meshCollider = new MeshColliderShape();
  2722. shapeData.mesh && (meshCollider.mesh = Laya.Loader.getRes(shapeData.mesh));
  2723. colliderShape = meshCollider;
  2724. break;
  2725. case "ConeColliderShape":
  2726. colliderShape = new ConeColliderShape(shapeData.radius, shapeData.height, shapeData.orientation);
  2727. break;
  2728. case "CylinderColliderShape":
  2729. colliderShape = new CylinderColliderShape(shapeData.radius, shapeData.height, shapeData.orientation);
  2730. break;
  2731. default:
  2732. throw "unknown shape type.";
  2733. }
  2734. if (shapeData.center) {
  2735. var localOffset = colliderShape.localOffset;
  2736. localOffset.fromArray(shapeData.center);
  2737. colliderShape.localOffset = localOffset;
  2738. }
  2739. return colliderShape;
  2740. }
  2741. static physicVector3TransformQuat(source, qx, qy, qz, qw, out) {
  2742. var x = source.x, y = source.y, z = source.z, ix = qw * x + qy * z - qz * y, iy = qw * y + qz * x - qx * z, iz = qw * z + qx * y - qy * x, iw = -qx * x - qy * y - qz * z;
  2743. out.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2744. out.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2745. out.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2746. }
  2747. static physicQuaternionMultiply(lx, ly, lz, lw, right, out) {
  2748. var rx = right.x;
  2749. var ry = right.y;
  2750. var rz = right.z;
  2751. var rw = right.w;
  2752. var a = (ly * rz - lz * ry);
  2753. var b = (lz * rx - lx * rz);
  2754. var c = (lx * ry - ly * rx);
  2755. var d = (lx * rx + ly * ry + lz * rz);
  2756. out.x = (lx * rw + rx * lw) + a;
  2757. out.y = (ly * rw + ry * lw) + b;
  2758. out.z = (lz * rw + rz * lw) + c;
  2759. out.w = lw * rw - d;
  2760. }
  2761. get restitution() {
  2762. return this._restitution;
  2763. }
  2764. set restitution(value) {
  2765. this._restitution = value;
  2766. this._btColliderObject && ILaya3D.Physics3D._bullet.btCollisionObject_setRestitution(this._btColliderObject, value);
  2767. }
  2768. get friction() {
  2769. return this._friction;
  2770. }
  2771. set friction(value) {
  2772. this._friction = value;
  2773. this._btColliderObject && ILaya3D.Physics3D._bullet.btCollisionObject_setFriction(this._btColliderObject, value);
  2774. }
  2775. get rollingFriction() {
  2776. return this._rollingFriction;
  2777. }
  2778. set rollingFriction(value) {
  2779. this._rollingFriction = value;
  2780. this._btColliderObject && ILaya3D.Physics3D._bullet.btCollisionObject_setRollingFriction(this._btColliderObject, value);
  2781. }
  2782. get ccdMotionThreshold() {
  2783. return this._ccdMotionThreshold;
  2784. }
  2785. set ccdMotionThreshold(value) {
  2786. this._ccdMotionThreshold = value;
  2787. this._btColliderObject && ILaya3D.Physics3D._bullet.btCollisionObject_setCcdMotionThreshold(this._btColliderObject, value);
  2788. }
  2789. get ccdSweptSphereRadius() {
  2790. return this._ccdSweptSphereRadius;
  2791. }
  2792. set ccdSweptSphereRadius(value) {
  2793. this._ccdSweptSphereRadius = value;
  2794. this._btColliderObject && ILaya3D.Physics3D._bullet.btCollisionObject_setCcdSweptSphereRadius(this._btColliderObject, value);
  2795. }
  2796. get isActive() {
  2797. return this._btColliderObject ? ILaya3D.Physics3D._bullet.btCollisionObject_isActive(this._btColliderObject) : false;
  2798. }
  2799. get colliderShape() {
  2800. return this._colliderShape;
  2801. }
  2802. set colliderShape(value) {
  2803. var lastColliderShape = this._colliderShape;
  2804. if (lastColliderShape) {
  2805. lastColliderShape._attatched = false;
  2806. lastColliderShape._attatchedCollisionObject = null;
  2807. }
  2808. this._colliderShape = value;
  2809. if (value) {
  2810. if (value._attatched) {
  2811. throw "PhysicsComponent: this shape has attatched to other entity.";
  2812. }
  2813. else {
  2814. value._attatched = true;
  2815. value._attatchedCollisionObject = this;
  2816. }
  2817. if (this._btColliderObject) {
  2818. ILaya3D.Physics3D._bullet.btCollisionObject_setCollisionShape(this._btColliderObject, value._btShape);
  2819. var canInSimulation = this._simulation && this._enabled;
  2820. (canInSimulation && lastColliderShape) && (this._removeFromSimulation());
  2821. this._onShapeChange(value);
  2822. if (canInSimulation) {
  2823. this._derivePhysicsTransformation(true);
  2824. this._addToSimulation();
  2825. }
  2826. }
  2827. }
  2828. else {
  2829. if (this._simulation && this._enabled)
  2830. lastColliderShape && this._removeFromSimulation();
  2831. }
  2832. }
  2833. get simulation() {
  2834. return this._simulation;
  2835. }
  2836. get collisionGroup() {
  2837. return this._collisionGroup;
  2838. }
  2839. set collisionGroup(value) {
  2840. if (this._collisionGroup !== value) {
  2841. this._collisionGroup = value;
  2842. if (this._simulation && this._colliderShape && this._enabled) {
  2843. this._removeFromSimulation();
  2844. this._addToSimulation();
  2845. }
  2846. }
  2847. }
  2848. get canCollideWith() {
  2849. return this._canCollideWith;
  2850. }
  2851. set canCollideWith(value) {
  2852. if (this._canCollideWith !== value) {
  2853. this._canCollideWith = value;
  2854. if (this._simulation && this._colliderShape && this._enabled) {
  2855. this._removeFromSimulation();
  2856. this._addToSimulation();
  2857. }
  2858. }
  2859. }
  2860. _parseShape(shapesData) {
  2861. var shapeCount = shapesData.length;
  2862. if (shapeCount === 1) {
  2863. var shape = PhysicsComponent._creatShape(shapesData[0]);
  2864. this.colliderShape = shape;
  2865. }
  2866. else {
  2867. var compoundShape = new CompoundColliderShape();
  2868. for (var i = 0; i < shapeCount; i++) {
  2869. shape = PhysicsComponent._creatShape(shapesData[i]);
  2870. compoundShape.addChildShape(shape);
  2871. }
  2872. this.colliderShape = compoundShape;
  2873. }
  2874. }
  2875. _onScaleChange(scale) {
  2876. this._colliderShape._setScale(scale);
  2877. }
  2878. _onEnable() {
  2879. this._simulation = this.owner._scene.physicsSimulation;
  2880. ILaya3D.Physics3D._bullet.btCollisionObject_setContactProcessingThreshold(this._btColliderObject, 0);
  2881. if (this._colliderShape) {
  2882. this._derivePhysicsTransformation(true);
  2883. this._addToSimulation();
  2884. }
  2885. }
  2886. _onDisable() {
  2887. if (this._colliderShape) {
  2888. this._removeFromSimulation();
  2889. (this._inPhysicUpdateListIndex !== -1) && (this._simulation._physicsUpdateList.remove(this));
  2890. }
  2891. this._simulation = null;
  2892. }
  2893. _onDestroy() {
  2894. delete PhysicsComponent._physicObjectsMap[this.id];
  2895. ILaya3D.Physics3D._bullet.btCollisionObject_destroy(this._btColliderObject);
  2896. this._colliderShape.destroy();
  2897. super._onDestroy();
  2898. this._btColliderObject = null;
  2899. this._colliderShape = null;
  2900. this._simulation = null;
  2901. this.owner.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onTransformChanged);
  2902. }
  2903. _isValid() {
  2904. return this._simulation && this._colliderShape && this._enabled;
  2905. }
  2906. _parse(data) {
  2907. (data.collisionGroup != null) && (this.collisionGroup = data.collisionGroup);
  2908. (data.canCollideWith != null) && (this.canCollideWith = data.canCollideWith);
  2909. (data.ccdMotionThreshold != null) && (this.ccdMotionThreshold = data.ccdMotionThreshold);
  2910. (data.ccdSweptSphereRadius != null) && (this.ccdSweptSphereRadius = data.ccdSweptSphereRadius);
  2911. }
  2912. _setTransformFlag(type, value) {
  2913. if (value)
  2914. this._transformFlag |= type;
  2915. else
  2916. this._transformFlag &= ~type;
  2917. }
  2918. _getTransformFlag(type) {
  2919. return (this._transformFlag & type) != 0;
  2920. }
  2921. _addToSimulation() {
  2922. }
  2923. _removeFromSimulation() {
  2924. }
  2925. _derivePhysicsTransformation(force) {
  2926. var bt = ILaya3D.Physics3D._bullet;
  2927. var btColliderObject = this._btColliderObject;
  2928. var btTransform = bt.btCollisionObject_getWorldTransform(btColliderObject);
  2929. this._innerDerivePhysicsTransformation(btTransform, force);
  2930. bt.btCollisionObject_setWorldTransform(btColliderObject, btTransform);
  2931. }
  2932. _innerDerivePhysicsTransformation(physicTransformOut, force) {
  2933. var bt = ILaya3D.Physics3D._bullet;
  2934. var transform = this.owner._transform;
  2935. if (force || this._getTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION)) {
  2936. var shapeOffset = this._colliderShape.localOffset;
  2937. var position = transform.position;
  2938. var btPosition = PhysicsComponent._btVector30;
  2939. if (shapeOffset.x !== 0 || shapeOffset.y !== 0 || shapeOffset.z !== 0) {
  2940. var physicPosition = PhysicsComponent._tempVector30;
  2941. var worldMat = transform.worldMatrix;
  2942. Vector3.transformCoordinate(shapeOffset, worldMat, physicPosition);
  2943. bt.btVector3_setValue(btPosition, -physicPosition.x, physicPosition.y, physicPosition.z);
  2944. }
  2945. else {
  2946. bt.btVector3_setValue(btPosition, -position.x, position.y, position.z);
  2947. }
  2948. bt.btTransform_setOrigin(physicTransformOut, btPosition);
  2949. this._setTransformFlag(Transform3D.TRANSFORM_WORLDPOSITION, false);
  2950. }
  2951. if (force || this._getTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION)) {
  2952. var shapeRotation = this._colliderShape.localRotation;
  2953. var btRotation = PhysicsComponent._btQuaternion0;
  2954. var rotation = transform.rotation;
  2955. if (shapeRotation.x !== 0 || shapeRotation.y !== 0 || shapeRotation.z !== 0 || shapeRotation.w !== 1) {
  2956. var physicRotation = PhysicsComponent._tempQuaternion0;
  2957. PhysicsComponent.physicQuaternionMultiply(rotation.x, rotation.y, rotation.z, rotation.w, shapeRotation, physicRotation);
  2958. bt.btQuaternion_setValue(btRotation, -physicRotation.x, physicRotation.y, physicRotation.z, -physicRotation.w);
  2959. }
  2960. else {
  2961. bt.btQuaternion_setValue(btRotation, -rotation.x, rotation.y, rotation.z, -rotation.w);
  2962. }
  2963. bt.btTransform_setRotation(physicTransformOut, btRotation);
  2964. this._setTransformFlag(Transform3D.TRANSFORM_WORLDQUATERNION, false);
  2965. }
  2966. if (force || this._getTransformFlag(Transform3D.TRANSFORM_WORLDSCALE)) {
  2967. this._onScaleChange(transform.getWorldLossyScale());
  2968. this._setTransformFlag(Transform3D.TRANSFORM_WORLDSCALE, false);
  2969. }
  2970. }
  2971. _updateTransformComponent(physicsTransform) {
  2972. var bt = ILaya3D.Physics3D._bullet;
  2973. var colliderShape = this._colliderShape;
  2974. var localOffset = colliderShape.localOffset;
  2975. var localRotation = colliderShape.localRotation;
  2976. var transform = this.owner._transform;
  2977. var position = transform.position;
  2978. var rotation = transform.rotation;
  2979. var btPosition = bt.btTransform_getOrigin(physicsTransform);
  2980. var btRotation = bt.btTransform_getRotation(physicsTransform);
  2981. var btRotX = -bt.btQuaternion_x(btRotation);
  2982. var btRotY = bt.btQuaternion_y(btRotation);
  2983. var btRotZ = bt.btQuaternion_z(btRotation);
  2984. var btRotW = -bt.btQuaternion_w(btRotation);
  2985. if (localRotation.x !== 0 || localRotation.y !== 0 || localRotation.z !== 0 || localRotation.w !== 1) {
  2986. var invertShapeRotaion = PhysicsComponent._tempQuaternion0;
  2987. localRotation.invert(invertShapeRotaion);
  2988. PhysicsComponent.physicQuaternionMultiply(btRotX, btRotY, btRotZ, btRotW, invertShapeRotaion, rotation);
  2989. }
  2990. else {
  2991. rotation.x = btRotX;
  2992. rotation.y = btRotY;
  2993. rotation.z = btRotZ;
  2994. rotation.w = btRotW;
  2995. }
  2996. transform.rotation = rotation;
  2997. if (localOffset.x !== 0 || localOffset.y !== 0 || localOffset.z !== 0) {
  2998. var btScale = bt.btCollisionShape_getLocalScaling(colliderShape._btShape);
  2999. var rotShapePosition = PhysicsComponent._tempVector30;
  3000. rotShapePosition.x = localOffset.x * bt.btVector3_x(btScale);
  3001. rotShapePosition.y = localOffset.y * bt.btVector3_y(btScale);
  3002. rotShapePosition.z = localOffset.z * bt.btVector3_z(btScale);
  3003. Vector3.transformQuat(rotShapePosition, rotation, rotShapePosition);
  3004. position.x = -bt.btVector3_x(btPosition) - rotShapePosition.x;
  3005. position.y = bt.btVector3_y(btPosition) - rotShapePosition.y;
  3006. position.z = bt.btVector3_z(btPosition) - rotShapePosition.z;
  3007. }
  3008. else {
  3009. position.x = -bt.btVector3_x(btPosition);
  3010. position.y = bt.btVector3_y(btPosition);
  3011. position.z = bt.btVector3_z(btPosition);
  3012. }
  3013. transform.position = position;
  3014. }
  3015. _onShapeChange(colShape) {
  3016. var btColObj = this._btColliderObject;
  3017. var bt = ILaya3D.Physics3D._bullet;
  3018. var flags = bt.btCollisionObject_getCollisionFlags(btColObj);
  3019. if (colShape.needsCustomCollisionCallback) {
  3020. if ((flags & PhysicsComponent.COLLISIONFLAGS_CUSTOM_MATERIAL_CALLBACK) === 0)
  3021. bt.btCollisionObject_setCollisionFlags(btColObj, flags | PhysicsComponent.COLLISIONFLAGS_CUSTOM_MATERIAL_CALLBACK);
  3022. }
  3023. else {
  3024. if ((flags & PhysicsComponent.COLLISIONFLAGS_CUSTOM_MATERIAL_CALLBACK) > 0)
  3025. bt.btCollisionObject_setCollisionFlags(btColObj, flags ^ PhysicsComponent.COLLISIONFLAGS_CUSTOM_MATERIAL_CALLBACK);
  3026. }
  3027. }
  3028. _onAdded() {
  3029. this.enabled = this._enabled;
  3030. this.restitution = this._restitution;
  3031. this.friction = this._friction;
  3032. this.rollingFriction = this._rollingFriction;
  3033. this.ccdMotionThreshold = this._ccdMotionThreshold;
  3034. this.ccdSweptSphereRadius = this._ccdSweptSphereRadius;
  3035. this.owner.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onTransformChanged);
  3036. }
  3037. _onTransformChanged(flag) {
  3038. if (PhysicsComponent._addUpdateList || !this._controlBySimulation) {
  3039. flag &= Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDSCALE;
  3040. if (flag) {
  3041. this._transformFlag |= flag;
  3042. if (this._isValid() && this._inPhysicUpdateListIndex === -1)
  3043. this._simulation._physicsUpdateList.add(this);
  3044. }
  3045. }
  3046. }
  3047. _cloneTo(dest) {
  3048. var destPhysicsComponent = dest;
  3049. destPhysicsComponent.restitution = this._restitution;
  3050. destPhysicsComponent.friction = this._friction;
  3051. destPhysicsComponent.rollingFriction = this._rollingFriction;
  3052. destPhysicsComponent.ccdMotionThreshold = this._ccdMotionThreshold;
  3053. destPhysicsComponent.ccdSweptSphereRadius = this._ccdSweptSphereRadius;
  3054. destPhysicsComponent.collisionGroup = this._collisionGroup;
  3055. destPhysicsComponent.canCollideWith = this._canCollideWith;
  3056. destPhysicsComponent.canScaleShape = this.canScaleShape;
  3057. (this._colliderShape) && (destPhysicsComponent.colliderShape = this._colliderShape.clone());
  3058. }
  3059. }
  3060. PhysicsComponent.ACTIVATIONSTATE_ACTIVE_TAG = 1;
  3061. PhysicsComponent.ACTIVATIONSTATE_ISLAND_SLEEPING = 2;
  3062. PhysicsComponent.ACTIVATIONSTATE_WANTS_DEACTIVATION = 3;
  3063. PhysicsComponent.ACTIVATIONSTATE_DISABLE_DEACTIVATION = 4;
  3064. PhysicsComponent.ACTIVATIONSTATE_DISABLE_SIMULATION = 5;
  3065. PhysicsComponent.COLLISIONFLAGS_STATIC_OBJECT = 1;
  3066. PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT = 2;
  3067. PhysicsComponent.COLLISIONFLAGS_NO_CONTACT_RESPONSE = 4;
  3068. PhysicsComponent.COLLISIONFLAGS_CUSTOM_MATERIAL_CALLBACK = 8;
  3069. PhysicsComponent.COLLISIONFLAGS_CHARACTER_OBJECT = 16;
  3070. PhysicsComponent.COLLISIONFLAGS_DISABLE_VISUALIZE_OBJECT = 32;
  3071. PhysicsComponent.COLLISIONFLAGS_DISABLE_SPU_COLLISION_PROCESSING = 64;
  3072. PhysicsComponent._tempVector30 = new Vector3();
  3073. PhysicsComponent._tempQuaternion0 = new Quaternion();
  3074. PhysicsComponent._tempQuaternion1 = new Quaternion();
  3075. PhysicsComponent._tempMatrix4x40 = new Matrix4x4();
  3076. PhysicsComponent._physicObjectsMap = {};
  3077. PhysicsComponent._addUpdateList = true;
  3078. class SingletonList {
  3079. constructor() {
  3080. this.elements = [];
  3081. this.length = 0;
  3082. }
  3083. _add(element) {
  3084. if (this.length === this.elements.length)
  3085. this.elements.push(element);
  3086. else
  3087. this.elements[this.length] = element;
  3088. }
  3089. add(element) {
  3090. if (this.length === this.elements.length)
  3091. this.elements.push(element);
  3092. else
  3093. this.elements[this.length] = element;
  3094. this.length++;
  3095. }
  3096. }
  3097. class PhysicsUpdateList extends SingletonList {
  3098. constructor() {
  3099. super();
  3100. }
  3101. add(element) {
  3102. var index = element._inPhysicUpdateListIndex;
  3103. if (index !== -1)
  3104. throw "PhysicsUpdateList:element has in PhysicsUpdateList.";
  3105. this._add(element);
  3106. element._inPhysicUpdateListIndex = this.length++;
  3107. }
  3108. remove(element) {
  3109. var index = element._inPhysicUpdateListIndex;
  3110. this.length--;
  3111. if (index !== this.length) {
  3112. var end = this.elements[this.length];
  3113. this.elements[index] = end;
  3114. end._inPhysicUpdateListIndex = index;
  3115. }
  3116. element._inPhysicUpdateListIndex = -1;
  3117. }
  3118. }
  3119. class ContactPoint {
  3120. constructor() {
  3121. this._idCounter = 0;
  3122. this.colliderA = null;
  3123. this.colliderB = null;
  3124. this.distance = 0;
  3125. this.normal = new Vector3();
  3126. this.positionOnA = new Vector3();
  3127. this.positionOnB = new Vector3();
  3128. this._id = ++this._idCounter;
  3129. }
  3130. }
  3131. class HitResult {
  3132. constructor() {
  3133. this.succeeded = false;
  3134. this.collider = null;
  3135. this.point = new Vector3();
  3136. this.normal = new Vector3();
  3137. this.hitFraction = 0;
  3138. }
  3139. }
  3140. class Collision {
  3141. constructor() {
  3142. this._lastUpdateFrame = -2147483648;
  3143. this._updateFrame = -2147483648;
  3144. this._isTrigger = false;
  3145. this.contacts = [];
  3146. }
  3147. _setUpdateFrame(farme) {
  3148. this._lastUpdateFrame = this._updateFrame;
  3149. this._updateFrame = farme;
  3150. }
  3151. }
  3152. class CollisionTool {
  3153. constructor() {
  3154. this._hitResultsPoolIndex = 0;
  3155. this._hitResultsPool = [];
  3156. this._contactPonintsPoolIndex = 0;
  3157. this._contactPointsPool = [];
  3158. this._collisionsPool = [];
  3159. this._collisions = {};
  3160. }
  3161. getHitResult() {
  3162. var hitResult = this._hitResultsPool[this._hitResultsPoolIndex++];
  3163. if (!hitResult) {
  3164. hitResult = new HitResult();
  3165. this._hitResultsPool.push(hitResult);
  3166. }
  3167. return hitResult;
  3168. }
  3169. recoverAllHitResultsPool() {
  3170. this._hitResultsPoolIndex = 0;
  3171. }
  3172. getContactPoints() {
  3173. var contactPoint = this._contactPointsPool[this._contactPonintsPoolIndex++];
  3174. if (!contactPoint) {
  3175. contactPoint = new ContactPoint();
  3176. this._contactPointsPool.push(contactPoint);
  3177. }
  3178. return contactPoint;
  3179. }
  3180. recoverAllContactPointsPool() {
  3181. this._contactPonintsPoolIndex = 0;
  3182. }
  3183. getCollision(physicComponentA, physicComponentB) {
  3184. var collision;
  3185. var idA = physicComponentA.id;
  3186. var idB = physicComponentB.id;
  3187. var subCollisionFirst = this._collisions[idA];
  3188. if (subCollisionFirst)
  3189. collision = subCollisionFirst[idB];
  3190. if (!collision) {
  3191. if (!subCollisionFirst) {
  3192. subCollisionFirst = {};
  3193. this._collisions[idA] = subCollisionFirst;
  3194. }
  3195. collision = this._collisionsPool.length === 0 ? new Collision() : this._collisionsPool.pop();
  3196. collision._colliderA = physicComponentA;
  3197. collision._colliderB = physicComponentB;
  3198. subCollisionFirst[idB] = collision;
  3199. }
  3200. return collision;
  3201. }
  3202. recoverCollision(collision) {
  3203. var idA = collision._colliderA.id;
  3204. var idB = collision._colliderB.id;
  3205. this._collisions[idA][idB] = null;
  3206. this._collisionsPool.push(collision);
  3207. }
  3208. garbageCollection() {
  3209. this._hitResultsPoolIndex = 0;
  3210. this._hitResultsPool.length = 0;
  3211. this._contactPonintsPoolIndex = 0;
  3212. this._contactPointsPool.length = 0;
  3213. this._collisionsPool.length = 0;
  3214. for (var subCollisionsKey in this._collisionsPool) {
  3215. var subCollisions = this._collisionsPool[subCollisionsKey];
  3216. var wholeDelete = true;
  3217. for (var collisionKey in subCollisions) {
  3218. if (subCollisions[collisionKey])
  3219. wholeDelete = false;
  3220. else
  3221. delete subCollisions[collisionKey];
  3222. }
  3223. if (wholeDelete)
  3224. delete this._collisionsPool[subCollisionsKey];
  3225. }
  3226. }
  3227. }
  3228. class PhysicsSimulation {
  3229. constructor(configuration, flags = 0) {
  3230. this._gravity = new Vector3(0, -10, 0);
  3231. this._btVector3Zero = ILaya3D.Physics3D._bullet.btVector3_create(0, 0, 0);
  3232. this._btDefaultQuaternion = ILaya3D.Physics3D._bullet.btQuaternion_create(0, 0, 0, -1);
  3233. this._collisionsUtils = new CollisionTool();
  3234. this._previousFrameCollisions = [];
  3235. this._currentFrameCollisions = [];
  3236. this._currentConstraint = {};
  3237. this._physicsUpdateList = new PhysicsUpdateList();
  3238. this._characters = [];
  3239. this._updatedRigidbodies = 0;
  3240. this.maxSubSteps = 1;
  3241. this.fixedTimeStep = 1.0 / 60.0;
  3242. this.maxSubSteps = configuration.maxSubSteps;
  3243. this.fixedTimeStep = configuration.fixedTimeStep;
  3244. var bt = ILaya3D.Physics3D._bullet;
  3245. this._btCollisionConfiguration = bt.btDefaultCollisionConfiguration_create();
  3246. this._btDispatcher = bt.btCollisionDispatcher_create(this._btCollisionConfiguration);
  3247. this._btBroadphase = bt.btDbvtBroadphase_create();
  3248. bt.btOverlappingPairCache_setInternalGhostPairCallback(bt.btDbvtBroadphase_getOverlappingPairCache(this._btBroadphase), bt.btGhostPairCallback_create());
  3249. var conFlags = configuration.flags;
  3250. if (conFlags & PhysicsSimulation.PHYSICSENGINEFLAGS_COLLISIONSONLY) {
  3251. this._btCollisionWorld = new bt.btCollisionWorld(this._btDispatcher, this._btBroadphase, this._btCollisionConfiguration);
  3252. }
  3253. else if (conFlags & PhysicsSimulation.PHYSICSENGINEFLAGS_SOFTBODYSUPPORT) {
  3254. throw "PhysicsSimulation:SoftBody processing is not yet available";
  3255. }
  3256. else {
  3257. var solver = bt.btSequentialImpulseConstraintSolver_create();
  3258. this._btDiscreteDynamicsWorld = bt.btDiscreteDynamicsWorld_create(this._btDispatcher, this._btBroadphase, solver, this._btCollisionConfiguration);
  3259. this._btCollisionWorld = this._btDiscreteDynamicsWorld;
  3260. }
  3261. if (this._btDiscreteDynamicsWorld) {
  3262. this._btSolverInfo = bt.btDynamicsWorld_getSolverInfo(this._btDiscreteDynamicsWorld);
  3263. this._btDispatchInfo = bt.btCollisionWorld_getDispatchInfo(this._btDiscreteDynamicsWorld);
  3264. }
  3265. this._btClosestRayResultCallback = bt.ClosestRayResultCallback_create(this._btVector3Zero, this._btVector3Zero);
  3266. this._btAllHitsRayResultCallback = bt.AllHitsRayResultCallback_create(this._btVector3Zero, this._btVector3Zero);
  3267. this._btClosestConvexResultCallback = bt.ClosestConvexResultCallback_create(this._btVector3Zero, this._btVector3Zero);
  3268. this._btAllConvexResultCallback = bt.AllConvexResultCallback_create(this._btVector3Zero, this._btVector3Zero);
  3269. this.setHitsRayResultCallbackFlag();
  3270. bt.btGImpactCollisionAlgorithm_RegisterAlgorithm(this._btDispatcher);
  3271. }
  3272. static __init__() {
  3273. var bt = ILaya3D.Physics3D._bullet;
  3274. PhysicsSimulation._btTempVector30 = bt.btVector3_create(0, 0, 0);
  3275. PhysicsSimulation._btTempVector31 = bt.btVector3_create(0, 0, 0);
  3276. PhysicsSimulation._btTempQuaternion0 = bt.btQuaternion_create(0, 0, 0, 1);
  3277. PhysicsSimulation._btTempQuaternion1 = bt.btQuaternion_create(0, 0, 0, 1);
  3278. PhysicsSimulation._btTempTransform0 = bt.btTransform_create();
  3279. PhysicsSimulation._btTempTransform1 = bt.btTransform_create();
  3280. }
  3281. static createConstraint() {
  3282. }
  3283. get continuousCollisionDetection() {
  3284. return ILaya3D.Physics3D._bullet.btCollisionWorld_get_m_useContinuous(this._btDispatchInfo);
  3285. }
  3286. set continuousCollisionDetection(value) {
  3287. ILaya3D.Physics3D._bullet.btCollisionWorld_set_m_useContinuous(this._btDispatchInfo, value);
  3288. }
  3289. get gravity() {
  3290. if (!this._btDiscreteDynamicsWorld)
  3291. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  3292. return this._gravity;
  3293. }
  3294. set gravity(value) {
  3295. if (!this._btDiscreteDynamicsWorld)
  3296. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  3297. this._gravity = value;
  3298. var bt = ILaya3D.Physics3D._bullet;
  3299. var btGravity = PhysicsSimulation._btTempVector30;
  3300. bt.btVector3_setValue(btGravity, -value.x, value.y, value.z);
  3301. bt.btDiscreteDynamicsWorld_setGravity(this._btDiscreteDynamicsWorld, btGravity);
  3302. }
  3303. get speculativeContactRestitution() {
  3304. if (!this._btDiscreteDynamicsWorld)
  3305. throw "Simulation:Cannot Cannot perform this action when the physics engine is set to CollisionsOnly";
  3306. return ILaya3D.Physics3D._bullet.btDiscreteDynamicsWorld_getApplySpeculativeContactRestitution(this._btDiscreteDynamicsWorld);
  3307. }
  3308. set speculativeContactRestitution(value) {
  3309. if (!this._btDiscreteDynamicsWorld)
  3310. throw "Simulation:Cannot Cannot perform this action when the physics engine is set to CollisionsOnly";
  3311. ILaya3D.Physics3D._bullet.btDiscreteDynamicsWorld_setApplySpeculativeContactRestitution(this._btDiscreteDynamicsWorld, value);
  3312. }
  3313. _simulate(deltaTime) {
  3314. this._updatedRigidbodies = 0;
  3315. var bt = ILaya3D.Physics3D._bullet;
  3316. if (this._btDiscreteDynamicsWorld)
  3317. bt.btDiscreteDynamicsWorld_stepSimulation(this._btDiscreteDynamicsWorld, deltaTime, this.maxSubSteps, this.fixedTimeStep);
  3318. else
  3319. bt.PerformDiscreteCollisionDetection(this._btCollisionWorld);
  3320. }
  3321. _destroy() {
  3322. var bt = ILaya3D.Physics3D._bullet;
  3323. if (this._btDiscreteDynamicsWorld) {
  3324. bt.btCollisionWorld_destroy(this._btDiscreteDynamicsWorld);
  3325. this._btDiscreteDynamicsWorld = null;
  3326. }
  3327. else {
  3328. bt.btCollisionWorld_destroy(this._btCollisionWorld);
  3329. this._btCollisionWorld = null;
  3330. }
  3331. bt.btDbvtBroadphase_destroy(this._btBroadphase);
  3332. this._btBroadphase = null;
  3333. bt.btCollisionDispatcher_destroy(this._btDispatcher);
  3334. this._btDispatcher = null;
  3335. bt.btDefaultCollisionConfiguration_destroy(this._btCollisionConfiguration);
  3336. this._btCollisionConfiguration = null;
  3337. }
  3338. _addPhysicsCollider(component, group, mask) {
  3339. ILaya3D.Physics3D._bullet.btCollisionWorld_addCollisionObject(this._btCollisionWorld, component._btColliderObject, group, mask);
  3340. }
  3341. _removePhysicsCollider(component) {
  3342. ILaya3D.Physics3D._bullet.btCollisionWorld_removeCollisionObject(this._btCollisionWorld, component._btColliderObject);
  3343. }
  3344. _addRigidBody(rigidBody, group, mask) {
  3345. if (!this._btDiscreteDynamicsWorld)
  3346. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  3347. ILaya3D.Physics3D._bullet.btDiscreteDynamicsWorld_addRigidBody(this._btCollisionWorld, rigidBody._btColliderObject, group, mask);
  3348. }
  3349. _removeRigidBody(rigidBody) {
  3350. if (!this._btDiscreteDynamicsWorld)
  3351. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  3352. ILaya3D.Physics3D._bullet.btDiscreteDynamicsWorld_removeRigidBody(this._btCollisionWorld, rigidBody._btColliderObject);
  3353. }
  3354. _addCharacter(character, group, mask) {
  3355. if (!this._btDiscreteDynamicsWorld)
  3356. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  3357. var bt = ILaya3D.Physics3D._bullet;
  3358. bt.btCollisionWorld_addCollisionObject(this._btCollisionWorld, character._btColliderObject, group, mask);
  3359. bt.btDynamicsWorld_addAction(this._btCollisionWorld, character._btKinematicCharacter);
  3360. }
  3361. _removeCharacter(character) {
  3362. if (!this._btDiscreteDynamicsWorld)
  3363. throw "Simulation:Cannot perform this action when the physics engine is set to CollisionsOnly";
  3364. var bt = ILaya3D.Physics3D._bullet;
  3365. bt.btCollisionWorld_removeCollisionObject(this._btCollisionWorld, character._btColliderObject);
  3366. bt.btDynamicsWorld_removeAction(this._btCollisionWorld, character._btKinematicCharacter);
  3367. }
  3368. raycastFromTo(from, to, out = null, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  3369. var bt = ILaya3D.Physics3D._bullet;
  3370. var rayResultCall = this._btClosestRayResultCallback;
  3371. var rayFrom = PhysicsSimulation._btTempVector30;
  3372. var rayTo = PhysicsSimulation._btTempVector31;
  3373. bt.btVector3_setValue(rayFrom, -from.x, from.y, from.z);
  3374. bt.btVector3_setValue(rayTo, -to.x, to.y, to.z);
  3375. bt.ClosestRayResultCallback_set_m_rayFromWorld(rayResultCall, rayFrom);
  3376. bt.ClosestRayResultCallback_set_m_rayToWorld(rayResultCall, rayTo);
  3377. bt.RayResultCallback_set_m_collisionFilterGroup(rayResultCall, collisonGroup);
  3378. bt.RayResultCallback_set_m_collisionFilterMask(rayResultCall, collisionMask);
  3379. bt.RayResultCallback_set_m_collisionObject(rayResultCall, null);
  3380. bt.RayResultCallback_set_m_closestHitFraction(rayResultCall, 1);
  3381. bt.btCollisionWorld_rayTest(this._btCollisionWorld, rayFrom, rayTo, rayResultCall);
  3382. if (bt.RayResultCallback_hasHit(rayResultCall)) {
  3383. if (out) {
  3384. out.succeeded = true;
  3385. out.collider = PhysicsComponent._physicObjectsMap[bt.btCollisionObject_getUserIndex(bt.RayResultCallback_get_m_collisionObject(rayResultCall))];
  3386. out.hitFraction = bt.RayResultCallback_get_m_closestHitFraction(rayResultCall);
  3387. var btPoint = bt.ClosestRayResultCallback_get_m_hitPointWorld(rayResultCall);
  3388. var point = out.point;
  3389. point.x = -bt.btVector3_x(btPoint);
  3390. point.y = bt.btVector3_y(btPoint);
  3391. point.z = bt.btVector3_z(btPoint);
  3392. var btNormal = bt.ClosestRayResultCallback_get_m_hitNormalWorld(rayResultCall);
  3393. var normal = out.normal;
  3394. normal.x = -bt.btVector3_x(btNormal);
  3395. normal.y = bt.btVector3_y(btNormal);
  3396. normal.z = bt.btVector3_z(btNormal);
  3397. }
  3398. return true;
  3399. }
  3400. else {
  3401. if (out)
  3402. out.succeeded = false;
  3403. return false;
  3404. }
  3405. }
  3406. raycastAllFromTo(from, to, out, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  3407. var bt = ILaya3D.Physics3D._bullet;
  3408. var rayResultCall = this._btAllHitsRayResultCallback;
  3409. var rayFrom = PhysicsSimulation._btTempVector30;
  3410. var rayTo = PhysicsSimulation._btTempVector31;
  3411. out.length = 0;
  3412. bt.btVector3_setValue(rayFrom, -from.x, from.y, from.z);
  3413. bt.btVector3_setValue(rayTo, -to.x, to.y, to.z);
  3414. bt.AllHitsRayResultCallback_set_m_rayFromWorld(rayResultCall, rayFrom);
  3415. bt.AllHitsRayResultCallback_set_m_rayToWorld(rayResultCall, rayTo);
  3416. bt.RayResultCallback_set_m_collisionFilterGroup(rayResultCall, collisonGroup);
  3417. bt.RayResultCallback_set_m_collisionFilterMask(rayResultCall, collisionMask);
  3418. var collisionObjects = bt.AllHitsRayResultCallback_get_m_collisionObjects(rayResultCall);
  3419. var btPoints = bt.AllHitsRayResultCallback_get_m_hitPointWorld(rayResultCall);
  3420. var btNormals = bt.AllHitsRayResultCallback_get_m_hitNormalWorld(rayResultCall);
  3421. var btFractions = bt.AllHitsRayResultCallback_get_m_hitFractions(rayResultCall);
  3422. bt.tBtCollisionObjectArray_clear(collisionObjects);
  3423. bt.tVector3Array_clear(btPoints);
  3424. bt.tVector3Array_clear(btNormals);
  3425. bt.tScalarArray_clear(btFractions);
  3426. bt.btCollisionWorld_rayTest(this._btCollisionWorld, rayFrom, rayTo, rayResultCall);
  3427. var count = bt.tBtCollisionObjectArray_size(collisionObjects);
  3428. if (count > 0) {
  3429. this._collisionsUtils.recoverAllHitResultsPool();
  3430. for (var i = 0; i < count; i++) {
  3431. var hitResult = this._collisionsUtils.getHitResult();
  3432. out.push(hitResult);
  3433. hitResult.succeeded = true;
  3434. hitResult.collider = PhysicsComponent._physicObjectsMap[bt.btCollisionObject_getUserIndex(bt.tBtCollisionObjectArray_at(collisionObjects, i))];
  3435. hitResult.hitFraction = bt.tScalarArray_at(btFractions, i);
  3436. var btPoint = bt.tVector3Array_at(btPoints, i);
  3437. var pointE = hitResult.point;
  3438. pointE.x = -bt.btVector3_x(btPoint);
  3439. pointE.y = bt.btVector3_y(btPoint);
  3440. pointE.z = bt.btVector3_z(btPoint);
  3441. var btNormal = bt.tVector3Array_at(btNormals, i);
  3442. var normal = hitResult.normal;
  3443. normal.x = -bt.btVector3_x(btNormal);
  3444. normal.y = bt.btVector3_y(btNormal);
  3445. normal.z = bt.btVector3_z(btNormal);
  3446. }
  3447. return true;
  3448. }
  3449. else {
  3450. return false;
  3451. }
  3452. }
  3453. rayCast(ray, outHitResult = null, distance = 2147483647, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  3454. var from = ray.origin;
  3455. var to = PhysicsSimulation._tempVector30;
  3456. Vector3.normalize(ray.direction, to);
  3457. Vector3.scale(to, distance, to);
  3458. Vector3.add(from, to, to);
  3459. return this.raycastFromTo(from, to, outHitResult, collisonGroup, collisionMask);
  3460. }
  3461. rayCastAll(ray, out, distance = 2147483647, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  3462. var from = ray.origin;
  3463. var to = PhysicsSimulation._tempVector30;
  3464. Vector3.normalize(ray.direction, to);
  3465. Vector3.scale(to, distance, to);
  3466. Vector3.add(from, to, to);
  3467. return this.raycastAllFromTo(from, to, out, collisonGroup, collisionMask);
  3468. }
  3469. shapeCast(shape, fromPosition, toPosition, out = null, fromRotation = null, toRotation = null, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, allowedCcdPenetration = 0.0) {
  3470. var bt = ILaya3D.Physics3D._bullet;
  3471. var convexResultCall = this._btClosestConvexResultCallback;
  3472. var convexPosFrom = PhysicsSimulation._btTempVector30;
  3473. var convexPosTo = PhysicsSimulation._btTempVector31;
  3474. var convexRotFrom = PhysicsSimulation._btTempQuaternion0;
  3475. var convexRotTo = PhysicsSimulation._btTempQuaternion1;
  3476. var convexTransform = PhysicsSimulation._btTempTransform0;
  3477. var convexTransTo = PhysicsSimulation._btTempTransform1;
  3478. var sweepShape = shape._btShape;
  3479. bt.btVector3_setValue(convexPosFrom, -fromPosition.x, fromPosition.y, fromPosition.z);
  3480. bt.btVector3_setValue(convexPosTo, -toPosition.x, toPosition.y, toPosition.z);
  3481. bt.ConvexResultCallback_set_m_collisionFilterGroup(convexResultCall, collisonGroup);
  3482. bt.ConvexResultCallback_set_m_collisionFilterMask(convexResultCall, collisionMask);
  3483. bt.btTransform_setOrigin(convexTransform, convexPosFrom);
  3484. bt.btTransform_setOrigin(convexTransTo, convexPosTo);
  3485. if (fromRotation) {
  3486. bt.btQuaternion_setValue(convexRotFrom, -fromRotation.x, fromRotation.y, fromRotation.z, -fromRotation.w);
  3487. bt.btTransform_setRotation(convexTransform, convexRotFrom);
  3488. }
  3489. else {
  3490. bt.btTransform_setRotation(convexTransform, this._btDefaultQuaternion);
  3491. }
  3492. if (toRotation) {
  3493. bt.btQuaternion_setValue(convexRotTo, -toRotation.x, toRotation.y, toRotation.z, -toRotation.w);
  3494. bt.btTransform_setRotation(convexTransTo, convexRotTo);
  3495. }
  3496. else {
  3497. bt.btTransform_setRotation(convexTransTo, this._btDefaultQuaternion);
  3498. }
  3499. bt.ClosestConvexResultCallback_set_m_hitCollisionObject(convexResultCall, null);
  3500. bt.ConvexResultCallback_set_m_closestHitFraction(convexResultCall, 1);
  3501. bt.btCollisionWorld_convexSweepTest(this._btCollisionWorld, sweepShape, convexTransform, convexTransTo, convexResultCall, allowedCcdPenetration);
  3502. if (bt.ConvexResultCallback_hasHit(convexResultCall)) {
  3503. if (out) {
  3504. out.succeeded = true;
  3505. out.collider = PhysicsComponent._physicObjectsMap[bt.btCollisionObject_getUserIndex(bt.ClosestConvexResultCallback_get_m_hitCollisionObject(convexResultCall))];
  3506. out.hitFraction = bt.ConvexResultCallback_get_m_closestHitFraction(convexResultCall);
  3507. var btPoint = bt.ClosestConvexResultCallback_get_m_hitPointWorld(convexResultCall);
  3508. var btNormal = bt.ClosestConvexResultCallback_get_m_hitNormalWorld(convexResultCall);
  3509. var point = out.point;
  3510. var normal = out.normal;
  3511. point.x = -bt.btVector3_x(btPoint);
  3512. point.y = bt.btVector3_y(btPoint);
  3513. point.z = bt.btVector3_z(btPoint);
  3514. normal.x = -bt.btVector3_x(btNormal);
  3515. normal.y = bt.btVector3_y(btNormal);
  3516. normal.z = bt.btVector3_z(btNormal);
  3517. }
  3518. return true;
  3519. }
  3520. else {
  3521. if (out)
  3522. out.succeeded = false;
  3523. return false;
  3524. }
  3525. }
  3526. shapeCastAll(shape, fromPosition, toPosition, out, fromRotation = null, toRotation = null, collisonGroup = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, collisionMask = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER, allowedCcdPenetration = 0.0) {
  3527. var bt = ILaya3D.Physics3D._bullet;
  3528. var convexResultCall = this._btAllConvexResultCallback;
  3529. var convexPosFrom = PhysicsSimulation._btTempVector30;
  3530. var convexPosTo = PhysicsSimulation._btTempVector31;
  3531. var convexRotFrom = PhysicsSimulation._btTempQuaternion0;
  3532. var convexRotTo = PhysicsSimulation._btTempQuaternion1;
  3533. var convexTransform = PhysicsSimulation._btTempTransform0;
  3534. var convexTransTo = PhysicsSimulation._btTempTransform1;
  3535. var sweepShape = shape._btShape;
  3536. out.length = 0;
  3537. bt.btVector3_setValue(convexPosFrom, -fromPosition.x, fromPosition.y, fromPosition.z);
  3538. bt.btVector3_setValue(convexPosTo, -toPosition.x, toPosition.y, toPosition.z);
  3539. bt.ConvexResultCallback_set_m_collisionFilterGroup(convexResultCall, collisonGroup);
  3540. bt.ConvexResultCallback_set_m_collisionFilterMask(convexResultCall, collisionMask);
  3541. bt.btTransform_setOrigin(convexTransform, convexPosFrom);
  3542. bt.btTransform_setOrigin(convexTransTo, convexPosTo);
  3543. if (fromRotation) {
  3544. bt.btQuaternion_setValue(convexRotFrom, -fromRotation.x, fromRotation.y, fromRotation.z, -fromRotation.w);
  3545. bt.btTransform_setRotation(convexTransform, convexRotFrom);
  3546. }
  3547. else {
  3548. bt.btTransform_setRotation(convexTransform, this._btDefaultQuaternion);
  3549. }
  3550. if (toRotation) {
  3551. bt.btQuaternion_setValue(convexRotTo, -toRotation.x, toRotation.y, toRotation.z, -toRotation.w);
  3552. bt.btTransform_setRotation(convexTransTo, convexRotTo);
  3553. }
  3554. else {
  3555. bt.btTransform_setRotation(convexTransTo, this._btDefaultQuaternion);
  3556. }
  3557. var collisionObjects = bt.AllConvexResultCallback_get_m_collisionObjects(convexResultCall);
  3558. var btPoints = bt.AllConvexResultCallback_get_m_hitPointWorld(convexResultCall);
  3559. var btNormals = bt.AllConvexResultCallback_get_m_hitNormalWorld(convexResultCall);
  3560. var btFractions = bt.AllConvexResultCallback_get_m_hitFractions(convexResultCall);
  3561. bt.tVector3Array_clear(btPoints);
  3562. bt.tVector3Array_clear(btNormals);
  3563. bt.tScalarArray_clear(btFractions);
  3564. bt.tBtCollisionObjectArray_clear(collisionObjects);
  3565. bt.btCollisionWorld_convexSweepTest(this._btCollisionWorld, sweepShape, convexTransform, convexTransTo, convexResultCall, allowedCcdPenetration);
  3566. var count = bt.tBtCollisionObjectArray_size(collisionObjects);
  3567. if (count > 0) {
  3568. this._collisionsUtils.recoverAllHitResultsPool();
  3569. for (var i = 0; i < count; i++) {
  3570. var hitResult = this._collisionsUtils.getHitResult();
  3571. out.push(hitResult);
  3572. hitResult.succeeded = true;
  3573. hitResult.collider = PhysicsComponent._physicObjectsMap[bt.btCollisionObject_getUserIndex(bt.tBtCollisionObjectArray_at(collisionObjects, i))];
  3574. hitResult.hitFraction = bt.tScalarArray_at(btFractions, i);
  3575. var btPoint = bt.tVector3Array_at(btPoints, i);
  3576. var point = hitResult.point;
  3577. point.x = -bt.btVector3_x(btPoint);
  3578. point.y = bt.btVector3_y(btPoint);
  3579. point.z = bt.btVector3_z(btPoint);
  3580. var btNormal = bt.tVector3Array_at(btNormals, i);
  3581. var normal = hitResult.normal;
  3582. normal.x = -bt.btVector3_x(btNormal);
  3583. normal.y = bt.btVector3_y(btNormal);
  3584. normal.z = bt.btVector3_z(btNormal);
  3585. }
  3586. return true;
  3587. }
  3588. else {
  3589. return false;
  3590. }
  3591. }
  3592. addConstraint(constraint, disableCollisionsBetweenLinkedBodies = false) {
  3593. if (!this._btDiscreteDynamicsWorld)
  3594. throw "Cannot perform this action when the physics engine is set to CollisionsOnly";
  3595. ILaya3D.Physics3D._bullet.btCollisionWorld_addConstraint(this._btDiscreteDynamicsWorld, constraint._btConstraint, disableCollisionsBetweenLinkedBodies);
  3596. this._currentConstraint[constraint.id] = constraint;
  3597. }
  3598. removeConstraint(constraint) {
  3599. if (!this._btDiscreteDynamicsWorld)
  3600. throw "Cannot perform this action when the physics engine is set to CollisionsOnly";
  3601. ILaya3D.Physics3D._bullet.btCollisionWorld_removeConstraint(this._btDiscreteDynamicsWorld, constraint._btConstraint);
  3602. delete this._currentConstraint[constraint.id];
  3603. }
  3604. setHitsRayResultCallbackFlag(flag = 1) {
  3605. var bt = ILaya3D.Physics3D._bullet;
  3606. bt.RayResultCallback_set_m_flags(this._btAllHitsRayResultCallback, flag);
  3607. bt.RayResultCallback_set_m_flags(this._btClosestRayResultCallback, flag);
  3608. }
  3609. _updatePhysicsTransformFromRender() {
  3610. var elements = this._physicsUpdateList.elements;
  3611. for (var i = 0, n = this._physicsUpdateList.length; i < n; i++) {
  3612. var physicCollider = elements[i];
  3613. physicCollider._derivePhysicsTransformation(false);
  3614. physicCollider._inPhysicUpdateListIndex = -1;
  3615. }
  3616. this._physicsUpdateList.length = 0;
  3617. }
  3618. _updateCharacters() {
  3619. for (var i = 0, n = this._characters.length; i < n; i++) {
  3620. var character = this._characters[i];
  3621. character._updateTransformComponent(ILaya3D.Physics3D._bullet.btCollisionObject_getWorldTransform(character._btColliderObject));
  3622. }
  3623. }
  3624. _updateCollisions() {
  3625. this._collisionsUtils.recoverAllContactPointsPool();
  3626. var previous = this._currentFrameCollisions;
  3627. this._currentFrameCollisions = this._previousFrameCollisions;
  3628. this._currentFrameCollisions.length = 0;
  3629. this._previousFrameCollisions = previous;
  3630. var loopCount = Laya.Stat.loopCount;
  3631. var bt = ILaya3D.Physics3D._bullet;
  3632. var numManifolds = bt.btDispatcher_getNumManifolds(this._btDispatcher);
  3633. for (var i = 0; i < numManifolds; i++) {
  3634. var contactManifold = bt.btDispatcher_getManifoldByIndexInternal(this._btDispatcher, i);
  3635. var componentA = PhysicsComponent._physicObjectsMap[bt.btCollisionObject_getUserIndex(bt.btPersistentManifold_getBody0(contactManifold))];
  3636. var componentB = PhysicsComponent._physicObjectsMap[bt.btCollisionObject_getUserIndex(bt.btPersistentManifold_getBody1(contactManifold))];
  3637. var collision = null;
  3638. var isFirstCollision;
  3639. var contacts = null;
  3640. var isTrigger = componentA.isTrigger || componentB.isTrigger;
  3641. if (isTrigger && (componentA.owner._needProcessTriggers || componentB.owner._needProcessTriggers)) {
  3642. var numContacts = bt.btPersistentManifold_getNumContacts(contactManifold);
  3643. for (var j = 0; j < numContacts; j++) {
  3644. var pt = bt.btPersistentManifold_getContactPoint(contactManifold, j);
  3645. var distance = bt.btManifoldPoint_getDistance(pt);
  3646. if (distance <= 0) {
  3647. collision = this._collisionsUtils.getCollision(componentA, componentB);
  3648. contacts = collision.contacts;
  3649. isFirstCollision = collision._updateFrame !== loopCount;
  3650. if (isFirstCollision) {
  3651. collision._isTrigger = true;
  3652. contacts.length = 0;
  3653. }
  3654. break;
  3655. }
  3656. }
  3657. }
  3658. else if (componentA.owner._needProcessCollisions || componentB.owner._needProcessCollisions) {
  3659. if (componentA._enableProcessCollisions || componentB._enableProcessCollisions) {
  3660. numContacts = bt.btPersistentManifold_getNumContacts(contactManifold);
  3661. for (j = 0; j < numContacts; j++) {
  3662. pt = bt.btPersistentManifold_getContactPoint(contactManifold, j);
  3663. distance = bt.btManifoldPoint_getDistance(pt);
  3664. if (distance <= 0) {
  3665. var contactPoint = this._collisionsUtils.getContactPoints();
  3666. contactPoint.colliderA = componentA;
  3667. contactPoint.colliderB = componentB;
  3668. contactPoint.distance = distance;
  3669. var btNormal = bt.btManifoldPoint_get_m_normalWorldOnB(pt);
  3670. var normal = contactPoint.normal;
  3671. normal.x = -bt.btVector3_x(btNormal);
  3672. normal.y = bt.btVector3_y(btNormal);
  3673. normal.z = bt.btVector3_z(btNormal);
  3674. var btPostionA = bt.btManifoldPoint_get_m_positionWorldOnA(pt);
  3675. var positionOnA = contactPoint.positionOnA;
  3676. positionOnA.x = -bt.btVector3_x(btPostionA);
  3677. positionOnA.y = bt.btVector3_y(btPostionA);
  3678. positionOnA.z = bt.btVector3_z(btPostionA);
  3679. var btPostionB = bt.btManifoldPoint_get_m_positionWorldOnB(pt);
  3680. var positionOnB = contactPoint.positionOnB;
  3681. positionOnB.x = -bt.btVector3_x(btPostionB);
  3682. positionOnB.y = bt.btVector3_y(btPostionB);
  3683. positionOnB.z = bt.btVector3_z(btPostionB);
  3684. if (!collision) {
  3685. collision = this._collisionsUtils.getCollision(componentA, componentB);
  3686. contacts = collision.contacts;
  3687. isFirstCollision = collision._updateFrame !== loopCount;
  3688. if (isFirstCollision) {
  3689. collision._isTrigger = false;
  3690. contacts.length = 0;
  3691. }
  3692. }
  3693. contacts.push(contactPoint);
  3694. }
  3695. }
  3696. }
  3697. }
  3698. if (collision && isFirstCollision) {
  3699. this._currentFrameCollisions.push(collision);
  3700. collision._setUpdateFrame(loopCount);
  3701. }
  3702. }
  3703. }
  3704. _eventScripts() {
  3705. var loopCount = Laya.Stat.loopCount;
  3706. for (var i = 0, n = this._currentFrameCollisions.length; i < n; i++) {
  3707. var curFrameCol = this._currentFrameCollisions[i];
  3708. var colliderA = curFrameCol._colliderA;
  3709. var colliderB = curFrameCol._colliderB;
  3710. if (colliderA.destroyed || colliderB.destroyed)
  3711. continue;
  3712. if (loopCount - curFrameCol._lastUpdateFrame === 1) {
  3713. var ownerA = colliderA.owner;
  3714. var scriptsA = ownerA._scripts;
  3715. if (scriptsA) {
  3716. if (curFrameCol._isTrigger) {
  3717. if (ownerA._needProcessTriggers) {
  3718. for (var j = 0, m = scriptsA.length; j < m; j++)
  3719. scriptsA[j].onTriggerStay(colliderB);
  3720. }
  3721. }
  3722. else {
  3723. if (ownerA._needProcessCollisions) {
  3724. for (j = 0, m = scriptsA.length; j < m; j++) {
  3725. curFrameCol.other = colliderB;
  3726. scriptsA[j].onCollisionStay(curFrameCol);
  3727. }
  3728. }
  3729. }
  3730. }
  3731. var ownerB = colliderB.owner;
  3732. var scriptsB = ownerB._scripts;
  3733. if (scriptsB) {
  3734. if (curFrameCol._isTrigger) {
  3735. if (ownerB._needProcessTriggers) {
  3736. for (j = 0, m = scriptsB.length; j < m; j++)
  3737. scriptsB[j].onTriggerStay(colliderA);
  3738. }
  3739. }
  3740. else {
  3741. if (ownerB._needProcessCollisions) {
  3742. for (j = 0, m = scriptsB.length; j < m; j++) {
  3743. curFrameCol.other = colliderA;
  3744. scriptsB[j].onCollisionStay(curFrameCol);
  3745. }
  3746. }
  3747. }
  3748. }
  3749. }
  3750. else {
  3751. ownerA = colliderA.owner;
  3752. scriptsA = ownerA._scripts;
  3753. if (scriptsA) {
  3754. if (curFrameCol._isTrigger) {
  3755. if (ownerA._needProcessTriggers) {
  3756. for (j = 0, m = scriptsA.length; j < m; j++)
  3757. scriptsA[j].onTriggerEnter(colliderB);
  3758. }
  3759. }
  3760. else {
  3761. if (ownerA._needProcessCollisions) {
  3762. for (j = 0, m = scriptsA.length; j < m; j++) {
  3763. curFrameCol.other = colliderB;
  3764. scriptsA[j].onCollisionEnter(curFrameCol);
  3765. }
  3766. }
  3767. }
  3768. }
  3769. ownerB = colliderB.owner;
  3770. scriptsB = ownerB._scripts;
  3771. if (scriptsB) {
  3772. if (curFrameCol._isTrigger) {
  3773. if (ownerB._needProcessTriggers) {
  3774. for (j = 0, m = scriptsB.length; j < m; j++)
  3775. scriptsB[j].onTriggerEnter(colliderA);
  3776. }
  3777. }
  3778. else {
  3779. if (ownerB._needProcessCollisions) {
  3780. for (j = 0, m = scriptsB.length; j < m; j++) {
  3781. curFrameCol.other = colliderA;
  3782. scriptsB[j].onCollisionEnter(curFrameCol);
  3783. }
  3784. }
  3785. }
  3786. }
  3787. }
  3788. }
  3789. for (i = 0, n = this._previousFrameCollisions.length; i < n; i++) {
  3790. var preFrameCol = this._previousFrameCollisions[i];
  3791. var preColliderA = preFrameCol._colliderA;
  3792. var preColliderB = preFrameCol._colliderB;
  3793. if (preColliderA.destroyed || preColliderB.destroyed)
  3794. continue;
  3795. if (loopCount - preFrameCol._updateFrame === 1) {
  3796. this._collisionsUtils.recoverCollision(preFrameCol);
  3797. ownerA = preColliderA.owner;
  3798. scriptsA = ownerA._scripts;
  3799. if (scriptsA) {
  3800. if (preFrameCol._isTrigger) {
  3801. if (ownerA._needProcessTriggers) {
  3802. for (j = 0, m = scriptsA.length; j < m; j++)
  3803. scriptsA[j].onTriggerExit(preColliderB);
  3804. }
  3805. }
  3806. else {
  3807. if (ownerA._needProcessCollisions) {
  3808. for (j = 0, m = scriptsA.length; j < m; j++) {
  3809. preFrameCol.other = preColliderB;
  3810. scriptsA[j].onCollisionExit(preFrameCol);
  3811. }
  3812. }
  3813. }
  3814. }
  3815. ownerB = preColliderB.owner;
  3816. scriptsB = ownerB._scripts;
  3817. if (scriptsB) {
  3818. if (preFrameCol._isTrigger) {
  3819. if (ownerB._needProcessTriggers) {
  3820. for (j = 0, m = scriptsB.length; j < m; j++)
  3821. scriptsB[j].onTriggerExit(preColliderA);
  3822. }
  3823. }
  3824. else {
  3825. if (ownerB._needProcessCollisions) {
  3826. for (j = 0, m = scriptsB.length; j < m; j++) {
  3827. preFrameCol.other = preColliderA;
  3828. scriptsB[j].onCollisionExit(preFrameCol);
  3829. }
  3830. }
  3831. }
  3832. }
  3833. }
  3834. }
  3835. for (var id in this._currentConstraint) {
  3836. var constraintObj = this._currentConstraint[id];
  3837. var scripts = constraintObj.owner._scripts;
  3838. if (constraintObj.enabled && constraintObj._isBreakConstrained() && (!!scripts)) {
  3839. if (scripts.length != 0) {
  3840. for (i = 0, n = scripts.length; i < n; i++) {
  3841. scripts[i].onJointBreak();
  3842. }
  3843. }
  3844. }
  3845. }
  3846. }
  3847. clearForces() {
  3848. if (!this._btDiscreteDynamicsWorld)
  3849. throw "Cannot perform this action when the physics engine is set to CollisionsOnly";
  3850. ILaya3D.Physics3D._bullet.btDiscreteDynamicsWorld_clearForces(this._btDiscreteDynamicsWorld);
  3851. }
  3852. }
  3853. PhysicsSimulation.PHYSICSENGINEFLAGS_NONE = 0x0;
  3854. PhysicsSimulation.PHYSICSENGINEFLAGS_COLLISIONSONLY = 0x1;
  3855. PhysicsSimulation.PHYSICSENGINEFLAGS_SOFTBODYSUPPORT = 0x2;
  3856. PhysicsSimulation.PHYSICSENGINEFLAGS_MULTITHREADED = 0x4;
  3857. PhysicsSimulation.PHYSICSENGINEFLAGS_USEHARDWAREWHENPOSSIBLE = 0x8;
  3858. PhysicsSimulation.SOLVERMODE_RANDMIZE_ORDER = 1;
  3859. PhysicsSimulation.SOLVERMODE_FRICTION_SEPARATE = 2;
  3860. PhysicsSimulation.SOLVERMODE_USE_WARMSTARTING = 4;
  3861. PhysicsSimulation.SOLVERMODE_USE_2_FRICTION_DIRECTIONS = 16;
  3862. PhysicsSimulation.SOLVERMODE_ENABLE_FRICTION_DIRECTION_CACHING = 32;
  3863. PhysicsSimulation.SOLVERMODE_DISABLE_VELOCITY_DEPENDENT_FRICTION_DIRECTION = 64;
  3864. PhysicsSimulation.SOLVERMODE_CACHE_FRIENDLY = 128;
  3865. PhysicsSimulation.SOLVERMODE_SIMD = 256;
  3866. PhysicsSimulation.SOLVERMODE_INTERLEAVE_CONTACT_AND_FRICTION_CONSTRAINTS = 512;
  3867. PhysicsSimulation.SOLVERMODE_ALLOW_ZERO_LENGTH_FRICTION_DIRECTIONS = 1024;
  3868. PhysicsSimulation.HITSRAYRESULTCALLBACK_FLAG_NONE = 0;
  3869. PhysicsSimulation.HITSRAYRESULTCALLBACK_FLAG_FILTERBACKFACESS = 1;
  3870. PhysicsSimulation.HITSRAYRESULTCALLBACK_FLAG_KEEPUNFILIPPEDNORMAL = 2;
  3871. PhysicsSimulation.HITSRAYRESULTCALLBACK_FLAG_USESUBSIMPLEXCONVEXCASTRAYTEST = 4;
  3872. PhysicsSimulation.HITSRAYRESULTCALLBACK_FLAG_USEGJKCONVEXCASTRAYTEST = 8;
  3873. PhysicsSimulation.HITSRAYRESULTCALLBACK_FLAG_TERMINATOR = 0xffffffff;
  3874. PhysicsSimulation._tempVector30 = new Vector3();
  3875. PhysicsSimulation.disableSimulation = false;
  3876. class TextureGenerator {
  3877. constructor() {
  3878. }
  3879. static lightAttenTexture(x, y, maxX, maxY, index, data) {
  3880. var sqrRange = x / maxX;
  3881. var atten = 1.0 / (1.0 + 25.0 * sqrRange);
  3882. if (sqrRange >= 0.64) {
  3883. if (sqrRange > 1.0) {
  3884. atten = 0;
  3885. }
  3886. else {
  3887. atten *= 1 - (sqrRange - 0.64) / (1 - 0.64);
  3888. }
  3889. }
  3890. data[index] = Math.floor(atten * 255.0 + 0.5);
  3891. }
  3892. static haloTexture(x, y, maxX, maxY, index, data) {
  3893. maxX >>= 1;
  3894. maxY >>= 1;
  3895. var xFac = (x - maxX) / maxX;
  3896. var yFac = (y - maxY) / maxY;
  3897. var sqrRange = xFac * xFac + yFac * yFac;
  3898. if (sqrRange > 1.0) {
  3899. sqrRange = 1.0;
  3900. }
  3901. data[index] = Math.floor((1.0 - sqrRange) * 255.0 + 0.5);
  3902. }
  3903. static _generateTexture2D(texture, textureWidth, textureHeight, func) {
  3904. var index = 0;
  3905. var size = 0;
  3906. switch (texture.format) {
  3907. case Laya.TextureFormat.R8G8B8:
  3908. size = 3;
  3909. break;
  3910. case Laya.TextureFormat.R8G8B8A8:
  3911. size = 4;
  3912. break;
  3913. case Laya.TextureFormat.Alpha8:
  3914. size = 1;
  3915. break;
  3916. default:
  3917. throw "GeneratedTexture._generateTexture: unkonw texture format.";
  3918. }
  3919. var data = new Uint8Array(textureWidth * textureHeight * size);
  3920. for (var y = 0; y < textureHeight; y++) {
  3921. for (var x = 0; x < textureWidth; x++) {
  3922. func(x, y, textureWidth, textureHeight, index, data);
  3923. index += size;
  3924. }
  3925. }
  3926. texture.setPixels(data);
  3927. }
  3928. }
  3929. class Utils3D {
  3930. static _createFloatTextureBuffer(width, height) {
  3931. var floatTex = new Laya.Texture2D(width, height, Laya.TextureFormat.R32G32B32A32, false, false);
  3932. floatTex.filterMode = Laya.FilterMode.Point;
  3933. floatTex.wrapModeU = Laya.WarpMode.Clamp;
  3934. floatTex.wrapModeV = Laya.WarpMode.Clamp;
  3935. floatTex.anisoLevel = 0;
  3936. return floatTex;
  3937. }
  3938. static _convertToLayaVec3(bVector, out, inverseX) {
  3939. var bullet = ILaya3D.Physics3D._bullet;
  3940. out.x = inverseX ? -bullet.btVector3_x(bVector) : bullet.btVector3_x(bVector);
  3941. out.y = bullet.btVector3_y(bVector);
  3942. out.z = bullet.btVector3_z(bVector);
  3943. }
  3944. static _convertToBulletVec3(lVector, out, inverseX) {
  3945. ILaya3D.Physics3D._bullet.btVector3_setValue(out, inverseX ? -lVector.x : lVector.x, lVector.y, lVector.z);
  3946. }
  3947. static _rotationTransformScaleSkinAnimation(tx, ty, tz, qx, qy, qz, qw, sx, sy, sz, outArray, outOffset) {
  3948. var re = Utils3D._tempArray16_0;
  3949. var se = Utils3D._tempArray16_1;
  3950. var tse = Utils3D._tempArray16_2;
  3951. var x2 = qx + qx;
  3952. var y2 = qy + qy;
  3953. var z2 = qz + qz;
  3954. var xx = qx * x2;
  3955. var yx = qy * x2;
  3956. var yy = qy * y2;
  3957. var zx = qz * x2;
  3958. var zy = qz * y2;
  3959. var zz = qz * z2;
  3960. var wx = qw * x2;
  3961. var wy = qw * y2;
  3962. var wz = qw * z2;
  3963. re[15] = 1;
  3964. re[0] = 1 - yy - zz;
  3965. re[1] = yx + wz;
  3966. re[2] = zx - wy;
  3967. re[4] = yx - wz;
  3968. re[5] = 1 - xx - zz;
  3969. re[6] = zy + wx;
  3970. re[8] = zx + wy;
  3971. re[9] = zy - wx;
  3972. re[10] = 1 - xx - yy;
  3973. se[15] = 1;
  3974. se[0] = sx;
  3975. se[5] = sy;
  3976. se[10] = sz;
  3977. var i, ai0, ai1, ai2, ai3;
  3978. for (i = 0; i < 4; i++) {
  3979. ai0 = re[i];
  3980. ai1 = re[i + 4];
  3981. ai2 = re[i + 8];
  3982. ai3 = re[i + 12];
  3983. tse[i] = ai0;
  3984. tse[i + 4] = ai1;
  3985. tse[i + 8] = ai2;
  3986. tse[i + 12] = ai0 * tx + ai1 * ty + ai2 * tz + ai3;
  3987. }
  3988. for (i = 0; i < 4; i++) {
  3989. ai0 = tse[i];
  3990. ai1 = tse[i + 4];
  3991. ai2 = tse[i + 8];
  3992. ai3 = tse[i + 12];
  3993. outArray[i + outOffset] = ai0 * se[0] + ai1 * se[1] + ai2 * se[2] + ai3 * se[3];
  3994. outArray[i + outOffset + 4] = ai0 * se[4] + ai1 * se[5] + ai2 * se[6] + ai3 * se[7];
  3995. outArray[i + outOffset + 8] = ai0 * se[8] + ai1 * se[9] + ai2 * se[10] + ai3 * se[11];
  3996. outArray[i + outOffset + 12] = ai0 * se[12] + ai1 * se[13] + ai2 * se[14] + ai3 * se[15];
  3997. }
  3998. }
  3999. static _computeBoneAndAnimationDatasByBindPoseMatrxix(bones, curData, inverGlobalBindPose, outBonesDatas, outAnimationDatas, boneIndexToMesh) {
  4000. var offset = 0;
  4001. var matOffset = 0;
  4002. var i;
  4003. var parentOffset;
  4004. var boneLength = bones.length;
  4005. for (i = 0; i < boneLength; offset += bones[i].keyframeWidth, matOffset += 16, i++) {
  4006. Utils3D._rotationTransformScaleSkinAnimation(curData[offset + 0], curData[offset + 1], curData[offset + 2], curData[offset + 3], curData[offset + 4], curData[offset + 5], curData[offset + 6], curData[offset + 7], curData[offset + 8], curData[offset + 9], outBonesDatas, matOffset);
  4007. if (i != 0) {
  4008. parentOffset = bones[i].parentIndex * 16;
  4009. Utils3D.mulMatrixByArray(outBonesDatas, parentOffset, outBonesDatas, matOffset, outBonesDatas, matOffset);
  4010. }
  4011. }
  4012. var n = inverGlobalBindPose.length;
  4013. for (i = 0; i < n; i++) {
  4014. Utils3D.mulMatrixByArrayAndMatrixFast(outBonesDatas, boneIndexToMesh[i] * 16, inverGlobalBindPose[i], outAnimationDatas, i * 16);
  4015. }
  4016. }
  4017. static _computeAnimationDatasByArrayAndMatrixFast(inverGlobalBindPose, bonesDatas, outAnimationDatas, boneIndexToMesh) {
  4018. for (var i = 0, n = inverGlobalBindPose.length; i < n; i++)
  4019. Utils3D.mulMatrixByArrayAndMatrixFast(bonesDatas, boneIndexToMesh[i] * 16, inverGlobalBindPose[i], outAnimationDatas, i * 16);
  4020. }
  4021. static _computeBoneAndAnimationDatasByBindPoseMatrxixOld(bones, curData, inverGlobalBindPose, outBonesDatas, outAnimationDatas) {
  4022. var offset = 0;
  4023. var matOffset = 0;
  4024. var i;
  4025. var parentOffset;
  4026. var boneLength = bones.length;
  4027. for (i = 0; i < boneLength; offset += bones[i].keyframeWidth, matOffset += 16, i++) {
  4028. Utils3D._rotationTransformScaleSkinAnimation(curData[offset + 7], curData[offset + 8], curData[offset + 9], curData[offset + 3], curData[offset + 4], curData[offset + 5], curData[offset + 6], curData[offset + 0], curData[offset + 1], curData[offset + 2], outBonesDatas, matOffset);
  4029. if (i != 0) {
  4030. parentOffset = bones[i].parentIndex * 16;
  4031. Utils3D.mulMatrixByArray(outBonesDatas, parentOffset, outBonesDatas, matOffset, outBonesDatas, matOffset);
  4032. }
  4033. }
  4034. var n = inverGlobalBindPose.length;
  4035. for (i = 0; i < n; i++) {
  4036. var arrayOffset = i * 16;
  4037. Utils3D.mulMatrixByArrayAndMatrixFast(outBonesDatas, arrayOffset, inverGlobalBindPose[i], outAnimationDatas, arrayOffset);
  4038. }
  4039. }
  4040. static _computeAnimationDatasByArrayAndMatrixFastOld(inverGlobalBindPose, bonesDatas, outAnimationDatas) {
  4041. var n = inverGlobalBindPose.length;
  4042. for (var i = 0; i < n; i++) {
  4043. var arrayOffset = i * 16;
  4044. Utils3D.mulMatrixByArrayAndMatrixFast(bonesDatas, arrayOffset, inverGlobalBindPose[i], outAnimationDatas, arrayOffset);
  4045. }
  4046. }
  4047. static _computeRootAnimationData(bones, curData, animationDatas) {
  4048. for (var i = 0, offset = 0, matOffset = 0, boneLength = bones.length; i < boneLength; offset += bones[i].keyframeWidth, matOffset += 16, i++)
  4049. Utils3D.createAffineTransformationArray(curData[offset + 0], curData[offset + 1], curData[offset + 2], curData[offset + 3], curData[offset + 4], curData[offset + 5], curData[offset + 6], curData[offset + 7], curData[offset + 8], curData[offset + 9], animationDatas, matOffset);
  4050. }
  4051. static transformVector3ArrayByQuat(sourceArray, sourceOffset, rotation, outArray, outOffset) {
  4052. var x = sourceArray[sourceOffset], y = sourceArray[sourceOffset + 1], z = sourceArray[sourceOffset + 2], qx = rotation.x, qy = rotation.y, qz = rotation.z, qw = rotation.w, ix = qw * x + qy * z - qz * y, iy = qw * y + qz * x - qx * z, iz = qw * z + qx * y - qy * x, iw = -qx * x - qy * y - qz * z;
  4053. outArray[outOffset] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  4054. outArray[outOffset + 1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  4055. outArray[outOffset + 2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  4056. }
  4057. static mulMatrixByArray(leftArray, leftOffset, rightArray, rightOffset, outArray, outOffset) {
  4058. var i, ai0, ai1, ai2, ai3;
  4059. if (outArray === rightArray) {
  4060. rightArray = Utils3D._tempArray16_3;
  4061. for (i = 0; i < 16; ++i) {
  4062. rightArray[i] = outArray[outOffset + i];
  4063. }
  4064. rightOffset = 0;
  4065. }
  4066. for (i = 0; i < 4; i++) {
  4067. ai0 = leftArray[leftOffset + i];
  4068. ai1 = leftArray[leftOffset + i + 4];
  4069. ai2 = leftArray[leftOffset + i + 8];
  4070. ai3 = leftArray[leftOffset + i + 12];
  4071. outArray[outOffset + i] = ai0 * rightArray[rightOffset + 0] + ai1 * rightArray[rightOffset + 1] + ai2 * rightArray[rightOffset + 2] + ai3 * rightArray[rightOffset + 3];
  4072. outArray[outOffset + i + 4] = ai0 * rightArray[rightOffset + 4] + ai1 * rightArray[rightOffset + 5] + ai2 * rightArray[rightOffset + 6] + ai3 * rightArray[rightOffset + 7];
  4073. outArray[outOffset + i + 8] = ai0 * rightArray[rightOffset + 8] + ai1 * rightArray[rightOffset + 9] + ai2 * rightArray[rightOffset + 10] + ai3 * rightArray[rightOffset + 11];
  4074. outArray[outOffset + i + 12] = ai0 * rightArray[rightOffset + 12] + ai1 * rightArray[rightOffset + 13] + ai2 * rightArray[rightOffset + 14] + ai3 * rightArray[rightOffset + 15];
  4075. }
  4076. }
  4077. static mulMatrixByArrayFast(leftArray, leftOffset, rightArray, rightOffset, outArray, outOffset) {
  4078. var i, ai0, ai1, ai2, ai3;
  4079. for (i = 0; i < 4; i++) {
  4080. ai0 = leftArray[leftOffset + i];
  4081. ai1 = leftArray[leftOffset + i + 4];
  4082. ai2 = leftArray[leftOffset + i + 8];
  4083. ai3 = leftArray[leftOffset + i + 12];
  4084. outArray[outOffset + i] = ai0 * rightArray[rightOffset + 0] + ai1 * rightArray[rightOffset + 1] + ai2 * rightArray[rightOffset + 2] + ai3 * rightArray[rightOffset + 3];
  4085. outArray[outOffset + i + 4] = ai0 * rightArray[rightOffset + 4] + ai1 * rightArray[rightOffset + 5] + ai2 * rightArray[rightOffset + 6] + ai3 * rightArray[rightOffset + 7];
  4086. outArray[outOffset + i + 8] = ai0 * rightArray[rightOffset + 8] + ai1 * rightArray[rightOffset + 9] + ai2 * rightArray[rightOffset + 10] + ai3 * rightArray[rightOffset + 11];
  4087. outArray[outOffset + i + 12] = ai0 * rightArray[rightOffset + 12] + ai1 * rightArray[rightOffset + 13] + ai2 * rightArray[rightOffset + 14] + ai3 * rightArray[rightOffset + 15];
  4088. }
  4089. }
  4090. static mulMatrixByArrayAndMatrixFast(leftArray, leftOffset, rightMatrix, outArray, outOffset) {
  4091. var i, ai0, ai1, ai2, ai3;
  4092. var rightMatrixE = rightMatrix.elements;
  4093. var m11 = rightMatrixE[0], m12 = rightMatrixE[1], m13 = rightMatrixE[2], m14 = rightMatrixE[3];
  4094. var m21 = rightMatrixE[4], m22 = rightMatrixE[5], m23 = rightMatrixE[6], m24 = rightMatrixE[7];
  4095. var m31 = rightMatrixE[8], m32 = rightMatrixE[9], m33 = rightMatrixE[10], m34 = rightMatrixE[11];
  4096. var m41 = rightMatrixE[12], m42 = rightMatrixE[13], m43 = rightMatrixE[14], m44 = rightMatrixE[15];
  4097. var ai0LeftOffset = leftOffset;
  4098. var ai1LeftOffset = leftOffset + 4;
  4099. var ai2LeftOffset = leftOffset + 8;
  4100. var ai3LeftOffset = leftOffset + 12;
  4101. var ai0OutOffset = outOffset;
  4102. var ai1OutOffset = outOffset + 4;
  4103. var ai2OutOffset = outOffset + 8;
  4104. var ai3OutOffset = outOffset + 12;
  4105. for (i = 0; i < 4; i++) {
  4106. ai0 = leftArray[ai0LeftOffset + i];
  4107. ai1 = leftArray[ai1LeftOffset + i];
  4108. ai2 = leftArray[ai2LeftOffset + i];
  4109. ai3 = leftArray[ai3LeftOffset + i];
  4110. outArray[ai0OutOffset + i] = ai0 * m11 + ai1 * m12 + ai2 * m13 + ai3 * m14;
  4111. outArray[ai1OutOffset + i] = ai0 * m21 + ai1 * m22 + ai2 * m23 + ai3 * m24;
  4112. outArray[ai2OutOffset + i] = ai0 * m31 + ai1 * m32 + ai2 * m33 + ai3 * m34;
  4113. outArray[ai3OutOffset + i] = ai0 * m41 + ai1 * m42 + ai2 * m43 + ai3 * m44;
  4114. }
  4115. }
  4116. static createAffineTransformationArray(tX, tY, tZ, rX, rY, rZ, rW, sX, sY, sZ, outArray, outOffset) {
  4117. var x2 = rX + rX, y2 = rY + rY, z2 = rZ + rZ;
  4118. var xx = rX * x2, xy = rX * y2, xz = rX * z2, yy = rY * y2, yz = rY * z2, zz = rZ * z2;
  4119. var wx = rW * x2, wy = rW * y2, wz = rW * z2;
  4120. outArray[outOffset + 0] = (1 - (yy + zz)) * sX;
  4121. outArray[outOffset + 1] = (xy + wz) * sX;
  4122. outArray[outOffset + 2] = (xz - wy) * sX;
  4123. outArray[outOffset + 3] = 0;
  4124. outArray[outOffset + 4] = (xy - wz) * sY;
  4125. outArray[outOffset + 5] = (1 - (xx + zz)) * sY;
  4126. outArray[outOffset + 6] = (yz + wx) * sY;
  4127. outArray[outOffset + 7] = 0;
  4128. outArray[outOffset + 8] = (xz + wy) * sZ;
  4129. outArray[outOffset + 9] = (yz - wx) * sZ;
  4130. outArray[outOffset + 10] = (1 - (xx + yy)) * sZ;
  4131. outArray[outOffset + 11] = 0;
  4132. outArray[outOffset + 12] = tX;
  4133. outArray[outOffset + 13] = tY;
  4134. outArray[outOffset + 14] = tZ;
  4135. outArray[outOffset + 15] = 1;
  4136. }
  4137. static transformVector3ArrayToVector3ArrayCoordinate(source, sourceOffset, transform, result, resultOffset) {
  4138. var coordinateX = source[sourceOffset + 0];
  4139. var coordinateY = source[sourceOffset + 1];
  4140. var coordinateZ = source[sourceOffset + 2];
  4141. var transformElem = transform.elements;
  4142. var w = ((coordinateX * transformElem[3]) + (coordinateY * transformElem[7]) + (coordinateZ * transformElem[11]) + transformElem[15]);
  4143. result[resultOffset] = (coordinateX * transformElem[0]) + (coordinateY * transformElem[4]) + (coordinateZ * transformElem[8]) + transformElem[12] / w;
  4144. result[resultOffset + 1] = (coordinateX * transformElem[1]) + (coordinateY * transformElem[5]) + (coordinateZ * transformElem[9]) + transformElem[13] / w;
  4145. result[resultOffset + 2] = (coordinateX * transformElem[2]) + (coordinateY * transformElem[6]) + (coordinateZ * transformElem[10]) + transformElem[14] / w;
  4146. }
  4147. static transformVector3ArrayToVector3ArrayNormal(source, sourceOffset, transform, result, resultOffset) {
  4148. var coordinateX = source[sourceOffset + 0];
  4149. var coordinateY = source[sourceOffset + 1];
  4150. var coordinateZ = source[sourceOffset + 2];
  4151. var transformElem = transform.elements;
  4152. result[resultOffset] = coordinateX * transformElem[0] + coordinateY * transformElem[4] + coordinateZ * transformElem[8];
  4153. result[resultOffset + 1] = coordinateX * transformElem[1] + coordinateY * transformElem[5] + coordinateZ * transformElem[9];
  4154. result[resultOffset + 2] = coordinateX * transformElem[2] + coordinateY * transformElem[6] + coordinateZ * transformElem[10];
  4155. }
  4156. static transformLightingMapTexcoordArray(source, sourceOffset, lightingMapScaleOffset, result, resultOffset) {
  4157. result[resultOffset + 0] = source[sourceOffset + 0] * lightingMapScaleOffset.x + lightingMapScaleOffset.z;
  4158. result[resultOffset + 1] = 1.0 - ((1.0 - source[sourceOffset + 1]) * lightingMapScaleOffset.y + lightingMapScaleOffset.w);
  4159. }
  4160. static getURLVerion(url) {
  4161. var index = url.indexOf("?");
  4162. return index >= 0 ? url.substr(index) : null;
  4163. }
  4164. static _createAffineTransformationArray(trans, rot, scale, outE) {
  4165. var x = rot.x, y = rot.y, z = rot.z, w = rot.w, x2 = x + x, y2 = y + y, z2 = z + z;
  4166. var xx = x * x2, xy = x * y2, xz = x * z2, yy = y * y2, yz = y * z2, zz = z * z2;
  4167. var wx = w * x2, wy = w * y2, wz = w * z2, sx = scale.x, sy = scale.y, sz = scale.z;
  4168. outE[0] = (1 - (yy + zz)) * sx;
  4169. outE[1] = (xy + wz) * sx;
  4170. outE[2] = (xz - wy) * sx;
  4171. outE[3] = 0;
  4172. outE[4] = (xy - wz) * sy;
  4173. outE[5] = (1 - (xx + zz)) * sy;
  4174. outE[6] = (yz + wx) * sy;
  4175. outE[7] = 0;
  4176. outE[8] = (xz + wy) * sz;
  4177. outE[9] = (yz - wx) * sz;
  4178. outE[10] = (1 - (xx + yy)) * sz;
  4179. outE[11] = 0;
  4180. outE[12] = trans.x;
  4181. outE[13] = trans.y;
  4182. outE[14] = trans.z;
  4183. outE[15] = 1;
  4184. }
  4185. static _mulMatrixArray(left, right, rightOffset, outArray, outOffset) {
  4186. var l = right;
  4187. var r = left;
  4188. var e = outArray;
  4189. var l11 = l[rightOffset], l12 = l[rightOffset + 1], l13 = l[rightOffset + 2], l14 = l[rightOffset + 3];
  4190. var l21 = l[rightOffset + 4], l22 = l[rightOffset + 5], l23 = l[rightOffset + 6], l24 = l[rightOffset + 7];
  4191. var l31 = l[rightOffset + 8], l32 = l[rightOffset + 9], l33 = l[rightOffset + 10], l34 = l[rightOffset + 11];
  4192. var l41 = l[rightOffset + 12], l42 = l[rightOffset + 13], l43 = l[rightOffset + 14], l44 = l[rightOffset + 15];
  4193. var r11 = r[0], r12 = r[1], r13 = r[2], r14 = r[3];
  4194. var r21 = r[4], r22 = r[5], r23 = r[6], r24 = r[7];
  4195. var r31 = r[8], r32 = r[9], r33 = r[10], r34 = r[11];
  4196. var r41 = r[12], r42 = r[13], r43 = r[14], r44 = r[15];
  4197. e[outOffset] = (l11 * r11) + (l12 * r21) + (l13 * r31) + (l14 * r41);
  4198. e[outOffset + 1] = (l11 * r12) + (l12 * r22) + (l13 * r32) + (l14 * r42);
  4199. e[outOffset + 2] = (l11 * r13) + (l12 * r23) + (l13 * r33) + (l14 * r43);
  4200. e[outOffset + 3] = (l11 * r14) + (l12 * r24) + (l13 * r34) + (l14 * r44);
  4201. e[outOffset + 4] = (l21 * r11) + (l22 * r21) + (l23 * r31) + (l24 * r41);
  4202. e[outOffset + 5] = (l21 * r12) + (l22 * r22) + (l23 * r32) + (l24 * r42);
  4203. e[outOffset + 6] = (l21 * r13) + (l22 * r23) + (l23 * r33) + (l24 * r43);
  4204. e[outOffset + 7] = (l21 * r14) + (l22 * r24) + (l23 * r34) + (l24 * r44);
  4205. e[outOffset + 8] = (l31 * r11) + (l32 * r21) + (l33 * r31) + (l34 * r41);
  4206. e[outOffset + 9] = (l31 * r12) + (l32 * r22) + (l33 * r32) + (l34 * r42);
  4207. e[outOffset + 10] = (l31 * r13) + (l32 * r23) + (l33 * r33) + (l34 * r43);
  4208. e[outOffset + 11] = (l31 * r14) + (l32 * r24) + (l33 * r34) + (l34 * r44);
  4209. e[outOffset + 12] = (l41 * r11) + (l42 * r21) + (l43 * r31) + (l44 * r41);
  4210. e[outOffset + 13] = (l41 * r12) + (l42 * r22) + (l43 * r32) + (l44 * r42);
  4211. e[outOffset + 14] = (l41 * r13) + (l42 * r23) + (l43 * r33) + (l44 * r43);
  4212. e[outOffset + 15] = (l41 * r14) + (l42 * r24) + (l43 * r34) + (l44 * r44);
  4213. }
  4214. static arcTanAngle(x, y) {
  4215. if (x == 0) {
  4216. if (y == 1)
  4217. return Math.PI / 2;
  4218. return -Math.PI / 2;
  4219. }
  4220. if (x > 0)
  4221. return Math.atan(y / x);
  4222. if (x < 0) {
  4223. if (y > 0)
  4224. return Math.atan(y / x) + Math.PI;
  4225. return Math.atan(y / x) - Math.PI;
  4226. }
  4227. return 0;
  4228. }
  4229. static angleTo(from, location, angle) {
  4230. Vector3.subtract(location, from, Quaternion.TEMPVector30);
  4231. Vector3.normalize(Quaternion.TEMPVector30, Quaternion.TEMPVector30);
  4232. angle.x = Math.asin(Quaternion.TEMPVector30.y);
  4233. angle.y = Utils3D.arcTanAngle(-Quaternion.TEMPVector30.z, -Quaternion.TEMPVector30.x);
  4234. }
  4235. static transformQuat(source, rotation, out) {
  4236. var re = rotation;
  4237. var x = source.x, y = source.y, z = source.z, qx = re[0], qy = re[1], qz = re[2], qw = re[3], ix = qw * x + qy * z - qz * y, iy = qw * y + qz * x - qx * z, iz = qw * z + qx * y - qy * x, iw = -qx * x - qy * y - qz * z;
  4238. out.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  4239. out.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  4240. out.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  4241. }
  4242. static quaternionWeight(f, weight, e) {
  4243. e.x = f.x * weight;
  4244. e.y = f.y * weight;
  4245. e.z = f.z * weight;
  4246. e.w = f.w;
  4247. }
  4248. static quaternionConjugate(value, result) {
  4249. result.x = -value.x;
  4250. result.y = -value.y;
  4251. result.z = -value.z;
  4252. result.w = value.w;
  4253. }
  4254. static scaleWeight(s, w, out) {
  4255. var sX = s.x, sY = s.y, sZ = s.z;
  4256. out.x = sX > 0 ? Math.pow(Math.abs(sX), w) : -Math.pow(Math.abs(sX), w);
  4257. out.y = sY > 0 ? Math.pow(Math.abs(sY), w) : -Math.pow(Math.abs(sY), w);
  4258. out.z = sZ > 0 ? Math.pow(Math.abs(sZ), w) : -Math.pow(Math.abs(sZ), w);
  4259. }
  4260. static scaleBlend(sa, sb, w, out) {
  4261. var saw = Utils3D._tempVector3_0;
  4262. var sbw = Utils3D._tempVector3_1;
  4263. Utils3D.scaleWeight(sa, 1.0 - w, saw);
  4264. Utils3D.scaleWeight(sb, w, sbw);
  4265. var sng = w > 0.5 ? sb : sa;
  4266. out.x = sng.x > 0 ? Math.abs(saw.x * sbw.x) : -Math.abs(saw.x * sbw.x);
  4267. out.y = sng.y > 0 ? Math.abs(saw.y * sbw.y) : -Math.abs(saw.y * sbw.y);
  4268. out.z = sng.z > 0 ? Math.abs(saw.z * sbw.z) : -Math.abs(saw.z * sbw.z);
  4269. }
  4270. static matrix4x4MultiplyFFF(a, b, e) {
  4271. var i, ai0, ai1, ai2, ai3;
  4272. if (e === b) {
  4273. b = new Float32Array(16);
  4274. for (i = 0; i < 16; ++i) {
  4275. b[i] = e[i];
  4276. }
  4277. }
  4278. var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3];
  4279. var b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7];
  4280. var b8 = b[8], b9 = b[9], b10 = b[10], b11 = b[11];
  4281. var b12 = b[12], b13 = b[13], b14 = b[14], b15 = b[15];
  4282. for (i = 0; i < 4; i++) {
  4283. ai0 = a[i];
  4284. ai1 = a[i + 4];
  4285. ai2 = a[i + 8];
  4286. ai3 = a[i + 12];
  4287. e[i] = ai0 * b0 + ai1 * b1 + ai2 * b2 + ai3 * b3;
  4288. e[i + 4] = ai0 * b4 + ai1 * b5 + ai2 * b6 + ai3 * b7;
  4289. e[i + 8] = ai0 * b8 + ai1 * b9 + ai2 * b10 + ai3 * b11;
  4290. e[i + 12] = ai0 * b12 + ai1 * b13 + ai2 * b14 + ai3 * b15;
  4291. }
  4292. }
  4293. static matrix4x4MultiplyFFFForNative(a, b, e) {
  4294. Laya.LayaGL.instance.matrix4x4Multiply(a, b, e);
  4295. }
  4296. static matrix4x4MultiplyMFM(left, right, out) {
  4297. Utils3D.matrix4x4MultiplyFFF(left.elements, right, out.elements);
  4298. }
  4299. static _buildTexture2D(width, height, format, colorFunc, mipmaps = false) {
  4300. var texture = new Laya.Texture2D(width, height, format, mipmaps, true);
  4301. texture.anisoLevel = 1;
  4302. texture.filterMode = Laya.FilterMode.Point;
  4303. TextureGenerator._generateTexture2D(texture, width, height, colorFunc);
  4304. return texture;
  4305. }
  4306. static _drawBound(debugLine, boundBox, color) {
  4307. if (debugLine.lineCount + 12 > debugLine.maxLineCount)
  4308. debugLine.maxLineCount += 12;
  4309. var start = Utils3D._tempVector3_0;
  4310. var end = Utils3D._tempVector3_1;
  4311. var min = boundBox.min;
  4312. var max = boundBox.max;
  4313. start.setValue(min.x, min.y, min.z);
  4314. end.setValue(max.x, min.y, min.z);
  4315. debugLine.addLine(start, end, color, color);
  4316. start.setValue(min.x, min.y, min.z);
  4317. end.setValue(min.x, min.y, max.z);
  4318. debugLine.addLine(start, end, color, color);
  4319. start.setValue(max.x, min.y, min.z);
  4320. end.setValue(max.x, min.y, max.z);
  4321. debugLine.addLine(start, end, color, color);
  4322. start.setValue(min.x, min.y, max.z);
  4323. end.setValue(max.x, min.y, max.z);
  4324. debugLine.addLine(start, end, color, color);
  4325. start.setValue(min.x, min.y, min.z);
  4326. end.setValue(min.x, max.y, min.z);
  4327. debugLine.addLine(start, end, color, color);
  4328. start.setValue(min.x, min.y, max.z);
  4329. end.setValue(min.x, max.y, max.z);
  4330. debugLine.addLine(start, end, color, color);
  4331. start.setValue(max.x, min.y, min.z);
  4332. end.setValue(max.x, max.y, min.z);
  4333. debugLine.addLine(start, end, color, color);
  4334. start.setValue(max.x, min.y, max.z);
  4335. end.setValue(max.x, max.y, max.z);
  4336. debugLine.addLine(start, end, color, color);
  4337. start.setValue(min.x, max.y, min.z);
  4338. end.setValue(max.x, max.y, min.z);
  4339. debugLine.addLine(start, end, color, color);
  4340. start.setValue(min.x, max.y, min.z);
  4341. end.setValue(min.x, max.y, max.z);
  4342. debugLine.addLine(start, end, color, color);
  4343. start.setValue(max.x, max.y, min.z);
  4344. end.setValue(max.x, max.y, max.z);
  4345. debugLine.addLine(start, end, color, color);
  4346. start.setValue(min.x, max.y, max.z);
  4347. end.setValue(max.x, max.y, max.z);
  4348. debugLine.addLine(start, end, color, color);
  4349. }
  4350. static _getHierarchyPath(rootSprite, checkSprite, path) {
  4351. path.length = 0;
  4352. var sprite = checkSprite;
  4353. while (sprite !== rootSprite) {
  4354. var parent = sprite._parent;
  4355. if (parent)
  4356. path.push(parent.getChildIndex(sprite));
  4357. else
  4358. return null;
  4359. sprite = parent;
  4360. }
  4361. return path;
  4362. }
  4363. static _getNodeByHierarchyPath(rootSprite, invPath) {
  4364. var sprite = rootSprite;
  4365. for (var i = invPath.length - 1; i >= 0; i--) {
  4366. sprite = sprite.getChildAt(invPath[i]);
  4367. }
  4368. return sprite;
  4369. }
  4370. }
  4371. Utils3D._tempVector3_0 = new Vector3();
  4372. Utils3D._tempVector3_1 = new Vector3();
  4373. Utils3D._tempArray16_0 = new Float32Array(16);
  4374. Utils3D._tempArray16_1 = new Float32Array(16);
  4375. Utils3D._tempArray16_2 = new Float32Array(16);
  4376. Utils3D._tempArray16_3 = new Float32Array(16);
  4377. Utils3D._compIdToNode = new Object();
  4378. class CharacterController extends PhysicsComponent {
  4379. constructor(stepheight = 0.1, upAxis = null, collisionGroup = Physics3DUtils.COLLISIONFILTERGROUP_DEFAULTFILTER, canCollideWith = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  4380. super(collisionGroup, canCollideWith);
  4381. this._upAxis = new Vector3(0, 1, 0);
  4382. this._maxSlope = 45.0;
  4383. this._jumpSpeed = 10.0;
  4384. this._fallSpeed = 55.0;
  4385. this._gravity = new Vector3(0, -9.8 * 3, 0);
  4386. this._btKinematicCharacter = null;
  4387. this._stepHeight = stepheight;
  4388. (upAxis) && (this._upAxis = upAxis);
  4389. this._controlBySimulation = true;
  4390. }
  4391. static __init__() {
  4392. CharacterController._btTempVector30 = ILaya3D.Physics3D._bullet.btVector3_create(0, 0, 0);
  4393. }
  4394. get fallSpeed() {
  4395. return this._fallSpeed;
  4396. }
  4397. set fallSpeed(value) {
  4398. this._fallSpeed = value;
  4399. ILaya3D.Physics3D._bullet.btKinematicCharacterController_setFallSpeed(this._btKinematicCharacter, value);
  4400. }
  4401. get jumpSpeed() {
  4402. return this._jumpSpeed;
  4403. }
  4404. set jumpSpeed(value) {
  4405. this._jumpSpeed = value;
  4406. ILaya3D.Physics3D._bullet.btKinematicCharacterController_setJumpSpeed(this._btKinematicCharacter, value);
  4407. }
  4408. get gravity() {
  4409. return this._gravity;
  4410. }
  4411. set gravity(value) {
  4412. this._gravity = value;
  4413. var bt = ILaya3D.Physics3D._bullet;
  4414. var btGravity = CharacterController._btTempVector30;
  4415. bt.btVector3_setValue(btGravity, -value.x, value.y, value.z);
  4416. bt.btKinematicCharacterController_setGravity(this._btKinematicCharacter, btGravity);
  4417. }
  4418. get maxSlope() {
  4419. return this._maxSlope;
  4420. }
  4421. set maxSlope(value) {
  4422. this._maxSlope = value;
  4423. ILaya3D.Physics3D._bullet.btKinematicCharacterController_setMaxSlope(this._btKinematicCharacter, (value / 180) * Math.PI);
  4424. }
  4425. get isGrounded() {
  4426. return ILaya3D.Physics3D._bullet.btKinematicCharacterController_onGround(this._btKinematicCharacter);
  4427. }
  4428. get stepHeight() {
  4429. return this._stepHeight;
  4430. }
  4431. set stepHeight(value) {
  4432. this._stepHeight = value;
  4433. ILaya3D.Physics3D._bullet.btKinematicCharacterController_setStepHeight(this._btKinematicCharacter, value);
  4434. }
  4435. get upAxis() {
  4436. return this._upAxis;
  4437. }
  4438. set upAxis(value) {
  4439. this._upAxis = value;
  4440. var btUpAxis = CharacterController._btTempVector30;
  4441. Utils3D._convertToBulletVec3(value, btUpAxis, false);
  4442. ILaya3D.Physics3D._bullet.btKinematicCharacterController_setUp(this._btKinematicCharacter, btUpAxis);
  4443. }
  4444. _constructCharacter() {
  4445. var bt = ILaya3D.Physics3D._bullet;
  4446. if (this._btKinematicCharacter)
  4447. bt.btKinematicCharacterController_destroy(this._btKinematicCharacter);
  4448. var btUpAxis = CharacterController._btTempVector30;
  4449. bt.btVector3_setValue(btUpAxis, this._upAxis.x, this._upAxis.y, this._upAxis.z);
  4450. this._btKinematicCharacter = bt.btKinematicCharacterController_create(this._btColliderObject, this._colliderShape._btShape, this._stepHeight, btUpAxis);
  4451. this.fallSpeed = this._fallSpeed;
  4452. this.maxSlope = this._maxSlope;
  4453. this.jumpSpeed = this._jumpSpeed;
  4454. this.gravity = this._gravity;
  4455. }
  4456. _onShapeChange(colShape) {
  4457. super._onShapeChange(colShape);
  4458. this._constructCharacter();
  4459. }
  4460. _onAdded() {
  4461. var bt = ILaya3D.Physics3D._bullet;
  4462. var ghostObject = bt.btPairCachingGhostObject_create();
  4463. bt.btCollisionObject_setUserIndex(ghostObject, this.id);
  4464. bt.btCollisionObject_setCollisionFlags(ghostObject, PhysicsComponent.COLLISIONFLAGS_CHARACTER_OBJECT);
  4465. this._btColliderObject = ghostObject;
  4466. (this._colliderShape) && (this._constructCharacter());
  4467. super._onAdded();
  4468. }
  4469. _addToSimulation() {
  4470. this._simulation._characters.push(this);
  4471. this._simulation._addCharacter(this, this._collisionGroup, this._canCollideWith);
  4472. }
  4473. _removeFromSimulation() {
  4474. this._simulation._removeCharacter(this);
  4475. var characters = this._simulation._characters;
  4476. characters.splice(characters.indexOf(this), 1);
  4477. }
  4478. _cloneTo(dest) {
  4479. super._cloneTo(dest);
  4480. var destCharacterController = dest;
  4481. destCharacterController.stepHeight = this._stepHeight;
  4482. destCharacterController.upAxis = this._upAxis;
  4483. destCharacterController.maxSlope = this._maxSlope;
  4484. destCharacterController.jumpSpeed = this._jumpSpeed;
  4485. destCharacterController.fallSpeed = this._fallSpeed;
  4486. destCharacterController.gravity = this._gravity;
  4487. }
  4488. _onDestroy() {
  4489. ILaya3D.Physics3D._bullet.btKinematicCharacterController_destroy(this._btKinematicCharacter);
  4490. super._onDestroy();
  4491. this._btKinematicCharacter = null;
  4492. }
  4493. move(movement) {
  4494. var btMovement = CharacterController._btVector30;
  4495. var bt = ILaya3D.Physics3D._bullet;
  4496. bt.btVector3_setValue(btMovement, -movement.x, movement.y, movement.z);
  4497. bt.btKinematicCharacterController_setWalkDirection(this._btKinematicCharacter, btMovement);
  4498. }
  4499. jump(velocity = null) {
  4500. var bt = ILaya3D.Physics3D._bullet;
  4501. var btVelocity = CharacterController._btVector30;
  4502. if (velocity) {
  4503. Utils3D._convertToBulletVec3(velocity, btVelocity, true);
  4504. bt.btKinematicCharacterController_jump(this._btKinematicCharacter, btVelocity);
  4505. }
  4506. else {
  4507. bt.btVector3_setValue(btVelocity, 0, 0, 0);
  4508. bt.btKinematicCharacterController_jump(this._btKinematicCharacter, btVelocity);
  4509. }
  4510. }
  4511. }
  4512. CharacterController.UPAXIS_X = 0;
  4513. CharacterController.UPAXIS_Y = 1;
  4514. CharacterController.UPAXIS_Z = 2;
  4515. class PhysicsTriggerComponent extends PhysicsComponent {
  4516. constructor(collisionGroup, canCollideWith) {
  4517. super(collisionGroup, canCollideWith);
  4518. this._isTrigger = false;
  4519. }
  4520. get isTrigger() {
  4521. return this._isTrigger;
  4522. }
  4523. set isTrigger(value) {
  4524. this._isTrigger = value;
  4525. var bt = ILaya3D.Physics3D._bullet;
  4526. if (this._btColliderObject) {
  4527. var flags = bt.btCollisionObject_getCollisionFlags(this._btColliderObject);
  4528. if (value) {
  4529. if ((flags & PhysicsComponent.COLLISIONFLAGS_NO_CONTACT_RESPONSE) === 0)
  4530. bt.btCollisionObject_setCollisionFlags(this._btColliderObject, flags | PhysicsComponent.COLLISIONFLAGS_NO_CONTACT_RESPONSE);
  4531. }
  4532. else {
  4533. if ((flags & PhysicsComponent.COLLISIONFLAGS_NO_CONTACT_RESPONSE) !== 0)
  4534. bt.btCollisionObject_setCollisionFlags(this._btColliderObject, flags ^ PhysicsComponent.COLLISIONFLAGS_NO_CONTACT_RESPONSE);
  4535. }
  4536. }
  4537. }
  4538. _onAdded() {
  4539. super._onAdded();
  4540. this.isTrigger = this._isTrigger;
  4541. }
  4542. _cloneTo(dest) {
  4543. super._cloneTo(dest);
  4544. dest.isTrigger = this._isTrigger;
  4545. }
  4546. }
  4547. class Rigidbody3D extends PhysicsTriggerComponent {
  4548. constructor(collisionGroup = Physics3DUtils.COLLISIONFILTERGROUP_DEFAULTFILTER, canCollideWith = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  4549. super(collisionGroup, canCollideWith);
  4550. this._isKinematic = false;
  4551. this._mass = 1.0;
  4552. this._gravity = new Vector3(0, -10, 0);
  4553. this._angularDamping = 0.0;
  4554. this._linearDamping = 0.0;
  4555. this._overrideGravity = false;
  4556. this._totalTorque = new Vector3(0, 0, 0);
  4557. this._totalForce = new Vector3(0, 0, 0);
  4558. this._linearVelocity = new Vector3();
  4559. this._angularVelocity = new Vector3();
  4560. this._linearFactor = new Vector3(1, 1, 1);
  4561. this._angularFactor = new Vector3(1, 1, 1);
  4562. this._detectCollisions = true;
  4563. this._controlBySimulation = true;
  4564. }
  4565. static __init__() {
  4566. var bt = ILaya3D.Physics3D._bullet;
  4567. Rigidbody3D._btTempVector30 = bt.btVector3_create(0, 0, 0);
  4568. Rigidbody3D._btTempVector31 = bt.btVector3_create(0, 0, 0);
  4569. Rigidbody3D._btVector3Zero = bt.btVector3_create(0, 0, 0);
  4570. Rigidbody3D._btInertia = bt.btVector3_create(0, 0, 0);
  4571. Rigidbody3D._btImpulse = bt.btVector3_create(0, 0, 0);
  4572. Rigidbody3D._btImpulseOffset = bt.btVector3_create(0, 0, 0);
  4573. Rigidbody3D._btGravity = bt.btVector3_create(0, 0, 0);
  4574. Rigidbody3D._btTransform0 = bt.btTransform_create();
  4575. }
  4576. get mass() {
  4577. return this._mass;
  4578. }
  4579. set mass(value) {
  4580. value = Math.max(value, 1e-07);
  4581. this._mass = value;
  4582. (this._isKinematic) || (this._updateMass(value));
  4583. }
  4584. get isKinematic() {
  4585. return this._isKinematic;
  4586. }
  4587. set isKinematic(value) {
  4588. this._isKinematic = value;
  4589. this._controlBySimulation = !value;
  4590. var bt = ILaya3D.Physics3D._bullet;
  4591. var canInSimulation = !!(this._simulation && this._enabled && this._colliderShape);
  4592. canInSimulation && this._removeFromSimulation();
  4593. var natColObj = this._btColliderObject;
  4594. var flags = bt.btCollisionObject_getCollisionFlags(natColObj);
  4595. if (value) {
  4596. flags = flags | PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT;
  4597. bt.btCollisionObject_setCollisionFlags(natColObj, flags);
  4598. bt.btCollisionObject_forceActivationState(this._btColliderObject, PhysicsComponent.ACTIVATIONSTATE_DISABLE_DEACTIVATION);
  4599. this._enableProcessCollisions = false;
  4600. this._updateMass(0);
  4601. }
  4602. else {
  4603. if ((flags & PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT) > 0)
  4604. flags = flags ^ PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT;
  4605. bt.btCollisionObject_setCollisionFlags(natColObj, flags);
  4606. bt.btCollisionObject_setActivationState(this._btColliderObject, PhysicsComponent.ACTIVATIONSTATE_ACTIVE_TAG);
  4607. this._enableProcessCollisions = true;
  4608. this._updateMass(this._mass);
  4609. }
  4610. var btZero = Rigidbody3D._btVector3Zero;
  4611. bt.btCollisionObject_setInterpolationLinearVelocity(natColObj, btZero);
  4612. bt.btRigidBody_setLinearVelocity(natColObj, btZero);
  4613. bt.btCollisionObject_setInterpolationAngularVelocity(natColObj, btZero);
  4614. bt.btRigidBody_setAngularVelocity(natColObj, btZero);
  4615. canInSimulation && this._addToSimulation();
  4616. }
  4617. get linearDamping() {
  4618. return this._linearDamping;
  4619. }
  4620. set linearDamping(value) {
  4621. this._linearDamping = value;
  4622. if (this._btColliderObject)
  4623. ILaya3D.Physics3D._bullet.btRigidBody_setDamping(this._btColliderObject, value, this._angularDamping);
  4624. }
  4625. get angularDamping() {
  4626. return this._angularDamping;
  4627. }
  4628. set angularDamping(value) {
  4629. this._angularDamping = value;
  4630. if (this._btColliderObject)
  4631. ILaya3D.Physics3D._bullet.btRigidBody_setDamping(this._btColliderObject, this._linearDamping, value);
  4632. }
  4633. get overrideGravity() {
  4634. return this._overrideGravity;
  4635. }
  4636. set overrideGravity(value) {
  4637. this._overrideGravity = value;
  4638. var bt = ILaya3D.Physics3D._bullet;
  4639. if (this._btColliderObject) {
  4640. var flag = bt.btRigidBody_getFlags(this._btColliderObject);
  4641. if (value) {
  4642. if ((flag & Rigidbody3D._BT_DISABLE_WORLD_GRAVITY) === 0)
  4643. bt.btRigidBody_setFlags(this._btColliderObject, flag | Rigidbody3D._BT_DISABLE_WORLD_GRAVITY);
  4644. }
  4645. else {
  4646. if ((flag & Rigidbody3D._BT_DISABLE_WORLD_GRAVITY) > 0)
  4647. bt.btRigidBody_setFlags(this._btColliderObject, flag ^ Rigidbody3D._BT_DISABLE_WORLD_GRAVITY);
  4648. }
  4649. }
  4650. }
  4651. get gravity() {
  4652. var bt = ILaya3D.Physics3D._bullet;
  4653. Rigidbody3D._btGravity = bt.btRigidBody_getGravity(this._btColliderObject);
  4654. Utils3D._convertToLayaVec3(Rigidbody3D._btGravity, this._gravity, true);
  4655. return this._gravity;
  4656. }
  4657. set gravity(value) {
  4658. this._gravity = value;
  4659. var bt = ILaya3D.Physics3D._bullet;
  4660. bt.btVector3_setValue(Rigidbody3D._btGravity, -value.x, value.y, value.z);
  4661. bt.btRigidBody_setGravity(this._btColliderObject, Rigidbody3D._btGravity);
  4662. }
  4663. get totalForce() {
  4664. if (this._btColliderObject) {
  4665. var btTotalForce = ILaya3D.Physics3D._bullet.btRigidBody_getTotalForce(this._btColliderObject);
  4666. Utils3D._convertToLayaVec3(btTotalForce, this._totalForce, true);
  4667. return this._totalForce;
  4668. }
  4669. return null;
  4670. }
  4671. get linearFactor() {
  4672. return this._linearFactor;
  4673. }
  4674. set linearFactor(value) {
  4675. this._linearFactor = value;
  4676. var btValue = Rigidbody3D._btTempVector30;
  4677. Utils3D._convertToBulletVec3(value, btValue, false);
  4678. ILaya3D.Physics3D._bullet.btRigidBody_setLinearFactor(this._btColliderObject, btValue);
  4679. }
  4680. get linearVelocity() {
  4681. if (this._btColliderObject)
  4682. Utils3D._convertToLayaVec3(ILaya3D.Physics3D._bullet.btRigidBody_getLinearVelocity(this._btColliderObject), this._linearVelocity, true);
  4683. return this._linearVelocity;
  4684. }
  4685. set linearVelocity(value) {
  4686. this._linearVelocity = value;
  4687. if (this._btColliderObject) {
  4688. var btValue = Rigidbody3D._btTempVector30;
  4689. Utils3D._convertToBulletVec3(value, btValue, true);
  4690. (this.isSleeping) && (this.wakeUp());
  4691. ILaya3D.Physics3D._bullet.btRigidBody_setLinearVelocity(this._btColliderObject, btValue);
  4692. }
  4693. }
  4694. get angularFactor() {
  4695. return this._angularFactor;
  4696. }
  4697. set angularFactor(value) {
  4698. this._angularFactor = value;
  4699. var btValue = Rigidbody3D._btTempVector30;
  4700. Utils3D._convertToBulletVec3(value, btValue, false);
  4701. ILaya3D.Physics3D._bullet.btRigidBody_setAngularFactor(this._btColliderObject, btValue);
  4702. }
  4703. get angularVelocity() {
  4704. if (this._btColliderObject)
  4705. Utils3D._convertToLayaVec3(ILaya3D.Physics3D._bullet.btRigidBody_getAngularVelocity(this._btColliderObject), this._angularVelocity, true);
  4706. return this._angularVelocity;
  4707. }
  4708. set angularVelocity(value) {
  4709. this._angularVelocity = value;
  4710. if (this._btColliderObject) {
  4711. var btValue = Rigidbody3D._btTempVector30;
  4712. Utils3D._convertToBulletVec3(value, btValue, true);
  4713. (this.isSleeping) && (this.wakeUp());
  4714. ILaya3D.Physics3D._bullet.btRigidBody_setAngularVelocity(this._btColliderObject, btValue);
  4715. }
  4716. }
  4717. get totalTorque() {
  4718. if (this._btColliderObject) {
  4719. var btTotalTorque = ILaya3D.Physics3D._bullet.btRigidBody_getTotalTorque(this._btColliderObject);
  4720. Utils3D._convertToLayaVec3(btTotalTorque, this._totalTorque, true);
  4721. return this._totalTorque;
  4722. }
  4723. return null;
  4724. }
  4725. get detectCollisions() {
  4726. return this._detectCollisions;
  4727. }
  4728. set detectCollisions(value) {
  4729. if (this._detectCollisions !== value) {
  4730. this._detectCollisions = value;
  4731. if (this._colliderShape && this._enabled && this._simulation) {
  4732. this._simulation._removeRigidBody(this);
  4733. this._simulation._addRigidBody(this, this._collisionGroup, value ? this._canCollideWith : 0);
  4734. }
  4735. }
  4736. }
  4737. get isSleeping() {
  4738. if (this._btColliderObject)
  4739. return ILaya3D.Physics3D._bullet.btCollisionObject_getActivationState(this._btColliderObject) === PhysicsComponent.ACTIVATIONSTATE_ISLAND_SLEEPING;
  4740. return false;
  4741. }
  4742. get sleepLinearVelocity() {
  4743. return ILaya3D.Physics3D._bullet.btRigidBody_getLinearSleepingThreshold(this._btColliderObject);
  4744. }
  4745. set sleepLinearVelocity(value) {
  4746. var bt = ILaya3D.Physics3D._bullet;
  4747. bt.btRigidBody_setSleepingThresholds(this._btColliderObject, value, bt.btRigidBody_getAngularSleepingThreshold(this._btColliderObject));
  4748. }
  4749. get sleepAngularVelocity() {
  4750. return ILaya3D.Physics3D._bullet.btRigidBody_getAngularSleepingThreshold(this._btColliderObject);
  4751. }
  4752. set sleepAngularVelocity(value) {
  4753. var bt = ILaya3D.Physics3D._bullet;
  4754. bt.btRigidBody_setSleepingThresholds(this._btColliderObject, bt.btRigidBody_getLinearSleepingThreshold(this._btColliderObject), value);
  4755. }
  4756. get btColliderObject() {
  4757. return this._btColliderObject;
  4758. }
  4759. set constaintRigidbodyA(value) {
  4760. this._constaintRigidbodyA = value;
  4761. }
  4762. get constaintRigidbodyA() {
  4763. return this._constaintRigidbodyA;
  4764. }
  4765. set constaintRigidbodyB(value) {
  4766. this._constaintRigidbodyB = value;
  4767. }
  4768. get constaintRigidbodyB() {
  4769. return this._constaintRigidbodyB;
  4770. }
  4771. _updateMass(mass) {
  4772. if (this._btColliderObject && this._colliderShape) {
  4773. var bt = ILaya3D.Physics3D._bullet;
  4774. bt.btCollisionShape_calculateLocalInertia(this._colliderShape._btShape, mass, Rigidbody3D._btInertia);
  4775. bt.btRigidBody_setMassProps(this._btColliderObject, mass, Rigidbody3D._btInertia);
  4776. bt.btRigidBody_updateInertiaTensor(this._btColliderObject);
  4777. }
  4778. }
  4779. _onScaleChange(scale) {
  4780. super._onScaleChange(scale);
  4781. this._updateMass(this._isKinematic ? 0 : this._mass);
  4782. }
  4783. _derivePhysicsTransformation(force) {
  4784. var bt = ILaya3D.Physics3D._bullet;
  4785. var btColliderObject = this._btColliderObject;
  4786. var oriTransform = bt.btCollisionObject_getWorldTransform(btColliderObject);
  4787. var transform = Rigidbody3D._btTransform0;
  4788. bt.btTransform_equal(transform, oriTransform);
  4789. this._innerDerivePhysicsTransformation(transform, force);
  4790. bt.btRigidBody_setCenterOfMassTransform(btColliderObject, transform);
  4791. }
  4792. _onAdded() {
  4793. var bt = ILaya3D.Physics3D._bullet;
  4794. var motionState = bt.layaMotionState_create();
  4795. bt.layaMotionState_set_rigidBodyID(motionState, this._id);
  4796. this._btLayaMotionState = motionState;
  4797. var constructInfo = bt.btRigidBodyConstructionInfo_create(0.0, motionState, null, Rigidbody3D._btVector3Zero);
  4798. var btRigid = bt.btRigidBody_create(constructInfo);
  4799. bt.btCollisionObject_setUserIndex(btRigid, this.id);
  4800. this._btColliderObject = btRigid;
  4801. super._onAdded();
  4802. this.mass = this._mass;
  4803. this.linearFactor = this._linearFactor;
  4804. this.angularFactor = this._angularFactor;
  4805. this.linearDamping = this._linearDamping;
  4806. this.angularDamping = this._angularDamping;
  4807. this.overrideGravity = this._overrideGravity;
  4808. this.gravity = this._gravity;
  4809. this.isKinematic = this._isKinematic;
  4810. bt.btRigidBodyConstructionInfo_destroy(constructInfo);
  4811. }
  4812. _onEnable() {
  4813. super._onEnable();
  4814. if (this._constaintRigidbodyA) {
  4815. if (this._constaintRigidbodyA.connectedBody._simulation) {
  4816. this._constaintRigidbodyA._createConstraint();
  4817. this._constaintRigidbodyA._onEnable();
  4818. }
  4819. }
  4820. if (this._constaintRigidbodyB) {
  4821. if (this._constaintRigidbodyB.ownBody._simulation) {
  4822. this._constaintRigidbodyB._createConstraint();
  4823. this._constaintRigidbodyB._onEnable();
  4824. }
  4825. }
  4826. }
  4827. _onShapeChange(colShape) {
  4828. super._onShapeChange(colShape);
  4829. if (this._isKinematic) {
  4830. this._updateMass(0);
  4831. }
  4832. else {
  4833. var bt = ILaya3D.Physics3D._bullet;
  4834. bt.btRigidBody_setCenterOfMassTransform(this._btColliderObject, bt.btCollisionObject_getWorldTransform(this._btColliderObject));
  4835. this._updateMass(this._mass);
  4836. }
  4837. }
  4838. _parse(data) {
  4839. (data.friction != null) && (this.friction = data.friction);
  4840. (data.rollingFriction != null) && (this.rollingFriction = data.rollingFriction);
  4841. (data.restitution != null) && (this.restitution = data.restitution);
  4842. (data.isTrigger != null) && (this.isTrigger = data.isTrigger);
  4843. (data.mass != null) && (this.mass = data.mass);
  4844. (data.linearDamping != null) && (this.linearDamping = data.linearDamping);
  4845. (data.angularDamping != null) && (this.angularDamping = data.angularDamping);
  4846. (data.overrideGravity != null) && (this.overrideGravity = data.overrideGravity);
  4847. if (data.linearFactor != null) {
  4848. var linFac = this.linearFactor;
  4849. linFac.fromArray(data.linearFactor);
  4850. this.linearFactor = linFac;
  4851. }
  4852. if (data.angularFactor != null) {
  4853. var angFac = this.angularFactor;
  4854. angFac.fromArray(data.angularFactor);
  4855. this.angularFactor = angFac;
  4856. }
  4857. if (data.gravity) {
  4858. this.gravity.fromArray(data.gravity);
  4859. this.gravity = this.gravity;
  4860. }
  4861. super._parse(data);
  4862. this._parseShape(data.shapes);
  4863. (data.isKinematic != null) && (this.isKinematic = data.isKinematic);
  4864. }
  4865. _onDestroy() {
  4866. ILaya3D.Physics3D._bullet.btMotionState_destroy(this._btLayaMotionState);
  4867. super._onDestroy();
  4868. this._btLayaMotionState = null;
  4869. this._gravity = null;
  4870. this._totalTorque = null;
  4871. this._linearVelocity = null;
  4872. this._angularVelocity = null;
  4873. this._linearFactor = null;
  4874. this._angularFactor = null;
  4875. if (this.constaintRigidbodyA)
  4876. this.constaintRigidbodyA._breakConstrained();
  4877. if (this.constaintRigidbodyB) {
  4878. this.constaintRigidbodyB.connectedBody = null;
  4879. this.constaintRigidbodyB._onDisable();
  4880. }
  4881. }
  4882. _addToSimulation() {
  4883. this._simulation._addRigidBody(this, this._collisionGroup, this._detectCollisions ? this._canCollideWith : 0);
  4884. }
  4885. _removeFromSimulation() {
  4886. this._simulation._removeRigidBody(this);
  4887. }
  4888. _cloneTo(dest) {
  4889. super._cloneTo(dest);
  4890. var destRigidbody3D = dest;
  4891. destRigidbody3D.isKinematic = this._isKinematic;
  4892. destRigidbody3D.mass = this._mass;
  4893. destRigidbody3D.gravity = this._gravity;
  4894. destRigidbody3D.angularDamping = this._angularDamping;
  4895. destRigidbody3D.linearDamping = this._linearDamping;
  4896. destRigidbody3D.overrideGravity = this._overrideGravity;
  4897. destRigidbody3D.linearVelocity = this._linearVelocity;
  4898. destRigidbody3D.angularVelocity = this._angularVelocity;
  4899. destRigidbody3D.linearFactor = this._linearFactor;
  4900. destRigidbody3D.angularFactor = this._angularFactor;
  4901. destRigidbody3D.detectCollisions = this._detectCollisions;
  4902. }
  4903. applyForce(force, localOffset = null) {
  4904. if (this._btColliderObject == null)
  4905. throw "Attempted to call a Physics function that is avaliable only when the Entity has been already added to the Scene.";
  4906. var bt = ILaya3D.Physics3D._bullet;
  4907. var btForce = Rigidbody3D._btTempVector30;
  4908. bt.btVector3_setValue(btForce, -force.x, force.y, force.z);
  4909. if (localOffset) {
  4910. var btOffset = Rigidbody3D._btTempVector31;
  4911. bt.btVector3_setValue(btOffset, -localOffset.x, localOffset.y, localOffset.z);
  4912. bt.btRigidBody_applyForce(this._btColliderObject, btForce, btOffset);
  4913. }
  4914. else {
  4915. bt.btRigidBody_applyCentralForce(this._btColliderObject, btForce);
  4916. }
  4917. }
  4918. applyTorque(torque) {
  4919. if (this._btColliderObject == null)
  4920. throw "Attempted to call a Physics function that is avaliable only when the Entity has been already added to the Scene.";
  4921. var bullet = ILaya3D.Physics3D._bullet;
  4922. var btTorque = Rigidbody3D._btTempVector30;
  4923. bullet.btVector3_setValue(btTorque, -torque.x, torque.y, torque.z);
  4924. bullet.btRigidBody_applyTorque(this._btColliderObject, btTorque);
  4925. }
  4926. applyImpulse(impulse, localOffset = null) {
  4927. if (this._btColliderObject == null)
  4928. throw "Attempted to call a Physics function that is avaliable only when the Entity has been already added to the Scene.";
  4929. var bt = ILaya3D.Physics3D._bullet;
  4930. bt.btVector3_setValue(Rigidbody3D._btImpulse, -impulse.x, impulse.y, impulse.z);
  4931. if (localOffset) {
  4932. bt.btVector3_setValue(Rigidbody3D._btImpulseOffset, -localOffset.x, localOffset.y, localOffset.z);
  4933. bt.btRigidBody_applyImpulse(this._btColliderObject, Rigidbody3D._btImpulse, Rigidbody3D._btImpulseOffset);
  4934. }
  4935. else {
  4936. bt.btRigidBody_applyCentralImpulse(this._btColliderObject, Rigidbody3D._btImpulse);
  4937. }
  4938. }
  4939. applyTorqueImpulse(torqueImpulse) {
  4940. if (this._btColliderObject == null)
  4941. throw "Attempted to call a Physics function that is avaliable only when the Entity has been already added to the Scene.";
  4942. var bt = ILaya3D.Physics3D._bullet;
  4943. var btTorqueImpulse = Rigidbody3D._btTempVector30;
  4944. bt.btVector3_setValue(btTorqueImpulse, -torqueImpulse.x, torqueImpulse.y, torqueImpulse.z);
  4945. bt.btRigidBody_applyTorqueImpulse(this._btColliderObject, btTorqueImpulse);
  4946. }
  4947. wakeUp() {
  4948. this._btColliderObject && (ILaya3D.Physics3D._bullet.btCollisionObject_activate(this._btColliderObject, false));
  4949. }
  4950. clearForces() {
  4951. var rigidBody = this._btColliderObject;
  4952. if (rigidBody == null)
  4953. throw "Attempted to call a Physics function that is avaliable only when the Entity has been already added to the Scene.";
  4954. var bt = ILaya3D.Physics3D._bullet;
  4955. bt.btRigidBody_clearForces(rigidBody);
  4956. var btZero = Rigidbody3D._btVector3Zero;
  4957. bt.btCollisionObject_setInterpolationLinearVelocity(rigidBody, btZero);
  4958. bt.btRigidBody_setLinearVelocity(rigidBody, btZero);
  4959. bt.btCollisionObject_setInterpolationAngularVelocity(rigidBody, btZero);
  4960. bt.btRigidBody_setAngularVelocity(rigidBody, btZero);
  4961. }
  4962. }
  4963. Rigidbody3D.TYPE_STATIC = 0;
  4964. Rigidbody3D.TYPE_DYNAMIC = 1;
  4965. Rigidbody3D.TYPE_KINEMATIC = 2;
  4966. Rigidbody3D._BT_DISABLE_WORLD_GRAVITY = 1;
  4967. Rigidbody3D._BT_ENABLE_GYROPSCOPIC_FORCE = 2;
  4968. class Physics3D {
  4969. static __bulletinit__() {
  4970. this._bullet = window.Physics3D;
  4971. if (this._bullet) {
  4972. StaticPlaneColliderShape.__init__();
  4973. ColliderShape.__init__();
  4974. CompoundColliderShape.__init__();
  4975. PhysicsComponent.__init__();
  4976. PhysicsSimulation.__init__();
  4977. BoxColliderShape.__init__();
  4978. CylinderColliderShape.__init__();
  4979. CharacterController.__init__();
  4980. Rigidbody3D.__init__();
  4981. }
  4982. }
  4983. static __cannoninit__() {
  4984. this._cannon = window.CANNON;
  4985. if (!this._cannon)
  4986. return;
  4987. Laya.CannonColliderShape.__init__();
  4988. Laya.CannonPhysicsComponent.__init__();
  4989. Laya.CannonPhysicsSimulation.__init__();
  4990. Laya.CannonBoxColliderShape.__init__();
  4991. Laya.CannonRigidbody3D.__init__();
  4992. }
  4993. }
  4994. Physics3D._bullet = null;
  4995. Physics3D._cannon = null;
  4996. Physics3D._enablePhysics = false;
  4997. class Config3D {
  4998. constructor() {
  4999. this._defaultPhysicsMemory = 16;
  5000. this._maxLightCount = 32;
  5001. this._lightClusterCount = new Vector3(12, 12, 12);
  5002. this._editerEnvironment = false;
  5003. this.isAntialias = true;
  5004. this.isAlpha = false;
  5005. this.premultipliedAlpha = true;
  5006. this.isStencil = true;
  5007. this.enableMultiLight = true;
  5008. this.octreeCulling = false;
  5009. this.octreeInitialSize = 64.0;
  5010. this.octreeInitialCenter = new Vector3(0, 0, 0);
  5011. this.octreeMinNodeSize = 2.0;
  5012. this.octreeLooseness = 1.25;
  5013. this.debugFrustumCulling = false;
  5014. this.pbrRenderQuality = exports.PBRRenderQuality.High;
  5015. this.isUseCannonPhysicsEngine = false;
  5016. this._maxAreaLightCountPerClusterAverage = Math.min(Math.floor(2048 / this._lightClusterCount.z - 1) * 4, this._maxLightCount);
  5017. }
  5018. static get useCannonPhysics() {
  5019. return Config3D._config.isUseCannonPhysicsEngine;
  5020. }
  5021. static set useCannonPhysics(value) {
  5022. Config3D._config.isUseCannonPhysicsEngine = value;
  5023. if (value) {
  5024. Physics3D.__cannoninit__();
  5025. if (!ILaya3D.Scene3D.cannonPhysicsSettings)
  5026. ILaya3D.Scene3D.cannonPhysicsSettings = new Laya.CannonPhysicsSettings();
  5027. }
  5028. }
  5029. get defaultPhysicsMemory() {
  5030. return this._defaultPhysicsMemory;
  5031. }
  5032. set defaultPhysicsMemory(value) {
  5033. if (value < 16)
  5034. throw "defaultPhysicsMemory must large than 16M";
  5035. this._defaultPhysicsMemory = value;
  5036. }
  5037. get maxLightCount() {
  5038. return this._maxLightCount;
  5039. }
  5040. set maxLightCount(value) {
  5041. if (value > 2048) {
  5042. this._maxLightCount = 2048;
  5043. console.warn("Config3D: maxLightCount must less equal 2048.");
  5044. }
  5045. else {
  5046. this._maxLightCount = value;
  5047. }
  5048. }
  5049. get lightClusterCount() {
  5050. return this._lightClusterCount;
  5051. }
  5052. set lightClusterCount(value) {
  5053. if (value.x > 128 || value.y > 128 || value.z > 128) {
  5054. this._lightClusterCount.setValue(Math.min(value.x, 128), Math.min(value.y, 128), Math.min(value.z, 128));
  5055. console.warn("Config3D: lightClusterCount X and Y、Z must less equal 128.");
  5056. }
  5057. else {
  5058. value.cloneTo(this._lightClusterCount);
  5059. }
  5060. var maxAreaLightCountWithZ = Math.floor(2048 / this._lightClusterCount.z - 1) * 4;
  5061. if (maxAreaLightCountWithZ < this._maxLightCount)
  5062. console.warn("Config3D: if the area light(PointLight、SpotLight) count is large than " + maxAreaLightCountWithZ + ",maybe the far away culster will ingonre some light.");
  5063. this._maxAreaLightCountPerClusterAverage = Math.min(maxAreaLightCountWithZ, this._maxLightCount);
  5064. }
  5065. cloneTo(dest) {
  5066. var destConfig3D = dest;
  5067. destConfig3D._defaultPhysicsMemory = this._defaultPhysicsMemory;
  5068. destConfig3D._editerEnvironment = this._editerEnvironment;
  5069. destConfig3D.isAntialias = this.isAntialias;
  5070. destConfig3D.isAlpha = this.isAlpha;
  5071. destConfig3D.premultipliedAlpha = this.premultipliedAlpha;
  5072. destConfig3D.isStencil = this.isStencil;
  5073. destConfig3D.octreeCulling = this.octreeCulling;
  5074. this.octreeInitialCenter.cloneTo(destConfig3D.octreeInitialCenter);
  5075. destConfig3D.octreeInitialSize = this.octreeInitialSize;
  5076. destConfig3D.octreeMinNodeSize = this.octreeMinNodeSize;
  5077. destConfig3D.octreeLooseness = this.octreeLooseness;
  5078. destConfig3D.debugFrustumCulling = this.debugFrustumCulling;
  5079. destConfig3D.maxLightCount = this.maxLightCount;
  5080. destConfig3D.enableMultiLight = this.enableMultiLight;
  5081. var lightClusterCount = destConfig3D.lightClusterCount;
  5082. this.lightClusterCount.cloneTo(lightClusterCount);
  5083. destConfig3D.lightClusterCount = lightClusterCount;
  5084. destConfig3D.pbrRenderQuality = this.pbrRenderQuality;
  5085. }
  5086. clone() {
  5087. var dest = new Config3D();
  5088. this.cloneTo(dest);
  5089. return dest;
  5090. }
  5091. }
  5092. Config3D._config = new Config3D();
  5093. window.Config3D = Config3D;
  5094. class KeyframeNode {
  5095. constructor() {
  5096. this._ownerPath = [];
  5097. this._propertys = [];
  5098. this._keyFrames = [];
  5099. }
  5100. get ownerPathCount() {
  5101. return this._ownerPath.length;
  5102. }
  5103. get propertyCount() {
  5104. return this._propertys.length;
  5105. }
  5106. get keyFramesCount() {
  5107. return this._keyFrames.length;
  5108. }
  5109. _setOwnerPathCount(value) {
  5110. this._ownerPath.length = value;
  5111. }
  5112. _setOwnerPathByIndex(index, value) {
  5113. this._ownerPath[index] = value;
  5114. }
  5115. _joinOwnerPath(sep) {
  5116. return this._ownerPath.join(sep);
  5117. }
  5118. _setPropertyCount(value) {
  5119. this._propertys.length = value;
  5120. }
  5121. _setPropertyByIndex(index, value) {
  5122. this._propertys[index] = value;
  5123. }
  5124. _joinProperty(sep) {
  5125. return this._propertys.join(sep);
  5126. }
  5127. _setKeyframeCount(value) {
  5128. this._keyFrames.length = value;
  5129. }
  5130. _setKeyframeByIndex(index, value) {
  5131. this._keyFrames[index] = value;
  5132. }
  5133. getOwnerPathByIndex(index) {
  5134. return this._ownerPath[index];
  5135. }
  5136. getPropertyByIndex(index) {
  5137. return this._propertys[index];
  5138. }
  5139. getKeyframeByIndex(index) {
  5140. return this._keyFrames[index];
  5141. }
  5142. }
  5143. class AnimationEvent {
  5144. constructor() {
  5145. }
  5146. }
  5147. class Keyframe {
  5148. constructor() {
  5149. }
  5150. cloneTo(destObject) {
  5151. var destKeyFrame = destObject;
  5152. destKeyFrame.time = this.time;
  5153. }
  5154. clone() {
  5155. var dest = new Keyframe();
  5156. this.cloneTo(dest);
  5157. return dest;
  5158. }
  5159. }
  5160. class FloatKeyframe extends Keyframe {
  5161. constructor() {
  5162. super();
  5163. }
  5164. cloneTo(destObject) {
  5165. super.cloneTo(destObject);
  5166. var destKeyFrame = destObject;
  5167. destKeyFrame.inTangent = this.inTangent;
  5168. destKeyFrame.outTangent = this.outTangent;
  5169. destKeyFrame.value = this.value;
  5170. }
  5171. }
  5172. class QuaternionKeyframe extends Keyframe {
  5173. constructor() {
  5174. super();
  5175. this.inTangent = new Vector4();
  5176. this.outTangent = new Vector4();
  5177. this.value = new Quaternion();
  5178. }
  5179. cloneTo(dest) {
  5180. super.cloneTo(dest);
  5181. var destKeyFarme = dest;
  5182. this.inTangent.cloneTo(destKeyFarme.inTangent);
  5183. this.outTangent.cloneTo(destKeyFarme.outTangent);
  5184. this.value.cloneTo(destKeyFarme.value);
  5185. }
  5186. }
  5187. class Vector3Keyframe extends Keyframe {
  5188. constructor() {
  5189. super();
  5190. this.inTangent = new Vector3();
  5191. this.outTangent = new Vector3();
  5192. this.value = new Vector3();
  5193. }
  5194. cloneTo(dest) {
  5195. super.cloneTo(dest);
  5196. var destKeyFarme = dest;
  5197. this.inTangent.cloneTo(destKeyFarme.inTangent);
  5198. this.outTangent.cloneTo(destKeyFarme.outTangent);
  5199. this.value.cloneTo(destKeyFarme.value);
  5200. }
  5201. }
  5202. class AnimationClipParser03 {
  5203. static READ_DATA() {
  5204. AnimationClipParser03._DATA.offset = AnimationClipParser03._reader.getUint32();
  5205. AnimationClipParser03._DATA.size = AnimationClipParser03._reader.getUint32();
  5206. }
  5207. static READ_BLOCK() {
  5208. var count = AnimationClipParser03._BLOCK.count = AnimationClipParser03._reader.getUint16();
  5209. var blockStarts = AnimationClipParser03._BLOCK.blockStarts = [];
  5210. var blockLengths = AnimationClipParser03._BLOCK.blockLengths = [];
  5211. for (var i = 0; i < count; i++) {
  5212. blockStarts.push(AnimationClipParser03._reader.getUint32());
  5213. blockLengths.push(AnimationClipParser03._reader.getUint32());
  5214. }
  5215. }
  5216. static READ_STRINGS() {
  5217. var offset = AnimationClipParser03._reader.getUint32();
  5218. var count = AnimationClipParser03._reader.getUint16();
  5219. var prePos = AnimationClipParser03._reader.pos;
  5220. AnimationClipParser03._reader.pos = offset + AnimationClipParser03._DATA.offset;
  5221. for (var i = 0; i < count; i++)
  5222. AnimationClipParser03._strings[i] = AnimationClipParser03._reader.readUTFString();
  5223. AnimationClipParser03._reader.pos = prePos;
  5224. }
  5225. static parse(clip, reader) {
  5226. AnimationClipParser03._animationClip = clip;
  5227. AnimationClipParser03._reader = reader;
  5228. AnimationClipParser03.READ_DATA();
  5229. AnimationClipParser03.READ_BLOCK();
  5230. AnimationClipParser03.READ_STRINGS();
  5231. for (var i = 0, n = AnimationClipParser03._BLOCK.count; i < n; i++) {
  5232. var index = reader.getUint16();
  5233. var blockName = AnimationClipParser03._strings[index];
  5234. var fn = AnimationClipParser03["READ_" + blockName];
  5235. if (fn == null)
  5236. throw new Error("model file err,no this function:" + index + " " + blockName);
  5237. else
  5238. fn.call(null);
  5239. }
  5240. }
  5241. static READ_ANIMATIONS() {
  5242. var i, j;
  5243. var node;
  5244. var reader = AnimationClipParser03._reader;
  5245. var startTimeTypes = [];
  5246. var startTimeTypeCount = reader.getUint16();
  5247. startTimeTypes.length = startTimeTypeCount;
  5248. for (i = 0; i < startTimeTypeCount; i++)
  5249. startTimeTypes[i] = reader.getFloat32();
  5250. var clip = AnimationClipParser03._animationClip;
  5251. clip.name = AnimationClipParser03._strings[reader.getUint16()];
  5252. var clipDur = clip._duration = reader.getFloat32();
  5253. clip.islooping = !!reader.getByte();
  5254. clip._frameRate = reader.getInt16();
  5255. var nodeCount = reader.getInt16();
  5256. var nodes = clip._nodes;
  5257. nodes.count = nodeCount;
  5258. var nodesMap = clip._nodesMap = {};
  5259. var nodesDic = clip._nodesDic = {};
  5260. for (i = 0; i < nodeCount; i++) {
  5261. node = new KeyframeNode();
  5262. nodes.setNodeByIndex(i, node);
  5263. node._indexInList = i;
  5264. var type = node.type = reader.getUint8();
  5265. var pathLength = reader.getUint16();
  5266. node._setOwnerPathCount(pathLength);
  5267. for (j = 0; j < pathLength; j++)
  5268. node._setOwnerPathByIndex(j, AnimationClipParser03._strings[reader.getUint16()]);
  5269. var nodePath = node._joinOwnerPath("/");
  5270. var mapArray = nodesMap[nodePath];
  5271. (mapArray) || (nodesMap[nodePath] = mapArray = []);
  5272. mapArray.push(node);
  5273. node.propertyOwner = AnimationClipParser03._strings[reader.getUint16()];
  5274. var propertyLength = reader.getUint16();
  5275. node._setPropertyCount(propertyLength);
  5276. for (j = 0; j < propertyLength; j++)
  5277. node._setPropertyByIndex(j, AnimationClipParser03._strings[reader.getUint16()]);
  5278. var fullPath = nodePath + "." + node.propertyOwner + "." + node._joinProperty(".");
  5279. nodesDic[fullPath] = node;
  5280. node.fullPath = fullPath;
  5281. var keyframeCount = reader.getUint16();
  5282. node._setKeyframeCount(keyframeCount);
  5283. var startTime;
  5284. for (j = 0; j < keyframeCount; j++) {
  5285. switch (type) {
  5286. case 0:
  5287. var floatKeyframe = new FloatKeyframe();
  5288. node._setKeyframeByIndex(j, floatKeyframe);
  5289. startTime = floatKeyframe.time = startTimeTypes[reader.getUint16()];
  5290. floatKeyframe.inTangent = reader.getFloat32();
  5291. floatKeyframe.outTangent = reader.getFloat32();
  5292. floatKeyframe.value = reader.getFloat32();
  5293. break;
  5294. case 1:
  5295. case 3:
  5296. case 4:
  5297. var floatArrayKeyframe = new Vector3Keyframe();
  5298. node._setKeyframeByIndex(j, floatArrayKeyframe);
  5299. startTime = floatArrayKeyframe.time = startTimeTypes[reader.getUint16()];
  5300. var inTangent = floatArrayKeyframe.inTangent;
  5301. var outTangent = floatArrayKeyframe.outTangent;
  5302. var value = floatArrayKeyframe.value;
  5303. inTangent.x = reader.getFloat32();
  5304. inTangent.y = reader.getFloat32();
  5305. inTangent.z = reader.getFloat32();
  5306. outTangent.x = reader.getFloat32();
  5307. outTangent.y = reader.getFloat32();
  5308. outTangent.z = reader.getFloat32();
  5309. value.x = reader.getFloat32();
  5310. value.y = reader.getFloat32();
  5311. value.z = reader.getFloat32();
  5312. break;
  5313. case 2:
  5314. var quaArrayKeyframe = new QuaternionKeyframe();
  5315. node._setKeyframeByIndex(j, quaArrayKeyframe);
  5316. startTime = quaArrayKeyframe.time = startTimeTypes[reader.getUint16()];
  5317. var inTangentQua = quaArrayKeyframe.inTangent;
  5318. var outTangentQua = quaArrayKeyframe.outTangent;
  5319. var valueQua = quaArrayKeyframe.value;
  5320. inTangentQua.x = reader.getFloat32();
  5321. inTangentQua.y = reader.getFloat32();
  5322. inTangentQua.z = reader.getFloat32();
  5323. inTangentQua.w = reader.getFloat32();
  5324. outTangentQua.x = reader.getFloat32();
  5325. outTangentQua.y = reader.getFloat32();
  5326. outTangentQua.z = reader.getFloat32();
  5327. outTangentQua.w = reader.getFloat32();
  5328. valueQua.x = reader.getFloat32();
  5329. valueQua.y = reader.getFloat32();
  5330. valueQua.z = reader.getFloat32();
  5331. valueQua.w = reader.getFloat32();
  5332. break;
  5333. default:
  5334. throw "AnimationClipParser03:unknown type.";
  5335. }
  5336. }
  5337. }
  5338. var eventCount = reader.getUint16();
  5339. for (i = 0; i < eventCount; i++) {
  5340. var event = new AnimationEvent();
  5341. event.time = Math.min(clipDur, reader.getFloat32());
  5342. event.eventName = AnimationClipParser03._strings[reader.getUint16()];
  5343. var params = [];
  5344. var paramCount = reader.getUint16();
  5345. (paramCount > 0) && (event.params = params = []);
  5346. for (j = 0; j < paramCount; j++) {
  5347. var eventType = reader.getByte();
  5348. switch (eventType) {
  5349. case 0:
  5350. params.push(!!reader.getByte());
  5351. break;
  5352. case 1:
  5353. params.push(reader.getInt32());
  5354. break;
  5355. case 2:
  5356. params.push(reader.getFloat32());
  5357. break;
  5358. case 3:
  5359. params.push(AnimationClipParser03._strings[reader.getUint16()]);
  5360. break;
  5361. default:
  5362. throw new Error("unknown type.");
  5363. }
  5364. }
  5365. clip.addEvent(event);
  5366. }
  5367. }
  5368. }
  5369. AnimationClipParser03._strings = [];
  5370. AnimationClipParser03._BLOCK = { count: 0 };
  5371. AnimationClipParser03._DATA = { offset: 0, size: 0 };
  5372. class AnimationClipParser04 {
  5373. static READ_DATA() {
  5374. AnimationClipParser04._DATA.offset = AnimationClipParser04._reader.getUint32();
  5375. AnimationClipParser04._DATA.size = AnimationClipParser04._reader.getUint32();
  5376. }
  5377. static READ_BLOCK() {
  5378. var count = AnimationClipParser04._BLOCK.count = AnimationClipParser04._reader.getUint16();
  5379. var blockStarts = AnimationClipParser04._BLOCK.blockStarts = [];
  5380. var blockLengths = AnimationClipParser04._BLOCK.blockLengths = [];
  5381. for (var i = 0; i < count; i++) {
  5382. blockStarts.push(AnimationClipParser04._reader.getUint32());
  5383. blockLengths.push(AnimationClipParser04._reader.getUint32());
  5384. }
  5385. }
  5386. static READ_STRINGS() {
  5387. var offset = AnimationClipParser04._reader.getUint32();
  5388. var count = AnimationClipParser04._reader.getUint16();
  5389. var prePos = AnimationClipParser04._reader.pos;
  5390. AnimationClipParser04._reader.pos = offset + AnimationClipParser04._DATA.offset;
  5391. for (var i = 0; i < count; i++)
  5392. AnimationClipParser04._strings[i] = AnimationClipParser04._reader.readUTFString();
  5393. AnimationClipParser04._reader.pos = prePos;
  5394. }
  5395. static parse(clip, reader, version) {
  5396. AnimationClipParser04._animationClip = clip;
  5397. AnimationClipParser04._reader = reader;
  5398. AnimationClipParser04._version = version;
  5399. AnimationClipParser04.READ_DATA();
  5400. AnimationClipParser04.READ_BLOCK();
  5401. AnimationClipParser04.READ_STRINGS();
  5402. for (var i = 0, n = AnimationClipParser04._BLOCK.count; i < n; i++) {
  5403. var index = reader.getUint16();
  5404. var blockName = AnimationClipParser04._strings[index];
  5405. var fn = AnimationClipParser04["READ_" + blockName];
  5406. if (fn == null)
  5407. throw new Error("model file err,no this function:" + index + " " + blockName);
  5408. else
  5409. fn.call(null);
  5410. }
  5411. AnimationClipParser04._version = null;
  5412. AnimationClipParser04._reader = null;
  5413. AnimationClipParser04._animationClip = null;
  5414. }
  5415. static READ_ANIMATIONS() {
  5416. var i, j;
  5417. var node;
  5418. var reader = AnimationClipParser04._reader;
  5419. var startTimeTypes = [];
  5420. var startTimeTypeCount = reader.getUint16();
  5421. startTimeTypes.length = startTimeTypeCount;
  5422. for (i = 0; i < startTimeTypeCount; i++)
  5423. startTimeTypes[i] = reader.getFloat32();
  5424. var clip = AnimationClipParser04._animationClip;
  5425. clip.name = AnimationClipParser04._strings[reader.getUint16()];
  5426. var clipDur = clip._duration = reader.getFloat32();
  5427. clip.islooping = !!reader.getByte();
  5428. clip._frameRate = reader.getInt16();
  5429. var nodeCount = reader.getInt16();
  5430. var nodes = clip._nodes;
  5431. nodes.count = nodeCount;
  5432. var nodesMap = clip._nodesMap = {};
  5433. var nodesDic = clip._nodesDic = {};
  5434. for (i = 0; i < nodeCount; i++) {
  5435. node = new KeyframeNode();
  5436. nodes.setNodeByIndex(i, node);
  5437. node._indexInList = i;
  5438. var type = node.type = reader.getUint8();
  5439. var pathLength = reader.getUint16();
  5440. node._setOwnerPathCount(pathLength);
  5441. for (j = 0; j < pathLength; j++)
  5442. node._setOwnerPathByIndex(j, AnimationClipParser04._strings[reader.getUint16()]);
  5443. var nodePath = node._joinOwnerPath("/");
  5444. var mapArray = nodesMap[nodePath];
  5445. (mapArray) || (nodesMap[nodePath] = mapArray = []);
  5446. mapArray.push(node);
  5447. node.propertyOwner = AnimationClipParser04._strings[reader.getUint16()];
  5448. var propertyLength = reader.getUint16();
  5449. node._setPropertyCount(propertyLength);
  5450. for (j = 0; j < propertyLength; j++)
  5451. node._setPropertyByIndex(j, AnimationClipParser04._strings[reader.getUint16()]);
  5452. var fullPath = nodePath + "." + node.propertyOwner + "." + node._joinProperty(".");
  5453. nodesDic[fullPath] = node;
  5454. node.fullPath = fullPath;
  5455. var keyframeCount = reader.getUint16();
  5456. node._setKeyframeCount(keyframeCount);
  5457. switch (AnimationClipParser04._version) {
  5458. case "LAYAANIMATION:04":
  5459. for (j = 0; j < keyframeCount; j++) {
  5460. switch (type) {
  5461. case 0:
  5462. var floatKeyframe = new FloatKeyframe();
  5463. node._setKeyframeByIndex(j, floatKeyframe);
  5464. floatKeyframe.time = startTimeTypes[reader.getUint16()];
  5465. floatKeyframe.inTangent = reader.getFloat32();
  5466. floatKeyframe.outTangent = reader.getFloat32();
  5467. floatKeyframe.value = reader.getFloat32();
  5468. break;
  5469. case 1:
  5470. case 3:
  5471. case 4:
  5472. var floatArrayKeyframe = new Vector3Keyframe();
  5473. node._setKeyframeByIndex(j, floatArrayKeyframe);
  5474. floatArrayKeyframe.time = startTimeTypes[reader.getUint16()];
  5475. var inTangent = floatArrayKeyframe.inTangent;
  5476. var outTangent = floatArrayKeyframe.outTangent;
  5477. var value = floatArrayKeyframe.value;
  5478. inTangent.x = reader.getFloat32();
  5479. inTangent.y = reader.getFloat32();
  5480. inTangent.z = reader.getFloat32();
  5481. outTangent.x = reader.getFloat32();
  5482. outTangent.y = reader.getFloat32();
  5483. outTangent.z = reader.getFloat32();
  5484. value.x = reader.getFloat32();
  5485. value.y = reader.getFloat32();
  5486. value.z = reader.getFloat32();
  5487. break;
  5488. case 2:
  5489. var quaternionKeyframe = new QuaternionKeyframe();
  5490. node._setKeyframeByIndex(j, quaternionKeyframe);
  5491. quaternionKeyframe.time = startTimeTypes[reader.getUint16()];
  5492. var inTangentQua = quaternionKeyframe.inTangent;
  5493. var outTangentQua = quaternionKeyframe.outTangent;
  5494. var valueQua = quaternionKeyframe.value;
  5495. inTangentQua.x = reader.getFloat32();
  5496. inTangentQua.y = reader.getFloat32();
  5497. inTangentQua.z = reader.getFloat32();
  5498. inTangentQua.w = reader.getFloat32();
  5499. outTangentQua.x = reader.getFloat32();
  5500. outTangentQua.y = reader.getFloat32();
  5501. outTangentQua.z = reader.getFloat32();
  5502. outTangentQua.w = reader.getFloat32();
  5503. valueQua.x = reader.getFloat32();
  5504. valueQua.y = reader.getFloat32();
  5505. valueQua.z = reader.getFloat32();
  5506. valueQua.w = reader.getFloat32();
  5507. break;
  5508. default:
  5509. throw "AnimationClipParser04:unknown type.";
  5510. }
  5511. }
  5512. break;
  5513. case "LAYAANIMATION:COMPRESSION_04":
  5514. for (j = 0; j < keyframeCount; j++) {
  5515. switch (type) {
  5516. case 0:
  5517. floatKeyframe = new FloatKeyframe();
  5518. node._setKeyframeByIndex(j, floatKeyframe);
  5519. floatKeyframe.time = startTimeTypes[reader.getUint16()];
  5520. floatKeyframe.inTangent = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5521. floatKeyframe.outTangent = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5522. floatKeyframe.value = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5523. break;
  5524. case 1:
  5525. case 3:
  5526. case 4:
  5527. floatArrayKeyframe = new Vector3Keyframe();
  5528. node._setKeyframeByIndex(j, floatArrayKeyframe);
  5529. floatArrayKeyframe.time = startTimeTypes[reader.getUint16()];
  5530. inTangent = floatArrayKeyframe.inTangent;
  5531. outTangent = floatArrayKeyframe.outTangent;
  5532. value = floatArrayKeyframe.value;
  5533. inTangent.x = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5534. inTangent.y = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5535. inTangent.z = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5536. outTangent.x = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5537. outTangent.y = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5538. outTangent.z = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5539. value.x = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5540. value.y = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5541. value.z = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5542. break;
  5543. case 2:
  5544. quaternionKeyframe = new QuaternionKeyframe();
  5545. node._setKeyframeByIndex(j, quaternionKeyframe);
  5546. quaternionKeyframe.time = startTimeTypes[reader.getUint16()];
  5547. inTangentQua = quaternionKeyframe.inTangent;
  5548. outTangentQua = quaternionKeyframe.outTangent;
  5549. valueQua = quaternionKeyframe.value;
  5550. inTangentQua.x = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5551. inTangentQua.y = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5552. inTangentQua.z = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5553. inTangentQua.w = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5554. outTangentQua.x = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5555. outTangentQua.y = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5556. outTangentQua.z = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5557. outTangentQua.w = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5558. valueQua.x = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5559. valueQua.y = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5560. valueQua.z = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5561. valueQua.w = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  5562. break;
  5563. default:
  5564. throw "AnimationClipParser04:unknown type.";
  5565. }
  5566. }
  5567. break;
  5568. }
  5569. }
  5570. var eventCount = reader.getUint16();
  5571. for (i = 0; i < eventCount; i++) {
  5572. var event = new AnimationEvent();
  5573. event.time = Math.min(clipDur, reader.getFloat32());
  5574. event.eventName = AnimationClipParser04._strings[reader.getUint16()];
  5575. var params = [];
  5576. var paramCount = reader.getUint16();
  5577. (paramCount > 0) && (event.params = params = []);
  5578. for (j = 0; j < paramCount; j++) {
  5579. var eventType = reader.getByte();
  5580. switch (eventType) {
  5581. case 0:
  5582. params.push(!!reader.getByte());
  5583. break;
  5584. case 1:
  5585. params.push(reader.getInt32());
  5586. break;
  5587. case 2:
  5588. params.push(reader.getFloat32());
  5589. break;
  5590. case 3:
  5591. params.push(AnimationClipParser04._strings[reader.getUint16()]);
  5592. break;
  5593. default:
  5594. throw new Error("unknown type.");
  5595. }
  5596. }
  5597. clip.addEvent(event);
  5598. }
  5599. }
  5600. }
  5601. AnimationClipParser04._strings = [];
  5602. AnimationClipParser04._BLOCK = { count: 0 };
  5603. AnimationClipParser04._DATA = { offset: 0, size: 0 };
  5604. class KeyframeNodeList {
  5605. constructor() {
  5606. this._nodes = [];
  5607. }
  5608. get count() {
  5609. return this._nodes.length;
  5610. }
  5611. set count(value) {
  5612. this._nodes.length = value;
  5613. }
  5614. getNodeByIndex(index) {
  5615. return this._nodes[index];
  5616. }
  5617. setNodeByIndex(index, node) {
  5618. this._nodes[index] = node;
  5619. }
  5620. }
  5621. class AnimationClip extends Laya.Resource {
  5622. constructor() {
  5623. super();
  5624. this._duration = 0;
  5625. this._frameRate = 0;
  5626. this._nodes = new KeyframeNodeList();
  5627. this.islooping = false;
  5628. this._animationEvents = [];
  5629. }
  5630. static _parse(data) {
  5631. var clip = new AnimationClip();
  5632. var reader = new Laya.Byte(data);
  5633. var version = reader.readUTFString();
  5634. switch (version) {
  5635. case "LAYAANIMATION:03":
  5636. AnimationClipParser03.parse(clip, reader);
  5637. break;
  5638. case "LAYAANIMATION:04":
  5639. case "LAYAANIMATION:COMPRESSION_04":
  5640. AnimationClipParser04.parse(clip, reader, version);
  5641. break;
  5642. default:
  5643. throw "unknown animationClip version.";
  5644. }
  5645. return clip;
  5646. }
  5647. static load(url, complete) {
  5648. Laya.ILaya.loader.create(url, complete, null, AnimationClip.ANIMATIONCLIP);
  5649. }
  5650. duration() {
  5651. return this._duration;
  5652. }
  5653. _hermiteInterpolate(frame, nextFrame, t, dur) {
  5654. var t0 = frame.outTangent, t1 = nextFrame.inTangent;
  5655. if (Number.isFinite(t0) && Number.isFinite(t1)) {
  5656. var t2 = t * t;
  5657. var t3 = t2 * t;
  5658. var a = 2.0 * t3 - 3.0 * t2 + 1.0;
  5659. var b = t3 - 2.0 * t2 + t;
  5660. var c = t3 - t2;
  5661. var d = -2.0 * t3 + 3.0 * t2;
  5662. return a * frame.value + b * t0 * dur + c * t1 * dur + d * nextFrame.value;
  5663. }
  5664. else
  5665. return frame.value;
  5666. }
  5667. _hermiteInterpolateVector3(frame, nextFrame, t, dur, out) {
  5668. var p0 = frame.value;
  5669. var tan0 = frame.outTangent;
  5670. var p1 = nextFrame.value;
  5671. var tan1 = nextFrame.inTangent;
  5672. var t2 = t * t;
  5673. var t3 = t2 * t;
  5674. var a = 2.0 * t3 - 3.0 * t2 + 1.0;
  5675. var b = t3 - 2.0 * t2 + t;
  5676. var c = t3 - t2;
  5677. var d = -2.0 * t3 + 3.0 * t2;
  5678. var t0 = tan0.x, t1 = tan1.x;
  5679. if (Number.isFinite(t0) && Number.isFinite(t1))
  5680. out.x = a * p0.x + b * t0 * dur + c * t1 * dur + d * p1.x;
  5681. else
  5682. out.x = p0.x;
  5683. t0 = tan0.y, t1 = tan1.y;
  5684. if (Number.isFinite(t0) && Number.isFinite(t1))
  5685. out.y = a * p0.y + b * t0 * dur + c * t1 * dur + d * p1.y;
  5686. else
  5687. out.y = p0.y;
  5688. t0 = tan0.z, t1 = tan1.z;
  5689. if (Number.isFinite(t0) && Number.isFinite(t1))
  5690. out.z = a * p0.z + b * t0 * dur + c * t1 * dur + d * p1.z;
  5691. else
  5692. out.z = p0.z;
  5693. }
  5694. _hermiteInterpolateQuaternion(frame, nextFrame, t, dur, out) {
  5695. var p0 = frame.value;
  5696. var tan0 = frame.outTangent;
  5697. var p1 = nextFrame.value;
  5698. var tan1 = nextFrame.inTangent;
  5699. var t2 = t * t;
  5700. var t3 = t2 * t;
  5701. var a = 2.0 * t3 - 3.0 * t2 + 1.0;
  5702. var b = t3 - 2.0 * t2 + t;
  5703. var c = t3 - t2;
  5704. var d = -2.0 * t3 + 3.0 * t2;
  5705. var t0 = tan0.x, t1 = tan1.x;
  5706. if (Number.isFinite(t0) && Number.isFinite(t1))
  5707. out.x = a * p0.x + b * t0 * dur + c * t1 * dur + d * p1.x;
  5708. else
  5709. out.x = p0.x;
  5710. t0 = tan0.y, t1 = tan1.y;
  5711. if (Number.isFinite(t0) && Number.isFinite(t1))
  5712. out.y = a * p0.y + b * t0 * dur + c * t1 * dur + d * p1.y;
  5713. else
  5714. out.y = p0.y;
  5715. t0 = tan0.z, t1 = tan1.z;
  5716. if (Number.isFinite(t0) && Number.isFinite(t1))
  5717. out.z = a * p0.z + b * t0 * dur + c * t1 * dur + d * p1.z;
  5718. else
  5719. out.z = p0.z;
  5720. t0 = tan0.w, t1 = tan1.w;
  5721. if (Number.isFinite(t0) && Number.isFinite(t1))
  5722. out.w = a * p0.w + b * t0 * dur + c * t1 * dur + d * p1.w;
  5723. else
  5724. out.w = p0.w;
  5725. }
  5726. _evaluateClipDatasRealTime(nodes, playCurTime, realTimeCurrentFrameIndexes, addtive, frontPlay, outDatas) {
  5727. for (var i = 0, n = nodes.count; i < n; i++) {
  5728. var node = nodes.getNodeByIndex(i);
  5729. var type = node.type;
  5730. var nextFrameIndex;
  5731. var keyFrames = node._keyFrames;
  5732. var keyFramesCount = keyFrames.length;
  5733. var frameIndex = realTimeCurrentFrameIndexes[i];
  5734. if (frontPlay) {
  5735. if ((frameIndex !== -1) && (playCurTime < keyFrames[frameIndex].time)) {
  5736. frameIndex = -1;
  5737. realTimeCurrentFrameIndexes[i] = frameIndex;
  5738. }
  5739. nextFrameIndex = frameIndex + 1;
  5740. while (nextFrameIndex < keyFramesCount) {
  5741. if (keyFrames[nextFrameIndex].time > playCurTime)
  5742. break;
  5743. frameIndex++;
  5744. nextFrameIndex++;
  5745. realTimeCurrentFrameIndexes[i] = frameIndex;
  5746. }
  5747. }
  5748. else {
  5749. nextFrameIndex = frameIndex + 1;
  5750. if ((nextFrameIndex !== keyFramesCount) && (playCurTime > keyFrames[nextFrameIndex].time)) {
  5751. frameIndex = keyFramesCount - 1;
  5752. realTimeCurrentFrameIndexes[i] = frameIndex;
  5753. }
  5754. nextFrameIndex = frameIndex + 1;
  5755. while (frameIndex > -1) {
  5756. if (keyFrames[frameIndex].time < playCurTime)
  5757. break;
  5758. frameIndex--;
  5759. nextFrameIndex--;
  5760. realTimeCurrentFrameIndexes[i] = frameIndex;
  5761. }
  5762. }
  5763. var isEnd = nextFrameIndex === keyFramesCount;
  5764. switch (type) {
  5765. case 0:
  5766. if (frameIndex !== -1) {
  5767. var frame = keyFrames[frameIndex];
  5768. if (isEnd) {
  5769. outDatas[i] = frame.value;
  5770. }
  5771. else {
  5772. var nextFarme = keyFrames[nextFrameIndex];
  5773. var d = nextFarme.time - frame.time;
  5774. var t;
  5775. if (d !== 0)
  5776. t = (playCurTime - frame.time) / d;
  5777. else
  5778. t = 0;
  5779. outDatas[i] = this._hermiteInterpolate(frame, nextFarme, t, d);
  5780. }
  5781. }
  5782. else {
  5783. outDatas[i] = keyFrames[0].value;
  5784. }
  5785. if (addtive)
  5786. outDatas[i] = outDatas[i] - keyFrames[0].value;
  5787. break;
  5788. case 1:
  5789. case 4:
  5790. var clipData = outDatas[i];
  5791. this._evaluateFrameNodeVector3DatasRealTime(keyFrames, frameIndex, isEnd, playCurTime, clipData);
  5792. if (addtive) {
  5793. var firstFrameValue = keyFrames[0].value;
  5794. clipData.x -= firstFrameValue.x;
  5795. clipData.y -= firstFrameValue.y;
  5796. clipData.z -= firstFrameValue.z;
  5797. }
  5798. break;
  5799. case 2:
  5800. var clipQuat = outDatas[i];
  5801. this._evaluateFrameNodeQuaternionDatasRealTime(keyFrames, frameIndex, isEnd, playCurTime, clipQuat);
  5802. if (addtive) {
  5803. var tempQuat = AnimationClip._tempQuaternion0;
  5804. var firstFrameValueQua = keyFrames[0].value;
  5805. Utils3D.quaternionConjugate(firstFrameValueQua, tempQuat);
  5806. Quaternion.multiply(tempQuat, clipQuat, clipQuat);
  5807. }
  5808. break;
  5809. case 3:
  5810. clipData = outDatas[i];
  5811. this._evaluateFrameNodeVector3DatasRealTime(keyFrames, frameIndex, isEnd, playCurTime, clipData);
  5812. if (addtive) {
  5813. firstFrameValue = keyFrames[0].value;
  5814. clipData.x /= firstFrameValue.x;
  5815. clipData.y /= firstFrameValue.y;
  5816. clipData.z /= firstFrameValue.z;
  5817. }
  5818. break;
  5819. default:
  5820. throw "AnimationClip:unknown node type.";
  5821. }
  5822. }
  5823. }
  5824. _evaluateClipDatasRealTimeForNative(nodes, playCurTime, realTimeCurrentFrameIndexes, addtive) {
  5825. Laya.LayaGL.instance.evaluateClipDatasRealTime(nodes._nativeObj, playCurTime, realTimeCurrentFrameIndexes, addtive);
  5826. }
  5827. _evaluateFrameNodeVector3DatasRealTime(keyFrames, frameIndex, isEnd, playCurTime, outDatas) {
  5828. if (frameIndex !== -1) {
  5829. var frame = keyFrames[frameIndex];
  5830. if (isEnd) {
  5831. var frameData = frame.value;
  5832. outDatas.x = frameData.x;
  5833. outDatas.y = frameData.y;
  5834. outDatas.z = frameData.z;
  5835. }
  5836. else {
  5837. var nextKeyFrame = keyFrames[frameIndex + 1];
  5838. var t;
  5839. var startTime = frame.time;
  5840. var d = nextKeyFrame.time - startTime;
  5841. if (d !== 0)
  5842. t = (playCurTime - startTime) / d;
  5843. else
  5844. t = 0;
  5845. this._hermiteInterpolateVector3(frame, nextKeyFrame, t, d, outDatas);
  5846. }
  5847. }
  5848. else {
  5849. var firstFrameDatas = keyFrames[0].value;
  5850. outDatas.x = firstFrameDatas.x;
  5851. outDatas.y = firstFrameDatas.y;
  5852. outDatas.z = firstFrameDatas.z;
  5853. }
  5854. }
  5855. _evaluateFrameNodeQuaternionDatasRealTime(keyFrames, frameIndex, isEnd, playCurTime, outDatas) {
  5856. if (frameIndex !== -1) {
  5857. var frame = keyFrames[frameIndex];
  5858. if (isEnd) {
  5859. var frameData = frame.value;
  5860. outDatas.x = frameData.x;
  5861. outDatas.y = frameData.y;
  5862. outDatas.z = frameData.z;
  5863. outDatas.w = frameData.w;
  5864. }
  5865. else {
  5866. var nextKeyFrame = keyFrames[frameIndex + 1];
  5867. var t;
  5868. var startTime = frame.time;
  5869. var d = nextKeyFrame.time - startTime;
  5870. if (d !== 0)
  5871. t = (playCurTime - startTime) / d;
  5872. else
  5873. t = 0;
  5874. this._hermiteInterpolateQuaternion(frame, nextKeyFrame, t, d, outDatas);
  5875. }
  5876. }
  5877. else {
  5878. var firstFrameDatas = keyFrames[0].value;
  5879. outDatas.x = firstFrameDatas.x;
  5880. outDatas.y = firstFrameDatas.y;
  5881. outDatas.z = firstFrameDatas.z;
  5882. outDatas.w = firstFrameDatas.w;
  5883. }
  5884. }
  5885. _binarySearchEventIndex(time) {
  5886. var start = 0;
  5887. var end = this._animationEvents.length - 1;
  5888. var mid;
  5889. while (start <= end) {
  5890. mid = Math.floor((start + end) / 2);
  5891. var midValue = this._animationEvents[mid].time;
  5892. if (midValue == time)
  5893. return mid;
  5894. else if (midValue > time)
  5895. end = mid - 1;
  5896. else
  5897. start = mid + 1;
  5898. }
  5899. return start;
  5900. }
  5901. addEvent(event) {
  5902. var index = this._binarySearchEventIndex(event.time);
  5903. this._animationEvents.splice(index, 0, event);
  5904. }
  5905. _disposeResource() {
  5906. this._nodes = null;
  5907. this._nodesMap = null;
  5908. }
  5909. }
  5910. AnimationClip.ANIMATIONCLIP = "ANIMATIONCLIP";
  5911. AnimationClip._tempQuaternion0 = new Quaternion();
  5912. class AnimatorPlayState {
  5913. constructor() {
  5914. this._currentState = null;
  5915. }
  5916. get normalizedTime() {
  5917. return this._normalizedTime;
  5918. }
  5919. get duration() {
  5920. return this._duration;
  5921. }
  5922. get animatorState() {
  5923. return this._currentState;
  5924. }
  5925. _resetPlayState(startTime, clipDuration) {
  5926. this._finish = false;
  5927. this._startPlayTime = startTime;
  5928. this._elapsedTime = startTime;
  5929. this._playEventIndex = 0;
  5930. this._lastIsFront = true;
  5931. this._normalizedTime = this._elapsedTime / clipDuration;
  5932. var playTime = this._normalizedTime % 1.0;
  5933. this._normalizedPlayTime = playTime < 0 ? playTime + 1.0 : playTime;
  5934. }
  5935. _cloneTo(dest) {
  5936. dest._finish = this._finish;
  5937. dest._startPlayTime = this._startPlayTime;
  5938. dest._elapsedTime = this._elapsedTime;
  5939. dest._normalizedTime = this._normalizedTime;
  5940. dest._normalizedPlayTime = this._normalizedPlayTime;
  5941. dest._playEventIndex = this._playEventIndex;
  5942. dest._lastIsFront = this._lastIsFront;
  5943. }
  5944. }
  5945. class AnimatorControllerLayer {
  5946. constructor(name) {
  5947. this._defaultState = null;
  5948. this._referenceCount = 0;
  5949. this._playType = -1;
  5950. this._crossDuration = -1;
  5951. this._crossMark = 0;
  5952. this._crossNodesOwnersCount = 0;
  5953. this._crossNodesOwners = [];
  5954. this._crossNodesOwnersIndicesMap = {};
  5955. this._srcCrossClipNodeIndices = [];
  5956. this._destCrossClipNodeIndices = [];
  5957. this._statesMap = {};
  5958. this._states = [];
  5959. this._playStateInfo = new AnimatorPlayState();
  5960. this._crossPlayStateInfo = new AnimatorPlayState();
  5961. this.blendingMode = AnimatorControllerLayer.BLENDINGMODE_OVERRIDE;
  5962. this.defaultWeight = 1.0;
  5963. this.playOnWake = true;
  5964. this.name = name;
  5965. }
  5966. get defaultState() {
  5967. return this._defaultState;
  5968. }
  5969. set defaultState(value) {
  5970. this._defaultState = value;
  5971. this._statesMap[value.name] = value;
  5972. }
  5973. _removeClip(clipStateInfos, statesMap, index, state) {
  5974. var clip = state._clip;
  5975. var clipStateInfo = clipStateInfos[index];
  5976. clipStateInfos.splice(index, 1);
  5977. delete statesMap[state.name];
  5978. if (this._animator) {
  5979. var frameNodes = clip._nodes;
  5980. var nodeOwners = clipStateInfo._nodeOwners;
  5981. clip._removeReference();
  5982. for (var i = 0, n = frameNodes.count; i < n; i++)
  5983. this._animator._removeKeyframeNodeOwner(nodeOwners, frameNodes.getNodeByIndex(i));
  5984. }
  5985. }
  5986. _getReferenceCount() {
  5987. return this._referenceCount;
  5988. }
  5989. _addReference(count = 1) {
  5990. for (var i = 0, n = this._states.length; i < n; i++)
  5991. this._states[i]._addReference(count);
  5992. this._referenceCount += count;
  5993. }
  5994. _removeReference(count = 1) {
  5995. for (var i = 0, n = this._states.length; i < n; i++)
  5996. this._states[i]._removeReference(count);
  5997. this._referenceCount -= count;
  5998. }
  5999. _clearReference() {
  6000. this._removeReference(-this._referenceCount);
  6001. }
  6002. getCurrentPlayState() {
  6003. return this._playStateInfo;
  6004. }
  6005. getAnimatorState(name) {
  6006. var state = this._statesMap[name];
  6007. return state ? state : null;
  6008. }
  6009. addState(state) {
  6010. var stateName = state.name;
  6011. if (this._statesMap[stateName]) {
  6012. throw "AnimatorControllerLayer:this stat's name has exist.";
  6013. }
  6014. else {
  6015. this._statesMap[stateName] = state;
  6016. this._states.push(state);
  6017. if (this._animator) {
  6018. state._clip._addReference();
  6019. this._animator._getOwnersByClip(state);
  6020. }
  6021. }
  6022. }
  6023. removeState(state) {
  6024. var states = this._states;
  6025. var index = -1;
  6026. for (var i = 0, n = states.length; i < n; i++) {
  6027. if (states[i] === state) {
  6028. index = i;
  6029. break;
  6030. }
  6031. }
  6032. if (index !== -1)
  6033. this._removeClip(states, this._statesMap, index, state);
  6034. }
  6035. destroy() {
  6036. this._clearReference();
  6037. this._statesMap = null;
  6038. this._states = null;
  6039. this._playStateInfo = null;
  6040. this._crossPlayStateInfo = null;
  6041. this._defaultState = null;
  6042. }
  6043. cloneTo(destObject) {
  6044. var dest = destObject;
  6045. dest.name = this.name;
  6046. dest.blendingMode = this.blendingMode;
  6047. dest.defaultWeight = this.defaultWeight;
  6048. dest.playOnWake = this.playOnWake;
  6049. }
  6050. clone() {
  6051. var dest = new AnimatorControllerLayer(this.name);
  6052. this.cloneTo(dest);
  6053. return dest;
  6054. }
  6055. }
  6056. AnimatorControllerLayer.BLENDINGMODE_OVERRIDE = 0;
  6057. AnimatorControllerLayer.BLENDINGMODE_ADDTIVE = 1;
  6058. class AnimatorState {
  6059. constructor() {
  6060. this._referenceCount = 0;
  6061. this._clip = null;
  6062. this._nodeOwners = [];
  6063. this._currentFrameIndices = null;
  6064. this._realtimeDatas = [];
  6065. this._scripts = null;
  6066. this.speed = 1.0;
  6067. this.clipStart = 0.0;
  6068. this.clipEnd = 1.0;
  6069. }
  6070. get clip() {
  6071. return this._clip;
  6072. }
  6073. set clip(value) {
  6074. if (this._clip !== value) {
  6075. if (this._clip)
  6076. (this._referenceCount > 0) && (this._clip._removeReference(this._referenceCount));
  6077. if (value) {
  6078. var realtimeDatas = this._realtimeDatas;
  6079. var clipNodes = value._nodes;
  6080. var count = clipNodes.count;
  6081. this._currentFrameIndices = new Int16Array(count);
  6082. this._resetFrameIndices();
  6083. (this._referenceCount > 0) && (value._addReference(this._referenceCount));
  6084. this._realtimeDatas.length = count;
  6085. for (var i = 0; i < count; i++) {
  6086. switch (clipNodes.getNodeByIndex(i).type) {
  6087. case 0:
  6088. break;
  6089. case 1:
  6090. case 3:
  6091. case 4:
  6092. realtimeDatas[i] = new Vector3();
  6093. break;
  6094. case 2:
  6095. realtimeDatas[i] = new Quaternion();
  6096. break;
  6097. default:
  6098. throw "AnimationClipParser04:unknown type.";
  6099. }
  6100. }
  6101. }
  6102. this._clip = value;
  6103. }
  6104. }
  6105. _getReferenceCount() {
  6106. return this._referenceCount;
  6107. }
  6108. _addReference(count = 1) {
  6109. (this._clip) && (this._clip._addReference(count));
  6110. this._referenceCount += count;
  6111. }
  6112. _removeReference(count = 1) {
  6113. (this._clip) && (this._clip._removeReference(count));
  6114. this._referenceCount -= count;
  6115. }
  6116. _clearReference() {
  6117. this._removeReference(-this._referenceCount);
  6118. }
  6119. _resetFrameIndices() {
  6120. for (var i = 0, n = this._currentFrameIndices.length; i < n; i++)
  6121. this._currentFrameIndices[i] = -1;
  6122. }
  6123. addScript(type) {
  6124. var script = new type();
  6125. this._scripts = this._scripts || [];
  6126. this._scripts.push(script);
  6127. return script;
  6128. }
  6129. getScript(type) {
  6130. if (this._scripts) {
  6131. for (var i = 0, n = this._scripts.length; i < n; i++) {
  6132. var script = this._scripts[i];
  6133. if (script instanceof type)
  6134. return script;
  6135. }
  6136. }
  6137. return null;
  6138. }
  6139. getScripts(type) {
  6140. var coms;
  6141. if (this._scripts) {
  6142. for (var i = 0, n = this._scripts.length; i < n; i++) {
  6143. var script = this._scripts[i];
  6144. if (script instanceof type) {
  6145. coms = coms || [];
  6146. coms.push(script);
  6147. }
  6148. }
  6149. }
  6150. return coms;
  6151. }
  6152. cloneTo(destObject) {
  6153. var dest = destObject;
  6154. dest.name = this.name;
  6155. dest.speed = this.speed;
  6156. dest.clipStart = this.clipStart;
  6157. dest.clipEnd = this.clipEnd;
  6158. dest.clip = this._clip;
  6159. }
  6160. clone() {
  6161. var dest = new AnimatorState();
  6162. this.cloneTo(dest);
  6163. return dest;
  6164. }
  6165. }
  6166. class KeyframeNodeOwner {
  6167. constructor() {
  6168. this.indexInList = -1;
  6169. this.referenceCount = 0;
  6170. this.updateMark = -1;
  6171. this.type = -1;
  6172. this.fullPath = null;
  6173. this.propertyOwner = null;
  6174. this.property = null;
  6175. this.defaultValue = null;
  6176. this.value = null;
  6177. this.crossFixedValue = null;
  6178. }
  6179. saveCrossFixedValue() {
  6180. var pro = this.propertyOwner;
  6181. if (pro) {
  6182. switch (this.type) {
  6183. case 0:
  6184. this.crossFixedValue = this.value;
  6185. break;
  6186. case 1:
  6187. case 3:
  6188. case 4:
  6189. this.value.cloneTo(this.crossFixedValue);
  6190. break;
  6191. case 2:
  6192. this.value.cloneTo(this.crossFixedValue);
  6193. break;
  6194. default:
  6195. throw "Animator:unknown type.";
  6196. }
  6197. }
  6198. }
  6199. }
  6200. class Animator extends Laya.Component {
  6201. constructor() {
  6202. super();
  6203. this._keyframeNodeOwners = [];
  6204. this._linkAvatarSpritesData = {};
  6205. this._linkAvatarSprites = [];
  6206. this._renderableSprites = [];
  6207. this.cullingMode = Animator.CULLINGMODE_CULLCOMPLETELY;
  6208. this._controllerLayers = [];
  6209. this._linkSprites = {};
  6210. this._speed = 1.0;
  6211. this._keyframeNodeOwnerMap = {};
  6212. this._updateMark = 0;
  6213. }
  6214. static _update(scene) {
  6215. var pool = scene._animatorPool;
  6216. var elements = pool.elements;
  6217. for (var i = 0, n = pool.length; i < n; i++) {
  6218. var animator = elements[i];
  6219. (animator && animator.enabled) && (animator._update());
  6220. }
  6221. }
  6222. get speed() {
  6223. return this._speed;
  6224. }
  6225. set speed(value) {
  6226. this._speed = value;
  6227. }
  6228. _linkToSprites(linkSprites) {
  6229. for (var k in linkSprites) {
  6230. var nodeOwner = this.owner;
  6231. var path = linkSprites[k];
  6232. for (var j = 0, m = path.length; j < m; j++) {
  6233. var p = path[j];
  6234. if (p === "") {
  6235. break;
  6236. }
  6237. else {
  6238. nodeOwner = nodeOwner.getChildByName(p);
  6239. if (!nodeOwner)
  6240. break;
  6241. }
  6242. }
  6243. (nodeOwner) && (this.linkSprite3DToAvatarNode(k, nodeOwner));
  6244. }
  6245. }
  6246. _addKeyframeNodeOwner(clipOwners, node, propertyOwner) {
  6247. var nodeIndex = node._indexInList;
  6248. var fullPath = node.fullPath;
  6249. var keyframeNodeOwner = this._keyframeNodeOwnerMap[fullPath];
  6250. if (keyframeNodeOwner) {
  6251. keyframeNodeOwner.referenceCount++;
  6252. clipOwners[nodeIndex] = keyframeNodeOwner;
  6253. }
  6254. else {
  6255. var property = propertyOwner;
  6256. for (var i = 0, n = node.propertyCount; i < n; i++) {
  6257. property = property[node.getPropertyByIndex(i)];
  6258. if (!property)
  6259. break;
  6260. }
  6261. keyframeNodeOwner = this._keyframeNodeOwnerMap[fullPath] = new KeyframeNodeOwner();
  6262. keyframeNodeOwner.fullPath = fullPath;
  6263. keyframeNodeOwner.indexInList = this._keyframeNodeOwners.length;
  6264. keyframeNodeOwner.referenceCount = 1;
  6265. keyframeNodeOwner.propertyOwner = propertyOwner;
  6266. var propertyCount = node.propertyCount;
  6267. var propertys = [];
  6268. for (i = 0; i < propertyCount; i++)
  6269. propertys[i] = node.getPropertyByIndex(i);
  6270. keyframeNodeOwner.property = propertys;
  6271. keyframeNodeOwner.type = node.type;
  6272. if (property) {
  6273. if (node.type === 0) {
  6274. keyframeNodeOwner.defaultValue = property;
  6275. }
  6276. else {
  6277. var defaultValue = new property.constructor();
  6278. property.cloneTo(defaultValue);
  6279. keyframeNodeOwner.defaultValue = defaultValue;
  6280. keyframeNodeOwner.value = new property.constructor();
  6281. keyframeNodeOwner.crossFixedValue = new property.constructor();
  6282. }
  6283. }
  6284. this._keyframeNodeOwners.push(keyframeNodeOwner);
  6285. clipOwners[nodeIndex] = keyframeNodeOwner;
  6286. }
  6287. }
  6288. _removeKeyframeNodeOwner(nodeOwners, node) {
  6289. var fullPath = node.fullPath;
  6290. var keyframeNodeOwner = this._keyframeNodeOwnerMap[fullPath];
  6291. if (keyframeNodeOwner) {
  6292. keyframeNodeOwner.referenceCount--;
  6293. if (keyframeNodeOwner.referenceCount === 0) {
  6294. delete this._keyframeNodeOwnerMap[fullPath];
  6295. this._keyframeNodeOwners.splice(this._keyframeNodeOwners.indexOf(keyframeNodeOwner), 1);
  6296. }
  6297. nodeOwners[node._indexInList] = null;
  6298. }
  6299. }
  6300. _getOwnersByClip(clipStateInfo) {
  6301. var frameNodes = clipStateInfo._clip._nodes;
  6302. var frameNodesCount = frameNodes.count;
  6303. var nodeOwners = clipStateInfo._nodeOwners;
  6304. nodeOwners.length = frameNodesCount;
  6305. for (var i = 0; i < frameNodesCount; i++) {
  6306. var node = frameNodes.getNodeByIndex(i);
  6307. var property = this._avatar ? this._avatarNodeMap[this._avatar._rootNode.name] : this.owner;
  6308. for (var j = 0, m = node.ownerPathCount; j < m; j++) {
  6309. var ownPat = node.getOwnerPathByIndex(j);
  6310. if (ownPat === "") {
  6311. break;
  6312. }
  6313. else {
  6314. property = property.getChildByName(ownPat);
  6315. if (!property)
  6316. break;
  6317. }
  6318. }
  6319. if (property) {
  6320. var propertyOwner = node.propertyOwner;
  6321. (propertyOwner) && (property = property[propertyOwner]);
  6322. property && this._addKeyframeNodeOwner(nodeOwners, node, property);
  6323. }
  6324. }
  6325. }
  6326. _updatePlayer(animatorState, playState, elapsedTime, islooping) {
  6327. var clipDuration = animatorState._clip._duration * (animatorState.clipEnd - animatorState.clipStart);
  6328. var lastElapsedTime = playState._elapsedTime;
  6329. var elapsedPlaybackTime = lastElapsedTime + elapsedTime;
  6330. playState._lastElapsedTime = lastElapsedTime;
  6331. playState._elapsedTime = elapsedPlaybackTime;
  6332. var normalizedTime = elapsedPlaybackTime / clipDuration;
  6333. playState._normalizedTime = normalizedTime;
  6334. var playTime = normalizedTime % 1.0;
  6335. playState._normalizedPlayTime = playTime < 0 ? playTime + 1.0 : playTime;
  6336. playState._duration = clipDuration;
  6337. var scripts = animatorState._scripts;
  6338. if ((!islooping && elapsedPlaybackTime >= clipDuration)) {
  6339. playState._finish = true;
  6340. playState._elapsedTime = clipDuration;
  6341. playState._normalizedPlayTime = 1.0;
  6342. if (scripts) {
  6343. for (var i = 0, n = scripts.length; i < n; i++)
  6344. scripts[i].onStateExit();
  6345. }
  6346. return;
  6347. }
  6348. if (scripts) {
  6349. for (i = 0, n = scripts.length; i < n; i++)
  6350. scripts[i].onStateUpdate();
  6351. }
  6352. }
  6353. _eventScript(scripts, events, eventIndex, endTime, front) {
  6354. if (front) {
  6355. for (var n = events.length; eventIndex < n; eventIndex++) {
  6356. var event = events[eventIndex];
  6357. if (event.time <= endTime) {
  6358. for (var j = 0, m = scripts.length; j < m; j++) {
  6359. var script = scripts[j];
  6360. var fun = script[event.eventName];
  6361. (fun) && (fun.apply(script, event.params));
  6362. }
  6363. }
  6364. else {
  6365. break;
  6366. }
  6367. }
  6368. }
  6369. else {
  6370. for (; eventIndex >= 0; eventIndex--) {
  6371. event = events[eventIndex];
  6372. if (event.time >= endTime) {
  6373. for (j = 0, m = scripts.length; j < m; j++) {
  6374. script = scripts[j];
  6375. fun = script[event.eventName];
  6376. (fun) && (fun.apply(script, event.params));
  6377. }
  6378. }
  6379. else {
  6380. break;
  6381. }
  6382. }
  6383. }
  6384. return eventIndex;
  6385. }
  6386. _updateEventScript(stateInfo, playStateInfo) {
  6387. var scripts = this.owner._scripts;
  6388. if (scripts) {
  6389. var clip = stateInfo._clip;
  6390. var events = clip._animationEvents;
  6391. var clipDuration = clip._duration;
  6392. var elapsedTime = playStateInfo._elapsedTime;
  6393. var time = elapsedTime % clipDuration;
  6394. var loopCount = Math.abs(Math.floor(elapsedTime / clipDuration) - Math.floor(playStateInfo._lastElapsedTime / clipDuration));
  6395. var frontPlay = playStateInfo._elapsedTime >= playStateInfo._lastElapsedTime;
  6396. if (playStateInfo._lastIsFront !== frontPlay) {
  6397. if (frontPlay)
  6398. playStateInfo._playEventIndex++;
  6399. else
  6400. playStateInfo._playEventIndex--;
  6401. playStateInfo._lastIsFront = frontPlay;
  6402. }
  6403. var preEventIndex = playStateInfo._playEventIndex;
  6404. if (frontPlay) {
  6405. var newEventIndex = this._eventScript(scripts, events, playStateInfo._playEventIndex, loopCount > 0 ? clipDuration : time, true);
  6406. (preEventIndex === playStateInfo._playEventIndex) && (playStateInfo._playEventIndex = newEventIndex);
  6407. for (var i = 0, n = loopCount - 1; i < n; i++)
  6408. this._eventScript(scripts, events, 0, clipDuration, true);
  6409. (loopCount > 0 && time > 0) && (playStateInfo._playEventIndex = this._eventScript(scripts, events, 0, time, true));
  6410. }
  6411. else {
  6412. var newEventIndex = this._eventScript(scripts, events, playStateInfo._playEventIndex, loopCount > 0 ? 0 : time, false);
  6413. (preEventIndex === playStateInfo._playEventIndex) && (playStateInfo._playEventIndex = newEventIndex);
  6414. var eventIndex = events.length - 1;
  6415. for (i = 0, n = loopCount - 1; i < n; i++)
  6416. this._eventScript(scripts, events, eventIndex, 0, false);
  6417. (loopCount > 0 && time > 0) && (playStateInfo._playEventIndex = this._eventScript(scripts, events, eventIndex, time, false));
  6418. }
  6419. }
  6420. }
  6421. _updateClipDatas(animatorState, addtive, playStateInfo, scale) {
  6422. var clip = animatorState._clip;
  6423. var clipDuration = clip._duration;
  6424. var curPlayTime = animatorState.clipStart * clipDuration + playStateInfo._normalizedPlayTime * playStateInfo._duration;
  6425. var currentFrameIndices = animatorState._currentFrameIndices;
  6426. var frontPlay = playStateInfo._elapsedTime > playStateInfo._lastElapsedTime;
  6427. clip._evaluateClipDatasRealTime(clip._nodes, curPlayTime, currentFrameIndices, addtive, frontPlay, animatorState._realtimeDatas);
  6428. }
  6429. _applyFloat(pro, proName, nodeOwner, additive, weight, isFirstLayer, data) {
  6430. if (nodeOwner.updateMark === this._updateMark) {
  6431. if (additive) {
  6432. pro[proName] += weight * data;
  6433. }
  6434. else {
  6435. var oriValue = pro[proName];
  6436. pro[proName] = oriValue + weight * (data - oriValue);
  6437. }
  6438. }
  6439. else {
  6440. if (isFirstLayer) {
  6441. if (additive)
  6442. pro[proName] = nodeOwner.defaultValue + data;
  6443. else
  6444. pro[proName] = data;
  6445. }
  6446. else {
  6447. if (additive) {
  6448. pro[proName] = nodeOwner.defaultValue + weight * (data);
  6449. }
  6450. else {
  6451. var defValue = nodeOwner.defaultValue;
  6452. pro[proName] = defValue + weight * (data - defValue);
  6453. }
  6454. }
  6455. }
  6456. }
  6457. _applyPositionAndRotationEuler(nodeOwner, additive, weight, isFirstLayer, data, out) {
  6458. if (nodeOwner.updateMark === this._updateMark) {
  6459. if (additive) {
  6460. out.x += weight * data.x;
  6461. out.y += weight * data.y;
  6462. out.z += weight * data.z;
  6463. }
  6464. else {
  6465. var oriX = out.x;
  6466. var oriY = out.y;
  6467. var oriZ = out.z;
  6468. out.x = oriX + weight * (data.x - oriX);
  6469. out.y = oriY + weight * (data.y - oriY);
  6470. out.z = oriZ + weight * (data.z - oriZ);
  6471. }
  6472. }
  6473. else {
  6474. if (isFirstLayer) {
  6475. if (additive) {
  6476. var defValue = nodeOwner.defaultValue;
  6477. out.x = defValue.x + data.x;
  6478. out.y = defValue.y + data.y;
  6479. out.z = defValue.z + data.z;
  6480. }
  6481. else {
  6482. out.x = data.x;
  6483. out.y = data.y;
  6484. out.z = data.z;
  6485. }
  6486. }
  6487. else {
  6488. defValue = nodeOwner.defaultValue;
  6489. if (additive) {
  6490. out.x = defValue.x + weight * data.x;
  6491. out.y = defValue.y + weight * data.y;
  6492. out.z = defValue.z + weight * data.z;
  6493. }
  6494. else {
  6495. var defX = defValue.x;
  6496. var defY = defValue.y;
  6497. var defZ = defValue.z;
  6498. out.x = defX + weight * (data.x - defX);
  6499. out.y = defY + weight * (data.y - defY);
  6500. out.z = defZ + weight * (data.z - defZ);
  6501. }
  6502. }
  6503. }
  6504. }
  6505. _applyRotation(nodeOwner, additive, weight, isFirstLayer, clipRot, localRotation) {
  6506. if (nodeOwner.updateMark === this._updateMark) {
  6507. if (additive) {
  6508. var tempQuat = Animator._tempQuaternion1;
  6509. Utils3D.quaternionWeight(clipRot, weight, tempQuat);
  6510. tempQuat.normalize(tempQuat);
  6511. Quaternion.multiply(localRotation, tempQuat, localRotation);
  6512. }
  6513. else {
  6514. Quaternion.lerp(localRotation, clipRot, weight, localRotation);
  6515. }
  6516. }
  6517. else {
  6518. if (isFirstLayer) {
  6519. if (additive) {
  6520. var defaultRot = nodeOwner.defaultValue;
  6521. Quaternion.multiply(defaultRot, clipRot, localRotation);
  6522. }
  6523. else {
  6524. localRotation.x = clipRot.x;
  6525. localRotation.y = clipRot.y;
  6526. localRotation.z = clipRot.z;
  6527. localRotation.w = clipRot.w;
  6528. }
  6529. }
  6530. else {
  6531. defaultRot = nodeOwner.defaultValue;
  6532. if (additive) {
  6533. tempQuat = Animator._tempQuaternion1;
  6534. Utils3D.quaternionWeight(clipRot, weight, tempQuat);
  6535. tempQuat.normalize(tempQuat);
  6536. Quaternion.multiply(defaultRot, tempQuat, localRotation);
  6537. }
  6538. else {
  6539. Quaternion.lerp(defaultRot, clipRot, weight, localRotation);
  6540. }
  6541. }
  6542. }
  6543. }
  6544. _applyScale(nodeOwner, additive, weight, isFirstLayer, clipSca, localScale) {
  6545. if (nodeOwner.updateMark === this._updateMark) {
  6546. if (additive) {
  6547. var scale = Animator._tempVector31;
  6548. Utils3D.scaleWeight(clipSca, weight, scale);
  6549. localScale.x = localScale.x * scale.x;
  6550. localScale.y = localScale.y * scale.y;
  6551. localScale.z = localScale.z * scale.z;
  6552. }
  6553. else {
  6554. Utils3D.scaleBlend(localScale, clipSca, weight, localScale);
  6555. }
  6556. }
  6557. else {
  6558. if (isFirstLayer) {
  6559. if (additive) {
  6560. var defaultSca = nodeOwner.defaultValue;
  6561. localScale.x = defaultSca.x * clipSca.x;
  6562. localScale.y = defaultSca.y * clipSca.y;
  6563. localScale.z = defaultSca.z * clipSca.z;
  6564. }
  6565. else {
  6566. localScale.x = clipSca.x;
  6567. localScale.y = clipSca.y;
  6568. localScale.z = clipSca.z;
  6569. }
  6570. }
  6571. else {
  6572. defaultSca = nodeOwner.defaultValue;
  6573. if (additive) {
  6574. scale = Animator._tempVector31;
  6575. Utils3D.scaleWeight(clipSca, weight, scale);
  6576. localScale.x = defaultSca.x * scale.x;
  6577. localScale.y = defaultSca.y * scale.y;
  6578. localScale.z = defaultSca.z * scale.z;
  6579. }
  6580. else {
  6581. Utils3D.scaleBlend(defaultSca, clipSca, weight, localScale);
  6582. }
  6583. }
  6584. }
  6585. }
  6586. _applyCrossData(nodeOwner, additive, weight, isFirstLayer, srcValue, desValue, crossWeight) {
  6587. var pro = nodeOwner.propertyOwner;
  6588. if (pro) {
  6589. switch (nodeOwner.type) {
  6590. case 0:
  6591. var proPat = nodeOwner.property;
  6592. var m = proPat.length - 1;
  6593. for (var j = 0; j < m; j++) {
  6594. pro = pro[proPat[j]];
  6595. if (!pro)
  6596. break;
  6597. }
  6598. var crossValue = srcValue + crossWeight * (desValue - srcValue);
  6599. nodeOwner.value = crossValue;
  6600. pro && this._applyFloat(pro, proPat[m], nodeOwner, additive, weight, isFirstLayer, crossValue);
  6601. break;
  6602. case 1:
  6603. var localPos = pro.localPosition;
  6604. var position = nodeOwner.value;
  6605. var srcX = srcValue.x, srcY = srcValue.y, srcZ = srcValue.z;
  6606. position.x = srcX + crossWeight * (desValue.x - srcX);
  6607. position.y = srcY + crossWeight * (desValue.y - srcY);
  6608. position.z = srcZ + crossWeight * (desValue.z - srcZ);
  6609. this._applyPositionAndRotationEuler(nodeOwner, additive, weight, isFirstLayer, position, localPos);
  6610. pro.localPosition = localPos;
  6611. break;
  6612. case 2:
  6613. var localRot = pro.localRotation;
  6614. var rotation = nodeOwner.value;
  6615. Quaternion.lerp(srcValue, desValue, crossWeight, rotation);
  6616. this._applyRotation(nodeOwner, additive, weight, isFirstLayer, rotation, localRot);
  6617. pro.localRotation = localRot;
  6618. break;
  6619. case 3:
  6620. var localSca = pro.localScale;
  6621. var scale = nodeOwner.value;
  6622. Utils3D.scaleBlend(srcValue, desValue, crossWeight, scale);
  6623. this._applyScale(nodeOwner, additive, weight, isFirstLayer, scale, localSca);
  6624. pro.localScale = localSca;
  6625. break;
  6626. case 4:
  6627. var localEuler = pro.localRotationEuler;
  6628. var rotationEuler = nodeOwner.value;
  6629. srcX = srcValue.x, srcY = srcValue.y, srcZ = srcValue.z;
  6630. rotationEuler.x = srcX + crossWeight * (desValue.x - srcX);
  6631. rotationEuler.y = srcY + crossWeight * (desValue.y - srcY);
  6632. rotationEuler.z = srcZ + crossWeight * (desValue.z - srcZ);
  6633. this._applyPositionAndRotationEuler(nodeOwner, additive, weight, isFirstLayer, rotationEuler, localEuler);
  6634. pro.localRotationEuler = localEuler;
  6635. break;
  6636. }
  6637. nodeOwner.updateMark = this._updateMark;
  6638. }
  6639. }
  6640. _setClipDatasToNode(stateInfo, additive, weight, isFirstLayer) {
  6641. var realtimeDatas = stateInfo._realtimeDatas;
  6642. var nodes = stateInfo._clip._nodes;
  6643. var nodeOwners = stateInfo._nodeOwners;
  6644. for (var i = 0, n = nodes.count; i < n; i++) {
  6645. var nodeOwner = nodeOwners[i];
  6646. if (nodeOwner) {
  6647. var pro = nodeOwner.propertyOwner;
  6648. if (pro) {
  6649. switch (nodeOwner.type) {
  6650. case 0:
  6651. var proPat = nodeOwner.property;
  6652. var m = proPat.length - 1;
  6653. for (var j = 0; j < m; j++) {
  6654. pro = pro[proPat[j]];
  6655. if (!pro)
  6656. break;
  6657. }
  6658. pro && this._applyFloat(pro, proPat[m], nodeOwner, additive, weight, isFirstLayer, realtimeDatas[i]);
  6659. break;
  6660. case 1:
  6661. var localPos = pro.localPosition;
  6662. this._applyPositionAndRotationEuler(nodeOwner, additive, weight, isFirstLayer, realtimeDatas[i], localPos);
  6663. pro.localPosition = localPos;
  6664. break;
  6665. case 2:
  6666. var localRot = pro.localRotation;
  6667. this._applyRotation(nodeOwner, additive, weight, isFirstLayer, realtimeDatas[i], localRot);
  6668. pro.localRotation = localRot;
  6669. break;
  6670. case 3:
  6671. var localSca = pro.localScale;
  6672. this._applyScale(nodeOwner, additive, weight, isFirstLayer, realtimeDatas[i], localSca);
  6673. pro.localScale = localSca;
  6674. break;
  6675. case 4:
  6676. var localEuler = pro.localRotationEuler;
  6677. this._applyPositionAndRotationEuler(nodeOwner, additive, weight, isFirstLayer, realtimeDatas[i], localEuler);
  6678. pro.localRotationEuler = localEuler;
  6679. break;
  6680. }
  6681. nodeOwner.updateMark = this._updateMark;
  6682. }
  6683. }
  6684. }
  6685. }
  6686. _setCrossClipDatasToNode(controllerLayer, srcState, destState, crossWeight, isFirstLayer) {
  6687. var nodeOwners = controllerLayer._crossNodesOwners;
  6688. var ownerCount = controllerLayer._crossNodesOwnersCount;
  6689. var additive = controllerLayer.blendingMode !== AnimatorControllerLayer.BLENDINGMODE_OVERRIDE;
  6690. var weight = controllerLayer.defaultWeight;
  6691. var destRealtimeDatas = destState._realtimeDatas;
  6692. var destDataIndices = controllerLayer._destCrossClipNodeIndices;
  6693. var destNodeOwners = destState._nodeOwners;
  6694. var srcRealtimeDatas = srcState._realtimeDatas;
  6695. var srcDataIndices = controllerLayer._srcCrossClipNodeIndices;
  6696. var srcNodeOwners = srcState._nodeOwners;
  6697. for (var i = 0; i < ownerCount; i++) {
  6698. var nodeOwner = nodeOwners[i];
  6699. if (nodeOwner) {
  6700. var srcIndex = srcDataIndices[i];
  6701. var destIndex = destDataIndices[i];
  6702. var srcValue = srcIndex !== -1 ? srcRealtimeDatas[srcIndex] : destNodeOwners[destIndex].defaultValue;
  6703. var desValue = destIndex !== -1 ? destRealtimeDatas[destIndex] : srcNodeOwners[srcIndex].defaultValue;
  6704. this._applyCrossData(nodeOwner, additive, weight, isFirstLayer, srcValue, desValue, crossWeight);
  6705. }
  6706. }
  6707. }
  6708. _setFixedCrossClipDatasToNode(controllerLayer, destState, crossWeight, isFirstLayer) {
  6709. var nodeOwners = controllerLayer._crossNodesOwners;
  6710. var ownerCount = controllerLayer._crossNodesOwnersCount;
  6711. var additive = controllerLayer.blendingMode !== AnimatorControllerLayer.BLENDINGMODE_OVERRIDE;
  6712. var weight = controllerLayer.defaultWeight;
  6713. var destRealtimeDatas = destState._realtimeDatas;
  6714. var destDataIndices = controllerLayer._destCrossClipNodeIndices;
  6715. for (var i = 0; i < ownerCount; i++) {
  6716. var nodeOwner = nodeOwners[i];
  6717. if (nodeOwner) {
  6718. var destIndex = destDataIndices[i];
  6719. var srcValue = nodeOwner.crossFixedValue;
  6720. var desValue = destIndex !== -1 ? destRealtimeDatas[destIndex] : nodeOwner.defaultValue;
  6721. this._applyCrossData(nodeOwner, additive, weight, isFirstLayer, srcValue, desValue, crossWeight);
  6722. }
  6723. }
  6724. }
  6725. _revertDefaultKeyframeNodes(clipStateInfo) {
  6726. var nodeOwners = clipStateInfo._nodeOwners;
  6727. for (var i = 0, n = nodeOwners.length; i < n; i++) {
  6728. var nodeOwner = nodeOwners[i];
  6729. if (nodeOwner) {
  6730. var pro = nodeOwner.propertyOwner;
  6731. if (pro) {
  6732. switch (nodeOwner.type) {
  6733. case 0:
  6734. var proPat = nodeOwner.property;
  6735. var m = proPat.length - 1;
  6736. for (var j = 0; j < m; j++) {
  6737. pro = pro[proPat[j]];
  6738. if (!pro)
  6739. break;
  6740. }
  6741. pro[proPat[m]] = nodeOwner.defaultValue;
  6742. break;
  6743. case 1:
  6744. var locPos = pro.localPosition;
  6745. var def = nodeOwner.defaultValue;
  6746. locPos.x = def.x;
  6747. locPos.y = def.y;
  6748. locPos.z = def.z;
  6749. pro.localPosition = locPos;
  6750. break;
  6751. case 2:
  6752. var locRot = pro.localRotation;
  6753. var defQua = nodeOwner.defaultValue;
  6754. locRot.x = defQua.x;
  6755. locRot.y = defQua.y;
  6756. locRot.z = defQua.z;
  6757. locRot.w = defQua.w;
  6758. pro.localRotation = locRot;
  6759. break;
  6760. case 3:
  6761. var locSca = pro.localScale;
  6762. def = nodeOwner.defaultValue;
  6763. locSca.x = def.x;
  6764. locSca.y = def.y;
  6765. locSca.z = def.z;
  6766. pro.localScale = locSca;
  6767. break;
  6768. case 4:
  6769. var locEul = pro.localRotationEuler;
  6770. def = nodeOwner.defaultValue;
  6771. locEul.x = def.x;
  6772. locEul.y = def.y;
  6773. locEul.z = def.z;
  6774. pro.localRotationEuler = locEul;
  6775. break;
  6776. default:
  6777. throw "Animator:unknown type.";
  6778. }
  6779. }
  6780. }
  6781. }
  6782. }
  6783. _onAdded() {
  6784. var parent = this.owner._parent;
  6785. this.owner._setHierarchyAnimator(this, parent ? parent._hierarchyAnimator : null);
  6786. this.owner._changeAnimatorToLinkSprite3DNoAvatar(this, true, []);
  6787. }
  6788. _onDestroy() {
  6789. for (var i = 0, n = this._controllerLayers.length; i < n; i++)
  6790. this._controllerLayers[i]._removeReference();
  6791. var parent = this.owner._parent;
  6792. this.owner._clearHierarchyAnimator(this, parent ? parent._hierarchyAnimator : null);
  6793. }
  6794. _onEnable() {
  6795. this.owner._scene._animatorPool.add(this);
  6796. for (var i = 0, n = this._controllerLayers.length; i < n; i++) {
  6797. if (this._controllerLayers[i].playOnWake) {
  6798. var defaultClip = this.getDefaultState(i);
  6799. (defaultClip) && (this.play(null, i, 0));
  6800. }
  6801. }
  6802. }
  6803. _onDisable() {
  6804. this.owner._scene._animatorPool.remove(this);
  6805. }
  6806. _handleSpriteOwnersBySprite(isLink, path, sprite) {
  6807. for (var i = 0, n = this._controllerLayers.length; i < n; i++) {
  6808. var clipStateInfos = this._controllerLayers[i]._states;
  6809. for (var j = 0, m = clipStateInfos.length; j < m; j++) {
  6810. var clipStateInfo = clipStateInfos[j];
  6811. var clip = clipStateInfo._clip;
  6812. var nodePath = path.join("/");
  6813. var ownersNodes = clip._nodesMap[nodePath];
  6814. if (ownersNodes) {
  6815. var nodeOwners = clipStateInfo._nodeOwners;
  6816. for (var k = 0, p = ownersNodes.length; k < p; k++) {
  6817. if (isLink)
  6818. this._addKeyframeNodeOwner(nodeOwners, ownersNodes[k], sprite);
  6819. else
  6820. this._removeKeyframeNodeOwner(nodeOwners, ownersNodes[k]);
  6821. }
  6822. }
  6823. }
  6824. }
  6825. }
  6826. _parse(data) {
  6827. var avatarData = data.avatar;
  6828. if (avatarData) {
  6829. this.avatar = Laya.Loader.getRes(avatarData.path);
  6830. var linkSprites = avatarData.linkSprites;
  6831. this._linkSprites = linkSprites;
  6832. this._linkToSprites(linkSprites);
  6833. }
  6834. var clipPaths = data.clipPaths;
  6835. var play = data.playOnWake;
  6836. var layersData = data.layers;
  6837. for (var i = 0; i < layersData.length; i++) {
  6838. var layerData = layersData[i];
  6839. var animatorLayer = new AnimatorControllerLayer(layerData.name);
  6840. if (i === 0)
  6841. animatorLayer.defaultWeight = 1.0;
  6842. else
  6843. animatorLayer.defaultWeight = layerData.weight;
  6844. var blendingModeData = layerData.blendingMode;
  6845. (blendingModeData) && (animatorLayer.blendingMode = blendingModeData);
  6846. this.addControllerLayer(animatorLayer);
  6847. var states = layerData.states;
  6848. for (var j = 0, m = states.length; j < m; j++) {
  6849. var state = states[j];
  6850. var clipPath = state.clipPath;
  6851. if (clipPath) {
  6852. var name = state.name;
  6853. var motion;
  6854. motion = Laya.Loader.getRes(clipPath);
  6855. if (motion) {
  6856. var animatorState = new AnimatorState();
  6857. animatorState.name = name;
  6858. animatorState.clip = motion;
  6859. animatorLayer.addState(animatorState);
  6860. (j === 0) && (this.getControllerLayer(i).defaultState = animatorState);
  6861. }
  6862. }
  6863. }
  6864. (play !== undefined) && (animatorLayer.playOnWake = play);
  6865. }
  6866. var cullingModeData = data.cullingMode;
  6867. (cullingModeData !== undefined) && (this.cullingMode = cullingModeData);
  6868. }
  6869. _update() {
  6870. var timer = this.owner._scene.timer;
  6871. var delta = timer._delta / 1000.0;
  6872. if (this._speed === 0 || delta === 0)
  6873. return;
  6874. var needRender;
  6875. if (this.cullingMode === Animator.CULLINGMODE_CULLCOMPLETELY) {
  6876. needRender = false;
  6877. for (var i = 0, n = this._renderableSprites.length; i < n; i++) {
  6878. if (this._renderableSprites[i]._render.isRender) {
  6879. needRender = true;
  6880. break;
  6881. }
  6882. }
  6883. }
  6884. else {
  6885. needRender = true;
  6886. }
  6887. this._updateMark++;
  6888. var timerScale = timer.scale;
  6889. for (i = 0, n = this._controllerLayers.length; i < n; i++) {
  6890. var controllerLayer = this._controllerLayers[i];
  6891. var playStateInfo = controllerLayer._playStateInfo;
  6892. var crossPlayStateInfo = controllerLayer._crossPlayStateInfo;
  6893. addtive = controllerLayer.blendingMode !== AnimatorControllerLayer.BLENDINGMODE_OVERRIDE;
  6894. switch (controllerLayer._playType) {
  6895. case 0:
  6896. var animatorState = playStateInfo._currentState;
  6897. var clip = animatorState._clip;
  6898. var speed = this._speed * animatorState.speed;
  6899. var finish = playStateInfo._finish;
  6900. finish || this._updatePlayer(animatorState, playStateInfo, delta * speed, clip.islooping);
  6901. if (needRender) {
  6902. var addtive = controllerLayer.blendingMode !== AnimatorControllerLayer.BLENDINGMODE_OVERRIDE;
  6903. this._updateClipDatas(animatorState, addtive, playStateInfo, timerScale * speed);
  6904. this._setClipDatasToNode(animatorState, addtive, controllerLayer.defaultWeight, i === 0);
  6905. finish || this._updateEventScript(animatorState, playStateInfo);
  6906. }
  6907. break;
  6908. case 1:
  6909. animatorState = playStateInfo._currentState;
  6910. clip = animatorState._clip;
  6911. var crossState = controllerLayer._crossPlayState;
  6912. var crossClip = crossState._clip;
  6913. var crossDuratuion = controllerLayer._crossDuration;
  6914. var startPlayTime = crossPlayStateInfo._startPlayTime;
  6915. var crossClipDuration = crossClip._duration - startPlayTime;
  6916. var crossScale = crossDuratuion > crossClipDuration ? crossClipDuration / crossDuratuion : 1.0;
  6917. var crossSpeed = this._speed * crossState.speed;
  6918. this._updatePlayer(crossState, crossPlayStateInfo, delta * crossScale * crossSpeed, crossClip.islooping);
  6919. var crossWeight = ((crossPlayStateInfo._elapsedTime - startPlayTime) / crossScale) / crossDuratuion;
  6920. if (crossWeight >= 1.0) {
  6921. if (needRender) {
  6922. this._updateClipDatas(crossState, addtive, crossPlayStateInfo, timerScale * crossSpeed);
  6923. this._setClipDatasToNode(crossState, addtive, controllerLayer.defaultWeight, i === 0);
  6924. controllerLayer._playType = 0;
  6925. playStateInfo._currentState = crossState;
  6926. crossPlayStateInfo._cloneTo(playStateInfo);
  6927. }
  6928. }
  6929. else {
  6930. if (!playStateInfo._finish) {
  6931. speed = this._speed * animatorState.speed;
  6932. this._updatePlayer(animatorState, playStateInfo, delta * speed, clip.islooping);
  6933. if (needRender)
  6934. this._updateClipDatas(animatorState, addtive, playStateInfo, timerScale * speed);
  6935. }
  6936. if (needRender) {
  6937. this._updateClipDatas(crossState, addtive, crossPlayStateInfo, timerScale * crossScale * crossSpeed);
  6938. this._setCrossClipDatasToNode(controllerLayer, animatorState, crossState, crossWeight, i === 0);
  6939. }
  6940. }
  6941. if (needRender) {
  6942. this._updateEventScript(animatorState, playStateInfo);
  6943. this._updateEventScript(crossState, crossPlayStateInfo);
  6944. }
  6945. break;
  6946. case 2:
  6947. crossState = controllerLayer._crossPlayState;
  6948. crossClip = crossState._clip;
  6949. crossDuratuion = controllerLayer._crossDuration;
  6950. startPlayTime = crossPlayStateInfo._startPlayTime;
  6951. crossClipDuration = crossClip._duration - startPlayTime;
  6952. crossScale = crossDuratuion > crossClipDuration ? crossClipDuration / crossDuratuion : 1.0;
  6953. crossSpeed = this._speed * crossState.speed;
  6954. this._updatePlayer(crossState, crossPlayStateInfo, delta * crossScale * crossSpeed, crossClip.islooping);
  6955. if (needRender) {
  6956. crossWeight = ((crossPlayStateInfo._elapsedTime - startPlayTime) / crossScale) / crossDuratuion;
  6957. if (crossWeight >= 1.0) {
  6958. this._updateClipDatas(crossState, addtive, crossPlayStateInfo, timerScale * crossSpeed);
  6959. this._setClipDatasToNode(crossState, addtive, 1.0, i === 0);
  6960. controllerLayer._playType = 0;
  6961. playStateInfo._currentState = crossState;
  6962. crossPlayStateInfo._cloneTo(playStateInfo);
  6963. }
  6964. else {
  6965. this._updateClipDatas(crossState, addtive, crossPlayStateInfo, timerScale * crossScale * crossSpeed);
  6966. this._setFixedCrossClipDatasToNode(controllerLayer, crossState, crossWeight, i === 0);
  6967. }
  6968. this._updateEventScript(crossState, crossPlayStateInfo);
  6969. }
  6970. break;
  6971. }
  6972. }
  6973. if (needRender) {
  6974. if (this._avatar) {
  6975. this._updateAvatarNodesToSprite();
  6976. }
  6977. }
  6978. }
  6979. _cloneTo(dest) {
  6980. var animator = dest;
  6981. animator.avatar = this.avatar;
  6982. animator.cullingMode = this.cullingMode;
  6983. for (var i = 0, n = this._controllerLayers.length; i < n; i++) {
  6984. var controllLayer = this._controllerLayers[i];
  6985. animator.addControllerLayer(controllLayer.clone());
  6986. var animatorStates = controllLayer._states;
  6987. for (var j = 0, m = animatorStates.length; j < m; j++) {
  6988. var state = animatorStates[j].clone();
  6989. var cloneLayer = animator.getControllerLayer(i);
  6990. cloneLayer.addState(state);
  6991. (j == 0) && (cloneLayer.defaultState = state);
  6992. }
  6993. }
  6994. animator._linkSprites = this._linkSprites;
  6995. animator._linkToSprites(this._linkSprites);
  6996. }
  6997. getDefaultState(layerIndex = 0) {
  6998. var controllerLayer = this._controllerLayers[layerIndex];
  6999. return controllerLayer.defaultState;
  7000. }
  7001. addState(state, layerIndex = 0) {
  7002. var controllerLayer = this._controllerLayers[layerIndex];
  7003. controllerLayer.addState(state);
  7004. console.warn("Animator:this function is discard,please use animatorControllerLayer.addState() instead.");
  7005. }
  7006. removeState(state, layerIndex = 0) {
  7007. var controllerLayer = this._controllerLayers[layerIndex];
  7008. controllerLayer.removeState(state);
  7009. console.warn("Animator:this function is discard,please use animatorControllerLayer.removeState() instead.");
  7010. }
  7011. addControllerLayer(controllderLayer) {
  7012. this._controllerLayers.push(controllderLayer);
  7013. controllderLayer._animator = this;
  7014. controllderLayer._addReference();
  7015. var states = controllderLayer._states;
  7016. for (var i = 0, n = states.length; i < n; i++)
  7017. this._getOwnersByClip(states[i]);
  7018. }
  7019. getControllerLayer(layerInex = 0) {
  7020. return this._controllerLayers[layerInex];
  7021. }
  7022. play(name = null, layerIndex = 0, normalizedTime = Number.NEGATIVE_INFINITY) {
  7023. var controllerLayer = this._controllerLayers[layerIndex];
  7024. if (controllerLayer) {
  7025. var defaultState = controllerLayer.defaultState;
  7026. if (!name && !defaultState)
  7027. throw new Error("Animator:must have default clip value,please set clip property.");
  7028. var playStateInfo = controllerLayer._playStateInfo;
  7029. var curPlayState = playStateInfo._currentState;
  7030. var animatorState = name ? controllerLayer._statesMap[name] : defaultState;
  7031. var clipDuration = animatorState._clip._duration;
  7032. var calclipduration = animatorState._clip._duration * (animatorState.clipEnd - animatorState.clipStart);
  7033. if (curPlayState !== animatorState) {
  7034. if (normalizedTime !== Number.NEGATIVE_INFINITY)
  7035. playStateInfo._resetPlayState(clipDuration * normalizedTime, calclipduration);
  7036. else
  7037. playStateInfo._resetPlayState(0.0, calclipduration);
  7038. (curPlayState !== null && curPlayState !== animatorState) && (this._revertDefaultKeyframeNodes(curPlayState));
  7039. controllerLayer._playType = 0;
  7040. playStateInfo._currentState = animatorState;
  7041. }
  7042. else {
  7043. if (normalizedTime !== Number.NEGATIVE_INFINITY) {
  7044. playStateInfo._resetPlayState(clipDuration * normalizedTime, calclipduration);
  7045. controllerLayer._playType = 0;
  7046. }
  7047. }
  7048. var scripts = animatorState._scripts;
  7049. if (scripts) {
  7050. for (var i = 0, n = scripts.length; i < n; i++)
  7051. scripts[i].onStateEnter();
  7052. }
  7053. }
  7054. else {
  7055. console.warn("Invalid layerIndex " + layerIndex + ".");
  7056. }
  7057. }
  7058. crossFade(name, transitionDuration, layerIndex = 0, normalizedTime = Number.NEGATIVE_INFINITY) {
  7059. var controllerLayer = this._controllerLayers[layerIndex];
  7060. if (controllerLayer) {
  7061. var destAnimatorState = controllerLayer._statesMap[name];
  7062. if (destAnimatorState) {
  7063. var playType = controllerLayer._playType;
  7064. if (playType === -1) {
  7065. this.play(name, layerIndex, normalizedTime);
  7066. return;
  7067. }
  7068. var crossPlayStateInfo = controllerLayer._crossPlayStateInfo;
  7069. var crossNodeOwners = controllerLayer._crossNodesOwners;
  7070. var crossNodeOwnerIndicesMap = controllerLayer._crossNodesOwnersIndicesMap;
  7071. var srcAnimatorState = controllerLayer._playStateInfo._currentState;
  7072. var destNodeOwners = destAnimatorState._nodeOwners;
  7073. var destCrossClipNodeIndices = controllerLayer._destCrossClipNodeIndices;
  7074. var destClip = destAnimatorState._clip;
  7075. var destNodes = destClip._nodes;
  7076. var destNodesMap = destClip._nodesDic;
  7077. switch (playType) {
  7078. case 0:
  7079. var srcNodeOwners = srcAnimatorState._nodeOwners;
  7080. var scrCrossClipNodeIndices = controllerLayer._srcCrossClipNodeIndices;
  7081. var srcClip = srcAnimatorState._clip;
  7082. var srcNodes = srcClip._nodes;
  7083. var srcNodesMap = srcClip._nodesDic;
  7084. controllerLayer._playType = 1;
  7085. var crossMark = ++controllerLayer._crossMark;
  7086. var crossCount = controllerLayer._crossNodesOwnersCount = 0;
  7087. for (var i = 0, n = srcNodes.count; i < n; i++) {
  7088. var srcNode = srcNodes.getNodeByIndex(i);
  7089. var srcIndex = srcNode._indexInList;
  7090. var srcNodeOwner = srcNodeOwners[srcIndex];
  7091. if (srcNodeOwner) {
  7092. var srcFullPath = srcNode.fullPath;
  7093. scrCrossClipNodeIndices[crossCount] = srcIndex;
  7094. var destNode = destNodesMap[srcFullPath];
  7095. if (destNode)
  7096. destCrossClipNodeIndices[crossCount] = destNode._indexInList;
  7097. else
  7098. destCrossClipNodeIndices[crossCount] = -1;
  7099. crossNodeOwnerIndicesMap[srcFullPath] = crossMark;
  7100. crossNodeOwners[crossCount] = srcNodeOwner;
  7101. crossCount++;
  7102. }
  7103. }
  7104. for (i = 0, n = destNodes.count; i < n; i++) {
  7105. destNode = destNodes.getNodeByIndex(i);
  7106. var destIndex = destNode._indexInList;
  7107. var destNodeOwner = destNodeOwners[destIndex];
  7108. if (destNodeOwner) {
  7109. var destFullPath = destNode.fullPath;
  7110. if (!srcNodesMap[destFullPath]) {
  7111. scrCrossClipNodeIndices[crossCount] = -1;
  7112. destCrossClipNodeIndices[crossCount] = destIndex;
  7113. crossNodeOwnerIndicesMap[destFullPath] = crossMark;
  7114. crossNodeOwners[crossCount] = destNodeOwner;
  7115. crossCount++;
  7116. }
  7117. }
  7118. }
  7119. break;
  7120. case 1:
  7121. case 2:
  7122. controllerLayer._playType = 2;
  7123. for (i = 0, n = crossNodeOwners.length; i < n; i++) {
  7124. var nodeOwner = crossNodeOwners[i];
  7125. nodeOwner.saveCrossFixedValue();
  7126. destNode = destNodesMap[nodeOwner.fullPath];
  7127. if (destNode)
  7128. destCrossClipNodeIndices[i] = destNode._indexInList;
  7129. else
  7130. destCrossClipNodeIndices[i] = -1;
  7131. }
  7132. crossCount = controllerLayer._crossNodesOwnersCount;
  7133. crossMark = controllerLayer._crossMark;
  7134. for (i = 0, n = destNodes.count; i < n; i++) {
  7135. destNode = destNodes.getNodeByIndex(i);
  7136. destIndex = destNode._indexInList;
  7137. destNodeOwner = destNodeOwners[destIndex];
  7138. if (destNodeOwner) {
  7139. destFullPath = destNode.fullPath;
  7140. if (crossNodeOwnerIndicesMap[destFullPath] !== crossMark) {
  7141. destCrossClipNodeIndices[crossCount] = destIndex;
  7142. crossNodeOwnerIndicesMap[destFullPath] = crossMark;
  7143. nodeOwner = destNodeOwners[destIndex];
  7144. crossNodeOwners[crossCount] = nodeOwner;
  7145. nodeOwner.saveCrossFixedValue();
  7146. crossCount++;
  7147. }
  7148. }
  7149. }
  7150. break;
  7151. default:
  7152. }
  7153. controllerLayer._crossNodesOwnersCount = crossCount;
  7154. controllerLayer._crossPlayState = destAnimatorState;
  7155. controllerLayer._crossDuration = srcAnimatorState._clip._duration * transitionDuration;
  7156. if (normalizedTime !== Number.NEGATIVE_INFINITY)
  7157. crossPlayStateInfo._resetPlayState(destClip._duration * normalizedTime, controllerLayer._crossDuration);
  7158. else
  7159. crossPlayStateInfo._resetPlayState(0.0, controllerLayer._crossDuration);
  7160. var scripts = destAnimatorState._scripts;
  7161. if (scripts) {
  7162. for (i = 0, n = scripts.length; i < n; i++)
  7163. scripts[i].onStateEnter();
  7164. }
  7165. }
  7166. else {
  7167. console.warn("Invalid name " + layerIndex + ".");
  7168. }
  7169. }
  7170. else {
  7171. console.warn("Invalid layerIndex " + layerIndex + ".");
  7172. }
  7173. }
  7174. getCurrentAnimatorPlayState(layerInex = 0) {
  7175. return this._controllerLayers[layerInex]._playStateInfo;
  7176. }
  7177. get avatar() {
  7178. return this._avatar;
  7179. }
  7180. set avatar(value) {
  7181. if (this._avatar !== value) {
  7182. this._avatar = value;
  7183. if (value) {
  7184. this._getAvatarOwnersAndInitDatasAsync();
  7185. this.owner._changeHierarchyAnimatorAvatar(this, value);
  7186. }
  7187. else {
  7188. var parent = this.owner._parent;
  7189. this.owner._changeHierarchyAnimatorAvatar(this, parent ? parent._hierarchyAnimator._avatar : null);
  7190. }
  7191. }
  7192. }
  7193. _isLinkSpriteToAnimationNodeData(sprite, nodeName, isLink) {
  7194. var linkSprites = this._linkAvatarSpritesData[nodeName];
  7195. if (isLink) {
  7196. linkSprites || (this._linkAvatarSpritesData[nodeName] = linkSprites = []);
  7197. linkSprites.push(sprite);
  7198. }
  7199. else {
  7200. var index = linkSprites.indexOf(sprite);
  7201. linkSprites.splice(index, 1);
  7202. }
  7203. }
  7204. _getAvatarOwnersAndInitDatasAsync() {
  7205. for (var i = 0, n = this._controllerLayers.length; i < n; i++) {
  7206. var clipStateInfos = this._controllerLayers[i]._states;
  7207. for (var j = 0, m = clipStateInfos.length; j < m; j++)
  7208. this._getOwnersByClip(clipStateInfos[j]);
  7209. }
  7210. this._avatar._cloneDatasToAnimator(this);
  7211. for (var k in this._linkAvatarSpritesData) {
  7212. var sprites = this._linkAvatarSpritesData[k];
  7213. if (sprites) {
  7214. for (var c = 0, p = sprites.length; c < p; c++)
  7215. this._isLinkSpriteToAnimationNode(sprites[c], k, true);
  7216. }
  7217. }
  7218. }
  7219. _isLinkSpriteToAnimationNode(sprite, nodeName, isLink) {
  7220. if (this._avatar) {
  7221. var node = this._avatarNodeMap[nodeName];
  7222. if (node) {
  7223. if (isLink) {
  7224. sprite._transform._dummy = node.transform;
  7225. this._linkAvatarSprites.push(sprite);
  7226. var nodeTransform = node.transform;
  7227. var spriteTransform = sprite.transform;
  7228. if (!spriteTransform.owner.isStatic && nodeTransform) {
  7229. var spriteWorldMatrix = spriteTransform.worldMatrix;
  7230. var ownParTra = this.owner._transform._parent;
  7231. if (ownParTra) {
  7232. Utils3D.matrix4x4MultiplyMFM(ownParTra.worldMatrix, nodeTransform.getWorldMatrix(), spriteWorldMatrix);
  7233. }
  7234. else {
  7235. var sprWorE = spriteWorldMatrix.elements;
  7236. var nodWorE = nodeTransform.getWorldMatrix();
  7237. for (var i = 0; i < 16; i++)
  7238. sprWorE[i] = nodWorE[i];
  7239. }
  7240. spriteTransform.worldMatrix = spriteWorldMatrix;
  7241. }
  7242. }
  7243. else {
  7244. sprite._transform._dummy = null;
  7245. this._linkAvatarSprites.splice(this._linkAvatarSprites.indexOf(sprite), 1);
  7246. }
  7247. }
  7248. }
  7249. }
  7250. _updateAvatarNodesToSprite() {
  7251. for (var i = 0, n = this._linkAvatarSprites.length; i < n; i++) {
  7252. var sprite = this._linkAvatarSprites[i];
  7253. var nodeTransform = sprite.transform._dummy;
  7254. var spriteTransform = sprite.transform;
  7255. if (!spriteTransform.owner.isStatic && nodeTransform) {
  7256. var spriteWorldMatrix = spriteTransform.worldMatrix;
  7257. var ownTra = this.owner._transform;
  7258. Utils3D.matrix4x4MultiplyMFM(ownTra.worldMatrix, nodeTransform.getWorldMatrix(), spriteWorldMatrix);
  7259. spriteTransform.worldMatrix = spriteWorldMatrix;
  7260. }
  7261. }
  7262. }
  7263. linkSprite3DToAvatarNode(nodeName, sprite3D) {
  7264. this._isLinkSpriteToAnimationNodeData(sprite3D, nodeName, true);
  7265. this._isLinkSpriteToAnimationNode(sprite3D, nodeName, true);
  7266. return true;
  7267. }
  7268. unLinkSprite3DToAvatarNode(sprite3D) {
  7269. var dummy = sprite3D.transform._dummy;
  7270. if (dummy) {
  7271. var nodeName = dummy._owner.name;
  7272. this._isLinkSpriteToAnimationNodeData(sprite3D, nodeName, false);
  7273. this._isLinkSpriteToAnimationNode(sprite3D, nodeName, false);
  7274. return true;
  7275. }
  7276. else {
  7277. return false;
  7278. }
  7279. }
  7280. _updateAnimationNodeWorldMatix(localPositions, localRotations, localScales, worldMatrixs, parentIndices) {
  7281. Laya.LayaGL.instance.updateAnimationNodeWorldMatix(localPositions, localRotations, localScales, parentIndices, worldMatrixs);
  7282. }
  7283. }
  7284. Animator._tempVector31 = new Vector3();
  7285. Animator._tempQuaternion1 = new Quaternion();
  7286. Animator.CULLINGMODE_ALWAYSANIMATE = 0;
  7287. Animator.CULLINGMODE_CULLCOMPLETELY = 2;
  7288. class RenderContext3D {
  7289. constructor() {
  7290. this.invertY = false;
  7291. this.configPipeLineMode = "Forward";
  7292. }
  7293. }
  7294. RenderContext3D._instance = new RenderContext3D();
  7295. class RenderTexture extends Laya.BaseTexture {
  7296. constructor(width, height, format = Laya.RenderTextureFormat.R8G8B8, depthStencilFormat = Laya.RenderTextureDepthFormat.DEPTH_16) {
  7297. super(format, false);
  7298. this._inPool = false;
  7299. this._isCameraTarget = false;
  7300. this._glTextureType = Laya.LayaGL.instance.TEXTURE_2D;
  7301. this._width = width;
  7302. this._height = height;
  7303. this._depthStencilFormat = depthStencilFormat;
  7304. this._mipmapCount = 1;
  7305. this._create(width, height);
  7306. }
  7307. static get currentActive() {
  7308. return RenderTexture._currentActive;
  7309. }
  7310. static createFromPool(width, height, format = Laya.RenderTextureFormat.R8G8B8, depthStencilFormat = Laya.RenderTextureDepthFormat.DEPTH_16) {
  7311. var tex;
  7312. for (var i = 0, n = RenderTexture._pool.length; i < n; i++) {
  7313. tex = RenderTexture._pool[i];
  7314. if (tex._width == width && tex._height == height && tex._format == format && tex._depthStencilFormat == depthStencilFormat) {
  7315. tex._inPool = false;
  7316. var end = RenderTexture._pool[n - 1];
  7317. RenderTexture._pool[i] = end;
  7318. RenderTexture._pool.length -= 1;
  7319. return tex;
  7320. }
  7321. }
  7322. tex = new RenderTexture(width, height, format, depthStencilFormat);
  7323. tex.lock = true;
  7324. return tex;
  7325. }
  7326. static recoverToPool(renderTexture) {
  7327. if (renderTexture._inPool)
  7328. return;
  7329. RenderTexture._pool.push(renderTexture);
  7330. renderTexture._inPool = true;
  7331. }
  7332. get depthStencilFormat() {
  7333. return this._depthStencilFormat;
  7334. }
  7335. get defaulteTexture() {
  7336. return Laya.Texture2D.grayTexture;
  7337. }
  7338. _create(width, height) {
  7339. var gl = Laya.LayaGL.instance;
  7340. var gl2 = gl;
  7341. var glTextureType = this._glTextureType;
  7342. var layaGPU = Laya.LayaGL.layaGPUInstance;
  7343. var isWebGL2 = layaGPU._isWebGL2;
  7344. var format = this._format;
  7345. this._frameBuffer = gl.createFramebuffer();
  7346. gl.bindFramebuffer(gl.FRAMEBUFFER, this._frameBuffer);
  7347. if (format !== Laya.RenderTextureFormat.Depth && format !== Laya.RenderTextureFormat.ShadowMap) {
  7348. Laya.WebGLContext.bindTexture(gl, glTextureType, this._glTexture);
  7349. switch (format) {
  7350. case Laya.RenderTextureFormat.R8G8B8:
  7351. if (isWebGL2)
  7352. gl2.texStorage2D(glTextureType, this._mipmapCount, gl2.RGB8, width, height);
  7353. else
  7354. gl.texImage2D(glTextureType, 0, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, null);
  7355. break;
  7356. case Laya.RenderTextureFormat.R8G8B8A8:
  7357. if (isWebGL2)
  7358. gl2.texStorage2D(glTextureType, this._mipmapCount, gl2.RGBA8, width, height);
  7359. else
  7360. gl.texImage2D(glTextureType, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  7361. break;
  7362. case Laya.RenderTextureFormat.Alpha8:
  7363. if (isWebGL2)
  7364. gl2.texStorage2D(glTextureType, 0, gl2.R8, width, height);
  7365. else
  7366. gl.texImage2D(glTextureType, 0, gl.ALPHA, width, height, 0, gl.ALPHA, gl.UNSIGNED_BYTE, null);
  7367. break;
  7368. case Laya.RenderTextureFormat.R16G16B16A16:
  7369. if (isWebGL2)
  7370. gl2.texStorage2D(glTextureType, this._mipmapCount, gl2.RGBA16F, width, height);
  7371. else
  7372. gl.texImage2D(glTextureType, 0, gl.RGBA, width, height, 0, gl.RGBA, layaGPU._oesTextureHalfFloat.HALF_FLOAT_OES, null);
  7373. break;
  7374. }
  7375. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this._glTexture, 0);
  7376. }
  7377. if (format == Laya.RenderTextureFormat.Depth || format == Laya.RenderTextureFormat.ShadowMap) {
  7378. Laya.WebGLContext.bindTexture(gl, glTextureType, this._glTexture);
  7379. switch (this._depthStencilFormat) {
  7380. case Laya.RenderTextureDepthFormat.DEPTH_16:
  7381. if (isWebGL2) {
  7382. gl2.texStorage2D(glTextureType, this._mipmapCount, gl2.DEPTH_COMPONENT16, width, height);
  7383. }
  7384. else
  7385. gl.texImage2D(glTextureType, 0, gl.DEPTH_COMPONENT, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  7386. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, this._glTexture, 0);
  7387. break;
  7388. case Laya.RenderTextureDepthFormat.DEPTHSTENCIL_24_8:
  7389. if (isWebGL2)
  7390. gl2.texStorage2D(glTextureType, this._mipmapCount, gl2.DEPTH24_STENCIL8, width, height);
  7391. else
  7392. gl.texImage2D(glTextureType, 0, gl.DEPTH_STENCIL, width, height, 0, gl.DEPTH_STENCIL, layaGPU._webgl_depth_texture.UNSIGNED_INT_24_8_WEBGL, null);
  7393. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, this._glTexture, 0);
  7394. break;
  7395. default:
  7396. throw "RenderTexture: depth format RenderTexture must use depthFormat with DEPTH_16 and DEPTHSTENCIL_16_8.";
  7397. }
  7398. if (isWebGL2 && format == Laya.RenderTextureFormat.ShadowMap)
  7399. gl2.texParameteri(glTextureType, gl2.TEXTURE_COMPARE_MODE, gl2.COMPARE_REF_TO_TEXTURE);
  7400. }
  7401. else {
  7402. if (this._depthStencilFormat !== Laya.RenderTextureDepthFormat.DEPTHSTENCIL_NONE) {
  7403. this._depthStencilBuffer = gl.createRenderbuffer();
  7404. gl.bindRenderbuffer(gl.RENDERBUFFER, this._depthStencilBuffer);
  7405. switch (this._depthStencilFormat) {
  7406. case Laya.RenderTextureDepthFormat.DEPTH_16:
  7407. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  7408. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this._depthStencilBuffer);
  7409. break;
  7410. case Laya.RenderTextureDepthFormat.STENCIL_8:
  7411. gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8, width, height);
  7412. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, this._depthStencilBuffer);
  7413. break;
  7414. case Laya.RenderTextureDepthFormat.DEPTHSTENCIL_24_8:
  7415. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  7416. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this._depthStencilBuffer);
  7417. break;
  7418. default:
  7419. throw "RenderTexture: unkonw depth format.";
  7420. }
  7421. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7422. }
  7423. }
  7424. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  7425. this._setWarpMode(gl.TEXTURE_WRAP_S, this._wrapModeU);
  7426. this._setWarpMode(gl.TEXTURE_WRAP_T, this._wrapModeV);
  7427. this._setFilterMode(this._filterMode);
  7428. this._setAnisotropy(this._anisoLevel);
  7429. this._readyed = true;
  7430. this._activeResource();
  7431. this._setGPUMemory(width * height * 4);
  7432. }
  7433. _start() {
  7434. var gl = Laya.LayaGL.instance;
  7435. gl.bindFramebuffer(gl.FRAMEBUFFER, this._frameBuffer);
  7436. RenderTexture._currentActive = this;
  7437. (this._isCameraTarget) && (RenderContext3D._instance.invertY = true);
  7438. this._readyed = false;
  7439. }
  7440. _end() {
  7441. var gl = Laya.LayaGL.instance;
  7442. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  7443. RenderTexture._currentActive = null;
  7444. (this._isCameraTarget) && (RenderContext3D._instance.invertY = false);
  7445. this._readyed = true;
  7446. }
  7447. getData(x, y, width, height, out) {
  7448. if (Laya.Render.isConchApp && window.conchConfig.threadMode == 2) {
  7449. throw "native 2 thread mode use getDataAsync";
  7450. }
  7451. var gl = Laya.LayaGL.instance;
  7452. gl.bindFramebuffer(gl.FRAMEBUFFER, this._frameBuffer);
  7453. var canRead = (gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE);
  7454. if (!canRead) {
  7455. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  7456. return null;
  7457. }
  7458. gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, out);
  7459. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  7460. return out;
  7461. }
  7462. _disposeResource() {
  7463. if (this._frameBuffer) {
  7464. var gl = Laya.LayaGL.instance;
  7465. gl.deleteTexture(this._glTexture);
  7466. gl.deleteFramebuffer(this._frameBuffer);
  7467. gl.deleteRenderbuffer(this._depthStencilBuffer);
  7468. this._glTexture = null;
  7469. this._frameBuffer = null;
  7470. this._depthStencilBuffer = null;
  7471. this._setGPUMemory(0);
  7472. }
  7473. }
  7474. getDataAsync(x, y, width, height, callBack) {
  7475. var gl = Laya.LayaGL.instance;
  7476. gl.bindFramebuffer(gl.FRAMEBUFFER, this._frameBuffer);
  7477. gl.readPixelsAsync(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, function (data) {
  7478. callBack(new Uint8Array(data));
  7479. });
  7480. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  7481. }
  7482. }
  7483. RenderTexture._pool = [];
  7484. class DefineDatas {
  7485. constructor() {
  7486. this._mask = [];
  7487. this._length = 0;
  7488. }
  7489. _intersectionDefineDatas(define) {
  7490. var unionMask = define._mask;
  7491. var mask = this._mask;
  7492. for (var i = this._length - 1; i >= 0; i--) {
  7493. var value = mask[i] & unionMask[i];
  7494. if (value == 0 && i == this._length - 1)
  7495. this._length--;
  7496. else
  7497. mask[i] = value;
  7498. }
  7499. }
  7500. add(define) {
  7501. var index = define._index;
  7502. var size = index + 1;
  7503. var mask = this._mask;
  7504. var maskStart = this._length;
  7505. if (maskStart < size) {
  7506. (mask.length < size) && (mask.length = size);
  7507. for (; maskStart < index; maskStart++)
  7508. mask[maskStart] = 0;
  7509. mask[index] = define._value;
  7510. this._length = size;
  7511. }
  7512. else {
  7513. mask[index] |= define._value;
  7514. }
  7515. }
  7516. remove(define) {
  7517. var index = define._index;
  7518. var mask = this._mask;
  7519. var endIndex = this._length - 1;
  7520. if (index > endIndex)
  7521. return;
  7522. var newValue = mask[index] & ~define._value;
  7523. if (index == endIndex && newValue === 0)
  7524. this._length--;
  7525. else
  7526. mask[index] = newValue;
  7527. }
  7528. addDefineDatas(define) {
  7529. var addMask = define._mask;
  7530. var size = define._length;
  7531. var mask = this._mask;
  7532. var maskStart = this._length;
  7533. if (maskStart < size) {
  7534. mask.length = size;
  7535. for (var i = 0; i < maskStart; i++)
  7536. mask[i] |= addMask[i];
  7537. for (; i < size; i++)
  7538. mask[i] = addMask[i];
  7539. this._length = size;
  7540. }
  7541. else {
  7542. for (var i = 0; i < size; i++) {
  7543. mask[i] |= addMask[i];
  7544. }
  7545. }
  7546. }
  7547. removeDefineDatas(define) {
  7548. var removeMask = define._mask;
  7549. var mask = this._mask;
  7550. var endIndex = this._length - 1;
  7551. var i = Math.min(define._length, endIndex);
  7552. for (; i >= 0; i--) {
  7553. var newValue = mask[i] & ~removeMask[i];
  7554. if (i == endIndex && newValue === 0) {
  7555. endIndex--;
  7556. this._length--;
  7557. }
  7558. else {
  7559. mask[i] = newValue;
  7560. }
  7561. }
  7562. }
  7563. has(define) {
  7564. var index = define._index;
  7565. if (index >= this._length)
  7566. return false;
  7567. return (this._mask[index] & define._value) !== 0;
  7568. }
  7569. clear() {
  7570. this._length = 0;
  7571. }
  7572. cloneTo(destObject) {
  7573. var destDefineData = destObject;
  7574. var destMask = destDefineData._mask;
  7575. var mask = this._mask;
  7576. var count = this._length;
  7577. destMask.length = count;
  7578. for (var i = 0; i < count; i++)
  7579. destMask[i] = mask[i];
  7580. destDefineData._length = count;
  7581. }
  7582. clone() {
  7583. var dest = new DefineDatas();
  7584. this.cloneTo(dest);
  7585. return dest;
  7586. }
  7587. }
  7588. class VertexBuffer3D extends Laya.Buffer {
  7589. constructor(byteLength, bufferUsage, canRead = false) {
  7590. super();
  7591. this._vertexDeclaration = null;
  7592. this._float32Reader = null;
  7593. var gl = Laya.LayaGL.instance;
  7594. this._bufferUsage = bufferUsage;
  7595. this._bufferType = gl.ARRAY_BUFFER;
  7596. this._canRead = canRead;
  7597. this._byteLength = byteLength;
  7598. this.bind();
  7599. gl.bufferData(this._bufferType, this._byteLength, this._bufferUsage);
  7600. if (canRead) {
  7601. this._buffer = new Uint8Array(byteLength);
  7602. this._float32Reader = new Float32Array(this._buffer.buffer);
  7603. }
  7604. }
  7605. get vertexDeclaration() {
  7606. return this._vertexDeclaration;
  7607. }
  7608. set vertexDeclaration(value) {
  7609. this._vertexDeclaration = value;
  7610. }
  7611. get canRead() {
  7612. return this._canRead;
  7613. }
  7614. bind() {
  7615. if (Laya.Buffer._bindedVertexBuffer !== this._glBuffer) {
  7616. var gl = Laya.LayaGL.instance;
  7617. gl.bindBuffer(gl.ARRAY_BUFFER, this._glBuffer);
  7618. Laya.Buffer._bindedVertexBuffer = this._glBuffer;
  7619. return true;
  7620. }
  7621. else {
  7622. return false;
  7623. }
  7624. }
  7625. orphanStorage() {
  7626. this.bind();
  7627. Laya.LayaGL.instance.bufferData(this._bufferType, this._byteLength, this._bufferUsage);
  7628. }
  7629. setData(buffer, bufferOffset = 0, dataStartIndex = 0, dataCount = Number.MAX_SAFE_INTEGER) {
  7630. this.bind();
  7631. var needSubData = dataStartIndex !== 0 || dataCount !== Number.MAX_SAFE_INTEGER;
  7632. if (needSubData) {
  7633. var subData = new Uint8Array(buffer, dataStartIndex, dataCount);
  7634. Laya.LayaGL.instance.bufferSubData(this._bufferType, bufferOffset, subData);
  7635. if (this._canRead)
  7636. this._buffer.set(subData, bufferOffset);
  7637. }
  7638. else {
  7639. Laya.LayaGL.instance.bufferSubData(this._bufferType, bufferOffset, buffer);
  7640. if (this._canRead)
  7641. this._buffer.set(new Uint8Array(buffer), bufferOffset);
  7642. }
  7643. }
  7644. getUint8Data() {
  7645. if (this._canRead)
  7646. return this._buffer;
  7647. else
  7648. throw new Error("Can't read data from VertexBuffer with only write flag!");
  7649. }
  7650. getFloat32Data() {
  7651. if (this._canRead)
  7652. return this._float32Reader;
  7653. else
  7654. throw new Error("Can't read data from VertexBuffer with only write flag!");
  7655. }
  7656. markAsUnreadbale() {
  7657. this._canRead = false;
  7658. this._buffer = null;
  7659. this._float32Reader = null;
  7660. }
  7661. destroy() {
  7662. super.destroy();
  7663. this._buffer = null;
  7664. this._float32Reader = null;
  7665. this._vertexDeclaration = null;
  7666. this._byteLength = 0;
  7667. }
  7668. }
  7669. VertexBuffer3D.DATATYPE_FLOAT32ARRAY = 0;
  7670. VertexBuffer3D.DATATYPE_UINT8ARRAY = 1;
  7671. class VertexElementFormat {
  7672. static __init__() {
  7673. var gl = Laya.LayaGL.instance;
  7674. VertexElementFormat._elementInfos = {
  7675. "single": [1, gl.FLOAT, 0],
  7676. "vector2": [2, gl.FLOAT, 0],
  7677. "vector3": [3, gl.FLOAT, 0],
  7678. "vector4": [4, gl.FLOAT, 0],
  7679. "color": [4, gl.FLOAT, 0],
  7680. "byte4": [4, gl.UNSIGNED_BYTE, 0],
  7681. "short2": [2, gl.FLOAT, 0],
  7682. "short4": [4, gl.FLOAT, 0],
  7683. "normalizedshort2": [2, gl.FLOAT, 0],
  7684. "normalizedshort4": [4, gl.FLOAT, 0],
  7685. "halfvector2": [2, gl.FLOAT, 0],
  7686. "halfvector4": [4, gl.FLOAT, 0]
  7687. };
  7688. }
  7689. static getElementInfos(element) {
  7690. var info = VertexElementFormat._elementInfos[element];
  7691. if (info)
  7692. return info;
  7693. else
  7694. throw "VertexElementFormat: this vertexElementFormat is not implement.";
  7695. }
  7696. }
  7697. VertexElementFormat.Single = "single";
  7698. VertexElementFormat.Vector2 = "vector2";
  7699. VertexElementFormat.Vector3 = "vector3";
  7700. VertexElementFormat.Vector4 = "vector4";
  7701. VertexElementFormat.Color = "color";
  7702. VertexElementFormat.Byte4 = "byte4";
  7703. VertexElementFormat.Short2 = "short2";
  7704. VertexElementFormat.Short4 = "short4";
  7705. VertexElementFormat.NormalizedShort2 = "normalizedshort2";
  7706. VertexElementFormat.NormalizedShort4 = "normalizedshort4";
  7707. VertexElementFormat.HalfVector2 = "halfvector2";
  7708. VertexElementFormat.HalfVector4 = "halfvector4";
  7709. class ShaderData {
  7710. constructor(ownerResource = null) {
  7711. this._ownerResource = null;
  7712. this._data = null;
  7713. this._defineDatas = new DefineDatas();
  7714. this._runtimeCopyValues = [];
  7715. this._ownerResource = ownerResource;
  7716. this._initData();
  7717. }
  7718. _initData() {
  7719. this._data = new Object();
  7720. }
  7721. getData() {
  7722. return this._data;
  7723. }
  7724. addDefine(define) {
  7725. this._defineDatas.add(define);
  7726. }
  7727. removeDefine(define) {
  7728. this._defineDatas.remove(define);
  7729. }
  7730. hasDefine(define) {
  7731. return this._defineDatas.has(define);
  7732. }
  7733. clearDefine() {
  7734. this._defineDatas.clear();
  7735. }
  7736. getBool(index) {
  7737. return this._data[index];
  7738. }
  7739. setBool(index, value) {
  7740. this._data[index] = value;
  7741. }
  7742. getInt(index) {
  7743. return this._data[index];
  7744. }
  7745. setInt(index, value) {
  7746. this._data[index] = value;
  7747. }
  7748. getNumber(index) {
  7749. return this._data[index];
  7750. }
  7751. setNumber(index, value) {
  7752. this._data[index] = value;
  7753. }
  7754. getVector2(index) {
  7755. return this._data[index];
  7756. }
  7757. setVector2(index, value) {
  7758. this._data[index] = value;
  7759. }
  7760. getVector3(index) {
  7761. return this._data[index];
  7762. }
  7763. setVector3(index, value) {
  7764. this._data[index] = value;
  7765. }
  7766. getVector(index) {
  7767. return this._data[index];
  7768. }
  7769. setVector(index, value) {
  7770. this._data[index] = value;
  7771. }
  7772. getQuaternion(index) {
  7773. return this._data[index];
  7774. }
  7775. setQuaternion(index, value) {
  7776. this._data[index] = value;
  7777. }
  7778. getMatrix4x4(index) {
  7779. return this._data[index];
  7780. }
  7781. setMatrix4x4(index, value) {
  7782. this._data[index] = value;
  7783. }
  7784. getBuffer(shaderIndex) {
  7785. return this._data[shaderIndex];
  7786. }
  7787. setBuffer(index, value) {
  7788. this._data[index] = value;
  7789. }
  7790. setTexture(index, value) {
  7791. var lastValue = this._data[index];
  7792. this._data[index] = value;
  7793. if (this._ownerResource && this._ownerResource.referenceCount > 0) {
  7794. (lastValue) && (lastValue._removeReference());
  7795. (value) && (value._addReference());
  7796. }
  7797. }
  7798. getTexture(index) {
  7799. return this._data[index];
  7800. }
  7801. setAttribute(index, value) {
  7802. this._data[index] = value;
  7803. }
  7804. getAttribute(index) {
  7805. return this._data[index];
  7806. }
  7807. getLength() {
  7808. return this._data.length;
  7809. }
  7810. setLength(value) {
  7811. this._data.length = value;
  7812. }
  7813. cloneTo(destObject) {
  7814. var dest = destObject;
  7815. var destData = dest._data;
  7816. for (var k in this._data) {
  7817. var value = this._data[k];
  7818. if (value != null) {
  7819. if (typeof (value) == 'number') {
  7820. destData[k] = value;
  7821. }
  7822. else if (typeof (value) == 'number') {
  7823. destData[k] = value;
  7824. }
  7825. else if (typeof (value) == "boolean") {
  7826. destData[k] = value;
  7827. }
  7828. else if (value instanceof Vector2) {
  7829. var v2 = (destData[k]) || (destData[k] = new Vector2());
  7830. value.cloneTo(v2);
  7831. destData[k] = v2;
  7832. }
  7833. else if (value instanceof Vector3) {
  7834. var v3 = (destData[k]) || (destData[k] = new Vector3());
  7835. value.cloneTo(v3);
  7836. destData[k] = v3;
  7837. }
  7838. else if (value instanceof Vector4) {
  7839. var v4 = (destData[k]) || (destData[k] = new Vector4());
  7840. value.cloneTo(v4);
  7841. destData[k] = v4;
  7842. }
  7843. else if (value instanceof Matrix4x4) {
  7844. var mat = (destData[k]) || (destData[k] = new Matrix4x4());
  7845. value.cloneTo(mat);
  7846. destData[k] = mat;
  7847. }
  7848. else if (value instanceof Laya.BaseTexture) {
  7849. destData[k] = value;
  7850. }
  7851. }
  7852. }
  7853. this._defineDatas.cloneTo(dest._defineDatas);
  7854. }
  7855. clone() {
  7856. var dest = new ShaderData();
  7857. this.cloneTo(dest);
  7858. return dest;
  7859. }
  7860. cloneToForNative(destObject) {
  7861. var dest = destObject;
  7862. var diffSize = this._int32Data.length - dest._int32Data.length;
  7863. if (diffSize > 0) {
  7864. dest.needRenewArrayBufferForNative(this._int32Data.length);
  7865. }
  7866. dest._int32Data.set(this._int32Data, 0);
  7867. var destData = dest._nativeArray;
  7868. var dataCount = this._nativeArray.length;
  7869. destData.length = dataCount;
  7870. for (var i = 0; i < dataCount; i++) {
  7871. var value = this._nativeArray[i];
  7872. if (value) {
  7873. if (typeof (value) == 'number') {
  7874. destData[i] = value;
  7875. dest.setNumber(i, value);
  7876. }
  7877. else if (typeof (value) == 'number') {
  7878. destData[i] = value;
  7879. dest.setInt(i, value);
  7880. }
  7881. else if (typeof (value) == "boolean") {
  7882. destData[i] = value;
  7883. dest.setBool(i, value);
  7884. }
  7885. else if (value instanceof Vector2) {
  7886. var v2 = (destData[i]) || (destData[i] = new Vector2());
  7887. value.cloneTo(v2);
  7888. destData[i] = v2;
  7889. dest.setVector2(i, v2);
  7890. }
  7891. else if (value instanceof Vector3) {
  7892. var v3 = (destData[i]) || (destData[i] = new Vector3());
  7893. value.cloneTo(v3);
  7894. destData[i] = v3;
  7895. dest.setVector3(i, v3);
  7896. }
  7897. else if (value instanceof Vector4) {
  7898. var v4 = (destData[i]) || (destData[i] = new Vector4());
  7899. value.cloneTo(v4);
  7900. destData[i] = v4;
  7901. dest.setVector(i, v4);
  7902. }
  7903. else if (value instanceof Matrix4x4) {
  7904. var mat = (destData[i]) || (destData[i] = new Matrix4x4());
  7905. value.cloneTo(mat);
  7906. destData[i] = mat;
  7907. dest.setMatrix4x4(i, mat);
  7908. }
  7909. else if (value instanceof Laya.BaseTexture) {
  7910. destData[i] = value;
  7911. dest.setTexture(i, value);
  7912. }
  7913. }
  7914. }
  7915. this._defineDatas.cloneTo(dest._defineDatas);
  7916. }
  7917. _initDataForNative() {
  7918. var length = 8;
  7919. this._frameCount = -1;
  7920. this._runtimeCopyValues.length = 0;
  7921. this._nativeArray = [];
  7922. this._data = new ArrayBuffer(length * 4);
  7923. this._int32Data = new Int32Array(this._data);
  7924. this._float32Data = new Float32Array(this._data);
  7925. Laya.LayaGL.instance.createArrayBufferRef(this._data, Laya.LayaGL.ARRAY_BUFFER_TYPE_DATA, true);
  7926. }
  7927. needRenewArrayBufferForNative(index) {
  7928. if (index >= this._int32Data.length) {
  7929. var nByteLen = (index + 1) * 4;
  7930. var pre = this._int32Data;
  7931. var preConchRef = this._data["conchRef"];
  7932. var prePtrID = this._data["_ptrID"];
  7933. this._data = new ArrayBuffer(nByteLen);
  7934. this._int32Data = new Int32Array(this._data);
  7935. this._float32Data = new Float32Array(this._data);
  7936. this._data["conchRef"] = preConchRef;
  7937. this._data["_ptrID"] = prePtrID;
  7938. pre && this._int32Data.set(pre, 0);
  7939. var layagl = Laya.LayaGL.instance;
  7940. if (layagl.updateArrayBufferRef) {
  7941. layagl.updateArrayBufferRef(this._data['_ptrID'], preConchRef.isSyncToRender(), this._data);
  7942. }
  7943. else {
  7944. window.conch.updateArrayBufferRef(this._data['_ptrID'], preConchRef.isSyncToRender(), this._data);
  7945. }
  7946. }
  7947. }
  7948. getDataForNative() {
  7949. return this._nativeArray;
  7950. }
  7951. getIntForNative(index) {
  7952. return this._int32Data[index];
  7953. }
  7954. setIntForNative(index, value) {
  7955. this.needRenewArrayBufferForNative(index);
  7956. this._int32Data[index] = value;
  7957. this._nativeArray[index] = value;
  7958. }
  7959. getBoolForNative(index) {
  7960. return this._int32Data[index] == 1;
  7961. }
  7962. setBoolForNative(index, value) {
  7963. this.needRenewArrayBufferForNative(index);
  7964. this._int32Data[index] = value ? 1 : 0;
  7965. this._nativeArray[index] = value;
  7966. }
  7967. getNumberForNative(index) {
  7968. return this._float32Data[index];
  7969. }
  7970. setNumberForNative(index, value) {
  7971. this.needRenewArrayBufferForNative(index);
  7972. this._float32Data[index] = value;
  7973. this._nativeArray[index] = value;
  7974. }
  7975. getMatrix4x4ForNative(index) {
  7976. return this._nativeArray[index];
  7977. }
  7978. setMatrix4x4ForNative(index, value) {
  7979. this.needRenewArrayBufferForNative(index);
  7980. this._nativeArray[index] = value;
  7981. var nPtrID = this.setReferenceForNative(value.elements);
  7982. this._int32Data[index] = nPtrID;
  7983. }
  7984. getVectorForNative(index) {
  7985. return this._nativeArray[index];
  7986. }
  7987. setVectorForNative(index, value) {
  7988. this.needRenewArrayBufferForNative(index);
  7989. this._nativeArray[index] = value;
  7990. if (!value.elements) {
  7991. value.forNativeElement();
  7992. }
  7993. var nPtrID = this.setReferenceForNative(value.elements);
  7994. this._int32Data[index] = nPtrID;
  7995. }
  7996. getVector2ForNative(index) {
  7997. return this._nativeArray[index];
  7998. }
  7999. setVector2ForNative(index, value) {
  8000. this.needRenewArrayBufferForNative(index);
  8001. this._nativeArray[index] = value;
  8002. if (!value.elements) {
  8003. value.forNativeElement();
  8004. }
  8005. var nPtrID = this.setReferenceForNative(value.elements);
  8006. this._int32Data[index] = nPtrID;
  8007. }
  8008. getVector3ForNative(index) {
  8009. return this._nativeArray[index];
  8010. }
  8011. setVector3ForNative(index, value) {
  8012. this.needRenewArrayBufferForNative(index);
  8013. this._nativeArray[index] = value;
  8014. if (!value.elements) {
  8015. value.forNativeElement();
  8016. }
  8017. var nPtrID = this.setReferenceForNative(value.elements);
  8018. this._int32Data[index] = nPtrID;
  8019. }
  8020. getQuaternionForNative(index) {
  8021. return this._nativeArray[index];
  8022. }
  8023. setQuaternionForNative(index, value) {
  8024. this.needRenewArrayBufferForNative(index);
  8025. this._nativeArray[index] = value;
  8026. if (!value.elements) {
  8027. value.forNativeElement();
  8028. }
  8029. var nPtrID = this.setReferenceForNative(value.elements);
  8030. this._int32Data[index] = nPtrID;
  8031. }
  8032. getBufferForNative(shaderIndex) {
  8033. return this._nativeArray[shaderIndex];
  8034. }
  8035. setBufferForNative(index, value) {
  8036. this.needRenewArrayBufferForNative(index);
  8037. this._nativeArray[index] = value;
  8038. var nPtrID = this.setReferenceForNative(value);
  8039. this._int32Data[index] = nPtrID;
  8040. }
  8041. getAttributeForNative(index) {
  8042. return this._nativeArray[index];
  8043. }
  8044. setAttributeForNative(index, value) {
  8045. this._nativeArray[index] = value;
  8046. if (!value["_ptrID"]) {
  8047. Laya.LayaGL.instance.createArrayBufferRef(value, Laya.LayaGL.ARRAY_BUFFER_TYPE_DATA, true);
  8048. }
  8049. Laya.LayaGL.instance.syncBufferToRenderThread(value);
  8050. this._int32Data[index] = value["_ptrID"];
  8051. }
  8052. getTextureForNative(index) {
  8053. return this._nativeArray[index];
  8054. }
  8055. setTextureForNative(index, value) {
  8056. if (!value)
  8057. return;
  8058. this.needRenewArrayBufferForNative(index);
  8059. var lastValue = this._nativeArray[index];
  8060. this._nativeArray[index] = value;
  8061. var glTexture = value._getSource() || value.defaulteTexture._getSource();
  8062. this._int32Data[index] = glTexture.id;
  8063. if (this._ownerResource && this._ownerResource.referenceCount > 0) {
  8064. (lastValue) && (lastValue._removeReference());
  8065. (value) && (value._addReference());
  8066. }
  8067. }
  8068. setReferenceForNative(value) {
  8069. this.clearRuntimeCopyArray();
  8070. var nRefID = 0;
  8071. var nPtrID = 0;
  8072. if (ShaderData._SET_RUNTIME_VALUE_MODE_REFERENCE_) {
  8073. Laya.LayaGL.instance.createArrayBufferRefs(value, Laya.LayaGL.ARRAY_BUFFER_TYPE_DATA, true, Laya.LayaGL.ARRAY_BUFFER_REF_REFERENCE);
  8074. nRefID = 0;
  8075. nPtrID = value.getPtrID(nRefID);
  8076. }
  8077. else {
  8078. Laya.LayaGL.instance.createArrayBufferRefs(value, Laya.LayaGL.ARRAY_BUFFER_TYPE_DATA, true, Laya.LayaGL.ARRAY_BUFFER_REF_COPY);
  8079. nRefID = value.getRefNum() - 1;
  8080. nPtrID = value.getPtrID(nRefID);
  8081. this._runtimeCopyValues.push({ "obj": value, "refID": nRefID, "ptrID": nPtrID });
  8082. }
  8083. Laya.LayaGL.instance.syncBufferToRenderThread(value, nRefID);
  8084. return nPtrID;
  8085. }
  8086. static setRuntimeValueMode(bReference) {
  8087. ShaderData._SET_RUNTIME_VALUE_MODE_REFERENCE_ = bReference;
  8088. }
  8089. clearRuntimeCopyArray() {
  8090. var currentFrame = Laya.Stat.loopCount;
  8091. if (this._frameCount != currentFrame) {
  8092. this._frameCount = currentFrame;
  8093. for (var i = 0, n = this._runtimeCopyValues.length; i < n; i++) {
  8094. var obj = this._runtimeCopyValues[i];
  8095. obj.obj.clearRefNum();
  8096. }
  8097. this._runtimeCopyValues.length = 0;
  8098. }
  8099. }
  8100. }
  8101. ShaderData._SET_RUNTIME_VALUE_MODE_REFERENCE_ = true;
  8102. class VertexDeclaration {
  8103. constructor(vertexStride, vertexElements) {
  8104. this._id = ++VertexDeclaration._uniqueIDCounter;
  8105. this._vertexElementsDic = {};
  8106. this._vertexStride = vertexStride;
  8107. this._vertexElements = vertexElements;
  8108. var count = vertexElements.length;
  8109. this._shaderValues = new ShaderData(null);
  8110. for (var j = 0; j < count; j++) {
  8111. var vertexElement = vertexElements[j];
  8112. var name = vertexElement._elementUsage;
  8113. this._vertexElementsDic[name] = vertexElement;
  8114. var value = new Int32Array(5);
  8115. var elmentInfo = VertexElementFormat.getElementInfos(vertexElement._elementFormat);
  8116. value[0] = elmentInfo[0];
  8117. value[1] = elmentInfo[1];
  8118. value[2] = elmentInfo[2];
  8119. value[3] = this._vertexStride;
  8120. value[4] = vertexElement._offset;
  8121. this._shaderValues.setAttribute(name, value);
  8122. }
  8123. }
  8124. get id() {
  8125. return this._id;
  8126. }
  8127. get vertexStride() {
  8128. return this._vertexStride;
  8129. }
  8130. get vertexElementCount() {
  8131. return this._vertexElements.length;
  8132. }
  8133. getVertexElementByIndex(index) {
  8134. return this._vertexElements[index];
  8135. }
  8136. getVertexElementByUsage(usage) {
  8137. return this._vertexElementsDic[usage];
  8138. }
  8139. }
  8140. VertexDeclaration._uniqueIDCounter = 1;
  8141. class VertexElement {
  8142. constructor(offset, elementFormat, elementUsage) {
  8143. this._offset = offset;
  8144. this._elementFormat = elementFormat;
  8145. this._elementUsage = elementUsage;
  8146. }
  8147. get offset() {
  8148. return this._offset;
  8149. }
  8150. get elementFormat() {
  8151. return this._elementFormat;
  8152. }
  8153. get elementUsage() {
  8154. return this._elementUsage;
  8155. }
  8156. }
  8157. class BufferState extends Laya.BufferStateBase {
  8158. constructor() {
  8159. super();
  8160. }
  8161. applyVertexBuffer(vertexBuffer) {
  8162. if (Laya.BufferStateBase._curBindedBufferState === this) {
  8163. var gl = Laya.LayaGL.instance;
  8164. var verDec = vertexBuffer.vertexDeclaration;
  8165. var valueData = verDec._shaderValues.getData();
  8166. this.vertexDeclaration = verDec;
  8167. vertexBuffer.bind();
  8168. for (var k in valueData) {
  8169. var loc = parseInt(k);
  8170. var attribute = valueData[k];
  8171. gl.enableVertexAttribArray(loc);
  8172. gl.vertexAttribPointer(loc, attribute[0], attribute[1], !!attribute[2], attribute[3], attribute[4]);
  8173. }
  8174. }
  8175. else {
  8176. throw "BufferState: must call bind() function first.";
  8177. }
  8178. }
  8179. applyVertexBuffers(vertexBuffers) {
  8180. if (Laya.BufferStateBase._curBindedBufferState === this) {
  8181. var gl = Laya.LayaGL.instance;
  8182. for (var i = 0, n = vertexBuffers.length; i < n; i++) {
  8183. var verBuf = vertexBuffers[i];
  8184. var verDec = verBuf.vertexDeclaration;
  8185. var valueData = verDec._shaderValues.getData();
  8186. verBuf.bind();
  8187. for (var k in valueData) {
  8188. var loc = parseInt(k);
  8189. var attribute = valueData[k];
  8190. gl.enableVertexAttribArray(loc);
  8191. gl.vertexAttribPointer(loc, attribute[0], attribute[1], !!attribute[2], attribute[3], attribute[4]);
  8192. }
  8193. }
  8194. }
  8195. else {
  8196. throw "BufferState: must call bind() function first.";
  8197. }
  8198. }
  8199. applyInstanceVertexBuffer(vertexBuffer) {
  8200. if (Laya.LayaGL.layaGPUInstance.supportInstance()) {
  8201. if (Laya.BufferStateBase._curBindedBufferState === this) {
  8202. var gl = Laya.LayaGL.instance;
  8203. var verDec = vertexBuffer.vertexDeclaration;
  8204. var valueData = verDec._shaderValues.getData();
  8205. vertexBuffer.bind();
  8206. for (var k in valueData) {
  8207. var loc = parseInt(k);
  8208. var attribute = valueData[k];
  8209. gl.enableVertexAttribArray(loc);
  8210. gl.vertexAttribPointer(loc, attribute[0], attribute[1], !!attribute[2], attribute[3], attribute[4]);
  8211. Laya.LayaGL.layaGPUInstance.vertexAttribDivisor(loc, 1);
  8212. }
  8213. }
  8214. else {
  8215. throw "BufferState: must call bind() function first.";
  8216. }
  8217. }
  8218. }
  8219. applyIndexBuffer(indexBuffer) {
  8220. if (Laya.BufferStateBase._curBindedBufferState === this) {
  8221. if (this._bindedIndexBuffer !== indexBuffer) {
  8222. indexBuffer._bindForVAO();
  8223. this._bindedIndexBuffer = indexBuffer;
  8224. }
  8225. }
  8226. else {
  8227. throw "BufferState: must call bind() function first.";
  8228. }
  8229. }
  8230. }
  8231. class ScreenQuad extends Laya.Resource {
  8232. constructor() {
  8233. super();
  8234. this._bufferState = new BufferState();
  8235. this._bufferStateInvertUV = new BufferState();
  8236. var gl = Laya.LayaGL.instance;
  8237. this._vertexBuffer = new VertexBuffer3D(16 * 4, gl.STATIC_DRAW, false);
  8238. this._vertexBuffer.vertexDeclaration = ScreenQuad._vertexDeclaration;
  8239. this._vertexBuffer.setData(ScreenQuad._vertices.buffer);
  8240. this._bufferState.bind();
  8241. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  8242. this._bufferState.unBind();
  8243. this._vertexBufferInvertUV = new VertexBuffer3D(16 * 4, gl.STATIC_DRAW, false);
  8244. this._vertexBufferInvertUV.vertexDeclaration = ScreenQuad._vertexDeclaration;
  8245. this._vertexBufferInvertUV.setData(ScreenQuad._verticesInvertUV.buffer);
  8246. this._bufferStateInvertUV.bind();
  8247. this._bufferStateInvertUV.applyVertexBuffer(this._vertexBufferInvertUV);
  8248. this._bufferStateInvertUV.unBind();
  8249. this._setGPUMemory(this._vertexBuffer._byteLength + this._vertexBufferInvertUV._byteLength);
  8250. }
  8251. static __init__() {
  8252. ScreenQuad._vertexDeclaration = new VertexDeclaration(16, [new VertexElement(0, VertexElementFormat.Vector4, ScreenQuad.SCREENQUAD_POSITION_UV)]);
  8253. ScreenQuad.instance = new ScreenQuad();
  8254. ScreenQuad.instance.lock = true;
  8255. }
  8256. render() {
  8257. var gl = Laya.LayaGL.instance;
  8258. this._bufferState.bind();
  8259. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  8260. Laya.Stat.renderBatches++;
  8261. }
  8262. renderInvertUV() {
  8263. var gl = Laya.LayaGL.instance;
  8264. this._bufferStateInvertUV.bind();
  8265. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  8266. Laya.Stat.renderBatches++;
  8267. }
  8268. destroy() {
  8269. super.destroy();
  8270. this._bufferState.destroy();
  8271. this._vertexBuffer.destroy();
  8272. this._bufferStateInvertUV.destroy();
  8273. this._vertexBufferInvertUV.destroy();
  8274. this._setGPUMemory(0);
  8275. }
  8276. }
  8277. ScreenQuad.SCREENQUAD_POSITION_UV = 0;
  8278. ScreenQuad._vertices = new Float32Array([1, 1, 1, 1, 1, -1, 1, 0, -1, 1, 0, 1, -1, -1, 0, 0]);
  8279. ScreenQuad._verticesInvertUV = new Float32Array([1, 1, 1, 0, 1, -1, 1, 1, -1, 1, 0, 0, -1, -1, 0, 1]);
  8280. class ScreenTriangle extends Laya.Resource {
  8281. constructor() {
  8282. super();
  8283. this._bufferState = new BufferState();
  8284. this._bufferStateInvertUV = new BufferState();
  8285. var gl = Laya.LayaGL.instance;
  8286. this._vertexBuffer = new VertexBuffer3D(12 * 4, gl.STATIC_DRAW, false);
  8287. this._vertexBuffer.vertexDeclaration = ScreenTriangle._vertexDeclaration;
  8288. this._vertexBuffer.setData(ScreenTriangle._vertices.buffer);
  8289. this._bufferState.bind();
  8290. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  8291. this._bufferState.unBind();
  8292. this._vertexBufferInvertUV = new VertexBuffer3D(12 * 4, gl.STATIC_DRAW, false);
  8293. this._vertexBufferInvertUV.vertexDeclaration = ScreenTriangle._vertexDeclaration;
  8294. this._vertexBufferInvertUV.setData(ScreenTriangle._verticesInvertUV.buffer);
  8295. this._bufferStateInvertUV.bind();
  8296. this._bufferStateInvertUV.applyVertexBuffer(this._vertexBufferInvertUV);
  8297. this._bufferStateInvertUV.unBind();
  8298. this._setGPUMemory(this._vertexBuffer._byteLength + this._vertexBufferInvertUV._byteLength);
  8299. }
  8300. static __init__() {
  8301. ScreenTriangle._vertexDeclaration = new VertexDeclaration(16, [new VertexElement(0, VertexElementFormat.Vector4, ScreenTriangle.SCREENTRIANGLE_POSITION_UV)]);
  8302. ScreenTriangle.instance = new ScreenTriangle();
  8303. ScreenTriangle.instance.lock = true;
  8304. }
  8305. render() {
  8306. var gl = Laya.LayaGL.instance;
  8307. this._bufferState.bind();
  8308. gl.drawArrays(gl.TRIANGLES, 0, 3);
  8309. Laya.Stat.renderBatches++;
  8310. }
  8311. renderInvertUV() {
  8312. var gl = Laya.LayaGL.instance;
  8313. this._bufferStateInvertUV.bind();
  8314. gl.drawArrays(gl.TRIANGLES, 0, 3);
  8315. Laya.Stat.renderBatches++;
  8316. }
  8317. destroy() {
  8318. super.destroy();
  8319. this._bufferState.destroy();
  8320. this._vertexBuffer.destroy();
  8321. this._bufferStateInvertUV.destroy();
  8322. this._vertexBufferInvertUV.destroy();
  8323. this._setGPUMemory(0);
  8324. }
  8325. }
  8326. ScreenTriangle.SCREENTRIANGLE_POSITION_UV = 0;
  8327. ScreenTriangle._vertices = new Float32Array([-1, -1, 0, 0, -1, 3, 0, 2, 3, -1, 2, 0]);
  8328. ScreenTriangle._verticesInvertUV = new Float32Array([-1, -1, 0, 1, -1, 3, 0, -1, 3, -1, 2, 1]);
  8329. class ShaderDefine {
  8330. constructor(index, value) {
  8331. this._index = index;
  8332. this._value = value;
  8333. }
  8334. }
  8335. class ShaderVariant {
  8336. constructor(shader, subShaderIndex, passIndex, defines) {
  8337. this._subShaderIndex = 0;
  8338. this._passIndex = 0;
  8339. this.setValue(shader, subShaderIndex, passIndex, defines);
  8340. }
  8341. get shader() {
  8342. return this._shader;
  8343. }
  8344. get subShaderIndex() {
  8345. return this._subShaderIndex;
  8346. }
  8347. get passIndex() {
  8348. return this._passIndex;
  8349. }
  8350. get defineNames() {
  8351. return this._defineNames;
  8352. }
  8353. setValue(shader, subShaderIndex, passIndex, defineNames) {
  8354. if (shader) {
  8355. var subShader = shader.getSubShaderAt(subShaderIndex);
  8356. if (subShader) {
  8357. var pass = subShader._passes[passIndex];
  8358. if (pass) {
  8359. var validDefine = pass._validDefine;
  8360. for (var i = 0, n = defineNames.length; i < n; i++) {
  8361. var defname = defineNames[i];
  8362. if (!validDefine.has(ILaya3D.Shader3D.getDefineByName(defname)))
  8363. throw `ShaderVariantInfo:Invalid defineName ${defname} in ${shader._name} subShaderIndex of ${subShaderIndex} passIndex of ${passIndex}.`;
  8364. }
  8365. }
  8366. else {
  8367. throw `ShaderVariantInfo:Shader don't have passIndex of ${passIndex}.`;
  8368. }
  8369. }
  8370. else {
  8371. throw `ShaderVariantInfo:Shader don't have subShaderIndex of ${subShaderIndex}.`;
  8372. }
  8373. }
  8374. else {
  8375. throw `ShaderVariantInfo:Shader can't be null.`;
  8376. }
  8377. this._shader = shader;
  8378. this._subShaderIndex = subShaderIndex;
  8379. this._passIndex = passIndex;
  8380. this._defineNames = defineNames;
  8381. }
  8382. equal(other) {
  8383. if (this._shader !== other._shader || this._subShaderIndex !== other._subShaderIndex || this._passIndex !== other._passIndex)
  8384. return false;
  8385. var defines = this._defineNames;
  8386. var otherDefines = other._defineNames;
  8387. if (defines.length !== otherDefines.length)
  8388. return false;
  8389. for (var i = 0, n = this._defineNames.length; i < n; i++) {
  8390. if (defines[i] !== otherDefines[i])
  8391. return false;
  8392. }
  8393. return true;
  8394. }
  8395. clone() {
  8396. var dest = new ShaderVariant(this._shader, this._subShaderIndex, this._passIndex, this._defineNames.slice());
  8397. return dest;
  8398. }
  8399. }
  8400. class ShaderVariantCollection {
  8401. constructor() {
  8402. this._allCompiled = false;
  8403. this._variants = [];
  8404. }
  8405. get allCompiled() {
  8406. return this._allCompiled;
  8407. }
  8408. get variantCount() {
  8409. return this._variants.length;
  8410. }
  8411. add(variant) {
  8412. for (var i = 0, n = this._variants.length; i < n; i++) {
  8413. if (this._variants[i].equal(variant))
  8414. return false;
  8415. }
  8416. this._variants.push(variant.clone());
  8417. this._allCompiled = false;
  8418. return true;
  8419. }
  8420. remove(variant) {
  8421. for (var i = 0, n = this._variants.length; i < n; i++) {
  8422. if (this._variants[i].equal(variant)) {
  8423. this._variants.splice(i, 1);
  8424. return true;
  8425. }
  8426. }
  8427. return false;
  8428. }
  8429. contatins(variant) {
  8430. for (var i = 0, n = this._variants.length; i < n; i++) {
  8431. if (this._variants[i].equal(variant))
  8432. return true;
  8433. }
  8434. return false;
  8435. }
  8436. getByIndex(index) {
  8437. return this._variants[index];
  8438. }
  8439. clear() {
  8440. this._variants.length = 0;
  8441. }
  8442. compile() {
  8443. if (!this._allCompiled) {
  8444. var variants = this._variants;
  8445. for (var i = 0, n = variants.length; i < n; i++) {
  8446. var variant = variants[i];
  8447. ILaya3D.Shader3D.compileShaderByDefineNames(variant._shader._name, variant._subShaderIndex, variant._passIndex, variant._defineNames);
  8448. }
  8449. this._allCompiled = true;
  8450. }
  8451. }
  8452. }
  8453. class Shader3D {
  8454. constructor(name, attributeMap, uniformMap, enableInstancing, supportReflectionProbe) {
  8455. this._attributeMap = null;
  8456. this._uniformMap = null;
  8457. this._enableInstancing = false;
  8458. this._supportReflectionProbe = false;
  8459. this._subShaders = [];
  8460. this._name = name;
  8461. this._attributeMap = attributeMap;
  8462. this._uniformMap = uniformMap;
  8463. this._enableInstancing = enableInstancing;
  8464. this._supportReflectionProbe = supportReflectionProbe;
  8465. }
  8466. static _getNamesByDefineData(defineData, out) {
  8467. var maskMap = Shader3D._maskMap;
  8468. var mask = defineData._mask;
  8469. out.length = 0;
  8470. for (var i = 0, n = defineData._length; i < n; i++) {
  8471. var subMaskMap = maskMap[i];
  8472. var subMask = mask[i];
  8473. for (var j = 0; j < 32; j++) {
  8474. var d = 1 << j;
  8475. if (subMask > 0 && d > subMask)
  8476. break;
  8477. if (subMask & d)
  8478. out.push(subMaskMap[d]);
  8479. }
  8480. }
  8481. }
  8482. static getDefineByName(name) {
  8483. var define = Shader3D._defineMap[name];
  8484. if (!define) {
  8485. var maskMap = Shader3D._maskMap;
  8486. var counter = Shader3D._defineCounter;
  8487. var index = Math.floor(counter / 32);
  8488. var value = 1 << counter % 32;
  8489. define = new ShaderDefine(index, value);
  8490. Shader3D._defineMap[name] = define;
  8491. if (index == maskMap.length) {
  8492. maskMap.length++;
  8493. maskMap[index] = {};
  8494. }
  8495. maskMap[index][value] = name;
  8496. Shader3D._defineCounter++;
  8497. }
  8498. return define;
  8499. }
  8500. static propertyNameToID(name) {
  8501. if (Shader3D._propertyNameMap[name] != null) {
  8502. return Shader3D._propertyNameMap[name];
  8503. }
  8504. else {
  8505. var id = Shader3D._propertyNameCounter++;
  8506. Shader3D._propertyNameMap[name] = id;
  8507. return id;
  8508. }
  8509. }
  8510. static getAttributeMapByDefine(defineString, attributeMap) {
  8511. var newAttributeMap = {};
  8512. for (var value in attributeMap) {
  8513. newAttributeMap[value] = attributeMap[value];
  8514. }
  8515. for (var i = 0, n = defineString.length; i < n; i++) {
  8516. var def = defineString[i];
  8517. switch (def) {
  8518. case "SIMPLEBONE":
  8519. if (attributeMap["a_Texcoord1"]) {
  8520. newAttributeMap["a_SimpleTextureParams"] = attributeMap["a_Texcoord1"];
  8521. delete newAttributeMap["a_Texcoord1"];
  8522. }
  8523. newAttributeMap["a_SimpleTextureParams"] = 7;
  8524. break;
  8525. }
  8526. }
  8527. return newAttributeMap;
  8528. }
  8529. static addInclude(fileName, txt) {
  8530. txt = txt.replace(Laya.ShaderCompile._clearCR, "");
  8531. Laya.ShaderCompile.addInclude(fileName, txt);
  8532. }
  8533. static compileShaderByDefineNames(shaderName, subShaderIndex, passIndex, defineNames) {
  8534. var shader = Shader3D.find(shaderName);
  8535. if (shader) {
  8536. var subShader = shader.getSubShaderAt(subShaderIndex);
  8537. if (subShader) {
  8538. var pass = subShader._passes[passIndex];
  8539. if (pass) {
  8540. var compileDefineDatas = Shader3D._compileDefineDatas;
  8541. compileDefineDatas.clear();
  8542. for (var i = 0, n = defineNames.length; i < n; i++)
  8543. compileDefineDatas.add(Shader3D.getDefineByName(defineNames[i]));
  8544. pass.withCompile(compileDefineDatas);
  8545. }
  8546. else {
  8547. console.warn("Shader3D: unknown passIndex.");
  8548. }
  8549. }
  8550. else {
  8551. console.warn("Shader3D: unknown subShaderIndex.");
  8552. }
  8553. }
  8554. else {
  8555. console.warn("Shader3D: unknown shader name.");
  8556. }
  8557. }
  8558. static add(name, attributeMap = null, uniformMap = null, enableInstancing = false, supportReflectionProbe = false) {
  8559. return Shader3D._preCompileShader[name] = new Shader3D(name, attributeMap, uniformMap, enableInstancing, supportReflectionProbe);
  8560. }
  8561. static find(name) {
  8562. return Shader3D._preCompileShader[name];
  8563. }
  8564. get name() {
  8565. return this._name;
  8566. }
  8567. addSubShader(subShader) {
  8568. this._subShaders.push(subShader);
  8569. subShader._owner = this;
  8570. }
  8571. getSubShaderAt(index) {
  8572. return this._subShaders[index];
  8573. }
  8574. static compileShader(shaderName, subShaderIndex, passIndex, ...defineMask) {
  8575. var shader = Shader3D.find(shaderName);
  8576. if (shader) {
  8577. var subShader = shader.getSubShaderAt(subShaderIndex);
  8578. if (subShader) {
  8579. var pass = subShader._passes[passIndex];
  8580. if (pass) {
  8581. var compileDefineDatas = Shader3D._compileDefineDatas;
  8582. var mask = compileDefineDatas._mask;
  8583. mask.length = 0;
  8584. for (var i = 0, n = defineMask.length; i < n; i++)
  8585. mask.push(defineMask[i]);
  8586. compileDefineDatas._length = defineMask.length;
  8587. pass.withCompile(compileDefineDatas);
  8588. }
  8589. else {
  8590. console.warn("Shader3D: unknown passIndex.");
  8591. }
  8592. }
  8593. else {
  8594. console.warn("Shader3D: unknown subShaderIndex.");
  8595. }
  8596. }
  8597. else {
  8598. console.warn("Shader3D: unknown shader name.");
  8599. }
  8600. }
  8601. }
  8602. Shader3D._compileDefineDatas = new DefineDatas();
  8603. Shader3D.RENDER_STATE_CULL = 0;
  8604. Shader3D.RENDER_STATE_BLEND = 1;
  8605. Shader3D.RENDER_STATE_BLEND_SRC = 2;
  8606. Shader3D.RENDER_STATE_BLEND_DST = 3;
  8607. Shader3D.RENDER_STATE_BLEND_SRC_RGB = 4;
  8608. Shader3D.RENDER_STATE_BLEND_DST_RGB = 5;
  8609. Shader3D.RENDER_STATE_BLEND_SRC_ALPHA = 6;
  8610. Shader3D.RENDER_STATE_BLEND_DST_ALPHA = 7;
  8611. Shader3D.RENDER_STATE_BLEND_CONST_COLOR = 8;
  8612. Shader3D.RENDER_STATE_BLEND_EQUATION = 9;
  8613. Shader3D.RENDER_STATE_BLEND_EQUATION_RGB = 10;
  8614. Shader3D.RENDER_STATE_BLEND_EQUATION_ALPHA = 11;
  8615. Shader3D.RENDER_STATE_DEPTH_TEST = 12;
  8616. Shader3D.RENDER_STATE_DEPTH_WRITE = 13;
  8617. Shader3D.PERIOD_CUSTOM = 0;
  8618. Shader3D.PERIOD_MATERIAL = 1;
  8619. Shader3D.PERIOD_SPRITE = 2;
  8620. Shader3D.PERIOD_CAMERA = 3;
  8621. Shader3D.PERIOD_SCENE = 4;
  8622. Shader3D._propertyNameCounter = 0;
  8623. Shader3D._propertyNameMap = {};
  8624. Shader3D._defineCounter = 0;
  8625. Shader3D._defineMap = {};
  8626. Shader3D._preCompileShader = {};
  8627. Shader3D._maskMap = [];
  8628. Shader3D.debugMode = false;
  8629. Shader3D.debugShaderVariantCollection = new ShaderVariantCollection();
  8630. class Command {
  8631. constructor() {
  8632. this._commandBuffer = null;
  8633. }
  8634. static __init__() {
  8635. Command._screenShaderData = new ShaderData();
  8636. Command._screenShader = Shader3D.find("BlitScreen");
  8637. }
  8638. run() {
  8639. }
  8640. recover() {
  8641. this._commandBuffer = null;
  8642. }
  8643. setContext(context) {
  8644. this._context = context;
  8645. }
  8646. }
  8647. Command.SCREENTEXTURE_NAME = "u_MainTex";
  8648. Command.SCREENTEXTUREOFFSETSCALE_NAME = "u_OffsetScale";
  8649. Command.MAINTEXTURE_TEXELSIZE_NAME = "u_MainTex_TexelSize";
  8650. Command.SCREENTEXTURE_ID = Shader3D.propertyNameToID(Command.SCREENTEXTURE_NAME);
  8651. Command.SCREENTEXTUREOFFSETSCALE_ID = Shader3D.propertyNameToID(Command.SCREENTEXTUREOFFSETSCALE_NAME);
  8652. Command.MAINTEXTURE_TEXELSIZE_ID = Shader3D.propertyNameToID(Command.MAINTEXTURE_TEXELSIZE_NAME);
  8653. class BlitScreenQuadCMD extends Command {
  8654. constructor() {
  8655. super(...arguments);
  8656. this._source = null;
  8657. this._dest = null;
  8658. this._offsetScale = null;
  8659. this._shader = null;
  8660. this._shaderData = null;
  8661. this._subShader = 0;
  8662. this._sourceTexelSize = new Vector4();
  8663. this._screenType = 0;
  8664. this._drawDefineCavans = false;
  8665. }
  8666. static create(source, dest, offsetScale = null, shader = null, shaderData = null, subShader = 0, screenType = BlitScreenQuadCMD._SCREENTYPE_QUAD, commandbuffer = null, definedCanvas = false) {
  8667. var cmd;
  8668. cmd = BlitScreenQuadCMD._pool.length > 0 ? BlitScreenQuadCMD._pool.pop() : new BlitScreenQuadCMD();
  8669. cmd._source = source;
  8670. cmd._dest = dest;
  8671. cmd._offsetScale = offsetScale;
  8672. cmd._shader = shader;
  8673. cmd._shaderData = shaderData;
  8674. cmd._subShader = subShader;
  8675. cmd._screenType = screenType;
  8676. cmd._commandBuffer = commandbuffer;
  8677. cmd._drawDefineCavans = definedCanvas;
  8678. return cmd;
  8679. }
  8680. run() {
  8681. var source;
  8682. if (!this._source) {
  8683. if (!this._commandBuffer._camera._internalRenderTexture)
  8684. throw "camera internalRenderTexture is null,please set camera enableBuiltInRenderTexture";
  8685. source = this._commandBuffer._camera._internalRenderTexture;
  8686. }
  8687. else
  8688. source = this._source;
  8689. var shader = this._shader || Command._screenShader;
  8690. var shaderData = this._shaderData || Command._screenShaderData;
  8691. var dest = this._dest ? this._dest : (this._drawDefineCavans ? this._dest : this._commandBuffer._camera._internalRenderTexture);
  8692. Laya.LayaGL.instance.viewport(0, 0, dest ? dest.width : RenderContext3D.clientWidth, dest ? dest.height : RenderContext3D.clientHeight);
  8693. shaderData.setTexture(Command.SCREENTEXTURE_ID, source);
  8694. shaderData.setVector(Command.SCREENTEXTUREOFFSETSCALE_ID, this._offsetScale || BlitScreenQuadCMD._defaultOffsetScale);
  8695. this._sourceTexelSize.setValue(1.0 / source.width, 1.0 / source.height, source.width, source.height);
  8696. shaderData.setVector(Command.MAINTEXTURE_TEXELSIZE_ID, this._sourceTexelSize);
  8697. (RenderTexture.currentActive) && (RenderTexture.currentActive._end());
  8698. (dest) && (dest._start());
  8699. var subShader = shader.getSubShaderAt(this._subShader);
  8700. var passes = subShader._passes;
  8701. for (var i = 0, n = passes.length; i < n; i++) {
  8702. var comDef = BlitScreenQuadCMD._compileDefine;
  8703. shaderData._defineDatas.cloneTo(comDef);
  8704. var shaderPass = passes[i].withCompile(comDef);
  8705. shaderPass.bind();
  8706. shaderPass.uploadUniforms(shaderPass._materialUniformParamsMap, shaderData, true);
  8707. shaderPass.uploadRenderStateBlendDepth(shaderData);
  8708. shaderPass.uploadRenderStateFrontFace(shaderData, false, null);
  8709. switch (this._screenType) {
  8710. case BlitScreenQuadCMD._SCREENTYPE_QUAD:
  8711. RenderContext3D._instance.invertY ? ScreenQuad.instance.renderInvertUV() : ScreenQuad.instance.render();
  8712. break;
  8713. case BlitScreenQuadCMD._SCREENTYPE_TRIANGLE:
  8714. RenderContext3D._instance.invertY ? ScreenTriangle.instance.renderInvertUV() : ScreenTriangle.instance.render();
  8715. break;
  8716. default:
  8717. throw "BlitScreenQuadCMD:unknown screen Type.";
  8718. }
  8719. }
  8720. (dest) && (dest._end());
  8721. }
  8722. recover() {
  8723. BlitScreenQuadCMD._pool.push(this);
  8724. this._source = null;
  8725. this._dest = null;
  8726. this._offsetScale = null;
  8727. this._shader = null;
  8728. this._shaderData = null;
  8729. this._drawDefineCavans = false;
  8730. super.recover();
  8731. }
  8732. }
  8733. BlitScreenQuadCMD._SCREENTYPE_QUAD = 0;
  8734. BlitScreenQuadCMD._SCREENTYPE_TRIANGLE = 1;
  8735. BlitScreenQuadCMD._compileDefine = new DefineDatas();
  8736. BlitScreenQuadCMD._pool = [];
  8737. BlitScreenQuadCMD._defaultOffsetScale = new Vector4(0, 0, 1, 1);
  8738. class SetRenderTargetCMD extends Command {
  8739. constructor() {
  8740. super(...arguments);
  8741. this._renderTexture = null;
  8742. }
  8743. static create(renderTexture) {
  8744. var cmd;
  8745. cmd = SetRenderTargetCMD._pool.length > 0 ? SetRenderTargetCMD._pool.pop() : new SetRenderTargetCMD();
  8746. cmd._renderTexture = renderTexture;
  8747. return cmd;
  8748. }
  8749. run() {
  8750. (RenderTexture.currentActive) && (RenderTexture.currentActive._end());
  8751. Laya.LayaGL.instance.viewport(0, 0, this._renderTexture.width, this._renderTexture.height);
  8752. this._renderTexture._start();
  8753. }
  8754. recover() {
  8755. SetRenderTargetCMD._pool.push(this);
  8756. this._renderTexture = null;
  8757. }
  8758. }
  8759. SetRenderTargetCMD._pool = [];
  8760. (function (ShaderDataType) {
  8761. ShaderDataType[ShaderDataType["Int"] = 0] = "Int";
  8762. ShaderDataType[ShaderDataType["Bool"] = 1] = "Bool";
  8763. ShaderDataType[ShaderDataType["Number"] = 2] = "Number";
  8764. ShaderDataType[ShaderDataType["Vector2"] = 3] = "Vector2";
  8765. ShaderDataType[ShaderDataType["Vector3"] = 4] = "Vector3";
  8766. ShaderDataType[ShaderDataType["Vector4"] = 5] = "Vector4";
  8767. ShaderDataType[ShaderDataType["Quaternion"] = 6] = "Quaternion";
  8768. ShaderDataType[ShaderDataType["Matrix4x4"] = 7] = "Matrix4x4";
  8769. ShaderDataType[ShaderDataType["Buffer"] = 8] = "Buffer";
  8770. ShaderDataType[ShaderDataType["Texture"] = 9] = "Texture";
  8771. })(exports.ShaderDataType || (exports.ShaderDataType = {}));
  8772. class SetShaderDataCMD extends Command {
  8773. constructor() {
  8774. super(...arguments);
  8775. this._shaderData = null;
  8776. this._nameID = 0;
  8777. this._value = null;
  8778. this._dataType = -1;
  8779. }
  8780. static create(shaderData, nameID, value, shaderDataType, commandBuffer) {
  8781. var cmd;
  8782. cmd = SetShaderDataCMD._pool.length > 0 ? SetShaderDataCMD._pool.pop() : new SetShaderDataCMD();
  8783. cmd._shaderData = shaderData;
  8784. cmd._nameID = nameID;
  8785. cmd._value = value;
  8786. cmd._dataType = shaderDataType;
  8787. cmd._commandBuffer = commandBuffer;
  8788. return cmd;
  8789. }
  8790. run() {
  8791. switch (this._dataType) {
  8792. case exports.ShaderDataType.Int:
  8793. this._shaderData.setInt(this._nameID, this._value);
  8794. break;
  8795. case exports.ShaderDataType.Number:
  8796. this._shaderData.setNumber(this._nameID, this._value);
  8797. break;
  8798. case exports.ShaderDataType.Bool:
  8799. this._shaderData.setBool(this._nameID, this._value);
  8800. break;
  8801. case exports.ShaderDataType.Matrix4x4:
  8802. this._shaderData.setMatrix4x4(this._nameID, this._value);
  8803. break;
  8804. case exports.ShaderDataType.Quaternion:
  8805. this._shaderData.setQuaternion(this._nameID, this._value);
  8806. break;
  8807. case exports.ShaderDataType.Texture:
  8808. this._shaderData.setTexture(this._nameID, this._value);
  8809. break;
  8810. case exports.ShaderDataType.Vector4:
  8811. this._shaderData.setVector(this._nameID, this._value);
  8812. break;
  8813. case exports.ShaderDataType.Vector2:
  8814. this._shaderData.setVector2(this._nameID, this._value);
  8815. break;
  8816. case exports.ShaderDataType.Vector3:
  8817. this._shaderData.setVector3(this._nameID, this._value);
  8818. break;
  8819. case exports.ShaderDataType.Buffer:
  8820. this._shaderData.setBuffer(this._nameID, this._value);
  8821. break;
  8822. default:
  8823. throw "no type shaderValue on this CommendBuffer";
  8824. }
  8825. }
  8826. recover() {
  8827. SetShaderDataCMD._pool.push(this);
  8828. this._shaderData = null;
  8829. this._nameID = 0;
  8830. this._value = null;
  8831. this._dataType = -1;
  8832. }
  8833. }
  8834. SetShaderDataCMD._pool = [];
  8835. class Sprite3D extends Laya.Node {
  8836. constructor(name = null, isStatic = false) {
  8837. super();
  8838. this._needProcessCollisions = false;
  8839. this._needProcessTriggers = false;
  8840. this._id = ++Sprite3D._uniqueIDCounter;
  8841. this._transform = new Transform3D(this);
  8842. this._isStatic = isStatic;
  8843. this.layer = 0;
  8844. this.name = name ? name : "New Sprite3D";
  8845. }
  8846. static __init__() {
  8847. }
  8848. static instantiate(original, parent = null, worldPositionStays = true, position = null, rotation = null) {
  8849. var destSprite3D = original.clone();
  8850. (parent) && (parent.addChild(destSprite3D));
  8851. var transform = destSprite3D.transform;
  8852. if (worldPositionStays) {
  8853. var worldMatrix = transform.worldMatrix;
  8854. original.transform.worldMatrix.cloneTo(worldMatrix);
  8855. transform.worldMatrix = worldMatrix;
  8856. }
  8857. else {
  8858. (position) && (transform.position = position);
  8859. (rotation) && (transform.rotation = rotation);
  8860. }
  8861. return destSprite3D;
  8862. }
  8863. static load(url, complete) {
  8864. Laya.Laya.loader.create(url, complete, null, Sprite3D.HIERARCHY);
  8865. }
  8866. get id() {
  8867. return this._id;
  8868. }
  8869. get layer() {
  8870. return this._layer;
  8871. }
  8872. set layer(value) {
  8873. if (this._layer !== value) {
  8874. if (value >= 0 && value <= 30) {
  8875. this._layer = value;
  8876. }
  8877. else {
  8878. throw new Error("Layer value must be 0-30.");
  8879. }
  8880. }
  8881. }
  8882. get url() {
  8883. return this._url;
  8884. }
  8885. get isStatic() {
  8886. return this._isStatic;
  8887. }
  8888. get transform() {
  8889. return this._transform;
  8890. }
  8891. _setCreateURL(url) {
  8892. this._url = Laya.URL.formatURL(url);
  8893. }
  8894. _changeAnimatorsToLinkSprite3D(sprite3D, isLink, path) {
  8895. var animator = this.getComponent(Animator);
  8896. if (animator) {
  8897. if (!animator.avatar)
  8898. sprite3D._changeAnimatorToLinkSprite3DNoAvatar(animator, isLink, path);
  8899. }
  8900. if (this._parent && this._parent instanceof Sprite3D) {
  8901. path.unshift(this._parent.name);
  8902. var p = this._parent;
  8903. (p._hierarchyAnimator) && (p._changeAnimatorsToLinkSprite3D(sprite3D, isLink, path));
  8904. }
  8905. }
  8906. _setHierarchyAnimator(animator, parentAnimator) {
  8907. this._changeHierarchyAnimator(animator);
  8908. this._changeAnimatorAvatar(animator.avatar);
  8909. for (var i = 0, n = this._children.length; i < n; i++) {
  8910. var child = this._children[i];
  8911. (child._hierarchyAnimator == parentAnimator) && (child._setHierarchyAnimator(animator, parentAnimator));
  8912. }
  8913. }
  8914. _clearHierarchyAnimator(animator, parentAnimator) {
  8915. this._changeHierarchyAnimator(parentAnimator);
  8916. this._changeAnimatorAvatar(parentAnimator ? parentAnimator.avatar : null);
  8917. for (var i = 0, n = this._children.length; i < n; i++) {
  8918. var child = this._children[i];
  8919. (child._hierarchyAnimator == animator) && (child._clearHierarchyAnimator(animator, parentAnimator));
  8920. }
  8921. }
  8922. _changeHierarchyAnimatorAvatar(animator, avatar) {
  8923. this._changeAnimatorAvatar(avatar);
  8924. for (var i = 0, n = this._children.length; i < n; i++) {
  8925. var child = this._children[i];
  8926. (child._hierarchyAnimator == animator) && (child._changeHierarchyAnimatorAvatar(animator, avatar));
  8927. }
  8928. }
  8929. _changeAnimatorToLinkSprite3DNoAvatar(animator, isLink, path) {
  8930. animator._handleSpriteOwnersBySprite(isLink, path, this);
  8931. for (var i = 0, n = this._children.length; i < n; i++) {
  8932. var child = this._children[i];
  8933. var index = path.length;
  8934. path.push(child.name);
  8935. child._changeAnimatorToLinkSprite3DNoAvatar(animator, isLink, path);
  8936. path.splice(index, 1);
  8937. }
  8938. }
  8939. _changeHierarchyAnimator(animator) {
  8940. this._hierarchyAnimator = animator;
  8941. }
  8942. _changeAnimatorAvatar(avatar) {
  8943. }
  8944. _onAdded() {
  8945. if (this._parent instanceof Sprite3D) {
  8946. var parent3D = this._parent;
  8947. this.transform._setParent(parent3D.transform);
  8948. if (parent3D._hierarchyAnimator) {
  8949. (!this._hierarchyAnimator) && (this._setHierarchyAnimator(parent3D._hierarchyAnimator, null));
  8950. parent3D._changeAnimatorsToLinkSprite3D(this, true, [this.name]);
  8951. }
  8952. }
  8953. super._onAdded();
  8954. }
  8955. _onRemoved() {
  8956. super._onRemoved();
  8957. if (this._parent instanceof Sprite3D) {
  8958. var parent3D = this._parent;
  8959. this.transform._setParent(null);
  8960. if (parent3D._hierarchyAnimator) {
  8961. (this._hierarchyAnimator == parent3D._hierarchyAnimator) && (this._clearHierarchyAnimator(parent3D._hierarchyAnimator, null));
  8962. parent3D._changeAnimatorsToLinkSprite3D(this, false, [this.name]);
  8963. }
  8964. }
  8965. }
  8966. _parse(data, spriteMap) {
  8967. (data.isStatic !== undefined) && (this._isStatic = data.isStatic);
  8968. (data.active !== undefined) && (this.active = data.active);
  8969. (data.name != undefined) && (this.name = data.name);
  8970. if (data.position !== undefined) {
  8971. var loccalPosition = this.transform.localPosition;
  8972. loccalPosition.fromArray(data.position);
  8973. this.transform.localPosition = loccalPosition;
  8974. }
  8975. if (data.rotationEuler !== undefined) {
  8976. var localRotationEuler = this.transform.localRotationEuler;
  8977. localRotationEuler.fromArray(data.rotationEuler);
  8978. this.transform.localRotationEuler = localRotationEuler;
  8979. }
  8980. if (data.rotation !== undefined) {
  8981. var localRotation = this.transform.localRotation;
  8982. localRotation.fromArray(data.rotation);
  8983. this.transform.localRotation = localRotation;
  8984. }
  8985. if (data.scale !== undefined) {
  8986. var localScale = this.transform.localScale;
  8987. localScale.fromArray(data.scale);
  8988. this.transform.localScale = localScale;
  8989. }
  8990. (data.layer != undefined) && (this.layer = data.layer);
  8991. }
  8992. _cloneTo(destObject, srcRoot, dstRoot) {
  8993. if (this.destroyed)
  8994. throw new Error("Sprite3D: Can't be cloned if the Sprite3D has destroyed.");
  8995. var destSprite3D = destObject;
  8996. var trans = this._transform;
  8997. var destTrans = destSprite3D._transform;
  8998. destSprite3D.name = this.name;
  8999. destSprite3D.destroyed = this.destroyed;
  9000. destSprite3D.active = this.active;
  9001. destTrans.localPosition = trans.localPosition;
  9002. destTrans.localRotation = trans.localRotation;
  9003. destTrans.localScale = trans.localScale;
  9004. destSprite3D._isStatic = this._isStatic;
  9005. destSprite3D.layer = this.layer;
  9006. super._cloneTo(destSprite3D, srcRoot, dstRoot);
  9007. }
  9008. static _createSprite3DInstance(scrSprite) {
  9009. var node = scrSprite._create();
  9010. var children = scrSprite._children;
  9011. for (var i = 0, n = children.length; i < n; i++) {
  9012. var child = Sprite3D._createSprite3DInstance(children[i]);
  9013. node.addChild(child);
  9014. }
  9015. return node;
  9016. }
  9017. static _parseSprite3DInstance(srcRoot, dstRoot, scrSprite, dstSprite) {
  9018. var srcChildren = scrSprite._children;
  9019. var dstChildren = dstSprite._children;
  9020. for (var i = 0, n = srcChildren.length; i < n; i++)
  9021. Sprite3D._parseSprite3DInstance(srcRoot, dstRoot, srcChildren[i], dstChildren[i]);
  9022. scrSprite._cloneTo(dstSprite, srcRoot, dstRoot);
  9023. }
  9024. clone() {
  9025. var dstSprite3D = Sprite3D._createSprite3DInstance(this);
  9026. Sprite3D._parseSprite3DInstance(this, dstSprite3D, this, dstSprite3D);
  9027. return dstSprite3D;
  9028. }
  9029. destroy(destroyChild = true) {
  9030. if (this.destroyed)
  9031. return;
  9032. super.destroy(destroyChild);
  9033. this._transform = null;
  9034. this._scripts = null;
  9035. this._url && Laya.Loader.clearRes(this._url);
  9036. }
  9037. _create() {
  9038. return new Sprite3D();
  9039. }
  9040. }
  9041. Sprite3D.HIERARCHY = "HIERARCHY";
  9042. Sprite3D.WORLDMATRIX = Shader3D.propertyNameToID("u_WorldMat");
  9043. Sprite3D.MVPMATRIX = Shader3D.propertyNameToID("u_MvpMatrix");
  9044. Sprite3D._uniqueIDCounter = 0;
  9045. class DrawMeshCMD extends Command {
  9046. constructor() {
  9047. super();
  9048. this._projectionViewWorldMatrix = new Matrix4x4();
  9049. this._renderShaderValue = new ShaderData();
  9050. this._renderShaderValue = new ShaderData(null);
  9051. }
  9052. static create(mesh, matrix, material, subMeshIndex, subShaderIndex, commandBuffer) {
  9053. var cmd;
  9054. cmd = DrawMeshCMD._pool.length > 0 ? DrawMeshCMD._pool.pop() : new DrawMeshCMD();
  9055. cmd._mesh = mesh;
  9056. cmd._matrix = matrix;
  9057. cmd._material = material;
  9058. cmd._subMeshIndex = subMeshIndex;
  9059. cmd._subShaderIndex = subShaderIndex;
  9060. cmd._commandBuffer = commandBuffer;
  9061. return cmd;
  9062. }
  9063. run() {
  9064. var renderSubShader = this._material._shader.getSubShaderAt(this._subShaderIndex);
  9065. this.setContext(this._commandBuffer._context);
  9066. var context = this._context;
  9067. var forceInvertFace = context.invertY;
  9068. var scene = context.scene;
  9069. var cameraShaderValue = context.cameraShaderValue;
  9070. var projectionView = context.projectionViewMatrix;
  9071. Matrix4x4.multiply(projectionView, this._matrix, this._projectionViewWorldMatrix);
  9072. this._renderShaderValue.setMatrix4x4(Sprite3D.WORLDMATRIX, this._matrix);
  9073. this._renderShaderValue.setMatrix4x4(Sprite3D.MVPMATRIX, this._projectionViewWorldMatrix);
  9074. var currentPipelineMode = context.pipelineMode;
  9075. var passes = renderSubShader._passes;
  9076. for (var j = 0, m = passes.length; j < m; j++) {
  9077. var pass = passes[j];
  9078. if (pass._pipelineMode !== currentPipelineMode)
  9079. continue;
  9080. var comDef = DrawMeshCMD._compileDefine;
  9081. scene._shaderValues._defineDatas.cloneTo(comDef);
  9082. comDef.addDefineDatas(this._renderShaderValue._defineDatas);
  9083. comDef.addDefineDatas(this._material._shaderValues._defineDatas);
  9084. var shaderIns = context.shader = pass.withCompile(comDef);
  9085. shaderIns.bind();
  9086. shaderIns.uploadUniforms(shaderIns._sceneUniformParamsMap, scene._shaderValues, true);
  9087. shaderIns.uploadUniforms(shaderIns._spriteUniformParamsMap, this._renderShaderValue, true);
  9088. shaderIns.uploadUniforms(shaderIns._cameraUniformParamsMap, cameraShaderValue, true);
  9089. var matValues = this._material._shaderValues;
  9090. shaderIns.uploadUniforms(shaderIns._materialUniformParamsMap, matValues, true);
  9091. shaderIns.uploadRenderStateBlendDepth(matValues);
  9092. shaderIns.uploadRenderStateFrontFace(matValues, forceInvertFace, this._matrix.getInvertFront());
  9093. }
  9094. var subGeometryElement = this._mesh._subMeshes;
  9095. var subMeshRender;
  9096. if (this._subMeshIndex == -1) {
  9097. for (var i = 0, n = subGeometryElement.length; i < n; i++) {
  9098. subMeshRender = subGeometryElement[i];
  9099. if (subMeshRender._prepareRender(context)) {
  9100. subMeshRender._render(context);
  9101. }
  9102. }
  9103. }
  9104. else {
  9105. var subGeometryElement = this._mesh._subMeshes;
  9106. subMeshRender = subGeometryElement[this._subMeshIndex];
  9107. if (subMeshRender._prepareRender(context)) {
  9108. subMeshRender._render(context);
  9109. }
  9110. }
  9111. }
  9112. recover() {
  9113. DrawMeshCMD._pool.push(this);
  9114. this._renderShaderValue.clearDefine();
  9115. this._renderShaderValue._initData();
  9116. }
  9117. }
  9118. DrawMeshCMD._pool = [];
  9119. DrawMeshCMD._compileDefine = new DefineDatas();
  9120. class ClearRenderTextureCMD extends Command {
  9121. constructor() {
  9122. super(...arguments);
  9123. this._clearColor = false;
  9124. this._clearDepth = false;
  9125. this._backgroundColor = new Vector4();
  9126. this._depth = 1;
  9127. }
  9128. static create(clearColor, clearDepth, backgroundColor, depth = 1, commandBuffer) {
  9129. var cmd;
  9130. cmd = ClearRenderTextureCMD._pool.length > 0 ? ClearRenderTextureCMD._pool.pop() : new ClearRenderTextureCMD();
  9131. cmd._clearColor = clearColor;
  9132. cmd._clearDepth = clearDepth;
  9133. backgroundColor.cloneTo(cmd._backgroundColor);
  9134. cmd._depth = depth;
  9135. cmd._commandBuffer = commandBuffer;
  9136. return cmd;
  9137. }
  9138. run() {
  9139. var gl = Laya.LayaGL.instance;
  9140. var flag;
  9141. var backgroundColor = this._backgroundColor;
  9142. if (this._clearColor) {
  9143. gl.clearColor(backgroundColor.x, backgroundColor.y, backgroundColor.z, backgroundColor.w);
  9144. flag |= gl.COLOR_BUFFER_BIT;
  9145. }
  9146. if (this._clearDepth) {
  9147. gl.clearDepth(this._depth);
  9148. flag |= gl.DEPTH_BUFFER_BIT;
  9149. }
  9150. if (this._clearColor || this._clearDepth) {
  9151. gl.clear(flag);
  9152. }
  9153. }
  9154. recover() {
  9155. }
  9156. }
  9157. ClearRenderTextureCMD._pool = [];
  9158. class LightBound {
  9159. }
  9160. class ClusterData {
  9161. constructor() {
  9162. this.updateMark = -1;
  9163. this.pointLightCount = 0;
  9164. this.spotLightCount = 0;
  9165. this.indices = [];
  9166. }
  9167. }
  9168. class Cluster {
  9169. constructor(xSlices, ySlices, zSlices, maxLightsPerClusterAverage) {
  9170. this._updateMark = 0;
  9171. this._depthSliceParam = new Vector2();
  9172. this._xSlices = xSlices;
  9173. this._ySlices = ySlices;
  9174. this._zSlices = zSlices;
  9175. var clusterTexWidth = xSlices * ySlices;
  9176. var clisterTexHeight = zSlices * (1 + Math.ceil(maxLightsPerClusterAverage / 4));
  9177. this._clusterTexture = Utils3D._createFloatTextureBuffer(clusterTexWidth, clisterTexHeight);
  9178. this._clusterTexture.lock = true;
  9179. this._clusterPixels = new Float32Array(clusterTexWidth * clisterTexHeight * 4);
  9180. var clusterDatas = new Array(this._zSlices);
  9181. for (var z = 0; z < this._zSlices; z++) {
  9182. clusterDatas[z] = new Array(this._ySlices);
  9183. for (var y = 0; y < this._ySlices; y++) {
  9184. clusterDatas[z][y] = new Array(this._xSlices);
  9185. for (var x = 0; x < this._xSlices; x++)
  9186. clusterDatas[z][y][x] = new ClusterData();
  9187. }
  9188. }
  9189. this._clusterDatas = clusterDatas;
  9190. }
  9191. _insertSpotLightSphere(origin, forward, size, angle, testSphere) {
  9192. var V = Cluster._tempVector35;
  9193. V.x = testSphere.x - origin.x;
  9194. V.y = testSphere.y - origin.y;
  9195. V.z = testSphere.z - origin.z;
  9196. var VlenSq = Vector3.dot(V, V);
  9197. var sphereRadius = testSphere.w;
  9198. var rangeCull = VlenSq > sphereRadius * sphereRadius;
  9199. if (!rangeCull)
  9200. return false;
  9201. var V1len = Vector3.dot(V, forward);
  9202. var distanceClosestPoint = Math.cos(angle) * Math.sqrt(VlenSq - V1len * V1len) - V1len * Math.sin(angle);
  9203. var angleCull = distanceClosestPoint > sphereRadius;
  9204. var frontCull = V1len > sphereRadius + size;
  9205. var backCull = V1len < -sphereRadius;
  9206. return !(angleCull || frontCull || backCull);
  9207. }
  9208. _placePointLightToClusters(lightIndex, lightBound) {
  9209. var clusterDatas = this._clusterDatas;
  9210. var updateMark = this._updateMark;
  9211. for (var z = lightBound.zMin, zEnd = lightBound.zMax; z < zEnd; z++) {
  9212. for (var y = lightBound.yMin, yEnd = lightBound.yMax; y < yEnd; y++) {
  9213. for (var x = lightBound.xMin, xEnd = lightBound.xMax; x < xEnd; x++) {
  9214. var data = clusterDatas[z][y][x];
  9215. if (data.updateMark != updateMark) {
  9216. data.pointLightCount = 0;
  9217. data.spotLightCount = 0;
  9218. data.updateMark = updateMark;
  9219. }
  9220. var indices = data.indices;
  9221. var lightCount = data.pointLightCount++;
  9222. if (lightCount < indices.length)
  9223. indices[lightCount] = lightIndex;
  9224. else
  9225. indices.push(lightIndex);
  9226. }
  9227. }
  9228. }
  9229. }
  9230. _placeSpotLightToClusters(lightIndex, lightBound) {
  9231. var clusterDatas = this._clusterDatas;
  9232. var updateMark = this._updateMark;
  9233. for (var z = lightBound.zMin, zEnd = lightBound.zMax; z < zEnd; z++) {
  9234. for (var y = lightBound.yMin, yEnd = lightBound.yMax; y < yEnd; y++) {
  9235. for (var x = lightBound.xMin, xEnd = lightBound.xMax; x < xEnd; x++) {
  9236. var data = clusterDatas[z][y][x];
  9237. if (data.updateMark != updateMark) {
  9238. data.pointLightCount = 0;
  9239. data.spotLightCount = 0;
  9240. data.updateMark = updateMark;
  9241. }
  9242. var indices = data.indices;
  9243. var lightCount = data.pointLightCount + data.spotLightCount++;
  9244. if (lightCount < indices.length)
  9245. indices[lightCount] = lightIndex;
  9246. else
  9247. indices.push(lightIndex);
  9248. }
  9249. }
  9250. }
  9251. }
  9252. _insertConePlane(origin, forward, radius, halfAngle, pNor) {
  9253. var V1 = Cluster._tempVector36;
  9254. var V2 = Cluster._tempVector37;
  9255. Vector3.cross(pNor, forward, V1);
  9256. Vector3.cross(V1, forward, V2);
  9257. Vector3.normalize(V2, V2);
  9258. var tanR = radius * Math.tan(halfAngle);
  9259. var capRimX = origin.x + radius * forward.x + tanR * V2.x;
  9260. var capRimY = origin.y + radius * forward.y + tanR * V2.y;
  9261. var capRimZ = origin.z + radius * forward.z + tanR * V2.z;
  9262. return capRimX * pNor.x + capRimY * pNor.y + capRimZ * pNor.z <= 0 || origin.x * pNor.x + origin.y * pNor.y + origin.z * pNor.z <= 0;
  9263. }
  9264. _shrinkSphereLightZPerspective(near, far, lightviewPos, radius, lightBound) {
  9265. var lvZ = lightviewPos.z;
  9266. var minZ = lvZ - radius;
  9267. var maxZ = lvZ + radius;
  9268. if ((minZ > far) || (maxZ <= near))
  9269. return false;
  9270. var depthSliceParam = this._depthSliceParam;
  9271. lightBound.zMin = Math.floor(Math.log2(Math.max(minZ, near)) * depthSliceParam.x - depthSliceParam.y);
  9272. lightBound.zMax = Math.min(Math.ceil(Math.log2(maxZ) * depthSliceParam.x - depthSliceParam.y), this._zSlices);
  9273. return true;
  9274. }
  9275. _shrinkSpotLightZPerspective(near, far, viewLightPos, viewConeCap, radius, halfAngle, lightBound) {
  9276. var pbX = viewConeCap.x, pbY = viewConeCap.y, pbZ = viewConeCap.z;
  9277. var rb = Math.tan(halfAngle) * radius;
  9278. var paX = viewLightPos.x, paY = viewLightPos.y, paZ = viewLightPos.z;
  9279. var aX = pbX - paX, aY = pbY - paY, aZ = pbZ - paZ;
  9280. var dotA = aX * aX + aY * aY + aZ * aZ;
  9281. var eZ = Math.sqrt(1.0 - aZ * aZ / dotA);
  9282. var minZ = Math.max(Math.min(paZ, pbZ - eZ * rb), viewLightPos.z - radius);
  9283. var maxZ = Math.min(Math.max(paZ, pbZ + eZ * rb), viewLightPos.z + radius);
  9284. if ((minZ > far) || (maxZ <= near))
  9285. return false;
  9286. var depthSliceParam = this._depthSliceParam;
  9287. lightBound.zMin = Math.floor(Math.log2(Math.max(minZ, near)) * depthSliceParam.x - depthSliceParam.y);
  9288. lightBound.zMax = Math.min(Math.ceil(Math.log2(maxZ) * depthSliceParam.x - depthSliceParam.y), this._zSlices);
  9289. return true;
  9290. }
  9291. _shrinkSphereLightByBoundOrth(halfX, halfY, near, far, lightviewPos, radius, lightBound) {
  9292. var lvZ = lightviewPos.z;
  9293. var minZ = lvZ - radius, maxZ = lvZ + radius;
  9294. if ((minZ > far) || (maxZ <= near))
  9295. return false;
  9296. var lvX = lightviewPos.x;
  9297. var minX = lvX - radius, maxX = lvX + radius;
  9298. if ((minX > halfX) || (maxX <= -halfX))
  9299. return false;
  9300. var lvY = lightviewPos.y;
  9301. var minY = lvY - radius, maxY = lvY + radius;
  9302. if ((minY > halfY) || (maxY <= -halfY))
  9303. return false;
  9304. var xSlices = this._xSlices, ySlices = this._ySlices;
  9305. var depthSliceParam = this._depthSliceParam;
  9306. var xStride = halfX * 2 / xSlices, yStride = halfY * 2 / ySlices;
  9307. lightBound.xMin = Math.max(Math.floor((minX + halfX) / xStride), 0);
  9308. lightBound.xMax = Math.min(Math.ceil((maxX + halfX) / xStride), xSlices);
  9309. lightBound.yMin = Math.max(Math.floor((halfY - maxY) / yStride), 0);
  9310. lightBound.yMax = Math.min(Math.ceil((halfY - minY) / yStride), ySlices);
  9311. lightBound.zMin = Math.floor(Math.log2(Math.max(minZ, near)) * depthSliceParam.x - depthSliceParam.y);
  9312. lightBound.zMax = Math.min(Math.ceil(Math.log2(maxZ) * depthSliceParam.x - depthSliceParam.y), this._zSlices);
  9313. return true;
  9314. }
  9315. _shrinkSpotLightByBoundOrth(halfX, halfY, near, far, viewLightPos, viewConeCap, radius, halfAngle, lightBound) {
  9316. var pbX = viewConeCap.x, pbY = viewConeCap.y, pbZ = viewConeCap.z;
  9317. var rb = Math.tan(halfAngle) * radius;
  9318. var paX = viewLightPos.x, paY = viewLightPos.y, paZ = viewLightPos.z;
  9319. var aX = pbX - paX, aY = pbY - paY, aZ = pbZ - paZ;
  9320. var dotA = aX * aX + aY * aY + aZ * aZ;
  9321. var eZ = Math.sqrt(1.0 - aZ * aZ / dotA);
  9322. var minZ = Math.max(Math.min(paZ, pbZ - eZ * rb), viewLightPos.z - radius);
  9323. var maxZ = Math.min(Math.max(paZ, pbZ + eZ * rb), viewLightPos.z + radius);
  9324. if ((minZ > far) || (maxZ <= near))
  9325. return false;
  9326. var eX = Math.sqrt(1.0 - aX * aX / dotA);
  9327. var minX = Math.max(Math.min(paX, pbX - eX * rb), viewLightPos.x - radius);
  9328. var maxX = Math.min(Math.max(paX, pbX + eX * rb), viewLightPos.x + radius);
  9329. if ((minX > halfX) || (maxX <= -halfX))
  9330. return false;
  9331. var eY = Math.sqrt(1.0 - aY * aY / dotA);
  9332. var minY = Math.max(Math.min(paY, pbY - eY * rb), viewLightPos.y - radius);
  9333. var maxY = Math.min(Math.max(paY, pbY + eY * rb), viewLightPos.y + radius);
  9334. if ((minY > halfY) || (maxY <= -halfY))
  9335. return false;
  9336. var xSlices = this._xSlices, ySlices = this._ySlices;
  9337. var depthSliceParam = this._depthSliceParam;
  9338. var xStride = halfX * 2 / xSlices, yStride = halfY * 2 / ySlices;
  9339. lightBound.xMin = Math.max(Math.floor((minX + halfX) / xStride), 0);
  9340. lightBound.xMax = Math.min(Math.ceil((maxX + halfX) / xStride), xSlices);
  9341. lightBound.yMin = Math.max(Math.floor((halfY - maxY) / yStride), 0);
  9342. lightBound.yMax = Math.min(Math.ceil((halfY - minY) / yStride), ySlices);
  9343. lightBound.zMin = Math.floor(Math.log2(Math.max(minZ, near)) * depthSliceParam.x - depthSliceParam.y);
  9344. lightBound.zMax = Math.min(Math.ceil(Math.log2(maxZ) * depthSliceParam.x - depthSliceParam.y), this._zSlices);
  9345. return true;
  9346. }
  9347. _shrinkXYByRadiusPerspective(lightviewPos, radius, lightBound, xPlanes, yPlanes) {
  9348. var xMin, yMin;
  9349. var xMax, yMax;
  9350. var lvX = lightviewPos.x, lvY = lightviewPos.y, lvZ = lightviewPos.z;
  9351. var i;
  9352. var n = this._ySlices + 1;
  9353. for (i = 0; i < n; i++) {
  9354. var plane = yPlanes[i];
  9355. if (lvY * plane.y + lvZ * plane.z < radius) {
  9356. yMin = Math.max(0, i - 1);
  9357. break;
  9358. }
  9359. }
  9360. if (i == n)
  9361. return false;
  9362. yMax = this._ySlices;
  9363. for (i = yMin + 1; i < n; i++) {
  9364. var plane = yPlanes[i];
  9365. if (lvY * plane.y + lvZ * plane.z <= -radius) {
  9366. yMax = Math.max(0, i);
  9367. break;
  9368. }
  9369. }
  9370. n = this._xSlices + 1;
  9371. for (i = 0; i < n; i++) {
  9372. var plane = xPlanes[i];
  9373. if (lvX * plane.x + lvZ * plane.z < radius) {
  9374. xMin = Math.max(0, i - 1);
  9375. break;
  9376. }
  9377. }
  9378. xMax = this._xSlices;
  9379. for (i = xMin + 1; i < n; i++) {
  9380. var plane = xPlanes[i];
  9381. if (lvX * plane.x + lvZ * plane.z <= -radius) {
  9382. xMax = Math.max(0, i);
  9383. break;
  9384. }
  9385. }
  9386. lightBound.xMin = xMin;
  9387. lightBound.xMax = xMax;
  9388. lightBound.yMin = yMin;
  9389. lightBound.yMax = yMax;
  9390. return true;
  9391. }
  9392. _shrinkSpotXYByConePerspective(lightviewPos, viewForward, radius, halfAngle, lightBound, xPlanes, yPlanes) {
  9393. var xMin, yMin;
  9394. var xMax, yMax;
  9395. var normal = Cluster._tempVector32;
  9396. var n = lightBound.yMax + 1;
  9397. for (var i = lightBound.yMin + 1; i < n; i++) {
  9398. if (this._insertConePlane(lightviewPos, viewForward, radius, halfAngle, yPlanes[i])) {
  9399. yMin = Math.max(0, i - 1);
  9400. break;
  9401. }
  9402. }
  9403. yMax = lightBound.yMax;
  9404. for (var i = yMin + 1; i < n; i++) {
  9405. var plane = yPlanes[i];
  9406. normal.setValue(0, -plane.y, -plane.z);
  9407. if (!this._insertConePlane(lightviewPos, viewForward, radius, halfAngle, normal)) {
  9408. yMax = Math.max(0, i);
  9409. break;
  9410. }
  9411. }
  9412. n = lightBound.xMax + 1;
  9413. for (var i = lightBound.xMin + 1; i < n; i++) {
  9414. if (this._insertConePlane(lightviewPos, viewForward, radius, halfAngle, xPlanes[i])) {
  9415. xMin = Math.max(0, i - 1);
  9416. break;
  9417. }
  9418. }
  9419. xMax = lightBound.xMax;
  9420. for (var i = xMin + 1; i < n; i++) {
  9421. var plane = xPlanes[i];
  9422. normal.setValue(-plane.x, 0, -plane.z);
  9423. if (!this._insertConePlane(lightviewPos, viewForward, radius, halfAngle, normal)) {
  9424. xMax = Math.max(0, i);
  9425. break;
  9426. }
  9427. }
  9428. lightBound.xMin = xMin;
  9429. lightBound.xMax = xMax;
  9430. lightBound.yMin = yMin;
  9431. lightBound.yMax = yMax;
  9432. }
  9433. _updatePointLightPerspective(near, far, viewMat, pointLight, lightIndex, xPlanes, yPlanes) {
  9434. var lightBound = Cluster._tempLightBound;
  9435. var lightviewPos = Cluster._tempVector30;
  9436. Vector3.transformV3ToV3(pointLight._transform.position, viewMat, lightviewPos);
  9437. lightviewPos.z *= -1;
  9438. if (!this._shrinkSphereLightZPerspective(near, far, lightviewPos, pointLight.range, lightBound))
  9439. return;
  9440. if (!this._shrinkXYByRadiusPerspective(lightviewPos, pointLight.range, lightBound, xPlanes, yPlanes))
  9441. return;
  9442. this._placePointLightToClusters(lightIndex, lightBound);
  9443. }
  9444. _updateSpotLightPerspective(near, far, viewMat, spotLight, lightIndex, xPlanes, yPlanes) {
  9445. var lightBound = Cluster._tempLightBound;
  9446. var viewPos = Cluster._tempVector30;
  9447. var forward = Cluster._tempVector31;
  9448. var viewConeCap = Cluster._tempVector34;
  9449. var position = spotLight._transform.position;
  9450. var range = spotLight.range;
  9451. spotLight._transform.worldMatrix.getForward(forward);
  9452. Vector3.normalize(forward, forward);
  9453. Vector3.scale(forward, range, viewConeCap);
  9454. Vector3.add(position, viewConeCap, viewConeCap);
  9455. Vector3.transformV3ToV3(position, viewMat, viewPos);
  9456. Vector3.transformV3ToV3(viewConeCap, viewMat, viewConeCap);
  9457. viewPos.z *= -1;
  9458. viewConeCap.z *= -1;
  9459. var halfAngle = (spotLight.spotAngle / 2) * Math.PI / 180;
  9460. if (!this._shrinkSpotLightZPerspective(near, far, viewPos, viewConeCap, range, halfAngle, lightBound))
  9461. return;
  9462. if (!this._shrinkXYByRadiusPerspective(viewPos, range, lightBound, xPlanes, yPlanes))
  9463. return;
  9464. var viewFor = Cluster._tempVector33;
  9465. viewFor.x = viewConeCap.x - viewPos.x, viewFor.y = viewConeCap.y - viewPos.y, viewFor.z = viewConeCap.z - viewPos.z;
  9466. Vector3.normalize(viewFor, viewFor);
  9467. this._shrinkSpotXYByConePerspective(viewPos, viewFor, range, halfAngle, lightBound, xPlanes, yPlanes);
  9468. this._placeSpotLightToClusters(lightIndex, lightBound);
  9469. }
  9470. _updatePointLightOrth(halfX, halfY, near, far, viewMat, pointLight, lightIndex) {
  9471. var lightBound = Cluster._tempLightBound;
  9472. var lightviewPos = Cluster._tempVector30;
  9473. Vector3.transformV3ToV3(pointLight._transform.position, viewMat, lightviewPos);
  9474. lightviewPos.z *= -1;
  9475. if (!this._shrinkSphereLightByBoundOrth(halfX, halfY, near, far, lightviewPos, pointLight.range, lightBound))
  9476. return;
  9477. this._placePointLightToClusters(lightIndex, lightBound);
  9478. }
  9479. _updateSpotLightOrth(halfX, halfY, near, far, viewMat, spotLight, lightIndex) {
  9480. var lightBound = Cluster._tempLightBound;
  9481. var viewPos = Cluster._tempVector30;
  9482. var forward = Cluster._tempVector31;
  9483. var viewConeCap = Cluster._tempVector34;
  9484. var position = spotLight._transform.position;
  9485. var range = spotLight.range;
  9486. spotLight._transform.worldMatrix.getForward(forward);
  9487. Vector3.normalize(forward, forward);
  9488. Vector3.scale(forward, range, viewConeCap);
  9489. Vector3.add(position, viewConeCap, viewConeCap);
  9490. Vector3.transformV3ToV3(position, viewMat, viewPos);
  9491. Vector3.transformV3ToV3(viewConeCap, viewMat, viewConeCap);
  9492. viewPos.z *= -1;
  9493. viewConeCap.z *= -1;
  9494. var halfAngle = (spotLight.spotAngle / 2) * Math.PI / 180;
  9495. if (!this._shrinkSpotLightByBoundOrth(halfX, halfY, near, far, viewPos, viewConeCap, range, halfAngle, lightBound))
  9496. return;
  9497. this._placeSpotLightToClusters(lightIndex, lightBound);
  9498. }
  9499. update(camera, scene) {
  9500. this._updateMark++;
  9501. var camNear = camera.nearPlane;
  9502. this._depthSliceParam.x = Config3D._config.lightClusterCount.z / Math.log2(camera.farPlane / camNear);
  9503. this._depthSliceParam.y = Math.log2(camNear) * this._depthSliceParam.x;
  9504. var near = camera.nearPlane;
  9505. var far = camera.farPlane;
  9506. var viewMat = camera.viewMatrix;
  9507. var curCount = scene._directionLights._length;
  9508. var pointLights = scene._pointLights;
  9509. var poiCount = pointLights._length;
  9510. var poiElements = pointLights._elements;
  9511. var spotLights = scene._spotLights;
  9512. var spoCount = spotLights._length;
  9513. var spoElements = spotLights._elements;
  9514. if (camera.orthographic) {
  9515. var halfY = camera.orthographicVerticalSize / 2.0;
  9516. var halfX = halfY * camera.aspectRatio;
  9517. for (var i = 0; i < poiCount; i++, curCount++)
  9518. this._updatePointLightOrth(halfX, halfY, near, far, viewMat, poiElements[i], curCount);
  9519. for (var i = 0; i < spoCount; i++, curCount++)
  9520. this._updateSpotLightOrth(halfX, halfY, near, far, viewMat, spoElements[i], curCount);
  9521. }
  9522. else {
  9523. camera._updateClusterPlaneXY();
  9524. var xPlanes = camera._clusterXPlanes;
  9525. var yPlanes = camera._clusterYPlanes;
  9526. for (var i = 0; i < poiCount; i++, curCount++)
  9527. this._updatePointLightPerspective(near, far, viewMat, poiElements[i], curCount, xPlanes, yPlanes);
  9528. for (var i = 0; i < spoCount; i++, curCount++)
  9529. this._updateSpotLightPerspective(near, far, viewMat, spoElements[i], curCount, xPlanes, yPlanes);
  9530. }
  9531. if (poiCount + spoCount > 0) {
  9532. var xSlices = this._xSlices, ySlices = this._ySlices, zSlices = this._zSlices;
  9533. var widthFloat = xSlices * ySlices * 4;
  9534. var lightOff = widthFloat * zSlices;
  9535. var clusterPixels = this._clusterPixels;
  9536. var clusterPixelsCount = clusterPixels.length;
  9537. var clusterDatas = this._clusterDatas;
  9538. var updateMark = this._updateMark;
  9539. var freeSpace = true;
  9540. for (var z = 0; z < zSlices; z++) {
  9541. for (var y = 0; y < ySlices; y++) {
  9542. for (var x = 0; x < xSlices; x++) {
  9543. var data = clusterDatas[z][y][x];
  9544. var clusterOff = (x + y * xSlices + z * xSlices * ySlices) * 4;
  9545. if (data.updateMark !== updateMark) {
  9546. clusterPixels[clusterOff] = 0;
  9547. clusterPixels[clusterOff + 1] = 0;
  9548. }
  9549. else {
  9550. if (freeSpace) {
  9551. var indices = data.indices;
  9552. var pCount = data.pointLightCount;
  9553. var sCount = data.spotLightCount;
  9554. var count = pCount + sCount;
  9555. if (lightOff + count < clusterPixelsCount) {
  9556. clusterPixels[clusterOff] = pCount;
  9557. clusterPixels[clusterOff + 1] = sCount;
  9558. clusterPixels[clusterOff + 2] = Math.floor(lightOff / widthFloat);
  9559. clusterPixels[clusterOff + 3] = lightOff % widthFloat;
  9560. for (var i = 0; i < count; i++)
  9561. clusterPixels[lightOff++] = indices[i];
  9562. }
  9563. else {
  9564. count = clusterPixelsCount - (lightOff + count);
  9565. pCount = Math.min(pCount, count);
  9566. clusterPixels[clusterOff] = pCount;
  9567. clusterPixels[clusterOff + 1] = Math.min(sCount, count - pCount);
  9568. clusterPixels[clusterOff + 2] = Math.floor(lightOff / widthFloat);
  9569. clusterPixels[clusterOff + 3] = lightOff % widthFloat;
  9570. for (var i = 0; i < count; i++)
  9571. clusterPixels[lightOff++] = indices[i];
  9572. freeSpace = false;
  9573. }
  9574. }
  9575. }
  9576. }
  9577. }
  9578. }
  9579. var width = this._clusterTexture.width;
  9580. this._clusterTexture.setSubPixels(0, 0, width, Math.ceil(lightOff / (4 * width)), clusterPixels);
  9581. }
  9582. }
  9583. }
  9584. Cluster._tempVector30 = new Vector3();
  9585. Cluster._tempVector31 = new Vector3();
  9586. Cluster._tempVector32 = new Vector3();
  9587. Cluster._tempVector33 = new Vector3();
  9588. Cluster._tempVector34 = new Vector3();
  9589. Cluster._tempVector35 = new Vector3();
  9590. Cluster._tempVector36 = new Vector3();
  9591. Cluster._tempVector37 = new Vector3();
  9592. Cluster._tempLightBound = new LightBound();
  9593. class Plane {
  9594. constructor(normal, d = 0) {
  9595. this.normal = normal;
  9596. this.distance = d;
  9597. }
  9598. static createPlaneBy3P(point0, point1, point2, out) {
  9599. var x1 = point1.x - point0.x;
  9600. var y1 = point1.y - point0.y;
  9601. var z1 = point1.z - point0.z;
  9602. var x2 = point2.x - point0.x;
  9603. var y2 = point2.y - point0.y;
  9604. var z2 = point2.z - point0.z;
  9605. var yz = (y1 * z2) - (z1 * y2);
  9606. var xz = (z1 * x2) - (x1 * z2);
  9607. var xy = (x1 * y2) - (y1 * x2);
  9608. var invPyth = 1.0 / (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  9609. var x = yz * invPyth;
  9610. var y = xz * invPyth;
  9611. var z = xy * invPyth;
  9612. var normal = out.normal;
  9613. normal.x = x;
  9614. normal.y = y;
  9615. normal.z = z;
  9616. out.distance = -((x * point0.x) + (y * point0.y) + (z * point0.z));
  9617. }
  9618. normalize() {
  9619. var normalEX = this.normal.x;
  9620. var normalEY = this.normal.y;
  9621. var normalEZ = this.normal.z;
  9622. var magnitude = 1.0 / Math.sqrt(normalEX * normalEX + normalEY * normalEY + normalEZ * normalEZ);
  9623. this.normal.x = normalEX * magnitude;
  9624. this.normal.y = normalEY * magnitude;
  9625. this.normal.z = normalEZ * magnitude;
  9626. this.distance *= magnitude;
  9627. }
  9628. cloneTo(destObject) {
  9629. var dest = destObject;
  9630. this.normal.cloneTo(dest.normal);
  9631. dest.distance = this.distance;
  9632. }
  9633. clone() {
  9634. var dest = new Plane(new Vector3());
  9635. this.cloneTo(dest);
  9636. return dest;
  9637. }
  9638. }
  9639. Plane.PlaneIntersectionType_Back = 0;
  9640. Plane.PlaneIntersectionType_Front = 1;
  9641. Plane.PlaneIntersectionType_Intersecting = 2;
  9642. class Ray {
  9643. constructor(origin, direction) {
  9644. this.origin = origin;
  9645. this.direction = direction;
  9646. }
  9647. }
  9648. class ContainmentType {
  9649. }
  9650. ContainmentType.Disjoint = 0;
  9651. ContainmentType.Contains = 1;
  9652. ContainmentType.Intersects = 2;
  9653. class CollisionUtils {
  9654. constructor() {
  9655. }
  9656. static distancePlaneToPoint(plane, point) {
  9657. var dot = Vector3.dot(plane.normal, point);
  9658. return dot - plane.distance;
  9659. }
  9660. static distanceBoxToPoint(box, point) {
  9661. var boxMin = box.min;
  9662. var boxMineX = boxMin.x;
  9663. var boxMineY = boxMin.y;
  9664. var boxMineZ = boxMin.z;
  9665. var boxMax = box.max;
  9666. var boxMaxeX = boxMax.x;
  9667. var boxMaxeY = boxMax.y;
  9668. var boxMaxeZ = boxMax.z;
  9669. var pointeX = point.x;
  9670. var pointeY = point.y;
  9671. var pointeZ = point.z;
  9672. var distance = 0;
  9673. if (pointeX < boxMineX)
  9674. distance += (boxMineX - pointeX) * (boxMineX - pointeX);
  9675. if (pointeX > boxMaxeX)
  9676. distance += (boxMaxeX - pointeX) * (boxMaxeX - pointeX);
  9677. if (pointeY < boxMineY)
  9678. distance += (boxMineY - pointeY) * (boxMineY - pointeY);
  9679. if (pointeY > boxMaxeY)
  9680. distance += (boxMaxeY - pointeY) * (boxMaxeY - pointeY);
  9681. if (pointeZ < boxMineZ)
  9682. distance += (boxMineZ - pointeZ) * (boxMineZ - pointeZ);
  9683. if (pointeZ > boxMaxeZ)
  9684. distance += (boxMaxeZ - pointeZ) * (boxMaxeZ - pointeZ);
  9685. return Math.sqrt(distance);
  9686. }
  9687. static distanceBoxToBox(box1, box2) {
  9688. var box1Mine = box1.min;
  9689. var box1MineX = box1Mine.x;
  9690. var box1MineY = box1Mine.y;
  9691. var box1MineZ = box1Mine.z;
  9692. var box1Maxe = box1.max;
  9693. var box1MaxeX = box1Maxe.x;
  9694. var box1MaxeY = box1Maxe.y;
  9695. var box1MaxeZ = box1Maxe.z;
  9696. var box2Mine = box2.min;
  9697. var box2MineX = box2Mine.x;
  9698. var box2MineY = box2Mine.y;
  9699. var box2MineZ = box2Mine.z;
  9700. var box2Maxe = box2.max;
  9701. var box2MaxeX = box2Maxe.x;
  9702. var box2MaxeY = box2Maxe.y;
  9703. var box2MaxeZ = box2Maxe.z;
  9704. var distance = 0;
  9705. var delta;
  9706. if (box1MineX > box2MaxeX) {
  9707. delta = box1MineX - box2MaxeX;
  9708. distance += delta * delta;
  9709. }
  9710. else if (box2MineX > box1MaxeX) {
  9711. delta = box2MineX - box1MaxeX;
  9712. distance += delta * delta;
  9713. }
  9714. if (box1MineY > box2MaxeY) {
  9715. delta = box1MineY - box2MaxeY;
  9716. distance += delta * delta;
  9717. }
  9718. else if (box2MineY > box1MaxeY) {
  9719. delta = box2MineY - box1MaxeY;
  9720. distance += delta * delta;
  9721. }
  9722. if (box1MineZ > box2MaxeZ) {
  9723. delta = box1MineZ - box2MaxeZ;
  9724. distance += delta * delta;
  9725. }
  9726. else if (box2MineZ > box1MaxeZ) {
  9727. delta = box2MineZ - box1MaxeZ;
  9728. distance += delta * delta;
  9729. }
  9730. return Math.sqrt(distance);
  9731. }
  9732. static distanceSphereToPoint(sphere, point) {
  9733. var distance = Math.sqrt(Vector3.distanceSquared(sphere.center, point));
  9734. distance -= sphere.radius;
  9735. return Math.max(distance, 0);
  9736. }
  9737. static distanceSphereToSphere(sphere1, sphere2) {
  9738. var distance = Math.sqrt(Vector3.distanceSquared(sphere1.center, sphere2.center));
  9739. distance -= sphere1.radius + sphere2.radius;
  9740. return Math.max(distance, 0);
  9741. }
  9742. static intersectsRayAndTriangleRD(ray, vertex1, vertex2, vertex3, out) {
  9743. var rayO = ray.origin;
  9744. var rayOeX = rayO.x;
  9745. var rayOeY = rayO.y;
  9746. var rayOeZ = rayO.z;
  9747. var rayD = ray.direction;
  9748. var rayDeX = rayD.x;
  9749. var rayDeY = rayD.y;
  9750. var rayDeZ = rayD.z;
  9751. var v1eX = vertex1.x;
  9752. var v1eY = vertex1.y;
  9753. var v1eZ = vertex1.z;
  9754. var v2eX = vertex2.x;
  9755. var v2eY = vertex2.y;
  9756. var v2eZ = vertex2.z;
  9757. var v3eX = vertex3.x;
  9758. var v3eY = vertex3.y;
  9759. var v3eZ = vertex3.z;
  9760. var _tempV30eX = CollisionUtils._tempV30.x;
  9761. var _tempV30eY = CollisionUtils._tempV30.y;
  9762. var _tempV30eZ = CollisionUtils._tempV30.z;
  9763. _tempV30eX = v2eX - v1eX;
  9764. _tempV30eY = v2eY - v1eY;
  9765. _tempV30eZ = v2eZ - v1eZ;
  9766. var _tempV31eX = CollisionUtils._tempV31.x;
  9767. var _tempV31eY = CollisionUtils._tempV31.y;
  9768. var _tempV31eZ = CollisionUtils._tempV31.z;
  9769. _tempV31eX = v3eX - v1eX;
  9770. _tempV31eY = v3eY - v1eY;
  9771. _tempV31eZ = v3eZ - v1eZ;
  9772. var _tempV32eX = CollisionUtils._tempV32.x;
  9773. var _tempV32eY = CollisionUtils._tempV32.y;
  9774. var _tempV32eZ = CollisionUtils._tempV32.z;
  9775. _tempV32eX = (rayDeY * _tempV31eZ) - (rayDeZ * _tempV31eY);
  9776. _tempV32eY = (rayDeZ * _tempV31eX) - (rayDeX * _tempV31eZ);
  9777. _tempV32eZ = (rayDeX * _tempV31eY) - (rayDeY * _tempV31eX);
  9778. var determinant = (_tempV30eX * _tempV32eX) + (_tempV30eY * _tempV32eY) + (_tempV30eZ * _tempV32eZ);
  9779. if (MathUtils3D.isZero(determinant)) {
  9780. return false;
  9781. }
  9782. var inversedeterminant = 1 / determinant;
  9783. var _tempV33eX = CollisionUtils._tempV33.x;
  9784. var _tempV33eY = CollisionUtils._tempV33.y;
  9785. var _tempV33eZ = CollisionUtils._tempV33.z;
  9786. _tempV33eX = rayOeX - v1eX;
  9787. _tempV33eY = rayOeY - v1eY;
  9788. _tempV33eZ = rayOeZ - v1eZ;
  9789. var triangleU = (_tempV33eX * _tempV32eX) + (_tempV33eY * _tempV32eY) + (_tempV33eZ * _tempV32eZ);
  9790. triangleU *= inversedeterminant;
  9791. if (triangleU < 0 || triangleU > 1) {
  9792. return false;
  9793. }
  9794. var _tempV34eX = CollisionUtils._tempV34.x;
  9795. var _tempV34eY = CollisionUtils._tempV34.y;
  9796. var _tempV34eZ = CollisionUtils._tempV34.z;
  9797. _tempV34eX = (_tempV33eY * _tempV30eZ) - (_tempV33eZ * _tempV30eY);
  9798. _tempV34eY = (_tempV33eZ * _tempV30eX) - (_tempV33eX * _tempV30eZ);
  9799. _tempV34eZ = (_tempV33eX * _tempV30eY) - (_tempV33eY * _tempV30eX);
  9800. var triangleV = ((rayDeX * _tempV34eX) + (rayDeY * _tempV34eY)) + (rayDeZ * _tempV34eZ);
  9801. triangleV *= inversedeterminant;
  9802. if (triangleV < 0 || triangleU + triangleV > 1) {
  9803. return false;
  9804. }
  9805. var raydistance = (_tempV31eX * _tempV34eX) + (_tempV31eY * _tempV34eY) + (_tempV31eZ * _tempV34eZ);
  9806. raydistance *= inversedeterminant;
  9807. if (raydistance < 0) {
  9808. return false;
  9809. }
  9810. return true;
  9811. }
  9812. static intersectsRayAndTriangleRP(ray, vertex1, vertex2, vertex3, out) {
  9813. var distance;
  9814. if (!CollisionUtils.intersectsRayAndTriangleRD(ray, vertex1, vertex2, vertex3, distance)) {
  9815. out = Vector3._ZERO;
  9816. return false;
  9817. }
  9818. Vector3.scale(ray.direction, distance, CollisionUtils._tempV30);
  9819. Vector3.add(ray.origin, CollisionUtils._tempV30, out);
  9820. return true;
  9821. }
  9822. static intersectsRayAndPoint(ray, point) {
  9823. Vector3.subtract(ray.origin, point, CollisionUtils._tempV30);
  9824. var b = Vector3.dot(CollisionUtils._tempV30, ray.direction);
  9825. var c = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV30) - MathUtils3D.zeroTolerance;
  9826. if (c > 0 && b > 0)
  9827. return false;
  9828. var discriminant = b * b - c;
  9829. if (discriminant < 0)
  9830. return false;
  9831. return true;
  9832. }
  9833. static intersectsRayAndRay(ray1, ray2, out) {
  9834. var ray1o = ray1.origin;
  9835. var ray1oeX = ray1o.x;
  9836. var ray1oeY = ray1o.y;
  9837. var ray1oeZ = ray1o.z;
  9838. var ray1d = ray1.direction;
  9839. var ray1deX = ray1d.x;
  9840. var ray1deY = ray1d.y;
  9841. var ray1deZ = ray1d.z;
  9842. var ray2o = ray2.origin;
  9843. var ray2oeX = ray2o.x;
  9844. var ray2oeY = ray2o.y;
  9845. var ray2oeZ = ray2o.z;
  9846. var ray2d = ray2.direction;
  9847. var ray2deX = ray2d.x;
  9848. var ray2deY = ray2d.y;
  9849. var ray2deZ = ray2d.z;
  9850. Vector3.cross(ray1d, ray2d, CollisionUtils._tempV30);
  9851. var tempV3 = CollisionUtils._tempV30;
  9852. var denominator = Vector3.scalarLength(CollisionUtils._tempV30);
  9853. if (MathUtils3D.isZero(denominator)) {
  9854. if (MathUtils3D.nearEqual(ray2oeX, ray1oeX) && MathUtils3D.nearEqual(ray2oeY, ray1oeY) && MathUtils3D.nearEqual(ray2oeZ, ray1oeZ)) {
  9855. return true;
  9856. }
  9857. }
  9858. denominator = denominator * denominator;
  9859. var m11 = ray2oeX - ray1oeX;
  9860. var m12 = ray2oeY - ray1oeY;
  9861. var m13 = ray2oeZ - ray1oeZ;
  9862. var m21 = ray2deX;
  9863. var m22 = ray2deY;
  9864. var m23 = ray2deZ;
  9865. var m31 = tempV3.x;
  9866. var m32 = tempV3.y;
  9867. var m33 = tempV3.z;
  9868. var dets = m11 * m22 * m33 + m12 * m23 * m31 + m13 * m21 * m32 - m11 * m23 * m32 - m12 * m21 * m33 - m13 * m22 * m31;
  9869. m21 = ray1deX;
  9870. m22 = ray1deY;
  9871. m23 = ray1deZ;
  9872. var s = dets / denominator;
  9873. Vector3.scale(ray1d, s, CollisionUtils._tempV30);
  9874. Vector3.scale(ray2d, s, CollisionUtils._tempV31);
  9875. Vector3.add(ray1o, CollisionUtils._tempV30, CollisionUtils._tempV32);
  9876. Vector3.add(ray2o, CollisionUtils._tempV31, CollisionUtils._tempV33);
  9877. var point1e = CollisionUtils._tempV32;
  9878. var point2e = CollisionUtils._tempV33;
  9879. if (!MathUtils3D.nearEqual(point2e.x, point1e.x) || !MathUtils3D.nearEqual(point2e.y, point1e.y) || !MathUtils3D.nearEqual(point2e.z, point1e.z)) {
  9880. return false;
  9881. }
  9882. return true;
  9883. }
  9884. static intersectsPlaneAndTriangle(plane, vertex1, vertex2, vertex3) {
  9885. var test1 = CollisionUtils.intersectsPlaneAndPoint(plane, vertex1);
  9886. var test2 = CollisionUtils.intersectsPlaneAndPoint(plane, vertex2);
  9887. var test3 = CollisionUtils.intersectsPlaneAndPoint(plane, vertex3);
  9888. if (test1 == Plane.PlaneIntersectionType_Front && test2 == Plane.PlaneIntersectionType_Front && test3 == Plane.PlaneIntersectionType_Front)
  9889. return Plane.PlaneIntersectionType_Front;
  9890. if (test1 == Plane.PlaneIntersectionType_Back && test2 == Plane.PlaneIntersectionType_Back && test3 == Plane.PlaneIntersectionType_Back)
  9891. return Plane.PlaneIntersectionType_Back;
  9892. return Plane.PlaneIntersectionType_Intersecting;
  9893. }
  9894. static intersectsRayAndPlaneRD(ray, plane) {
  9895. var planeNor = plane.normal;
  9896. var direction = Vector3.dot(planeNor, ray.direction);
  9897. if (Math.abs(direction) < MathUtils3D.zeroTolerance)
  9898. return -1;
  9899. var position = Vector3.dot(planeNor, ray.origin);
  9900. var distance = (-plane.distance - position) / direction;
  9901. if (distance < 0) {
  9902. if (distance < -MathUtils3D.zeroTolerance)
  9903. return -1;
  9904. distance = 0;
  9905. }
  9906. return distance;
  9907. }
  9908. static intersectsRayAndPlaneRP(ray, plane, out) {
  9909. var distance = CollisionUtils.intersectsRayAndPlaneRD(ray, plane);
  9910. if (distance == -1) {
  9911. out.setValue(0, 0, 0);
  9912. return false;
  9913. }
  9914. var scaDis = CollisionUtils._tempV30;
  9915. Vector3.scale(ray.direction, distance, scaDis);
  9916. Vector3.add(ray.origin, scaDis, out);
  9917. return true;
  9918. }
  9919. static intersectsRayAndBoxRD(ray, box) {
  9920. var rayoe = ray.origin;
  9921. var rayoeX = rayoe.x;
  9922. var rayoeY = rayoe.y;
  9923. var rayoeZ = rayoe.z;
  9924. var rayde = ray.direction;
  9925. var raydeX = rayde.x;
  9926. var raydeY = rayde.y;
  9927. var raydeZ = rayde.z;
  9928. var boxMine = box.min;
  9929. var boxMineX = boxMine.x;
  9930. var boxMineY = boxMine.y;
  9931. var boxMineZ = boxMine.z;
  9932. var boxMaxe = box.max;
  9933. var boxMaxeX = boxMaxe.x;
  9934. var boxMaxeY = boxMaxe.y;
  9935. var boxMaxeZ = boxMaxe.z;
  9936. var out = 0;
  9937. var tmax = MathUtils3D.MaxValue;
  9938. if (MathUtils3D.isZero(raydeX)) {
  9939. if (rayoeX < boxMineX || rayoeX > boxMaxeX) {
  9940. return -1;
  9941. }
  9942. }
  9943. else {
  9944. var inverse = 1 / raydeX;
  9945. var t1 = (boxMineX - rayoeX) * inverse;
  9946. var t2 = (boxMaxeX - rayoeX) * inverse;
  9947. if (t1 > t2) {
  9948. var temp = t1;
  9949. t1 = t2;
  9950. t2 = temp;
  9951. }
  9952. out = Math.max(t1, out);
  9953. tmax = Math.min(t2, tmax);
  9954. if (out > tmax) {
  9955. return -1;
  9956. }
  9957. }
  9958. if (MathUtils3D.isZero(raydeY)) {
  9959. if (rayoeY < boxMineY || rayoeY > boxMaxeY) {
  9960. return -1;
  9961. }
  9962. }
  9963. else {
  9964. var inverse1 = 1 / raydeY;
  9965. var t3 = (boxMineY - rayoeY) * inverse1;
  9966. var t4 = (boxMaxeY - rayoeY) * inverse1;
  9967. if (t3 > t4) {
  9968. var temp1 = t3;
  9969. t3 = t4;
  9970. t4 = temp1;
  9971. }
  9972. out = Math.max(t3, out);
  9973. tmax = Math.min(t4, tmax);
  9974. if (out > tmax) {
  9975. return -1;
  9976. }
  9977. }
  9978. if (MathUtils3D.isZero(raydeZ)) {
  9979. if (rayoeZ < boxMineZ || rayoeZ > boxMaxeZ) {
  9980. return -1;
  9981. }
  9982. }
  9983. else {
  9984. var inverse2 = 1 / raydeZ;
  9985. var t5 = (boxMineZ - rayoeZ) * inverse2;
  9986. var t6 = (boxMaxeZ - rayoeZ) * inverse2;
  9987. if (t5 > t6) {
  9988. var temp2 = t5;
  9989. t5 = t6;
  9990. t6 = temp2;
  9991. }
  9992. out = Math.max(t5, out);
  9993. tmax = Math.min(t6, tmax);
  9994. if (out > tmax) {
  9995. return -1;
  9996. }
  9997. }
  9998. return out;
  9999. }
  10000. static intersectsRayAndBoxRP(ray, box, out) {
  10001. var distance = CollisionUtils.intersectsRayAndBoxRD(ray, box);
  10002. if (distance === -1) {
  10003. Vector3._ZERO.cloneTo(out);
  10004. return distance;
  10005. }
  10006. Vector3.scale(ray.direction, distance, CollisionUtils._tempV30);
  10007. Vector3.add(ray.origin, CollisionUtils._tempV30, CollisionUtils._tempV31);
  10008. CollisionUtils._tempV31.cloneTo(out);
  10009. return distance;
  10010. }
  10011. static intersectsRayAndSphereRD(ray, sphere) {
  10012. var sphereR = sphere.radius;
  10013. Vector3.subtract(ray.origin, sphere.center, CollisionUtils._tempV30);
  10014. var b = Vector3.dot(CollisionUtils._tempV30, ray.direction);
  10015. var c = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV30) - (sphereR * sphereR);
  10016. if (c > 0 && b > 0) {
  10017. return -1;
  10018. }
  10019. var discriminant = b * b - c;
  10020. if (discriminant < 0) {
  10021. return -1;
  10022. }
  10023. var distance = -b - Math.sqrt(discriminant);
  10024. if (distance < 0)
  10025. distance = 0;
  10026. return distance;
  10027. }
  10028. static intersectsRayAndSphereRP(ray, sphere, out) {
  10029. var distance = CollisionUtils.intersectsRayAndSphereRD(ray, sphere);
  10030. if (distance === -1) {
  10031. Vector3._ZERO.cloneTo(out);
  10032. return distance;
  10033. }
  10034. Vector3.scale(ray.direction, distance, CollisionUtils._tempV30);
  10035. Vector3.add(ray.origin, CollisionUtils._tempV30, CollisionUtils._tempV31);
  10036. CollisionUtils._tempV31.cloneTo(out);
  10037. return distance;
  10038. }
  10039. static intersectsSphereAndTriangle(sphere, vertex1, vertex2, vertex3) {
  10040. var sphereC = sphere.center;
  10041. var sphereR = sphere.radius;
  10042. CollisionUtils.closestPointPointTriangle(sphereC, vertex1, vertex2, vertex3, CollisionUtils._tempV30);
  10043. Vector3.subtract(CollisionUtils._tempV30, sphereC, CollisionUtils._tempV31);
  10044. var dot = Vector3.dot(CollisionUtils._tempV31, CollisionUtils._tempV31);
  10045. return dot <= sphereR * sphereR;
  10046. }
  10047. static intersectsPlaneAndPoint(plane, point) {
  10048. var distance = Vector3.dot(plane.normal, point) + plane.distance;
  10049. if (distance > 0)
  10050. return Plane.PlaneIntersectionType_Front;
  10051. if (distance < 0)
  10052. return Plane.PlaneIntersectionType_Back;
  10053. return Plane.PlaneIntersectionType_Intersecting;
  10054. }
  10055. static intersectsPlaneAndPlane(plane1, plane2) {
  10056. Vector3.cross(plane1.normal, plane2.normal, CollisionUtils._tempV30);
  10057. var denominator = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV30);
  10058. if (MathUtils3D.isZero(denominator))
  10059. return false;
  10060. return true;
  10061. }
  10062. static intersectsPlaneAndPlaneRL(plane1, plane2, line) {
  10063. var plane1nor = plane1.normal;
  10064. var plane2nor = plane2.normal;
  10065. Vector3.cross(plane1nor, plane2nor, CollisionUtils._tempV34);
  10066. var denominator = Vector3.dot(CollisionUtils._tempV34, CollisionUtils._tempV34);
  10067. if (MathUtils3D.isZero(denominator))
  10068. return false;
  10069. Vector3.scale(plane2nor, plane1.distance, CollisionUtils._tempV30);
  10070. Vector3.scale(plane1nor, plane2.distance, CollisionUtils._tempV31);
  10071. Vector3.subtract(CollisionUtils._tempV30, CollisionUtils._tempV31, CollisionUtils._tempV32);
  10072. Vector3.cross(CollisionUtils._tempV32, CollisionUtils._tempV34, CollisionUtils._tempV33);
  10073. Vector3.normalize(CollisionUtils._tempV34, CollisionUtils._tempV34);
  10074. return true;
  10075. }
  10076. static intersectsPlaneAndBox(plane, box) {
  10077. var planeD = plane.distance;
  10078. var planeNor = plane.normal;
  10079. var planeNoreX = planeNor.x;
  10080. var planeNoreY = planeNor.y;
  10081. var planeNoreZ = planeNor.z;
  10082. var boxMine = box.min;
  10083. var boxMineX = boxMine.x;
  10084. var boxMineY = boxMine.y;
  10085. var boxMineZ = boxMine.z;
  10086. var boxMaxe = box.max;
  10087. var boxMaxeX = boxMaxe.x;
  10088. var boxMaxeY = boxMaxe.y;
  10089. var boxMaxeZ = boxMaxe.z;
  10090. CollisionUtils._tempV30.x = (planeNoreX > 0) ? boxMineX : boxMaxeX;
  10091. CollisionUtils._tempV30.y = (planeNoreY > 0) ? boxMineY : boxMaxeY;
  10092. CollisionUtils._tempV30.z = (planeNoreZ > 0) ? boxMineZ : boxMaxeZ;
  10093. CollisionUtils._tempV31.x = (planeNoreX > 0) ? boxMaxeX : boxMineX;
  10094. CollisionUtils._tempV31.y = (planeNoreY > 0) ? boxMaxeY : boxMineY;
  10095. CollisionUtils._tempV31.z = (planeNoreZ > 0) ? boxMaxeZ : boxMineZ;
  10096. var distance = Vector3.dot(planeNor, CollisionUtils._tempV30);
  10097. if (distance + planeD > 0)
  10098. return Plane.PlaneIntersectionType_Front;
  10099. distance = Vector3.dot(planeNor, CollisionUtils._tempV31);
  10100. if (distance + planeD < 0)
  10101. return Plane.PlaneIntersectionType_Back;
  10102. return Plane.PlaneIntersectionType_Intersecting;
  10103. }
  10104. static intersectsPlaneAndSphere(plane, sphere) {
  10105. var sphereR = sphere.radius;
  10106. var distance = Vector3.dot(plane.normal, sphere.center) + plane.distance;
  10107. if (distance > sphereR)
  10108. return Plane.PlaneIntersectionType_Front;
  10109. if (distance < -sphereR)
  10110. return Plane.PlaneIntersectionType_Back;
  10111. return Plane.PlaneIntersectionType_Intersecting;
  10112. }
  10113. static intersectsBoxAndBox(box1, box2) {
  10114. var box1Mine = box1.min;
  10115. var box1Maxe = box1.max;
  10116. var box2Mine = box2.min;
  10117. var box2Maxe = box2.max;
  10118. if (box1Mine.x > box2Maxe.x || box2Mine.x > box1Maxe.x)
  10119. return false;
  10120. if (box1Mine.y > box2Maxe.y || box2Mine.y > box1Maxe.y)
  10121. return false;
  10122. if (box1Mine.z > box2Maxe.z || box2Mine.z > box1Maxe.z)
  10123. return false;
  10124. return true;
  10125. }
  10126. static intersectsBoxAndSphere(box, sphere) {
  10127. var center = sphere.center;
  10128. var radius = sphere.radius;
  10129. var nearest = CollisionUtils._tempV30;
  10130. Vector3.Clamp(center, box.min, box.max, nearest);
  10131. var distance = Vector3.distanceSquared(center, nearest);
  10132. return distance <= radius * radius;
  10133. }
  10134. static intersectsSphereAndSphere(sphere1, sphere2) {
  10135. var radiisum = sphere1.radius + sphere2.radius;
  10136. return Vector3.distanceSquared(sphere1.center, sphere2.center) <= radiisum * radiisum;
  10137. }
  10138. static boxContainsPoint(box, point) {
  10139. var boxMine = box.min;
  10140. var boxMaxe = box.max;
  10141. if (boxMine.x <= point.x && boxMaxe.x >= point.x && boxMine.y <= point.y && boxMaxe.y >= point.y && boxMine.z <= point.z && boxMaxe.z >= point.z)
  10142. return ContainmentType.Contains;
  10143. return ContainmentType.Disjoint;
  10144. }
  10145. static boxContainsBox(box1, box2) {
  10146. var box1Mine = box1.min;
  10147. var box1MineX = box1Mine.x;
  10148. var box1MineY = box1Mine.y;
  10149. var box1MineZ = box1Mine.z;
  10150. var box1Maxe = box1.max;
  10151. var box1MaxeX = box1Maxe.x;
  10152. var box1MaxeY = box1Maxe.y;
  10153. var box1MaxeZ = box1Maxe.z;
  10154. var box2Mine = box2.min;
  10155. var box2MineX = box2Mine.x;
  10156. var box2MineY = box2Mine.y;
  10157. var box2MineZ = box2Mine.z;
  10158. var box2Maxe = box2.max;
  10159. var box2MaxeX = box2Maxe.x;
  10160. var box2MaxeY = box2Maxe.y;
  10161. var box2MaxeZ = box2Maxe.z;
  10162. if (box1MaxeX < box2MineX || box1MineX > box2MaxeX)
  10163. return ContainmentType.Disjoint;
  10164. if (box1MaxeY < box2MineY || box1MineY > box2MaxeY)
  10165. return ContainmentType.Disjoint;
  10166. if (box1MaxeZ < box2MineZ || box1MineZ > box2MaxeZ)
  10167. return ContainmentType.Disjoint;
  10168. if (box1MineX <= box2MineX && box2MaxeX <= box1MaxeX && box1MineY <= box2MineY && box2MaxeY <= box1MaxeY && box1MineZ <= box2MineZ && box2MaxeZ <= box1MaxeZ) {
  10169. return ContainmentType.Contains;
  10170. }
  10171. return ContainmentType.Intersects;
  10172. }
  10173. static boxContainsSphere(box, sphere) {
  10174. var boxMin = box.min;
  10175. var boxMineX = boxMin.x;
  10176. var boxMineY = boxMin.y;
  10177. var boxMineZ = boxMin.z;
  10178. var boxMax = box.max;
  10179. var boxMaxeX = boxMax.x;
  10180. var boxMaxeY = boxMax.y;
  10181. var boxMaxeZ = boxMax.z;
  10182. var sphereC = sphere.center;
  10183. var sphereCeX = sphereC.x;
  10184. var sphereCeY = sphereC.y;
  10185. var sphereCeZ = sphereC.z;
  10186. var sphereR = sphere.radius;
  10187. Vector3.Clamp(sphereC, boxMin, boxMax, CollisionUtils._tempV30);
  10188. var distance = Vector3.distanceSquared(sphereC, CollisionUtils._tempV30);
  10189. if (distance > sphereR * sphereR)
  10190. return ContainmentType.Disjoint;
  10191. if ((((boxMineX + sphereR <= sphereCeX) && (sphereCeX <= boxMaxeX - sphereR)) && ((boxMaxeX - boxMineX > sphereR) &&
  10192. (boxMineY + sphereR <= sphereCeY))) && (((sphereCeY <= boxMaxeY - sphereR) && (boxMaxeY - boxMineY > sphereR)) &&
  10193. (((boxMineZ + sphereR <= sphereCeZ) && (sphereCeZ <= boxMaxeZ - sphereR)) && (boxMaxeZ - boxMineZ > sphereR))))
  10194. return ContainmentType.Contains;
  10195. return ContainmentType.Intersects;
  10196. }
  10197. static sphereContainsPoint(sphere, point) {
  10198. if (Vector3.distanceSquared(point, sphere.center) <= sphere.radius * sphere.radius)
  10199. return ContainmentType.Contains;
  10200. return ContainmentType.Disjoint;
  10201. }
  10202. static sphereContainsTriangle(sphere, vertex1, vertex2, vertex3) {
  10203. var test1 = CollisionUtils.sphereContainsPoint(sphere, vertex1);
  10204. var test2 = CollisionUtils.sphereContainsPoint(sphere, vertex2);
  10205. var test3 = CollisionUtils.sphereContainsPoint(sphere, vertex3);
  10206. if (test1 == ContainmentType.Contains && test2 == ContainmentType.Contains && test3 == ContainmentType.Contains)
  10207. return ContainmentType.Contains;
  10208. if (CollisionUtils.intersectsSphereAndTriangle(sphere, vertex1, vertex2, vertex3))
  10209. return ContainmentType.Intersects;
  10210. return ContainmentType.Disjoint;
  10211. }
  10212. static sphereContainsBox(sphere, box) {
  10213. var sphereC = sphere.center;
  10214. var sphereCeX = sphereC.x;
  10215. var sphereCeY = sphereC.y;
  10216. var sphereCeZ = sphereC.z;
  10217. var sphereR = sphere.radius;
  10218. var boxMin = box.min;
  10219. var boxMineX = boxMin.x;
  10220. var boxMineY = boxMin.y;
  10221. var boxMineZ = boxMin.z;
  10222. var boxMax = box.max;
  10223. var boxMaxeX = boxMax.x;
  10224. var boxMaxeY = boxMax.y;
  10225. var boxMaxeZ = boxMax.z;
  10226. var _tempV30e = CollisionUtils._tempV30;
  10227. var _tempV30eX = _tempV30e.x;
  10228. var _tempV30eY = _tempV30e.y;
  10229. var _tempV30eZ = _tempV30e.z;
  10230. if (!CollisionUtils.intersectsBoxAndSphere(box, sphere))
  10231. return ContainmentType.Disjoint;
  10232. var radiusSquared = sphereR * sphereR;
  10233. _tempV30eX = sphereCeX - boxMineX;
  10234. _tempV30eY = sphereCeY - boxMaxeY;
  10235. _tempV30eZ = sphereCeZ - boxMaxeZ;
  10236. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  10237. return ContainmentType.Intersects;
  10238. _tempV30eX = sphereCeX - boxMaxeX;
  10239. _tempV30eY = sphereCeY - boxMaxeY;
  10240. _tempV30eZ = sphereCeZ - boxMaxeZ;
  10241. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  10242. return ContainmentType.Intersects;
  10243. _tempV30eX = sphereCeX - boxMaxeX;
  10244. _tempV30eY = sphereCeY - boxMineY;
  10245. _tempV30eZ = sphereCeZ - boxMaxeZ;
  10246. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  10247. return ContainmentType.Intersects;
  10248. _tempV30eX = sphereCeX - boxMineX;
  10249. _tempV30eY = sphereCeY - boxMineY;
  10250. _tempV30eZ = sphereCeZ - boxMaxeZ;
  10251. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  10252. return ContainmentType.Intersects;
  10253. _tempV30eX = sphereCeX - boxMineX;
  10254. _tempV30eY = sphereCeY - boxMaxeY;
  10255. _tempV30eZ = sphereCeZ - boxMineZ;
  10256. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  10257. return ContainmentType.Intersects;
  10258. _tempV30eX = sphereCeX - boxMaxeX;
  10259. _tempV30eY = sphereCeY - boxMaxeY;
  10260. _tempV30eZ = sphereCeZ - boxMineZ;
  10261. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  10262. return ContainmentType.Intersects;
  10263. _tempV30eX = sphereCeX - boxMaxeX;
  10264. _tempV30eY = sphereCeY - boxMineY;
  10265. _tempV30eZ = sphereCeZ - boxMineZ;
  10266. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  10267. return ContainmentType.Intersects;
  10268. _tempV30eX = sphereCeX - boxMineX;
  10269. _tempV30eY = sphereCeY - boxMineY;
  10270. _tempV30eZ = sphereCeZ - boxMineZ;
  10271. if (Vector3.scalarLengthSquared(CollisionUtils._tempV30) > radiusSquared)
  10272. return ContainmentType.Intersects;
  10273. return ContainmentType.Contains;
  10274. }
  10275. static sphereContainsSphere(sphere1, sphere2) {
  10276. var sphere1R = sphere1.radius;
  10277. var sphere2R = sphere2.radius;
  10278. var distance = Vector3.distance(sphere1.center, sphere2.center);
  10279. if (sphere1R + sphere2R < distance)
  10280. return ContainmentType.Disjoint;
  10281. if (sphere1R - sphere2R < distance)
  10282. return ContainmentType.Intersects;
  10283. return ContainmentType.Contains;
  10284. }
  10285. static closestPointPointTriangle(point, vertex1, vertex2, vertex3, out) {
  10286. Vector3.subtract(vertex2, vertex1, CollisionUtils._tempV30);
  10287. Vector3.subtract(vertex3, vertex1, CollisionUtils._tempV31);
  10288. Vector3.subtract(point, vertex1, CollisionUtils._tempV32);
  10289. Vector3.subtract(point, vertex2, CollisionUtils._tempV33);
  10290. Vector3.subtract(point, vertex3, CollisionUtils._tempV34);
  10291. var d1 = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV32);
  10292. var d2 = Vector3.dot(CollisionUtils._tempV31, CollisionUtils._tempV32);
  10293. var d3 = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV33);
  10294. var d4 = Vector3.dot(CollisionUtils._tempV31, CollisionUtils._tempV33);
  10295. var d5 = Vector3.dot(CollisionUtils._tempV30, CollisionUtils._tempV34);
  10296. var d6 = Vector3.dot(CollisionUtils._tempV31, CollisionUtils._tempV34);
  10297. if (d1 <= 0 && d2 <= 0) {
  10298. vertex1.cloneTo(out);
  10299. return;
  10300. }
  10301. if (d3 >= 0 && d4 <= d3) {
  10302. vertex2.cloneTo(out);
  10303. return;
  10304. }
  10305. var vc = d1 * d4 - d3 * d2;
  10306. if (vc <= 0 && d1 >= 0 && d3 <= 0) {
  10307. var v = d1 / (d1 - d3);
  10308. Vector3.scale(CollisionUtils._tempV30, v, out);
  10309. Vector3.add(vertex1, out, out);
  10310. return;
  10311. }
  10312. if (d6 >= 0 && d5 <= d6) {
  10313. vertex3.cloneTo(out);
  10314. return;
  10315. }
  10316. var vb = d5 * d2 - d1 * d6;
  10317. if (vb <= 0 && d2 >= 0 && d6 <= 0) {
  10318. var w = d2 / (d2 - d6);
  10319. Vector3.scale(CollisionUtils._tempV31, w, out);
  10320. Vector3.add(vertex1, out, out);
  10321. return;
  10322. }
  10323. var va = d3 * d6 - d5 * d4;
  10324. if (va <= 0 && (d4 - d3) >= 0 && (d5 - d6) >= 0) {
  10325. var w3 = (d4 - d3) / ((d4 - d3) + (d5 - d6));
  10326. Vector3.subtract(vertex3, vertex2, out);
  10327. Vector3.scale(out, w3, out);
  10328. Vector3.add(vertex2, out, out);
  10329. return;
  10330. }
  10331. var denom = 1 / (va + vb + vc);
  10332. var v2 = vb * denom;
  10333. var w2 = vc * denom;
  10334. Vector3.scale(CollisionUtils._tempV30, v2, CollisionUtils._tempV35);
  10335. Vector3.scale(CollisionUtils._tempV31, w2, CollisionUtils._tempV36);
  10336. Vector3.add(CollisionUtils._tempV35, CollisionUtils._tempV36, out);
  10337. Vector3.add(vertex1, out, out);
  10338. }
  10339. static closestPointPlanePoint(plane, point, out) {
  10340. var planeN = plane.normal;
  10341. var t = Vector3.dot(planeN, point) - plane.distance;
  10342. Vector3.scale(planeN, t, CollisionUtils._tempV30);
  10343. Vector3.subtract(point, CollisionUtils._tempV30, out);
  10344. }
  10345. static closestPointBoxPoint(box, point, out) {
  10346. Vector3.max(point, box.min, CollisionUtils._tempV30);
  10347. Vector3.min(CollisionUtils._tempV30, box.max, out);
  10348. }
  10349. static closestPointSpherePoint(sphere, point, out) {
  10350. var sphereC = sphere.center;
  10351. Vector3.subtract(point, sphereC, out);
  10352. Vector3.normalize(out, out);
  10353. Vector3.scale(out, sphere.radius, out);
  10354. Vector3.add(out, sphereC, out);
  10355. }
  10356. static closestPointSphereSphere(sphere1, sphere2, out) {
  10357. var sphere1C = sphere1.center;
  10358. Vector3.subtract(sphere2.center, sphere1C, out);
  10359. Vector3.normalize(out, out);
  10360. Vector3.scale(out, sphere1.radius, out);
  10361. Vector3.add(out, sphere1C, out);
  10362. }
  10363. }
  10364. CollisionUtils._tempV30 = new Vector3();
  10365. CollisionUtils._tempV31 = new Vector3();
  10366. CollisionUtils._tempV32 = new Vector3();
  10367. CollisionUtils._tempV33 = new Vector3();
  10368. CollisionUtils._tempV34 = new Vector3();
  10369. CollisionUtils._tempV35 = new Vector3();
  10370. CollisionUtils._tempV36 = new Vector3();
  10371. (function (FrustumCorner) {
  10372. FrustumCorner[FrustumCorner["FarBottomLeft"] = 0] = "FarBottomLeft";
  10373. FrustumCorner[FrustumCorner["FarTopLeft"] = 1] = "FarTopLeft";
  10374. FrustumCorner[FrustumCorner["FarTopRight"] = 2] = "FarTopRight";
  10375. FrustumCorner[FrustumCorner["FarBottomRight"] = 3] = "FarBottomRight";
  10376. FrustumCorner[FrustumCorner["nearBottomLeft"] = 4] = "nearBottomLeft";
  10377. FrustumCorner[FrustumCorner["nearTopLeft"] = 5] = "nearTopLeft";
  10378. FrustumCorner[FrustumCorner["nearTopRight"] = 6] = "nearTopRight";
  10379. FrustumCorner[FrustumCorner["nearBottomRight"] = 7] = "nearBottomRight";
  10380. FrustumCorner[FrustumCorner["unknown"] = 8] = "unknown";
  10381. })(exports.FrustumCorner || (exports.FrustumCorner = {}));
  10382. class BoundFrustum {
  10383. constructor(matrix) {
  10384. this._matrix = matrix;
  10385. this._near = new Plane(new Vector3());
  10386. this._far = new Plane(new Vector3());
  10387. this._left = new Plane(new Vector3());
  10388. this._right = new Plane(new Vector3());
  10389. this._top = new Plane(new Vector3());
  10390. this._bottom = new Plane(new Vector3());
  10391. BoundFrustum.getPlanesFromMatrix(this._matrix, this._near, this._far, this._left, this._right, this._top, this._bottom);
  10392. }
  10393. static getPlanesFromMatrix(m, np, fp, lp, rp, tp, bp) {
  10394. var matrixE = m.elements;
  10395. var m11 = matrixE[0];
  10396. var m12 = matrixE[1];
  10397. var m13 = matrixE[2];
  10398. var m14 = matrixE[3];
  10399. var m21 = matrixE[4];
  10400. var m22 = matrixE[5];
  10401. var m23 = matrixE[6];
  10402. var m24 = matrixE[7];
  10403. var m31 = matrixE[8];
  10404. var m32 = matrixE[9];
  10405. var m33 = matrixE[10];
  10406. var m34 = matrixE[11];
  10407. var m41 = matrixE[12];
  10408. var m42 = matrixE[13];
  10409. var m43 = matrixE[14];
  10410. var m44 = matrixE[15];
  10411. var nearNorE = np.normal;
  10412. nearNorE.x = m13;
  10413. nearNorE.y = m23;
  10414. nearNorE.z = m33;
  10415. np.distance = m43;
  10416. np.normalize();
  10417. var farNorE = fp.normal;
  10418. farNorE.x = m14 - m13;
  10419. farNorE.y = m24 - m23;
  10420. farNorE.z = m34 - m33;
  10421. fp.distance = m44 - m43;
  10422. fp.normalize();
  10423. var leftNorE = lp.normal;
  10424. leftNorE.x = m14 + m11;
  10425. leftNorE.y = m24 + m21;
  10426. leftNorE.z = m34 + m31;
  10427. lp.distance = m44 + m41;
  10428. lp.normalize();
  10429. var rightNorE = rp.normal;
  10430. rightNorE.x = m14 - m11;
  10431. rightNorE.y = m24 - m21;
  10432. rightNorE.z = m34 - m31;
  10433. rp.distance = m44 - m41;
  10434. rp.normalize();
  10435. var topNorE = tp.normal;
  10436. topNorE.x = m14 - m12;
  10437. topNorE.y = m24 - m22;
  10438. topNorE.z = m34 - m32;
  10439. tp.distance = m44 - m42;
  10440. tp.normalize();
  10441. var bottomNorE = bp.normal;
  10442. bottomNorE.x = m14 + m12;
  10443. bottomNorE.y = m24 + m22;
  10444. bottomNorE.z = m34 + m32;
  10445. bp.distance = m44 + m42;
  10446. bp.normalize();
  10447. }
  10448. get matrix() {
  10449. return this._matrix;
  10450. }
  10451. set matrix(matrix) {
  10452. matrix.cloneTo(this._matrix);
  10453. BoundFrustum.getPlanesFromMatrix(this._matrix, this._near, this._far, this._left, this._right, this._top, this._bottom);
  10454. }
  10455. get near() {
  10456. return this._near;
  10457. }
  10458. get far() {
  10459. return this._far;
  10460. }
  10461. get left() {
  10462. return this._left;
  10463. }
  10464. get right() {
  10465. return this._right;
  10466. }
  10467. get top() {
  10468. return this._top;
  10469. }
  10470. get bottom() {
  10471. return this._bottom;
  10472. }
  10473. equalsBoundFrustum(other) {
  10474. return this._matrix.equalsOtherMatrix(other.matrix);
  10475. }
  10476. equalsObj(obj) {
  10477. if (obj instanceof BoundFrustum) {
  10478. var bf = obj;
  10479. return this.equalsBoundFrustum(bf);
  10480. }
  10481. return false;
  10482. }
  10483. getPlane(index) {
  10484. switch (index) {
  10485. case 0:
  10486. return this._near;
  10487. case 1:
  10488. return this._far;
  10489. case 2:
  10490. return this._left;
  10491. case 3:
  10492. return this._right;
  10493. case 4:
  10494. return this._top;
  10495. case 5:
  10496. return this._bottom;
  10497. default:
  10498. return null;
  10499. }
  10500. }
  10501. static get3PlaneInterPoint(p1, p2, p3, out) {
  10502. var p1Nor = p1.normal;
  10503. var p2Nor = p2.normal;
  10504. var p3Nor = p3.normal;
  10505. Vector3.cross(p2Nor, p3Nor, BoundFrustum._tempV30);
  10506. Vector3.cross(p3Nor, p1Nor, BoundFrustum._tempV31);
  10507. Vector3.cross(p1Nor, p2Nor, BoundFrustum._tempV32);
  10508. var a = Vector3.dot(p1Nor, BoundFrustum._tempV30);
  10509. var b = Vector3.dot(p2Nor, BoundFrustum._tempV31);
  10510. var c = Vector3.dot(p3Nor, BoundFrustum._tempV32);
  10511. Vector3.scale(BoundFrustum._tempV30, -p1.distance / a, BoundFrustum._tempV33);
  10512. Vector3.scale(BoundFrustum._tempV31, -p2.distance / b, BoundFrustum._tempV34);
  10513. Vector3.scale(BoundFrustum._tempV32, -p3.distance / c, BoundFrustum._tempV35);
  10514. Vector3.add(BoundFrustum._tempV33, BoundFrustum._tempV34, BoundFrustum._tempV36);
  10515. Vector3.add(BoundFrustum._tempV35, BoundFrustum._tempV36, out);
  10516. }
  10517. getCorners(corners) {
  10518. BoundFrustum.get3PlaneInterPoint(this._near, this._bottom, this._right, corners[exports.FrustumCorner.nearBottomRight]);
  10519. BoundFrustum.get3PlaneInterPoint(this._near, this._top, this._right, corners[exports.FrustumCorner.nearTopRight]);
  10520. BoundFrustum.get3PlaneInterPoint(this._near, this._top, this._left, corners[exports.FrustumCorner.nearTopLeft]);
  10521. BoundFrustum.get3PlaneInterPoint(this._near, this._bottom, this._left, corners[exports.FrustumCorner.nearBottomLeft]);
  10522. BoundFrustum.get3PlaneInterPoint(this._far, this._bottom, this._right, corners[exports.FrustumCorner.FarBottomRight]);
  10523. BoundFrustum.get3PlaneInterPoint(this._far, this._top, this._right, corners[exports.FrustumCorner.FarTopRight]);
  10524. BoundFrustum.get3PlaneInterPoint(this._far, this._top, this._left, corners[exports.FrustumCorner.FarTopLeft]);
  10525. BoundFrustum.get3PlaneInterPoint(this._far, this._bottom, this._left, corners[exports.FrustumCorner.FarBottomLeft]);
  10526. }
  10527. containsPoint(point) {
  10528. var result = Plane.PlaneIntersectionType_Front;
  10529. var planeResult = Plane.PlaneIntersectionType_Front;
  10530. for (var i = 0; i < 6; i++) {
  10531. switch (i) {
  10532. case 0:
  10533. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._near, point);
  10534. break;
  10535. case 1:
  10536. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._far, point);
  10537. break;
  10538. case 2:
  10539. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._left, point);
  10540. break;
  10541. case 3:
  10542. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._right, point);
  10543. break;
  10544. case 4:
  10545. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._top, point);
  10546. break;
  10547. case 5:
  10548. planeResult = CollisionUtils.intersectsPlaneAndPoint(this._bottom, point);
  10549. break;
  10550. }
  10551. switch (planeResult) {
  10552. case Plane.PlaneIntersectionType_Back:
  10553. return ContainmentType.Disjoint;
  10554. case Plane.PlaneIntersectionType_Intersecting:
  10555. result = Plane.PlaneIntersectionType_Intersecting;
  10556. break;
  10557. }
  10558. }
  10559. switch (result) {
  10560. case Plane.PlaneIntersectionType_Intersecting:
  10561. return ContainmentType.Intersects;
  10562. default:
  10563. return ContainmentType.Contains;
  10564. }
  10565. }
  10566. intersects(box) {
  10567. var min = box.min;
  10568. var max = box.max;
  10569. var minX = min.x;
  10570. var minY = min.y;
  10571. var minZ = min.z;
  10572. var maxX = max.x;
  10573. var maxY = max.y;
  10574. var maxZ = max.z;
  10575. var nearNormal = this._near.normal;
  10576. if (this._near.distance + (nearNormal.x * (nearNormal.x < 0 ? minX : maxX)) + (nearNormal.y * (nearNormal.y < 0 ? minY : maxY)) + (nearNormal.z * (nearNormal.z < 0 ? minZ : maxZ)) < 0)
  10577. return false;
  10578. var leftNormal = this._left.normal;
  10579. if (this._left.distance + (leftNormal.x * (leftNormal.x < 0 ? minX : maxX)) + (leftNormal.y * (leftNormal.y < 0 ? minY : maxY)) + (leftNormal.z * (leftNormal.z < 0 ? minZ : maxZ)) < 0)
  10580. return false;
  10581. var rightNormal = this._right.normal;
  10582. if (this._right.distance + (rightNormal.x * (rightNormal.x < 0 ? minX : maxX)) + (rightNormal.y * (rightNormal.y < 0 ? minY : maxY)) + (rightNormal.z * (rightNormal.z < 0 ? minZ : maxZ)) < 0)
  10583. return false;
  10584. var bottomNormal = this._bottom.normal;
  10585. if (this._bottom.distance + (bottomNormal.x * (bottomNormal.x < 0 ? minX : maxX)) + (bottomNormal.y * (bottomNormal.y < 0 ? minY : maxY)) + (bottomNormal.z * (bottomNormal.z < 0 ? minZ : maxZ)) < 0)
  10586. return false;
  10587. var topNormal = this._top.normal;
  10588. if (this._top.distance + (topNormal.x * (topNormal.x < 0 ? minX : maxX)) + (topNormal.y * (topNormal.y < 0 ? minY : maxY)) + (topNormal.z * (topNormal.z < 0 ? minZ : maxZ)) < 0)
  10589. return false;
  10590. var farNormal = this._far.normal;
  10591. if (this._far.distance + (farNormal.x * (farNormal.x < 0 ? minX : maxX)) + (farNormal.y * (farNormal.y < 0 ? minY : maxY)) + (farNormal.z * (farNormal.z < 0 ? minZ : maxZ)) < 0)
  10592. return false;
  10593. return true;
  10594. }
  10595. containsBoundBox(box) {
  10596. var p = BoundFrustum._tempV30, n = BoundFrustum._tempV31;
  10597. var boxMin = box.min;
  10598. var boxMax = box.max;
  10599. var result = ContainmentType.Contains;
  10600. for (var i = 0; i < 6; i++) {
  10601. var plane = this.getPlane(i);
  10602. var planeNor = plane.normal;
  10603. if (planeNor.x >= 0) {
  10604. p.x = boxMax.x;
  10605. n.x = boxMin.x;
  10606. }
  10607. else {
  10608. p.x = boxMin.x;
  10609. n.x = boxMax.x;
  10610. }
  10611. if (planeNor.y >= 0) {
  10612. p.y = boxMax.y;
  10613. n.y = boxMin.y;
  10614. }
  10615. else {
  10616. p.y = boxMin.y;
  10617. n.y = boxMax.y;
  10618. }
  10619. if (planeNor.z >= 0) {
  10620. p.z = boxMax.z;
  10621. n.z = boxMin.z;
  10622. }
  10623. else {
  10624. p.z = boxMin.z;
  10625. n.z = boxMax.z;
  10626. }
  10627. if (CollisionUtils.intersectsPlaneAndPoint(plane, p) === Plane.PlaneIntersectionType_Back)
  10628. return ContainmentType.Disjoint;
  10629. if (CollisionUtils.intersectsPlaneAndPoint(plane, n) === Plane.PlaneIntersectionType_Back)
  10630. result = ContainmentType.Intersects;
  10631. }
  10632. return result;
  10633. }
  10634. containsBoundSphere(sphere) {
  10635. var result = Plane.PlaneIntersectionType_Front;
  10636. var planeResult = Plane.PlaneIntersectionType_Front;
  10637. for (var i = 0; i < 6; i++) {
  10638. switch (i) {
  10639. case 0:
  10640. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._near, sphere);
  10641. break;
  10642. case 1:
  10643. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._far, sphere);
  10644. break;
  10645. case 2:
  10646. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._left, sphere);
  10647. break;
  10648. case 3:
  10649. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._right, sphere);
  10650. break;
  10651. case 4:
  10652. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._top, sphere);
  10653. break;
  10654. case 5:
  10655. planeResult = CollisionUtils.intersectsPlaneAndSphere(this._bottom, sphere);
  10656. break;
  10657. }
  10658. switch (planeResult) {
  10659. case Plane.PlaneIntersectionType_Back:
  10660. return ContainmentType.Disjoint;
  10661. case Plane.PlaneIntersectionType_Intersecting:
  10662. result = Plane.PlaneIntersectionType_Intersecting;
  10663. break;
  10664. }
  10665. }
  10666. switch (result) {
  10667. case Plane.PlaneIntersectionType_Intersecting:
  10668. return ContainmentType.Intersects;
  10669. default:
  10670. return ContainmentType.Contains;
  10671. }
  10672. }
  10673. }
  10674. BoundFrustum._tempV30 = new Vector3();
  10675. BoundFrustum._tempV31 = new Vector3();
  10676. BoundFrustum._tempV32 = new Vector3();
  10677. BoundFrustum._tempV33 = new Vector3();
  10678. BoundFrustum._tempV34 = new Vector3();
  10679. BoundFrustum._tempV35 = new Vector3();
  10680. BoundFrustum._tempV36 = new Vector3();
  10681. class Viewport {
  10682. constructor(x, y, width, height) {
  10683. this.minDepth = 0.0;
  10684. this.maxDepth = 1.0;
  10685. this.x = x;
  10686. this.y = y;
  10687. this.width = width;
  10688. this.height = height;
  10689. }
  10690. project(source, matrix, out) {
  10691. Vector3.transformV3ToV4(source, matrix, out);
  10692. var x = out.x, y = out.y, z = out.z;
  10693. var w = out.w;
  10694. if (w !== 1.0) {
  10695. x = x / w;
  10696. y = y / w;
  10697. z = z / w;
  10698. }
  10699. out.x = (x + 1.0) * 0.5 * this.width + this.x;
  10700. out.y = (-y + 1.0) * 0.5 * this.height + this.y;
  10701. out.z = z * (this.maxDepth - this.minDepth) + this.minDepth;
  10702. }
  10703. unprojectFromMat(source, matrix, out) {
  10704. var matrixEleme = matrix.elements;
  10705. out.x = (((source.x - this.x) / this.width) * 2.0) - 1.0;
  10706. out.y = -((((source.y - this.y) / this.height) * 2.0) - 1.0);
  10707. out.z = (source.z - this.minDepth) / (this.maxDepth - this.minDepth);
  10708. var a = (((out.x * matrixEleme[3]) + (out.y * matrixEleme[7])) + (out.z * matrixEleme[11])) + matrixEleme[15];
  10709. Vector3.transformV3ToV3(out, matrix, out);
  10710. if (a !== 1.0) {
  10711. out.x = out.x / a;
  10712. out.y = out.y / a;
  10713. out.z = out.z / a;
  10714. }
  10715. }
  10716. unprojectFromWVP(source, projection, view, world, out) {
  10717. Matrix4x4.multiply(projection, view, Viewport._tempMatrix4x4);
  10718. (world) && (Matrix4x4.multiply(Viewport._tempMatrix4x4, world, Viewport._tempMatrix4x4));
  10719. Viewport._tempMatrix4x4.invert(Viewport._tempMatrix4x4);
  10720. this.unprojectFromMat(source, Viewport._tempMatrix4x4, out);
  10721. }
  10722. cloneTo(out) {
  10723. out.x = this.x;
  10724. out.y = this.y;
  10725. out.width = this.width;
  10726. out.height = this.height;
  10727. out.minDepth = this.minDepth;
  10728. out.maxDepth = this.maxDepth;
  10729. }
  10730. }
  10731. Viewport._tempMatrix4x4 = new Matrix4x4();
  10732. class Picker {
  10733. constructor() {
  10734. }
  10735. static calculateCursorRay(point, viewPort, projectionMatrix, viewMatrix, world, out) {
  10736. var x = point.x;
  10737. var y = point.y;
  10738. var nearSource = Picker._tempVector30;
  10739. var nerSourceE = nearSource;
  10740. nerSourceE.x = x;
  10741. nerSourceE.y = y;
  10742. nerSourceE.z = viewPort.minDepth;
  10743. var farSource = Picker._tempVector31;
  10744. var farSourceE = farSource;
  10745. farSourceE.x = x;
  10746. farSourceE.y = y;
  10747. farSourceE.z = viewPort.maxDepth;
  10748. var nearPoint = out.origin;
  10749. var farPoint = Picker._tempVector32;
  10750. viewPort.unprojectFromWVP(nearSource, projectionMatrix, viewMatrix, world, nearPoint);
  10751. viewPort.unprojectFromWVP(farSource, projectionMatrix, viewMatrix, world, farPoint);
  10752. var outDire = out.direction;
  10753. outDire.x = farPoint.x - nearPoint.x;
  10754. outDire.y = farPoint.y - nearPoint.y;
  10755. outDire.z = farPoint.z - nearPoint.z;
  10756. Vector3.normalize(out.direction, out.direction);
  10757. }
  10758. static rayIntersectsTriangle(ray, vertex1, vertex2, vertex3) {
  10759. var result;
  10760. var edge1 = Picker._tempVector30, edge2 = Picker._tempVector31;
  10761. Vector3.subtract(vertex2, vertex1, edge1);
  10762. Vector3.subtract(vertex3, vertex1, edge2);
  10763. var directionCrossEdge2 = Picker._tempVector32;
  10764. Vector3.cross(ray.direction, edge2, directionCrossEdge2);
  10765. var determinant;
  10766. determinant = Vector3.dot(edge1, directionCrossEdge2);
  10767. if (determinant > -Number.MIN_VALUE && determinant < Number.MIN_VALUE) {
  10768. result = Number.NaN;
  10769. return result;
  10770. }
  10771. var inverseDeterminant = 1.0 / determinant;
  10772. var distanceVector = Picker._tempVector33;
  10773. Vector3.subtract(ray.origin, vertex1, distanceVector);
  10774. var triangleU;
  10775. triangleU = Vector3.dot(distanceVector, directionCrossEdge2);
  10776. triangleU *= inverseDeterminant;
  10777. if (triangleU < 0 || triangleU > 1) {
  10778. result = Number.NaN;
  10779. return result;
  10780. }
  10781. var distanceCrossEdge1 = Picker._tempVector34;
  10782. Vector3.cross(distanceVector, edge1, distanceCrossEdge1);
  10783. var triangleV;
  10784. triangleV = Vector3.dot(ray.direction, distanceCrossEdge1);
  10785. triangleV *= inverseDeterminant;
  10786. if (triangleV < 0 || triangleU + triangleV > 1) {
  10787. result = Number.NaN;
  10788. return result;
  10789. }
  10790. var rayDistance;
  10791. rayDistance = Vector3.dot(edge2, distanceCrossEdge1);
  10792. rayDistance *= inverseDeterminant;
  10793. if (rayDistance < 0) {
  10794. result = Number.NaN;
  10795. return result;
  10796. }
  10797. result = rayDistance;
  10798. return result;
  10799. }
  10800. }
  10801. Picker._tempVector30 = new Vector3();
  10802. Picker._tempVector31 = new Vector3();
  10803. Picker._tempVector32 = new Vector3();
  10804. Picker._tempVector33 = new Vector3();
  10805. Picker._tempVector34 = new Vector3();
  10806. (function (IndexFormat) {
  10807. IndexFormat[IndexFormat["UInt8"] = 0] = "UInt8";
  10808. IndexFormat[IndexFormat["UInt16"] = 1] = "UInt16";
  10809. IndexFormat[IndexFormat["UInt32"] = 2] = "UInt32";
  10810. })(exports.IndexFormat || (exports.IndexFormat = {}));
  10811. class IndexBuffer3D extends Laya.Buffer {
  10812. constructor(indexType, indexCount, bufferUsage = 0x88E4, canRead = false) {
  10813. super();
  10814. this._indexType = indexType;
  10815. this._indexCount = indexCount;
  10816. this._bufferUsage = bufferUsage;
  10817. this._bufferType = Laya.LayaGL.instance.ELEMENT_ARRAY_BUFFER;
  10818. this._canRead = canRead;
  10819. switch (indexType) {
  10820. case exports.IndexFormat.UInt32:
  10821. this._indexTypeByteCount = 4;
  10822. break;
  10823. case exports.IndexFormat.UInt16:
  10824. this._indexTypeByteCount = 2;
  10825. break;
  10826. case exports.IndexFormat.UInt8:
  10827. this._indexTypeByteCount = 1;
  10828. break;
  10829. default:
  10830. throw new Error("unidentification index type.");
  10831. }
  10832. var byteLength = this._indexTypeByteCount * indexCount;
  10833. var curBufSta = Laya.BufferStateBase._curBindedBufferState;
  10834. this._byteLength = byteLength;
  10835. if (curBufSta) {
  10836. if (curBufSta._bindedIndexBuffer === this) {
  10837. Laya.LayaGL.instance.bufferData(this._bufferType, byteLength, this._bufferUsage);
  10838. }
  10839. else {
  10840. curBufSta.unBind();
  10841. this.bind();
  10842. Laya.LayaGL.instance.bufferData(this._bufferType, byteLength, this._bufferUsage);
  10843. curBufSta.bind();
  10844. }
  10845. }
  10846. else {
  10847. this.bind();
  10848. Laya.LayaGL.instance.bufferData(this._bufferType, byteLength, this._bufferUsage);
  10849. }
  10850. if (canRead) {
  10851. switch (indexType) {
  10852. case exports.IndexFormat.UInt32:
  10853. this._buffer = new Uint32Array(indexCount);
  10854. break;
  10855. case exports.IndexFormat.UInt16:
  10856. this._buffer = new Uint16Array(indexCount);
  10857. break;
  10858. case exports.IndexFormat.UInt8:
  10859. this._buffer = new Uint8Array(indexCount);
  10860. break;
  10861. }
  10862. }
  10863. }
  10864. get indexType() {
  10865. return this._indexType;
  10866. }
  10867. get indexTypeByteCount() {
  10868. return this._indexTypeByteCount;
  10869. }
  10870. get indexCount() {
  10871. return this._indexCount;
  10872. }
  10873. get canRead() {
  10874. return this._canRead;
  10875. }
  10876. _bindForVAO() {
  10877. if (Laya.BufferStateBase._curBindedBufferState) {
  10878. var gl = Laya.LayaGL.instance;
  10879. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._glBuffer);
  10880. }
  10881. else {
  10882. throw "IndexBuffer3D: must bind current BufferState.";
  10883. }
  10884. }
  10885. bind() {
  10886. if (Laya.BufferStateBase._curBindedBufferState) {
  10887. throw "IndexBuffer3D: must unbind current BufferState.";
  10888. }
  10889. else {
  10890. if (Laya.Buffer._bindedIndexBuffer !== this._glBuffer) {
  10891. var gl = Laya.LayaGL.instance;
  10892. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._glBuffer);
  10893. Laya.Buffer._bindedIndexBuffer = this._glBuffer;
  10894. return true;
  10895. }
  10896. else {
  10897. return false;
  10898. }
  10899. }
  10900. }
  10901. setData(data, bufferOffset = 0, dataStartIndex = 0, dataCount = 4294967295) {
  10902. var byteCount = this._indexTypeByteCount;
  10903. if (dataStartIndex !== 0 || dataCount !== 4294967295) {
  10904. switch (this._indexType) {
  10905. case exports.IndexFormat.UInt32:
  10906. data = new Uint32Array(data.buffer, dataStartIndex * byteCount, dataCount);
  10907. break;
  10908. case exports.IndexFormat.UInt16:
  10909. data = new Uint16Array(data.buffer, dataStartIndex * byteCount, dataCount);
  10910. break;
  10911. case exports.IndexFormat.UInt8:
  10912. data = new Uint8Array(data.buffer, dataStartIndex * byteCount, dataCount);
  10913. break;
  10914. }
  10915. }
  10916. var curBufSta = Laya.BufferStateBase._curBindedBufferState;
  10917. if (curBufSta) {
  10918. if (curBufSta._bindedIndexBuffer === this) {
  10919. Laya.LayaGL.instance.bufferSubData(this._bufferType, bufferOffset * byteCount, data);
  10920. }
  10921. else {
  10922. curBufSta.unBind();
  10923. this.bind();
  10924. Laya.LayaGL.instance.bufferSubData(this._bufferType, bufferOffset * byteCount, data);
  10925. curBufSta.bind();
  10926. }
  10927. }
  10928. else {
  10929. this.bind();
  10930. Laya.LayaGL.instance.bufferSubData(this._bufferType, bufferOffset * byteCount, data);
  10931. }
  10932. if (this._canRead) {
  10933. if (bufferOffset !== 0 || dataStartIndex !== 0 || dataCount !== 4294967295) {
  10934. var maxLength = this._buffer.length - bufferOffset;
  10935. if (dataCount > maxLength)
  10936. dataCount = maxLength;
  10937. for (var i = 0; i < dataCount; i++)
  10938. this._buffer[bufferOffset + i] = data[i];
  10939. }
  10940. else {
  10941. this._buffer = data;
  10942. }
  10943. }
  10944. }
  10945. getData() {
  10946. if (this._canRead)
  10947. return this._buffer;
  10948. else
  10949. throw new Error("Can't read data from VertexBuffer with only write flag!");
  10950. }
  10951. destroy() {
  10952. super.destroy();
  10953. this._buffer = null;
  10954. this._byteLength = 0;
  10955. this._indexCount = 0;
  10956. }
  10957. }
  10958. class VertexMesh {
  10959. static __init__() {
  10960. VertexMesh.instanceWorldMatrixDeclaration = new VertexDeclaration(64, [new VertexElement(0, VertexElementFormat.Vector4, VertexMesh.MESH_WORLDMATRIX_ROW0),
  10961. new VertexElement(16, VertexElementFormat.Vector4, VertexMesh.MESH_WORLDMATRIX_ROW1),
  10962. new VertexElement(32, VertexElementFormat.Vector4, VertexMesh.MESH_WORLDMATRIX_ROW2),
  10963. new VertexElement(48, VertexElementFormat.Vector4, VertexMesh.MESH_WORLDMATRIX_ROW3)]);
  10964. VertexMesh.instanceMVPMatrixDeclaration = new VertexDeclaration(64, [new VertexElement(0, VertexElementFormat.Vector4, VertexMesh.MESH_MVPMATRIX_ROW0),
  10965. new VertexElement(16, VertexElementFormat.Vector4, VertexMesh.MESH_MVPMATRIX_ROW1),
  10966. new VertexElement(32, VertexElementFormat.Vector4, VertexMesh.MESH_MVPMATRIX_ROW2),
  10967. new VertexElement(48, VertexElementFormat.Vector4, VertexMesh.MESH_MVPMATRIX_ROW3)]);
  10968. VertexMesh.instanceSimpleAnimatorDeclaration = new VertexDeclaration(16, [new VertexElement(0, VertexElementFormat.Vector4, VertexMesh.MESH_SIMPLEANIMATOR)]);
  10969. }
  10970. static getVertexDeclaration(vertexFlag, compatible = true) {
  10971. var verDec = VertexMesh._vertexDeclarationMap[vertexFlag + (compatible ? "_0" : "_1")];
  10972. if (!verDec) {
  10973. var subFlags = vertexFlag.split(",");
  10974. var offset = 0;
  10975. var elements = [];
  10976. for (var i = 0, n = subFlags.length; i < n; i++) {
  10977. var element;
  10978. switch (subFlags[i]) {
  10979. case "POSITION":
  10980. element = new VertexElement(offset, VertexElementFormat.Vector3, VertexMesh.MESH_POSITION0);
  10981. offset += 12;
  10982. break;
  10983. case "NORMAL":
  10984. element = new VertexElement(offset, VertexElementFormat.Vector3, VertexMesh.MESH_NORMAL0);
  10985. offset += 12;
  10986. break;
  10987. case "COLOR":
  10988. element = new VertexElement(offset, VertexElementFormat.Vector4, VertexMesh.MESH_COLOR0);
  10989. offset += 16;
  10990. break;
  10991. case "UV":
  10992. element = new VertexElement(offset, VertexElementFormat.Vector2, VertexMesh.MESH_TEXTURECOORDINATE0);
  10993. offset += 8;
  10994. break;
  10995. case "UV1":
  10996. element = new VertexElement(offset, VertexElementFormat.Vector2, VertexMesh.MESH_TEXTURECOORDINATE1);
  10997. offset += 8;
  10998. break;
  10999. case "BLENDWEIGHT":
  11000. element = new VertexElement(offset, VertexElementFormat.Vector4, VertexMesh.MESH_BLENDWEIGHT0);
  11001. offset += 16;
  11002. break;
  11003. case "BLENDINDICES":
  11004. if (compatible) {
  11005. element = new VertexElement(offset, VertexElementFormat.Vector4, VertexMesh.MESH_BLENDINDICES0);
  11006. offset += 16;
  11007. }
  11008. else {
  11009. element = new VertexElement(offset, VertexElementFormat.Byte4, VertexMesh.MESH_BLENDINDICES0);
  11010. offset += 4;
  11011. }
  11012. break;
  11013. case "TANGENT":
  11014. element = new VertexElement(offset, VertexElementFormat.Vector4, VertexMesh.MESH_TANGENT0);
  11015. offset += 16;
  11016. break;
  11017. default:
  11018. throw "VertexMesh: unknown vertex flag.";
  11019. }
  11020. elements.push(element);
  11021. }
  11022. verDec = new VertexDeclaration(offset, elements);
  11023. VertexMesh._vertexDeclarationMap[vertexFlag + (compatible ? "_0" : "_1")] = verDec;
  11024. }
  11025. return verDec;
  11026. }
  11027. }
  11028. VertexMesh.MESH_POSITION0 = 0;
  11029. VertexMesh.MESH_COLOR0 = 1;
  11030. VertexMesh.MESH_TEXTURECOORDINATE0 = 2;
  11031. VertexMesh.MESH_NORMAL0 = 3;
  11032. VertexMesh.MESH_TANGENT0 = 4;
  11033. VertexMesh.MESH_BLENDINDICES0 = 5;
  11034. VertexMesh.MESH_BLENDWEIGHT0 = 6;
  11035. VertexMesh.MESH_TEXTURECOORDINATE1 = 7;
  11036. VertexMesh.MESH_WORLDMATRIX_ROW0 = 8;
  11037. VertexMesh.MESH_WORLDMATRIX_ROW1 = 9;
  11038. VertexMesh.MESH_WORLDMATRIX_ROW2 = 10;
  11039. VertexMesh.MESH_WORLDMATRIX_ROW3 = 11;
  11040. VertexMesh.MESH_MVPMATRIX_ROW0 = 12;
  11041. VertexMesh.MESH_MVPMATRIX_ROW1 = 13;
  11042. VertexMesh.MESH_MVPMATRIX_ROW2 = 14;
  11043. VertexMesh.MESH_MVPMATRIX_ROW3 = 15;
  11044. VertexMesh.MESH_SIMPLEANIMATOR = 7;
  11045. VertexMesh._vertexDeclarationMap = {};
  11046. class SkyMesh {
  11047. constructor() {
  11048. }
  11049. _render(state) {
  11050. }
  11051. }
  11052. class SkyBox extends SkyMesh {
  11053. constructor() {
  11054. super();
  11055. var gl = Laya.LayaGL.instance;
  11056. var halfHeight = 1.0;
  11057. var halfWidth = 1.0;
  11058. var halfDepth = 1.0;
  11059. var vertices = new Float32Array([-halfDepth, halfHeight, -halfWidth, halfDepth, halfHeight, -halfWidth, halfDepth, halfHeight, halfWidth, -halfDepth, halfHeight, halfWidth,
  11060. -halfDepth, -halfHeight, -halfWidth, halfDepth, -halfHeight, -halfWidth, halfDepth, -halfHeight, halfWidth, -halfDepth, -halfHeight, halfWidth]);
  11061. var indices = new Uint8Array([
  11062. 0, 1, 2, 2, 3, 0,
  11063. 4, 7, 6, 6, 5, 4,
  11064. 0, 3, 7, 7, 4, 0,
  11065. 1, 5, 6, 6, 2, 1,
  11066. 3, 2, 6, 6, 7, 3,
  11067. 0, 4, 5, 5, 1, 0
  11068. ]);
  11069. var verDec = VertexMesh.getVertexDeclaration("POSITION");
  11070. this._vertexBuffer = new VertexBuffer3D(verDec.vertexStride * 8, gl.STATIC_DRAW, false);
  11071. this._vertexBuffer.vertexDeclaration = verDec;
  11072. this._indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt8, 36, gl.STATIC_DRAW, false);
  11073. this._vertexBuffer.setData(vertices.buffer);
  11074. this._indexBuffer.setData(indices);
  11075. var bufferState = new BufferState();
  11076. bufferState.bind();
  11077. bufferState.applyVertexBuffer(this._vertexBuffer);
  11078. bufferState.applyIndexBuffer(this._indexBuffer);
  11079. bufferState.unBind();
  11080. this._bufferState = bufferState;
  11081. }
  11082. static __init__() {
  11083. SkyBox.instance = new SkyBox();
  11084. }
  11085. _render(state) {
  11086. var gl = Laya.LayaGL.instance;
  11087. gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_BYTE, 0);
  11088. Laya.Stat.trianglesFaces += 12;
  11089. Laya.Stat.renderBatches++;
  11090. }
  11091. }
  11092. class SkyRenderer {
  11093. constructor() {
  11094. this._mesh = SkyBox.instance;
  11095. }
  11096. get material() {
  11097. return this._material;
  11098. }
  11099. set material(value) {
  11100. if (this._material !== value) {
  11101. (this._material) && (this._material._removeReference());
  11102. (value) && (value._addReference());
  11103. this._material = value;
  11104. }
  11105. }
  11106. get mesh() {
  11107. return this._mesh;
  11108. }
  11109. set mesh(value) {
  11110. if (this._mesh !== value) {
  11111. this._mesh = value;
  11112. }
  11113. }
  11114. _isAvailable() {
  11115. return this._material && this._mesh ? true : false;
  11116. }
  11117. _render(context) {
  11118. if (this._material && this._mesh) {
  11119. var gl = Laya.LayaGL.instance;
  11120. var scene = context.scene;
  11121. var cameraShaderValue = context.cameraShaderValue;
  11122. var camera = context.camera;
  11123. var noteValue = ShaderData._SET_RUNTIME_VALUE_MODE_REFERENCE_;
  11124. Laya.ILaya.Render.supportWebGLPlusRendering && ShaderData.setRuntimeValueMode(false);
  11125. Laya.WebGLContext.setCullFace(gl, false);
  11126. Laya.WebGLContext.setDepthFunc(gl, gl.LEQUAL);
  11127. Laya.WebGLContext.setDepthMask(gl, false);
  11128. var comDef = SkyRenderer._compileDefine;
  11129. this._material._shaderValues._defineDatas.cloneTo(comDef);
  11130. var shader = context.shader = this._material._shader.getSubShaderAt(0)._passes[0].withCompile(comDef);
  11131. var switchShader = shader.bind();
  11132. var switchShaderLoop = (Laya.Stat.loopCount !== shader._uploadMark);
  11133. var uploadScene = (shader._uploadScene !== scene) || switchShaderLoop;
  11134. if (uploadScene || switchShader) {
  11135. shader.uploadUniforms(shader._sceneUniformParamsMap, scene._shaderValues, uploadScene);
  11136. shader._uploadScene = scene;
  11137. }
  11138. var renderTex = camera._getRenderTexture();
  11139. var uploadCamera = (shader._uploadCameraShaderValue !== cameraShaderValue) || switchShaderLoop;
  11140. if (uploadCamera || switchShader) {
  11141. var viewMatrix = SkyRenderer._tempMatrix0;
  11142. var projectionMatrix = SkyRenderer._tempMatrix1;
  11143. camera.viewMatrix.cloneTo(viewMatrix);
  11144. camera.projectionMatrix.cloneTo(projectionMatrix);
  11145. viewMatrix.setTranslationVector(Vector3._ZERO);
  11146. if (camera.orthographic)
  11147. Matrix4x4.createPerspective(camera.fieldOfView, camera.aspectRatio, camera.nearPlane, camera.farPlane, projectionMatrix);
  11148. var epsilon = 1e-6;
  11149. var yScale = 1.0 / Math.tan(3.1416 * camera.fieldOfView / 180 * 0.5);
  11150. projectionMatrix.elements[0] = yScale / camera.aspectRatio;
  11151. projectionMatrix.elements[5] = yScale;
  11152. projectionMatrix.elements[10] = epsilon - 1.0;
  11153. projectionMatrix.elements[11] = -1.0;
  11154. projectionMatrix.elements[14] = -0;
  11155. camera._applyViewProject(context, viewMatrix, projectionMatrix);
  11156. shader.uploadUniforms(shader._cameraUniformParamsMap, cameraShaderValue, uploadCamera);
  11157. shader._uploadCameraShaderValue = cameraShaderValue;
  11158. }
  11159. var uploadMaterial = (shader._uploadMaterial !== this._material) || switchShaderLoop;
  11160. if (uploadMaterial || switchShader) {
  11161. shader.uploadUniforms(shader._materialUniformParamsMap, this._material._shaderValues, uploadMaterial);
  11162. shader._uploadMaterial = this._material;
  11163. }
  11164. this._mesh._bufferState.bind();
  11165. this._mesh._render(context);
  11166. Laya.ILaya.Render.supportWebGLPlusRendering && ShaderData.setRuntimeValueMode(noteValue);
  11167. Laya.WebGLContext.setDepthFunc(gl, gl.LESS);
  11168. Laya.WebGLContext.setDepthMask(gl, true);
  11169. camera._applyViewProject(context, camera.viewMatrix, camera.projectionMatrix);
  11170. }
  11171. }
  11172. destroy() {
  11173. if (this._material) {
  11174. this._material._removeReference();
  11175. this._material = null;
  11176. }
  11177. }
  11178. }
  11179. SkyRenderer._tempMatrix0 = new Matrix4x4();
  11180. SkyRenderer._tempMatrix1 = new Matrix4x4();
  11181. SkyRenderer._compileDefine = new DefineDatas();
  11182. class BaseCamera extends Sprite3D {
  11183. constructor(nearPlane = 0.3, farPlane = 1000) {
  11184. super();
  11185. this._skyRenderer = new SkyRenderer();
  11186. this._forward = new Vector3();
  11187. this._up = new Vector3();
  11188. this.clearColor = new Vector4(100 / 255, 149 / 255, 237 / 255, 255 / 255);
  11189. this._shaderValues = new ShaderData(null);
  11190. this._fieldOfView = 60;
  11191. this._useUserProjectionMatrix = false;
  11192. this._orthographic = false;
  11193. this._orthographicVerticalSize = 10;
  11194. this.renderingOrder = 0;
  11195. this._nearPlane = nearPlane;
  11196. this._farPlane = farPlane;
  11197. this.cullingMask = 2147483647;
  11198. this.useOcclusionCulling = true;
  11199. }
  11200. get skyRenderer() {
  11201. return this._skyRenderer;
  11202. }
  11203. get fieldOfView() {
  11204. return this._fieldOfView;
  11205. }
  11206. set fieldOfView(value) {
  11207. this._fieldOfView = value;
  11208. this._calculateProjectionMatrix();
  11209. }
  11210. get nearPlane() {
  11211. return this._nearPlane;
  11212. }
  11213. set nearPlane(value) {
  11214. this._nearPlane = value;
  11215. this._calculateProjectionMatrix();
  11216. }
  11217. get farPlane() {
  11218. return this._farPlane;
  11219. }
  11220. set farPlane(vaule) {
  11221. this._farPlane = vaule;
  11222. this._calculateProjectionMatrix();
  11223. }
  11224. get orthographic() {
  11225. return this._orthographic;
  11226. }
  11227. set orthographic(vaule) {
  11228. this._orthographic = vaule;
  11229. this._calculateProjectionMatrix();
  11230. }
  11231. get orthographicVerticalSize() {
  11232. return this._orthographicVerticalSize;
  11233. }
  11234. set orthographicVerticalSize(vaule) {
  11235. this._orthographicVerticalSize = vaule;
  11236. this._calculateProjectionMatrix();
  11237. }
  11238. get renderingOrder() {
  11239. return this._renderingOrder;
  11240. }
  11241. set renderingOrder(value) {
  11242. this._renderingOrder = value;
  11243. this._sortCamerasByRenderingOrder();
  11244. }
  11245. _sortCamerasByRenderingOrder() {
  11246. if (this.displayedInStage) {
  11247. var cameraPool = this.scene._cameraPool;
  11248. var n = cameraPool.length - 1;
  11249. for (var i = 0; i < n; i++) {
  11250. if (cameraPool[i].renderingOrder > cameraPool[n].renderingOrder) {
  11251. var tempCamera = cameraPool[i];
  11252. cameraPool[i] = cameraPool[n];
  11253. cameraPool[n] = tempCamera;
  11254. }
  11255. }
  11256. }
  11257. }
  11258. _calculateProjectionMatrix() {
  11259. }
  11260. _onScreenSizeChanged() {
  11261. this._calculateProjectionMatrix();
  11262. }
  11263. _prepareCameraToRender() {
  11264. var cameraSV = this._shaderValues;
  11265. this.transform.getForward(this._forward);
  11266. this.transform.getUp(this._up);
  11267. cameraSV.setVector3(BaseCamera.CAMERAPOS, this.transform.position);
  11268. cameraSV.setVector3(BaseCamera.CAMERADIRECTION, this._forward);
  11269. cameraSV.setVector3(BaseCamera.CAMERAUP, this._up);
  11270. }
  11271. render(shader = null, replacementTag = null) {
  11272. }
  11273. addLayer(layer) {
  11274. this.cullingMask |= Math.pow(2, layer);
  11275. }
  11276. removeLayer(layer) {
  11277. this.cullingMask &= ~Math.pow(2, layer);
  11278. }
  11279. addAllLayers() {
  11280. this.cullingMask = 2147483647;
  11281. }
  11282. removeAllLayers() {
  11283. this.cullingMask = 0;
  11284. }
  11285. resetProjectionMatrix() {
  11286. this._useUserProjectionMatrix = false;
  11287. this._calculateProjectionMatrix();
  11288. }
  11289. _onActive() {
  11290. this._scene._addCamera(this);
  11291. super._onActive();
  11292. }
  11293. _onInActive() {
  11294. this._scene._removeCamera(this);
  11295. super._onInActive();
  11296. }
  11297. _parse(data, spriteMap) {
  11298. super._parse(data, spriteMap);
  11299. this.orthographic = data.orthographic;
  11300. (data.orthographicVerticalSize !== undefined) && (this.orthographicVerticalSize = data.orthographicVerticalSize);
  11301. (data.fieldOfView !== undefined) && (this.fieldOfView = data.fieldOfView);
  11302. this.nearPlane = data.nearPlane;
  11303. this.farPlane = data.farPlane;
  11304. var color = data.clearColor;
  11305. this.clearColor = new Vector4(color[0], color[1], color[2], color[3]);
  11306. var skyboxMaterial = data.skyboxMaterial;
  11307. if (skyboxMaterial) {
  11308. this._skyRenderer.material = Laya.Loader.getRes(skyboxMaterial.path);
  11309. }
  11310. }
  11311. destroy(destroyChild = true) {
  11312. this._skyRenderer.destroy();
  11313. this._skyRenderer = null;
  11314. Laya.Laya.stage.off(Laya.Event.RESIZE, this, this._onScreenSizeChanged);
  11315. super.destroy(destroyChild);
  11316. }
  11317. _create() {
  11318. return new BaseCamera();
  11319. }
  11320. }
  11321. BaseCamera._tempMatrix4x40 = new Matrix4x4();
  11322. BaseCamera.CAMERAPOS = Shader3D.propertyNameToID("u_CameraPos");
  11323. BaseCamera.VIEWMATRIX = Shader3D.propertyNameToID("u_View");
  11324. BaseCamera.PROJECTMATRIX = Shader3D.propertyNameToID("u_Projection");
  11325. BaseCamera.VIEWPROJECTMATRIX = Shader3D.propertyNameToID("u_ViewProjection");
  11326. BaseCamera.CAMERADIRECTION = Shader3D.propertyNameToID("u_CameraDirection");
  11327. BaseCamera.CAMERAUP = Shader3D.propertyNameToID("u_CameraUp");
  11328. BaseCamera.VIEWPORT = Shader3D.propertyNameToID("u_Viewport");
  11329. BaseCamera.PROJECTION_PARAMS = Shader3D.propertyNameToID("u_ProjectionParams");
  11330. BaseCamera.DEPTHTEXTURE = Shader3D.propertyNameToID("u_CameraDepthTexture");
  11331. BaseCamera.DEPTHNORMALSTEXTURE = Shader3D.propertyNameToID("u_CameraDepthNormalsTexture");
  11332. BaseCamera.DEPTHZBUFFERPARAMS = Shader3D.propertyNameToID("u_ZBufferParams");
  11333. BaseCamera.SHADERDEFINE_DEPTH = Shader3D.getDefineByName("DEPTHMAP");
  11334. BaseCamera.SHADERDEFINE_DEPTHNORMALS = Shader3D.getDefineByName("DEPTHNORMALSMAP");
  11335. BaseCamera.RENDERINGTYPE_DEFERREDLIGHTING = "DEFERREDLIGHTING";
  11336. BaseCamera.RENDERINGTYPE_FORWARDRENDERING = "FORWARDRENDERING";
  11337. BaseCamera._invertYScaleMatrix = new Matrix4x4(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
  11338. BaseCamera._invertYProjectionMatrix = new Matrix4x4();
  11339. BaseCamera._invertYProjectionViewMatrix = new Matrix4x4();
  11340. BaseCamera.CLEARFLAG_SOLIDCOLOR = 0;
  11341. BaseCamera.CLEARFLAG_SKY = 1;
  11342. BaseCamera.CLEARFLAG_DEPTHONLY = 2;
  11343. BaseCamera.CLEARFLAG_NONE = 3;
  11344. (function (ShadowMode) {
  11345. ShadowMode[ShadowMode["None"] = 0] = "None";
  11346. ShadowMode[ShadowMode["Hard"] = 1] = "Hard";
  11347. ShadowMode[ShadowMode["SoftLow"] = 2] = "SoftLow";
  11348. ShadowMode[ShadowMode["SoftHigh"] = 3] = "SoftHigh";
  11349. })(exports.ShadowMode || (exports.ShadowMode = {}));
  11350. class Scene3DShaderDeclaration {
  11351. }
  11352. (function (LightType) {
  11353. LightType[LightType["Directional"] = 0] = "Directional";
  11354. LightType[LightType["Spot"] = 1] = "Spot";
  11355. LightType[LightType["Point"] = 2] = "Point";
  11356. })(exports.LightType || (exports.LightType = {}));
  11357. class LightSprite extends Sprite3D {
  11358. constructor() {
  11359. super();
  11360. this._shadowMode = exports.ShadowMode.None;
  11361. this._isAlternate = false;
  11362. this._shadowResolution = 2048;
  11363. this._shadowDistance = 50.0;
  11364. this._shadowDepthBias = 1.0;
  11365. this._shadowNormalBias = 1.0;
  11366. this._shadowNearPlane = 0.1;
  11367. this._shadowStrength = 1.0;
  11368. this._lightWoldMatrix = new Matrix4x4();
  11369. this._intensity = 1.0;
  11370. this._intensityColor = new Vector3();
  11371. this.color = new Vector3(1.0, 1.0, 1.0);
  11372. this._lightmapBakedType = LightSprite.LIGHTMAPBAKEDTYPE_REALTIME;
  11373. }
  11374. get intensity() {
  11375. return this._intensity;
  11376. }
  11377. set intensity(value) {
  11378. this._intensity = value;
  11379. }
  11380. get shadowMode() {
  11381. return this._shadowMode;
  11382. }
  11383. set shadowMode(value) {
  11384. this._shadowMode = value;
  11385. }
  11386. get shadowDistance() {
  11387. return this._shadowDistance;
  11388. }
  11389. set shadowDistance(value) {
  11390. this._shadowDistance = value;
  11391. }
  11392. get shadowResolution() {
  11393. return this._shadowResolution;
  11394. }
  11395. set shadowResolution(value) {
  11396. this._shadowResolution = value;
  11397. }
  11398. get shadowDepthBias() {
  11399. return this._shadowDepthBias;
  11400. }
  11401. set shadowDepthBias(value) {
  11402. this._shadowDepthBias = value;
  11403. }
  11404. get shadowNormalBias() {
  11405. return this._shadowNormalBias;
  11406. }
  11407. set shadowNormalBias(value) {
  11408. this._shadowNormalBias = value;
  11409. }
  11410. get shadowStrength() {
  11411. return this._shadowStrength;
  11412. }
  11413. set shadowStrength(value) {
  11414. this._shadowStrength = value;
  11415. }
  11416. get shadowNearPlane() {
  11417. return this._shadowNearPlane;
  11418. }
  11419. set shadowNearPlane(value) {
  11420. this._shadowNearPlane = value;
  11421. }
  11422. get lightmapBakedType() {
  11423. return this._lightmapBakedType;
  11424. }
  11425. set lightmapBakedType(value) {
  11426. if (this._lightmapBakedType !== value) {
  11427. this._lightmapBakedType = value;
  11428. if (this.activeInHierarchy) {
  11429. if (value !== LightSprite.LIGHTMAPBAKEDTYPE_BAKED)
  11430. this._addToScene();
  11431. else
  11432. this._removeFromScene();
  11433. }
  11434. }
  11435. }
  11436. get lightWorldMatrix() {
  11437. var position = this.transform.position;
  11438. var quaterian = this.transform.rotation;
  11439. Matrix4x4.createAffineTransformation(position, quaterian, Vector3._ONE, this._lightWoldMatrix);
  11440. return this._lightWoldMatrix;
  11441. }
  11442. _parse(data, spriteMap) {
  11443. super._parse(data, spriteMap);
  11444. var colorData = data.color;
  11445. this.color.fromArray(colorData);
  11446. this.intensity = data.intensity;
  11447. this.lightmapBakedType = data.lightmapBakedType;
  11448. }
  11449. _cloneTo(destObject, rootSprite, dstSprite) {
  11450. super._cloneTo(destObject, rootSprite, dstSprite);
  11451. var spriteLight = destObject;
  11452. spriteLight.color = this.color.clone();
  11453. spriteLight.intensity = this.intensity;
  11454. spriteLight.lightmapBakedType = this.lightmapBakedType;
  11455. }
  11456. _addToScene() {
  11457. var scene = this._scene;
  11458. var maxLightCount = Config3D._config.maxLightCount;
  11459. if (scene._lightCount < maxLightCount) {
  11460. scene._lightCount++;
  11461. this._addToLightQueue();
  11462. this._isAlternate = false;
  11463. }
  11464. else {
  11465. scene._alternateLights.add(this);
  11466. this._isAlternate = true;
  11467. console.warn("LightSprite:light count has large than maxLightCount,the latest added light will be ignore.");
  11468. }
  11469. }
  11470. _removeFromScene() {
  11471. var scene = this._scene;
  11472. if (this._isAlternate) {
  11473. scene._alternateLights.remove(this);
  11474. }
  11475. else {
  11476. scene._lightCount--;
  11477. this._removeFromLightQueue();
  11478. if (scene._alternateLights._length > 0) {
  11479. var alternateLight = scene._alternateLights.shift();
  11480. alternateLight._addToLightQueue();
  11481. alternateLight._isAlternate = false;
  11482. scene._lightCount++;
  11483. }
  11484. }
  11485. }
  11486. _addToLightQueue() {
  11487. }
  11488. _removeFromLightQueue() {
  11489. }
  11490. _onActive() {
  11491. super._onActive();
  11492. (this.lightmapBakedType !== LightSprite.LIGHTMAPBAKEDTYPE_BAKED) && (this._addToScene());
  11493. }
  11494. _onInActive() {
  11495. super._onInActive();
  11496. (this.lightmapBakedType !== LightSprite.LIGHTMAPBAKEDTYPE_BAKED) && (this._removeFromScene());
  11497. }
  11498. _create() {
  11499. return new LightSprite();
  11500. }
  11501. get diffuseColor() {
  11502. console.log("LightSprite: discard property,please use color property instead.");
  11503. return this.color;
  11504. }
  11505. set diffuseColor(value) {
  11506. console.log("LightSprite: discard property,please use color property instead.");
  11507. this.color = value;
  11508. }
  11509. }
  11510. LightSprite.LIGHTMAPBAKEDTYPE_REALTIME = 0;
  11511. LightSprite.LIGHTMAPBAKEDTYPE_MIXED = 1;
  11512. LightSprite.LIGHTMAPBAKEDTYPE_BAKED = 2;
  11513. (function (ShadowCascadesMode) {
  11514. ShadowCascadesMode[ShadowCascadesMode["NoCascades"] = 0] = "NoCascades";
  11515. ShadowCascadesMode[ShadowCascadesMode["TwoCascades"] = 1] = "TwoCascades";
  11516. ShadowCascadesMode[ShadowCascadesMode["FourCascades"] = 2] = "FourCascades";
  11517. })(exports.ShadowCascadesMode || (exports.ShadowCascadesMode = {}));
  11518. var FrustumFace;
  11519. (function (FrustumFace) {
  11520. FrustumFace[FrustumFace["Near"] = 0] = "Near";
  11521. FrustumFace[FrustumFace["Far"] = 1] = "Far";
  11522. FrustumFace[FrustumFace["Left"] = 2] = "Left";
  11523. FrustumFace[FrustumFace["Right"] = 3] = "Right";
  11524. FrustumFace[FrustumFace["Bottom"] = 4] = "Bottom";
  11525. FrustumFace[FrustumFace["Top"] = 5] = "Top";
  11526. })(FrustumFace || (FrustumFace = {}));
  11527. class ShadowUtils {
  11528. static supportShadow() {
  11529. return Laya.LayaGL.layaGPUInstance._isWebGL2 || Laya.SystemUtils.supportRenderTextureFormat(Laya.RenderTextureFormat.Depth);
  11530. }
  11531. static init() {
  11532. if (Laya.LayaGL.layaGPUInstance._isWebGL2)
  11533. ShadowUtils._shadowTextureFormat = Laya.RenderTextureFormat.ShadowMap;
  11534. else
  11535. ShadowUtils._shadowTextureFormat = Laya.RenderTextureFormat.Depth;
  11536. }
  11537. static getTemporaryShadowTexture(witdh, height, depthFormat) {
  11538. var shadowMap = RenderTexture.createFromPool(witdh, height, ShadowUtils._shadowTextureFormat, depthFormat);
  11539. shadowMap.filterMode = Laya.FilterMode.Bilinear;
  11540. shadowMap.wrapModeU = Laya.WarpMode.Clamp;
  11541. shadowMap.wrapModeV = Laya.WarpMode.Clamp;
  11542. return shadowMap;
  11543. }
  11544. static getShadowBias(light, shadowProjectionMatrix, shadowResolution, out) {
  11545. var frustumSize;
  11546. if (light._lightType == exports.LightType.Directional) {
  11547. frustumSize = 2.0 / shadowProjectionMatrix.elements[0];
  11548. }
  11549. else if (light._lightType == exports.LightType.Spot) {
  11550. frustumSize = Math.tan(light.spotAngle * 0.5 * MathUtils3D.Deg2Rad) * light.range;
  11551. }
  11552. else {
  11553. console.warn("ShadowUtils:Only spot and directional shadow casters are supported now.");
  11554. frustumSize = 0.0;
  11555. }
  11556. var texelSize = frustumSize / shadowResolution;
  11557. var depthBias = -light._shadowDepthBias * texelSize;
  11558. var normalBias = -light._shadowNormalBias * texelSize;
  11559. if (light.shadowMode == exports.ShadowMode.SoftHigh) {
  11560. const kernelRadius = 2.5;
  11561. depthBias *= kernelRadius;
  11562. normalBias *= kernelRadius;
  11563. }
  11564. out.setValue(depthBias, normalBias, 0.0, 0.0);
  11565. }
  11566. static getCameraFrustumPlanes(cameraViewProjectMatrix, frustumPlanes) {
  11567. BoundFrustum.getPlanesFromMatrix(cameraViewProjectMatrix, frustumPlanes[FrustumFace.Near], frustumPlanes[FrustumFace.Far], frustumPlanes[FrustumFace.Left], frustumPlanes[FrustumFace.Right], frustumPlanes[FrustumFace.Top], frustumPlanes[FrustumFace.Bottom]);
  11568. }
  11569. static getFarWithRadius(radius, denominator) {
  11570. return Math.sqrt(radius * radius / denominator);
  11571. }
  11572. static getCascadesSplitDistance(twoSplitRatio, fourSplitRatio, cameraNear, shadowFar, fov, aspectRatio, cascadesMode, out) {
  11573. out[0] = cameraNear;
  11574. var range = shadowFar - cameraNear;
  11575. var tFov = Math.tan(fov * 0.5);
  11576. var denominator = 1.0 + tFov * tFov * (aspectRatio * aspectRatio + 1.0);
  11577. switch (cascadesMode) {
  11578. case exports.ShadowCascadesMode.NoCascades:
  11579. out[1] = ShadowUtils.getFarWithRadius(shadowFar, denominator);
  11580. break;
  11581. case exports.ShadowCascadesMode.TwoCascades:
  11582. out[1] = ShadowUtils.getFarWithRadius(cameraNear + range * twoSplitRatio, denominator);
  11583. out[2] = ShadowUtils.getFarWithRadius(shadowFar, denominator);
  11584. break;
  11585. case exports.ShadowCascadesMode.FourCascades:
  11586. out[1] = ShadowUtils.getFarWithRadius(cameraNear + range * fourSplitRatio.x, denominator);
  11587. out[2] = ShadowUtils.getFarWithRadius(cameraNear + range * fourSplitRatio.y, denominator);
  11588. out[3] = ShadowUtils.getFarWithRadius(cameraNear + range * fourSplitRatio.z, denominator);
  11589. out[4] = ShadowUtils.getFarWithRadius(shadowFar, denominator);
  11590. break;
  11591. }
  11592. }
  11593. static applySliceTransform(shadowSliceData, atlasWidth, atlasHeight, cascadeIndex, outShadowMatrices) {
  11594. var sliceE = ShadowUtils._tempMatrix0.elements;
  11595. var oneOverAtlasWidth = 1.0 / atlasWidth;
  11596. var oneOverAtlasHeight = 1.0 / atlasHeight;
  11597. sliceE[0] = shadowSliceData.resolution * oneOverAtlasWidth;
  11598. sliceE[5] = shadowSliceData.resolution * oneOverAtlasHeight;
  11599. sliceE[12] = shadowSliceData.offsetX * oneOverAtlasWidth;
  11600. sliceE[13] = shadowSliceData.offsetY * oneOverAtlasHeight;
  11601. sliceE[1] = sliceE[2] = sliceE[2] = sliceE[4] = sliceE[6] = sliceE[7] = sliceE[8] = sliceE[9] = sliceE[11] = sliceE[14] = 0;
  11602. sliceE[10] = sliceE[15] = 1;
  11603. var offset = cascadeIndex * 16;
  11604. Utils3D._mulMatrixArray(sliceE, outShadowMatrices, offset, outShadowMatrices, offset);
  11605. }
  11606. static getDirectionLightShadowCullPlanes(cameraFrustumPlanes, cascadeIndex, splitDistance, cameraNear, direction, shadowSliceData) {
  11607. var frustumCorners = ShadowUtils._frustumCorners;
  11608. var backPlaneFaces = ShadowUtils._backPlaneFaces;
  11609. var planeNeighbors = ShadowUtils._frustumPlaneNeighbors;
  11610. var twoPlaneCorners = ShadowUtils._frustumTwoPlaneCorners;
  11611. var edgePlanePoint2 = ShadowUtils._edgePlanePoint2;
  11612. var out = shadowSliceData.cullPlanes;
  11613. var near = cameraFrustumPlanes[FrustumFace.Near], far = cameraFrustumPlanes[FrustumFace.Far];
  11614. var left = cameraFrustumPlanes[FrustumFace.Left], right = cameraFrustumPlanes[FrustumFace.Right];
  11615. var bottom = cameraFrustumPlanes[FrustumFace.Bottom], top = cameraFrustumPlanes[FrustumFace.Top];
  11616. var splitNearDistance = splitDistance[cascadeIndex] - cameraNear;
  11617. var splitNear = ShadowUtils._adjustNearPlane;
  11618. var splitFar = ShadowUtils._adjustFarPlane;
  11619. near.normal.cloneTo(splitNear.normal);
  11620. far.normal.cloneTo(splitFar.normal);
  11621. splitNear.distance = near.distance - splitNearDistance;
  11622. splitFar.distance = Math.min(-near.distance + shadowSliceData.sphereCenterZ + shadowSliceData.splitBoundSphere.radius, far.distance);
  11623. BoundFrustum.get3PlaneInterPoint(splitNear, bottom, right, frustumCorners[exports.FrustumCorner.nearBottomRight]);
  11624. BoundFrustum.get3PlaneInterPoint(splitNear, top, right, frustumCorners[exports.FrustumCorner.nearTopRight]);
  11625. BoundFrustum.get3PlaneInterPoint(splitNear, top, left, frustumCorners[exports.FrustumCorner.nearTopLeft]);
  11626. BoundFrustum.get3PlaneInterPoint(splitNear, bottom, left, frustumCorners[exports.FrustumCorner.nearBottomLeft]);
  11627. BoundFrustum.get3PlaneInterPoint(splitFar, bottom, right, frustumCorners[exports.FrustumCorner.FarBottomRight]);
  11628. BoundFrustum.get3PlaneInterPoint(splitFar, top, right, frustumCorners[exports.FrustumCorner.FarTopRight]);
  11629. BoundFrustum.get3PlaneInterPoint(splitFar, top, left, frustumCorners[exports.FrustumCorner.FarTopLeft]);
  11630. BoundFrustum.get3PlaneInterPoint(splitFar, bottom, left, frustumCorners[exports.FrustumCorner.FarBottomLeft]);
  11631. var backIndex = 0;
  11632. for (var i = 0; i < 6; i++) {
  11633. var plane;
  11634. switch (i) {
  11635. case FrustumFace.Near:
  11636. plane = splitNear;
  11637. break;
  11638. case FrustumFace.Far:
  11639. plane = splitFar;
  11640. break;
  11641. default:
  11642. plane = cameraFrustumPlanes[i];
  11643. break;
  11644. }
  11645. if (Vector3.dot(plane.normal, direction) < 0.0) {
  11646. plane.cloneTo(out[backIndex]);
  11647. backPlaneFaces[backIndex] = i;
  11648. backIndex++;
  11649. }
  11650. }
  11651. var edgeIndex = backIndex;
  11652. for (var i = 0; i < backIndex; i++) {
  11653. var backFace = backPlaneFaces[i];
  11654. var neighborFaces = planeNeighbors[backFace];
  11655. for (var j = 0; j < 4; j++) {
  11656. var neighborFace = neighborFaces[j];
  11657. var notBackFace = true;
  11658. for (var k = 0; k < backIndex; k++)
  11659. if (neighborFace == backPlaneFaces[k]) {
  11660. notBackFace = false;
  11661. break;
  11662. }
  11663. if (notBackFace) {
  11664. var corners = twoPlaneCorners[backFace][neighborFace];
  11665. var point0 = frustumCorners[corners[0]];
  11666. var point1 = frustumCorners[corners[1]];
  11667. Vector3.add(point0, direction, edgePlanePoint2);
  11668. Plane.createPlaneBy3P(point0, point1, edgePlanePoint2, out[edgeIndex++]);
  11669. }
  11670. }
  11671. }
  11672. shadowSliceData.cullPlaneCount = edgeIndex;
  11673. }
  11674. static getBoundSphereByFrustum(near, far, fov, aspectRatio, cameraPos, forward, outBoundSphere) {
  11675. var centerZ;
  11676. var radius;
  11677. var k = Math.sqrt(1.0 + aspectRatio * aspectRatio) * Math.tan(fov / 2.0);
  11678. var k2 = k * k;
  11679. var farSNear = far - near;
  11680. var farANear = far + near;
  11681. if (k2 > farSNear / farANear) {
  11682. centerZ = far;
  11683. radius = far * k;
  11684. }
  11685. else {
  11686. centerZ = 0.5 * farANear * (1 + k2);
  11687. radius = 0.5 * Math.sqrt(farSNear * farSNear + 2.0 * (far * far + near * near) * k2 + farANear * farANear * k2 * k2);
  11688. }
  11689. var center = outBoundSphere.center;
  11690. outBoundSphere.radius = radius;
  11691. Vector3.scale(forward, centerZ, center);
  11692. Vector3.add(cameraPos, center, center);
  11693. return centerZ;
  11694. }
  11695. static getMaxTileResolutionInAtlas(atlasWidth, atlasHeight, tileCount) {
  11696. var resolution = Math.min(atlasWidth, atlasHeight);
  11697. var currentTileCount = Math.floor(atlasWidth / resolution) * Math.floor(atlasHeight / resolution);
  11698. while (currentTileCount < tileCount) {
  11699. resolution = Math.floor(resolution >> 1);
  11700. currentTileCount = Math.floor(atlasWidth / resolution) * Math.floor(atlasHeight / resolution);
  11701. }
  11702. return resolution;
  11703. }
  11704. static getDirectionalLightMatrices(lightUp, lightSide, lightForward, cascadeIndex, nearPlane, shadowResolution, shadowSliceData, shadowMatrices) {
  11705. var boundSphere = shadowSliceData.splitBoundSphere;
  11706. var center = boundSphere.center;
  11707. var radius = boundSphere.radius;
  11708. var halfShadowResolution = shadowResolution / 2;
  11709. var borderRadius = radius * halfShadowResolution / (halfShadowResolution - ShadowUtils.atlasBorderSize);
  11710. var borderDiam = borderRadius * 2.0;
  11711. var sizeUnit = shadowResolution / borderDiam;
  11712. var radiusUnit = borderDiam / shadowResolution;
  11713. var upLen = Math.ceil(Vector3.dot(center, lightUp) * sizeUnit) * radiusUnit;
  11714. var sideLen = Math.ceil(Vector3.dot(center, lightSide) * sizeUnit) * radiusUnit;
  11715. var forwardLen = Vector3.dot(center, lightForward);
  11716. center.x = lightUp.x * upLen + lightSide.x * sideLen + lightForward.x * forwardLen;
  11717. center.y = lightUp.y * upLen + lightSide.y * sideLen + lightForward.y * forwardLen;
  11718. center.z = lightUp.z * upLen + lightSide.z * sideLen + lightForward.z * forwardLen;
  11719. var origin = shadowSliceData.position;
  11720. var viewMatrix = shadowSliceData.viewMatrix;
  11721. var projectMatrix = shadowSliceData.projectionMatrix;
  11722. var viewProjectMatrix = shadowSliceData.viewProjectMatrix;
  11723. shadowSliceData.resolution = shadowResolution;
  11724. shadowSliceData.offsetX = (cascadeIndex % 2) * shadowResolution;
  11725. shadowSliceData.offsetY = Math.floor(cascadeIndex / 2) * shadowResolution;
  11726. Vector3.scale(lightForward, radius + nearPlane, origin);
  11727. Vector3.subtract(center, origin, origin);
  11728. Matrix4x4.createLookAt(origin, center, lightUp, viewMatrix);
  11729. Matrix4x4.createOrthoOffCenter(-borderRadius, borderRadius, -borderRadius, borderRadius, 0.0, radius * 2.0 + nearPlane, projectMatrix);
  11730. Matrix4x4.multiply(projectMatrix, viewMatrix, viewProjectMatrix);
  11731. Utils3D._mulMatrixArray(ShadowUtils._shadowMapScaleOffsetMatrix.elements, viewProjectMatrix.elements, 0, shadowMatrices, cascadeIndex * 16);
  11732. }
  11733. static getSpotLightShadowData(shadowSpotData, spotLight, resolution, shadowParams, shadowSpotMatrices, shadowMapSize) {
  11734. var out = shadowSpotData.position = spotLight.transform.position;
  11735. shadowSpotData.resolution = resolution;
  11736. shadowMapSize.setValue(1.0 / resolution, 1.0 / resolution, resolution, resolution);
  11737. shadowSpotData.offsetX = 0;
  11738. shadowSpotData.offsetY = 0;
  11739. var spotWorldMatrix = spotLight.lightWorldMatrix;
  11740. var viewMatrix = shadowSpotData.viewMatrix;
  11741. var projectMatrix = shadowSpotData.projectionMatrix;
  11742. var viewProjectMatrix = shadowSpotData.viewProjectMatrix;
  11743. var BoundFrustum = shadowSpotData.cameraCullInfo.boundFrustum;
  11744. spotWorldMatrix.invert(viewMatrix);
  11745. Matrix4x4.createPerspective(3.1416 * spotLight.spotAngle / 180.0, 1, 0.1, spotLight.range, projectMatrix);
  11746. shadowParams.y = spotLight.shadowStrength;
  11747. Matrix4x4.multiply(projectMatrix, viewMatrix, viewProjectMatrix);
  11748. BoundFrustum.matrix = viewProjectMatrix;
  11749. viewProjectMatrix.cloneTo(shadowSpotMatrices);
  11750. shadowSpotData.cameraCullInfo.position = out;
  11751. }
  11752. static prepareShadowReceiverShaderValues(light, shadowMapWidth, shadowMapHeight, shadowSliceDatas, cascadeCount, shadowMapSize, shadowParams, shadowMatrices, splitBoundSpheres) {
  11753. shadowMapSize.setValue(1.0 / shadowMapWidth, 1.0 / shadowMapHeight, shadowMapWidth, shadowMapHeight);
  11754. shadowParams.setValue(light._shadowStrength, 0.0, 0.0, 0.0);
  11755. if (cascadeCount > 1) {
  11756. const matrixFloatCount = 16;
  11757. for (var i = cascadeCount * matrixFloatCount, n = 4 * matrixFloatCount; i < n; i++)
  11758. shadowMatrices[i] = 0.0;
  11759. for (var i = 0; i < cascadeCount; i++) {
  11760. var boundSphere = shadowSliceDatas[i].splitBoundSphere;
  11761. var center = boundSphere.center;
  11762. var radius = boundSphere.radius;
  11763. var offset = i * 4;
  11764. splitBoundSpheres[offset] = center.x;
  11765. splitBoundSpheres[offset + 1] = center.y;
  11766. splitBoundSpheres[offset + 2] = center.z;
  11767. splitBoundSpheres[offset + 3] = radius * radius;
  11768. }
  11769. const sphereFloatCount = 4;
  11770. for (var i = cascadeCount * sphereFloatCount, n = 4 * sphereFloatCount; i < n; i++)
  11771. splitBoundSpheres[i] = 0.0;
  11772. }
  11773. }
  11774. }
  11775. ShadowUtils._tempMatrix0 = new Matrix4x4();
  11776. ShadowUtils._shadowMapScaleOffsetMatrix = new Matrix4x4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.0, 1.0);
  11777. ShadowUtils._frustumCorners = [new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3()];
  11778. ShadowUtils._adjustNearPlane = new Plane(new Vector3());
  11779. ShadowUtils._adjustFarPlane = new Plane(new Vector3());
  11780. ShadowUtils._backPlaneFaces = new Array(5);
  11781. ShadowUtils._edgePlanePoint2 = new Vector3();
  11782. ShadowUtils._frustumPlaneNeighbors = [
  11783. [FrustumFace.Left, FrustumFace.Right, FrustumFace.Top, FrustumFace.Bottom],
  11784. [FrustumFace.Left, FrustumFace.Right, FrustumFace.Top, FrustumFace.Bottom],
  11785. [FrustumFace.Near, FrustumFace.Far, FrustumFace.Top, FrustumFace.Bottom],
  11786. [FrustumFace.Near, FrustumFace.Far, FrustumFace.Top, FrustumFace.Bottom],
  11787. [FrustumFace.Near, FrustumFace.Far, FrustumFace.Left, FrustumFace.Right],
  11788. [FrustumFace.Near, FrustumFace.Far, FrustumFace.Left, FrustumFace.Right]
  11789. ];
  11790. ShadowUtils._frustumTwoPlaneCorners = [
  11791. [[exports.FrustumCorner.unknown, exports.FrustumCorner.unknown], [exports.FrustumCorner.unknown, exports.FrustumCorner.unknown], [exports.FrustumCorner.nearBottomLeft, exports.FrustumCorner.nearTopLeft], [exports.FrustumCorner.nearTopRight, exports.FrustumCorner.nearBottomRight], [exports.FrustumCorner.nearBottomRight, exports.FrustumCorner.nearBottomLeft], [exports.FrustumCorner.nearTopLeft, exports.FrustumCorner.nearTopRight]],
  11792. [[exports.FrustumCorner.unknown, exports.FrustumCorner.unknown], [exports.FrustumCorner.unknown, exports.FrustumCorner.unknown], [exports.FrustumCorner.FarTopLeft, exports.FrustumCorner.FarBottomLeft], [exports.FrustumCorner.FarBottomRight, exports.FrustumCorner.FarTopRight], [exports.FrustumCorner.FarBottomLeft, exports.FrustumCorner.FarBottomRight], [exports.FrustumCorner.FarTopRight, exports.FrustumCorner.FarTopLeft]],
  11793. [[exports.FrustumCorner.nearTopLeft, exports.FrustumCorner.nearBottomLeft], [exports.FrustumCorner.FarBottomLeft, exports.FrustumCorner.FarTopLeft], [exports.FrustumCorner.unknown, exports.FrustumCorner.unknown], [exports.FrustumCorner.unknown, exports.FrustumCorner.unknown], [exports.FrustumCorner.nearBottomLeft, exports.FrustumCorner.FarBottomLeft], [exports.FrustumCorner.FarTopLeft, exports.FrustumCorner.nearTopLeft]],
  11794. [[exports.FrustumCorner.nearBottomRight, exports.FrustumCorner.nearTopRight], [exports.FrustumCorner.FarTopRight, exports.FrustumCorner.FarBottomRight], [exports.FrustumCorner.unknown, exports.FrustumCorner.unknown], [exports.FrustumCorner.unknown, exports.FrustumCorner.unknown], [exports.FrustumCorner.FarBottomRight, exports.FrustumCorner.nearBottomRight], [exports.FrustumCorner.nearTopRight, exports.FrustumCorner.FarTopRight]],
  11795. [[exports.FrustumCorner.nearBottomLeft, exports.FrustumCorner.nearBottomRight], [exports.FrustumCorner.FarBottomRight, exports.FrustumCorner.FarBottomLeft], [exports.FrustumCorner.FarBottomLeft, exports.FrustumCorner.nearBottomLeft], [exports.FrustumCorner.nearBottomRight, exports.FrustumCorner.FarBottomRight], [exports.FrustumCorner.unknown, exports.FrustumCorner.unknown], [exports.FrustumCorner.unknown, exports.FrustumCorner.unknown]],
  11796. [[exports.FrustumCorner.nearTopRight, exports.FrustumCorner.nearTopLeft], [exports.FrustumCorner.FarTopLeft, exports.FrustumCorner.FarTopRight], [exports.FrustumCorner.nearTopLeft, exports.FrustumCorner.FarTopLeft], [exports.FrustumCorner.FarTopRight, exports.FrustumCorner.nearTopRight], [exports.FrustumCorner.unknown, exports.FrustumCorner.unknown], [exports.FrustumCorner.unknown, exports.FrustumCorner.unknown]]
  11797. ];
  11798. ShadowUtils.atlasBorderSize = 4.0;
  11799. (function (DepthTextureMode) {
  11800. DepthTextureMode[DepthTextureMode["None"] = 0] = "None";
  11801. DepthTextureMode[DepthTextureMode["Depth"] = 1] = "Depth";
  11802. DepthTextureMode[DepthTextureMode["DepthNormals"] = 2] = "DepthNormals";
  11803. DepthTextureMode[DepthTextureMode["MotionVectors"] = 4] = "MotionVectors";
  11804. })(exports.DepthTextureMode || (exports.DepthTextureMode = {}));
  11805. class DepthPass {
  11806. constructor() {
  11807. this._zBufferParams = new Vector4();
  11808. }
  11809. update(camera, depthType) {
  11810. this._viewPort = camera.viewport;
  11811. this._camera = camera;
  11812. switch (depthType) {
  11813. case exports.DepthTextureMode.Depth:
  11814. camera.depthTexture = this._depthTexture = RenderTexture.createFromPool(this._viewPort.width, this._viewPort.height, Laya.RenderTextureFormat.Depth, Laya.RenderTextureDepthFormat.DEPTH_16);
  11815. break;
  11816. case exports.DepthTextureMode.DepthNormals:
  11817. camera.depthNormalTexture = this._depthNormalsTexture = RenderTexture.createFromPool(this._viewPort.width, this._viewPort.height, Laya.RenderTextureFormat.R8G8B8A8, Laya.RenderTextureDepthFormat.DEPTH_16);
  11818. break;
  11819. case exports.DepthTextureMode.MotionVectors:
  11820. break;
  11821. default:
  11822. throw ("there is UnDefined type of DepthTextureMode");
  11823. }
  11824. }
  11825. render(context, depthType) {
  11826. var scene = context.scene;
  11827. switch (depthType) {
  11828. case exports.DepthTextureMode.Depth:
  11829. var shaderValues = scene._shaderValues;
  11830. context.pipelineMode = "ShadowCaster";
  11831. ShaderData.setRuntimeValueMode(false);
  11832. this._depthTexture._start();
  11833. shaderValues.setVector(DepthPass.DEFINE_SHADOW_BIAS, DepthPass.SHADOW_BIAS);
  11834. var gl = Laya.LayaGL.instance;
  11835. var offsetX = this._viewPort.x;
  11836. var offsetY = this._viewPort.y;
  11837. gl.enable(gl.SCISSOR_TEST);
  11838. gl.viewport(offsetX, offsetY, this._viewPort.width, this._viewPort.height);
  11839. gl.scissor(offsetX, offsetY, this._viewPort.width, this._viewPort.height);
  11840. gl.clear(gl.DEPTH_BUFFER_BIT);
  11841. scene._opaqueQueue._render(context);
  11842. this._depthTexture._end();
  11843. ShaderData.setRuntimeValueMode(true);
  11844. this._setupDepthModeShaderValue(depthType, this._camera);
  11845. context.pipelineMode = context.configPipeLineMode;
  11846. break;
  11847. case exports.DepthTextureMode.DepthNormals:
  11848. var shaderValues = scene._shaderValues;
  11849. context.pipelineMode = "DepthNormal";
  11850. ShaderData.setRuntimeValueMode(false);
  11851. this._depthNormalsTexture._start();
  11852. var gl = Laya.LayaGL.instance;
  11853. var offsetX = this._viewPort.x;
  11854. var offsetY = this._viewPort.y;
  11855. gl.enable(gl.SCISSOR_TEST);
  11856. gl.viewport(offsetX, offsetY, this._viewPort.width, this._viewPort.height);
  11857. gl.scissor(offsetX, offsetY, this._viewPort.width, this._viewPort.height);
  11858. gl.clearColor(0.0, 0.0, 1.0, 0.0);
  11859. gl.clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT);
  11860. scene._opaqueQueue._render(context);
  11861. this._depthNormalsTexture._end();
  11862. ShaderData.setRuntimeValueMode(true);
  11863. this._setupDepthModeShaderValue(depthType, this._camera);
  11864. context.pipelineMode = context.configPipeLineMode;
  11865. break;
  11866. case exports.DepthTextureMode.MotionVectors:
  11867. break;
  11868. default:
  11869. throw ("there is UnDefined type of DepthTextureMode");
  11870. }
  11871. }
  11872. _setupDepthModeShaderValue(depthType, camera) {
  11873. switch (depthType) {
  11874. case exports.DepthTextureMode.Depth:
  11875. var far = camera.farPlane;
  11876. var near = camera.nearPlane;
  11877. this._zBufferParams.setValue(1.0 - far / near, far / near, (near - far) / (near * far), 1 / near);
  11878. camera._shaderValues.setVector(DepthPass.DEFINE_SHADOW_BIAS, DepthPass.SHADOW_BIAS);
  11879. camera._shaderValues.setTexture(DepthPass.DEPTHTEXTURE, this._depthTexture);
  11880. camera._shaderValues.setVector(DepthPass.DEPTHZBUFFERPARAMS, this._zBufferParams);
  11881. break;
  11882. case exports.DepthTextureMode.DepthNormals:
  11883. camera._shaderValues.setTexture(DepthPass.DEPTHNORMALSTEXTURE, this._depthNormalsTexture);
  11884. break;
  11885. case exports.DepthTextureMode.MotionVectors:
  11886. break;
  11887. default:
  11888. throw ("there is UnDefined type of DepthTextureMode");
  11889. }
  11890. }
  11891. cleanUp() {
  11892. this._depthTexture && RenderTexture.recoverToPool(this._depthTexture);
  11893. this._depthNormalsTexture && RenderTexture.recoverToPool(this._depthNormalsTexture);
  11894. this._depthTexture = null;
  11895. this._depthNormalsTexture = null;
  11896. }
  11897. }
  11898. DepthPass.SHADOW_BIAS = new Vector4();
  11899. DepthPass.DEFINE_SHADOW_BIAS = Shader3D.propertyNameToID("u_ShadowBias");
  11900. DepthPass.DEPTHTEXTURE = Shader3D.propertyNameToID("u_CameraDepthTexture");
  11901. DepthPass.DEPTHNORMALSTEXTURE = Shader3D.propertyNameToID("u_CameraDepthNormalsTexture");
  11902. DepthPass.DEPTHZBUFFERPARAMS = Shader3D.propertyNameToID("u_ZBufferParams");
  11903. (function (CameraClearFlags) {
  11904. CameraClearFlags[CameraClearFlags["SolidColor"] = 0] = "SolidColor";
  11905. CameraClearFlags[CameraClearFlags["Sky"] = 1] = "Sky";
  11906. CameraClearFlags[CameraClearFlags["DepthOnly"] = 2] = "DepthOnly";
  11907. CameraClearFlags[CameraClearFlags["Nothing"] = 3] = "Nothing";
  11908. })(exports.CameraClearFlags || (exports.CameraClearFlags = {}));
  11909. (function (CameraEventFlags) {
  11910. CameraEventFlags[CameraEventFlags["BeforeForwardOpaque"] = 0] = "BeforeForwardOpaque";
  11911. CameraEventFlags[CameraEventFlags["BeforeSkyBox"] = 2] = "BeforeSkyBox";
  11912. CameraEventFlags[CameraEventFlags["BeforeTransparent"] = 4] = "BeforeTransparent";
  11913. CameraEventFlags[CameraEventFlags["BeforeImageEffect"] = 6] = "BeforeImageEffect";
  11914. CameraEventFlags[CameraEventFlags["AfterEveryThing"] = 8] = "AfterEveryThing";
  11915. })(exports.CameraEventFlags || (exports.CameraEventFlags = {}));
  11916. class Camera extends BaseCamera {
  11917. constructor(aspectRatio = 0, nearPlane = 0.3, farPlane = 1000) {
  11918. super(nearPlane, farPlane);
  11919. this._updateViewMatrix = true;
  11920. this._postProcess = null;
  11921. this._enableHDR = false;
  11922. this._viewportParams = new Vector4();
  11923. this._projectionParams = new Vector4();
  11924. this._needBuiltInRenderTexture = false;
  11925. this._offScreenRenderTexture = null;
  11926. this._internalRenderTexture = null;
  11927. this._cameraEventCommandBuffer = {};
  11928. this._clusterPlaneCacheFlag = new Vector2(-1, -1);
  11929. this._screenOffsetScale = new Vector4();
  11930. this.enableRender = true;
  11931. this.clearFlag = exports.CameraClearFlags.SolidColor;
  11932. this._viewMatrix = new Matrix4x4();
  11933. this._projectionMatrix = new Matrix4x4();
  11934. this._projectionViewMatrix = new Matrix4x4();
  11935. this._viewport = new Viewport(0, 0, 0, 0);
  11936. this._normalizedViewport = new Viewport(0, 0, 1, 1);
  11937. this._aspectRatio = aspectRatio;
  11938. this._boundFrustum = new BoundFrustum(new Matrix4x4());
  11939. this._calculateProjectionMatrix();
  11940. Laya.Laya.stage.on(Laya.Event.RESIZE, this, this._onScreenSizeChanged);
  11941. this.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onTransformChanged);
  11942. }
  11943. static drawRenderTextureByScene(camera, scene, renderTexture) {
  11944. if (camera.renderTarget != renderTexture) {
  11945. camera.renderTarget && RenderTexture.recoverToPool(camera.renderTarget);
  11946. camera.renderTarget = renderTexture;
  11947. }
  11948. var viewport = camera.viewport;
  11949. var needInternalRT = camera._needInternalRenderTexture();
  11950. var context = RenderContext3D._instance;
  11951. var scene = context.scene = scene;
  11952. context.pipelineMode = context.configPipeLineMode;
  11953. if (needInternalRT) {
  11954. camera._internalRenderTexture = RenderTexture.createFromPool(viewport.width, viewport.height, camera._getRenderTextureFormat(), Laya.RenderTextureDepthFormat.DEPTH_16);
  11955. camera._internalRenderTexture.filterMode = Laya.FilterMode.Bilinear;
  11956. }
  11957. else {
  11958. camera._internalRenderTexture = null;
  11959. }
  11960. var needShadowCasterPass = camera._renderShadowMap(scene, context);
  11961. camera._preRenderMainPass(context, scene, needInternalRT, viewport);
  11962. camera._renderMainPass(context, viewport, scene, null, null, needInternalRT);
  11963. camera._aftRenderMainPass(needShadowCasterPass);
  11964. return camera.renderTarget;
  11965. }
  11966. get aspectRatio() {
  11967. if (this._aspectRatio === 0) {
  11968. var vp = this.viewport;
  11969. return vp.width / vp.height;
  11970. }
  11971. return this._aspectRatio;
  11972. }
  11973. set aspectRatio(value) {
  11974. if (value < 0)
  11975. throw new Error("Camera: the aspect ratio has to be a positive real number.");
  11976. this._aspectRatio = value;
  11977. this._calculateProjectionMatrix();
  11978. }
  11979. get viewport() {
  11980. if (this._offScreenRenderTexture)
  11981. this._calculationViewport(this._normalizedViewport, this._offScreenRenderTexture.width, this._offScreenRenderTexture.height);
  11982. else
  11983. this._calculationViewport(this._normalizedViewport, RenderContext3D.clientWidth, RenderContext3D.clientHeight);
  11984. return this._viewport;
  11985. }
  11986. set viewport(value) {
  11987. var width;
  11988. var height;
  11989. if (this._offScreenRenderTexture) {
  11990. width = this._offScreenRenderTexture.width;
  11991. height = this._offScreenRenderTexture.height;
  11992. }
  11993. else {
  11994. width = RenderContext3D.clientWidth;
  11995. height = RenderContext3D.clientHeight;
  11996. }
  11997. this._normalizedViewport.x = value.x / width;
  11998. this._normalizedViewport.y = value.y / height;
  11999. this._normalizedViewport.width = value.width / width;
  12000. this._normalizedViewport.height = value.height / height;
  12001. this._calculationViewport(this._normalizedViewport, width, height);
  12002. this._calculateProjectionMatrix();
  12003. }
  12004. get normalizedViewport() {
  12005. return this._normalizedViewport;
  12006. }
  12007. set normalizedViewport(value) {
  12008. var width;
  12009. var height;
  12010. if (this._offScreenRenderTexture) {
  12011. width = this._offScreenRenderTexture.width;
  12012. height = this._offScreenRenderTexture.height;
  12013. }
  12014. else {
  12015. width = RenderContext3D.clientWidth;
  12016. height = RenderContext3D.clientHeight;
  12017. }
  12018. if (this._normalizedViewport !== value)
  12019. value.cloneTo(this._normalizedViewport);
  12020. this._calculationViewport(value, width, height);
  12021. this._calculateProjectionMatrix();
  12022. }
  12023. get viewMatrix() {
  12024. if (this._updateViewMatrix) {
  12025. var scale = this.transform.getWorldLossyScale();
  12026. var scaleX = scale.x;
  12027. var scaleY = scale.y;
  12028. var scaleZ = scale.z;
  12029. var viewMatE = this._viewMatrix.elements;
  12030. this.transform.worldMatrix.cloneTo(this._viewMatrix);
  12031. viewMatE[0] /= scaleX;
  12032. viewMatE[1] /= scaleX;
  12033. viewMatE[2] /= scaleX;
  12034. viewMatE[4] /= scaleY;
  12035. viewMatE[5] /= scaleY;
  12036. viewMatE[6] /= scaleY;
  12037. viewMatE[8] /= scaleZ;
  12038. viewMatE[9] /= scaleZ;
  12039. viewMatE[10] /= scaleZ;
  12040. this._viewMatrix.invert(this._viewMatrix);
  12041. this._updateViewMatrix = false;
  12042. }
  12043. return this._viewMatrix;
  12044. }
  12045. get projectionMatrix() {
  12046. return this._projectionMatrix;
  12047. }
  12048. set projectionMatrix(value) {
  12049. this._projectionMatrix = value;
  12050. this._useUserProjectionMatrix = true;
  12051. }
  12052. get projectionViewMatrix() {
  12053. Matrix4x4.multiply(this.projectionMatrix, this.viewMatrix, this._projectionViewMatrix);
  12054. return this._projectionViewMatrix;
  12055. }
  12056. get boundFrustum() {
  12057. this._boundFrustum.matrix = this.projectionViewMatrix;
  12058. return this._boundFrustum;
  12059. }
  12060. get renderTarget() {
  12061. return this._offScreenRenderTexture;
  12062. }
  12063. set renderTarget(value) {
  12064. var lastValue = this._offScreenRenderTexture;
  12065. if (lastValue !== value) {
  12066. (lastValue) && (lastValue._isCameraTarget = false);
  12067. (value) && (value._isCameraTarget = true);
  12068. this._offScreenRenderTexture = value;
  12069. this._calculateProjectionMatrix();
  12070. }
  12071. }
  12072. get postProcess() {
  12073. return this._postProcess;
  12074. }
  12075. set postProcess(value) {
  12076. this._postProcess = value;
  12077. if (!value)
  12078. return;
  12079. value && value._init(this);
  12080. }
  12081. get enableHDR() {
  12082. return this._enableHDR;
  12083. }
  12084. set enableHDR(value) {
  12085. if (value && !Laya.SystemUtils.supportRenderTextureFormat(Laya.RenderTextureFormat.R16G16B16A16)) {
  12086. console.warn("Camera:can't enable HDR in this device.");
  12087. return;
  12088. }
  12089. this._enableHDR = value;
  12090. }
  12091. get enableBuiltInRenderTexture() {
  12092. return this._needBuiltInRenderTexture;
  12093. }
  12094. set enableBuiltInRenderTexture(value) {
  12095. this._needBuiltInRenderTexture = value;
  12096. }
  12097. get depthTextureMode() {
  12098. return this._depthTextureMode;
  12099. }
  12100. set depthTextureMode(value) {
  12101. this._depthTextureMode = value;
  12102. }
  12103. _calculationViewport(normalizedViewport, width, height) {
  12104. var lx = normalizedViewport.x * width;
  12105. var ly = normalizedViewport.y * height;
  12106. var rx = lx + Math.max(normalizedViewport.width * width, 0);
  12107. var ry = ly + Math.max(normalizedViewport.height * height, 0);
  12108. var ceilLeftX = Math.ceil(lx);
  12109. var ceilLeftY = Math.ceil(ly);
  12110. var floorRightX = Math.floor(rx);
  12111. var floorRightY = Math.floor(ry);
  12112. var pixelLeftX = ceilLeftX - lx >= 0.5 ? Math.floor(lx) : ceilLeftX;
  12113. var pixelLeftY = ceilLeftY - ly >= 0.5 ? Math.floor(ly) : ceilLeftY;
  12114. var pixelRightX = rx - floorRightX >= 0.5 ? Math.ceil(rx) : floorRightX;
  12115. var pixelRightY = ry - floorRightY >= 0.5 ? Math.ceil(ry) : floorRightY;
  12116. this._viewport.x = pixelLeftX;
  12117. this._viewport.y = pixelLeftY;
  12118. this._viewport.width = pixelRightX - pixelLeftX;
  12119. this._viewport.height = pixelRightY - pixelLeftY;
  12120. }
  12121. _calculateProjectionMatrix() {
  12122. if (!this._useUserProjectionMatrix) {
  12123. if (this._orthographic) {
  12124. var halfHeight = this.orthographicVerticalSize * 0.5;
  12125. var halfWidth = halfHeight * this.aspectRatio;
  12126. Matrix4x4.createOrthoOffCenter(-halfWidth, halfWidth, -halfHeight, halfHeight, this.nearPlane, this.farPlane, this._projectionMatrix);
  12127. }
  12128. else {
  12129. Matrix4x4.createPerspective(3.1416 * this.fieldOfView / 180.0, this.aspectRatio, this.nearPlane, this.farPlane, this._projectionMatrix);
  12130. }
  12131. }
  12132. }
  12133. _isLayerVisible(layer) {
  12134. return (Math.pow(2, layer) & this.cullingMask) != 0;
  12135. }
  12136. _onTransformChanged(flag) {
  12137. flag &= Transform3D.TRANSFORM_WORLDMATRIX;
  12138. (flag) && (this._updateViewMatrix = true);
  12139. }
  12140. _parse(data, spriteMap) {
  12141. super._parse(data, spriteMap);
  12142. var clearFlagData = data.clearFlag;
  12143. (clearFlagData !== undefined) && (this.clearFlag = clearFlagData);
  12144. var viewport = data.viewport;
  12145. this.normalizedViewport = new Viewport(viewport[0], viewport[1], viewport[2], viewport[3]);
  12146. var enableHDR = data.enableHDR;
  12147. (enableHDR !== undefined) && (this.enableHDR = enableHDR);
  12148. }
  12149. _getCanvasWidth() {
  12150. if (this._offScreenRenderTexture)
  12151. return this._offScreenRenderTexture.width;
  12152. else
  12153. return RenderContext3D.clientWidth;
  12154. }
  12155. _getCanvasHeight() {
  12156. if (this._offScreenRenderTexture)
  12157. return this._offScreenRenderTexture.height;
  12158. else
  12159. return RenderContext3D.clientHeight;
  12160. }
  12161. _getRenderTexture() {
  12162. return this._internalRenderTexture || this._offScreenRenderTexture;
  12163. }
  12164. _needInternalRenderTexture() {
  12165. return (this._postProcess && this._postProcess.enable) || this._enableHDR || this._needBuiltInRenderTexture ? true : false;
  12166. }
  12167. _getRenderTextureFormat() {
  12168. if (this._enableHDR)
  12169. return Laya.RenderTextureFormat.R16G16B16A16;
  12170. else
  12171. return Laya.RenderTextureFormat.R8G8B8;
  12172. }
  12173. _prepareCameraToRender() {
  12174. super._prepareCameraToRender();
  12175. var vp = this.viewport;
  12176. this._viewportParams.setValue(vp.x, vp.y, vp.width, vp.height);
  12177. this._projectionParams.setValue(this._nearPlane, this._farPlane, RenderContext3D._instance.invertY ? -1 : 1, 1 / this.farPlane);
  12178. this._shaderValues.setVector(BaseCamera.VIEWPORT, this._viewportParams);
  12179. this._shaderValues.setVector(BaseCamera.PROJECTION_PARAMS, this._projectionParams);
  12180. }
  12181. _applyViewProject(context, viewMat, proMat) {
  12182. var projectView;
  12183. var shaderData = this._shaderValues;
  12184. if (context.invertY) {
  12185. Matrix4x4.multiply(BaseCamera._invertYScaleMatrix, proMat, BaseCamera._invertYProjectionMatrix);
  12186. Matrix4x4.multiply(BaseCamera._invertYProjectionMatrix, viewMat, BaseCamera._invertYProjectionViewMatrix);
  12187. proMat = BaseCamera._invertYProjectionMatrix;
  12188. projectView = BaseCamera._invertYProjectionViewMatrix;
  12189. }
  12190. else {
  12191. Matrix4x4.multiply(proMat, viewMat, this._projectionViewMatrix);
  12192. projectView = this._projectionViewMatrix;
  12193. }
  12194. context.viewMatrix = viewMat;
  12195. context.projectionMatrix = proMat;
  12196. context.projectionViewMatrix = projectView;
  12197. shaderData.setMatrix4x4(BaseCamera.VIEWMATRIX, viewMat);
  12198. shaderData.setMatrix4x4(BaseCamera.PROJECTMATRIX, proMat);
  12199. shaderData.setMatrix4x4(BaseCamera.VIEWPROJECTMATRIX, projectView);
  12200. }
  12201. _updateClusterPlaneXY() {
  12202. var fieldOfView = this.fieldOfView;
  12203. var aspectRatio = this.aspectRatio;
  12204. if (this._clusterPlaneCacheFlag.x !== fieldOfView || this._clusterPlaneCacheFlag.y !== aspectRatio) {
  12205. var clusterCount = Config3D._config.lightClusterCount;
  12206. var xSlixe = clusterCount.x, ySlice = clusterCount.y;
  12207. var xCount = xSlixe + 1, yCount = ySlice + 1;
  12208. var xPlanes = this._clusterXPlanes, yPlanes = this._clusterYPlanes;
  12209. if (!xPlanes) {
  12210. xPlanes = this._clusterXPlanes = new Array(xCount);
  12211. yPlanes = this._clusterYPlanes = new Array(yCount);
  12212. for (var i = 0; i < xCount; i++)
  12213. xPlanes[i] = new Vector3();
  12214. for (var i = 0; i < yCount; i++)
  12215. yPlanes[i] = new Vector3();
  12216. }
  12217. var halfY = Math.tan((this.fieldOfView / 2) * Math.PI / 180);
  12218. var halfX = this.aspectRatio * halfY;
  12219. var yLengthPerCluster = 2 * halfY / xSlixe;
  12220. var xLengthPerCluster = 2 * halfX / ySlice;
  12221. for (var i = 0; i < xCount; i++) {
  12222. var angle = -halfX + xLengthPerCluster * i;
  12223. var bigHypot = Math.sqrt(1 + angle * angle);
  12224. var normX = 1 / bigHypot;
  12225. var xPlane = xPlanes[i];
  12226. xPlane.setValue(normX, 0, -angle * normX);
  12227. }
  12228. for (var i = 0; i < yCount; i++) {
  12229. var angle = halfY - yLengthPerCluster * i;
  12230. var bigHypot = Math.sqrt(1 + angle * angle);
  12231. var normY = -1 / bigHypot;
  12232. var yPlane = yPlanes[i];
  12233. yPlane.setValue(0, normY, -angle * normY);
  12234. }
  12235. this._clusterPlaneCacheFlag.x = fieldOfView;
  12236. this._clusterPlaneCacheFlag.y = aspectRatio;
  12237. }
  12238. }
  12239. _applyCommandBuffer(event, context) {
  12240. var gl = Laya.LayaGL.instance;
  12241. var commandBufferArray = this._cameraEventCommandBuffer[event];
  12242. if (!commandBufferArray || commandBufferArray.length == 0)
  12243. return;
  12244. commandBufferArray.forEach(function (value) {
  12245. value._context = context;
  12246. value._apply();
  12247. });
  12248. (RenderTexture.currentActive) && (RenderTexture.currentActive._end());
  12249. if (this._internalRenderTexture)
  12250. this._internalRenderTexture._start();
  12251. else {
  12252. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12253. }
  12254. gl.viewport(0, 0, context.viewport.width, context.viewport.height);
  12255. }
  12256. _renderShadowMap(scene, context) {
  12257. var shadowCasterPass;
  12258. var mainDirectLight = scene._mainDirectionLight;
  12259. var needShadowCasterPass = mainDirectLight && mainDirectLight.shadowMode !== exports.ShadowMode.None && ShadowUtils.supportShadow();
  12260. if (needShadowCasterPass) {
  12261. scene._shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT);
  12262. scene._shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW);
  12263. shadowCasterPass = ILaya3D.Scene3D._shadowCasterPass;
  12264. shadowCasterPass.update(this, mainDirectLight, ILaya3D.ShadowLightType.DirectionLight);
  12265. shadowCasterPass.render(context, scene, ILaya3D.ShadowLightType.DirectionLight);
  12266. }
  12267. else {
  12268. scene._shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW);
  12269. }
  12270. var spotMainLight = scene._mainSpotLight;
  12271. var spotneedShadowCasterPass = spotMainLight && spotMainLight.shadowMode !== exports.ShadowMode.None && ShadowUtils.supportShadow();
  12272. if (spotneedShadowCasterPass) {
  12273. scene._shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW);
  12274. scene._shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT);
  12275. shadowCasterPass = ILaya3D.Scene3D._shadowCasterPass;
  12276. shadowCasterPass.update(this, spotMainLight, ILaya3D.ShadowLightType.SpotLight);
  12277. shadowCasterPass.render(context, scene, ILaya3D.ShadowLightType.SpotLight);
  12278. }
  12279. else {
  12280. scene._shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT);
  12281. }
  12282. if (needShadowCasterPass)
  12283. scene._shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW);
  12284. if (spotneedShadowCasterPass)
  12285. scene._shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT);
  12286. return needShadowCasterPass || spotneedShadowCasterPass;
  12287. }
  12288. _preRenderMainPass(context, scene, needInternalRT, viewport) {
  12289. context.camera = this;
  12290. context.cameraShaderValue = this._shaderValues;
  12291. Camera._updateMark++;
  12292. scene._preRenderScript();
  12293. var gl = Laya.LayaGL.instance;
  12294. if (needInternalRT && !this._offScreenRenderTexture && (this.clearFlag == exports.CameraClearFlags.DepthOnly || this.clearFlag == exports.CameraClearFlags.Nothing)) {
  12295. if (this._enableHDR) {
  12296. var grabTexture = RenderTexture.createFromPool(viewport.width, viewport.height, Laya.RenderTextureFormat.R8G8B8, Laya.RenderTextureDepthFormat.DEPTH_16);
  12297. grabTexture.filterMode = Laya.FilterMode.Bilinear;
  12298. Laya.WebGLContext.bindTexture(gl, gl.TEXTURE_2D, grabTexture._getSource());
  12299. gl.copyTexSubImage2D(gl.TEXTURE_2D, 0, 0, 0, viewport.x, RenderContext3D.clientHeight - (viewport.y + viewport.height), viewport.width, viewport.height);
  12300. var blit = BlitScreenQuadCMD.create(grabTexture, this._internalRenderTexture);
  12301. blit.run();
  12302. blit.recover();
  12303. RenderTexture.recoverToPool(grabTexture);
  12304. }
  12305. else {
  12306. Laya.WebGLContext.bindTexture(gl, gl.TEXTURE_2D, this._internalRenderTexture._getSource());
  12307. gl.copyTexSubImage2D(gl.TEXTURE_2D, 0, 0, 0, viewport.x, RenderContext3D.clientHeight - (viewport.y + viewport.height), viewport.width, viewport.height);
  12308. }
  12309. }
  12310. }
  12311. _renderMainPass(context, viewport, scene, shader, replacementTag, needInternalRT) {
  12312. var gl = Laya.LayaGL.instance;
  12313. var renderTex = this._getRenderTexture();
  12314. context.viewport = viewport;
  12315. this._prepareCameraToRender();
  12316. var multiLighting = Config3D._config._multiLighting;
  12317. (multiLighting) && (Cluster.instance.update(this, (scene)));
  12318. scene._preCulling(context, this, shader, replacementTag);
  12319. if (this.depthTextureMode != 0) {
  12320. this._applyViewProject(context, this.viewMatrix, this._projectionMatrix);
  12321. this._renderDepthMode(context);
  12322. }
  12323. (renderTex) && (renderTex._start());
  12324. this._applyViewProject(context, this.viewMatrix, this._projectionMatrix);
  12325. scene._clear(gl, context);
  12326. this._applyCommandBuffer(exports.CameraEventFlags.BeforeForwardOpaque, context);
  12327. scene._renderScene(context, ILaya3D.Scene3D.SCENERENDERFLAG_RENDERQPAQUE);
  12328. this._applyCommandBuffer(exports.CameraEventFlags.BeforeSkyBox, context);
  12329. scene._renderScene(context, ILaya3D.Scene3D.SCENERENDERFLAG_SKYBOX);
  12330. this._applyCommandBuffer(exports.CameraEventFlags.BeforeTransparent, context);
  12331. scene._renderScene(context, ILaya3D.Scene3D.SCENERENDERFLAG_RENDERTRANSPARENT);
  12332. scene._postRenderScript();
  12333. this._applyCommandBuffer(exports.CameraEventFlags.BeforeImageEffect, context);
  12334. (renderTex) && (renderTex._end());
  12335. if (needInternalRT) {
  12336. if (this._postProcess && this._postProcess.enable) {
  12337. this._postProcess._render();
  12338. this._postProcess._applyPostProcessCommandBuffers();
  12339. }
  12340. else if (this._enableHDR || this._needBuiltInRenderTexture) {
  12341. var canvasWidth = this._getCanvasWidth(), canvasHeight = this._getCanvasHeight();
  12342. this._screenOffsetScale.setValue(viewport.x / canvasWidth, viewport.y / canvasHeight, viewport.width / canvasWidth, viewport.height / canvasHeight);
  12343. var blit = BlitScreenQuadCMD.create(this._internalRenderTexture, this._offScreenRenderTexture ? this._offScreenRenderTexture : null, this._screenOffsetScale, null, null, 0, BlitScreenQuadCMD._SCREENTYPE_QUAD, null, true);
  12344. blit.run();
  12345. blit.recover();
  12346. }
  12347. RenderTexture.recoverToPool(this._internalRenderTexture);
  12348. }
  12349. this._applyCommandBuffer(exports.CameraEventFlags.AfterEveryThing, context);
  12350. }
  12351. _renderDepthMode(context) {
  12352. var cameraDepthMode = this._depthTextureMode;
  12353. if ((cameraDepthMode & exports.DepthTextureMode.Depth) != 0) {
  12354. Camera.depthPass.update(this, exports.DepthTextureMode.Depth);
  12355. Camera.depthPass.render(context, exports.DepthTextureMode.Depth);
  12356. }
  12357. if ((cameraDepthMode & exports.DepthTextureMode.DepthNormals) != 0) {
  12358. Camera.depthPass.update(this, exports.DepthTextureMode.DepthNormals);
  12359. Camera.depthPass.render(context, exports.DepthTextureMode.DepthNormals);
  12360. }
  12361. }
  12362. get depthTexture() {
  12363. return this._depthTexture;
  12364. }
  12365. set depthTexture(value) {
  12366. this._depthTexture = value;
  12367. }
  12368. get depthNormalTexture() {
  12369. return this._depthNormalsTexture;
  12370. }
  12371. set depthNormalTexture(value) {
  12372. this._depthNormalsTexture = value;
  12373. }
  12374. _aftRenderMainPass(needShadowPass) {
  12375. if (needShadowPass)
  12376. ILaya3D.Scene3D._shadowCasterPass.cleanUp();
  12377. Camera.depthPass.cleanUp();
  12378. }
  12379. render(shader = null, replacementTag = null) {
  12380. if (!this.activeInHierarchy)
  12381. return;
  12382. var viewport = this.viewport;
  12383. var needInternalRT = this._needInternalRenderTexture();
  12384. var context = RenderContext3D._instance;
  12385. var scene = context.scene = this._scene;
  12386. context.pipelineMode = context.configPipeLineMode;
  12387. if (needInternalRT) {
  12388. this._internalRenderTexture = RenderTexture.createFromPool(viewport.width, viewport.height, this._getRenderTextureFormat(), Laya.RenderTextureDepthFormat.DEPTH_16);
  12389. this._internalRenderTexture.filterMode = Laya.FilterMode.Bilinear;
  12390. }
  12391. else {
  12392. this._internalRenderTexture = null;
  12393. }
  12394. var needShadowCasterPass = this._renderShadowMap(scene, context);
  12395. this._preRenderMainPass(context, scene, needInternalRT, viewport);
  12396. this._renderMainPass(context, viewport, scene, shader, replacementTag, needInternalRT);
  12397. this._aftRenderMainPass(needShadowCasterPass);
  12398. }
  12399. viewportPointToRay(point, out) {
  12400. Picker.calculateCursorRay(point, this.viewport, this._projectionMatrix, this.viewMatrix, null, out);
  12401. }
  12402. normalizedViewportPointToRay(point, out) {
  12403. var finalPoint = Camera._tempVector20;
  12404. var vp = this.viewport;
  12405. finalPoint.x = point.x * vp.width;
  12406. finalPoint.y = point.y * vp.height;
  12407. Picker.calculateCursorRay(finalPoint, this.viewport, this._projectionMatrix, this.viewMatrix, null, out);
  12408. }
  12409. worldToViewportPoint(position, out) {
  12410. Matrix4x4.multiply(this._projectionMatrix, this._viewMatrix, this._projectionViewMatrix);
  12411. this.viewport.project(position, this._projectionViewMatrix, out);
  12412. out.x = out.x / Laya.Laya.stage.clientScaleX;
  12413. out.y = out.y / Laya.Laya.stage.clientScaleY;
  12414. }
  12415. worldToNormalizedViewportPoint(position, out) {
  12416. Matrix4x4.multiply(this._projectionMatrix, this._viewMatrix, this._projectionViewMatrix);
  12417. this.normalizedViewport.project(position, this._projectionViewMatrix, out);
  12418. out.x = out.x / Laya.Laya.stage.clientScaleX;
  12419. out.y = out.y / Laya.Laya.stage.clientScaleY;
  12420. }
  12421. convertScreenCoordToOrthographicCoord(source, out) {
  12422. if (this._orthographic) {
  12423. var clientWidth = RenderContext3D.clientWidth;
  12424. var clientHeight = RenderContext3D.clientHeight;
  12425. var ratioX = this.orthographicVerticalSize * this.aspectRatio / clientWidth;
  12426. var ratioY = this.orthographicVerticalSize / clientHeight;
  12427. out.x = (-clientWidth / 2 + source.x * Laya.Laya.stage.clientScaleX) * ratioX;
  12428. out.y = (clientHeight / 2 - source.y * Laya.Laya.stage.clientScaleY) * ratioY;
  12429. out.z = (this.nearPlane - this.farPlane) * (source.z + 1) / 2 - this.nearPlane;
  12430. Vector3.transformCoordinate(out, this.transform.worldMatrix, out);
  12431. return true;
  12432. }
  12433. else {
  12434. return false;
  12435. }
  12436. }
  12437. destroy(destroyChild = true) {
  12438. this._offScreenRenderTexture = null;
  12439. this.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onTransformChanged);
  12440. super.destroy(destroyChild);
  12441. }
  12442. addCommandBuffer(event, commandBuffer) {
  12443. var commandBufferArray = this._cameraEventCommandBuffer[event];
  12444. if (!commandBufferArray)
  12445. commandBufferArray = this._cameraEventCommandBuffer[event] = [];
  12446. if (commandBufferArray.indexOf(commandBuffer) < 0)
  12447. commandBufferArray.push(commandBuffer);
  12448. commandBuffer._camera = this;
  12449. }
  12450. removeCommandBuffer(event, commandBuffer) {
  12451. var commandBufferArray = this._cameraEventCommandBuffer[event];
  12452. if (commandBufferArray) {
  12453. var index = commandBufferArray.indexOf(commandBuffer);
  12454. if (index != -1)
  12455. commandBufferArray.splice(index, 1);
  12456. }
  12457. else
  12458. throw "Camera:unknown event.";
  12459. }
  12460. removeCommandBuffers(event) {
  12461. if (this._cameraEventCommandBuffer[event])
  12462. this._cameraEventCommandBuffer[event].length = 0;
  12463. }
  12464. _create() {
  12465. return new Camera();
  12466. }
  12467. }
  12468. Camera._tempVector20 = new Vector2();
  12469. Camera._updateMark = 0;
  12470. Camera.depthPass = new DepthPass();
  12471. class RenderElement {
  12472. constructor() {
  12473. this.renderSubShader = null;
  12474. this.renderType = RenderElement.RENDERTYPE_NORMAL;
  12475. }
  12476. getInvertFront() {
  12477. return this._transform._isFrontFaceInvert;
  12478. }
  12479. setTransform(transform) {
  12480. this._transform = transform;
  12481. }
  12482. setGeometry(geometry) {
  12483. this._geometry = geometry;
  12484. }
  12485. addToOpaqueRenderQueue(context, queue) {
  12486. queue.elements.add(this);
  12487. }
  12488. addToTransparentRenderQueue(context, queue) {
  12489. queue.elements.add(this);
  12490. queue.lastTransparentBatched = false;
  12491. queue.lastTransparentRenderElement = this;
  12492. }
  12493. _update(scene, context, customShader, replacementTag, subshaderIndex = 0) {
  12494. if (this.material) {
  12495. var subShader = this.material._shader.getSubShaderAt(0);
  12496. this.renderSubShader = null;
  12497. if (customShader) {
  12498. if (replacementTag) {
  12499. var oriTag = subShader.getFlag(replacementTag);
  12500. if (oriTag) {
  12501. var customSubShaders = customShader._subShaders;
  12502. for (var k = 0, p = customSubShaders.length; k < p; k++) {
  12503. var customSubShader = customSubShaders[k];
  12504. if (oriTag === customSubShader.getFlag(replacementTag)) {
  12505. this.renderSubShader = customSubShader;
  12506. break;
  12507. }
  12508. }
  12509. if (!this.renderSubShader)
  12510. return;
  12511. }
  12512. else {
  12513. return;
  12514. }
  12515. }
  12516. else {
  12517. this.renderSubShader = customShader.getSubShaderAt(subshaderIndex);
  12518. }
  12519. }
  12520. else {
  12521. this.renderSubShader = subShader;
  12522. }
  12523. var renderQueue = scene._getRenderQueue(this.material.renderQueue);
  12524. if (renderQueue.isTransparent)
  12525. this.addToTransparentRenderQueue(context, renderQueue);
  12526. else
  12527. this.addToOpaqueRenderQueue(context, renderQueue);
  12528. }
  12529. }
  12530. _render(context) {
  12531. var forceInvertFace = context.invertY;
  12532. var lastStateMaterial, lastStateShaderInstance, lastStateRender;
  12533. var updateMark = Camera._updateMark;
  12534. var scene = context.scene;
  12535. var cameraShaderValue = context.cameraShaderValue;
  12536. var transform = this._transform;
  12537. var geometry = this._geometry;
  12538. context.renderElement = this;
  12539. var updateRender = updateMark !== this.render._updateMark || this.renderType !== this.render._updateRenderType;
  12540. if (updateRender) {
  12541. this.render._renderUpdate(context, transform);
  12542. this.render._renderUpdateWithCamera(context, transform);
  12543. this.render._updateMark = updateMark;
  12544. this.render._updateRenderType = this.renderType;
  12545. }
  12546. else {
  12547. if (this.renderType == RenderElement.RENDERTYPE_INSTANCEBATCH) {
  12548. this.render._renderUpdate(context, transform);
  12549. this.render._renderUpdateWithCamera(context, transform);
  12550. }
  12551. }
  12552. var currentPipelineMode = context.pipelineMode;
  12553. if (geometry._prepareRender(context)) {
  12554. var passes = this.renderSubShader._passes;
  12555. for (var j = 0, m = passes.length; j < m; j++) {
  12556. var pass = passes[j];
  12557. if (pass._pipelineMode !== currentPipelineMode)
  12558. continue;
  12559. var comDef = RenderElement._compileDefine;
  12560. scene._shaderValues._defineDatas.cloneTo(comDef);
  12561. comDef.addDefineDatas(this.render._shaderValues._defineDatas);
  12562. comDef.addDefineDatas(this.material._shaderValues._defineDatas);
  12563. var shaderIns = context.shader = pass.withCompile(comDef);
  12564. var switchShader = shaderIns.bind();
  12565. var switchUpdateMark = (updateMark !== shaderIns._uploadMark);
  12566. var uploadScene = (shaderIns._uploadScene !== scene) || switchUpdateMark;
  12567. if (uploadScene || switchShader) {
  12568. shaderIns.uploadUniforms(shaderIns._sceneUniformParamsMap, scene._shaderValues, uploadScene);
  12569. shaderIns._uploadScene = scene;
  12570. }
  12571. var uploadSprite3D = (shaderIns._uploadRender !== this.render || shaderIns._uploadRenderType !== this.renderType) || switchUpdateMark;
  12572. if (uploadSprite3D || switchShader) {
  12573. shaderIns.uploadUniforms(shaderIns._spriteUniformParamsMap, this.render._shaderValues, uploadSprite3D);
  12574. shaderIns._uploadRender = this.render;
  12575. shaderIns._uploadRenderType = this.renderType;
  12576. }
  12577. var uploadCamera = shaderIns._uploadCameraShaderValue !== cameraShaderValue || switchUpdateMark;
  12578. if (uploadCamera || switchShader) {
  12579. shaderIns.uploadUniforms(shaderIns._cameraUniformParamsMap, cameraShaderValue, uploadCamera);
  12580. shaderIns._uploadCameraShaderValue = cameraShaderValue;
  12581. }
  12582. var uploadMaterial = (shaderIns._uploadMaterial !== this.material) || switchUpdateMark;
  12583. if (uploadMaterial || switchShader) {
  12584. shaderIns.uploadUniforms(shaderIns._materialUniformParamsMap, this.material._shaderValues, uploadMaterial);
  12585. shaderIns._uploadMaterial = this.material;
  12586. }
  12587. var matValues = this.material._shaderValues;
  12588. if (lastStateMaterial !== this.material || lastStateShaderInstance !== shaderIns) {
  12589. shaderIns.uploadRenderStateBlendDepth(matValues);
  12590. shaderIns.uploadRenderStateFrontFace(matValues, forceInvertFace, this.getInvertFront());
  12591. lastStateMaterial = this.material;
  12592. lastStateShaderInstance = shaderIns;
  12593. lastStateRender = this.render;
  12594. }
  12595. else {
  12596. if (lastStateRender !== this.render) {
  12597. shaderIns.uploadRenderStateFrontFace(matValues, forceInvertFace, this.getInvertFront());
  12598. lastStateRender = this.render;
  12599. }
  12600. }
  12601. geometry._render(context);
  12602. shaderIns._uploadMark = updateMark;
  12603. }
  12604. }
  12605. if (this.renderType !== RenderElement.RENDERTYPE_NORMAL)
  12606. this.render._revertBatchRenderUpdate(context);
  12607. }
  12608. destroy() {
  12609. this._transform = null;
  12610. this._geometry = null;
  12611. this.material = null;
  12612. this.render = null;
  12613. }
  12614. }
  12615. RenderElement.RENDERTYPE_NORMAL = 0;
  12616. RenderElement.RENDERTYPE_STATICBATCH = 1;
  12617. RenderElement.RENDERTYPE_INSTANCEBATCH = 2;
  12618. RenderElement.RENDERTYPE_VERTEXBATCH = 3;
  12619. RenderElement._compileDefine = new DefineDatas();
  12620. class DrawRenderCMD extends Command {
  12621. static create(render, material, subShaderIndex, commandBuffer) {
  12622. var cmd;
  12623. cmd = DrawRenderCMD._pool.length > 0 ? DrawRenderCMD._pool.pop() : new DrawRenderCMD();
  12624. cmd._render = render;
  12625. cmd._material = material;
  12626. cmd._subShaderIndex = subShaderIndex;
  12627. cmd._commandBuffer = commandBuffer;
  12628. return cmd;
  12629. }
  12630. _elementRender(renderElement, context) {
  12631. var forceInvertFace = context.invertY;
  12632. var lastStateMaterial, lastStateShaderInstance, lastStateRender;
  12633. var updateMark = Camera._updateMark;
  12634. var scene = context.scene;
  12635. this._render._scene = context.scene;
  12636. var cameraShaderValue = context.cameraShaderValue;
  12637. var transform = renderElement._transform;
  12638. var geometry = renderElement._geometry;
  12639. context.renderElement = renderElement;
  12640. var updateRender = updateMark !== renderElement.render._updateMark || renderElement.renderType !== renderElement.render._updateRenderType;
  12641. if (updateRender) {
  12642. renderElement.render._renderUpdate(context, transform);
  12643. renderElement.render._renderUpdateWithCamera(context, transform);
  12644. renderElement.render._updateMark = updateMark;
  12645. renderElement.render._updateRenderType = renderElement.renderType;
  12646. }
  12647. else {
  12648. if (renderElement.renderType == RenderElement.RENDERTYPE_INSTANCEBATCH) {
  12649. renderElement.render._renderUpdate(context, transform);
  12650. renderElement.render._renderUpdateWithCamera(context, transform);
  12651. }
  12652. }
  12653. var currentPipelineMode = context.pipelineMode;
  12654. if (geometry._prepareRender(context)) {
  12655. var passes = renderElement.renderSubShader._passes;
  12656. for (var j = 0, m = passes.length; j < m; j++) {
  12657. var pass = passes[j];
  12658. if (pass._pipelineMode !== currentPipelineMode)
  12659. continue;
  12660. var comDef = DrawRenderCMD._compileDefine;
  12661. scene._shaderValues._defineDatas.cloneTo(comDef);
  12662. comDef.addDefineDatas(renderElement.render._shaderValues._defineDatas);
  12663. comDef.addDefineDatas(this._material._shaderValues._defineDatas);
  12664. var shaderIns = context.shader = pass.withCompile(comDef);
  12665. var switchShader = shaderIns.bind();
  12666. var switchUpdateMark = (updateMark !== shaderIns._uploadMark);
  12667. var uploadScene = (shaderIns._uploadScene !== scene) || switchUpdateMark;
  12668. if (uploadScene || switchShader) {
  12669. shaderIns.uploadUniforms(shaderIns._sceneUniformParamsMap, scene._shaderValues, uploadScene);
  12670. shaderIns._uploadScene = scene;
  12671. }
  12672. var uploadSprite3D = (shaderIns._uploadRender !== renderElement.render || shaderIns._uploadRenderType !== renderElement.renderType) || switchUpdateMark;
  12673. if (uploadSprite3D || switchShader) {
  12674. shaderIns.uploadUniforms(shaderIns._spriteUniformParamsMap, renderElement.render._shaderValues, uploadSprite3D);
  12675. shaderIns._uploadRender = renderElement.render;
  12676. shaderIns._uploadRenderType = renderElement.renderType;
  12677. }
  12678. var uploadCamera = shaderIns._uploadCameraShaderValue !== cameraShaderValue || switchUpdateMark;
  12679. if (uploadCamera || switchShader) {
  12680. shaderIns.uploadUniforms(shaderIns._cameraUniformParamsMap, cameraShaderValue, uploadCamera);
  12681. shaderIns._uploadCameraShaderValue = cameraShaderValue;
  12682. }
  12683. var uploadMaterial = (shaderIns._uploadMaterial !== this._material) || switchUpdateMark;
  12684. if (uploadMaterial || switchShader) {
  12685. shaderIns.uploadUniforms(shaderIns._materialUniformParamsMap, this._material._shaderValues, uploadMaterial);
  12686. shaderIns._uploadMaterial = this._material;
  12687. }
  12688. var matValues = this._material._shaderValues;
  12689. if (lastStateMaterial !== this._material || lastStateShaderInstance !== shaderIns) {
  12690. shaderIns.uploadRenderStateBlendDepth(matValues);
  12691. shaderIns.uploadRenderStateFrontFace(matValues, forceInvertFace, renderElement.getInvertFront());
  12692. lastStateMaterial = this._material;
  12693. lastStateShaderInstance = shaderIns;
  12694. lastStateRender = renderElement.render;
  12695. }
  12696. else {
  12697. if (lastStateRender !== renderElement.render) {
  12698. shaderIns.uploadRenderStateFrontFace(matValues, forceInvertFace, renderElement.getInvertFront());
  12699. lastStateRender = renderElement.render;
  12700. }
  12701. }
  12702. geometry._render(context);
  12703. shaderIns._uploadMark = updateMark;
  12704. }
  12705. }
  12706. if (renderElement.renderType !== RenderElement.RENDERTYPE_NORMAL)
  12707. renderElement.render._revertBatchRenderUpdate(context);
  12708. }
  12709. run() {
  12710. if (!this._material)
  12711. throw "This render command material cannot be empty";
  12712. this.setContext(this._commandBuffer._context);
  12713. var context = this._context;
  12714. var scene = context.scene;
  12715. var renderElements = this._render._renderElements;
  12716. for (var i = 0, n = renderElements.length; i < n; i++) {
  12717. var renderelement = renderElements[i];
  12718. this._renderElementUpdate(renderelement);
  12719. this._elementRender(renderelement, context);
  12720. }
  12721. }
  12722. _renderElementUpdate(renderelement) {
  12723. if (this._material) {
  12724. renderelement.renderSubShader = this._material._shader.getSubShaderAt(this._subShaderIndex);
  12725. }
  12726. }
  12727. recover() {
  12728. DrawRenderCMD._pool.push(this);
  12729. }
  12730. }
  12731. DrawRenderCMD._pool = [];
  12732. DrawRenderCMD._compileDefine = new DefineDatas();
  12733. class SetGlobalShaderDataCMD extends Command {
  12734. constructor() {
  12735. super(...arguments);
  12736. this._nameID = 0;
  12737. this._value = null;
  12738. this._dataType = -1;
  12739. }
  12740. static create(nameID, value, shaderDataType, commandBuffer) {
  12741. var cmd;
  12742. cmd = SetGlobalShaderDataCMD._pool.length > 0 ? SetGlobalShaderDataCMD._pool.pop() : new SetGlobalShaderDataCMD();
  12743. cmd._nameID = nameID;
  12744. cmd._value = value;
  12745. cmd._dataType = shaderDataType;
  12746. cmd._commandBuffer = commandBuffer;
  12747. return cmd;
  12748. }
  12749. run() {
  12750. var shaderData = this._commandBuffer._camera.scene._shaderValues;
  12751. switch (this._dataType) {
  12752. case exports.ShaderDataType.Int:
  12753. shaderData.setInt(this._nameID, this._value);
  12754. break;
  12755. case exports.ShaderDataType.Number:
  12756. shaderData.setNumber(this._nameID, this._value);
  12757. break;
  12758. case exports.ShaderDataType.Bool:
  12759. shaderData.setBool(this._nameID, this._value);
  12760. break;
  12761. case exports.ShaderDataType.Matrix4x4:
  12762. shaderData.setMatrix4x4(this._nameID, this._value);
  12763. break;
  12764. case exports.ShaderDataType.Quaternion:
  12765. shaderData.setQuaternion(this._nameID, this._value);
  12766. break;
  12767. case exports.ShaderDataType.Texture:
  12768. shaderData.setTexture(this._nameID, this._value);
  12769. break;
  12770. case exports.ShaderDataType.Vector4:
  12771. shaderData.setVector(this._nameID, this._value);
  12772. break;
  12773. case exports.ShaderDataType.Vector2:
  12774. shaderData.setVector2(this._nameID, this._value);
  12775. break;
  12776. case exports.ShaderDataType.Vector3:
  12777. shaderData.setVector3(this._nameID, this._value);
  12778. break;
  12779. case exports.ShaderDataType.Buffer:
  12780. shaderData.setBuffer(this._nameID, this._value);
  12781. break;
  12782. default:
  12783. throw "no type shaderValue on this CommendBuffer";
  12784. }
  12785. }
  12786. recover() {
  12787. SetGlobalShaderDataCMD._pool.push(this);
  12788. this._nameID = 0;
  12789. this._value = null;
  12790. this._dataType = -1;
  12791. }
  12792. }
  12793. SetGlobalShaderDataCMD._pool = [];
  12794. class CommandBuffer {
  12795. constructor() {
  12796. this._camera = null;
  12797. this._commands = [];
  12798. }
  12799. _apply() {
  12800. for (var i = 0, n = this._commands.length; i < n; i++)
  12801. this._commands[i].run();
  12802. }
  12803. setShaderDataTexture(shaderData, nameID, source) {
  12804. this._commands.push(SetShaderDataCMD.create(shaderData, nameID, source, exports.ShaderDataType.Texture, this));
  12805. }
  12806. setGlobalTexture(nameID, source) {
  12807. this._commands.push(SetGlobalShaderDataCMD.create(nameID, source, exports.ShaderDataType.Texture, this));
  12808. }
  12809. setShaderDataVector(shaderData, nameID, value) {
  12810. this._commands.push(SetShaderDataCMD.create(shaderData, nameID, value, exports.ShaderDataType.Vector4, this));
  12811. }
  12812. setGlobalVector(nameID, source) {
  12813. this._commands.push(SetGlobalShaderDataCMD.create(nameID, source, exports.ShaderDataType.Vector4, this));
  12814. }
  12815. setShaderDataVector3(shaderData, nameID, value) {
  12816. this._commands.push(SetShaderDataCMD.create(shaderData, nameID, value, exports.ShaderDataType.Vector3, this));
  12817. }
  12818. setGlobalVector3(nameID, source) {
  12819. this._commands.push(SetGlobalShaderDataCMD.create(nameID, source, exports.ShaderDataType.Vector3, this));
  12820. }
  12821. setShaderDataVector2(shaderData, nameID, value) {
  12822. this._commands.push(SetShaderDataCMD.create(shaderData, nameID, value, exports.ShaderDataType.Vector2, this));
  12823. }
  12824. setGlobalVector2(nameID, source) {
  12825. this._commands.push(SetGlobalShaderDataCMD.create(nameID, source, exports.ShaderDataType.Vector2, this));
  12826. }
  12827. setShaderDataNumber(shaderData, nameID, value) {
  12828. this._commands.push(SetShaderDataCMD.create(shaderData, nameID, value, exports.ShaderDataType.Number, this));
  12829. }
  12830. setGlobalNumber(nameID, source) {
  12831. this._commands.push(SetGlobalShaderDataCMD.create(nameID, source, exports.ShaderDataType.Number, this));
  12832. }
  12833. setShaderDataInt(shaderData, nameID, value) {
  12834. this._commands.push(SetShaderDataCMD.create(shaderData, nameID, value, exports.ShaderDataType.Int, this));
  12835. }
  12836. setGlobalInt(nameID, source) {
  12837. this._commands.push(SetGlobalShaderDataCMD.create(nameID, source, exports.ShaderDataType.Int, this));
  12838. }
  12839. setShaderDataMatrix(shaderData, nameID, value) {
  12840. this._commands.push(SetShaderDataCMD.create(shaderData, nameID, value, exports.ShaderDataType.Matrix4x4, this));
  12841. }
  12842. setGlobalMatrix(nameID, source) {
  12843. this._commands.push(SetGlobalShaderDataCMD.create(nameID, source, exports.ShaderDataType.Matrix4x4, this));
  12844. }
  12845. blitScreenQuad(source, dest, offsetScale = null, shader = null, shaderData = null, subShader = 0) {
  12846. this._commands.push(BlitScreenQuadCMD.create(source, dest, offsetScale, shader, shaderData, subShader, BlitScreenQuadCMD._SCREENTYPE_QUAD, this));
  12847. }
  12848. blitScreenQuadByMaterial(source, dest, offsetScale = null, material = null, subShader = 0) {
  12849. var shader;
  12850. var shaderData;
  12851. if (material) {
  12852. shader = material._shader;
  12853. shaderData = material.shaderData;
  12854. }
  12855. this._commands.push(BlitScreenQuadCMD.create(source, dest, offsetScale, shader, shaderData, subShader, BlitScreenQuadCMD._SCREENTYPE_QUAD, this));
  12856. }
  12857. blitScreenTriangle(source, dest, offsetScale = null, shader = null, shaderData = null, subShader = 0, defineCanvas = false) {
  12858. this._commands.push(BlitScreenQuadCMD.create(source, dest, offsetScale, shader, shaderData, subShader, BlitScreenQuadCMD._SCREENTYPE_TRIANGLE, this, defineCanvas));
  12859. }
  12860. setRenderTarget(renderTexture) {
  12861. this._commands.push(SetRenderTargetCMD.create(renderTexture));
  12862. }
  12863. clearRenderTarget(clearColor, clearDepth, backgroundColor, depth = 1) {
  12864. this._commands.push(ClearRenderTextureCMD.create(clearColor, clearDepth, backgroundColor, depth, this));
  12865. }
  12866. drawMesh(mesh, matrix, material, submeshIndex, subShaderIndex) {
  12867. this._commands.push(DrawMeshCMD.create(mesh, matrix, material, submeshIndex, subShaderIndex, this));
  12868. }
  12869. drawRender(render, material, subShaderIndex) {
  12870. this._commands.push(DrawRenderCMD.create(render, material, subShaderIndex, this));
  12871. }
  12872. clear() {
  12873. for (var i = 0, n = this._commands.length; i < n; i++)
  12874. this._commands[i].recover();
  12875. this._commands.length = 0;
  12876. }
  12877. }
  12878. class PostProcessRenderContext {
  12879. constructor() {
  12880. this.source = null;
  12881. this.destination = null;
  12882. this.camera = null;
  12883. this.compositeShaderData = null;
  12884. this.command = null;
  12885. this.deferredReleaseTextures = [];
  12886. }
  12887. }
  12888. class PostProcess {
  12889. constructor() {
  12890. this._compositeShader = Shader3D.find("PostProcessComposite");
  12891. this._compositeShaderData = new ShaderData();
  12892. this._effects = [];
  12893. this._enable = true;
  12894. this._context = null;
  12895. this._context = new PostProcessRenderContext();
  12896. this._context.compositeShaderData = this._compositeShaderData;
  12897. this._context.command = new CommandBuffer();
  12898. }
  12899. static __init__() {
  12900. PostProcess.SHADERDEFINE_BLOOM_LOW = Shader3D.getDefineByName("BLOOM_LOW");
  12901. PostProcess.SHADERDEFINE_BLOOM = Shader3D.getDefineByName("BLOOM");
  12902. PostProcess.SHADERDEFINE_FINALPASS = Shader3D.getDefineByName("FINALPASS");
  12903. }
  12904. get enable() {
  12905. return this._enable;
  12906. }
  12907. set enable(value) {
  12908. this._enable = value;
  12909. }
  12910. _init(camera) {
  12911. this._context.camera = camera;
  12912. this._context.command._camera = camera;
  12913. }
  12914. _render() {
  12915. var noteValue = ShaderData._SET_RUNTIME_VALUE_MODE_REFERENCE_;
  12916. Laya.ILaya.Render.supportWebGLPlusRendering && ShaderData.setRuntimeValueMode(false);
  12917. var camera = this._context.camera;
  12918. var viewport = camera.viewport;
  12919. var cameraTarget = camera._internalRenderTexture;
  12920. var screenTexture = cameraTarget;
  12921. this._context.command.clear();
  12922. this._context.source = screenTexture;
  12923. this._context.destination = cameraTarget;
  12924. this._context.compositeShaderData.clearDefine();
  12925. this._context.compositeShaderData.setTexture(PostProcess.SHADERVALUE_AUTOEXPOSURETEX, Laya.Texture2D.whiteTexture);
  12926. for (var i = 0, n = this._effects.length; i < n; i++)
  12927. this._effects[i].render(this._context);
  12928. this._compositeShaderData.addDefine(PostProcess.SHADERDEFINE_FINALPASS);
  12929. var offScreenTex = camera._offScreenRenderTexture;
  12930. var dest = offScreenTex ? offScreenTex : null;
  12931. this._context.destination = dest;
  12932. var canvasWidth = camera._getCanvasWidth(), canvasHeight = camera._getCanvasHeight();
  12933. camera._screenOffsetScale.setValue(viewport.x / canvasWidth, viewport.y / canvasHeight, viewport.width / canvasWidth, viewport.height / canvasHeight);
  12934. this._context.command.blitScreenTriangle(this._context.source, dest, camera._screenOffsetScale, this._compositeShader, this._compositeShaderData, 0, true);
  12935. RenderTexture.recoverToPool(screenTexture);
  12936. var tempRenderTextures = this._context.deferredReleaseTextures;
  12937. for (i = 0, n = tempRenderTextures.length; i < n; i++)
  12938. RenderTexture.recoverToPool(tempRenderTextures[i]);
  12939. tempRenderTextures.length = 0;
  12940. Laya.ILaya.Render.supportWebGLPlusRendering && ShaderData.setRuntimeValueMode(noteValue);
  12941. }
  12942. addEffect(effect) {
  12943. this._effects.push(effect);
  12944. }
  12945. removeEffect(effect) {
  12946. var index = this._effects.indexOf(effect);
  12947. if (index !== -1)
  12948. this._effects.splice(index, 1);
  12949. }
  12950. _applyPostProcessCommandBuffers() {
  12951. this._context.command._apply();
  12952. }
  12953. }
  12954. PostProcess.SHADERVALUE_MAINTEX = Shader3D.propertyNameToID("u_MainTex");
  12955. PostProcess.SHADERVALUE_BLOOMTEX = Shader3D.propertyNameToID("u_BloomTex");
  12956. PostProcess.SHADERVALUE_AUTOEXPOSURETEX = Shader3D.propertyNameToID("u_AutoExposureTex");
  12957. PostProcess.SHADERVALUE_BLOOM_DIRTTEX = Shader3D.propertyNameToID("u_Bloom_DirtTex");
  12958. PostProcess.SHADERVALUE_BLOOMTEX_TEXELSIZE = Shader3D.propertyNameToID("u_BloomTex_TexelSize");
  12959. PostProcess.SHADERVALUE_BLOOM_DIRTTILEOFFSET = Shader3D.propertyNameToID("u_Bloom_DirtTileOffset");
  12960. PostProcess.SHADERVALUE_BLOOM_SETTINGS = Shader3D.propertyNameToID("u_Bloom_Settings");
  12961. PostProcess.SHADERVALUE_BLOOM_COLOR = Shader3D.propertyNameToID("u_Bloom_Color");
  12962. class AnimationTransform3D extends Laya.EventDispatcher {
  12963. constructor(owner) {
  12964. super();
  12965. this._owner = owner;
  12966. this._children = [];
  12967. this._localMatrix = new Float32Array(16);
  12968. this._localPosition = new Vector3();
  12969. this._localRotation = new Quaternion();
  12970. this._localScale = new Vector3();
  12971. this._worldMatrix = new Float32Array(16);
  12972. this._localQuaternionUpdate = false;
  12973. this._locaEulerlUpdate = false;
  12974. this._localUpdate = false;
  12975. this._worldUpdate = true;
  12976. }
  12977. _getlocalMatrix() {
  12978. if (this._localUpdate) {
  12979. Utils3D._createAffineTransformationArray(this._localPosition, this._localRotation, this._localScale, this._localMatrix);
  12980. this._localUpdate = false;
  12981. }
  12982. return this._localMatrix;
  12983. }
  12984. _onWorldTransform() {
  12985. if (!this._worldUpdate) {
  12986. this._worldUpdate = true;
  12987. this.event(Laya.Event.TRANSFORM_CHANGED);
  12988. for (var i = 0, n = this._children.length; i < n; i++)
  12989. this._children[i]._onWorldTransform();
  12990. }
  12991. }
  12992. get localPosition() {
  12993. return this._localPosition;
  12994. }
  12995. set localPosition(value) {
  12996. this._localPosition = value;
  12997. this._localUpdate = true;
  12998. this._onWorldTransform();
  12999. }
  13000. get localRotation() {
  13001. if (this._localQuaternionUpdate) {
  13002. var euler = this._localRotationEuler;
  13003. Quaternion.createFromYawPitchRoll(euler.y / AnimationTransform3D._angleToRandin, euler.x / AnimationTransform3D._angleToRandin, euler.z / AnimationTransform3D._angleToRandin, this._localRotation);
  13004. this._localQuaternionUpdate = false;
  13005. }
  13006. return this._localRotation;
  13007. }
  13008. set localRotation(value) {
  13009. this._localRotation = value;
  13010. this._locaEulerlUpdate = true;
  13011. this._localQuaternionUpdate = false;
  13012. this._localUpdate = true;
  13013. this._onWorldTransform();
  13014. }
  13015. get localScale() {
  13016. return this._localScale;
  13017. }
  13018. set localScale(value) {
  13019. this._localScale = value;
  13020. this._localUpdate = true;
  13021. this._onWorldTransform();
  13022. }
  13023. get localRotationEuler() {
  13024. if (this._locaEulerlUpdate) {
  13025. this._localRotation.getYawPitchRoll(AnimationTransform3D._tempVector3);
  13026. var euler = AnimationTransform3D._tempVector3;
  13027. var localRotationEuler = this._localRotationEuler;
  13028. localRotationEuler.x = euler.y * AnimationTransform3D._angleToRandin;
  13029. localRotationEuler.y = euler.x * AnimationTransform3D._angleToRandin;
  13030. localRotationEuler.z = euler.z * AnimationTransform3D._angleToRandin;
  13031. this._locaEulerlUpdate = false;
  13032. }
  13033. return this._localRotationEuler;
  13034. }
  13035. set localRotationEuler(value) {
  13036. this._localRotationEuler = value;
  13037. this._locaEulerlUpdate = false;
  13038. this._localQuaternionUpdate = true;
  13039. this._localUpdate = true;
  13040. this._onWorldTransform();
  13041. }
  13042. getWorldMatrix() {
  13043. if (this._worldUpdate) {
  13044. if (this._parent != null) {
  13045. Utils3D.matrix4x4MultiplyFFF(this._parent.getWorldMatrix(), this._getlocalMatrix(), this._worldMatrix);
  13046. }
  13047. else {
  13048. var e = this._worldMatrix;
  13049. e[1] = e[2] = e[3] = e[4] = e[6] = e[7] = e[8] = e[9] = e[11] = e[12] = e[13] = e[14] = 0;
  13050. e[0] = e[5] = e[10] = e[15] = 1;
  13051. }
  13052. this._worldUpdate = false;
  13053. }
  13054. return this._worldMatrix;
  13055. }
  13056. setParent(value) {
  13057. if (this._parent !== value) {
  13058. if (this._parent) {
  13059. var parentChilds = this._parent._children;
  13060. var index = parentChilds.indexOf(this);
  13061. parentChilds.splice(index, 1);
  13062. }
  13063. if (value) {
  13064. value._children.push(this);
  13065. (value) && (this._onWorldTransform());
  13066. }
  13067. this._parent = value;
  13068. }
  13069. }
  13070. }
  13071. AnimationTransform3D._tempVector3 = new Vector3();
  13072. AnimationTransform3D._angleToRandin = 180 / Math.PI;
  13073. class AnimationNode {
  13074. constructor() {
  13075. this._parent = null;
  13076. this.name = null;
  13077. this._worldMatrixIndex = 0;
  13078. this._children = [];
  13079. this.transform = new AnimationTransform3D(this);
  13080. }
  13081. addChild(child) {
  13082. child._parent = this;
  13083. child.transform.setParent(this.transform);
  13084. this._children.push(child);
  13085. }
  13086. removeChild(child) {
  13087. var index = this._children.indexOf(child);
  13088. (index !== -1) && (this._children.splice(index, 1));
  13089. }
  13090. getChildByName(name) {
  13091. for (var i = 0, n = this._children.length; i < n; i++) {
  13092. var child = this._children[i];
  13093. if (child.name === name)
  13094. return child;
  13095. }
  13096. return null;
  13097. }
  13098. getChildByIndex(index) {
  13099. return this._children[index];
  13100. }
  13101. getChildCount() {
  13102. return this._children.length;
  13103. }
  13104. cloneTo(destObject) {
  13105. var destNode = destObject;
  13106. destNode.name = this.name;
  13107. for (var i = 0, n = this._children.length; i < n; i++) {
  13108. var child = this._children[i];
  13109. var destChild = child.clone();
  13110. destNode.addChild(destChild);
  13111. var transform = child.transform;
  13112. var destTransform = destChild.transform;
  13113. var destLocalPosition = destTransform.localPosition;
  13114. var destLocalRotation = destTransform.localRotation;
  13115. var destLocalScale = destTransform.localScale;
  13116. transform.localPosition.cloneTo(destLocalPosition);
  13117. transform.localRotation.cloneTo(destLocalRotation);
  13118. transform.localScale.cloneTo(destLocalScale);
  13119. destTransform.localPosition = destLocalPosition;
  13120. destTransform.localRotation = destLocalRotation;
  13121. destTransform.localScale = destLocalScale;
  13122. }
  13123. }
  13124. clone() {
  13125. var dest = new AnimationNode();
  13126. this.cloneTo(dest);
  13127. return dest;
  13128. }
  13129. _cloneNative(localPositions, localRotations, localScales, animationNodeWorldMatrixs, animationNodeParentIndices, parentIndex, avatar) {
  13130. var curID = avatar._nativeCurCloneCount;
  13131. animationNodeParentIndices[curID] = parentIndex;
  13132. var dest = new AnimationNode();
  13133. dest._worldMatrixIndex = curID;
  13134. this._cloneToNative(dest, localPositions, localRotations, localScales, animationNodeWorldMatrixs, animationNodeParentIndices, curID, avatar);
  13135. return dest;
  13136. }
  13137. _cloneToNative(destObject, localPositions, localRotations, localScales, animationNodeWorldMatrixs, animationNodeParentIndices, parentIndex, avatar) {
  13138. var destNode = destObject;
  13139. destNode.name = this.name;
  13140. for (var i = 0, n = this._children.length; i < n; i++) {
  13141. var child = this._children[i];
  13142. avatar._nativeCurCloneCount++;
  13143. var destChild = child._cloneNative(localPositions, localRotations, localScales, animationNodeWorldMatrixs, animationNodeParentIndices, parentIndex, avatar);
  13144. destNode.addChild(destChild);
  13145. var transform = child.transform;
  13146. var destTransform = destChild.transform;
  13147. var destLocalPosition = destTransform.localPosition;
  13148. var destLocalRotation = destTransform.localRotation;
  13149. var destLocalScale = destTransform.localScale;
  13150. transform.localPosition.cloneTo(destLocalPosition);
  13151. transform.localRotation.cloneTo(destLocalRotation);
  13152. transform.localScale.cloneTo(destLocalScale);
  13153. destTransform.localPosition = destLocalPosition;
  13154. destTransform.localRotation = destLocalRotation;
  13155. destTransform.localScale = destLocalScale;
  13156. }
  13157. }
  13158. }
  13159. class Avatar extends Laya.Resource {
  13160. constructor() {
  13161. super();
  13162. this._nativeNodeCount = 0;
  13163. this._nativeCurCloneCount = 0;
  13164. }
  13165. static _parse(data, propertyParams = null, constructParams = null) {
  13166. var avatar = new Avatar();
  13167. avatar._rootNode = new AnimationNode();
  13168. if (data.version) {
  13169. var rootNode = data.rootNode;
  13170. (rootNode) && (avatar._parseNode(rootNode, avatar._rootNode));
  13171. }
  13172. return avatar;
  13173. }
  13174. static load(url, complete) {
  13175. Laya.ILaya.loader.create(url, complete, null, Avatar.AVATAR);
  13176. }
  13177. _initCloneToAnimator(destNode, destAnimator) {
  13178. destAnimator._avatarNodeMap[destNode.name] = destNode;
  13179. for (var i = 0, n = destNode.getChildCount(); i < n; i++)
  13180. this._initCloneToAnimator(destNode.getChildByIndex(i), destAnimator);
  13181. }
  13182. _parseNode(nodaData, node) {
  13183. var name = nodaData.props.name;
  13184. node.name = name;
  13185. var props = nodaData.props;
  13186. var transform = node.transform;
  13187. var pos = transform.localPosition;
  13188. var rot = transform.localRotation;
  13189. var sca = transform.localScale;
  13190. pos.fromArray(props.translate);
  13191. rot.fromArray(props.rotation);
  13192. sca.fromArray(props.scale);
  13193. transform.localPosition = pos;
  13194. transform.localRotation = rot;
  13195. transform.localScale = sca;
  13196. var childrenData = nodaData.child;
  13197. for (var j = 0, n = childrenData.length; j < n; j++) {
  13198. var childData = childrenData[j];
  13199. var childBone = new AnimationNode();
  13200. node.addChild(childBone);
  13201. this._parseNode(childData, childBone);
  13202. }
  13203. }
  13204. _cloneDatasToAnimator(destAnimator) {
  13205. var destRoot;
  13206. destRoot = this._rootNode.clone();
  13207. var transform = this._rootNode.transform;
  13208. var destTransform = destRoot.transform;
  13209. var destPosition = destTransform.localPosition;
  13210. var destRotation = destTransform.localRotation;
  13211. var destScale = destTransform.localScale;
  13212. transform.localPosition.cloneTo(destPosition);
  13213. transform.localRotation.cloneTo(destRotation);
  13214. transform.localScale.cloneTo(destScale);
  13215. destTransform.localPosition = destPosition;
  13216. destTransform.localRotation = destRotation;
  13217. destTransform.localScale = destScale;
  13218. destAnimator._avatarNodeMap = {};
  13219. this._initCloneToAnimator(destRoot, destAnimator);
  13220. }
  13221. cloneTo(destObject) {
  13222. var destAvatar = destObject;
  13223. var destRoot = this._rootNode.clone();
  13224. destAvatar._rootNode = destRoot;
  13225. }
  13226. clone() {
  13227. var dest = new Avatar();
  13228. this.cloneTo(dest);
  13229. return dest;
  13230. }
  13231. _cloneDatasToAnimatorNative(destAnimator) {
  13232. var animationNodeLocalPositions = new Float32Array(this._nativeNodeCount * 3);
  13233. var animationNodeLocalRotations = new Float32Array(this._nativeNodeCount * 4);
  13234. var animationNodeLocalScales = new Float32Array(this._nativeNodeCount * 3);
  13235. var animationNodeWorldMatrixs = new Float32Array(this._nativeNodeCount * 16);
  13236. var animationNodeParentIndices = new Int16Array(this._nativeNodeCount);
  13237. destAnimator._animationNodeLocalPositions = animationNodeLocalPositions;
  13238. destAnimator._animationNodeLocalRotations = animationNodeLocalRotations;
  13239. destAnimator._animationNodeLocalScales = animationNodeLocalScales;
  13240. destAnimator._animationNodeWorldMatrixs = animationNodeWorldMatrixs;
  13241. destAnimator._animationNodeParentIndices = animationNodeParentIndices;
  13242. this._nativeCurCloneCount = 0;
  13243. var destRoot = this._rootNode._cloneNative(animationNodeLocalPositions, animationNodeLocalRotations, animationNodeLocalScales, animationNodeWorldMatrixs, animationNodeParentIndices, -1, this);
  13244. var transform = this._rootNode.transform;
  13245. var destTransform = destRoot.transform;
  13246. var destPosition = destTransform.localPosition;
  13247. var destRotation = destTransform.localRotation;
  13248. var destScale = destTransform.localScale;
  13249. transform.localPosition.cloneTo(destPosition);
  13250. transform.localRotation.cloneTo(destRotation);
  13251. transform.localScale.cloneTo(destScale);
  13252. destTransform.localPosition = destPosition;
  13253. destTransform.localRotation = destRotation;
  13254. destTransform.localScale = destScale;
  13255. destAnimator._avatarNodeMap = {};
  13256. this._initCloneToAnimator(destRoot, destAnimator);
  13257. }
  13258. }
  13259. Avatar.AVATAR = "AVATAR";
  13260. class Material extends Laya.Resource {
  13261. constructor() {
  13262. super();
  13263. this._shaderValues = null;
  13264. this._shaderValues = new ShaderData(this);
  13265. this.renderQueue = Material.RENDERQUEUE_OPAQUE;
  13266. this._alphaTest = false;
  13267. }
  13268. static load(url, complete) {
  13269. Laya.Laya.loader.create(url, complete, null, Material.MATERIAL);
  13270. }
  13271. static __initDefine__() {
  13272. Material.SHADERDEFINE_ALPHATEST = Shader3D.getDefineByName("ALPHATEST");
  13273. }
  13274. static _parse(data, propertyParams = null, constructParams = null) {
  13275. var jsonData = data;
  13276. var props = jsonData.props;
  13277. var material;
  13278. var classType = props.type;
  13279. var clas = Laya.ClassUtils.getRegClass(classType);
  13280. if (clas)
  13281. material = new clas();
  13282. else
  13283. throw ('_getSprite3DHierarchyInnerUrls 错误: ' + data.type + ' 不是类');
  13284. switch (jsonData.version) {
  13285. case "LAYAMATERIAL:01":
  13286. case "LAYAMATERIAL:02":
  13287. var i, n;
  13288. for (var key in props) {
  13289. switch (key) {
  13290. case "type":
  13291. break;
  13292. case "vectors":
  13293. var vectors = props[key];
  13294. for (i = 0, n = vectors.length; i < n; i++) {
  13295. var vector = vectors[i];
  13296. var vectorValue = vector.value;
  13297. switch (vectorValue.length) {
  13298. case 2:
  13299. material[vector.name] = new Vector2(vectorValue[0], vectorValue[1]);
  13300. break;
  13301. case 3:
  13302. material[vector.name] = new Vector3(vectorValue[0], vectorValue[1], vectorValue[2]);
  13303. break;
  13304. case 4:
  13305. material[vector.name] = new Vector4(vectorValue[0], vectorValue[1], vectorValue[2], vectorValue[3]);
  13306. break;
  13307. default:
  13308. throw new Error("BaseMaterial:unkonwn color length.");
  13309. }
  13310. }
  13311. break;
  13312. case "textures":
  13313. var textures = props[key];
  13314. for (i = 0, n = textures.length; i < n; i++) {
  13315. var texture = textures[i];
  13316. var path = texture.path;
  13317. (path) && (material[texture.name] = Laya.Loader.getRes(path));
  13318. }
  13319. break;
  13320. case "defines":
  13321. var defineNames = props[key];
  13322. for (i = 0, n = defineNames.length; i < n; i++) {
  13323. var define = Shader3D.getDefineByName(defineNames[i]);
  13324. material._shaderValues.addDefine(define);
  13325. }
  13326. break;
  13327. case "renderStates":
  13328. var renderStatesData = props[key];
  13329. var renderStateData = renderStatesData[0];
  13330. var mat = material;
  13331. mat.blend = renderStateData.blend;
  13332. mat.cull = renderStateData.cull;
  13333. mat.depthTest = renderStateData.depthTest;
  13334. mat.depthWrite = renderStateData.depthWrite;
  13335. mat.blendSrc = renderStateData.srcBlend;
  13336. mat.blendDst = renderStateData.dstBlend;
  13337. break;
  13338. case "cull":
  13339. material.cull = props[key];
  13340. break;
  13341. case "blend":
  13342. material.blend = props[key];
  13343. break;
  13344. case "depthWrite":
  13345. material.depthWrite = props[key];
  13346. break;
  13347. case "srcBlend":
  13348. material.blendSrc = props[key];
  13349. break;
  13350. case "dstBlend":
  13351. material.blendDst = props[key];
  13352. break;
  13353. default:
  13354. material[key] = props[key];
  13355. }
  13356. }
  13357. break;
  13358. default:
  13359. throw new Error("BaseMaterial:unkonwn version.");
  13360. }
  13361. return material;
  13362. }
  13363. get shaderData() {
  13364. return this._shaderValues;
  13365. }
  13366. get alphaTestValue() {
  13367. return this._shaderValues.getNumber(Material.ALPHATESTVALUE);
  13368. }
  13369. set alphaTestValue(value) {
  13370. this._shaderValues.setNumber(Material.ALPHATESTVALUE, value);
  13371. }
  13372. get alphaTest() {
  13373. return this._alphaTest;
  13374. }
  13375. set alphaTest(value) {
  13376. this._alphaTest = value;
  13377. if (value)
  13378. this._shaderValues.addDefine(Material.SHADERDEFINE_ALPHATEST);
  13379. else
  13380. this._shaderValues.removeDefine(Material.SHADERDEFINE_ALPHATEST);
  13381. }
  13382. get depthWrite() {
  13383. return this._shaderValues.getBool(Material.DEPTH_WRITE);
  13384. }
  13385. set depthWrite(value) {
  13386. this._shaderValues.setBool(Material.DEPTH_WRITE, value);
  13387. }
  13388. get cull() {
  13389. return this._shaderValues.getInt(Material.CULL);
  13390. }
  13391. set cull(value) {
  13392. this._shaderValues.setInt(Material.CULL, value);
  13393. }
  13394. get blend() {
  13395. return this._shaderValues.getInt(Material.BLEND);
  13396. }
  13397. set blend(value) {
  13398. this._shaderValues.setInt(Material.BLEND, value);
  13399. }
  13400. get blendSrc() {
  13401. return this._shaderValues.getInt(Material.BLEND_SRC);
  13402. }
  13403. set blendSrc(value) {
  13404. this._shaderValues.setInt(Material.BLEND_SRC, value);
  13405. }
  13406. get blendDst() {
  13407. return this._shaderValues.getInt(Material.BLEND_DST);
  13408. }
  13409. set blendDst(value) {
  13410. this._shaderValues.setInt(Material.BLEND_DST, value);
  13411. }
  13412. get depthTest() {
  13413. return this._shaderValues.getInt(Material.DEPTH_TEST);
  13414. }
  13415. set depthTest(value) {
  13416. this._shaderValues.setInt(Material.DEPTH_TEST, value);
  13417. }
  13418. _removeTetxureReference() {
  13419. var data = this._shaderValues.getData();
  13420. for (var k in data) {
  13421. var value = data[k];
  13422. if (value && value instanceof Laya.BaseTexture)
  13423. value._removeReference();
  13424. }
  13425. }
  13426. _disposeResource() {
  13427. if (this._referenceCount > 0)
  13428. this._removeTetxureReference();
  13429. this._shaderValues = null;
  13430. }
  13431. _addReference(count = 1) {
  13432. super._addReference(count);
  13433. var data = this._shaderValues.getData();
  13434. for (var k in data) {
  13435. var value = data[k];
  13436. if (value && value instanceof Laya.BaseTexture)
  13437. value._addReference();
  13438. }
  13439. }
  13440. _removeReference(count = 1) {
  13441. super._removeReference(count);
  13442. this._removeTetxureReference();
  13443. }
  13444. setShaderName(name) {
  13445. this._shader = Shader3D.find(name);
  13446. if (!this._shader)
  13447. throw new Error("BaseMaterial: unknown shader name.");
  13448. }
  13449. cloneTo(destObject) {
  13450. var destBaseMaterial = destObject;
  13451. destBaseMaterial.name = this.name;
  13452. destBaseMaterial.renderQueue = this.renderQueue;
  13453. this._shaderValues.cloneTo(destBaseMaterial._shaderValues);
  13454. }
  13455. clone() {
  13456. var dest = new Material();
  13457. this.cloneTo(dest);
  13458. return dest;
  13459. }
  13460. get _defineDatas() {
  13461. return this._shaderValues._defineDatas;
  13462. }
  13463. }
  13464. Material.MATERIAL = "MATERIAL";
  13465. Material.RENDERQUEUE_OPAQUE = 2000;
  13466. Material.RENDERQUEUE_ALPHATEST = 2450;
  13467. Material.RENDERQUEUE_TRANSPARENT = 3000;
  13468. Material.ALPHATESTVALUE = Shader3D.propertyNameToID("u_AlphaTestValue");
  13469. Material.CULL = Shader3D.propertyNameToID("s_Cull");
  13470. Material.BLEND = Shader3D.propertyNameToID("s_Blend");
  13471. Material.BLEND_SRC = Shader3D.propertyNameToID("s_BlendSrc");
  13472. Material.BLEND_DST = Shader3D.propertyNameToID("s_BlendDst");
  13473. Material.DEPTH_TEST = Shader3D.propertyNameToID("s_DepthTest");
  13474. Material.DEPTH_WRITE = Shader3D.propertyNameToID("s_DepthWrite");
  13475. Material.SHADERDEFINE_ALPHATEST = null;
  13476. class BaseMaterial {
  13477. static load(url, complete) {
  13478. Laya.Laya.loader.create(url, complete, null, Material.MATERIAL);
  13479. }
  13480. static __initDefine__() {
  13481. BaseMaterial.SHADERDEFINE_ALPHATEST = Material.SHADERDEFINE_ALPHATEST;
  13482. }
  13483. }
  13484. BaseMaterial.MATERIAL = "MATERIAL";
  13485. BaseMaterial.RENDERQUEUE_OPAQUE = 2000;
  13486. BaseMaterial.RENDERQUEUE_ALPHATEST = 2450;
  13487. BaseMaterial.RENDERQUEUE_TRANSPARENT = 3000;
  13488. BaseMaterial.ALPHATESTVALUE = Shader3D.propertyNameToID("u_AlphaTestValue");
  13489. BaseMaterial.SHADERDEFINE_ALPHATEST = null;
  13490. class RenderState {
  13491. constructor() {
  13492. this.cull = RenderState.CULL_BACK;
  13493. this.blend = RenderState.BLEND_DISABLE;
  13494. this.srcBlend = RenderState.BLENDPARAM_ONE;
  13495. this.dstBlend = RenderState.BLENDPARAM_ZERO;
  13496. this.srcBlendRGB = RenderState.BLENDPARAM_ONE;
  13497. this.dstBlendRGB = RenderState.BLENDPARAM_ZERO;
  13498. this.srcBlendAlpha = RenderState.BLENDPARAM_ONE;
  13499. this.dstBlendAlpha = RenderState.BLENDPARAM_ZERO;
  13500. this.blendConstColor = new Vector4(1, 1, 1, 1);
  13501. this.blendEquation = RenderState.BLENDEQUATION_ADD;
  13502. this.blendEquationRGB = RenderState.BLENDEQUATION_ADD;
  13503. this.blendEquationAlpha = RenderState.BLENDEQUATION_ADD;
  13504. this.depthTest = RenderState.DEPTHTEST_LEQUAL;
  13505. this.depthWrite = true;
  13506. }
  13507. cloneTo(dest) {
  13508. var destState = dest;
  13509. destState.cull = this.cull;
  13510. destState.blend = this.blend;
  13511. destState.srcBlend = this.srcBlend;
  13512. destState.dstBlend = this.dstBlend;
  13513. destState.srcBlendRGB = this.srcBlendRGB;
  13514. destState.dstBlendRGB = this.dstBlendRGB;
  13515. destState.srcBlendAlpha = this.srcBlendAlpha;
  13516. destState.dstBlendAlpha = this.dstBlendAlpha;
  13517. this.blendConstColor.cloneTo(destState.blendConstColor);
  13518. destState.blendEquation = this.blendEquation;
  13519. destState.blendEquationRGB = this.blendEquationRGB;
  13520. destState.blendEquationAlpha = this.blendEquationAlpha;
  13521. destState.depthTest = this.depthTest;
  13522. destState.depthWrite = this.depthWrite;
  13523. }
  13524. clone() {
  13525. var dest = new RenderState();
  13526. this.cloneTo(dest);
  13527. return dest;
  13528. }
  13529. }
  13530. RenderState.CULL_NONE = 0;
  13531. RenderState.CULL_FRONT = 1;
  13532. RenderState.CULL_BACK = 2;
  13533. RenderState.BLEND_DISABLE = 0;
  13534. RenderState.BLEND_ENABLE_ALL = 1;
  13535. RenderState.BLEND_ENABLE_SEPERATE = 2;
  13536. RenderState.BLENDPARAM_ZERO = 0;
  13537. RenderState.BLENDPARAM_ONE = 1;
  13538. RenderState.BLENDPARAM_SRC_COLOR = 0x0300;
  13539. RenderState.BLENDPARAM_ONE_MINUS_SRC_COLOR = 0x0301;
  13540. RenderState.BLENDPARAM_DST_COLOR = 0x0306;
  13541. RenderState.BLENDPARAM_ONE_MINUS_DST_COLOR = 0x0307;
  13542. RenderState.BLENDPARAM_SRC_ALPHA = 0x0302;
  13543. RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA = 0x0303;
  13544. RenderState.BLENDPARAM_DST_ALPHA = 0x0304;
  13545. RenderState.BLENDPARAM_ONE_MINUS_DST_ALPHA = 0x0305;
  13546. RenderState.BLENDPARAM_SRC_ALPHA_SATURATE = 0x0308;
  13547. RenderState.BLENDEQUATION_ADD = 0x8006;
  13548. RenderState.BLENDEQUATION_SUBTRACT = 0x800A;
  13549. RenderState.BLENDEQUATION_REVERSE_SUBTRACT = 0x800B;
  13550. RenderState.DEPTHTEST_OFF = 0;
  13551. RenderState.DEPTHTEST_NEVER = 0x0200;
  13552. RenderState.DEPTHTEST_LESS = 0x0201;
  13553. RenderState.DEPTHTEST_EQUAL = 0x0202;
  13554. RenderState.DEPTHTEST_LEQUAL = 0x0203;
  13555. RenderState.DEPTHTEST_GREATER = 0x0204;
  13556. RenderState.DEPTHTEST_NOTEQUAL = 0x0205;
  13557. RenderState.DEPTHTEST_GEQUAL = 0x0206;
  13558. RenderState.DEPTHTEST_ALWAYS = 0x0207;
  13559. class BlinnPhongMaterial extends Material {
  13560. constructor() {
  13561. super();
  13562. this._enableVertexColor = false;
  13563. this.setShaderName("BLINNPHONG");
  13564. this._albedoIntensity = 1.0;
  13565. this._albedoColor = new Vector4(1.0, 1.0, 1.0, 1.0);
  13566. var sv = this._shaderValues;
  13567. sv.setVector(BlinnPhongMaterial.ALBEDOCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  13568. sv.setVector(BlinnPhongMaterial.MATERIALSPECULAR, new Vector4(1.0, 1.0, 1.0, 1.0));
  13569. sv.setNumber(BlinnPhongMaterial.SHININESS, 0.078125);
  13570. sv.setNumber(Material.ALPHATESTVALUE, 0.5);
  13571. sv.setVector(BlinnPhongMaterial.TILINGOFFSET, new Vector4(1.0, 1.0, 0.0, 0.0));
  13572. this._enableLighting = true;
  13573. this.renderMode = BlinnPhongMaterial.RENDERMODE_OPAQUE;
  13574. }
  13575. static __initDefine__() {
  13576. BlinnPhongMaterial.SHADERDEFINE_DIFFUSEMAP = Shader3D.getDefineByName("DIFFUSEMAP");
  13577. BlinnPhongMaterial.SHADERDEFINE_NORMALMAP = Shader3D.getDefineByName("NORMALMAP");
  13578. BlinnPhongMaterial.SHADERDEFINE_SPECULARMAP = Shader3D.getDefineByName("SPECULARMAP");
  13579. BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  13580. BlinnPhongMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR = Shader3D.getDefineByName("ENABLEVERTEXCOLOR");
  13581. }
  13582. get _ColorR() {
  13583. return this._albedoColor.x;
  13584. }
  13585. set _ColorR(value) {
  13586. this._albedoColor.x = value;
  13587. this.albedoColor = this._albedoColor;
  13588. }
  13589. get _ColorG() {
  13590. return this._albedoColor.y;
  13591. }
  13592. set _ColorG(value) {
  13593. this._albedoColor.y = value;
  13594. this.albedoColor = this._albedoColor;
  13595. }
  13596. get _ColorB() {
  13597. return this._albedoColor.z;
  13598. }
  13599. set _ColorB(value) {
  13600. this._albedoColor.z = value;
  13601. this.albedoColor = this._albedoColor;
  13602. }
  13603. get _ColorA() {
  13604. return this._albedoColor.w;
  13605. }
  13606. set _ColorA(value) {
  13607. this._albedoColor.w = value;
  13608. this.albedoColor = this._albedoColor;
  13609. }
  13610. get _Color() {
  13611. return this._shaderValues.getVector(BlinnPhongMaterial.ALBEDOCOLOR);
  13612. }
  13613. set _Color(value) {
  13614. this.albedoColor = value;
  13615. }
  13616. get _SpecColorR() {
  13617. return this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).x;
  13618. }
  13619. set _SpecColorR(value) {
  13620. this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).x = value;
  13621. }
  13622. get _SpecColorG() {
  13623. return this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).y;
  13624. }
  13625. set _SpecColorG(value) {
  13626. this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).y = value;
  13627. }
  13628. get _SpecColorB() {
  13629. return this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).z;
  13630. }
  13631. set _SpecColorB(value) {
  13632. this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).z = value;
  13633. }
  13634. get _SpecColorA() {
  13635. return this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).w;
  13636. }
  13637. set _SpecColorA(value) {
  13638. this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR).w = value;
  13639. }
  13640. get _SpecColor() {
  13641. return this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR);
  13642. }
  13643. set _SpecColor(value) {
  13644. this.specularColor = value;
  13645. }
  13646. get _AlbedoIntensity() {
  13647. return this._albedoIntensity;
  13648. }
  13649. set _AlbedoIntensity(value) {
  13650. if (this._albedoIntensity !== value) {
  13651. var finalAlbedo = this._shaderValues.getVector(BlinnPhongMaterial.ALBEDOCOLOR);
  13652. Vector4.scale(this._albedoColor, value, finalAlbedo);
  13653. this._albedoIntensity = value;
  13654. this._shaderValues.setVector(BlinnPhongMaterial.ALBEDOCOLOR, finalAlbedo);
  13655. }
  13656. }
  13657. get _Shininess() {
  13658. return this._shaderValues.getNumber(BlinnPhongMaterial.SHININESS);
  13659. }
  13660. set _Shininess(value) {
  13661. value = Math.max(0.0, Math.min(1.0, value));
  13662. this._shaderValues.setNumber(BlinnPhongMaterial.SHININESS, value);
  13663. }
  13664. get _MainTex_STX() {
  13665. return this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET).x;
  13666. }
  13667. set _MainTex_STX(x) {
  13668. var tilOff = this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET);
  13669. tilOff.x = x;
  13670. this.tilingOffset = tilOff;
  13671. }
  13672. get _MainTex_STY() {
  13673. return this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET).y;
  13674. }
  13675. set _MainTex_STY(y) {
  13676. var tilOff = this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET);
  13677. tilOff.y = y;
  13678. this.tilingOffset = tilOff;
  13679. }
  13680. get _MainTex_STZ() {
  13681. return this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET).z;
  13682. }
  13683. set _MainTex_STZ(z) {
  13684. var tilOff = this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET);
  13685. tilOff.z = z;
  13686. this.tilingOffset = tilOff;
  13687. }
  13688. get _MainTex_STW() {
  13689. return this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET).w;
  13690. }
  13691. set _MainTex_STW(w) {
  13692. var tilOff = this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET);
  13693. tilOff.w = w;
  13694. this.tilingOffset = tilOff;
  13695. }
  13696. get _MainTex_ST() {
  13697. return this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET);
  13698. }
  13699. set _MainTex_ST(value) {
  13700. this.tilingOffset = value;
  13701. }
  13702. get _Cutoff() {
  13703. return this.alphaTestValue;
  13704. }
  13705. set _Cutoff(value) {
  13706. this.alphaTestValue = value;
  13707. }
  13708. set renderMode(value) {
  13709. switch (value) {
  13710. case BlinnPhongMaterial.RENDERMODE_OPAQUE:
  13711. this.alphaTest = false;
  13712. this.renderQueue = Material.RENDERQUEUE_OPAQUE;
  13713. this.depthWrite = true;
  13714. this.cull = RenderState.CULL_BACK;
  13715. this.blend = RenderState.BLEND_DISABLE;
  13716. this.depthTest = RenderState.DEPTHTEST_LESS;
  13717. break;
  13718. case BlinnPhongMaterial.RENDERMODE_CUTOUT:
  13719. this.renderQueue = Material.RENDERQUEUE_ALPHATEST;
  13720. this.alphaTest = true;
  13721. this.depthWrite = true;
  13722. this.cull = RenderState.CULL_BACK;
  13723. this.blend = RenderState.BLEND_DISABLE;
  13724. this.depthTest = RenderState.DEPTHTEST_LESS;
  13725. break;
  13726. case BlinnPhongMaterial.RENDERMODE_TRANSPARENT:
  13727. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  13728. this.alphaTest = false;
  13729. this.depthWrite = false;
  13730. this.cull = RenderState.CULL_BACK;
  13731. this.blend = RenderState.BLEND_ENABLE_ALL;
  13732. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  13733. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  13734. this.depthTest = RenderState.DEPTHTEST_LESS;
  13735. break;
  13736. default:
  13737. throw new Error("Material:renderMode value error.");
  13738. }
  13739. }
  13740. get enableVertexColor() {
  13741. return this._enableVertexColor;
  13742. }
  13743. set enableVertexColor(value) {
  13744. this._enableVertexColor = value;
  13745. if (value)
  13746. this._shaderValues.addDefine(BlinnPhongMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR);
  13747. else
  13748. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR);
  13749. }
  13750. get tilingOffsetX() {
  13751. return this._MainTex_STX;
  13752. }
  13753. set tilingOffsetX(x) {
  13754. this._MainTex_STX = x;
  13755. }
  13756. get tilingOffsetY() {
  13757. return this._MainTex_STY;
  13758. }
  13759. set tilingOffsetY(y) {
  13760. this._MainTex_STY = y;
  13761. }
  13762. get tilingOffsetZ() {
  13763. return this._MainTex_STZ;
  13764. }
  13765. set tilingOffsetZ(z) {
  13766. this._MainTex_STZ = z;
  13767. }
  13768. get tilingOffsetW() {
  13769. return this._MainTex_STW;
  13770. }
  13771. set tilingOffsetW(w) {
  13772. this._MainTex_STW = w;
  13773. }
  13774. get tilingOffset() {
  13775. return this._shaderValues.getVector(BlinnPhongMaterial.TILINGOFFSET);
  13776. }
  13777. set tilingOffset(value) {
  13778. if (value) {
  13779. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  13780. this._shaderValues.addDefine(BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET);
  13781. else
  13782. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET);
  13783. }
  13784. else {
  13785. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET);
  13786. }
  13787. this._shaderValues.setVector(BlinnPhongMaterial.TILINGOFFSET, value);
  13788. }
  13789. get albedoColorR() {
  13790. return this._ColorR;
  13791. }
  13792. set albedoColorR(value) {
  13793. this._ColorR = value;
  13794. }
  13795. get albedoColorG() {
  13796. return this._ColorG;
  13797. }
  13798. set albedoColorG(value) {
  13799. this._ColorG = value;
  13800. }
  13801. get albedoColorB() {
  13802. return this._ColorB;
  13803. }
  13804. set albedoColorB(value) {
  13805. this._ColorB = value;
  13806. }
  13807. get albedoColorA() {
  13808. return this._ColorA;
  13809. }
  13810. set albedoColorA(value) {
  13811. this._ColorA = value;
  13812. }
  13813. get albedoColor() {
  13814. return this._albedoColor;
  13815. }
  13816. set albedoColor(value) {
  13817. var finalAlbedo = this._shaderValues.getVector(BlinnPhongMaterial.ALBEDOCOLOR);
  13818. Vector4.scale(value, this._albedoIntensity, finalAlbedo);
  13819. this._albedoColor = value;
  13820. this._shaderValues.setVector(BlinnPhongMaterial.ALBEDOCOLOR, finalAlbedo);
  13821. }
  13822. get albedoIntensity() {
  13823. return this._albedoIntensity;
  13824. }
  13825. set albedoIntensity(value) {
  13826. this._AlbedoIntensity = value;
  13827. }
  13828. get specularColorR() {
  13829. return this._SpecColorR;
  13830. }
  13831. set specularColorR(value) {
  13832. this._SpecColorR = value;
  13833. }
  13834. get specularColorG() {
  13835. return this._SpecColorG;
  13836. }
  13837. set specularColorG(value) {
  13838. this._SpecColorG = value;
  13839. }
  13840. get specularColorB() {
  13841. return this._SpecColorB;
  13842. }
  13843. set specularColorB(value) {
  13844. this._SpecColorB = value;
  13845. }
  13846. get specularColorA() {
  13847. return this._SpecColorA;
  13848. }
  13849. set specularColorA(value) {
  13850. this._SpecColorA = value;
  13851. }
  13852. get specularColor() {
  13853. return this._shaderValues.getVector(BlinnPhongMaterial.MATERIALSPECULAR);
  13854. }
  13855. set specularColor(value) {
  13856. this._shaderValues.setVector(BlinnPhongMaterial.MATERIALSPECULAR, value);
  13857. }
  13858. get shininess() {
  13859. return this._Shininess;
  13860. }
  13861. set shininess(value) {
  13862. this._Shininess = value;
  13863. }
  13864. get albedoTexture() {
  13865. return this._shaderValues.getTexture(BlinnPhongMaterial.ALBEDOTEXTURE);
  13866. }
  13867. set albedoTexture(value) {
  13868. if (value)
  13869. this._shaderValues.addDefine(BlinnPhongMaterial.SHADERDEFINE_DIFFUSEMAP);
  13870. else
  13871. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_DIFFUSEMAP);
  13872. this._shaderValues.setTexture(BlinnPhongMaterial.ALBEDOTEXTURE, value);
  13873. }
  13874. get normalTexture() {
  13875. return this._shaderValues.getTexture(BlinnPhongMaterial.NORMALTEXTURE);
  13876. }
  13877. set normalTexture(value) {
  13878. if (value)
  13879. this._shaderValues.addDefine(BlinnPhongMaterial.SHADERDEFINE_NORMALMAP);
  13880. else
  13881. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_NORMALMAP);
  13882. this._shaderValues.setTexture(BlinnPhongMaterial.NORMALTEXTURE, value);
  13883. }
  13884. get specularTexture() {
  13885. return this._shaderValues.getTexture(BlinnPhongMaterial.SPECULARTEXTURE);
  13886. }
  13887. set specularTexture(value) {
  13888. if (value)
  13889. this._shaderValues.addDefine(BlinnPhongMaterial.SHADERDEFINE_SPECULARMAP);
  13890. else
  13891. this._shaderValues.removeDefine(BlinnPhongMaterial.SHADERDEFINE_SPECULARMAP);
  13892. this._shaderValues.setTexture(BlinnPhongMaterial.SPECULARTEXTURE, value);
  13893. }
  13894. clone() {
  13895. var dest = new BlinnPhongMaterial();
  13896. this.cloneTo(dest);
  13897. return dest;
  13898. }
  13899. cloneTo(destObject) {
  13900. super.cloneTo(destObject);
  13901. var destMaterial = destObject;
  13902. destMaterial._enableLighting = this._enableLighting;
  13903. destMaterial._albedoIntensity = this._albedoIntensity;
  13904. destMaterial._enableVertexColor = this._enableVertexColor;
  13905. this._albedoColor.cloneTo(destMaterial._albedoColor);
  13906. }
  13907. }
  13908. BlinnPhongMaterial.RENDERMODE_OPAQUE = 0;
  13909. BlinnPhongMaterial.RENDERMODE_CUTOUT = 1;
  13910. BlinnPhongMaterial.RENDERMODE_TRANSPARENT = 2;
  13911. BlinnPhongMaterial.ALBEDOTEXTURE = Shader3D.propertyNameToID("u_DiffuseTexture");
  13912. BlinnPhongMaterial.NORMALTEXTURE = Shader3D.propertyNameToID("u_NormalTexture");
  13913. BlinnPhongMaterial.SPECULARTEXTURE = Shader3D.propertyNameToID("u_SpecularTexture");
  13914. BlinnPhongMaterial.ALBEDOCOLOR = Shader3D.propertyNameToID("u_DiffuseColor");
  13915. BlinnPhongMaterial.MATERIALSPECULAR = Shader3D.propertyNameToID("u_MaterialSpecular");
  13916. BlinnPhongMaterial.SHININESS = Shader3D.propertyNameToID("u_Shininess");
  13917. BlinnPhongMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  13918. class EffectMaterial extends Material {
  13919. constructor() {
  13920. super();
  13921. this.setShaderName("Effect");
  13922. this._color = new Vector4(1.0, 1.0, 1.0, 1.0);
  13923. this._shaderValues.setVector(EffectMaterial.TINTCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  13924. this.renderMode = EffectMaterial.RENDERMODE_ADDTIVE;
  13925. }
  13926. static __initDefine__() {
  13927. EffectMaterial.SHADERDEFINE_MAINTEXTURE = Shader3D.getDefineByName("MAINTEXTURE");
  13928. EffectMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  13929. EffectMaterial.SHADERDEFINE_ADDTIVEFOG = Shader3D.getDefineByName("ADDTIVEFOG");
  13930. }
  13931. get _TintColorR() {
  13932. return this._color.x;
  13933. }
  13934. set _TintColorR(value) {
  13935. this._color.x = value;
  13936. this.color = this._color;
  13937. }
  13938. get _TintColorG() {
  13939. return this._color.y;
  13940. }
  13941. set _TintColorG(value) {
  13942. this._color.y = value;
  13943. this.color = this._color;
  13944. }
  13945. get _TintColorB() {
  13946. return this._color.z;
  13947. }
  13948. set _TintColorB(value) {
  13949. this._color.z = value;
  13950. this.color = this._color;
  13951. }
  13952. get _TintColorA() {
  13953. return this._color.w;
  13954. }
  13955. set _TintColorA(value) {
  13956. this._color.w = value;
  13957. this.color = this._color;
  13958. }
  13959. get _TintColor() {
  13960. return this._shaderValues.getVector(EffectMaterial.TINTCOLOR);
  13961. }
  13962. set _TintColor(value) {
  13963. this.color = value;
  13964. }
  13965. get _MainTex_STX() {
  13966. return this._shaderValues.getVector(EffectMaterial.TILINGOFFSET).x;
  13967. }
  13968. set _MainTex_STX(x) {
  13969. var tilOff = this._shaderValues.getVector(EffectMaterial.TILINGOFFSET);
  13970. tilOff.x = x;
  13971. this.tilingOffset = tilOff;
  13972. }
  13973. get _MainTex_STY() {
  13974. return this._shaderValues.getVector(EffectMaterial.TILINGOFFSET).y;
  13975. }
  13976. set _MainTex_STY(y) {
  13977. var tilOff = this._shaderValues.getVector(EffectMaterial.TILINGOFFSET);
  13978. tilOff.y = y;
  13979. this.tilingOffset = tilOff;
  13980. }
  13981. get _MainTex_STZ() {
  13982. return this._shaderValues.getVector(EffectMaterial.TILINGOFFSET).z;
  13983. }
  13984. set _MainTex_STZ(z) {
  13985. var tilOff = this._shaderValues.getVector(EffectMaterial.TILINGOFFSET);
  13986. tilOff.z = z;
  13987. this.tilingOffset = tilOff;
  13988. }
  13989. get _MainTex_STW() {
  13990. return this._shaderValues.getVector(EffectMaterial.TILINGOFFSET).w;
  13991. }
  13992. set _MainTex_STW(w) {
  13993. var tilOff = this._shaderValues.getVector(EffectMaterial.TILINGOFFSET);
  13994. tilOff.w = w;
  13995. this.tilingOffset = tilOff;
  13996. }
  13997. get _MainTex_ST() {
  13998. return this._shaderValues.getVector(EffectMaterial.TILINGOFFSET);
  13999. }
  14000. set _MainTex_ST(value) {
  14001. this.tilingOffset = value;
  14002. }
  14003. set renderMode(value) {
  14004. switch (value) {
  14005. case EffectMaterial.RENDERMODE_ADDTIVE:
  14006. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  14007. this.alphaTest = false;
  14008. this.depthWrite = false;
  14009. this.cull = RenderState.CULL_NONE;
  14010. this.blend = RenderState.BLEND_ENABLE_ALL;
  14011. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  14012. this.blendDst = RenderState.BLENDPARAM_ONE;
  14013. this.depthTest = RenderState.DEPTHTEST_LESS;
  14014. this._shaderValues.addDefine(EffectMaterial.SHADERDEFINE_ADDTIVEFOG);
  14015. break;
  14016. case EffectMaterial.RENDERMODE_ALPHABLENDED:
  14017. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  14018. this.alphaTest = false;
  14019. this.depthWrite = false;
  14020. this.cull = RenderState.CULL_NONE;
  14021. this.blend = RenderState.BLEND_ENABLE_ALL;
  14022. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  14023. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  14024. this.depthTest = RenderState.DEPTHTEST_LESS;
  14025. this._shaderValues.removeDefine(EffectMaterial.SHADERDEFINE_ADDTIVEFOG);
  14026. break;
  14027. default:
  14028. throw new Error("MeshEffectMaterial : renderMode value error.");
  14029. }
  14030. }
  14031. get colorR() {
  14032. return this._TintColorR;
  14033. }
  14034. set colorR(value) {
  14035. this._TintColorR = value;
  14036. }
  14037. get colorG() {
  14038. return this._TintColorG;
  14039. }
  14040. set colorG(value) {
  14041. this._TintColorG = value;
  14042. }
  14043. get colorB() {
  14044. return this._TintColorB;
  14045. }
  14046. set colorB(value) {
  14047. this._TintColorB = value;
  14048. }
  14049. get colorA() {
  14050. return this._TintColorA;
  14051. }
  14052. set colorA(value) {
  14053. this._TintColorA = value;
  14054. }
  14055. get color() {
  14056. return this._shaderValues.getVector(EffectMaterial.TINTCOLOR);
  14057. }
  14058. set color(value) {
  14059. this._shaderValues.setVector(EffectMaterial.TINTCOLOR, value);
  14060. }
  14061. get texture() {
  14062. return this._shaderValues.getTexture(EffectMaterial.MAINTEXTURE);
  14063. }
  14064. set texture(value) {
  14065. if (value)
  14066. this._shaderValues.addDefine(EffectMaterial.SHADERDEFINE_MAINTEXTURE);
  14067. else
  14068. this._shaderValues.removeDefine(EffectMaterial.SHADERDEFINE_MAINTEXTURE);
  14069. this._shaderValues.setTexture(EffectMaterial.MAINTEXTURE, value);
  14070. }
  14071. get tilingOffsetX() {
  14072. return this._MainTex_STX;
  14073. }
  14074. set tilingOffsetX(x) {
  14075. this._MainTex_STX = x;
  14076. }
  14077. get tilingOffsetY() {
  14078. return this._MainTex_STY;
  14079. }
  14080. set tilingOffsetY(y) {
  14081. this._MainTex_STY = y;
  14082. }
  14083. get tilingOffsetZ() {
  14084. return this._MainTex_STZ;
  14085. }
  14086. set tilingOffsetZ(z) {
  14087. this._MainTex_STZ = z;
  14088. }
  14089. get tilingOffsetW() {
  14090. return this._MainTex_STW;
  14091. }
  14092. set tilingOffsetW(w) {
  14093. this._MainTex_STW = w;
  14094. }
  14095. get tilingOffset() {
  14096. return this._shaderValues.getVector(EffectMaterial.TILINGOFFSET);
  14097. }
  14098. set tilingOffset(value) {
  14099. if (value) {
  14100. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  14101. this._shaderValues.addDefine(EffectMaterial.SHADERDEFINE_TILINGOFFSET);
  14102. else
  14103. this._shaderValues.removeDefine(EffectMaterial.SHADERDEFINE_TILINGOFFSET);
  14104. }
  14105. else {
  14106. this._shaderValues.removeDefine(EffectMaterial.SHADERDEFINE_TILINGOFFSET);
  14107. }
  14108. this._shaderValues.setVector(EffectMaterial.TILINGOFFSET, value);
  14109. }
  14110. clone() {
  14111. var dest = new EffectMaterial();
  14112. this.cloneTo(dest);
  14113. return dest;
  14114. }
  14115. }
  14116. EffectMaterial.RENDERMODE_ADDTIVE = 0;
  14117. EffectMaterial.RENDERMODE_ALPHABLENDED = 1;
  14118. EffectMaterial.MAINTEXTURE = Shader3D.propertyNameToID("u_AlbedoTexture");
  14119. EffectMaterial.TINTCOLOR = Shader3D.propertyNameToID("u_AlbedoColor");
  14120. EffectMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  14121. class ExtendTerrainMaterial extends Material {
  14122. constructor() {
  14123. super();
  14124. this._enableLighting = true;
  14125. this.setShaderName("ExtendTerrain");
  14126. this.renderMode = ExtendTerrainMaterial.RENDERMODE_OPAQUE;
  14127. }
  14128. static __initDefine__() {
  14129. ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1 = Shader3D.getDefineByName("ExtendTerrain_DETAIL_NUM1");
  14130. ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2 = Shader3D.getDefineByName("ExtendTerrain_DETAIL_NUM2");
  14131. ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3 = Shader3D.getDefineByName("ExtendTerrain_DETAIL_NUM3");
  14132. ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4 = Shader3D.getDefineByName("ExtendTerrain_DETAIL_NUM4");
  14133. ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5 = Shader3D.getDefineByName("ExtendTerrain_DETAIL_NUM5");
  14134. }
  14135. get splatAlphaTexture() {
  14136. return this._shaderValues.getTexture(ExtendTerrainMaterial.SPLATALPHATEXTURE);
  14137. }
  14138. set splatAlphaTexture(value) {
  14139. this._shaderValues.setTexture(ExtendTerrainMaterial.SPLATALPHATEXTURE, value);
  14140. }
  14141. get diffuseTexture1() {
  14142. return this._shaderValues.getTexture(ExtendTerrainMaterial.DIFFUSETEXTURE1);
  14143. }
  14144. set diffuseTexture1(value) {
  14145. this._shaderValues.setTexture(ExtendTerrainMaterial.DIFFUSETEXTURE1, value);
  14146. this._setDetailNum(1);
  14147. }
  14148. get diffuseTexture2() {
  14149. return this._shaderValues.getTexture(ExtendTerrainMaterial.DIFFUSETEXTURE2);
  14150. }
  14151. set diffuseTexture2(value) {
  14152. this._shaderValues.setTexture(ExtendTerrainMaterial.DIFFUSETEXTURE2, value);
  14153. this._setDetailNum(2);
  14154. }
  14155. get diffuseTexture3() {
  14156. return this._shaderValues.getTexture(ExtendTerrainMaterial.DIFFUSETEXTURE3);
  14157. }
  14158. set diffuseTexture3(value) {
  14159. this._shaderValues.setTexture(ExtendTerrainMaterial.DIFFUSETEXTURE3, value);
  14160. this._setDetailNum(3);
  14161. }
  14162. get diffuseTexture4() {
  14163. return this._shaderValues.getTexture(ExtendTerrainMaterial.DIFFUSETEXTURE4);
  14164. }
  14165. set diffuseTexture4(value) {
  14166. this._shaderValues.setTexture(ExtendTerrainMaterial.DIFFUSETEXTURE4, value);
  14167. this._setDetailNum(4);
  14168. }
  14169. get diffuseTexture5() {
  14170. return this._shaderValues.getTexture(ExtendTerrainMaterial.DIFFUSETEXTURE5);
  14171. }
  14172. set diffuseTexture5(value) {
  14173. this._shaderValues.setTexture(ExtendTerrainMaterial.DIFFUSETEXTURE5, value);
  14174. this._setDetailNum(5);
  14175. }
  14176. set diffuseScaleOffset1(scaleOffset1) {
  14177. this._shaderValues.setVector(ExtendTerrainMaterial.DIFFUSESCALEOFFSET1, scaleOffset1);
  14178. }
  14179. set diffuseScaleOffset2(scaleOffset2) {
  14180. this._shaderValues.setVector(ExtendTerrainMaterial.DIFFUSESCALEOFFSET2, scaleOffset2);
  14181. }
  14182. set diffuseScaleOffset3(scaleOffset3) {
  14183. this._shaderValues.setVector(ExtendTerrainMaterial.DIFFUSESCALEOFFSET3, scaleOffset3);
  14184. }
  14185. set diffuseScaleOffset4(scaleOffset4) {
  14186. this._shaderValues.setVector(ExtendTerrainMaterial.DIFFUSESCALEOFFSET4, scaleOffset4);
  14187. }
  14188. set diffuseScaleOffset5(scaleOffset5) {
  14189. this._shaderValues.setVector(ExtendTerrainMaterial.DIFFUSESCALEOFFSET5, scaleOffset5);
  14190. }
  14191. set renderMode(value) {
  14192. switch (value) {
  14193. case ExtendTerrainMaterial.RENDERMODE_OPAQUE:
  14194. this.renderQueue = Material.RENDERQUEUE_OPAQUE;
  14195. this.depthWrite = true;
  14196. this.cull = RenderState.CULL_BACK;
  14197. this.blend = RenderState.BLEND_DISABLE;
  14198. this.depthTest = RenderState.DEPTHTEST_LESS;
  14199. break;
  14200. case ExtendTerrainMaterial.RENDERMODE_TRANSPARENT:
  14201. this.renderQueue = Material.RENDERQUEUE_OPAQUE;
  14202. this.depthWrite = false;
  14203. this.cull = RenderState.CULL_BACK;
  14204. this.blend = RenderState.BLEND_ENABLE_ALL;
  14205. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  14206. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  14207. this.depthTest = RenderState.DEPTHTEST_LEQUAL;
  14208. break;
  14209. default:
  14210. throw new Error("ExtendTerrainMaterial:renderMode value error.");
  14211. }
  14212. }
  14213. _setDetailNum(value) {
  14214. switch (value) {
  14215. case 1:
  14216. this._shaderValues.addDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1);
  14217. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2);
  14218. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3);
  14219. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4);
  14220. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5);
  14221. break;
  14222. case 2:
  14223. this._shaderValues.addDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2);
  14224. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1);
  14225. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3);
  14226. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4);
  14227. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5);
  14228. break;
  14229. case 3:
  14230. this._shaderValues.addDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3);
  14231. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1);
  14232. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2);
  14233. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4);
  14234. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5);
  14235. break;
  14236. case 4:
  14237. this._shaderValues.addDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4);
  14238. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1);
  14239. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2);
  14240. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3);
  14241. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5);
  14242. break;
  14243. case 5:
  14244. this._shaderValues.addDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5);
  14245. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1);
  14246. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2);
  14247. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3);
  14248. this._shaderValues.removeDefine(ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4);
  14249. break;
  14250. }
  14251. }
  14252. clone() {
  14253. var dest = new ExtendTerrainMaterial();
  14254. this.cloneTo(dest);
  14255. return dest;
  14256. }
  14257. }
  14258. ExtendTerrainMaterial.RENDERMODE_OPAQUE = 1;
  14259. ExtendTerrainMaterial.RENDERMODE_TRANSPARENT = 2;
  14260. ExtendTerrainMaterial.SPLATALPHATEXTURE = Shader3D.propertyNameToID("u_SplatAlphaTexture");
  14261. ExtendTerrainMaterial.DIFFUSETEXTURE1 = Shader3D.propertyNameToID("u_DiffuseTexture1");
  14262. ExtendTerrainMaterial.DIFFUSETEXTURE2 = Shader3D.propertyNameToID("u_DiffuseTexture2");
  14263. ExtendTerrainMaterial.DIFFUSETEXTURE3 = Shader3D.propertyNameToID("u_DiffuseTexture3");
  14264. ExtendTerrainMaterial.DIFFUSETEXTURE4 = Shader3D.propertyNameToID("u_DiffuseTexture4");
  14265. ExtendTerrainMaterial.DIFFUSETEXTURE5 = Shader3D.propertyNameToID("u_DiffuseTexture5");
  14266. ExtendTerrainMaterial.DIFFUSESCALEOFFSET1 = Shader3D.propertyNameToID("u_DiffuseScaleOffset1");
  14267. ExtendTerrainMaterial.DIFFUSESCALEOFFSET2 = Shader3D.propertyNameToID("u_DiffuseScaleOffset2");
  14268. ExtendTerrainMaterial.DIFFUSESCALEOFFSET3 = Shader3D.propertyNameToID("u_DiffuseScaleOffset3");
  14269. ExtendTerrainMaterial.DIFFUSESCALEOFFSET4 = Shader3D.propertyNameToID("u_DiffuseScaleOffset4");
  14270. ExtendTerrainMaterial.DIFFUSESCALEOFFSET5 = Shader3D.propertyNameToID("u_DiffuseScaleOffset5");
  14271. (function (PBRRenderMode) {
  14272. PBRRenderMode[PBRRenderMode["Opaque"] = 0] = "Opaque";
  14273. PBRRenderMode[PBRRenderMode["Cutout"] = 1] = "Cutout";
  14274. PBRRenderMode[PBRRenderMode["Fade"] = 2] = "Fade";
  14275. PBRRenderMode[PBRRenderMode["Transparent"] = 3] = "Transparent";
  14276. })(exports.PBRRenderMode || (exports.PBRRenderMode = {}));
  14277. class PBRMaterial extends Material {
  14278. constructor() {
  14279. super();
  14280. this._enableEmission = false;
  14281. this._shaderValues.setVector(PBRMaterial.ALBEDOCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  14282. this._shaderValues.setVector(PBRMaterial.EMISSIONCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  14283. this._shaderValues.setNumber(PBRMaterial.SMOOTHNESS, 0.5);
  14284. this._shaderValues.setNumber(PBRMaterial.SMOOTHNESSSCALE, 1.0);
  14285. this._shaderValues.setNumber(PBRMaterial.OCCLUSIONSTRENGTH, 1.0);
  14286. this._shaderValues.setNumber(PBRMaterial.NORMALSCALE, 1.0);
  14287. this._shaderValues.setNumber(PBRMaterial.PARALLAXSCALE, 0.001);
  14288. this._shaderValues.setNumber(Material.ALPHATESTVALUE, 0.5);
  14289. this.renderMode = exports.PBRRenderMode.Opaque;
  14290. }
  14291. static __init__() {
  14292. PBRMaterial.SHADERDEFINE_ALBEDOTEXTURE = Shader3D.getDefineByName("ALBEDOTEXTURE");
  14293. PBRMaterial.SHADERDEFINE_NORMALTEXTURE = Shader3D.getDefineByName("NORMALTEXTURE");
  14294. PBRMaterial.SHADERDEFINE_PARALLAXTEXTURE = Shader3D.getDefineByName("PARALLAXTEXTURE");
  14295. PBRMaterial.SHADERDEFINE_OCCLUSIONTEXTURE = Shader3D.getDefineByName("OCCLUSIONTEXTURE");
  14296. PBRMaterial.SHADERDEFINE_EMISSION = Shader3D.getDefineByName("EMISSION");
  14297. PBRMaterial.SHADERDEFINE_EMISSIONTEXTURE = Shader3D.getDefineByName("EMISSIONTEXTURE");
  14298. PBRMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  14299. PBRMaterial.SHADERDEFINE_TRANSPARENTBLEND = Shader3D.getDefineByName("TRANSPARENTBLEND");
  14300. PBRMaterial.SHADERDEFINE_LAYA_PBR_BRDF_HIGH = Shader3D.getDefineByName("LAYA_PBR_BRDF_HIGH");
  14301. PBRMaterial.SHADERDEFINE_LAYA_PBR_BRDF_LOW = Shader3D.getDefineByName("LAYA_PBR_BRDF_LOW");
  14302. }
  14303. get albedoColor() {
  14304. return this._shaderValues.getVector(PBRMaterial.ALBEDOCOLOR);
  14305. }
  14306. set albedoColor(value) {
  14307. this._shaderValues.setVector(PBRMaterial.ALBEDOCOLOR, value);
  14308. }
  14309. get albedoTexture() {
  14310. return this._shaderValues.getTexture(PBRMaterial.ALBEDOTEXTURE);
  14311. }
  14312. set albedoTexture(value) {
  14313. if (value)
  14314. this._shaderValues.addDefine(PBRMaterial.SHADERDEFINE_ALBEDOTEXTURE);
  14315. else
  14316. this._shaderValues.removeDefine(PBRMaterial.SHADERDEFINE_ALBEDOTEXTURE);
  14317. this._shaderValues.setTexture(PBRMaterial.ALBEDOTEXTURE, value);
  14318. }
  14319. get normalTexture() {
  14320. return this._shaderValues.getTexture(PBRMaterial.NORMALTEXTURE);
  14321. }
  14322. set normalTexture(value) {
  14323. if (value) {
  14324. this._shaderValues.addDefine(PBRMaterial.SHADERDEFINE_NORMALTEXTURE);
  14325. }
  14326. else {
  14327. this._shaderValues.removeDefine(PBRMaterial.SHADERDEFINE_NORMALTEXTURE);
  14328. }
  14329. this._shaderValues.setTexture(PBRMaterial.NORMALTEXTURE, value);
  14330. }
  14331. get normalTextureScale() {
  14332. return this._shaderValues.getNumber(PBRMaterial.NORMALSCALE);
  14333. }
  14334. set normalTextureScale(value) {
  14335. this._shaderValues.setNumber(PBRMaterial.NORMALSCALE, value);
  14336. }
  14337. get parallaxTexture() {
  14338. return this._shaderValues.getTexture(PBRMaterial.PARALLAXTEXTURE);
  14339. }
  14340. set parallaxTexture(value) {
  14341. if (value)
  14342. this._shaderValues.addDefine(PBRMaterial.SHADERDEFINE_PARALLAXTEXTURE);
  14343. else
  14344. this._shaderValues.removeDefine(PBRMaterial.SHADERDEFINE_PARALLAXTEXTURE);
  14345. this._shaderValues.setTexture(PBRMaterial.PARALLAXTEXTURE, value);
  14346. }
  14347. get parallaxTextureScale() {
  14348. return this._shaderValues.getNumber(PBRMaterial.PARALLAXSCALE);
  14349. }
  14350. set parallaxTextureScale(value) {
  14351. this._shaderValues.setNumber(PBRMaterial.PARALLAXSCALE, Math.max(0.005, Math.min(0.08, value)));
  14352. }
  14353. get occlusionTexture() {
  14354. return this._shaderValues.getTexture(PBRMaterial.OCCLUSIONTEXTURE);
  14355. }
  14356. set occlusionTexture(value) {
  14357. if (value)
  14358. this._shaderValues.addDefine(PBRMaterial.SHADERDEFINE_OCCLUSIONTEXTURE);
  14359. else
  14360. this._shaderValues.removeDefine(PBRMaterial.SHADERDEFINE_OCCLUSIONTEXTURE);
  14361. this._shaderValues.setTexture(PBRMaterial.OCCLUSIONTEXTURE, value);
  14362. }
  14363. get occlusionTextureStrength() {
  14364. return this._shaderValues.getNumber(PBRMaterial.OCCLUSIONSTRENGTH);
  14365. }
  14366. set occlusionTextureStrength(value) {
  14367. this._shaderValues.setNumber(PBRMaterial.OCCLUSIONSTRENGTH, Math.max(0.0, Math.min(1.0, value)));
  14368. }
  14369. get smoothness() {
  14370. return this._shaderValues.getNumber(PBRMaterial.SMOOTHNESS);
  14371. }
  14372. set smoothness(value) {
  14373. this._shaderValues.setNumber(PBRMaterial.SMOOTHNESS, Math.max(0.0, Math.min(1.0, value)));
  14374. }
  14375. get smoothnessTextureScale() {
  14376. return this._shaderValues.getNumber(PBRMaterial.SMOOTHNESSSCALE);
  14377. }
  14378. set smoothnessTextureScale(value) {
  14379. this._shaderValues.setNumber(PBRMaterial.SMOOTHNESSSCALE, Math.max(0.0, Math.min(1.0, value)));
  14380. }
  14381. get enableEmission() {
  14382. return this._enableEmission;
  14383. }
  14384. set enableEmission(value) {
  14385. if (value)
  14386. this._shaderValues.addDefine(PBRMaterial.SHADERDEFINE_EMISSION);
  14387. else
  14388. this._shaderValues.removeDefine(PBRMaterial.SHADERDEFINE_EMISSION);
  14389. this._enableEmission = value;
  14390. }
  14391. get emissionColor() {
  14392. return this._shaderValues.getVector(PBRMaterial.EMISSIONCOLOR);
  14393. }
  14394. set emissionColor(value) {
  14395. this._shaderValues.setVector(PBRMaterial.EMISSIONCOLOR, value);
  14396. }
  14397. get emissionTexture() {
  14398. return this._shaderValues.getTexture(PBRMaterial.EMISSIONTEXTURE);
  14399. }
  14400. set emissionTexture(value) {
  14401. if (value)
  14402. this._shaderValues.addDefine(PBRMaterial.SHADERDEFINE_EMISSIONTEXTURE);
  14403. else
  14404. this._shaderValues.removeDefine(PBRMaterial.SHADERDEFINE_EMISSIONTEXTURE);
  14405. this._shaderValues.setTexture(PBRMaterial.EMISSIONTEXTURE, value);
  14406. }
  14407. get tilingOffset() {
  14408. return this._shaderValues.getVector(PBRMaterial.TILINGOFFSET);
  14409. }
  14410. set tilingOffset(value) {
  14411. if (value) {
  14412. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  14413. this._shaderValues.addDefine(PBRMaterial.SHADERDEFINE_TILINGOFFSET);
  14414. else
  14415. this._shaderValues.removeDefine(PBRMaterial.SHADERDEFINE_TILINGOFFSET);
  14416. }
  14417. else {
  14418. this._shaderValues.removeDefine(PBRMaterial.SHADERDEFINE_TILINGOFFSET);
  14419. }
  14420. this._shaderValues.setVector(PBRMaterial.TILINGOFFSET, value);
  14421. }
  14422. set renderMode(value) {
  14423. switch (value) {
  14424. case exports.PBRRenderMode.Opaque:
  14425. this.alphaTest = false;
  14426. this.renderQueue = Material.RENDERQUEUE_OPAQUE;
  14427. this.depthWrite = true;
  14428. this.cull = RenderState.CULL_BACK;
  14429. this.blend = RenderState.BLEND_DISABLE;
  14430. this.depthTest = RenderState.DEPTHTEST_LESS;
  14431. this._shaderValues.removeDefine(PBRMaterial.SHADERDEFINE_TRANSPARENTBLEND);
  14432. break;
  14433. case exports.PBRRenderMode.Cutout:
  14434. this.renderQueue = Material.RENDERQUEUE_ALPHATEST;
  14435. this.alphaTest = true;
  14436. this.depthWrite = true;
  14437. this.cull = RenderState.CULL_BACK;
  14438. this.blend = RenderState.BLEND_DISABLE;
  14439. this.depthTest = RenderState.DEPTHTEST_LESS;
  14440. this._shaderValues.removeDefine(PBRMaterial.SHADERDEFINE_TRANSPARENTBLEND);
  14441. break;
  14442. case exports.PBRRenderMode.Fade:
  14443. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  14444. this.alphaTest = false;
  14445. this.depthWrite = false;
  14446. this.cull = RenderState.CULL_BACK;
  14447. this.blend = RenderState.BLEND_ENABLE_ALL;
  14448. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  14449. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  14450. this.depthTest = RenderState.DEPTHTEST_LESS;
  14451. this._shaderValues.removeDefine(PBRMaterial.SHADERDEFINE_TRANSPARENTBLEND);
  14452. break;
  14453. case exports.PBRRenderMode.Transparent:
  14454. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  14455. this.alphaTest = false;
  14456. this.depthWrite = false;
  14457. this.cull = RenderState.CULL_BACK;
  14458. this.blend = RenderState.BLEND_ENABLE_ALL;
  14459. this.blendSrc = RenderState.BLENDPARAM_ONE;
  14460. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  14461. this.depthTest = RenderState.DEPTHTEST_LESS;
  14462. this._shaderValues.addDefine(PBRMaterial.SHADERDEFINE_TRANSPARENTBLEND);
  14463. break;
  14464. default:
  14465. throw new Error("PBRMaterial:unknown renderMode value.");
  14466. }
  14467. }
  14468. get enableReflection() {
  14469. return true;
  14470. }
  14471. set enableReflection(value) {
  14472. }
  14473. }
  14474. PBRMaterial.ALBEDOTEXTURE = Shader3D.propertyNameToID("u_AlbedoTexture");
  14475. PBRMaterial.ALBEDOCOLOR = Shader3D.propertyNameToID("u_AlbedoColor");
  14476. PBRMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  14477. PBRMaterial.NORMALTEXTURE = Shader3D.propertyNameToID("u_NormalTexture");
  14478. PBRMaterial.NORMALSCALE = Shader3D.propertyNameToID("u_NormalScale");
  14479. PBRMaterial.SMOOTHNESS = Shader3D.propertyNameToID("u_Smoothness");
  14480. PBRMaterial.SMOOTHNESSSCALE = Shader3D.propertyNameToID("u_SmoothnessScale");
  14481. PBRMaterial.OCCLUSIONTEXTURE = Shader3D.propertyNameToID("u_OcclusionTexture");
  14482. PBRMaterial.OCCLUSIONSTRENGTH = Shader3D.propertyNameToID("u_occlusionStrength");
  14483. PBRMaterial.PARALLAXTEXTURE = Shader3D.propertyNameToID("u_ParallaxTexture");
  14484. PBRMaterial.PARALLAXSCALE = Shader3D.propertyNameToID("u_ParallaxScale");
  14485. PBRMaterial.EMISSIONTEXTURE = Shader3D.propertyNameToID("u_EmissionTexture");
  14486. PBRMaterial.EMISSIONCOLOR = Shader3D.propertyNameToID("u_EmissionColor");
  14487. PBRMaterial.renderQuality = exports.PBRRenderQuality.High;
  14488. var PBRPS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n\tprecision highp int;\r\n#else\r\n\tprecision mediump float;\r\n\tprecision mediump int;\r\n#endif\r\n\r\n#define SETUP_BRDF_INPUT specularSetup\r\n\r\n#include \"Lighting.glsl\";\r\n#include \"PBRFSInput.glsl\";\r\n#include \"LayaPBRBRDF.glsl\";\r\n#include \"GlobalIllumination.glsl\";\r\n#include \"Shadow.glsl\"\r\n#include \"PBRCore.glsl\";\r\n\r\nvoid main()\r\n{\r\n\tfragmentForward();\r\n}";
  14489. var PBRVS = "#include \"PBRVSInput.glsl\";\r\n#include \"Lighting.glsl\";\r\n#include \"PBRVertex.glsl\";\r\n\r\nvoid main()\r\n{\r\n\tvertexForward();\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}";
  14490. var PBRShadowCasterPS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n\tprecision highp int;\r\n#else\r\n\tprecision mediump float;\r\n\tprecision mediump int;\r\n#endif\r\n\r\n#include \"ShadowCasterFS.glsl\"\r\n\r\nvoid main()\r\n{\r\n\tgl_FragColor=shadowCasterFragment();\r\n}";
  14491. var PBRShadowCasterVS = "#include \"ShadowCasterVS.glsl\"\r\n\r\nvoid main()\r\n{\r\n\tvec4 positionCS = shadowCasterVertex();\r\n\tgl_Position=remapGLPositionZ(positionCS);\r\n}";
  14492. var DepthNormalsTextureVS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n\tprecision highp int;\r\n#else\r\n\tprecision mediump float;\r\n\tprecision mediump int;\r\n#endif\r\n\r\n#include \"Lighting.glsl\";\r\n\r\nattribute vec4 a_Position;\r\nattribute vec3 a_Normal;\r\n\r\n#ifdef BONE\r\n\tconst int c_MaxBoneCount = 24;\r\n\tattribute vec4 a_BoneIndices;\r\n\tattribute vec4 a_BoneWeights;\r\n\tuniform mat4 u_Bones[c_MaxBoneCount];\r\n#endif\r\n\r\n#ifdef GPU_INSTANCE\r\n\tattribute mat4 a_WorldMat;\r\n#else\r\n\tuniform mat4 u_WorldMat;\r\n#endif\r\n\r\nuniform mat4 u_ViewProjection;\r\nuniform vec4 u_ProjectionParams;\r\n\r\n//传入法线\r\nvarying vec4 depthNormals;\r\n\r\n\r\nvec4 depthNormalsVertex()\r\n{\r\n\tmat4 worldMat;\r\n\t#ifdef GPU_INSTANCE\r\n\t\tworldMat = a_WorldMat;\r\n\t#else\r\n\t\tworldMat = u_WorldMat;\r\n\t#endif\r\n\t\r\n\t#ifdef BONE\r\n\t\tmat4 skinTransform;\r\n\t \t#ifdef SIMPLEBONE\r\n\t\t\tfloat currentPixelPos;\r\n\t\t\t#ifdef GPU_INSTANCE\r\n\t\t\t\tcurrentPixelPos = a_SimpleTextureParams.x+a_SimpleTextureParams.y;\r\n\t\t\t#else\r\n\t\t\t\tcurrentPixelPos = u_SimpleAnimatorParams.x+u_SimpleAnimatorParams.y;\r\n\t\t\t#endif\r\n\t\t\tfloat offset = 1.0/u_SimpleAnimatorTextureSize;\r\n\t\t\tskinTransform = loadMatFromTexture(currentPixelPos,int(a_BoneIndices.x),offset) * a_BoneWeights.x;\r\n\t\t\tskinTransform += loadMatFromTexture(currentPixelPos,int(a_BoneIndices.y),offset) * a_BoneWeights.y;\r\n\t\t\tskinTransform += loadMatFromTexture(currentPixelPos,int(a_BoneIndices.z),offset) * a_BoneWeights.z;\r\n\t\t\tskinTransform += loadMatFromTexture(currentPixelPos,int(a_BoneIndices.w),offset) * a_BoneWeights.w;\r\n\t\t#else\r\n\t\t\tskinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;\r\n\t\t\tskinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;\r\n\t\t\tskinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;\r\n\t\t\tskinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;\r\n\t\t#endif\r\n\t\tworldMat = worldMat * skinTransform;\r\n\t#endif\r\n\r\n\tvec4 positionWS = worldMat * a_Position;\r\n\r\n\tmat3 worldInvMat;\r\n\t#ifdef BONE\r\n\t\tworldInvMat=INVERSE_MAT(mat3(worldMat*skinTransform));\r\n\t#else\r\n\t\tworldInvMat=INVERSE_MAT(mat3(worldMat));\r\n\t#endif \r\n\r\n\tvec3 normalWS = normalize(a_Normal*worldInvMat);//if no normalize will cause precision problem\r\n\r\n\tdepthNormals.xyz = normalWS;\r\n\tvec4 positionCS = u_ViewProjection * positionWS;\r\n\tdepthNormals.w = (positionCS.z * 2.0 - positionCS.w)*u_ProjectionParams.w;\r\n\t\r\n return positionCS;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tvec4 positionCS = depthNormalsVertex();\r\n\tgl_Position=remapGLPositionZ(positionCS);\r\n}";
  14493. var DepthNormalsTextureFS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n\tprecision highp int;\r\n#else\r\n\tprecision mediump float;\r\n\tprecision mediump int;\r\n#endif\r\n#include \"DepthNormalUtil.glsl\";\r\n\r\nvarying vec4 depthNormals;\r\n\r\nvoid main()\r\n{\r\n\tgl_FragColor=depthNormalsFragment(depthNormals);\r\n}";
  14494. class ShaderVariable {
  14495. constructor() {
  14496. this.textureID = -1;
  14497. }
  14498. }
  14499. class ShaderInstance extends Laya.Resource {
  14500. constructor(vs, ps, attributeMap, uniformMap, shaderPass) {
  14501. super();
  14502. this._stateParamsMap = [];
  14503. this._uploadMark = -1;
  14504. this._uploadRenderType = -1;
  14505. this._vs = vs;
  14506. this._ps = ps;
  14507. this._attributeMap = attributeMap;
  14508. this._uniformMap = uniformMap;
  14509. this._shaderPass = shaderPass;
  14510. this._globaluniformMap = [];
  14511. this._create();
  14512. this.lock = true;
  14513. }
  14514. _create() {
  14515. var gl = Laya.LayaGL.instance;
  14516. this._program = gl.createProgram();
  14517. this._vshader = this._createShader(gl, this._vs, gl.VERTEX_SHADER);
  14518. this._pshader = this._createShader(gl, this._ps, gl.FRAGMENT_SHADER);
  14519. gl.attachShader(this._program, this._vshader);
  14520. gl.attachShader(this._program, this._pshader);
  14521. for (var k in this._attributeMap)
  14522. gl.bindAttribLocation(this._program, this._attributeMap[k], k);
  14523. gl.linkProgram(this._program);
  14524. if (!Laya.Render.isConchApp && Shader3D.debugMode && !gl.getProgramParameter(this._program, gl.LINK_STATUS))
  14525. throw gl.getProgramInfoLog(this._program);
  14526. var sceneParms = [];
  14527. var cameraParms = [];
  14528. var spriteParms = [];
  14529. var materialParms = [];
  14530. var customParms = [];
  14531. this._customUniformParamsMap = [];
  14532. var nUniformNum = gl.getProgramParameter(this._program, gl.ACTIVE_UNIFORMS);
  14533. Laya.WebGLContext.useProgram(gl, this._program);
  14534. this._curActTexIndex = 0;
  14535. var one, i, n;
  14536. for (i = 0; i < nUniformNum; i++) {
  14537. var uniformData = gl.getActiveUniform(this._program, i);
  14538. var uniName = uniformData.name;
  14539. one = new ShaderVariable();
  14540. one.location = gl.getUniformLocation(this._program, uniName);
  14541. if (uniName.indexOf('[0]') > 0) {
  14542. one.name = uniName = uniName.substr(0, uniName.length - 3);
  14543. one.isArray = true;
  14544. }
  14545. else {
  14546. one.name = uniName;
  14547. one.isArray = false;
  14548. }
  14549. one.type = uniformData.type;
  14550. this._addShaderUnifiormFun(one);
  14551. var uniformPeriod = this._uniformMap[uniName];
  14552. if (uniformPeriod != null) {
  14553. one.dataOffset = Shader3D.propertyNameToID(uniName);
  14554. switch (uniformPeriod) {
  14555. case Shader3D.PERIOD_CUSTOM:
  14556. customParms.push(one);
  14557. break;
  14558. case Shader3D.PERIOD_MATERIAL:
  14559. materialParms.push(one);
  14560. break;
  14561. case Shader3D.PERIOD_SPRITE:
  14562. spriteParms.push(one);
  14563. break;
  14564. case Shader3D.PERIOD_CAMERA:
  14565. cameraParms.push(one);
  14566. break;
  14567. case Shader3D.PERIOD_SCENE:
  14568. sceneParms.push(one);
  14569. break;
  14570. default:
  14571. throw new Error("Shader3D: period is unkonw.");
  14572. }
  14573. }
  14574. else {
  14575. one.dataOffset = Shader3D.propertyNameToID(uniName);
  14576. this._globaluniformMap[uniName] = Shader3D.PERIOD_SCENE;
  14577. sceneParms.push(one);
  14578. }
  14579. }
  14580. this._sceneUniformParamsMap = Laya.LayaGL.instance.createCommandEncoder(sceneParms.length * 4 * 5 + 4, 64, true);
  14581. for (i = 0, n = sceneParms.length; i < n; i++)
  14582. this._sceneUniformParamsMap.addShaderUniform(sceneParms[i]);
  14583. this._cameraUniformParamsMap = Laya.LayaGL.instance.createCommandEncoder(cameraParms.length * 4 * 5 + 4, 64, true);
  14584. for (i = 0, n = cameraParms.length; i < n; i++)
  14585. this._cameraUniformParamsMap.addShaderUniform(cameraParms[i]);
  14586. this._spriteUniformParamsMap = Laya.LayaGL.instance.createCommandEncoder(spriteParms.length * 4 * 5 + 4, 64, true);
  14587. for (i = 0, n = spriteParms.length; i < n; i++)
  14588. this._spriteUniformParamsMap.addShaderUniform(spriteParms[i]);
  14589. this._materialUniformParamsMap = Laya.LayaGL.instance.createCommandEncoder(materialParms.length * 4 * 5 + 4, 64, true);
  14590. for (i = 0, n = materialParms.length; i < n; i++)
  14591. this._materialUniformParamsMap.addShaderUniform(materialParms[i]);
  14592. this._customUniformParamsMap.length = customParms.length;
  14593. for (i = 0, n = customParms.length; i < n; i++) {
  14594. var custom = customParms[i];
  14595. this._customUniformParamsMap[custom.dataOffset] = custom;
  14596. }
  14597. var stateMap = this._shaderPass._stateMap;
  14598. for (var s in stateMap)
  14599. this._stateParamsMap[stateMap[s]] = Shader3D.propertyNameToID(s);
  14600. }
  14601. _getRenderState(shaderDatas, stateIndex) {
  14602. var stateID = this._stateParamsMap[stateIndex];
  14603. if (stateID == null)
  14604. return null;
  14605. else
  14606. return shaderDatas[stateID];
  14607. }
  14608. _disposeResource() {
  14609. Laya.LayaGL.instance.deleteShader(this._vshader);
  14610. Laya.LayaGL.instance.deleteShader(this._pshader);
  14611. Laya.LayaGL.instance.deleteProgram(this._program);
  14612. this._vshader = this._pshader = this._program = null;
  14613. this._setGPUMemory(0);
  14614. this._curActTexIndex = 0;
  14615. }
  14616. _addShaderUnifiormFun(one) {
  14617. var gl = Laya.LayaGL.instance;
  14618. one.caller = this;
  14619. var isArray = one.isArray;
  14620. switch (one.type) {
  14621. case gl.BOOL:
  14622. one.fun = this._uniform1i;
  14623. one.uploadedValue = new Array(1);
  14624. break;
  14625. case gl.INT:
  14626. one.fun = isArray ? this._uniform1iv : this._uniform1i;
  14627. one.uploadedValue = new Array(1);
  14628. break;
  14629. case gl.FLOAT:
  14630. one.fun = isArray ? this._uniform1fv : this._uniform1f;
  14631. one.uploadedValue = new Array(1);
  14632. break;
  14633. case gl.FLOAT_VEC2:
  14634. one.fun = isArray ? this._uniform_vec2v : this._uniform_vec2;
  14635. one.uploadedValue = new Array(2);
  14636. break;
  14637. case gl.FLOAT_VEC3:
  14638. one.fun = isArray ? this._uniform_vec3v : this._uniform_vec3;
  14639. one.uploadedValue = new Array(3);
  14640. break;
  14641. case gl.FLOAT_VEC4:
  14642. one.fun = isArray ? this._uniform_vec4v : this._uniform_vec4;
  14643. one.uploadedValue = new Array(4);
  14644. break;
  14645. case gl.FLOAT_MAT2:
  14646. one.fun = this._uniformMatrix2fv;
  14647. break;
  14648. case gl.FLOAT_MAT3:
  14649. one.fun = this._uniformMatrix3fv;
  14650. break;
  14651. case gl.FLOAT_MAT4:
  14652. one.fun = isArray ? this._uniformMatrix4fv : this._uniformMatrix4f;
  14653. break;
  14654. case gl.SAMPLER_2D:
  14655. case gl.SAMPLER_2D_SHADOW:
  14656. gl.uniform1i(one.location, this._curActTexIndex);
  14657. one.textureID = Laya.WebGLContext._glTextureIDs[this._curActTexIndex++];
  14658. one.fun = this._uniform_sampler2D;
  14659. break;
  14660. case 0x8b5f:
  14661. gl.uniform1i(one.location, this._curActTexIndex);
  14662. one.textureID = Laya.WebGLContext._glTextureIDs[this._curActTexIndex++];
  14663. one.fun = this._uniform_sampler3D;
  14664. break;
  14665. case gl.SAMPLER_CUBE:
  14666. gl.uniform1i(one.location, this._curActTexIndex);
  14667. one.textureID = Laya.WebGLContext._glTextureIDs[this._curActTexIndex++];
  14668. one.fun = this._uniform_samplerCube;
  14669. break;
  14670. default:
  14671. throw new Error("compile shader err!");
  14672. break;
  14673. }
  14674. }
  14675. _createShader(gl, str, type) {
  14676. var shader = gl.createShader(type);
  14677. gl.shaderSource(shader, str);
  14678. gl.compileShader(shader);
  14679. if (Shader3D.debugMode && !gl.getShaderParameter(shader, gl.COMPILE_STATUS))
  14680. throw gl.getShaderInfoLog(shader);
  14681. return shader;
  14682. }
  14683. _uniform1f(one, value) {
  14684. var uploadedValue = one.uploadedValue;
  14685. if (uploadedValue[0] !== value) {
  14686. Laya.LayaGL.instance.uniform1f(one.location, uploadedValue[0] = value);
  14687. return 1;
  14688. }
  14689. return 0;
  14690. }
  14691. _uniform1fv(one, value) {
  14692. if (value.length < 4) {
  14693. var uploadedValue = one.uploadedValue;
  14694. if (uploadedValue[0] !== value[0] || uploadedValue[1] !== value[1] || uploadedValue[2] !== value[2] || uploadedValue[3] !== value[3]) {
  14695. Laya.LayaGL.instance.uniform1fv(one.location, value);
  14696. uploadedValue[0] = value[0];
  14697. uploadedValue[1] = value[1];
  14698. uploadedValue[2] = value[2];
  14699. uploadedValue[3] = value[3];
  14700. return 1;
  14701. }
  14702. return 0;
  14703. }
  14704. else {
  14705. Laya.LayaGL.instance.uniform1fv(one.location, value);
  14706. return 1;
  14707. }
  14708. }
  14709. _uniform_vec2(one, v) {
  14710. var uploadedValue = one.uploadedValue;
  14711. if (uploadedValue[0] !== v.x || uploadedValue[1] !== v.y) {
  14712. Laya.LayaGL.instance.uniform2f(one.location, uploadedValue[0] = v.x, uploadedValue[1] = v.y);
  14713. return 1;
  14714. }
  14715. return 0;
  14716. }
  14717. _uniform_vec2v(one, value) {
  14718. if (value.length < 2) {
  14719. var uploadedValue = one.uploadedValue;
  14720. if (uploadedValue[0] !== value[0] || uploadedValue[1] !== value[1] || uploadedValue[2] !== value[2] || uploadedValue[3] !== value[3]) {
  14721. Laya.LayaGL.instance.uniform2fv(one.location, value);
  14722. uploadedValue[0] = value[0];
  14723. uploadedValue[1] = value[1];
  14724. uploadedValue[2] = value[2];
  14725. uploadedValue[3] = value[3];
  14726. return 1;
  14727. }
  14728. return 0;
  14729. }
  14730. else {
  14731. Laya.LayaGL.instance.uniform2fv(one.location, value);
  14732. return 1;
  14733. }
  14734. }
  14735. _uniform_vec3(one, v) {
  14736. var uploadedValue = one.uploadedValue;
  14737. if (uploadedValue[0] !== v.x || uploadedValue[1] !== v.y || uploadedValue[2] !== v.z) {
  14738. Laya.LayaGL.instance.uniform3f(one.location, uploadedValue[0] = v.x, uploadedValue[1] = v.y, uploadedValue[2] = v.z);
  14739. return 1;
  14740. }
  14741. return 0;
  14742. }
  14743. _uniform_vec3v(one, v) {
  14744. Laya.LayaGL.instance.uniform3fv(one.location, v);
  14745. return 1;
  14746. }
  14747. _uniform_vec4(one, v) {
  14748. var uploadedValue = one.uploadedValue;
  14749. if (uploadedValue[0] !== v.x || uploadedValue[1] !== v.y || uploadedValue[2] !== v.z || uploadedValue[3] !== v.w) {
  14750. Laya.LayaGL.instance.uniform4f(one.location, uploadedValue[0] = v.x, uploadedValue[1] = v.y, uploadedValue[2] = v.z, uploadedValue[3] = v.w);
  14751. return 1;
  14752. }
  14753. return 0;
  14754. }
  14755. _uniform_vec4v(one, v) {
  14756. Laya.LayaGL.instance.uniform4fv(one.location, v);
  14757. return 1;
  14758. }
  14759. _uniformMatrix2fv(one, value) {
  14760. Laya.LayaGL.instance.uniformMatrix2fv(one.location, false, value);
  14761. return 1;
  14762. }
  14763. _uniformMatrix3fv(one, value) {
  14764. Laya.LayaGL.instance.uniformMatrix3fv(one.location, false, value);
  14765. return 1;
  14766. }
  14767. _uniformMatrix4f(one, m) {
  14768. var value = m.elements;
  14769. Laya.LayaGL.instance.uniformMatrix4fv(one.location, false, value);
  14770. return 1;
  14771. }
  14772. _uniformMatrix4fv(one, m) {
  14773. Laya.LayaGL.instance.uniformMatrix4fv(one.location, false, m);
  14774. return 1;
  14775. }
  14776. _uniform1i(one, value) {
  14777. var uploadedValue = one.uploadedValue;
  14778. if (uploadedValue[0] !== value) {
  14779. Laya.LayaGL.instance.uniform1i(one.location, uploadedValue[0] = value);
  14780. return 1;
  14781. }
  14782. return 0;
  14783. }
  14784. _uniform1iv(one, value) {
  14785. Laya.LayaGL.instance.uniform1iv(one.location, value);
  14786. return 1;
  14787. }
  14788. _uniform_ivec2(one, value) {
  14789. var uploadedValue = one.uploadedValue;
  14790. if (uploadedValue[0] !== value[0] || uploadedValue[1] !== value[1]) {
  14791. Laya.LayaGL.instance.uniform2i(one.location, uploadedValue[0] = value[0], uploadedValue[1] = value[1]);
  14792. return 1;
  14793. }
  14794. return 0;
  14795. }
  14796. _uniform_ivec2v(one, value) {
  14797. Laya.LayaGL.instance.uniform2iv(one.location, value);
  14798. return 1;
  14799. }
  14800. _uniform_vec3i(one, value) {
  14801. var uploadedValue = one.uploadedValue;
  14802. if (uploadedValue[0] !== value[0] || uploadedValue[1] !== value[1] || uploadedValue[2] !== value[2]) {
  14803. Laya.LayaGL.instance.uniform3i(one.location, uploadedValue[0] = value[0], uploadedValue[1] = value[1], uploadedValue[2] = value[2]);
  14804. return 1;
  14805. }
  14806. return 0;
  14807. }
  14808. _uniform_vec3vi(one, value) {
  14809. Laya.LayaGL.instance.uniform3iv(one.location, value);
  14810. return 1;
  14811. }
  14812. _uniform_vec4i(one, value) {
  14813. var uploadedValue = one.uploadedValue;
  14814. if (uploadedValue[0] !== value[0] || uploadedValue[1] !== value[1] || uploadedValue[2] !== value[2] || uploadedValue[3] !== value[3]) {
  14815. Laya.LayaGL.instance.uniform4i(one.location, uploadedValue[0] = value[0], uploadedValue[1] = value[1], uploadedValue[2] = value[2], uploadedValue[3] = value[3]);
  14816. return 1;
  14817. }
  14818. return 0;
  14819. }
  14820. _uniform_vec4vi(one, value) {
  14821. Laya.LayaGL.instance.uniform4iv(one.location, value);
  14822. return 1;
  14823. }
  14824. _uniform_sampler2D(one, texture) {
  14825. var value = texture._getSource() || texture.defaulteTexture._getSource();
  14826. var gl = Laya.LayaGL.instance;
  14827. Laya.WebGLContext.activeTexture(gl, one.textureID);
  14828. Laya.WebGLContext.bindTexture(gl, gl.TEXTURE_2D, value);
  14829. return 0;
  14830. }
  14831. _uniform_sampler3D(one, texture) {
  14832. var value = texture._getSource() || texture.defaulteTexture._getSource();
  14833. var gl = Laya.LayaGL.instance;
  14834. Laya.WebGLContext.activeTexture(gl, one.textureID);
  14835. Laya.WebGLContext.bindTexture(gl, WebGL2RenderingContext.TEXTURE_3D, value);
  14836. return 0;
  14837. }
  14838. _uniform_samplerCube(one, texture) {
  14839. var value = texture._getSource() || texture.defaulteTexture._getSource();
  14840. var gl = Laya.LayaGL.instance;
  14841. Laya.WebGLContext.activeTexture(gl, one.textureID);
  14842. Laya.WebGLContext.bindTexture(gl, gl.TEXTURE_CUBE_MAP, value);
  14843. return 0;
  14844. }
  14845. bind() {
  14846. return Laya.WebGLContext.useProgram(Laya.LayaGL.instance, this._program);
  14847. }
  14848. uploadUniforms(shaderUniform, shaderDatas, uploadUnTexture) {
  14849. Laya.Stat.shaderCall += Laya.LayaGLRunner.uploadShaderUniforms(Laya.LayaGL.instance, shaderUniform, shaderDatas, uploadUnTexture);
  14850. }
  14851. uploadRenderStateBlendDepth(shaderDatas) {
  14852. var gl = Laya.LayaGL.instance;
  14853. var renderState = this._shaderPass.renderState;
  14854. var datas = shaderDatas.getData();
  14855. var depthWrite = this._getRenderState(datas, Shader3D.RENDER_STATE_DEPTH_WRITE);
  14856. var depthTest = this._getRenderState(datas, Shader3D.RENDER_STATE_DEPTH_TEST);
  14857. var blend = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND);
  14858. depthWrite == null && (depthWrite = renderState.depthWrite);
  14859. depthTest == null && (depthTest = renderState.depthTest);
  14860. blend == null && (blend = renderState.blend);
  14861. Laya.WebGLContext.setDepthMask(gl, depthWrite);
  14862. if (depthTest === RenderState.DEPTHTEST_OFF)
  14863. Laya.WebGLContext.setDepthTest(gl, false);
  14864. else {
  14865. Laya.WebGLContext.setDepthTest(gl, true);
  14866. Laya.WebGLContext.setDepthFunc(gl, depthTest);
  14867. }
  14868. switch (blend) {
  14869. case RenderState.BLEND_DISABLE:
  14870. Laya.WebGLContext.setBlend(gl, false);
  14871. break;
  14872. case RenderState.BLEND_ENABLE_ALL:
  14873. var blendEquation = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_EQUATION);
  14874. var srcBlend = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_SRC);
  14875. var dstBlend = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_DST);
  14876. blendEquation == null && (blendEquation = renderState.blendEquation);
  14877. srcBlend == null && (srcBlend = renderState.srcBlend);
  14878. dstBlend == null && (dstBlend = renderState.dstBlend);
  14879. Laya.WebGLContext.setBlend(gl, true);
  14880. Laya.WebGLContext.setBlendEquation(gl, blendEquation);
  14881. Laya.WebGLContext.setBlendFunc(gl, srcBlend, dstBlend);
  14882. break;
  14883. case RenderState.BLEND_ENABLE_SEPERATE:
  14884. var blendEquationRGB = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_EQUATION_RGB);
  14885. var blendEquationAlpha = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_EQUATION_ALPHA);
  14886. var srcRGB = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_SRC_RGB);
  14887. var dstRGB = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_DST_RGB);
  14888. var srcAlpha = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_SRC_ALPHA);
  14889. var dstAlpha = this._getRenderState(datas, Shader3D.RENDER_STATE_BLEND_DST_ALPHA);
  14890. blendEquationRGB == null && (blendEquationRGB = renderState.blendEquationRGB);
  14891. blendEquationAlpha == null && (blendEquationAlpha = renderState.blendEquationAlpha);
  14892. srcRGB == null && (srcRGB = renderState.srcBlendRGB);
  14893. dstRGB == null && (dstRGB = renderState.dstBlendRGB);
  14894. srcAlpha == null && (srcAlpha = renderState.srcBlendAlpha);
  14895. dstAlpha == null && (dstAlpha = renderState.dstBlendAlpha);
  14896. Laya.WebGLContext.setBlend(gl, true);
  14897. Laya.WebGLContext.setBlendEquationSeparate(gl, blendEquationRGB, blendEquationAlpha);
  14898. Laya.WebGLContext.setBlendFuncSeperate(gl, srcRGB, dstRGB, srcAlpha, dstAlpha);
  14899. break;
  14900. }
  14901. }
  14902. uploadRenderStateFrontFace(shaderDatas, isTarget, invertFront) {
  14903. var gl = Laya.LayaGL.instance;
  14904. var renderState = this._shaderPass.renderState;
  14905. var datas = shaderDatas.getData();
  14906. var cull = this._getRenderState(datas, Shader3D.RENDER_STATE_CULL);
  14907. cull == null && (cull = renderState.cull);
  14908. var forntFace;
  14909. switch (cull) {
  14910. case RenderState.CULL_NONE:
  14911. Laya.WebGLContext.setCullFace(gl, false);
  14912. break;
  14913. case RenderState.CULL_FRONT:
  14914. Laya.WebGLContext.setCullFace(gl, true);
  14915. if (isTarget) {
  14916. if (invertFront)
  14917. forntFace = gl.CCW;
  14918. else
  14919. forntFace = gl.CW;
  14920. }
  14921. else {
  14922. if (invertFront)
  14923. forntFace = gl.CW;
  14924. else
  14925. forntFace = gl.CCW;
  14926. }
  14927. Laya.WebGLContext.setFrontFace(gl, forntFace);
  14928. break;
  14929. case RenderState.CULL_BACK:
  14930. Laya.WebGLContext.setCullFace(gl, true);
  14931. if (isTarget) {
  14932. if (invertFront)
  14933. forntFace = gl.CW;
  14934. else
  14935. forntFace = gl.CCW;
  14936. }
  14937. else {
  14938. if (invertFront)
  14939. forntFace = gl.CCW;
  14940. else
  14941. forntFace = gl.CW;
  14942. }
  14943. Laya.WebGLContext.setFrontFace(gl, forntFace);
  14944. break;
  14945. }
  14946. }
  14947. uploadCustomUniform(index, data) {
  14948. Laya.Stat.shaderCall += Laya.LayaGLRunner.uploadCustomUniform(Laya.LayaGL.instance, this._customUniformParamsMap, index, data);
  14949. }
  14950. _uniformMatrix2fvForNative(one, value) {
  14951. Laya.LayaGL.instance.uniformMatrix2fvEx(one.location, false, value);
  14952. return 1;
  14953. }
  14954. _uniformMatrix3fvForNative(one, value) {
  14955. Laya.LayaGL.instance.uniformMatrix3fvEx(one.location, false, value);
  14956. return 1;
  14957. }
  14958. _uniformMatrix4fvForNative(one, m) {
  14959. Laya.LayaGL.instance.uniformMatrix4fvEx(one.location, false, m);
  14960. return 1;
  14961. }
  14962. }
  14963. class SimpleSingletonList extends SingletonList {
  14964. constructor() {
  14965. super();
  14966. }
  14967. add(element) {
  14968. var index = element._getIndexInList();
  14969. if (index !== -1)
  14970. throw "SimpleSingletonList:" + element + " has in SingletonList.";
  14971. this._add(element);
  14972. element._setIndexInList(this.length++);
  14973. }
  14974. remove(element) {
  14975. var index = element._getIndexInList();
  14976. this.length--;
  14977. if (index !== this.length) {
  14978. var end = this.elements[this.length];
  14979. this.elements[index] = end;
  14980. end._setIndexInList(index);
  14981. }
  14982. element._setIndexInList(-1);
  14983. }
  14984. clear() {
  14985. var elements = this.elements;
  14986. for (var i = 0, n = this.length; i < n; i++)
  14987. elements[i]._setIndexInList(-1);
  14988. this.length = 0;
  14989. }
  14990. }
  14991. class Color {
  14992. constructor(r = 1, g = 1, b = 1, a = 1) {
  14993. this.r = r;
  14994. this.g = g;
  14995. this.b = b;
  14996. this.a = a;
  14997. }
  14998. static gammaToLinearSpace(value) {
  14999. if (value <= 0.04045)
  15000. return value / 12.92;
  15001. else if (value < 1.0)
  15002. return Math.pow((value + 0.055) / 1.055, 2.4);
  15003. else
  15004. return Math.pow(value, 2.4);
  15005. }
  15006. static linearToGammaSpace(value) {
  15007. if (value <= 0.0)
  15008. return 0.0;
  15009. else if (value <= 0.0031308)
  15010. return 12.92 * value;
  15011. else if (value <= 1.0)
  15012. return 1.055 * Math.pow(value, 0.41666) - 0.055;
  15013. else
  15014. return Math.pow(value, 0.41666);
  15015. }
  15016. toLinear(out) {
  15017. out.r = Color.gammaToLinearSpace(this.r);
  15018. out.g = Color.gammaToLinearSpace(this.g);
  15019. out.b = Color.gammaToLinearSpace(this.b);
  15020. }
  15021. toGamma(out) {
  15022. out.r = Color.linearToGammaSpace(this.r);
  15023. out.g = Color.linearToGammaSpace(this.g);
  15024. out.b = Color.linearToGammaSpace(this.b);
  15025. }
  15026. cloneTo(destObject) {
  15027. var destColor = destObject;
  15028. destColor.r = this.r;
  15029. destColor.g = this.g;
  15030. destColor.b = this.b;
  15031. destColor.a = this.a;
  15032. }
  15033. clone() {
  15034. var dest = new Color();
  15035. this.cloneTo(dest);
  15036. return dest;
  15037. }
  15038. forNativeElement() {
  15039. }
  15040. }
  15041. Color.RED = new Color(1, 0, 0, 1);
  15042. Color.GREEN = new Color(0, 1, 0, 1);
  15043. Color.BLUE = new Color(0, 0, 1, 1);
  15044. Color.CYAN = new Color(0, 1, 1, 1);
  15045. Color.YELLOW = new Color(1, 0.92, 0.016, 1);
  15046. Color.MAGENTA = new Color(1, 0, 1, 1);
  15047. Color.GRAY = new Color(0.5, 0.5, 0.5, 1);
  15048. Color.WHITE = new Color(1, 1, 1, 1);
  15049. Color.BLACK = new Color(0, 0, 0, 1);
  15050. class CameraCullInfo {
  15051. }
  15052. class ShadowCullInfo {
  15053. }
  15054. class FrustumCulling {
  15055. static __init__() {
  15056. }
  15057. static _drawTraversalCullingBound(renderList, debugTool) {
  15058. var renders = renderList.elements;
  15059. for (var i = 0, n = renderList.length; i < n; i++) {
  15060. var color = FrustumCulling._tempColor0;
  15061. color.r = 0;
  15062. color.g = 1;
  15063. color.b = 0;
  15064. color.a = 1;
  15065. Utils3D._drawBound(debugTool, renders[i].bounds._getBoundBox(), color);
  15066. }
  15067. }
  15068. static _traversalCulling(cameraCullInfo, scene, context, renderList, customShader, replacementTag, isShadowCasterCull) {
  15069. var renders = renderList.elements;
  15070. var boundFrustum = cameraCullInfo.boundFrustum;
  15071. var camPos = cameraCullInfo.position;
  15072. var cullMask = cameraCullInfo.cullingMask;
  15073. var loopCount = Laya.Stat.loopCount;
  15074. for (var i = 0, n = renderList.length; i < n; i++) {
  15075. var render = renders[i];
  15076. var canPass;
  15077. if (isShadowCasterCull)
  15078. canPass = render._castShadow && render._enable;
  15079. else
  15080. canPass = ((Math.pow(2, render._owner._layer) & cullMask) != 0) && render._enable;
  15081. if (canPass) {
  15082. Laya.Stat.frustumCulling++;
  15083. if (!cameraCullInfo.useOcclusionCulling || render._needRender(boundFrustum, context)) {
  15084. render._renderMark = loopCount;
  15085. render._distanceForSort = Vector3.distance(render.bounds.getCenter(), camPos);
  15086. var elements = render._renderElements;
  15087. for (var j = 0, m = elements.length; j < m; j++)
  15088. elements[j]._update(scene, context, customShader, replacementTag);
  15089. }
  15090. }
  15091. }
  15092. }
  15093. static renderObjectCulling(cameraCullInfo, scene, context, customShader, replacementTag, isShadowCasterCull) {
  15094. var opaqueQueue = scene._opaqueQueue;
  15095. var transparentQueue = scene._transparentQueue;
  15096. var renderList = scene._renders;
  15097. scene._clearRenderQueue();
  15098. var octree = scene._octree;
  15099. if (octree) {
  15100. octree.updateMotionObjects();
  15101. octree.shrinkRootIfPossible();
  15102. octree.getCollidingWithFrustum(cameraCullInfo, context, customShader, replacementTag, isShadowCasterCull);
  15103. }
  15104. FrustumCulling._traversalCulling(cameraCullInfo, scene, context, renderList, customShader, replacementTag, isShadowCasterCull);
  15105. if (FrustumCulling.debugFrustumCulling) {
  15106. var debugTool = scene._debugTool;
  15107. debugTool.clear();
  15108. if (octree) {
  15109. octree.drawAllBounds(debugTool);
  15110. octree.drawAllObjects(debugTool);
  15111. }
  15112. FrustumCulling._drawTraversalCullingBound(renderList, debugTool);
  15113. }
  15114. var count = opaqueQueue.elements.length;
  15115. (count > 0) && (opaqueQueue._quickSort(0, count - 1));
  15116. count = transparentQueue.elements.length;
  15117. (count > 0) && (transparentQueue._quickSort(0, count - 1));
  15118. }
  15119. static cullingShadow(cullInfo, scene, context) {
  15120. var renderList = scene._renders;
  15121. scene._clearRenderQueue();
  15122. var opaqueQueue = scene._opaqueQueue;
  15123. var position = cullInfo.position;
  15124. var cullPlaneCount = cullInfo.cullPlaneCount;
  15125. var cullPlanes = cullInfo.cullPlanes;
  15126. var cullSphere = cullInfo.cullSphere;
  15127. var direction = cullInfo.direction;
  15128. var renders = renderList.elements;
  15129. var loopCount = Laya.Stat.loopCount;
  15130. for (var i = 0, n = renderList.length; i < n; i++) {
  15131. var render = renders[i];
  15132. var canPass = render._castShadow && render._enable;
  15133. if (canPass) {
  15134. Laya.Stat.frustumCulling++;
  15135. var bounds = render.bounds;
  15136. var min = bounds.getMin();
  15137. var max = bounds.getMax();
  15138. var minX = min.x;
  15139. var minY = min.y;
  15140. var minZ = min.z;
  15141. var maxX = max.x;
  15142. var maxY = max.y;
  15143. var maxZ = max.z;
  15144. var pass = true;
  15145. for (var j = 0; j < cullPlaneCount; j++) {
  15146. var plane = cullPlanes[j];
  15147. var normal = plane.normal;
  15148. if (plane.distance + (normal.x * (normal.x < 0.0 ? minX : maxX)) + (normal.y * (normal.y < 0.0 ? minY : maxY)) + (normal.z * (normal.z < 0.0 ? minZ : maxZ)) < 0.0) {
  15149. pass = false;
  15150. break;
  15151. }
  15152. }
  15153. if (pass) {
  15154. render._renderMark = loopCount;
  15155. render._distanceForSort = Vector3.distance(bounds.getCenter(), position);
  15156. var elements = render._renderElements;
  15157. for (var j = 0, m = elements.length; j < m; j++)
  15158. elements[j]._update(scene, context, null, null);
  15159. }
  15160. }
  15161. }
  15162. return opaqueQueue.elements.length > 0 ? true : false;
  15163. }
  15164. static cullingSpotShadow(cameraCullInfo, scene, context) {
  15165. var renderList = scene._renders;
  15166. scene._clearRenderQueue();
  15167. var opaqueQueue = scene._opaqueQueue;
  15168. var renders = renderList.elements;
  15169. var loopCount = Laya.Stat.loopCount;
  15170. for (var i = 0, n = renderList.length; i < n; i++) {
  15171. var render = renders[i];
  15172. var canPass = render._castShadow && render._enable;
  15173. if (canPass) {
  15174. if (render._needRender(cameraCullInfo.boundFrustum, context)) {
  15175. var bounds = render.bounds;
  15176. render._renderMark = loopCount;
  15177. render._distanceForSort = Vector3.distance(bounds.getCenter(), cameraCullInfo.position);
  15178. var elements = render._renderElements;
  15179. for (var j = 0, m = elements.length; j < m; j++)
  15180. elements[j]._update(scene, context, null, null);
  15181. }
  15182. }
  15183. }
  15184. return opaqueQueue.elements.length > 0 ? true : false;
  15185. }
  15186. static renderObjectCullingNative(camera, scene, context, renderList, customShader, replacementTag) {
  15187. var i, j, m;
  15188. var opaqueQueue = scene._opaqueQueue;
  15189. var transparentQueue = scene._transparentQueue;
  15190. scene._clearRenderQueue();
  15191. var validCount = renderList.length;
  15192. var renders = renderList.elements;
  15193. for (i = 0; i < validCount; i++) {
  15194. renders[i].bounds;
  15195. renders[i]._updateForNative && renders[i]._updateForNative(context);
  15196. }
  15197. var boundFrustum = camera.boundFrustum;
  15198. FrustumCulling.cullingNative(camera._boundFrustumBuffer, FrustumCulling._cullingBuffer, scene._cullingBufferIndices, validCount, scene._cullingBufferResult);
  15199. var loopCount = Laya.Stat.loopCount;
  15200. var camPos = context.camera._transform.position;
  15201. for (i = 0; i < validCount; i++) {
  15202. var render = renders[i];
  15203. if (!camera.useOcclusionCulling || (camera._isLayerVisible(render._owner._layer) && render._enable && scene._cullingBufferResult[i])) {
  15204. render._renderMark = loopCount;
  15205. render._distanceForSort = Vector3.distance(render.bounds.getCenter(), camPos);
  15206. var elements = render._renderElements;
  15207. for (j = 0, m = elements.length; j < m; j++) {
  15208. var element = elements[j];
  15209. element._update(scene, context, customShader, replacementTag);
  15210. }
  15211. }
  15212. }
  15213. var count = opaqueQueue.elements.length;
  15214. (count > 0) && (opaqueQueue._quickSort(0, count - 1));
  15215. count = transparentQueue.elements.length;
  15216. (count > 0) && (transparentQueue._quickSort(0, count - 1));
  15217. }
  15218. static cullingNative(boundFrustumBuffer, cullingBuffer, cullingBufferIndices, cullingCount, cullingBufferResult) {
  15219. return Laya.LayaGL.instance.culling(boundFrustumBuffer, cullingBuffer, cullingBufferIndices, cullingCount, cullingBufferResult);
  15220. }
  15221. }
  15222. FrustumCulling._tempColor0 = new Color();
  15223. FrustumCulling._tempVector0 = new Vector3();
  15224. FrustumCulling._cameraCullInfo = new CameraCullInfo();
  15225. FrustumCulling._shadowCullInfo = new ShadowCullInfo();
  15226. FrustumCulling.debugFrustumCulling = false;
  15227. class SphericalHarmonicsL2 {
  15228. constructor() {
  15229. this._coefficients = new Float32Array(27);
  15230. }
  15231. getCoefficient(i, j) {
  15232. return this._coefficients[i * 9 + j];
  15233. }
  15234. setCoefficient(i, j, coefficient) {
  15235. this._coefficients[i * 9 + j] = coefficient;
  15236. }
  15237. setCoefficients(i, coefficient0, coefficient1, coefficient2, coefficient3, coefficient4, coefficient5, coefficient6, coefficient7, coefficient8) {
  15238. var offset = i * 9;
  15239. this._coefficients[offset] = coefficient0;
  15240. this._coefficients[++offset] = coefficient1;
  15241. this._coefficients[++offset] = coefficient2;
  15242. this._coefficients[++offset] = coefficient3;
  15243. this._coefficients[++offset] = coefficient4;
  15244. this._coefficients[++offset] = coefficient5;
  15245. this._coefficients[++offset] = coefficient6;
  15246. this._coefficients[++offset] = coefficient7;
  15247. this._coefficients[++offset] = coefficient8;
  15248. }
  15249. cloneTo(dest) {
  15250. if (this === dest)
  15251. return;
  15252. var coes = this._coefficients;
  15253. var destCoes = dest._coefficients;
  15254. for (var i = 0; i < 27; i++)
  15255. destCoes[i] = coes[i];
  15256. }
  15257. }
  15258. SphericalHarmonicsL2._default = new SphericalHarmonicsL2();
  15259. class MouseTouch {
  15260. constructor() {
  15261. this._pressedSprite = null;
  15262. this._pressedLoopCount = -1;
  15263. this.sprite = null;
  15264. this.mousePositionX = 0;
  15265. this.mousePositionY = 0;
  15266. }
  15267. }
  15268. class Touch {
  15269. constructor() {
  15270. this._indexInList = -1;
  15271. this._identifier = -1;
  15272. this._position = new Vector2();
  15273. }
  15274. get identifier() {
  15275. return this._identifier;
  15276. }
  15277. get position() {
  15278. return this._position;
  15279. }
  15280. _getIndexInList() {
  15281. return this._indexInList;
  15282. }
  15283. _setIndexInList(index) {
  15284. this._indexInList = index;
  15285. }
  15286. }
  15287. class Input3D {
  15288. constructor() {
  15289. this._eventList = [];
  15290. this._mouseTouch = new MouseTouch();
  15291. this._touchPool = [];
  15292. this._touches = new SimpleSingletonList();
  15293. this._multiTouchEnabled = true;
  15294. this._pushEventList = ((e) => {
  15295. (e.cancelable) && (e.preventDefault());
  15296. this._eventList.push(e);
  15297. }).bind(this);
  15298. }
  15299. __init__(canvas, scene) {
  15300. this._scene = scene;
  15301. canvas.oncontextmenu = function (e) {
  15302. return false;
  15303. };
  15304. }
  15305. _onCanvasEvent(canvas) {
  15306. canvas.addEventListener('mousedown', this._pushEventList);
  15307. canvas.addEventListener('mouseup', this._pushEventList, true);
  15308. canvas.addEventListener('mousemove', this._pushEventList, true);
  15309. canvas.addEventListener("touchstart", this._pushEventList);
  15310. canvas.addEventListener("touchend", this._pushEventList, true);
  15311. canvas.addEventListener("touchmove", this._pushEventList, true);
  15312. canvas.addEventListener("touchcancel", this._pushEventList, true);
  15313. }
  15314. _offCanvasEvent(canvas) {
  15315. canvas.removeEventListener('mousedown', this._pushEventList);
  15316. canvas.removeEventListener('mouseup', this._pushEventList, true);
  15317. canvas.removeEventListener('mousemove', this._pushEventList, true);
  15318. canvas.removeEventListener("touchstart", this._pushEventList);
  15319. canvas.removeEventListener("touchend", this._pushEventList, true);
  15320. canvas.removeEventListener("touchmove", this._pushEventList, true);
  15321. canvas.removeEventListener("touchcancel", this._pushEventList, true);
  15322. this._eventList.length = 0;
  15323. this._touches.clear();
  15324. }
  15325. touchCount() {
  15326. return this._touches.length;
  15327. }
  15328. get multiTouchEnabled() {
  15329. return this._multiTouchEnabled;
  15330. }
  15331. set multiTouchEnabled(value) {
  15332. this._multiTouchEnabled = value;
  15333. }
  15334. _getTouch(touchID, type) {
  15335. var touch = this._touchPool[touchID];
  15336. if ((type == 0 && touch && touch._getIndexInList() != -1))
  15337. return null;
  15338. if (type == 1 && touch && (touch._getIndexInList() == -1))
  15339. return null;
  15340. if (!touch) {
  15341. touch = new Touch();
  15342. this._touchPool[touchID] = touch;
  15343. touch._identifier = touchID;
  15344. }
  15345. return touch;
  15346. }
  15347. _mouseTouchDown() {
  15348. var touch = this._mouseTouch;
  15349. var sprite = touch.sprite;
  15350. touch._pressedSprite = sprite;
  15351. touch._pressedLoopCount = Laya.Stat.loopCount;
  15352. if (sprite) {
  15353. var scripts = sprite._scripts;
  15354. if (scripts) {
  15355. for (var i = 0, n = scripts.length; i < n; i++)
  15356. scripts[i].onMouseDown();
  15357. }
  15358. }
  15359. }
  15360. _mouseTouchUp() {
  15361. var i, n;
  15362. var touch = this._mouseTouch;
  15363. var lastPressedSprite = touch._pressedSprite;
  15364. touch._pressedSprite = null;
  15365. touch._pressedLoopCount = -1;
  15366. var sprite = touch.sprite;
  15367. if (sprite) {
  15368. if (sprite === lastPressedSprite) {
  15369. var scripts = sprite._scripts;
  15370. if (scripts) {
  15371. for (i = 0, n = scripts.length; i < n; i++)
  15372. scripts[i].onMouseClick();
  15373. }
  15374. }
  15375. }
  15376. if (lastPressedSprite) {
  15377. var lastScripts = lastPressedSprite._scripts;
  15378. if (lastScripts) {
  15379. for (i = 0, n = lastScripts.length; i < n; i++)
  15380. lastScripts[i].onMouseUp();
  15381. }
  15382. }
  15383. }
  15384. _mouseTouchRayCast(cameras) {
  15385. var touchHitResult = Input3D._tempHitResult0;
  15386. var touchPos = Input3D._tempVector20;
  15387. var touchRay = Input3D._tempRay0;
  15388. touchHitResult.succeeded = false;
  15389. var x = this._mouseTouch.mousePositionX;
  15390. var y = this._mouseTouch.mousePositionY;
  15391. touchPos.x = x;
  15392. touchPos.y = y;
  15393. for (var i = cameras.length - 1; i >= 0; i--) {
  15394. var camera = cameras[i];
  15395. var viewport = camera.viewport;
  15396. if (touchPos.x >= viewport.x && touchPos.y >= viewport.y && touchPos.x <= viewport.width && touchPos.y <= viewport.height) {
  15397. camera.viewportPointToRay(touchPos, touchRay);
  15398. var sucess = this._scene._physicsSimulation.rayCast(touchRay, touchHitResult);
  15399. if (sucess || (camera.clearFlag === exports.CameraClearFlags.SolidColor || camera.clearFlag === exports.CameraClearFlags.Sky))
  15400. break;
  15401. }
  15402. }
  15403. var touch = this._mouseTouch;
  15404. var lastSprite = touch.sprite;
  15405. if (touchHitResult.succeeded) {
  15406. var touchSprite = touchHitResult.collider.owner;
  15407. touch.sprite = touchSprite;
  15408. var scripts = touchSprite._scripts;
  15409. if (lastSprite !== touchSprite) {
  15410. if (scripts) {
  15411. for (var j = 0, m = scripts.length; j < m; j++)
  15412. scripts[j].onMouseEnter();
  15413. }
  15414. }
  15415. }
  15416. else {
  15417. touch.sprite = null;
  15418. }
  15419. if (lastSprite && (lastSprite !== touchSprite)) {
  15420. var outScripts = lastSprite._scripts;
  15421. if (outScripts) {
  15422. for (j = 0, m = outScripts.length; j < m; j++)
  15423. outScripts[j].onMouseOut();
  15424. }
  15425. }
  15426. }
  15427. _changeTouches(changedTouches, flag) {
  15428. var offsetX = 0, offsetY = 0;
  15429. var lastCount = this._touches.length;
  15430. for (var j = 0, m = changedTouches.length; j < m; j++) {
  15431. var nativeTouch = changedTouches[j];
  15432. var identifier = nativeTouch.identifier;
  15433. if (!this._multiTouchEnabled && this._touches.length !== 0 && flag == 0)
  15434. continue;
  15435. var touch = this._getTouch(identifier, flag);
  15436. if (flag == 1 && !touch)
  15437. continue;
  15438. var pos = this._touchPool[identifier]._position;
  15439. var mousePoint = Input3D._tempPoint;
  15440. mousePoint.setTo(nativeTouch.pageX, nativeTouch.pageY);
  15441. Laya.ILaya.stage._canvasTransform.invertTransformPoint(mousePoint);
  15442. var posX = mousePoint.x;
  15443. var posY = mousePoint.y;
  15444. switch (flag) {
  15445. case 0:
  15446. if (!!touch)
  15447. this._touches.add(touch);
  15448. offsetX += posX;
  15449. offsetY += posY;
  15450. break;
  15451. case 1:
  15452. if (!!touch)
  15453. this._touches.remove(touch);
  15454. offsetX -= posX;
  15455. offsetY -= posY;
  15456. break;
  15457. case 2:
  15458. offsetX = posX - pos.x;
  15459. offsetY = posY - pos.y;
  15460. break;
  15461. }
  15462. pos.x = posX;
  15463. pos.y = posY;
  15464. }
  15465. var touchCount = this._touches.length;
  15466. if (touchCount === 0) {
  15467. this._mouseTouch.mousePositionX = 0;
  15468. this._mouseTouch.mousePositionY = 0;
  15469. }
  15470. else {
  15471. this._mouseTouch.mousePositionX = (this._mouseTouch.mousePositionX * lastCount + offsetX) / touchCount;
  15472. this._mouseTouch.mousePositionY = (this._mouseTouch.mousePositionY * lastCount + offsetY) / touchCount;
  15473. }
  15474. }
  15475. _update() {
  15476. var enablePhysics = Physics3D._enablePhysics && !PhysicsSimulation.disableSimulation;
  15477. var i, n, j, m;
  15478. n = this._eventList.length;
  15479. var cameras = this._scene._cameraPool;
  15480. if (n > 0) {
  15481. var rayCast = false;
  15482. for (i = 0; i < n; i++) {
  15483. var e = this._eventList[i];
  15484. switch (e.type) {
  15485. case "mousedown":
  15486. (enablePhysics) && (this._mouseTouchDown());
  15487. break;
  15488. case "mouseup":
  15489. (enablePhysics) && (this._mouseTouchUp());
  15490. break;
  15491. case "mousemove":
  15492. var mousePoint = Input3D._tempPoint;
  15493. mousePoint.setTo(e.pageX, e.pageY);
  15494. Laya.ILaya.stage._canvasTransform.invertTransformPoint(mousePoint);
  15495. this._mouseTouch.mousePositionX = mousePoint.x;
  15496. this._mouseTouch.mousePositionY = mousePoint.y;
  15497. (enablePhysics) && (rayCast = true);
  15498. break;
  15499. case "touchstart":
  15500. var lastLength = this._touches.length;
  15501. this._changeTouches(e.changedTouches, 0);
  15502. if (enablePhysics) {
  15503. (!Config3D._config.isUseCannonPhysicsEngine) && (this._mouseTouchRayCast(cameras));
  15504. (lastLength === 0) && (this._mouseTouchDown());
  15505. }
  15506. break;
  15507. case "touchend":
  15508. case "touchcancel":
  15509. this._changeTouches(e.changedTouches, 1);
  15510. (enablePhysics && this._touches.length === 0) && (this._mouseTouchUp());
  15511. break;
  15512. case "touchmove":
  15513. this._changeTouches(e.changedTouches, 2);
  15514. (enablePhysics) && (rayCast = true);
  15515. break;
  15516. default:
  15517. throw "Input3D:unkonwn event type.";
  15518. }
  15519. }
  15520. (rayCast) && (!Config3D._config.isUseCannonPhysicsEngine) && (this._mouseTouchRayCast(cameras));
  15521. this._eventList.length = 0;
  15522. }
  15523. if (enablePhysics) {
  15524. var mouseTouch = this._mouseTouch;
  15525. var pressedSprite = mouseTouch._pressedSprite;
  15526. if (pressedSprite && (Laya.Stat.loopCount > mouseTouch._pressedLoopCount)) {
  15527. var pressedScripts = pressedSprite._scripts;
  15528. if (pressedScripts) {
  15529. for (j = 0, m = pressedScripts.length; j < m; j++)
  15530. pressedScripts[j].onMouseDrag();
  15531. }
  15532. }
  15533. var touchSprite = mouseTouch.sprite;
  15534. if (touchSprite) {
  15535. var scripts = touchSprite._scripts;
  15536. if (scripts) {
  15537. for (j = 0, m = scripts.length; j < m; j++)
  15538. scripts[j].onMouseOver();
  15539. }
  15540. }
  15541. }
  15542. }
  15543. getTouch(index) {
  15544. if (index < this._touches.length) {
  15545. return this._touches.elements[index];
  15546. }
  15547. else {
  15548. return null;
  15549. }
  15550. }
  15551. }
  15552. Input3D._tempPoint = new Laya.Point();
  15553. Input3D._tempVector20 = new Vector2();
  15554. Input3D._tempRay0 = new Ray(new Vector3(), new Vector3());
  15555. Input3D._tempHitResult0 = new HitResult();
  15556. class PhysicsSettings {
  15557. constructor() {
  15558. this.flags = 0;
  15559. this.maxSubSteps = 1;
  15560. this.fixedTimeStep = 1.0 / 60.0;
  15561. }
  15562. }
  15563. class VertexPositionTexture0 {
  15564. constructor(position, textureCoordinate0) {
  15565. this._position = position;
  15566. this._textureCoordinate0 = textureCoordinate0;
  15567. }
  15568. static get vertexDeclaration() {
  15569. return VertexPositionTexture0._vertexDeclaration;
  15570. }
  15571. static __init__() {
  15572. VertexPositionTexture0._vertexDeclaration = new VertexDeclaration(20, [new VertexElement(0, VertexElementFormat.Vector3, VertexMesh.MESH_POSITION0),
  15573. new VertexElement(12, VertexElementFormat.Vector2, VertexMesh.MESH_TEXTURECOORDINATE0)]);
  15574. }
  15575. get position() {
  15576. return this._position;
  15577. }
  15578. get textureCoordinate0() {
  15579. return this._textureCoordinate0;
  15580. }
  15581. get vertexDeclaration() {
  15582. return VertexPositionTexture0._vertexDeclaration;
  15583. }
  15584. }
  15585. class SkyDome extends SkyMesh {
  15586. constructor(stacks = 48, slices = 48) {
  15587. super();
  15588. var gl = Laya.LayaGL.instance;
  15589. this._stacks = stacks;
  15590. this._slices = slices;
  15591. var vertexDeclaration = VertexPositionTexture0.vertexDeclaration;
  15592. var vertexFloatCount = vertexDeclaration.vertexStride / 4;
  15593. var numberVertices = (this._stacks + 1) * (this._slices + 1);
  15594. var numberIndices = (3 * this._stacks * (this._slices + 1)) * 2;
  15595. var vertices = new Float32Array(numberVertices * vertexFloatCount);
  15596. var indices = new Uint16Array(numberIndices);
  15597. var stackAngle = Math.PI / this._stacks;
  15598. var sliceAngle = (Math.PI * 2.0) / this._slices;
  15599. var vertexIndex = 0;
  15600. var vertexCount = 0;
  15601. var indexCount = 0;
  15602. for (var stack = 0; stack < (this._stacks + 1); stack++) {
  15603. var r = Math.sin(stack * stackAngle);
  15604. var y = Math.cos(stack * stackAngle);
  15605. for (var slice = 0; slice < (this._slices + 1); slice++) {
  15606. var x = r * Math.sin(slice * sliceAngle);
  15607. var z = r * Math.cos(slice * sliceAngle);
  15608. vertices[vertexCount + 0] = x * SkyDome._radius;
  15609. vertices[vertexCount + 1] = y * SkyDome._radius;
  15610. vertices[vertexCount + 2] = z * SkyDome._radius;
  15611. vertices[vertexCount + 3] = -(slice / this._slices) + 0.75;
  15612. vertices[vertexCount + 4] = stack / this._stacks;
  15613. vertexCount += vertexFloatCount;
  15614. if (stack != (this._stacks - 1)) {
  15615. indices[indexCount++] = vertexIndex + 1;
  15616. indices[indexCount++] = vertexIndex;
  15617. indices[indexCount++] = vertexIndex + (this._slices + 1);
  15618. indices[indexCount++] = vertexIndex + (this._slices + 1);
  15619. indices[indexCount++] = vertexIndex;
  15620. indices[indexCount++] = vertexIndex + (this._slices);
  15621. vertexIndex++;
  15622. }
  15623. }
  15624. }
  15625. this._vertexBuffer = new VertexBuffer3D(vertices.length * 4, gl.STATIC_DRAW, false);
  15626. this._vertexBuffer.vertexDeclaration = vertexDeclaration;
  15627. this._indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt16, indices.length, gl.STATIC_DRAW, false);
  15628. this._vertexBuffer.setData(vertices.buffer);
  15629. this._indexBuffer.setData(indices);
  15630. var bufferState = new BufferState();
  15631. bufferState.bind();
  15632. bufferState.applyVertexBuffer(this._vertexBuffer);
  15633. bufferState.applyIndexBuffer(this._indexBuffer);
  15634. bufferState.unBind();
  15635. this._bufferState = bufferState;
  15636. }
  15637. static __init__() {
  15638. SkyDome.instance = new SkyDome();
  15639. }
  15640. get stacks() {
  15641. return this._stacks;
  15642. }
  15643. get slices() {
  15644. return this._slices;
  15645. }
  15646. _render(state) {
  15647. var gl = Laya.LayaGL.instance;
  15648. var indexCount = this._indexBuffer.indexCount;
  15649. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, 0);
  15650. Laya.Stat.trianglesFaces += indexCount / 3;
  15651. Laya.Stat.renderBatches++;
  15652. }
  15653. }
  15654. SkyDome._radius = 1;
  15655. (function (TextureCubeFace) {
  15656. TextureCubeFace[TextureCubeFace["PositiveX"] = 0] = "PositiveX";
  15657. TextureCubeFace[TextureCubeFace["NegativeX"] = 1] = "NegativeX";
  15658. TextureCubeFace[TextureCubeFace["PositiveY"] = 2] = "PositiveY";
  15659. TextureCubeFace[TextureCubeFace["NegativeY"] = 3] = "NegativeY";
  15660. TextureCubeFace[TextureCubeFace["PositiveZ"] = 4] = "PositiveZ";
  15661. TextureCubeFace[TextureCubeFace["NegativeZ"] = 5] = "NegativeZ";
  15662. })(exports.TextureCubeFace || (exports.TextureCubeFace = {}));
  15663. class TextureCube extends Laya.BaseTexture {
  15664. constructor(size, format = Laya.TextureFormat.R8G8B8, mipmap = false) {
  15665. super(format, mipmap);
  15666. this._glTextureType = Laya.LayaGL.instance.TEXTURE_CUBE_MAP;
  15667. this._width = size;
  15668. this._height = size;
  15669. var gl = Laya.LayaGL.instance;
  15670. this._setWarpMode(gl.TEXTURE_WRAP_S, this._wrapModeU);
  15671. this._setWarpMode(gl.TEXTURE_WRAP_T, this._wrapModeV);
  15672. this._setFilterMode(this._filterMode);
  15673. this._setAnisotropy(this._anisoLevel);
  15674. if (this._mipmap) {
  15675. this._mipmapCount = Math.ceil(Math.log2(size)) + 1;
  15676. for (var i = 0; i < this._mipmapCount; i++)
  15677. this._setPixels([], i, Math.max(size >> i, 1), Math.max(size >> i, 1));
  15678. this._setGPUMemory(size * size * 4 * (1 + 1 / 3) * 6);
  15679. }
  15680. else {
  15681. this._mipmapCount = 1;
  15682. this._setGPUMemory(size * size * 4 * 6);
  15683. }
  15684. }
  15685. static get blackTexture() {
  15686. return TextureCube._blackTexture;
  15687. }
  15688. static get grayTexture() {
  15689. return TextureCube._grayTexture;
  15690. }
  15691. static __init__() {
  15692. var blackTexture = new TextureCube(1, Laya.TextureFormat.R8G8B8, false);
  15693. var grayTexture = new TextureCube(1, Laya.TextureFormat.R8G8B8, false);
  15694. var pixels = new Uint8Array(3);
  15695. pixels[0] = 0, pixels[1] = 0, pixels[2] = 0;
  15696. blackTexture.setSixSidePixels([pixels, pixels, pixels, pixels, pixels, pixels]);
  15697. blackTexture.lock = true;
  15698. pixels[0] = 128, pixels[1] = 128, pixels[2] = 128;
  15699. grayTexture.setSixSidePixels([pixels, pixels, pixels, pixels, pixels, pixels]);
  15700. grayTexture.lock = true;
  15701. TextureCube._grayTexture = grayTexture;
  15702. TextureCube._blackTexture = blackTexture;
  15703. }
  15704. static _parse(data, propertyParams = null, constructParams = null) {
  15705. var texture = constructParams ? new TextureCube(0, constructParams[0], constructParams[1]) : new TextureCube(0);
  15706. texture.setSixSideImageSources(data);
  15707. return texture;
  15708. }
  15709. static _parseBin(data, propertyParams = null, constructParams = null) {
  15710. var texture = constructParams ? new TextureCube(0, constructParams[0], constructParams[1]) : new TextureCube(0);
  15711. texture.setSixSideImageSources(data);
  15712. return texture;
  15713. }
  15714. static load(url, complete) {
  15715. var extension = (Laya.LoaderManager.createMap[Laya.Utils.getFilecompatibleExtension(url)]) ? Laya.Utils.getFilecompatibleExtension(url) : Laya.Utils.getFileExtension(url);
  15716. var type = Laya.LoaderManager.createMap[extension] ? Laya.LoaderManager.createMap[extension][0] : null;
  15717. Laya.ILaya.loader.create(url, complete, null, type);
  15718. }
  15719. get defaulteTexture() {
  15720. return TextureCube.grayTexture;
  15721. }
  15722. _setPixels(pixels, miplevel, width, height) {
  15723. var gl = Laya.LayaGL.instance;
  15724. var glFormat = this._getGLFormat();
  15725. Laya.WebGLContext.bindTexture(gl, this._glTextureType, this._glTexture);
  15726. if (this.format === Laya.TextureFormat.R8G8B8) {
  15727. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15728. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Z, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[0]);
  15729. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[1]);
  15730. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[2]);
  15731. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_X, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[3]);
  15732. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Y, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[4]);
  15733. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[5]);
  15734. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
  15735. }
  15736. else {
  15737. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Z, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[0]);
  15738. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[1]);
  15739. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[2]);
  15740. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_X, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[3]);
  15741. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Y, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[4]);
  15742. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, miplevel, glFormat, width, height, 0, glFormat, gl.UNSIGNED_BYTE, pixels[5]);
  15743. }
  15744. }
  15745. setSixSideImageSources(source, premultiplyAlpha = false) {
  15746. var width;
  15747. var height;
  15748. for (var i = 0; i < 6; i++) {
  15749. var img = source[i];
  15750. if (!img) {
  15751. console.log("TextureCube: image Source can't be null.");
  15752. return;
  15753. }
  15754. var nextWidth = img.width;
  15755. var nextHeight = img.height;
  15756. if (i > 0) {
  15757. if (width !== nextWidth) {
  15758. console.log("TextureCube: each side image's width and height must same.");
  15759. return;
  15760. }
  15761. }
  15762. width = nextWidth;
  15763. height = nextHeight;
  15764. if (width !== height) {
  15765. console.log("TextureCube: each side image's width and height must same.");
  15766. return;
  15767. }
  15768. }
  15769. this._width = width;
  15770. this._height = height;
  15771. var gl = Laya.LayaGL.instance;
  15772. Laya.WebGLContext.bindTexture(gl, this._glTextureType, this._glTexture);
  15773. var glFormat = this._getGLFormat();
  15774. if (!Laya.Render.isConchApp) {
  15775. (premultiplyAlpha) && (gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true));
  15776. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Z, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[0]);
  15777. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[1]);
  15778. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[2]);
  15779. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_X, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[3]);
  15780. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Y, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[4]);
  15781. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, glFormat, glFormat, gl.UNSIGNED_BYTE, source[5]);
  15782. (premultiplyAlpha) && (gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false));
  15783. }
  15784. else {
  15785. if (premultiplyAlpha == true) {
  15786. for (var j = 0; j < 6; j++)
  15787. source[j].setPremultiplyAlpha(premultiplyAlpha);
  15788. }
  15789. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Z, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[0]);
  15790. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[1]);
  15791. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[2]);
  15792. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_X, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[3]);
  15793. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Y, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[4]);
  15794. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source[5]);
  15795. }
  15796. if (this._mipmap && this._isPot(width) && this._isPot(height)) {
  15797. gl.generateMipmap(this._glTextureType);
  15798. this._setGPUMemory(width * height * 4 * (1 + 1 / 3) * 6);
  15799. }
  15800. else {
  15801. this._setGPUMemory(width * height * 4 * 6);
  15802. }
  15803. this._setWarpMode(gl.TEXTURE_WRAP_S, this._wrapModeU);
  15804. this._setWarpMode(gl.TEXTURE_WRAP_T, this._wrapModeV);
  15805. this._setFilterMode(this._filterMode);
  15806. this._readyed = true;
  15807. this._activeResource();
  15808. }
  15809. setSixSidePixels(pixels, miplevel = 0) {
  15810. if (!pixels)
  15811. throw new Error("TextureCube:pixels can't be null.");
  15812. var width = Math.max(this._width >> miplevel, 1);
  15813. var height = Math.max(this._height >> miplevel, 1);
  15814. var pixelsCount = width * height * this._getFormatByteCount();
  15815. if (pixels[0].length < pixelsCount)
  15816. throw "TextureCube:pixels length should at least " + pixelsCount + ".";
  15817. this._setPixels(pixels, miplevel, width, height);
  15818. if (miplevel === 0) {
  15819. var gl = Laya.LayaGL.instance;
  15820. this._setWarpMode(gl.TEXTURE_WRAP_S, this._wrapModeU);
  15821. this._setWarpMode(gl.TEXTURE_WRAP_T, this._wrapModeV);
  15822. }
  15823. this._readyed = true;
  15824. this._activeResource();
  15825. }
  15826. setImageSource(face, imageSource, miplevel = 0) {
  15827. var width = this._width;
  15828. var height = this._height;
  15829. if (imageSource) {
  15830. if (width !== imageSource.width || height !== imageSource.height) {
  15831. console.log("TextureCube: imageSource's width and height must same.");
  15832. return;
  15833. }
  15834. }
  15835. var gl = Laya.LayaGL.instance;
  15836. Laya.WebGLContext.bindTexture(gl, this._glTextureType, this._glTexture);
  15837. var glFormat = this._getGLFormat();
  15838. switch (face) {
  15839. case exports.TextureCubeFace.NegativeX:
  15840. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_X, miplevel, glFormat, glFormat, gl.UNSIGNED_BYTE, imageSource);
  15841. break;
  15842. case exports.TextureCubeFace.PositiveX:
  15843. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X, miplevel, glFormat, glFormat, gl.UNSIGNED_BYTE, imageSource);
  15844. break;
  15845. case exports.TextureCubeFace.NegativeY:
  15846. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, miplevel, glFormat, glFormat, gl.UNSIGNED_BYTE, imageSource);
  15847. break;
  15848. case exports.TextureCubeFace.PositiveY:
  15849. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Y, miplevel, glFormat, glFormat, gl.UNSIGNED_BYTE, imageSource);
  15850. break;
  15851. case exports.TextureCubeFace.NegativeZ:
  15852. gl.texImage2D(gl.TEXTURE_CUBE_MAP_NEGATIVE_Z, miplevel, glFormat, glFormat, gl.UNSIGNED_BYTE, imageSource);
  15853. break;
  15854. case exports.TextureCubeFace.PositiveZ:
  15855. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_Z, miplevel, glFormat, glFormat, gl.UNSIGNED_BYTE, imageSource);
  15856. break;
  15857. }
  15858. if (this._mipmap && this._isPot(width) && this._isPot(height)) {
  15859. gl.generateMipmap(this._glTextureType);
  15860. this._setGPUMemory(width * height * 4 * (1 + 1 / 3) * 6);
  15861. }
  15862. else {
  15863. this._setGPUMemory(width * height * 4 * 6);
  15864. }
  15865. this._setWarpMode(gl.TEXTURE_WRAP_S, this._wrapModeU);
  15866. this._setWarpMode(gl.TEXTURE_WRAP_T, this._wrapModeV);
  15867. this._setFilterMode(this._filterMode);
  15868. this._readyed = true;
  15869. }
  15870. }
  15871. TextureCube.TEXTURECUBE = "TEXTURECUBE";
  15872. TextureCube.TEXTURECUBEBIN = "TEXTURECUBEBIN";
  15873. class LightQueue {
  15874. constructor() {
  15875. this._length = 0;
  15876. this._elements = [];
  15877. }
  15878. add(light) {
  15879. if (this._length === this._elements.length)
  15880. this._elements.push(light);
  15881. else
  15882. this._elements[this._length] = light;
  15883. this._length++;
  15884. }
  15885. remove(light) {
  15886. var index = this._elements.indexOf(light);
  15887. this._length--;
  15888. if (index !== this._length) {
  15889. var end = this._elements[this._length];
  15890. this._elements[index] = end;
  15891. }
  15892. }
  15893. shift() {
  15894. this._length--;
  15895. return this._elements.shift();
  15896. }
  15897. getBrightestLight() {
  15898. var maxIntIndex;
  15899. var maxIntensity = -1;
  15900. var elements = this._elements;
  15901. for (var i = 0; i < this._length; i++) {
  15902. var intensity = elements[i]._intensity;
  15903. if (maxIntensity < intensity) {
  15904. maxIntensity = intensity;
  15905. maxIntIndex = i;
  15906. }
  15907. }
  15908. return maxIntIndex;
  15909. }
  15910. normalLightOrdering(brightestIndex) {
  15911. var slements = this._elements;
  15912. var firstLight = this._elements[0];
  15913. this._elements[0] = this._elements[brightestIndex];
  15914. this._elements[brightestIndex] = firstLight;
  15915. }
  15916. }
  15917. class AlternateLightQueue extends LightQueue {
  15918. remove(light) {
  15919. var index = this._elements.indexOf(light);
  15920. this._elements.splice(index, 1);
  15921. this._length--;
  15922. }
  15923. }
  15924. class PixelLineMaterial extends Material {
  15925. constructor() {
  15926. super();
  15927. this.setShaderName("LineShader");
  15928. this._shaderValues.setVector(PixelLineMaterial.COLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  15929. }
  15930. static __initDefine__() {
  15931. }
  15932. get color() {
  15933. return this._shaderValues.getVector(PixelLineMaterial.COLOR);
  15934. }
  15935. set color(value) {
  15936. this._shaderValues.setVector(PixelLineMaterial.COLOR, value);
  15937. }
  15938. clone() {
  15939. var dest = new PixelLineMaterial();
  15940. this.cloneTo(dest);
  15941. return dest;
  15942. }
  15943. }
  15944. PixelLineMaterial.COLOR = Shader3D.propertyNameToID("u_Color");
  15945. class BoundBox {
  15946. constructor(min, max) {
  15947. this.min = min;
  15948. this.max = max;
  15949. }
  15950. _rotateExtents(extents, rotation, out) {
  15951. var extentsX = extents.x;
  15952. var extentsY = extents.y;
  15953. var extentsZ = extents.z;
  15954. var matElements = rotation.elements;
  15955. out.x = Math.abs(matElements[0] * extentsX) + Math.abs(matElements[4] * extentsY) + Math.abs(matElements[8] * extentsZ);
  15956. out.y = Math.abs(matElements[1] * extentsX) + Math.abs(matElements[5] * extentsY) + Math.abs(matElements[9] * extentsZ);
  15957. out.z = Math.abs(matElements[2] * extentsX) + Math.abs(matElements[6] * extentsY) + Math.abs(matElements[10] * extentsZ);
  15958. }
  15959. getCorners(corners) {
  15960. corners.length = 8;
  15961. var minX = this.min.x;
  15962. var minY = this.min.y;
  15963. var minZ = this.min.z;
  15964. var maxX = this.max.x;
  15965. var maxY = this.max.y;
  15966. var maxZ = this.max.z;
  15967. corners[0] = new Vector3(minX, maxY, maxZ);
  15968. corners[1] = new Vector3(maxX, maxY, maxZ);
  15969. corners[2] = new Vector3(maxX, minY, maxZ);
  15970. corners[3] = new Vector3(minX, minY, maxZ);
  15971. corners[4] = new Vector3(minX, maxY, minZ);
  15972. corners[5] = new Vector3(maxX, maxY, minZ);
  15973. corners[6] = new Vector3(maxX, minY, minZ);
  15974. corners[7] = new Vector3(minX, minY, minZ);
  15975. }
  15976. getCenter(out) {
  15977. Vector3.add(this.min, this.max, out);
  15978. Vector3.scale(out, 0.5, out);
  15979. }
  15980. getExtent(out) {
  15981. Vector3.subtract(this.max, this.min, out);
  15982. Vector3.scale(out, 0.5, out);
  15983. }
  15984. setCenterAndExtent(center, extent) {
  15985. Vector3.subtract(center, extent, this.min);
  15986. Vector3.add(center, extent, this.max);
  15987. }
  15988. tranform(matrix, out) {
  15989. var center = BoundBox._tempVector30;
  15990. var extent = BoundBox._tempVector31;
  15991. this.getCenter(center);
  15992. this.getExtent(extent);
  15993. Vector3.transformCoordinate(center, matrix, center);
  15994. this._rotateExtents(extent, matrix, extent);
  15995. out.setCenterAndExtent(center, extent);
  15996. }
  15997. toDefault() {
  15998. this.min.toDefault();
  15999. this.max.toDefault();
  16000. }
  16001. static createfromPoints(points, out) {
  16002. if (points == null)
  16003. throw new Error("points");
  16004. var min = out.min;
  16005. var max = out.max;
  16006. min.x = Number.MAX_VALUE;
  16007. min.y = Number.MAX_VALUE;
  16008. min.z = Number.MAX_VALUE;
  16009. max.x = -Number.MAX_VALUE;
  16010. max.y = -Number.MAX_VALUE;
  16011. max.z = -Number.MAX_VALUE;
  16012. for (var i = 0, n = points.length; i < n; ++i) {
  16013. Vector3.min(min, points[i], min);
  16014. Vector3.max(max, points[i], max);
  16015. }
  16016. }
  16017. static merge(box1, box2, out) {
  16018. Vector3.min(box1.min, box2.min, out.min);
  16019. Vector3.max(box1.max, box2.max, out.max);
  16020. }
  16021. cloneTo(destObject) {
  16022. var dest = destObject;
  16023. this.min.cloneTo(dest.min);
  16024. this.max.cloneTo(dest.max);
  16025. }
  16026. clone() {
  16027. var dest = new BoundBox(new Vector3(), new Vector3());
  16028. this.cloneTo(dest);
  16029. return dest;
  16030. }
  16031. }
  16032. BoundBox._tempVector30 = new Vector3();
  16033. BoundBox._tempVector31 = new Vector3();
  16034. class Bounds {
  16035. constructor(min, max) {
  16036. this._updateFlag = 0;
  16037. this._center = new Vector3();
  16038. this._extent = new Vector3();
  16039. this._boundBox = new BoundBox(new Vector3(), new Vector3());
  16040. min.cloneTo(this._boundBox.min);
  16041. max.cloneTo(this._boundBox.max);
  16042. this._setUpdateFlag(Bounds._UPDATE_CENTER | Bounds._UPDATE_EXTENT, true);
  16043. }
  16044. setMin(value) {
  16045. var min = this._boundBox.min;
  16046. if (value !== min)
  16047. value.cloneTo(min);
  16048. this._setUpdateFlag(Bounds._UPDATE_CENTER | Bounds._UPDATE_EXTENT, true);
  16049. this._setUpdateFlag(Bounds._UPDATE_MIN, false);
  16050. }
  16051. getMin() {
  16052. var min = this._boundBox.min;
  16053. if (this._getUpdateFlag(Bounds._UPDATE_MIN)) {
  16054. this._getMin(this.getCenter(), this.getExtent(), min);
  16055. this._setUpdateFlag(Bounds._UPDATE_MIN, false);
  16056. }
  16057. return min;
  16058. }
  16059. setMax(value) {
  16060. var max = this._boundBox.max;
  16061. if (value !== max)
  16062. value.cloneTo(max);
  16063. this._setUpdateFlag(Bounds._UPDATE_CENTER | Bounds._UPDATE_EXTENT, true);
  16064. this._setUpdateFlag(Bounds._UPDATE_MAX, false);
  16065. }
  16066. getMax() {
  16067. var max = this._boundBox.max;
  16068. if (this._getUpdateFlag(Bounds._UPDATE_MAX)) {
  16069. this._getMax(this.getCenter(), this.getExtent(), max);
  16070. this._setUpdateFlag(Bounds._UPDATE_MAX, false);
  16071. }
  16072. return max;
  16073. }
  16074. setCenter(value) {
  16075. if (value !== this._center)
  16076. value.cloneTo(this._center);
  16077. this._setUpdateFlag(Bounds._UPDATE_MIN | Bounds._UPDATE_MAX, true);
  16078. this._setUpdateFlag(Bounds._UPDATE_CENTER, false);
  16079. }
  16080. getCenter() {
  16081. if (this._getUpdateFlag(Bounds._UPDATE_CENTER)) {
  16082. this._getCenter(this.getMin(), this.getMax(), this._center);
  16083. this._setUpdateFlag(Bounds._UPDATE_CENTER, false);
  16084. }
  16085. return this._center;
  16086. }
  16087. setExtent(value) {
  16088. if (value !== this._extent)
  16089. value.cloneTo(this._extent);
  16090. this._setUpdateFlag(Bounds._UPDATE_MIN | Bounds._UPDATE_MAX, true);
  16091. this._setUpdateFlag(Bounds._UPDATE_EXTENT, false);
  16092. }
  16093. getExtent() {
  16094. if (this._getUpdateFlag(Bounds._UPDATE_EXTENT)) {
  16095. this._getExtent(this.getMin(), this.getMax(), this._extent);
  16096. this._setUpdateFlag(Bounds._UPDATE_EXTENT, false);
  16097. }
  16098. return this._extent;
  16099. }
  16100. _getUpdateFlag(type) {
  16101. return (this._updateFlag & type) != 0;
  16102. }
  16103. _setUpdateFlag(type, value) {
  16104. if (value)
  16105. this._updateFlag |= type;
  16106. else
  16107. this._updateFlag &= ~type;
  16108. }
  16109. _getCenter(min, max, out) {
  16110. Vector3.add(min, max, out);
  16111. Vector3.scale(out, 0.5, out);
  16112. }
  16113. _getExtent(min, max, out) {
  16114. Vector3.subtract(max, min, out);
  16115. Vector3.scale(out, 0.5, out);
  16116. }
  16117. _getMin(center, extent, out) {
  16118. Vector3.subtract(center, extent, out);
  16119. }
  16120. _getMax(center, extent, out) {
  16121. Vector3.add(center, extent, out);
  16122. }
  16123. _rotateExtents(extents, rotation, out) {
  16124. var extentsX = extents.x;
  16125. var extentsY = extents.y;
  16126. var extentsZ = extents.z;
  16127. var matE = rotation.elements;
  16128. out.x = Math.abs(matE[0] * extentsX) + Math.abs(matE[4] * extentsY) + Math.abs(matE[8] * extentsZ);
  16129. out.y = Math.abs(matE[1] * extentsX) + Math.abs(matE[5] * extentsY) + Math.abs(matE[9] * extentsZ);
  16130. out.z = Math.abs(matE[2] * extentsX) + Math.abs(matE[6] * extentsY) + Math.abs(matE[10] * extentsZ);
  16131. }
  16132. _tranform(matrix, out) {
  16133. var outCen = out._center;
  16134. var outExt = out._extent;
  16135. Vector3.transformCoordinate(this.getCenter(), matrix, outCen);
  16136. this._rotateExtents(this.getExtent(), matrix, outExt);
  16137. out._boundBox.setCenterAndExtent(outCen, outExt);
  16138. out._updateFlag = 0;
  16139. }
  16140. _getBoundBox() {
  16141. if (this._updateFlag & Bounds._UPDATE_MIN) {
  16142. var min = this._boundBox.min;
  16143. this._getMin(this.getCenter(), this.getExtent(), min);
  16144. this._setUpdateFlag(Bounds._UPDATE_MIN, false);
  16145. }
  16146. if (this._updateFlag & Bounds._UPDATE_MAX) {
  16147. var max = this._boundBox.max;
  16148. this._getMax(this.getCenter(), this.getExtent(), max);
  16149. this._setUpdateFlag(Bounds._UPDATE_MAX, false);
  16150. }
  16151. return this._boundBox;
  16152. }
  16153. calculateBoundsintersection(bounds) {
  16154. var ownMax = this.getMax();
  16155. var ownMin = this.getMin();
  16156. var calMax = bounds.getMax();
  16157. var calMin = bounds.getMin();
  16158. var tempV0 = Bounds.TEMP_VECTOR3_MAX0;
  16159. var tempV1 = Bounds.TEMP_VECTOR3_MAX1;
  16160. var thisExtends = this.getExtent();
  16161. var boundExtends = bounds.getExtent();
  16162. tempV0.setValue(Math.max(ownMax.x, calMax.x) - Math.min(ownMin.x, calMin.x), Math.max(ownMax.y, calMax.y) - Math.min(ownMin.y, calMin.y), Math.max(ownMax.z, calMax.z) - Math.min(ownMin.z, calMin.z));
  16163. tempV1.setValue((thisExtends.x + boundExtends.x) * 2.0, (thisExtends.y + boundExtends.y) * 2.0, (thisExtends.z + boundExtends.z) * 2.0);
  16164. if ((tempV0.x) > (tempV1.x))
  16165. return -1;
  16166. if ((tempV0.y) > (tempV1.y))
  16167. return -1;
  16168. if ((tempV0.z) > (tempV1.z))
  16169. return -1;
  16170. return (tempV1.x - tempV0.x) * (tempV1.y - tempV0.y) * (tempV1.z - tempV0.z);
  16171. }
  16172. cloneTo(destObject) {
  16173. var destBounds = destObject;
  16174. this.getMin().cloneTo(destBounds._boundBox.min);
  16175. this.getMax().cloneTo(destBounds._boundBox.max);
  16176. this.getCenter().cloneTo(destBounds._center);
  16177. this.getExtent().cloneTo(destBounds._extent);
  16178. destBounds._updateFlag = 0;
  16179. }
  16180. clone() {
  16181. var dest = new Bounds(new Vector3(), new Vector3());
  16182. this.cloneTo(dest);
  16183. return dest;
  16184. }
  16185. }
  16186. Bounds._UPDATE_MIN = 0x01;
  16187. Bounds._UPDATE_MAX = 0x02;
  16188. Bounds._UPDATE_CENTER = 0x04;
  16189. Bounds._UPDATE_EXTENT = 0x08;
  16190. Bounds.TEMP_VECTOR3_MAX0 = new Vector3();
  16191. Bounds.TEMP_VECTOR3_MAX1 = new Vector3();
  16192. class GeometryElement {
  16193. constructor() {
  16194. this._destroyed = false;
  16195. }
  16196. get destroyed() {
  16197. return this._destroyed;
  16198. }
  16199. _getType() {
  16200. throw "GeometryElement:must override it.";
  16201. }
  16202. _prepareRender(state) {
  16203. return true;
  16204. }
  16205. _render(state) {
  16206. throw "GeometryElement:must override it.";
  16207. }
  16208. destroy() {
  16209. if (this._destroyed)
  16210. return;
  16211. this._destroyed = true;
  16212. }
  16213. }
  16214. GeometryElement._typeCounter = 0;
  16215. class PixelLineVertex {
  16216. constructor() {
  16217. }
  16218. static get vertexDeclaration() {
  16219. return PixelLineVertex._vertexDeclaration;
  16220. }
  16221. static __init__() {
  16222. PixelLineVertex._vertexDeclaration = new VertexDeclaration(28, [new VertexElement(0, VertexElementFormat.Vector3, VertexMesh.MESH_POSITION0),
  16223. new VertexElement(12, VertexElementFormat.Vector4, VertexMesh.MESH_COLOR0)]);
  16224. }
  16225. get vertexDeclaration() {
  16226. return PixelLineVertex._vertexDeclaration;
  16227. }
  16228. }
  16229. class PixelLineFilter extends GeometryElement {
  16230. constructor(owner, maxLineCount) {
  16231. super();
  16232. this._floatCountPerVertices = 7;
  16233. this._minUpdate = Number.MAX_VALUE;
  16234. this._maxUpdate = Number.MIN_VALUE;
  16235. this._bufferState = new BufferState();
  16236. this._floatBound = new Float32Array(6);
  16237. this._calculateBound = false;
  16238. this._maxLineCount = 0;
  16239. this._lineCount = 0;
  16240. var pointCount = maxLineCount * 2;
  16241. this._owner = owner;
  16242. this._maxLineCount = maxLineCount;
  16243. this._vertices = new Float32Array(pointCount * this._floatCountPerVertices);
  16244. this._vertexBuffer = new VertexBuffer3D(PixelLineVertex.vertexDeclaration.vertexStride * pointCount, Laya.LayaGL.instance.STATIC_DRAW, false);
  16245. this._vertexBuffer.vertexDeclaration = PixelLineVertex.vertexDeclaration;
  16246. this._bufferState.bind();
  16247. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  16248. this._bufferState.unBind();
  16249. var min = PixelLineFilter._tempVector0;
  16250. var max = PixelLineFilter._tempVector1;
  16251. min.setValue(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16252. max.setValue(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16253. this._bounds = new Bounds(min, max);
  16254. }
  16255. _getType() {
  16256. return PixelLineFilter._type;
  16257. }
  16258. _resizeLineData(maxCount) {
  16259. var pointCount = maxCount * 2;
  16260. var lastVertices = this._vertices;
  16261. this._vertexBuffer.destroy();
  16262. this._maxLineCount = maxCount;
  16263. var vertexCount = pointCount * this._floatCountPerVertices;
  16264. this._vertices = new Float32Array(vertexCount);
  16265. this._vertexBuffer = new VertexBuffer3D(PixelLineVertex.vertexDeclaration.vertexStride * pointCount, Laya.LayaGL.instance.STATIC_DRAW, false);
  16266. this._vertexBuffer.vertexDeclaration = PixelLineVertex.vertexDeclaration;
  16267. if (vertexCount < lastVertices.length) {
  16268. this._vertices.set(new Float32Array(lastVertices.buffer, 0, vertexCount));
  16269. this._vertexBuffer.setData(this._vertices.buffer, 0, 0, vertexCount * 4);
  16270. }
  16271. else {
  16272. this._vertices.set(lastVertices);
  16273. this._vertexBuffer.setData(this._vertices.buffer, 0, 0, lastVertices.length * 4);
  16274. }
  16275. this._bufferState.bind();
  16276. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  16277. this._bufferState.unBind();
  16278. }
  16279. _updateLineVertices(offset, startPosition, endPosition, startColor, endColor) {
  16280. if (startPosition) {
  16281. this._vertices[offset + 0] = startPosition.x;
  16282. this._vertices[offset + 1] = startPosition.y;
  16283. this._vertices[offset + 2] = startPosition.z;
  16284. }
  16285. if (startColor) {
  16286. this._vertices[offset + 3] = startColor.r;
  16287. this._vertices[offset + 4] = startColor.g;
  16288. this._vertices[offset + 5] = startColor.b;
  16289. this._vertices[offset + 6] = startColor.a;
  16290. }
  16291. if (endPosition) {
  16292. this._vertices[offset + 7] = endPosition.x;
  16293. this._vertices[offset + 8] = endPosition.y;
  16294. this._vertices[offset + 9] = endPosition.z;
  16295. }
  16296. if (endColor) {
  16297. this._vertices[offset + 10] = endColor.r;
  16298. this._vertices[offset + 11] = endColor.g;
  16299. this._vertices[offset + 12] = endColor.b;
  16300. this._vertices[offset + 13] = endColor.a;
  16301. }
  16302. this._minUpdate = Math.min(this._minUpdate, offset);
  16303. this._maxUpdate = Math.max(this._maxUpdate, offset + this._floatCountPerVertices * 2);
  16304. var bounds = this._bounds;
  16305. var floatBound = this._floatBound;
  16306. var min = bounds.getMin(), max = bounds.getMax();
  16307. Vector3.min(min, startPosition, min);
  16308. Vector3.min(min, endPosition, min);
  16309. Vector3.max(max, startPosition, max);
  16310. Vector3.max(max, endPosition, max);
  16311. bounds.setMin(min);
  16312. bounds.setMax(max);
  16313. floatBound[0] = min.x, floatBound[1] = min.y, floatBound[2] = min.z;
  16314. floatBound[3] = max.x, floatBound[4] = max.y, floatBound[5] = max.z;
  16315. }
  16316. _reCalculateBound() {
  16317. if (this._calculateBound) {
  16318. var vertices = this._vertices;
  16319. var min = PixelLineFilter._tempVector0;
  16320. var max = PixelLineFilter._tempVector1;
  16321. min.setValue(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16322. max.setValue(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16323. for (var i = 0; i < this._lineCount * 2; ++i) {
  16324. var offset = this._floatCountPerVertices * i;
  16325. var x = vertices[offset + 0], y = vertices[offset + 1], z = vertices[offset + 2];
  16326. min.x = Math.min(x, min.x);
  16327. min.y = Math.min(y, min.y);
  16328. min.z = Math.min(z, min.z);
  16329. max.x = Math.max(x, max.x);
  16330. max.y = Math.max(y, max.y);
  16331. max.z = Math.max(z, max.z);
  16332. }
  16333. this._bounds.setMin(min);
  16334. this._bounds.setMax(max);
  16335. var floatBound = this._floatBound;
  16336. floatBound[0] = min.x, floatBound[1] = min.y, floatBound[2] = min.z;
  16337. floatBound[3] = max.x, floatBound[4] = max.y, floatBound[5] = max.z;
  16338. this._calculateBound = false;
  16339. }
  16340. }
  16341. _removeLineData(index) {
  16342. var floatCount = this._floatCountPerVertices * 2;
  16343. var nextIndex = index + 1;
  16344. var offset = index * floatCount;
  16345. var vertices = this._vertices;
  16346. var rightPartVertices = new Float32Array(vertices.buffer, nextIndex * floatCount * 4, (this._lineCount - nextIndex) * floatCount);
  16347. vertices.set(rightPartVertices, offset);
  16348. this._minUpdate = Math.min(this._minUpdate, offset);
  16349. this._maxUpdate = Math.max(this._maxUpdate, offset + rightPartVertices.length);
  16350. this._lineCount--;
  16351. var floatBound = this._floatBound;
  16352. var startX = vertices[offset], startY = vertices[offset + 1], startZ = vertices[offset + 2];
  16353. var endX = vertices[offset + 7], endY = vertices[offset + 8], endZ = vertices[offset + 9];
  16354. var minX = floatBound[0], minY = floatBound[1], minZ = floatBound[2];
  16355. var maxX = floatBound[3], maxY = floatBound[4], maxZ = floatBound[5];
  16356. if ((startX === minX) || (startX === maxX) || (startY === minY) || (startY === maxY) || (startZ === minZ) || (startZ === maxZ) ||
  16357. (endX === minX) || (endX === maxX) || (endY === minY) || (endY === maxY) || (endZ === minZ) || (endZ === maxZ))
  16358. this._calculateBound = true;
  16359. }
  16360. _updateLineData(index, startPosition, endPosition, startColor, endColor) {
  16361. var floatCount = this._floatCountPerVertices * 2;
  16362. this._updateLineVertices(index * floatCount, startPosition, endPosition, startColor, endColor);
  16363. }
  16364. _updateLineDatas(index, data) {
  16365. var floatCount = this._floatCountPerVertices * 2;
  16366. var count = data.length;
  16367. for (var i = 0; i < count; i++) {
  16368. var line = data[i];
  16369. this._updateLineVertices((index + i) * floatCount, line.startPosition, line.endPosition, line.startColor, line.endColor);
  16370. }
  16371. }
  16372. _getLineData(index, out) {
  16373. var startPosition = out.startPosition;
  16374. var startColor = out.startColor;
  16375. var endPosition = out.endPosition;
  16376. var endColor = out.endColor;
  16377. var vertices = this._vertices;
  16378. var offset = index * this._floatCountPerVertices * 2;
  16379. startPosition.x = vertices[offset + 0];
  16380. startPosition.y = vertices[offset + 1];
  16381. startPosition.z = vertices[offset + 2];
  16382. startColor.r = vertices[offset + 3];
  16383. startColor.g = vertices[offset + 4];
  16384. startColor.b = vertices[offset + 5];
  16385. startColor.a = vertices[offset + 6];
  16386. endPosition.x = vertices[offset + 7];
  16387. endPosition.y = vertices[offset + 8];
  16388. endPosition.z = vertices[offset + 9];
  16389. endColor.r = vertices[offset + 10];
  16390. endColor.g = vertices[offset + 11];
  16391. endColor.b = vertices[offset + 12];
  16392. endColor.a = vertices[offset + 13];
  16393. }
  16394. _prepareRender(state) {
  16395. return true;
  16396. }
  16397. _render(state) {
  16398. if (this._minUpdate !== Number.MAX_VALUE && this._maxUpdate !== Number.MIN_VALUE) {
  16399. this._vertexBuffer.setData(this._vertices.buffer, this._minUpdate * 4, this._minUpdate * 4, (this._maxUpdate - this._minUpdate) * 4);
  16400. this._minUpdate = Number.MAX_VALUE;
  16401. this._maxUpdate = Number.MIN_VALUE;
  16402. }
  16403. if (this._lineCount > 0) {
  16404. this._bufferState.bind();
  16405. var gl = Laya.LayaGL.instance;
  16406. gl.drawArrays(gl.LINES, 0, this._lineCount * 2);
  16407. Laya.Stat.renderBatches++;
  16408. }
  16409. }
  16410. destroy() {
  16411. if (this._destroyed)
  16412. return;
  16413. super.destroy();
  16414. this._bufferState.destroy();
  16415. this._vertexBuffer.destroy();
  16416. this._bufferState = null;
  16417. this._vertexBuffer = null;
  16418. this._vertices = null;
  16419. }
  16420. }
  16421. PixelLineFilter._tempVector0 = new Vector3();
  16422. PixelLineFilter._tempVector1 = new Vector3();
  16423. PixelLineFilter._type = GeometryElement._typeCounter++;
  16424. class RenderableSprite3D extends Sprite3D {
  16425. constructor(name) {
  16426. super(name);
  16427. }
  16428. static __init__() {
  16429. RenderableSprite3D.SHADERDEFINE_RECEIVE_SHADOW = Shader3D.getDefineByName("RECEIVESHADOW");
  16430. RenderableSprite3D.SAHDERDEFINE_LIGHTMAP = Shader3D.getDefineByName("LIGHTMAP");
  16431. RenderableSprite3D.SHADERDEFINE_LIGHTMAP_DIRECTIONAL = Shader3D.getDefineByName("LIGHTMAP_DIRECTIONAL");
  16432. }
  16433. _onInActive() {
  16434. super._onInActive();
  16435. this._scene._removeRenderObject(this._render);
  16436. }
  16437. _onActive() {
  16438. super._onActive();
  16439. this._scene._addRenderObject(this._render);
  16440. }
  16441. _onActiveInScene() {
  16442. super._onActiveInScene();
  16443. if (ILaya3D.Laya3D._editerEnvironment) {
  16444. var scene = this._scene;
  16445. var pickColor = new Vector4();
  16446. scene._allotPickColorByID(this.id, pickColor);
  16447. scene._pickIdToSprite[this.id] = this;
  16448. this._render._shaderValues.setVector(RenderableSprite3D.PICKCOLOR, pickColor);
  16449. }
  16450. }
  16451. _addToInitStaticBatchManager() {
  16452. }
  16453. _setBelongScene(scene) {
  16454. super._setBelongScene(scene);
  16455. this._render._setBelongScene(scene);
  16456. }
  16457. _setUnBelongScene() {
  16458. this._render._shaderValues.removeDefine(RenderableSprite3D.SAHDERDEFINE_LIGHTMAP);
  16459. super._setUnBelongScene();
  16460. }
  16461. _changeHierarchyAnimator(animator) {
  16462. if (this._hierarchyAnimator) {
  16463. var renderableSprites = this._hierarchyAnimator._renderableSprites;
  16464. renderableSprites.splice(renderableSprites.indexOf(this), 1);
  16465. }
  16466. if (animator)
  16467. animator._renderableSprites.push(this);
  16468. super._changeHierarchyAnimator(animator);
  16469. }
  16470. destroy(destroyChild = true) {
  16471. super.destroy(destroyChild);
  16472. this._render._destroy();
  16473. this._render = null;
  16474. }
  16475. _create() {
  16476. return new RenderableSprite3D(this.name);
  16477. }
  16478. }
  16479. RenderableSprite3D.LIGHTMAPSCALEOFFSET = Shader3D.propertyNameToID("u_LightmapScaleOffset");
  16480. RenderableSprite3D.LIGHTMAP = Shader3D.propertyNameToID("u_LightMap");
  16481. RenderableSprite3D.LIGHTMAP_DIRECTION = Shader3D.propertyNameToID("u_LightMapDirection");
  16482. RenderableSprite3D.PICKCOLOR = Shader3D.propertyNameToID("u_PickColor");
  16483. RenderableSprite3D.REFLECTIONTEXTURE = Shader3D.propertyNameToID("u_ReflectTexture");
  16484. RenderableSprite3D.REFLECTIONCUBE_HDR_PARAMS = Shader3D.propertyNameToID("u_ReflectCubeHDRParams");
  16485. RenderableSprite3D.REFLECTIONCUBE_PROBEPOSITION = Shader3D.propertyNameToID("u_SpecCubeProbePosition");
  16486. RenderableSprite3D.REFLECTIONCUBE_PROBEBOXMAX = Shader3D.propertyNameToID("u_SpecCubeBoxMax");
  16487. RenderableSprite3D.REFLECTIONCUBE_PROBEBOXMIN = Shader3D.propertyNameToID("u_SpecCubeBoxMin");
  16488. class BatchMark {
  16489. constructor() {
  16490. this.updateMark = -1;
  16491. this.indexInList = -1;
  16492. this.batched = false;
  16493. }
  16494. }
  16495. class SubMeshInstanceBatch extends GeometryElement {
  16496. constructor() {
  16497. super();
  16498. this.maxInstanceCount = 1024;
  16499. this.instanceWorldMatrixData = new Float32Array(this.maxInstanceCount * 16);
  16500. this.instanceMVPMatrixData = new Float32Array(this.maxInstanceCount * 16);
  16501. this.instanceSimpleAnimatorData = new Float32Array(this.maxInstanceCount * 4);
  16502. var gl = Laya.LayaGL.instance;
  16503. this.instanceWorldMatrixBuffer = new VertexBuffer3D(this.instanceWorldMatrixData.length * 4, gl.DYNAMIC_DRAW);
  16504. this.instanceMVPMatrixBuffer = new VertexBuffer3D(this.instanceMVPMatrixData.length * 4, gl.DYNAMIC_DRAW);
  16505. this.instanceWorldMatrixBuffer.vertexDeclaration = VertexMesh.instanceWorldMatrixDeclaration;
  16506. this.instanceMVPMatrixBuffer.vertexDeclaration = VertexMesh.instanceMVPMatrixDeclaration;
  16507. this.instanceSimpleAnimatorBuffer = new VertexBuffer3D(this.instanceSimpleAnimatorData.length * 4, gl.DYNAMIC_DRAW);
  16508. this.instanceSimpleAnimatorBuffer.vertexDeclaration = VertexMesh.instanceSimpleAnimatorDeclaration;
  16509. }
  16510. static __init__() {
  16511. SubMeshInstanceBatch.instance = new SubMeshInstanceBatch();
  16512. }
  16513. _render(state) {
  16514. var gl = Laya.LayaGL.instance;
  16515. var element = state.renderElement;
  16516. var subMesh = element.instanceSubMesh;
  16517. var count = element.instanceBatchElementList.length;
  16518. var indexCount = subMesh._indexCount;
  16519. subMesh._mesh._instanceBufferState.bind();
  16520. Laya.LayaGL.layaGPUInstance.drawElementsInstanced(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, subMesh._indexStart * 2, count);
  16521. Laya.Stat.renderBatches++;
  16522. Laya.Stat.savedRenderBatches += count - 1;
  16523. Laya.Stat.trianglesFaces += indexCount * count / 3;
  16524. }
  16525. }
  16526. class SubMeshRenderElement extends RenderElement {
  16527. constructor() {
  16528. super();
  16529. this._dynamicWorldPositionNormalNeedUpdate = true;
  16530. }
  16531. _onWorldMatrixChanged() {
  16532. this._dynamicWorldPositionNormalNeedUpdate = true;
  16533. }
  16534. _computeWorldPositionsAndNormals(positionOffset, normalOffset, multiSubMesh, vertexCount) {
  16535. if (this._dynamicWorldPositionNormalNeedUpdate) {
  16536. var subMesh = this._geometry;
  16537. var vertexBuffer = subMesh._vertexBuffer;
  16538. var vertexFloatCount = vertexBuffer.vertexDeclaration.vertexStride / 4;
  16539. var oriVertexes = vertexBuffer.getFloat32Data();
  16540. var worldMat = this._transform.worldMatrix;
  16541. var rotation = this._transform.rotation;
  16542. var indices = subMesh._indices;
  16543. for (var i = 0; i < vertexCount; i++) {
  16544. var index = multiSubMesh ? indices[i] : i;
  16545. var oriOffset = index * vertexFloatCount;
  16546. var bakeOffset = i * 3;
  16547. Utils3D.transformVector3ArrayToVector3ArrayCoordinate(oriVertexes, oriOffset + positionOffset, worldMat, this._dynamicWorldPositions, bakeOffset);
  16548. (normalOffset !== -1) && (Utils3D.transformVector3ArrayByQuat(oriVertexes, oriOffset + normalOffset, rotation, this._dynamicWorldNormals, bakeOffset));
  16549. }
  16550. this._dynamicWorldPositionNormalNeedUpdate = false;
  16551. }
  16552. }
  16553. setTransform(transform) {
  16554. if (this._transform !== transform) {
  16555. (this._transform) && (this._transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatrixChanged));
  16556. (transform) && (transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatrixChanged));
  16557. this._dynamicWorldPositionNormalNeedUpdate = true;
  16558. this._transform = transform;
  16559. }
  16560. }
  16561. setGeometry(geometry) {
  16562. if (this._geometry !== geometry) {
  16563. var subMesh = geometry;
  16564. var mesh = subMesh._mesh;
  16565. if (mesh) {
  16566. var multiSubMesh = mesh._subMeshes.length > 1;
  16567. var dynBatVerCount = multiSubMesh ? subMesh._indexCount : mesh._vertexCount;
  16568. if (dynBatVerCount <= ILaya3D.SubMeshDynamicBatch.maxAllowVertexCount) {
  16569. var length = dynBatVerCount * 3;
  16570. this._dynamicVertexBatch = true;
  16571. this._dynamicWorldPositions = new Float32Array(length);
  16572. this._dynamicWorldNormals = new Float32Array(length);
  16573. this._dynamicVertexCount = dynBatVerCount;
  16574. this._dynamicMultiSubMesh = multiSubMesh;
  16575. }
  16576. else {
  16577. this._dynamicVertexBatch = false;
  16578. }
  16579. }
  16580. this._geometry = geometry;
  16581. }
  16582. }
  16583. addToOpaqueRenderQueue(context, queue) {
  16584. var subMeshStaticBatch = this.staticBatch;
  16585. var queueElements = queue.elements;
  16586. var elements = queueElements.elements;
  16587. if (subMeshStaticBatch && (!this.render._probReflection || this.render._probReflection._isScene)) {
  16588. var staManager = ILaya3D.MeshRenderStaticBatchManager.instance;
  16589. var staBatchMarks = staManager.getBatchOpaquaMark(this.render.lightmapIndex + 1, this.render.receiveShadow, this.material.id, subMeshStaticBatch._batchID);
  16590. if (staManager._updateCountMark === staBatchMarks.updateMark) {
  16591. var staBatchIndex = staBatchMarks.indexInList;
  16592. if (staBatchMarks.batched) {
  16593. elements[staBatchIndex].staticBatchElementList.add(this);
  16594. }
  16595. else {
  16596. var staOriElement = elements[staBatchIndex];
  16597. var staOriRender = staOriElement.render;
  16598. var staBatchElement = staManager._getBatchRenderElementFromPool();
  16599. staBatchElement.renderType = RenderElement.RENDERTYPE_STATICBATCH;
  16600. staBatchElement.setGeometry(subMeshStaticBatch);
  16601. staBatchElement.material = staOriElement.material;
  16602. var staRootOwner = subMeshStaticBatch.batchOwner;
  16603. var staBatchTransform = staRootOwner ? staRootOwner._transform : null;
  16604. staBatchElement.setTransform(staBatchTransform);
  16605. staBatchElement.render = staOriRender;
  16606. staBatchElement.renderSubShader = staOriElement.renderSubShader;
  16607. var staBatchList = staBatchElement.staticBatchElementList;
  16608. staBatchList.length = 0;
  16609. staBatchList.add(staOriElement);
  16610. staBatchList.add(this);
  16611. elements[staBatchIndex] = staBatchElement;
  16612. staBatchMarks.batched = true;
  16613. }
  16614. }
  16615. else {
  16616. staBatchMarks.updateMark = staManager._updateCountMark;
  16617. staBatchMarks.indexInList = queueElements.length;
  16618. staBatchMarks.batched = false;
  16619. queueElements.add(this);
  16620. }
  16621. }
  16622. else if (this.renderSubShader._owner._enableInstancing && Laya.LayaGL.layaGPUInstance.supportInstance() && this.render.lightmapIndex < 0 && (!this.render._probReflection || this.render._probReflection._isScene)) {
  16623. var subMesh = this._geometry;
  16624. var insManager = ILaya3D.MeshRenderDynamicBatchManager.instance;
  16625. var insBatchMarks = insManager.getInstanceBatchOpaquaMark(this.render.receiveShadow, this.material.id, subMesh._id, this._transform._isFrontFaceInvert);
  16626. if (insManager._updateCountMark === insBatchMarks.updateMark) {
  16627. var insBatchIndex = insBatchMarks.indexInList;
  16628. if (insBatchMarks.batched) {
  16629. var instanceBatchElementList = elements[insBatchIndex].instanceBatchElementList;
  16630. if (instanceBatchElementList.length === SubMeshInstanceBatch.instance.maxInstanceCount) {
  16631. insBatchMarks.updateMark = insManager._updateCountMark;
  16632. insBatchMarks.indexInList = queueElements.length;
  16633. insBatchMarks.batched = false;
  16634. queueElements.add(this);
  16635. }
  16636. else {
  16637. instanceBatchElementList.add(this);
  16638. }
  16639. }
  16640. else {
  16641. var insOriElement = elements[insBatchIndex];
  16642. var insOriRender = insOriElement.render;
  16643. var insBatchElement = insManager._getBatchRenderElementFromPool();
  16644. insBatchElement.renderType = RenderElement.RENDERTYPE_INSTANCEBATCH;
  16645. insBatchElement.setGeometry(SubMeshInstanceBatch.instance);
  16646. insBatchElement.material = insOriElement.material;
  16647. insBatchElement.setTransform(null);
  16648. insBatchElement.render = insOriRender;
  16649. insBatchElement.instanceSubMesh = subMesh;
  16650. insBatchElement.renderSubShader = insOriElement.renderSubShader;
  16651. var insBatchList = insBatchElement.instanceBatchElementList;
  16652. insBatchList.length = 0;
  16653. insBatchList.add(insOriElement);
  16654. insBatchList.add(this);
  16655. elements[insBatchIndex] = insBatchElement;
  16656. insBatchMarks.batched = true;
  16657. }
  16658. }
  16659. else {
  16660. insBatchMarks.updateMark = insManager._updateCountMark;
  16661. insBatchMarks.indexInList = queueElements.length;
  16662. insBatchMarks.batched = false;
  16663. queueElements.add(this);
  16664. }
  16665. }
  16666. else if (this._dynamicVertexBatch) {
  16667. var verDec = this._geometry._vertexBuffer.vertexDeclaration;
  16668. var dynManager = ILaya3D.MeshRenderDynamicBatchManager.instance;
  16669. var dynBatchMarks = dynManager.getVertexBatchOpaquaMark(this.render.lightmapIndex + 1, this.render.receiveShadow, this.material.id, verDec.id);
  16670. if (dynManager._updateCountMark === dynBatchMarks.updateMark) {
  16671. var dynBatchIndex = dynBatchMarks.indexInList;
  16672. if (dynBatchMarks.batched) {
  16673. elements[dynBatchIndex].vertexBatchElementList.add(this);
  16674. }
  16675. else {
  16676. var dynOriElement = elements[dynBatchIndex];
  16677. var dynOriRender = dynOriElement.render;
  16678. var dynBatchElement = dynManager._getBatchRenderElementFromPool();
  16679. dynBatchElement.renderType = RenderElement.RENDERTYPE_VERTEXBATCH;
  16680. dynBatchElement.setGeometry(ILaya3D.SubMeshDynamicBatch.instance);
  16681. dynBatchElement.material = dynOriElement.material;
  16682. dynBatchElement.setTransform(null);
  16683. dynBatchElement.render = dynOriRender;
  16684. dynBatchElement.vertexBatchVertexDeclaration = verDec;
  16685. dynBatchElement.renderSubShader = dynOriElement.renderSubShader;
  16686. var dynBatchList = dynBatchElement.vertexBatchElementList;
  16687. dynBatchList.length = 0;
  16688. dynBatchList.add(dynOriElement);
  16689. dynBatchList.add(this);
  16690. elements[dynBatchIndex] = dynBatchElement;
  16691. dynBatchMarks.batched = true;
  16692. }
  16693. }
  16694. else {
  16695. dynBatchMarks.updateMark = dynManager._updateCountMark;
  16696. dynBatchMarks.indexInList = queueElements.length;
  16697. dynBatchMarks.batched = false;
  16698. queueElements.add(this);
  16699. }
  16700. }
  16701. else {
  16702. queueElements.add(this);
  16703. }
  16704. }
  16705. addToTransparentRenderQueue(context, queue) {
  16706. var subMeshStaticBatch = this.staticBatch;
  16707. var queueElements = queue.elements;
  16708. var elements = queueElements.elements;
  16709. if (subMeshStaticBatch) {
  16710. var staManager = ILaya3D.MeshRenderStaticBatchManager.instance;
  16711. var staLastElement = queue.lastTransparentRenderElement;
  16712. if (staLastElement) {
  16713. var staLastRender = staLastElement.render;
  16714. if (staLastElement._geometry._getType() !== this._geometry._getType() || staLastElement.staticBatch !== subMeshStaticBatch || staLastElement.material !== this.material || staLastRender.receiveShadow !== this.render.receiveShadow || staLastRender.lightmapIndex !== this.render.lightmapIndex) {
  16715. queueElements.add(this);
  16716. queue.lastTransparentBatched = false;
  16717. }
  16718. else {
  16719. if (queue.lastTransparentBatched) {
  16720. elements[queueElements.length - 1].staticBatchElementList.add((this));
  16721. }
  16722. else {
  16723. var staBatchElement = staManager._getBatchRenderElementFromPool();
  16724. staBatchElement.renderType = RenderElement.RENDERTYPE_STATICBATCH;
  16725. staBatchElement.setGeometry(subMeshStaticBatch);
  16726. staBatchElement.material = staLastElement.material;
  16727. var staRootOwner = subMeshStaticBatch.batchOwner;
  16728. var staBatchTransform = staRootOwner ? staRootOwner._transform : null;
  16729. staBatchElement.setTransform(staBatchTransform);
  16730. staBatchElement.render = this.render;
  16731. staBatchElement.renderSubShader = staLastElement.renderSubShader;
  16732. var staBatchList = staBatchElement.staticBatchElementList;
  16733. staBatchList.length = 0;
  16734. staBatchList.add(staLastElement);
  16735. staBatchList.add(this);
  16736. elements[queueElements.length - 1] = staBatchElement;
  16737. }
  16738. queue.lastTransparentBatched = true;
  16739. }
  16740. }
  16741. else {
  16742. queueElements.add(this);
  16743. queue.lastTransparentBatched = false;
  16744. }
  16745. }
  16746. else if (this.renderSubShader._owner._enableInstancing && Laya.LayaGL.layaGPUInstance.supportInstance() && this.render.lightmapIndex < 0 && (!this.render._probReflection || this.render._probReflection._isScene)) {
  16747. var subMesh = this._geometry;
  16748. var insManager = ILaya3D.MeshRenderDynamicBatchManager.instance;
  16749. var insLastElement = queue.lastTransparentRenderElement;
  16750. if (insLastElement) {
  16751. var insLastRender = insLastElement.render;
  16752. if (insLastElement._geometry._getType() !== this._geometry._getType() || insLastElement._geometry !== subMesh || insLastElement.material !== this.material || insLastRender.receiveShadow !== this.render.receiveShadow) {
  16753. queueElements.add(this);
  16754. queue.lastTransparentBatched = false;
  16755. }
  16756. else {
  16757. if (queue.lastTransparentBatched) {
  16758. var instanceBatchElementList = elements[queueElements.length - 1].instanceBatchElementList;
  16759. if (instanceBatchElementList.length === SubMeshInstanceBatch.instance.maxInstanceCount) {
  16760. queueElements.add(this);
  16761. queue.lastTransparentBatched = false;
  16762. }
  16763. else {
  16764. instanceBatchElementList.add(this);
  16765. queue.lastTransparentBatched = true;
  16766. }
  16767. }
  16768. else {
  16769. var insBatchElement = insManager._getBatchRenderElementFromPool();
  16770. insBatchElement.renderType = RenderElement.RENDERTYPE_INSTANCEBATCH;
  16771. insBatchElement.setGeometry(SubMeshInstanceBatch.instance);
  16772. insBatchElement.material = insLastElement.material;
  16773. insBatchElement.setTransform(null);
  16774. insBatchElement.render = this.render;
  16775. insBatchElement.instanceSubMesh = subMesh;
  16776. insBatchElement.renderSubShader = insLastElement.renderSubShader;
  16777. var insBatchList = insBatchElement.instanceBatchElementList;
  16778. insBatchList.length = 0;
  16779. insBatchList.add(insLastElement);
  16780. insBatchList.add(this);
  16781. elements[queueElements.length - 1] = insBatchElement;
  16782. queue.lastTransparentBatched = true;
  16783. }
  16784. }
  16785. }
  16786. else {
  16787. queueElements.add(this);
  16788. queue.lastTransparentBatched = false;
  16789. }
  16790. }
  16791. else if (this._dynamicVertexBatch) {
  16792. var verDec = this._geometry._vertexBuffer.vertexDeclaration;
  16793. var dynManager = ILaya3D.MeshRenderDynamicBatchManager.instance;
  16794. var dynLastElement = queue.lastTransparentRenderElement;
  16795. if (dynLastElement) {
  16796. var dynLastRender = dynLastElement.render;
  16797. if (!dynLastElement._dynamicVertexBatch || dynLastElement._geometry._getType() !== this._geometry._getType() || dynLastElement._geometry._vertexBuffer._vertexDeclaration !== verDec || dynLastElement.material !== this.material || dynLastRender.receiveShadow !== this.render.receiveShadow || dynLastRender.lightmapIndex !== this.render.lightmapIndex) {
  16798. queueElements.add(this);
  16799. queue.lastTransparentBatched = false;
  16800. }
  16801. else {
  16802. if (queue.lastTransparentBatched) {
  16803. elements[queueElements.length - 1].vertexBatchElementList.add((this));
  16804. }
  16805. else {
  16806. var dynBatchElement = dynManager._getBatchRenderElementFromPool();
  16807. dynBatchElement.renderType = RenderElement.RENDERTYPE_VERTEXBATCH;
  16808. dynBatchElement.setGeometry(ILaya3D.SubMeshDynamicBatch.instance);
  16809. dynBatchElement.material = dynLastElement.material;
  16810. dynBatchElement.setTransform(null);
  16811. dynBatchElement.render = this.render;
  16812. dynBatchElement.vertexBatchVertexDeclaration = verDec;
  16813. dynBatchElement.renderSubShader = dynLastElement.renderSubShader;
  16814. var dynBatchList = dynBatchElement.vertexBatchElementList;
  16815. dynBatchList.length = 0;
  16816. dynBatchList.add(dynLastElement);
  16817. dynBatchList.add(this);
  16818. elements[queueElements.length - 1] = dynBatchElement;
  16819. }
  16820. queue.lastTransparentBatched = true;
  16821. }
  16822. }
  16823. else {
  16824. queueElements.add(this);
  16825. queue.lastTransparentBatched = false;
  16826. }
  16827. }
  16828. else {
  16829. queueElements.add(this);
  16830. }
  16831. queue.lastTransparentRenderElement = this;
  16832. }
  16833. getInvertFront() {
  16834. switch (this.renderType) {
  16835. case RenderElement.RENDERTYPE_NORMAL:
  16836. return this._transform._isFrontFaceInvert;
  16837. case RenderElement.RENDERTYPE_STATICBATCH:
  16838. case RenderElement.RENDERTYPE_VERTEXBATCH:
  16839. return false;
  16840. case RenderElement.RENDERTYPE_INSTANCEBATCH:
  16841. return this.instanceBatchElementList.elements[0]._transform._isFrontFaceInvert;
  16842. default:
  16843. throw "SubMeshRenderElement: unknown renderType";
  16844. }
  16845. }
  16846. destroy() {
  16847. super.destroy();
  16848. this._dynamicWorldPositions = null;
  16849. this._dynamicWorldNormals = null;
  16850. this.staticBatch = null;
  16851. this.staticBatchElementList = null;
  16852. this.vertexBatchElementList = null;
  16853. this.vertexBatchVertexDeclaration = null;
  16854. }
  16855. }
  16856. class StaticBatchManager {
  16857. constructor() {
  16858. this._initBatchSprites = [];
  16859. this._staticBatches = {};
  16860. this._batchRenderElementPoolIndex = 0;
  16861. this._batchRenderElementPool = [];
  16862. }
  16863. static _addToStaticBatchQueue(sprite3D, renderableSprite3D) {
  16864. if (sprite3D instanceof RenderableSprite3D)
  16865. renderableSprite3D.push(sprite3D);
  16866. for (var i = 0, n = sprite3D.numChildren; i < n; i++)
  16867. StaticBatchManager._addToStaticBatchQueue(sprite3D._children[i], renderableSprite3D);
  16868. }
  16869. static _registerManager(manager) {
  16870. StaticBatchManager._managers.push(manager);
  16871. }
  16872. static combine(staticBatchRoot, renderableSprite3Ds = null) {
  16873. if (!renderableSprite3Ds) {
  16874. renderableSprite3Ds = [];
  16875. if (staticBatchRoot)
  16876. StaticBatchManager._addToStaticBatchQueue(staticBatchRoot, renderableSprite3Ds);
  16877. }
  16878. var batchSpritesCount = renderableSprite3Ds.length;
  16879. if (batchSpritesCount > 0) {
  16880. for (var i = 0; i < batchSpritesCount; i++) {
  16881. var sprite = renderableSprite3Ds[i];
  16882. if (!sprite.destroyed) {
  16883. if (sprite._render._isPartOfStaticBatch)
  16884. console.warn("StaticBatchManager: Sprite " + sprite.name + " has a part of Static Batch,it will be ignore.");
  16885. else
  16886. sprite._addToInitStaticBatchManager();
  16887. }
  16888. }
  16889. for (var k = 0, m = StaticBatchManager._managers.length; k < m; k++) {
  16890. var manager = StaticBatchManager._managers[k];
  16891. manager._initStaticBatchs(staticBatchRoot);
  16892. }
  16893. }
  16894. }
  16895. _partition(items, left, right) {
  16896. var pivot = items[Math.floor((right + left) / 2)];
  16897. while (left <= right) {
  16898. while (this._compare(items[left], pivot) < 0)
  16899. left++;
  16900. while (this._compare(items[right], pivot) > 0)
  16901. right--;
  16902. if (left < right) {
  16903. var temp = items[left];
  16904. items[left] = items[right];
  16905. items[right] = temp;
  16906. left++;
  16907. right--;
  16908. }
  16909. else if (left === right) {
  16910. left++;
  16911. break;
  16912. }
  16913. }
  16914. return left;
  16915. }
  16916. _quickSort(items, left, right) {
  16917. if (items.length > 1) {
  16918. var index = this._partition(items, left, right);
  16919. var leftIndex = index - 1;
  16920. if (left < leftIndex)
  16921. this._quickSort(items, left, leftIndex);
  16922. if (index < right)
  16923. this._quickSort(items, index, right);
  16924. }
  16925. }
  16926. _compare(left, right) {
  16927. throw "StaticBatch:must override this function.";
  16928. }
  16929. _initStaticBatchs(rootSprite) {
  16930. throw "StaticBatch:must override this function.";
  16931. }
  16932. _getBatchRenderElementFromPool() {
  16933. throw "StaticBatch:must override this function.";
  16934. }
  16935. _addBatchSprite(renderableSprite3D) {
  16936. this._initBatchSprites.push(renderableSprite3D);
  16937. }
  16938. _clear() {
  16939. this._batchRenderElementPoolIndex = 0;
  16940. }
  16941. _garbageCollection() {
  16942. throw "StaticBatchManager: must override it.";
  16943. }
  16944. dispose() {
  16945. this._staticBatches = null;
  16946. }
  16947. }
  16948. StaticBatchManager._managers = [];
  16949. class SubMeshStaticBatch extends GeometryElement {
  16950. constructor(batchOwner, vertexDeclaration) {
  16951. super();
  16952. this._bufferState = new BufferState();
  16953. this._batchID = SubMeshStaticBatch._batchIDCounter++;
  16954. this._batchElements = [];
  16955. this._currentBatchVertexCount = 0;
  16956. this._currentBatchIndexCount = 0;
  16957. this._vertexDeclaration = vertexDeclaration;
  16958. this.batchOwner = batchOwner;
  16959. }
  16960. _getStaticBatchBakedVertexs(batchVertices, batchOffset, batchOwnerTransform, transform, render, mesh) {
  16961. var vertexBuffer = mesh._vertexBuffer;
  16962. var vertexDeclaration = vertexBuffer.vertexDeclaration;
  16963. var positionOffset = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_POSITION0)._offset / 4;
  16964. var normalElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_NORMAL0);
  16965. var normalOffset = normalElement ? normalElement._offset / 4 : -1;
  16966. var colorElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_COLOR0);
  16967. var colorOffset = colorElement ? colorElement._offset / 4 : -1;
  16968. var uv0Element = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TEXTURECOORDINATE0);
  16969. var uv0Offset = uv0Element ? uv0Element._offset / 4 : -1;
  16970. var uv1Element = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TEXTURECOORDINATE1);
  16971. var uv1Offset = uv1Element ? uv1Element._offset / 4 : -1;
  16972. var tangentElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TANGENT0);
  16973. var sTangentOffset = tangentElement ? tangentElement._offset / 4 : -1;
  16974. var bakeVertexFloatCount = 18;
  16975. var oriVertexFloatCount = vertexDeclaration.vertexStride / 4;
  16976. var oriVertexes = vertexBuffer.getFloat32Data();
  16977. var worldMat;
  16978. if (batchOwnerTransform) {
  16979. var rootMat = batchOwnerTransform.worldMatrix;
  16980. rootMat.invert(SubMeshStaticBatch._tempMatrix4x40);
  16981. worldMat = SubMeshStaticBatch._tempMatrix4x41;
  16982. Matrix4x4.multiply(SubMeshStaticBatch._tempMatrix4x40, transform.worldMatrix, worldMat);
  16983. }
  16984. else {
  16985. worldMat = transform.worldMatrix;
  16986. }
  16987. var normalMat = SubMeshStaticBatch._tempMatrix4x42;
  16988. worldMat.invert(normalMat);
  16989. normalMat.transpose();
  16990. var rotation = SubMeshStaticBatch._tempQuaternion0;
  16991. worldMat.decomposeTransRotScale(SubMeshStaticBatch._tempVector30, rotation, SubMeshStaticBatch._tempVector31);
  16992. var lightmapScaleOffset = render.lightmapScaleOffset;
  16993. var vertexCount = mesh.vertexCount;
  16994. for (var i = 0; i < vertexCount; i++) {
  16995. var oriOffset = i * oriVertexFloatCount;
  16996. var bakeOffset = (i + batchOffset) * bakeVertexFloatCount;
  16997. Utils3D.transformVector3ArrayToVector3ArrayCoordinate(oriVertexes, oriOffset + positionOffset, worldMat, batchVertices, bakeOffset + 0);
  16998. if (normalOffset !== -1)
  16999. Utils3D.transformVector3ArrayToVector3ArrayNormal(oriVertexes, oriOffset + normalOffset, normalMat, batchVertices, bakeOffset + 3);
  17000. var j, m;
  17001. var bakOff = bakeOffset + 6;
  17002. if (colorOffset !== -1) {
  17003. var oriOff = oriOffset + colorOffset;
  17004. for (j = 0, m = 4; j < m; j++)
  17005. batchVertices[bakOff + j] = oriVertexes[oriOff + j];
  17006. }
  17007. else {
  17008. for (j = 0, m = 4; j < m; j++)
  17009. batchVertices[bakOff + j] = 1.0;
  17010. }
  17011. if (uv0Offset !== -1) {
  17012. var absUv0Offset = oriOffset + uv0Offset;
  17013. batchVertices[bakeOffset + 10] = oriVertexes[absUv0Offset];
  17014. batchVertices[bakeOffset + 11] = oriVertexes[absUv0Offset + 1];
  17015. }
  17016. if (lightmapScaleOffset) {
  17017. if (uv1Offset !== -1)
  17018. Utils3D.transformLightingMapTexcoordArray(oriVertexes, oriOffset + uv1Offset, lightmapScaleOffset, batchVertices, bakeOffset + 12);
  17019. else
  17020. Utils3D.transformLightingMapTexcoordArray(oriVertexes, oriOffset + uv0Offset, lightmapScaleOffset, batchVertices, bakeOffset + 12);
  17021. }
  17022. if (sTangentOffset !== -1) {
  17023. var absSTanegntOffset = oriOffset + sTangentOffset;
  17024. Utils3D.transformVector3ArrayToVector3ArrayNormal(oriVertexes, absSTanegntOffset, normalMat, batchVertices, bakeOffset + 14);
  17025. batchVertices[bakeOffset + 17] = oriVertexes[absSTanegntOffset + 3];
  17026. }
  17027. }
  17028. return vertexCount;
  17029. }
  17030. addTest(sprite) {
  17031. var vertexCount;
  17032. var subMeshVertexCount = sprite.meshFilter.sharedMesh.vertexCount;
  17033. vertexCount = this._currentBatchVertexCount + subMeshVertexCount;
  17034. if (vertexCount > SubMeshStaticBatch.maxBatchVertexCount)
  17035. return false;
  17036. return true;
  17037. }
  17038. add(sprite) {
  17039. var mesh = sprite.meshFilter.sharedMesh;
  17040. var subMeshVertexCount = mesh.vertexCount;
  17041. this._batchElements.push(sprite);
  17042. var render = sprite._render;
  17043. render._isPartOfStaticBatch = true;
  17044. render._staticBatch = this;
  17045. var renderElements = render._renderElements;
  17046. for (var i = 0, n = renderElements.length; i < n; i++)
  17047. renderElements[i].staticBatch = this;
  17048. this._currentBatchIndexCount += mesh._indexBuffer.indexCount;
  17049. this._currentBatchVertexCount += subMeshVertexCount;
  17050. }
  17051. remove(sprite) {
  17052. var mesh = sprite.meshFilter.sharedMesh;
  17053. var index = this._batchElements.indexOf(sprite);
  17054. if (index !== -1) {
  17055. this._batchElements.splice(index, 1);
  17056. var renderElements = sprite._render._renderElements;
  17057. for (var i = 0, n = renderElements.length; i < n; i++)
  17058. renderElements[i].staticBatch = null;
  17059. this._currentBatchIndexCount = this._currentBatchIndexCount - mesh._indexBuffer.indexCount;
  17060. this._currentBatchVertexCount = this._currentBatchVertexCount - mesh.vertexCount;
  17061. sprite._render._isPartOfStaticBatch = false;
  17062. }
  17063. }
  17064. finishInit() {
  17065. if (this._vertexBuffer) {
  17066. this._vertexBuffer.destroy();
  17067. this._indexBuffer.destroy();
  17068. Laya.Resource._addGPUMemory(-(this._vertexBuffer._byteLength + this._indexBuffer._byteLength));
  17069. }
  17070. var gl = Laya.LayaGL.instance;
  17071. var batchVertexCount = 0;
  17072. var batchIndexCount = 0;
  17073. var rootOwner = this.batchOwner;
  17074. var floatStride = this._vertexDeclaration.vertexStride / 4;
  17075. var vertexDatas = new Float32Array(floatStride * this._currentBatchVertexCount);
  17076. var indexDatas = new Uint16Array(this._currentBatchIndexCount);
  17077. this._vertexBuffer = new VertexBuffer3D(this._vertexDeclaration.vertexStride * this._currentBatchVertexCount, gl.STATIC_DRAW);
  17078. this._vertexBuffer.vertexDeclaration = this._vertexDeclaration;
  17079. this._indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt16, this._currentBatchIndexCount, gl.STATIC_DRAW);
  17080. for (var i = 0, n = this._batchElements.length; i < n; i++) {
  17081. var sprite = this._batchElements[i];
  17082. var mesh = sprite.meshFilter.sharedMesh;
  17083. var meshVerCount = this._getStaticBatchBakedVertexs(vertexDatas, batchVertexCount, rootOwner ? rootOwner._transform : null, sprite._transform, sprite._render, mesh);
  17084. var indices = mesh._indexBuffer.getData();
  17085. var indexOffset = batchVertexCount;
  17086. var indexEnd = batchIndexCount + indices.length;
  17087. var elements = sprite._render._renderElements;
  17088. for (var j = 0, m = mesh.subMeshCount; j < m; j++) {
  17089. var subMesh = mesh._subMeshes[j];
  17090. var start = batchIndexCount + subMesh._indexStart;
  17091. var element = elements[j];
  17092. element.staticBatchIndexStart = start;
  17093. element.staticBatchIndexEnd = start + subMesh._indexCount;
  17094. }
  17095. indexDatas.set(indices, batchIndexCount);
  17096. var k;
  17097. var isInvert = rootOwner ? (sprite._transform._isFrontFaceInvert !== rootOwner.transform._isFrontFaceInvert) : sprite._transform._isFrontFaceInvert;
  17098. if (isInvert) {
  17099. for (k = batchIndexCount; k < indexEnd; k += 3) {
  17100. indexDatas[k] = indexOffset + indexDatas[k];
  17101. var index1 = indexDatas[k + 1];
  17102. var index2 = indexDatas[k + 2];
  17103. indexDatas[k + 1] = indexOffset + index2;
  17104. indexDatas[k + 2] = indexOffset + index1;
  17105. }
  17106. }
  17107. else {
  17108. for (k = batchIndexCount; k < indexEnd; k += 3) {
  17109. indexDatas[k] = indexOffset + indexDatas[k];
  17110. indexDatas[k + 1] = indexOffset + indexDatas[k + 1];
  17111. indexDatas[k + 2] = indexOffset + indexDatas[k + 2];
  17112. }
  17113. }
  17114. batchIndexCount += indices.length;
  17115. batchVertexCount += meshVerCount;
  17116. }
  17117. this._vertexBuffer.setData(vertexDatas.buffer);
  17118. this._indexBuffer.setData(indexDatas);
  17119. var memorySize = this._vertexBuffer._byteLength + this._indexBuffer._byteLength;
  17120. Laya.Resource._addGPUMemory(memorySize);
  17121. this._bufferState.bind();
  17122. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  17123. this._bufferState.applyIndexBuffer(this._indexBuffer);
  17124. this._bufferState.unBind();
  17125. }
  17126. _render(state) {
  17127. this._bufferState.bind();
  17128. var gl = Laya.LayaGL.instance;
  17129. var element = state.renderElement;
  17130. var staticBatchElementList = element.staticBatchElementList;
  17131. var batchElementList = staticBatchElementList.elements;
  17132. var from = 0;
  17133. var end = 0;
  17134. var count = staticBatchElementList.length;
  17135. for (var i = 1; i < count; i++) {
  17136. var lastElement = batchElementList[i - 1];
  17137. if (lastElement.staticBatchIndexEnd === batchElementList[i].staticBatchIndexStart) {
  17138. end++;
  17139. continue;
  17140. }
  17141. else {
  17142. var start = batchElementList[from].staticBatchIndexStart;
  17143. var indexCount = batchElementList[end].staticBatchIndexEnd - start;
  17144. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, start * 2);
  17145. from = ++end;
  17146. Laya.Stat.trianglesFaces += indexCount / 3;
  17147. }
  17148. }
  17149. start = batchElementList[from].staticBatchIndexStart;
  17150. indexCount = batchElementList[end].staticBatchIndexEnd - start;
  17151. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, start * 2);
  17152. Laya.Stat.renderBatches++;
  17153. Laya.Stat.savedRenderBatches += count - 1;
  17154. Laya.Stat.trianglesFaces += indexCount / 3;
  17155. }
  17156. dispose() {
  17157. var memorySize = this._vertexBuffer._byteLength + this._indexBuffer._byteLength;
  17158. Laya.Resource._addGPUMemory(-memorySize);
  17159. this._batchElements = null;
  17160. this.batchOwner = null;
  17161. this._vertexDeclaration = null;
  17162. this._bufferState.destroy();
  17163. this._vertexBuffer.destroy();
  17164. this._indexBuffer.destroy();
  17165. this._vertexBuffer = null;
  17166. this._indexBuffer = null;
  17167. this._bufferState = null;
  17168. }
  17169. }
  17170. SubMeshStaticBatch._tempVector30 = new Vector3();
  17171. SubMeshStaticBatch._tempVector31 = new Vector3();
  17172. SubMeshStaticBatch._tempQuaternion0 = new Quaternion();
  17173. SubMeshStaticBatch._tempMatrix4x40 = new Matrix4x4();
  17174. SubMeshStaticBatch._tempMatrix4x41 = new Matrix4x4();
  17175. SubMeshStaticBatch._tempMatrix4x42 = new Matrix4x4();
  17176. SubMeshStaticBatch.maxBatchVertexCount = 65535;
  17177. SubMeshStaticBatch._batchIDCounter = 0;
  17178. class MeshRenderStaticBatchManager extends StaticBatchManager {
  17179. constructor() {
  17180. super();
  17181. this._opaqueBatchMarks = [];
  17182. this._updateCountMark = 0;
  17183. }
  17184. static __init__() {
  17185. MeshRenderStaticBatchManager._verDec = VertexMesh.getVertexDeclaration("POSITION,NORMAL,COLOR,UV,UV1,TANGENT");
  17186. }
  17187. _compare(left, right) {
  17188. var lRender = left._render, rRender = right._render;
  17189. var leftGeo = left.meshFilter.sharedMesh, rightGeo = right.meshFilter.sharedMesh;
  17190. var lightOffset = lRender.lightmapIndex - rRender.lightmapIndex;
  17191. if (lightOffset === 0) {
  17192. var receiveShadowOffset = (lRender.receiveShadow ? 1 : 0) - (rRender.receiveShadow ? 1 : 0);
  17193. if (receiveShadowOffset === 0) {
  17194. var materialOffset = (lRender.sharedMaterial && rRender.sharedMaterial) ? lRender.sharedMaterial.id - rRender.sharedMaterial.id : 0;
  17195. if (materialOffset === 0) {
  17196. var verDec = leftGeo._vertexBuffer.vertexDeclaration.id - rightGeo._vertexBuffer.vertexDeclaration.id;
  17197. if (verDec === 0) {
  17198. return rightGeo._indexBuffer.indexCount - leftGeo._indexBuffer.indexCount;
  17199. }
  17200. else {
  17201. return verDec;
  17202. }
  17203. }
  17204. else {
  17205. return materialOffset;
  17206. }
  17207. }
  17208. else {
  17209. return receiveShadowOffset;
  17210. }
  17211. }
  17212. else {
  17213. return lightOffset;
  17214. }
  17215. }
  17216. _getBatchRenderElementFromPool() {
  17217. var renderElement = this._batchRenderElementPool[this._batchRenderElementPoolIndex++];
  17218. if (!renderElement) {
  17219. renderElement = new SubMeshRenderElement();
  17220. this._batchRenderElementPool[this._batchRenderElementPoolIndex - 1] = renderElement;
  17221. renderElement.staticBatchElementList = new SingletonList();
  17222. }
  17223. return renderElement;
  17224. }
  17225. _getStaticBatch(staticBatches, rootOwner, number) {
  17226. var subMeshStaticBatch = staticBatches[number];
  17227. if (!subMeshStaticBatch) {
  17228. subMeshStaticBatch = staticBatches[number] = new SubMeshStaticBatch(rootOwner, MeshRenderStaticBatchManager._verDec);
  17229. this._staticBatches[subMeshStaticBatch._batchID] = subMeshStaticBatch;
  17230. }
  17231. return subMeshStaticBatch;
  17232. }
  17233. _initStaticBatchs(rootOwner) {
  17234. var initBatchSprites = this._initBatchSprites;
  17235. this._quickSort(initBatchSprites, 0, initBatchSprites.length - 1);
  17236. var staticBatches = [];
  17237. var lastCanMerage = false;
  17238. var curStaticBatch;
  17239. var batchNumber = 0;
  17240. for (var i = 0, n = initBatchSprites.length; i < n; i++) {
  17241. var sprite = initBatchSprites[i];
  17242. if (lastCanMerage) {
  17243. if (curStaticBatch.addTest(sprite)) {
  17244. curStaticBatch.add(sprite);
  17245. }
  17246. else {
  17247. lastCanMerage = false;
  17248. batchNumber++;
  17249. }
  17250. }
  17251. else {
  17252. var lastIndex = n - 1;
  17253. if (i !== lastIndex) {
  17254. curStaticBatch = this._getStaticBatch(staticBatches, rootOwner, batchNumber);
  17255. curStaticBatch.add(sprite);
  17256. lastCanMerage = true;
  17257. }
  17258. }
  17259. }
  17260. for (i = 0, n = staticBatches.length; i < n; i++) {
  17261. var staticBatch = staticBatches[i];
  17262. staticBatch && staticBatch.finishInit();
  17263. }
  17264. this._initBatchSprites.length = 0;
  17265. }
  17266. _removeRenderSprite(sprite) {
  17267. var render = sprite._render;
  17268. var staticBatch = render._staticBatch;
  17269. var batchElements = staticBatch._batchElements;
  17270. var index = batchElements.indexOf(sprite);
  17271. if (index !== -1) {
  17272. batchElements.splice(index, 1);
  17273. render._staticBatch = null;
  17274. var renderElements = render._renderElements;
  17275. for (var i = 0, n = renderElements.length; i < n; i++)
  17276. renderElements[i].staticBatch = null;
  17277. }
  17278. if (batchElements.length === 0) {
  17279. delete this._staticBatches[staticBatch._batchID];
  17280. staticBatch.dispose();
  17281. }
  17282. }
  17283. _clear() {
  17284. super._clear();
  17285. this._updateCountMark++;
  17286. }
  17287. _garbageCollection() {
  17288. for (var key in this._staticBatches) {
  17289. var staticBatch = this._staticBatches[key];
  17290. if (staticBatch._batchElements.length === 0) {
  17291. staticBatch.dispose();
  17292. delete this._staticBatches[key];
  17293. }
  17294. }
  17295. }
  17296. getBatchOpaquaMark(lightMapIndex, receiveShadow, materialID, staticBatchID) {
  17297. var receiveShadowIndex = receiveShadow ? 1 : 0;
  17298. var staLightMapMarks = (this._opaqueBatchMarks[lightMapIndex]) || (this._opaqueBatchMarks[lightMapIndex] = []);
  17299. var staReceiveShadowMarks = (staLightMapMarks[receiveShadowIndex]) || (staLightMapMarks[receiveShadowIndex] = []);
  17300. var staMaterialMarks = (staReceiveShadowMarks[materialID]) || (staReceiveShadowMarks[materialID] = []);
  17301. return (staMaterialMarks[staticBatchID]) || (staMaterialMarks[staticBatchID] = new BatchMark);
  17302. }
  17303. }
  17304. MeshRenderStaticBatchManager.instance = new MeshRenderStaticBatchManager();
  17305. (function (ReflectionProbeMode) {
  17306. ReflectionProbeMode[ReflectionProbeMode["off"] = 0] = "off";
  17307. ReflectionProbeMode[ReflectionProbeMode["simple"] = 1] = "simple";
  17308. })(exports.ReflectionProbeMode || (exports.ReflectionProbeMode = {}));
  17309. class ReflectionProbe extends Sprite3D {
  17310. constructor() {
  17311. super();
  17312. this._boxProjection = false;
  17313. this._size = new Vector3();
  17314. this._offset = new Vector3();
  17315. this._reflectionHDRParams = new Vector4();
  17316. this._reflectionDecodeFormat = Laya.TextureDecodeFormat.Normal;
  17317. this._isScene = false;
  17318. }
  17319. get boxProjection() {
  17320. return this._boxProjection;
  17321. }
  17322. set boxProjection(value) {
  17323. this._boxProjection = value;
  17324. }
  17325. get importance() {
  17326. return this._importance;
  17327. }
  17328. set importance(value) {
  17329. this._importance = value;
  17330. }
  17331. get intensity() {
  17332. return this._intensity;
  17333. }
  17334. set intensity(value) {
  17335. value = Math.max(Math.min(value, 1.0), 0.0);
  17336. this._reflectionHDRParams.x = value;
  17337. if (this._reflectionDecodeFormat == Laya.TextureDecodeFormat.RGBM)
  17338. this._reflectionHDRParams.x *= 5.0;
  17339. this._intensity = value;
  17340. }
  17341. get reflectionTexture() {
  17342. return this._reflectionTexture;
  17343. }
  17344. set reflectionTexture(value) {
  17345. this._reflectionTexture = value;
  17346. this._reflectionTexture._addReference();
  17347. }
  17348. get bounds() {
  17349. return this._bounds;
  17350. }
  17351. set bounds(value) {
  17352. this._bounds = value;
  17353. }
  17354. get boundsMax() {
  17355. return this._bounds.getMax();
  17356. }
  17357. get boundsMin() {
  17358. return this._bounds.getMin();
  17359. }
  17360. get probePosition() {
  17361. return this.transform.position;
  17362. }
  17363. get reflectionHDRParams() {
  17364. return this._reflectionHDRParams;
  17365. }
  17366. set reflectionHDRParams(value) {
  17367. this._reflectionHDRParams = value;
  17368. }
  17369. _parse(data, spriteMap) {
  17370. super._parse(data, spriteMap);
  17371. this._boxProjection = data.boxProjection;
  17372. this._importance = data.importance;
  17373. this._reflectionTexture = Laya.Loader.getRes(data.reflection);
  17374. var position = this.transform.position;
  17375. this._size.fromArray(data.boxSize);
  17376. Vector3.scale(this._size, 0.5, ReflectionProbe.TEMPVECTOR3);
  17377. this._offset.fromArray(data.boxOffset);
  17378. var min = new Vector3();
  17379. var max = new Vector3();
  17380. Vector3.add(position, ReflectionProbe.TEMPVECTOR3, max);
  17381. Vector3.add(max, this._offset, max);
  17382. Vector3.subtract(position, ReflectionProbe.TEMPVECTOR3, min);
  17383. Vector3.add(min, this._offset, min);
  17384. this._reflectionDecodeFormat = data.reflectionDecodingFormat;
  17385. this.intensity = data.intensity;
  17386. if (!this._bounds)
  17387. this.bounds = new Bounds(min, max);
  17388. else {
  17389. this._bounds.setMin(min);
  17390. this._bounds.setMax(max);
  17391. }
  17392. }
  17393. _setIndexInReflectionList(value) {
  17394. this._indexInReflectProbList = value;
  17395. }
  17396. _getIndexInReflectionList() {
  17397. return this._indexInReflectProbList;
  17398. }
  17399. _onActive() {
  17400. super._onActive();
  17401. if (this._reflectionTexture)
  17402. this.scene._reflectionProbeManager.add(this);
  17403. }
  17404. _onInActive() {
  17405. super._onInActive();
  17406. if (this.reflectionTexture)
  17407. this.scene._reflectionProbeManager.remove(this);
  17408. }
  17409. destroy(destroyChild = true) {
  17410. if (this.destroyed)
  17411. return;
  17412. super.destroy(destroyChild);
  17413. this._reflectionTexture && this._reflectionTexture._removeReference();
  17414. this._reflectionTexture = null;
  17415. this._bounds = null;
  17416. }
  17417. _cloneTo(destObject, srcRoot, dstRoot) {
  17418. var dest = destObject;
  17419. dest.bounds = this.bounds;
  17420. dest.boxProjection = this.boxProjection;
  17421. dest.importance = this.importance;
  17422. dest._size = this._size;
  17423. dest._offset = this._offset;
  17424. dest.intensity = this.intensity;
  17425. dest.reflectionHDRParams = this.reflectionHDRParams;
  17426. super._cloneTo(destObject, srcRoot, dstRoot);
  17427. }
  17428. }
  17429. ReflectionProbe.TEMPVECTOR3 = new Vector3();
  17430. ReflectionProbe.defaultTextureHDRDecodeValues = new Vector4(1.0, 1.0, 0.0, 0.0);
  17431. class BaseRender extends Laya.EventDispatcher {
  17432. constructor(owner) {
  17433. super();
  17434. this._lightmapScaleOffset = new Vector4(1, 1, 0, 0);
  17435. this._indexInList = -1;
  17436. this._indexInCastShadowList = -1;
  17437. this._boundsChange = true;
  17438. this._castShadow = false;
  17439. this._supportOctree = true;
  17440. this._sharedMaterials = [];
  17441. this._renderMark = -1;
  17442. this._indexInOctreeMotionList = -1;
  17443. this._reflectionMode = exports.ReflectionProbeMode.simple;
  17444. this._updateMark = -1;
  17445. this._updateRenderType = -1;
  17446. this._isPartOfStaticBatch = false;
  17447. this._staticBatch = null;
  17448. this._id = ++BaseRender._uniqueIDCounter;
  17449. this._indexInCastShadowList = -1;
  17450. this._bounds = new Bounds(Vector3._ZERO, Vector3._ZERO);
  17451. this._renderElements = [];
  17452. this._owner = owner;
  17453. this._enable = true;
  17454. this._materialsInstance = [];
  17455. this._shaderValues = new ShaderData(null);
  17456. this.lightmapIndex = -1;
  17457. this.receiveShadow = false;
  17458. this.sortingFudge = 0.0;
  17459. (owner) && (this._owner.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange));
  17460. }
  17461. get id() {
  17462. return this._id;
  17463. }
  17464. get lightmapIndex() {
  17465. return this._lightmapIndex;
  17466. }
  17467. set lightmapIndex(value) {
  17468. this._lightmapIndex = value;
  17469. }
  17470. get lightmapScaleOffset() {
  17471. return this._lightmapScaleOffset;
  17472. }
  17473. set lightmapScaleOffset(value) {
  17474. if (!value)
  17475. throw "BaseRender: lightmapScaleOffset can't be null.";
  17476. this._lightmapScaleOffset = value;
  17477. this._shaderValues.setVector(RenderableSprite3D.LIGHTMAPSCALEOFFSET, value);
  17478. }
  17479. get enable() {
  17480. return this._enable;
  17481. }
  17482. set enable(value) {
  17483. this._enable = !!value;
  17484. }
  17485. get material() {
  17486. var material = this._sharedMaterials[0];
  17487. if (material && !this._materialsInstance[0]) {
  17488. var insMat = this._getInstanceMaterial(material, 0);
  17489. var renderElement = this._renderElements[0];
  17490. (renderElement) && (renderElement.material = insMat);
  17491. }
  17492. return this._sharedMaterials[0];
  17493. }
  17494. set material(value) {
  17495. this.sharedMaterial = value;
  17496. this._isSupportReflection();
  17497. }
  17498. get materials() {
  17499. for (var i = 0, n = this._sharedMaterials.length; i < n; i++) {
  17500. if (!this._materialsInstance[i]) {
  17501. var insMat = this._getInstanceMaterial(this._sharedMaterials[i], i);
  17502. var renderElement = this._renderElements[i];
  17503. (renderElement) && (renderElement.material = insMat);
  17504. }
  17505. }
  17506. return this._sharedMaterials.slice();
  17507. }
  17508. set materials(value) {
  17509. this.sharedMaterials = value;
  17510. this._isSupportReflection();
  17511. }
  17512. get sharedMaterial() {
  17513. return this._sharedMaterials[0];
  17514. }
  17515. set sharedMaterial(value) {
  17516. var lastValue = this._sharedMaterials[0];
  17517. if (lastValue !== value) {
  17518. this._sharedMaterials[0] = value;
  17519. this._materialsInstance[0] = false;
  17520. this._changeMaterialReference(lastValue, value);
  17521. var renderElement = this._renderElements[0];
  17522. (renderElement) && (renderElement.material = value);
  17523. }
  17524. this._isSupportReflection();
  17525. }
  17526. get sharedMaterials() {
  17527. return this._sharedMaterials.slice();
  17528. }
  17529. set sharedMaterials(value) {
  17530. var materialsInstance = this._materialsInstance;
  17531. var sharedMats = this._sharedMaterials;
  17532. for (var i = 0, n = sharedMats.length; i < n; i++) {
  17533. var lastMat = sharedMats[i];
  17534. (lastMat) && (lastMat._removeReference());
  17535. }
  17536. if (value) {
  17537. var count = value.length;
  17538. materialsInstance.length = count;
  17539. sharedMats.length = count;
  17540. for (i = 0; i < count; i++) {
  17541. lastMat = sharedMats[i];
  17542. var mat = value[i];
  17543. if (lastMat !== mat) {
  17544. materialsInstance[i] = false;
  17545. var renderElement = this._renderElements[i];
  17546. (renderElement) && (renderElement.material = mat);
  17547. }
  17548. if (mat) {
  17549. mat._addReference();
  17550. }
  17551. sharedMats[i] = mat;
  17552. }
  17553. }
  17554. else {
  17555. throw new Error("BaseRender: shadredMaterials value can't be null.");
  17556. }
  17557. this._isSupportReflection();
  17558. }
  17559. get bounds() {
  17560. if (this._boundsChange) {
  17561. this._calculateBoundingBox();
  17562. this._boundsChange = false;
  17563. }
  17564. return this._bounds;
  17565. }
  17566. set receiveShadow(value) {
  17567. if (this._receiveShadow !== value) {
  17568. this._receiveShadow = value;
  17569. if (value)
  17570. this._shaderValues.addDefine(RenderableSprite3D.SHADERDEFINE_RECEIVE_SHADOW);
  17571. else
  17572. this._shaderValues.removeDefine(RenderableSprite3D.SHADERDEFINE_RECEIVE_SHADOW);
  17573. }
  17574. }
  17575. get receiveShadow() {
  17576. return this._receiveShadow;
  17577. }
  17578. get castShadow() {
  17579. return this._castShadow;
  17580. }
  17581. set castShadow(value) {
  17582. this._castShadow = value;
  17583. }
  17584. get isPartOfStaticBatch() {
  17585. return this._isPartOfStaticBatch;
  17586. }
  17587. get isRender() {
  17588. return this._renderMark == -1 || this._renderMark == (Laya.Stat.loopCount - 1);
  17589. }
  17590. set reflectionMode(value) {
  17591. this._reflectionMode = value;
  17592. }
  17593. get reflectionMode() {
  17594. return this._reflectionMode;
  17595. }
  17596. _getOctreeNode() {
  17597. return this._octreeNode;
  17598. }
  17599. _setOctreeNode(value) {
  17600. if (!value) {
  17601. (this._indexInOctreeMotionList !== -1) && (this._octreeNode._octree.removeMotionObject(this));
  17602. }
  17603. this._octreeNode = value;
  17604. }
  17605. _getIndexInMotionList() {
  17606. return this._indexInOctreeMotionList;
  17607. }
  17608. _setIndexInMotionList(value) {
  17609. this._indexInOctreeMotionList = value;
  17610. }
  17611. _changeMaterialReference(lastValue, value) {
  17612. (lastValue) && (lastValue._removeReference());
  17613. value._addReference();
  17614. }
  17615. _getInstanceMaterial(material, index) {
  17616. var insMat = material.clone();
  17617. insMat.name = insMat.name + "(Instance)";
  17618. this._materialsInstance[index] = true;
  17619. this._changeMaterialReference(this._sharedMaterials[index], insMat);
  17620. this._sharedMaterials[index] = insMat;
  17621. return insMat;
  17622. }
  17623. _isSupportReflection() {
  17624. this._surportReflectionProbe = false;
  17625. var sharedMats = this._sharedMaterials;
  17626. for (var i = 0, n = sharedMats.length; i < n; i++) {
  17627. var mat = sharedMats[i];
  17628. this._surportReflectionProbe = (this._surportReflectionProbe || (mat && mat._shader._supportReflectionProbe));
  17629. }
  17630. }
  17631. _addReflectionProbeUpdate() {
  17632. if (this._surportReflectionProbe && this._reflectionMode == 1) {
  17633. this._scene._reflectionProbeManager.addMotionObject(this);
  17634. }
  17635. }
  17636. _applyLightMapParams() {
  17637. var lightMaps = this._scene.lightmaps;
  17638. var shaderValues = this._shaderValues;
  17639. var lightmapIndex = this._lightmapIndex;
  17640. if (lightmapIndex >= 0 && lightmapIndex < lightMaps.length) {
  17641. var lightMap = lightMaps[lightmapIndex];
  17642. shaderValues.setTexture(RenderableSprite3D.LIGHTMAP, lightMap.lightmapColor);
  17643. shaderValues.addDefine(RenderableSprite3D.SAHDERDEFINE_LIGHTMAP);
  17644. if (lightMap.lightmapDirection) {
  17645. shaderValues.setTexture(RenderableSprite3D.LIGHTMAP_DIRECTION, lightMap.lightmapDirection);
  17646. shaderValues.addDefine(RenderableSprite3D.SHADERDEFINE_LIGHTMAP_DIRECTIONAL);
  17647. }
  17648. else {
  17649. shaderValues.removeDefine(RenderableSprite3D.SHADERDEFINE_LIGHTMAP_DIRECTIONAL);
  17650. }
  17651. }
  17652. else {
  17653. shaderValues.removeDefine(RenderableSprite3D.SAHDERDEFINE_LIGHTMAP);
  17654. shaderValues.removeDefine(RenderableSprite3D.SHADERDEFINE_LIGHTMAP_DIRECTIONAL);
  17655. }
  17656. }
  17657. _onWorldMatNeedChange(flag) {
  17658. this._boundsChange = true;
  17659. if (this._octreeNode) {
  17660. flag &= Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDSCALE;
  17661. if (flag) {
  17662. if (this._indexInOctreeMotionList === -1)
  17663. this._octreeNode._octree.addMotionObject(this);
  17664. }
  17665. }
  17666. this._addReflectionProbeUpdate();
  17667. }
  17668. _calculateBoundingBox() {
  17669. throw ("BaseRender: must override it.");
  17670. }
  17671. _getIndexInList() {
  17672. return this._indexInList;
  17673. }
  17674. _setIndexInList(index) {
  17675. this._indexInList = index;
  17676. }
  17677. _setBelongScene(scene) {
  17678. this._scene = scene;
  17679. }
  17680. _needRender(boundFrustum, context) {
  17681. return true;
  17682. }
  17683. _renderUpdate(context, transform) {
  17684. }
  17685. _renderUpdateWithCamera(context, transform) {
  17686. }
  17687. _revertBatchRenderUpdate(context) {
  17688. }
  17689. _destroy() {
  17690. (this._indexInOctreeMotionList !== -1) && (this._octreeNode._octree.removeMotionObject(this));
  17691. this.offAll();
  17692. var i = 0, n = 0;
  17693. for (i = 0, n = this._renderElements.length; i < n; i++)
  17694. this._renderElements[i].destroy();
  17695. for (i = 0, n = this._sharedMaterials.length; i < n; i++)
  17696. (this._sharedMaterials[i].destroyed) || (this._sharedMaterials[i]._removeReference());
  17697. this._renderElements = null;
  17698. this._owner = null;
  17699. this._sharedMaterials = null;
  17700. this._bounds = null;
  17701. this._lightmapScaleOffset = null;
  17702. }
  17703. markAsUnStatic() {
  17704. if (this._isPartOfStaticBatch) {
  17705. MeshRenderStaticBatchManager.instance._removeRenderSprite(this._owner);
  17706. this._isPartOfStaticBatch = false;
  17707. }
  17708. }
  17709. }
  17710. BaseRender._tempBoundBoxCorners = [new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3(), new Vector3()];
  17711. BaseRender._uniqueIDCounter = 0;
  17712. BaseRender._defaultLightmapScaleOffset = new Vector4(1.0, 1.0, 0.0, 0.0);
  17713. class PixelLineRenderer extends BaseRender {
  17714. constructor(owner) {
  17715. super(owner);
  17716. this._projectionViewWorldMatrix = new Matrix4x4();
  17717. }
  17718. _calculateBoundingBox() {
  17719. var worldMat = this._owner.transform.worldMatrix;
  17720. var lineFilter = this._owner._geometryFilter;
  17721. lineFilter._reCalculateBound();
  17722. lineFilter._bounds._tranform(worldMat, this._bounds);
  17723. }
  17724. _renderUpdateWithCamera(context, transform) {
  17725. var projectionView = context.projectionViewMatrix;
  17726. var sv = this._shaderValues;
  17727. if (transform) {
  17728. var worldMat = transform.worldMatrix;
  17729. sv.setMatrix4x4(Sprite3D.WORLDMATRIX, worldMat);
  17730. Matrix4x4.multiply(projectionView, worldMat, this._projectionViewWorldMatrix);
  17731. sv.setMatrix4x4(Sprite3D.MVPMATRIX, this._projectionViewWorldMatrix);
  17732. }
  17733. else {
  17734. sv.setMatrix4x4(Sprite3D.WORLDMATRIX, Matrix4x4.DEFAULT);
  17735. sv.setMatrix4x4(Sprite3D.MVPMATRIX, projectionView);
  17736. }
  17737. }
  17738. }
  17739. class PixelLineSprite3D extends RenderableSprite3D {
  17740. constructor(maxCount = 2, name = null) {
  17741. super(name);
  17742. this._isRenderActive = false;
  17743. this._isInRenders = false;
  17744. this._geometryFilter = new PixelLineFilter(this, maxCount);
  17745. this._render = new PixelLineRenderer(this);
  17746. this._changeRenderObjects(this._render, 0, PixelLineMaterial.defaultMaterial);
  17747. }
  17748. get maxLineCount() {
  17749. return this._geometryFilter._maxLineCount;
  17750. }
  17751. set maxLineCount(value) {
  17752. this._geometryFilter._resizeLineData(value);
  17753. this._geometryFilter._lineCount = Math.min(this._geometryFilter._lineCount, value);
  17754. }
  17755. get lineCount() {
  17756. return this._geometryFilter._lineCount;
  17757. }
  17758. set lineCount(value) {
  17759. if (value > this.maxLineCount)
  17760. throw "PixelLineSprite3D: lineCount can't large than maxLineCount";
  17761. else
  17762. this._geometryFilter._lineCount = value;
  17763. }
  17764. get pixelLineRenderer() {
  17765. return this._render;
  17766. }
  17767. _onInActive() {
  17768. Laya.Stat.spriteCount--;
  17769. if (this._geometryFilter._lineCount != 0 && this._isRenderActive) {
  17770. this._scene._removeRenderObject(this._render);
  17771. this._isInRenders = false;
  17772. }
  17773. this._isRenderActive = false;
  17774. }
  17775. _onActive() {
  17776. Laya.Stat.spriteCount++;
  17777. this._isRenderActive = true;
  17778. if (this._geometryFilter._lineCount != 0) {
  17779. this._scene._addRenderObject(this._render);
  17780. this._isInRenders = true;
  17781. }
  17782. }
  17783. _changeRenderObjects(sender, index, material) {
  17784. var renderObjects = this._render._renderElements;
  17785. (material) || (material = PixelLineMaterial.defaultMaterial);
  17786. var renderElement = renderObjects[index];
  17787. (renderElement) || (renderElement = renderObjects[index] = new RenderElement());
  17788. renderElement.setTransform(this._transform);
  17789. renderElement.setGeometry(this._geometryFilter);
  17790. renderElement.render = this._render;
  17791. renderElement.material = material;
  17792. }
  17793. addLine(startPosition, endPosition, startColor, endColor) {
  17794. if (this._geometryFilter._lineCount !== this._geometryFilter._maxLineCount)
  17795. this._geometryFilter._updateLineData(this._geometryFilter._lineCount++, startPosition, endPosition, startColor, endColor);
  17796. else
  17797. throw "PixelLineSprite3D: lineCount has equal with maxLineCount.";
  17798. if (this._isRenderActive && !this._isInRenders && this._geometryFilter._lineCount > 0) {
  17799. this._scene._addRenderObject(this._render);
  17800. this._isInRenders = true;
  17801. }
  17802. }
  17803. addLines(lines) {
  17804. var lineCount = this._geometryFilter._lineCount;
  17805. var addCount = lines.length;
  17806. if (lineCount + addCount > this._geometryFilter._maxLineCount) {
  17807. throw "PixelLineSprite3D: lineCount plus lines count must less than maxLineCount.";
  17808. }
  17809. else {
  17810. this._geometryFilter._updateLineDatas(lineCount, lines);
  17811. this._geometryFilter._lineCount += addCount;
  17812. }
  17813. if (this._isRenderActive && !this._isInRenders && this._geometryFilter._lineCount > 0) {
  17814. this._scene._addRenderObject(this._render);
  17815. this._isInRenders = true;
  17816. }
  17817. }
  17818. removeLine(index) {
  17819. if (index < this._geometryFilter._lineCount)
  17820. this._geometryFilter._removeLineData(index);
  17821. else
  17822. throw "PixelLineSprite3D: index must less than lineCount.";
  17823. if (this._isRenderActive && this._isInRenders && this._geometryFilter._lineCount == 0) {
  17824. this._scene._removeRenderObject(this._render);
  17825. this._isInRenders = false;
  17826. }
  17827. }
  17828. setLine(index, startPosition, endPosition, startColor, endColor) {
  17829. if (index < this._geometryFilter._lineCount)
  17830. this._geometryFilter._updateLineData(index, startPosition, endPosition, startColor, endColor);
  17831. else
  17832. throw "PixelLineSprite3D: index must less than lineCount.";
  17833. }
  17834. getLine(index, out) {
  17835. if (index < this.lineCount)
  17836. this._geometryFilter._getLineData(index, out);
  17837. else
  17838. throw "PixelLineSprite3D: index must less than lineCount.";
  17839. }
  17840. clear() {
  17841. this._geometryFilter._lineCount = 0;
  17842. if (this._isRenderActive && this._isInRenders) {
  17843. this._scene._removeRenderObject(this._render);
  17844. this._isInRenders = false;
  17845. }
  17846. }
  17847. _create() {
  17848. return new PixelLineSprite3D();
  17849. }
  17850. }
  17851. class RenderQueue {
  17852. constructor(isTransparent = false) {
  17853. this.isTransparent = false;
  17854. this.elements = new SingletonList();
  17855. this.lastTransparentRenderElement = null;
  17856. this.lastTransparentBatched = false;
  17857. this.isTransparent = isTransparent;
  17858. }
  17859. _compare(left, right) {
  17860. var renderQueue = left.material.renderQueue - right.material.renderQueue;
  17861. if (renderQueue === 0) {
  17862. var sort = this.isTransparent ? right.render._distanceForSort - left.render._distanceForSort : left.render._distanceForSort - right.render._distanceForSort;
  17863. return sort + right.render.sortingFudge - left.render.sortingFudge;
  17864. }
  17865. else {
  17866. return renderQueue;
  17867. }
  17868. }
  17869. _partitionRenderObject(left, right) {
  17870. var elements = this.elements.elements;
  17871. var pivot = elements[Math.floor((right + left) / 2)];
  17872. while (left <= right) {
  17873. while (this._compare(elements[left], pivot) < 0)
  17874. left++;
  17875. while (this._compare(elements[right], pivot) > 0)
  17876. right--;
  17877. if (left < right) {
  17878. var temp = elements[left];
  17879. elements[left] = elements[right];
  17880. elements[right] = temp;
  17881. left++;
  17882. right--;
  17883. }
  17884. else if (left === right) {
  17885. left++;
  17886. break;
  17887. }
  17888. }
  17889. return left;
  17890. }
  17891. _quickSort(left, right) {
  17892. if (this.elements.length > 1) {
  17893. var index = this._partitionRenderObject(left, right);
  17894. var leftIndex = index - 1;
  17895. if (left < leftIndex)
  17896. this._quickSort(left, leftIndex);
  17897. if (index < right)
  17898. this._quickSort(index, right);
  17899. }
  17900. }
  17901. _render(context) {
  17902. var elements = this.elements.elements;
  17903. for (var i = 0, n = this.elements.length; i < n; i++)
  17904. elements[i]._render(context);
  17905. }
  17906. clear() {
  17907. this.elements.length = 0;
  17908. this.lastTransparentRenderElement = null;
  17909. this.lastTransparentBatched = false;
  17910. }
  17911. }
  17912. class BoundsOctreeNode {
  17913. constructor(octree, parent, baseLength, center) {
  17914. this._bounds = new BoundBox(new Vector3(), new Vector3());
  17915. this._objects = [];
  17916. this._isContaion = false;
  17917. this.center = new Vector3();
  17918. this.baseLength = 0.0;
  17919. this._setValues(octree, parent, baseLength, center);
  17920. }
  17921. static _encapsulates(outerBound, innerBound) {
  17922. return CollisionUtils.boxContainsBox(outerBound, innerBound) == ContainmentType.Contains;
  17923. }
  17924. _setValues(octree, parent, baseLength, center) {
  17925. this._octree = octree;
  17926. this._parent = parent;
  17927. this.baseLength = baseLength;
  17928. center.cloneTo(this.center);
  17929. var min = this._bounds.min;
  17930. var max = this._bounds.max;
  17931. var halfSize = (octree._looseness * baseLength) / 2;
  17932. min.setValue(center.x - halfSize, center.y - halfSize, center.z - halfSize);
  17933. max.setValue(center.x + halfSize, center.y + halfSize, center.z + halfSize);
  17934. }
  17935. _getChildBound(index) {
  17936. if (this._children != null && this._children[index]) {
  17937. return this._children[index]._bounds;
  17938. }
  17939. else {
  17940. var quarter = this.baseLength / 4;
  17941. var halfChildSize = ((this.baseLength / 2) * this._octree._looseness) / 2;
  17942. var bounds = BoundsOctreeNode._tempBoundBox;
  17943. var min = bounds.min;
  17944. var max = bounds.max;
  17945. switch (index) {
  17946. case 0:
  17947. min.x = this.center.x - quarter - halfChildSize;
  17948. min.y = this.center.y + quarter - halfChildSize;
  17949. min.z = this.center.z - quarter - halfChildSize;
  17950. max.x = this.center.x - quarter + halfChildSize;
  17951. max.y = this.center.y + quarter + halfChildSize;
  17952. max.z = this.center.z - quarter + halfChildSize;
  17953. break;
  17954. case 1:
  17955. min.x = this.center.x + quarter - halfChildSize;
  17956. min.y = this.center.y + quarter - halfChildSize;
  17957. min.z = this.center.z - quarter - halfChildSize;
  17958. max.x = this.center.x + quarter + halfChildSize;
  17959. max.y = this.center.y + quarter + halfChildSize;
  17960. max.z = this.center.z - quarter + halfChildSize;
  17961. break;
  17962. case 2:
  17963. min.x = this.center.x - quarter - halfChildSize;
  17964. min.y = this.center.y + quarter - halfChildSize;
  17965. min.z = this.center.z + quarter - halfChildSize;
  17966. max.x = this.center.x - quarter + halfChildSize;
  17967. max.y = this.center.y + quarter + halfChildSize;
  17968. max.z = this.center.z + quarter + halfChildSize;
  17969. break;
  17970. case 3:
  17971. min.x = this.center.x + quarter - halfChildSize;
  17972. min.y = this.center.y + quarter - halfChildSize;
  17973. min.z = this.center.z + quarter - halfChildSize;
  17974. max.x = this.center.x + quarter + halfChildSize;
  17975. max.y = this.center.y + quarter + halfChildSize;
  17976. max.z = this.center.z + quarter + halfChildSize;
  17977. break;
  17978. case 4:
  17979. min.x = this.center.x - quarter - halfChildSize;
  17980. min.y = this.center.y - quarter - halfChildSize;
  17981. min.z = this.center.z - quarter - halfChildSize;
  17982. max.x = this.center.x - quarter + halfChildSize;
  17983. max.y = this.center.y - quarter + halfChildSize;
  17984. max.z = this.center.z - quarter + halfChildSize;
  17985. break;
  17986. case 5:
  17987. min.x = this.center.x + quarter - halfChildSize;
  17988. min.y = this.center.y - quarter - halfChildSize;
  17989. min.z = this.center.z - quarter - halfChildSize;
  17990. max.x = this.center.x + quarter + halfChildSize;
  17991. max.y = this.center.y - quarter + halfChildSize;
  17992. max.z = this.center.z - quarter + halfChildSize;
  17993. break;
  17994. case 6:
  17995. min.x = this.center.x - quarter - halfChildSize;
  17996. min.y = this.center.y - quarter - halfChildSize;
  17997. min.z = this.center.z + quarter - halfChildSize;
  17998. max.x = this.center.x - quarter + halfChildSize;
  17999. max.y = this.center.y - quarter + halfChildSize;
  18000. max.z = this.center.z + quarter + halfChildSize;
  18001. break;
  18002. case 7:
  18003. min.x = this.center.x + quarter - halfChildSize;
  18004. min.y = this.center.y - quarter - halfChildSize;
  18005. min.z = this.center.z + quarter - halfChildSize;
  18006. max.x = this.center.x + quarter + halfChildSize;
  18007. max.y = this.center.y - quarter + halfChildSize;
  18008. max.z = this.center.z + quarter + halfChildSize;
  18009. break;
  18010. default:
  18011. }
  18012. return bounds;
  18013. }
  18014. }
  18015. _getChildCenter(index) {
  18016. if (this._children != null) {
  18017. return this._children[index].center;
  18018. }
  18019. else {
  18020. var quarter = this.baseLength / 4;
  18021. var childCenter = BoundsOctreeNode._tempVector30;
  18022. switch (index) {
  18023. case 0:
  18024. childCenter.x = this.center.x - quarter;
  18025. childCenter.y = this.center.y + quarter;
  18026. childCenter.z = this.center.z - quarter;
  18027. break;
  18028. case 1:
  18029. childCenter.x = this.center.x + quarter;
  18030. childCenter.y = this.center.y + quarter;
  18031. childCenter.z = this.center.z - quarter;
  18032. break;
  18033. case 2:
  18034. childCenter.x = this.center.x - quarter;
  18035. childCenter.y = this.center.y + quarter;
  18036. childCenter.z = this.center.z + quarter;
  18037. break;
  18038. case 3:
  18039. childCenter.x = this.center.x + quarter;
  18040. childCenter.y = this.center.y + quarter;
  18041. childCenter.z = this.center.z + quarter;
  18042. break;
  18043. case 4:
  18044. childCenter.x = this.center.x - quarter;
  18045. childCenter.y = this.center.y - quarter;
  18046. childCenter.z = this.center.z - quarter;
  18047. break;
  18048. case 5:
  18049. childCenter.x = this.center.x + quarter;
  18050. childCenter.y = this.center.y - quarter;
  18051. childCenter.z = this.center.z - quarter;
  18052. break;
  18053. case 6:
  18054. childCenter.x = this.center.x - quarter;
  18055. childCenter.y = this.center.y - quarter;
  18056. childCenter.z = this.center.z + quarter;
  18057. break;
  18058. case 7:
  18059. childCenter.x = this.center.x + quarter;
  18060. childCenter.y = this.center.y - quarter;
  18061. childCenter.z = this.center.z + quarter;
  18062. break;
  18063. default:
  18064. }
  18065. return childCenter;
  18066. }
  18067. }
  18068. _getChild(index) {
  18069. var quarter = this.baseLength / 4;
  18070. this._children || (this._children = []);
  18071. switch (index) {
  18072. case 0:
  18073. return this._children[0] || (this._children[0] = new BoundsOctreeNode(this._octree, this, this.baseLength / 2, new Vector3(this.center.x + -quarter, this.center.y + quarter, this.center.z - quarter)));
  18074. case 1:
  18075. return this._children[1] || (this._children[1] = new BoundsOctreeNode(this._octree, this, this.baseLength / 2, new Vector3(this.center.x + quarter, this.center.y + quarter, this.center.z - quarter)));
  18076. case 2:
  18077. return this._children[2] || (this._children[2] = new BoundsOctreeNode(this._octree, this, this.baseLength / 2, new Vector3(this.center.x - quarter, this.center.y + quarter, this.center.z + quarter)));
  18078. case 3:
  18079. return this._children[3] || (this._children[3] = new BoundsOctreeNode(this._octree, this, this.baseLength / 2, new Vector3(this.center.x + quarter, this.center.y + quarter, this.center.z + quarter)));
  18080. case 4:
  18081. return this._children[4] || (this._children[4] = new BoundsOctreeNode(this._octree, this, this.baseLength / 2, new Vector3(this.center.x - quarter, this.center.y - quarter, this.center.z - quarter)));
  18082. case 5:
  18083. return this._children[5] || (this._children[5] = new BoundsOctreeNode(this._octree, this, this.baseLength / 2, new Vector3(this.center.x + quarter, this.center.y - quarter, this.center.z - quarter)));
  18084. case 6:
  18085. return this._children[6] || (this._children[6] = new BoundsOctreeNode(this._octree, this, this.baseLength / 2, new Vector3(this.center.x - quarter, this.center.y - quarter, this.center.z + quarter)));
  18086. case 7:
  18087. return this._children[7] || (this._children[7] = new BoundsOctreeNode(this._octree, this, this.baseLength / 2, new Vector3(this.center.x + quarter, this.center.y - quarter, this.center.z + quarter)));
  18088. default:
  18089. throw "BoundsOctreeNode: unknown index.";
  18090. }
  18091. }
  18092. _shouldMerge() {
  18093. var objectCount = this._objects.length;
  18094. for (var i = 0; i < 8; i++) {
  18095. var child = this._children[i];
  18096. if (child) {
  18097. if (child._children != null)
  18098. return false;
  18099. objectCount += child._objects.length;
  18100. }
  18101. }
  18102. return objectCount <= BoundsOctreeNode._NUM_OBJECTS_ALLOWED;
  18103. }
  18104. _mergeChildren() {
  18105. for (var i = 0; i < 8; i++) {
  18106. var child = this._children[i];
  18107. if (child) {
  18108. child._parent = null;
  18109. var childObjects = child._objects;
  18110. for (var j = childObjects.length - 1; j >= 0; j--) {
  18111. var childObject = childObjects[j];
  18112. this._objects.push(childObject);
  18113. childObject._setOctreeNode(this);
  18114. }
  18115. }
  18116. }
  18117. this._children = null;
  18118. }
  18119. _merge() {
  18120. if (this._children === null) {
  18121. var parent = this._parent;
  18122. if (parent && parent._shouldMerge()) {
  18123. parent._mergeChildren();
  18124. parent._merge();
  18125. }
  18126. }
  18127. }
  18128. _checkAddNode(object) {
  18129. if (this._children == null) {
  18130. if (this._objects.length < BoundsOctreeNode._NUM_OBJECTS_ALLOWED || (this.baseLength / 2) < this._octree._minSize) {
  18131. return this;
  18132. }
  18133. for (var i = this._objects.length - 1; i >= 0; i--) {
  18134. var existObject = this._objects[i];
  18135. var fitChildIndex = this._bestFitChild(existObject.bounds.getCenter());
  18136. if (BoundsOctreeNode._encapsulates(this._getChildBound(fitChildIndex), existObject.bounds._getBoundBox())) {
  18137. this._objects.splice(this._objects.indexOf(existObject), 1);
  18138. this._getChild(fitChildIndex)._add(existObject);
  18139. }
  18140. }
  18141. }
  18142. var newFitChildIndex = this._bestFitChild(object.bounds.getCenter());
  18143. if (BoundsOctreeNode._encapsulates(this._getChildBound(newFitChildIndex), object.bounds._getBoundBox()))
  18144. return this._getChild(newFitChildIndex)._checkAddNode(object);
  18145. else
  18146. return this;
  18147. }
  18148. _add(object) {
  18149. var addNode = this._checkAddNode(object);
  18150. addNode._objects.push(object);
  18151. object._setOctreeNode(addNode);
  18152. }
  18153. _remove(object) {
  18154. var index = this._objects.indexOf(object);
  18155. this._objects.splice(index, 1);
  18156. object._setOctreeNode(null);
  18157. this._merge();
  18158. }
  18159. _addUp(object) {
  18160. if ((CollisionUtils.boxContainsBox(this._bounds, object.bounds._getBoundBox()) === ContainmentType.Contains)) {
  18161. this._add(object);
  18162. return true;
  18163. }
  18164. else {
  18165. if (this._parent)
  18166. return this._parent._addUp(object);
  18167. else
  18168. return false;
  18169. }
  18170. }
  18171. _getCollidingWithFrustum(cameraCullInfo, context, testVisible, customShader, replacementTag, isShadowCasterCull) {
  18172. var frustum = cameraCullInfo.boundFrustum;
  18173. var camPos = cameraCullInfo.position;
  18174. var cullMask = cameraCullInfo.cullingMask;
  18175. if (testVisible) {
  18176. var type = frustum.containsBoundBox(this._bounds);
  18177. Laya.Stat.octreeNodeCulling++;
  18178. if (type === ContainmentType.Disjoint)
  18179. return;
  18180. testVisible = (type === ContainmentType.Intersects);
  18181. }
  18182. this._isContaion = !testVisible;
  18183. var scene = context.scene;
  18184. var loopCount = Laya.Stat.loopCount;
  18185. for (var i = 0, n = this._objects.length; i < n; i++) {
  18186. var render = this._objects[i];
  18187. var canPass;
  18188. if (isShadowCasterCull)
  18189. canPass = render._castShadow && render._enable;
  18190. else
  18191. canPass = (((Math.pow(2, render._owner._layer) & cullMask) != 0)) && render._enable;
  18192. if (canPass) {
  18193. if (testVisible) {
  18194. Laya.Stat.frustumCulling++;
  18195. if (!render._needRender(frustum, context))
  18196. continue;
  18197. }
  18198. render._renderMark = loopCount;
  18199. render._distanceForSort = Vector3.distance(render.bounds.getCenter(), camPos);
  18200. var elements = render._renderElements;
  18201. for (var j = 0, m = elements.length; j < m; j++) {
  18202. var element = elements[j];
  18203. element._update(scene, context, customShader, replacementTag);
  18204. }
  18205. }
  18206. }
  18207. if (this._children != null) {
  18208. for (i = 0; i < 8; i++) {
  18209. var child = this._children[i];
  18210. child && child._getCollidingWithFrustum(cameraCullInfo, context, testVisible, customShader, replacementTag, isShadowCasterCull);
  18211. }
  18212. }
  18213. }
  18214. _getCollidingWithBoundBox(checkBound, testVisible, result) {
  18215. if (testVisible) {
  18216. var type = CollisionUtils.boxContainsBox(this._bounds, checkBound);
  18217. if (type === ContainmentType.Disjoint)
  18218. return;
  18219. testVisible = (type === ContainmentType.Intersects);
  18220. }
  18221. if (testVisible) {
  18222. for (var i = 0, n = this._objects.length; i < n; i++) {
  18223. var object = this._objects[i];
  18224. if (CollisionUtils.intersectsBoxAndBox(object.bounds._getBoundBox(), checkBound)) {
  18225. result.push(object);
  18226. }
  18227. }
  18228. }
  18229. if (this._children != null) {
  18230. for (i = 0; i < 8; i++) {
  18231. var child = this._children[i];
  18232. child._getCollidingWithBoundBox(checkBound, testVisible, result);
  18233. }
  18234. }
  18235. }
  18236. _bestFitChild(boundCenter) {
  18237. return (boundCenter.x <= this.center.x ? 0 : 1) + (boundCenter.y >= this.center.y ? 0 : 4) + (boundCenter.z <= this.center.z ? 0 : 2);
  18238. }
  18239. _update(object) {
  18240. if (CollisionUtils.boxContainsBox(this._bounds, object.bounds._getBoundBox()) === ContainmentType.Contains) {
  18241. var addNode = this._checkAddNode(object);
  18242. if (addNode !== object._getOctreeNode()) {
  18243. addNode._objects.push(object);
  18244. object._setOctreeNode(addNode);
  18245. var index = this._objects.indexOf(object);
  18246. this._objects.splice(index, 1);
  18247. this._merge();
  18248. }
  18249. return true;
  18250. }
  18251. else {
  18252. if (this._parent) {
  18253. var sucess = this._parent._addUp(object);
  18254. if (sucess) {
  18255. index = this._objects.indexOf(object);
  18256. this._objects.splice(index, 1);
  18257. this._merge();
  18258. }
  18259. return sucess;
  18260. }
  18261. else {
  18262. return false;
  18263. }
  18264. }
  18265. }
  18266. add(object) {
  18267. if (!BoundsOctreeNode._encapsulates(this._bounds, object.bounds._getBoundBox()))
  18268. return false;
  18269. this._add(object);
  18270. return true;
  18271. }
  18272. remove(object) {
  18273. if (object._getOctreeNode() !== this)
  18274. return false;
  18275. this._remove(object);
  18276. return true;
  18277. }
  18278. update(object) {
  18279. if (object._getOctreeNode() !== this)
  18280. return false;
  18281. return this._update(object);
  18282. }
  18283. shrinkIfPossible(minLength) {
  18284. if (this.baseLength < minLength * 2)
  18285. return this;
  18286. var bestFit = -1;
  18287. for (var i = 0, n = this._objects.length; i < n; i++) {
  18288. var object = this._objects[i];
  18289. var newBestFit = this._bestFitChild(object.bounds.getCenter());
  18290. if (i == 0 || newBestFit == bestFit) {
  18291. var childBounds = this._getChildBound(newBestFit);
  18292. if (BoundsOctreeNode._encapsulates(childBounds, object.bounds._getBoundBox()))
  18293. (i == 0) && (bestFit = newBestFit);
  18294. else
  18295. return this;
  18296. }
  18297. else {
  18298. return this;
  18299. }
  18300. }
  18301. if (this._children != null) {
  18302. var childHadContent = false;
  18303. for (i = 0, n = this._children.length; i < n; i++) {
  18304. var child = this._children[i];
  18305. if (child && child.hasAnyObjects()) {
  18306. if (childHadContent)
  18307. return this;
  18308. if (bestFit >= 0 && bestFit != i)
  18309. return this;
  18310. childHadContent = true;
  18311. bestFit = i;
  18312. }
  18313. }
  18314. }
  18315. else {
  18316. if (bestFit != -1) {
  18317. var childCenter = this._getChildCenter(bestFit);
  18318. this._setValues(this._octree, null, this.baseLength / 2, childCenter);
  18319. }
  18320. return this;
  18321. }
  18322. if (bestFit != -1) {
  18323. var newRoot = this._children[bestFit];
  18324. newRoot._parent = null;
  18325. return newRoot;
  18326. }
  18327. else {
  18328. return this;
  18329. }
  18330. }
  18331. hasAnyObjects() {
  18332. if (this._objects.length > 0)
  18333. return true;
  18334. if (this._children != null) {
  18335. for (var i = 0; i < 8; i++) {
  18336. var child = this._children[i];
  18337. if (child && child.hasAnyObjects())
  18338. return true;
  18339. }
  18340. }
  18341. return false;
  18342. }
  18343. getCollidingWithBoundBox(checkBound, result) {
  18344. this._getCollidingWithBoundBox(checkBound, true, result);
  18345. }
  18346. getCollidingWithRay(ray, result, maxDistance = Number.MAX_VALUE) {
  18347. var distance = CollisionUtils.intersectsRayAndBoxRD(ray, this._bounds);
  18348. if (distance == -1 || distance > maxDistance)
  18349. return;
  18350. for (var i = 0, n = this._objects.length; i < n; i++) {
  18351. var object = this._objects[i];
  18352. distance = CollisionUtils.intersectsRayAndBoxRD(ray, object.bounds._getBoundBox());
  18353. if (distance !== -1 && distance <= maxDistance)
  18354. result.push(object);
  18355. }
  18356. if (this._children != null) {
  18357. for (i = 0; i < 8; i++) {
  18358. var child = this._children[i];
  18359. child.getCollidingWithRay(ray, result, maxDistance);
  18360. }
  18361. }
  18362. }
  18363. getCollidingWithFrustum(cameraCullInfo, context, customShader, replacementTag, isShadowCasterCull) {
  18364. this._getCollidingWithFrustum(cameraCullInfo, context, true, customShader, replacementTag, isShadowCasterCull);
  18365. }
  18366. isCollidingWithBoundBox(checkBound) {
  18367. if (!(CollisionUtils.intersectsBoxAndBox(this._bounds, checkBound)))
  18368. return false;
  18369. for (var i = 0, n = this._objects.length; i < n; i++) {
  18370. var object = this._objects[i];
  18371. if (CollisionUtils.intersectsBoxAndBox(object.bounds._getBoundBox(), checkBound))
  18372. return true;
  18373. }
  18374. if (this._children != null) {
  18375. for (i = 0; i < 8; i++) {
  18376. var child = this._children[i];
  18377. if (child.isCollidingWithBoundBox(checkBound))
  18378. return true;
  18379. }
  18380. }
  18381. return false;
  18382. }
  18383. isCollidingWithRay(ray, maxDistance = Number.MAX_VALUE) {
  18384. var distance = CollisionUtils.intersectsRayAndBoxRD(ray, this._bounds);
  18385. if (distance == -1 || distance > maxDistance)
  18386. return false;
  18387. for (var i = 0, n = this._objects.length; i < n; i++) {
  18388. var object = this._objects[i];
  18389. distance = CollisionUtils.intersectsRayAndBoxRD(ray, object.bounds._getBoundBox());
  18390. if (distance !== -1 && distance <= maxDistance)
  18391. return true;
  18392. }
  18393. if (this._children != null) {
  18394. for (i = 0; i < 8; i++) {
  18395. var child = this._children[i];
  18396. if (child.isCollidingWithRay(ray, maxDistance))
  18397. return true;
  18398. }
  18399. }
  18400. return false;
  18401. }
  18402. getBound() {
  18403. return this._bounds;
  18404. }
  18405. drawAllBounds(debugLine, currentDepth, maxDepth) {
  18406. if (this._children === null && this._objects.length == 0)
  18407. return;
  18408. currentDepth++;
  18409. var color = BoundsOctreeNode._tempColor0;
  18410. if (this._isContaion) {
  18411. color.r = 0.0;
  18412. color.g = 0.0;
  18413. color.b = 1.0;
  18414. }
  18415. else {
  18416. var tint = maxDepth ? currentDepth / maxDepth : 0;
  18417. color.r = 1.0 - tint;
  18418. color.g = tint;
  18419. color.b = 0.0;
  18420. }
  18421. color.a = 0.3;
  18422. Utils3D._drawBound(debugLine, this._bounds, color);
  18423. if (this._children != null) {
  18424. for (var i = 0; i < 8; i++) {
  18425. var child = this._children[i];
  18426. child && child.drawAllBounds(debugLine, currentDepth, maxDepth);
  18427. }
  18428. }
  18429. }
  18430. drawAllObjects(debugLine, currentDepth, maxDepth) {
  18431. currentDepth++;
  18432. var color = BoundsOctreeNode._tempColor0;
  18433. if (this._isContaion) {
  18434. color.r = 0.0;
  18435. color.g = 0.0;
  18436. color.b = 1.0;
  18437. }
  18438. else {
  18439. var tint = maxDepth ? currentDepth / maxDepth : 0;
  18440. color.r = 1.0 - tint;
  18441. color.g = tint;
  18442. color.b = 0.0;
  18443. }
  18444. color.a = 1.0;
  18445. for (var i = 0, n = this._objects.length; i < n; i++)
  18446. Utils3D._drawBound(debugLine, this._objects[i].bounds._getBoundBox(), color);
  18447. if (this._children != null) {
  18448. for (i = 0; i < 8; i++) {
  18449. var child = this._children[i];
  18450. child && child.drawAllObjects(debugLine, currentDepth, maxDepth);
  18451. }
  18452. }
  18453. }
  18454. }
  18455. BoundsOctreeNode._tempVector3 = new Vector3();
  18456. BoundsOctreeNode._tempVector30 = new Vector3();
  18457. BoundsOctreeNode._tempVector31 = new Vector3();
  18458. BoundsOctreeNode._tempColor0 = new Color();
  18459. BoundsOctreeNode._tempBoundBox = new BoundBox(new Vector3(), new Vector3());
  18460. BoundsOctreeNode._NUM_OBJECTS_ALLOWED = 8;
  18461. class OctreeMotionList extends SingletonList {
  18462. constructor() {
  18463. super();
  18464. }
  18465. add(element) {
  18466. var index = element._getIndexInMotionList();
  18467. if (index !== -1)
  18468. throw "OctreeMotionList:element has in PhysicsUpdateList.";
  18469. this._add(element);
  18470. element._setIndexInMotionList(this.length++);
  18471. }
  18472. remove(element) {
  18473. var index = element._getIndexInMotionList();
  18474. this.length--;
  18475. if (index !== this.length) {
  18476. var end = this.elements[this.length];
  18477. this.elements[index] = end;
  18478. end._setIndexInMotionList(index);
  18479. }
  18480. element._setIndexInMotionList(-1);
  18481. }
  18482. }
  18483. class BoundsOctree {
  18484. constructor(initialWorldSize, initialWorldPos, minNodeSize, looseness) {
  18485. this._motionObjects = new OctreeMotionList();
  18486. this.count = 0;
  18487. if (minNodeSize > initialWorldSize) {
  18488. console.warn("Minimum node size must be at least as big as the initial world size. Was: " + minNodeSize + " Adjusted to: " + initialWorldSize);
  18489. minNodeSize = initialWorldSize;
  18490. }
  18491. this._initialSize = initialWorldSize;
  18492. this._minSize = minNodeSize;
  18493. this._looseness = Math.min(Math.max(looseness, 1.0), 2.0);
  18494. this._rootNode = new BoundsOctreeNode(this, null, initialWorldSize, initialWorldPos);
  18495. }
  18496. _getMaxDepth(node, depth) {
  18497. depth++;
  18498. var children = node._children;
  18499. if (children != null) {
  18500. var curDepth = depth;
  18501. for (var i = 0, n = children.length; i < n; i++) {
  18502. var child = children[i];
  18503. child && (depth = Math.max(this._getMaxDepth(child, curDepth), depth));
  18504. }
  18505. }
  18506. return depth;
  18507. }
  18508. _grow(growObjectCenter) {
  18509. var xDirection = growObjectCenter.x >= 0 ? 1 : -1;
  18510. var yDirection = growObjectCenter.y >= 0 ? 1 : -1;
  18511. var zDirection = growObjectCenter.z >= 0 ? 1 : -1;
  18512. var oldRoot = this._rootNode;
  18513. var half = this._rootNode.baseLength / 2;
  18514. var newLength = this._rootNode.baseLength * 2;
  18515. var rootCenter = this._rootNode.center;
  18516. var newCenter = new Vector3(rootCenter.x + xDirection * half, rootCenter.y + yDirection * half, rootCenter.z + zDirection * half);
  18517. this._rootNode = new BoundsOctreeNode(this, null, newLength, newCenter);
  18518. if (oldRoot.hasAnyObjects()) {
  18519. var rootPos = this._rootNode._bestFitChild(oldRoot.center);
  18520. var children = [];
  18521. for (var i = 0; i < 8; i++) {
  18522. if (i == rootPos) {
  18523. oldRoot._parent = this._rootNode;
  18524. children[i] = oldRoot;
  18525. }
  18526. }
  18527. this._rootNode._children = children;
  18528. }
  18529. }
  18530. add(object) {
  18531. var count = 0;
  18532. while (!this._rootNode.add(object)) {
  18533. var growCenter = BoundsOctree._tempVector30;
  18534. Vector3.subtract(object.bounds.getCenter(), this._rootNode.center, growCenter);
  18535. this._grow(growCenter);
  18536. if (++count > 20) {
  18537. throw "Aborted Add operation as it seemed to be going on forever (" + (count - 1) + ") attempts at growing the octree.";
  18538. }
  18539. }
  18540. this.count++;
  18541. }
  18542. remove(object) {
  18543. var removed = object._getOctreeNode().remove(object);
  18544. if (removed) {
  18545. this.count--;
  18546. }
  18547. return removed;
  18548. }
  18549. update(object) {
  18550. var count = 0;
  18551. var octreeNode = object._getOctreeNode();
  18552. if (octreeNode) {
  18553. while (!octreeNode._update(object)) {
  18554. var growCenter = BoundsOctree._tempVector30;
  18555. Vector3.subtract(object.bounds.getCenter(), this._rootNode.center, growCenter);
  18556. this._grow(growCenter);
  18557. if (++count > 20) {
  18558. throw "Aborted Add operation as it seemed to be going on forever (" + (count - 1) + ") attempts at growing the octree.";
  18559. }
  18560. }
  18561. return true;
  18562. }
  18563. else {
  18564. return false;
  18565. }
  18566. }
  18567. shrinkRootIfPossible() {
  18568. this._rootNode = this._rootNode.shrinkIfPossible(this._initialSize);
  18569. }
  18570. addMotionObject(object) {
  18571. this._motionObjects.add(object);
  18572. }
  18573. removeMotionObject(object) {
  18574. this._motionObjects.remove(object);
  18575. }
  18576. updateMotionObjects() {
  18577. var elements = this._motionObjects.elements;
  18578. for (var i = 0, n = this._motionObjects.length; i < n; i++) {
  18579. var object = elements[i];
  18580. this.update(object);
  18581. object._setIndexInMotionList(-1);
  18582. }
  18583. this._motionObjects.length = 0;
  18584. }
  18585. isCollidingWithBoundBox(checkBounds) {
  18586. return this._rootNode.isCollidingWithBoundBox(checkBounds);
  18587. }
  18588. isCollidingWithRay(ray, maxDistance = Number.MAX_VALUE) {
  18589. return this._rootNode.isCollidingWithRay(ray, maxDistance);
  18590. }
  18591. getCollidingWithBoundBox(checkBound, result) {
  18592. this._rootNode.getCollidingWithBoundBox(checkBound, result);
  18593. }
  18594. getCollidingWithRay(ray, result, maxDistance = Number.MAX_VALUE) {
  18595. this._rootNode.getCollidingWithRay(ray, result, maxDistance);
  18596. }
  18597. getCollidingWithFrustum(cameraCullInfo, context, shader, replacementTag, isShadowCasterCull) {
  18598. this._rootNode.getCollidingWithFrustum(cameraCullInfo, context, shader, replacementTag, isShadowCasterCull);
  18599. }
  18600. getMaxBounds() {
  18601. return this._rootNode.getBound();
  18602. }
  18603. drawAllBounds(pixelLine) {
  18604. var maxDepth = this._getMaxDepth(this._rootNode, -1);
  18605. this._rootNode.drawAllBounds(pixelLine, -1, maxDepth);
  18606. }
  18607. drawAllObjects(pixelLine) {
  18608. var maxDepth = this._getMaxDepth(this._rootNode, -1);
  18609. this._rootNode.drawAllObjects(pixelLine, -1, maxDepth);
  18610. }
  18611. }
  18612. BoundsOctree._tempVector30 = new Vector3();
  18613. class Lightmap {
  18614. }
  18615. class BoundSphere {
  18616. constructor(center, radius) {
  18617. this.center = center;
  18618. this.radius = radius;
  18619. }
  18620. toDefault() {
  18621. this.center.toDefault();
  18622. this.radius = 0;
  18623. }
  18624. static createFromSubPoints(points, start, count, out) {
  18625. if (points == null) {
  18626. throw new Error("points");
  18627. }
  18628. if (start < 0 || start >= points.length) {
  18629. throw new Error("start" + start + "Must be in the range [0, " + (points.length - 1) + "]");
  18630. }
  18631. if (count < 0 || (start + count) > points.length) {
  18632. throw new Error("count" + count + "Must be in the range <= " + points.length + "}");
  18633. }
  18634. var upperEnd = start + count;
  18635. var center = BoundSphere._tempVector3;
  18636. center.x = 0;
  18637. center.y = 0;
  18638. center.z = 0;
  18639. for (var i = start; i < upperEnd; ++i) {
  18640. Vector3.add(points[i], center, center);
  18641. }
  18642. var outCenter = out.center;
  18643. Vector3.scale(center, 1 / count, outCenter);
  18644. var radius = 0.0;
  18645. for (i = start; i < upperEnd; ++i) {
  18646. var distance = Vector3.distanceSquared(outCenter, points[i]);
  18647. if (distance > radius)
  18648. radius = distance;
  18649. }
  18650. out.radius = Math.sqrt(radius);
  18651. }
  18652. static createfromPoints(points, out) {
  18653. if (points == null) {
  18654. throw new Error("points");
  18655. }
  18656. BoundSphere.createFromSubPoints(points, 0, points.length, out);
  18657. }
  18658. intersectsRayDistance(ray) {
  18659. return CollisionUtils.intersectsRayAndSphereRD(ray, this);
  18660. }
  18661. intersectsRayPoint(ray, outPoint) {
  18662. return CollisionUtils.intersectsRayAndSphereRP(ray, this, outPoint);
  18663. }
  18664. cloneTo(destObject) {
  18665. var dest = destObject;
  18666. this.center.cloneTo(dest.center);
  18667. dest.radius = this.radius;
  18668. }
  18669. clone() {
  18670. var dest = new BoundSphere(new Vector3(), 0);
  18671. this.cloneTo(dest);
  18672. return dest;
  18673. }
  18674. }
  18675. BoundSphere._tempVector3 = new Vector3();
  18676. class ShadowSliceData {
  18677. constructor() {
  18678. this.cameraShaderValue = new ShaderData();
  18679. this.position = new Vector3();
  18680. this.viewMatrix = new Matrix4x4();
  18681. this.projectionMatrix = new Matrix4x4();
  18682. this.viewProjectMatrix = new Matrix4x4();
  18683. this.cullPlanes = [new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3())];
  18684. this.splitBoundSphere = new BoundSphere(new Vector3(), 0.0);
  18685. }
  18686. }
  18687. class ShadowSpotData {
  18688. constructor() {
  18689. this.cameraShaderValue = new ShaderData();
  18690. this.position = new Vector3;
  18691. this.viewMatrix = new Matrix4x4();
  18692. this.projectionMatrix = new Matrix4x4();
  18693. this.viewProjectMatrix = new Matrix4x4();
  18694. this.cameraCullInfo = new CameraCullInfo();
  18695. }
  18696. }
  18697. (function (ShadowLightType) {
  18698. ShadowLightType[ShadowLightType["DirectionLight"] = 0] = "DirectionLight";
  18699. ShadowLightType[ShadowLightType["SpotLight"] = 1] = "SpotLight";
  18700. ShadowLightType[ShadowLightType["PointLight"] = 2] = "PointLight";
  18701. })(exports.ShadowLightType || (exports.ShadowLightType = {}));
  18702. class ShadowCasterPass {
  18703. constructor() {
  18704. this._shadowBias = new Vector4();
  18705. this._shadowParams = new Vector4();
  18706. this._shadowMapSize = new Vector4();
  18707. this._shadowSpotMapSize = new Vector4();
  18708. this._shadowMatrices = new Float32Array(16 * (ShadowCasterPass._maxCascades));
  18709. this._shadowSpotMatrices = new Matrix4x4();
  18710. this._splitBoundSpheres = new Float32Array(ShadowCasterPass._maxCascades * 4);
  18711. this._cascadeCount = 0;
  18712. this._shadowMapWidth = 0;
  18713. this._shadowMapHeight = 0;
  18714. this._shadowSliceDatas = [new ShadowSliceData(), new ShadowSliceData(), new ShadowSliceData(), new ShadowSliceData()];
  18715. this._shadowSpotData = new ShadowSpotData();
  18716. this._lightUp = new Vector3();
  18717. this._lightSide = new Vector3();
  18718. this._lightForward = new Vector3();
  18719. this._shadowSpotData.cameraCullInfo.boundFrustum = new BoundFrustum(new Matrix4x4());
  18720. }
  18721. _setupShadowCasterShaderValues(context, shaderValues, shadowSliceData, LightParam, shadowparams, shadowBias, lightType) {
  18722. shaderValues.setVector(ShadowCasterPass.SHADOW_BIAS, shadowBias);
  18723. switch (lightType) {
  18724. case exports.LightType.Directional:
  18725. shaderValues.setVector3(ShadowCasterPass.SHADOW_LIGHT_DIRECTION, LightParam);
  18726. break;
  18727. case exports.LightType.Spot:
  18728. shaderValues.setVector(ShadowCasterPass.SHADOW_PARAMS, shadowparams);
  18729. break;
  18730. case exports.LightType.Point:
  18731. break;
  18732. }
  18733. var cameraSV = shadowSliceData.cameraShaderValue;
  18734. cameraSV.setMatrix4x4(BaseCamera.VIEWMATRIX, shadowSliceData.viewMatrix);
  18735. cameraSV.setMatrix4x4(BaseCamera.PROJECTMATRIX, shadowSliceData.projectionMatrix);
  18736. cameraSV.setMatrix4x4(BaseCamera.VIEWPROJECTMATRIX, shadowSliceData.viewProjectMatrix);
  18737. context.viewMatrix = shadowSliceData.viewMatrix;
  18738. context.projectionMatrix = shadowSliceData.projectionMatrix;
  18739. context.projectionViewMatrix = shadowSliceData.viewProjectMatrix;
  18740. }
  18741. _setupShadowReceiverShaderValues(shaderValues) {
  18742. var light = this._light;
  18743. if (light.shadowCascadesMode !== exports.ShadowCascadesMode.NoCascades)
  18744. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_CASCADE);
  18745. else
  18746. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_CASCADE);
  18747. switch (light.shadowMode) {
  18748. case exports.ShadowMode.Hard:
  18749. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SOFT_SHADOW_LOW);
  18750. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SOFT_SHADOW_HIGH);
  18751. break;
  18752. case exports.ShadowMode.SoftLow:
  18753. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SOFT_SHADOW_LOW);
  18754. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SOFT_SHADOW_HIGH);
  18755. break;
  18756. case exports.ShadowMode.SoftHigh:
  18757. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SOFT_SHADOW_HIGH);
  18758. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SOFT_SHADOW_LOW);
  18759. break;
  18760. }
  18761. shaderValues.setTexture(ShadowCasterPass.SHADOW_MAP, this._shadowDirectLightMap);
  18762. shaderValues.setBuffer(ShadowCasterPass.SHADOW_MATRICES, this._shadowMatrices);
  18763. shaderValues.setVector(ShadowCasterPass.SHADOW_MAP_SIZE, this._shadowMapSize);
  18764. shaderValues.setVector(ShadowCasterPass.SHADOW_PARAMS, this._shadowParams);
  18765. shaderValues.setBuffer(ShadowCasterPass.SHADOW_SPLIT_SPHERES, this._splitBoundSpheres);
  18766. }
  18767. _setupSpotShadowReceiverShaderValues(shaderValues) {
  18768. var spotLight = this._light;
  18769. switch (spotLight.shadowMode) {
  18770. case exports.ShadowMode.Hard:
  18771. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT_SOFT_SHADOW_HIGH);
  18772. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT_SOFT_SHADOW_LOW);
  18773. break;
  18774. case exports.ShadowMode.SoftLow:
  18775. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT_SOFT_SHADOW_LOW);
  18776. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT_SOFT_SHADOW_HIGH);
  18777. break;
  18778. case exports.ShadowMode.SoftHigh:
  18779. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT_SOFT_SHADOW_HIGH);
  18780. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT_SOFT_SHADOW_LOW);
  18781. break;
  18782. }
  18783. shaderValues.setTexture(ShadowCasterPass.SHADOW_SPOTMAP, this._shadowSpotLightMap);
  18784. shaderValues.setMatrix4x4(ShadowCasterPass.SHADOW_SPOTMATRICES, this._shadowSpotMatrices);
  18785. shaderValues.setVector(ShadowCasterPass.SHADOW_SPOTMAP_SIZE, this._shadowSpotMapSize);
  18786. shaderValues.setVector(ShadowCasterPass.SHADOW_PARAMS, this._shadowParams);
  18787. }
  18788. update(camera, light, lightType) {
  18789. switch (lightType) {
  18790. case exports.ShadowLightType.DirectionLight:
  18791. this._light = light;
  18792. var lightWorld = ShadowCasterPass._tempMatrix0;
  18793. var lightWorldE = lightWorld.elements;
  18794. var lightUp = this._lightUp;
  18795. var lightSide = this._lightSide;
  18796. var lightForward = this._lightForward;
  18797. Matrix4x4.createFromQuaternion(light._transform.rotation, lightWorld);
  18798. lightSide.setValue(lightWorldE[0], lightWorldE[1], lightWorldE[2]);
  18799. lightUp.setValue(lightWorldE[4], lightWorldE[5], lightWorldE[6]);
  18800. lightForward.setValue(-lightWorldE[8], -lightWorldE[9], -lightWorldE[10]);
  18801. var atlasResolution = light._shadowResolution;
  18802. var cascadesMode = light._shadowCascadesMode;
  18803. var cascadesCount;
  18804. var shadowTileResolution;
  18805. var shadowMapWidth, shadowMapHeight;
  18806. if (cascadesMode == exports.ShadowCascadesMode.NoCascades) {
  18807. cascadesCount = 1;
  18808. shadowTileResolution = atlasResolution;
  18809. shadowMapWidth = atlasResolution;
  18810. shadowMapHeight = atlasResolution;
  18811. }
  18812. else {
  18813. cascadesCount = cascadesMode == exports.ShadowCascadesMode.TwoCascades ? 2 : 4;
  18814. shadowTileResolution = ShadowUtils.getMaxTileResolutionInAtlas(atlasResolution, atlasResolution, cascadesCount);
  18815. shadowMapWidth = shadowTileResolution * 2;
  18816. shadowMapHeight = cascadesMode == exports.ShadowCascadesMode.TwoCascades ? shadowTileResolution : shadowTileResolution * 2;
  18817. }
  18818. this._cascadeCount = cascadesCount;
  18819. this._shadowMapWidth = shadowMapWidth;
  18820. this._shadowMapHeight = shadowMapHeight;
  18821. var splitDistance = ShadowCasterPass._cascadesSplitDistance;
  18822. var frustumPlanes = ShadowCasterPass._frustumPlanes;
  18823. var cameraNear = camera.nearPlane;
  18824. var shadowFar = Math.min(camera.farPlane, light._shadowDistance);
  18825. var shadowMatrices = this._shadowMatrices;
  18826. var boundSpheres = this._splitBoundSpheres;
  18827. ShadowUtils.getCascadesSplitDistance(light._shadowTwoCascadeSplits, light._shadowFourCascadeSplits, cameraNear, shadowFar, camera.fieldOfView * MathUtils3D.Deg2Rad, camera.aspectRatio, cascadesMode, splitDistance);
  18828. ShadowUtils.getCameraFrustumPlanes(camera.projectionViewMatrix, frustumPlanes);
  18829. var forward = ShadowCasterPass._tempVector30;
  18830. camera._transform.getForward(forward);
  18831. Vector3.normalize(forward, forward);
  18832. for (var i = 0; i < cascadesCount; i++) {
  18833. var sliceData = this._shadowSliceDatas[i];
  18834. sliceData.sphereCenterZ = ShadowUtils.getBoundSphereByFrustum(splitDistance[i], splitDistance[i + 1], camera.fieldOfView * MathUtils3D.Deg2Rad, camera.aspectRatio, camera._transform.position, forward, sliceData.splitBoundSphere);
  18835. ShadowUtils.getDirectionLightShadowCullPlanes(frustumPlanes, i, splitDistance, cameraNear, lightForward, sliceData);
  18836. ShadowUtils.getDirectionalLightMatrices(lightUp, lightSide, lightForward, i, light._shadowNearPlane, shadowTileResolution, sliceData, shadowMatrices);
  18837. if (cascadesCount > 1)
  18838. ShadowUtils.applySliceTransform(sliceData, shadowMapWidth, shadowMapHeight, i, shadowMatrices);
  18839. }
  18840. ShadowUtils.prepareShadowReceiverShaderValues(light, shadowMapWidth, shadowMapHeight, this._shadowSliceDatas, cascadesCount, this._shadowMapSize, this._shadowParams, shadowMatrices, boundSpheres);
  18841. break;
  18842. case exports.ShadowLightType.SpotLight:
  18843. this._light = light;
  18844. var lightWorld = ShadowCasterPass._tempMatrix0;
  18845. var lightForward = this._lightForward;
  18846. var shadowResolution = this._light._shadowResolution;
  18847. this._shadowMapWidth = shadowResolution;
  18848. this._shadowMapHeight = shadowResolution;
  18849. var shadowSpotData = this._shadowSpotData;
  18850. ShadowUtils.getSpotLightShadowData(shadowSpotData, this._light, shadowResolution, this._shadowParams, this._shadowSpotMatrices, this._shadowSpotMapSize);
  18851. break;
  18852. case exports.ShadowLightType.PointLight:
  18853. break;
  18854. default:
  18855. throw ("There is no shadow of this type");
  18856. break;
  18857. }
  18858. }
  18859. render(context, scene, lightType) {
  18860. switch (lightType) {
  18861. case exports.ShadowLightType.DirectionLight:
  18862. var shaderValues = scene._shaderValues;
  18863. context.pipelineMode = "ShadowCaster";
  18864. ShaderData.setRuntimeValueMode(false);
  18865. var shadowMap = this._shadowDirectLightMap = ShadowUtils.getTemporaryShadowTexture(this._shadowMapWidth, this._shadowMapHeight, Laya.RenderTextureDepthFormat.DEPTH_16);
  18866. shadowMap._start();
  18867. var light = this._light;
  18868. for (var i = 0, n = this._cascadeCount; i < n; i++) {
  18869. var sliceData = this._shadowSliceDatas[i];
  18870. ShadowUtils.getShadowBias(light, sliceData.projectionMatrix, sliceData.resolution, this._shadowBias);
  18871. this._setupShadowCasterShaderValues(context, shaderValues, sliceData, this._lightForward, this._shadowParams, this._shadowBias, exports.LightType.Directional);
  18872. var shadowCullInfo = FrustumCulling._shadowCullInfo;
  18873. shadowCullInfo.position = sliceData.position;
  18874. shadowCullInfo.cullPlanes = sliceData.cullPlanes;
  18875. shadowCullInfo.cullPlaneCount = sliceData.cullPlaneCount;
  18876. shadowCullInfo.cullSphere = sliceData.splitBoundSphere;
  18877. shadowCullInfo.direction = this._lightForward;
  18878. var needRender = FrustumCulling.cullingShadow(shadowCullInfo, scene, context);
  18879. context.cameraShaderValue = sliceData.cameraShaderValue;
  18880. Camera._updateMark++;
  18881. var gl = Laya.LayaGL.instance;
  18882. var resolution = sliceData.resolution;
  18883. var offsetX = sliceData.offsetX;
  18884. var offsetY = sliceData.offsetY;
  18885. gl.enable(gl.SCISSOR_TEST);
  18886. gl.viewport(offsetX, offsetY, resolution, resolution);
  18887. gl.scissor(offsetX, offsetY, resolution, resolution);
  18888. gl.clear(gl.DEPTH_BUFFER_BIT);
  18889. if (needRender) {
  18890. gl.scissor(offsetX + 1, offsetY + 1, resolution - 2, resolution - 2);
  18891. scene._opaqueQueue._render(context);
  18892. }
  18893. }
  18894. shadowMap._end();
  18895. this._setupShadowReceiverShaderValues(shaderValues);
  18896. ShaderData.setRuntimeValueMode(true);
  18897. context.pipelineMode = context.configPipeLineMode;
  18898. break;
  18899. case exports.ShadowLightType.SpotLight:
  18900. var shaderValues = scene._shaderValues;
  18901. context.pipelineMode = "ShadowCaster";
  18902. ShaderData.setRuntimeValueMode(false);
  18903. var spotlight = this._light;
  18904. var shadowMap = this._shadowSpotLightMap = ShadowUtils.getTemporaryShadowTexture(this._shadowMapWidth, this._shadowMapHeight, Laya.RenderTextureDepthFormat.DEPTH_16);
  18905. shadowMap._start();
  18906. var shadowSpotData = this._shadowSpotData;
  18907. ShadowUtils.getShadowBias(spotlight, shadowSpotData.projectionMatrix, shadowSpotData.resolution, this._shadowBias);
  18908. this._setupShadowCasterShaderValues(context, shaderValues, shadowSpotData, this._light.transform.position, this._shadowParams, this._shadowBias, exports.LightType.Spot);
  18909. var needRender = FrustumCulling.cullingSpotShadow(shadowSpotData.cameraCullInfo, scene, context);
  18910. context.cameraShaderValue = shadowSpotData.cameraShaderValue;
  18911. Camera._updateMark++;
  18912. var gl = Laya.LayaGL.instance;
  18913. gl.enable(gl.SCISSOR_TEST);
  18914. gl.viewport(shadowSpotData.offsetX, shadowSpotData.offsetY, shadowSpotData.resolution, shadowSpotData.resolution);
  18915. gl.scissor(shadowSpotData.offsetX, shadowSpotData.offsetY, shadowSpotData.resolution, shadowSpotData.resolution);
  18916. gl.clear(gl.DEPTH_BUFFER_BIT);
  18917. if (needRender) {
  18918. gl.scissor(shadowSpotData.offsetX, shadowSpotData.offsetY, shadowSpotData.resolution, shadowSpotData.resolution);
  18919. scene._opaqueQueue._render(context);
  18920. }
  18921. shadowMap._end();
  18922. this._setupSpotShadowReceiverShaderValues(shaderValues);
  18923. ShaderData.setRuntimeValueMode(true);
  18924. context.pipelineMode = context.configPipeLineMode;
  18925. break;
  18926. case exports.ShadowLightType.PointLight:
  18927. break;
  18928. default:
  18929. throw ("There is no shadow of this type");
  18930. break;
  18931. }
  18932. }
  18933. cleanUp() {
  18934. this._shadowDirectLightMap && RenderTexture.recoverToPool(this._shadowDirectLightMap);
  18935. this._shadowSpotLightMap && RenderTexture.recoverToPool(this._shadowSpotLightMap);
  18936. this._shadowDirectLightMap = null;
  18937. this._shadowSpotLightMap = null;
  18938. this._light = null;
  18939. }
  18940. }
  18941. ShadowCasterPass._tempVector30 = new Vector3();
  18942. ShadowCasterPass._tempMatrix0 = new Matrix4x4();
  18943. ShadowCasterPass.SHADOW_BIAS = Shader3D.propertyNameToID("u_ShadowBias");
  18944. ShadowCasterPass.SHADOW_LIGHT_DIRECTION = Shader3D.propertyNameToID("u_ShadowLightDirection");
  18945. ShadowCasterPass.SHADOW_SPLIT_SPHERES = Shader3D.propertyNameToID("u_ShadowSplitSpheres");
  18946. ShadowCasterPass.SHADOW_MATRICES = Shader3D.propertyNameToID("u_ShadowMatrices");
  18947. ShadowCasterPass.SHADOW_MAP_SIZE = Shader3D.propertyNameToID("u_ShadowMapSize");
  18948. ShadowCasterPass.SHADOW_MAP = Shader3D.propertyNameToID("u_ShadowMap");
  18949. ShadowCasterPass.SHADOW_PARAMS = Shader3D.propertyNameToID("u_ShadowParams");
  18950. ShadowCasterPass.SHADOW_SPOTMAP_SIZE = Shader3D.propertyNameToID("u_SpotShadowMapSize");
  18951. ShadowCasterPass.SHADOW_SPOTMAP = Shader3D.propertyNameToID("u_SpotShadowMap");
  18952. ShadowCasterPass.SHADOW_SPOTMATRICES = Shader3D.propertyNameToID("u_SpotViewProjectMatrix");
  18953. ShadowCasterPass._maxCascades = 4;
  18954. ShadowCasterPass._cascadesSplitDistance = new Array(ShadowCasterPass._maxCascades + 1);
  18955. ShadowCasterPass._frustumPlanes = new Array(new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3()), new Plane(new Vector3()));
  18956. class DynamicBatchManager {
  18957. constructor() {
  18958. this._batchRenderElementPool = [];
  18959. }
  18960. static _registerManager(manager) {
  18961. DynamicBatchManager._managers.push(manager);
  18962. }
  18963. _clear() {
  18964. this._batchRenderElementPoolIndex = 0;
  18965. }
  18966. _getBatchRenderElementFromPool() {
  18967. throw "StaticBatch:must override this function.";
  18968. }
  18969. dispose() {
  18970. }
  18971. }
  18972. DynamicBatchManager._managers = [];
  18973. class ReflectionProbeList extends SingletonList {
  18974. constructor() {
  18975. super();
  18976. }
  18977. add(singleElement) {
  18978. this._add(singleElement);
  18979. singleElement._setIndexInReflectionList(this.length++);
  18980. }
  18981. remove(singleElement) {
  18982. var index = singleElement._getIndexInReflectionList();
  18983. this.length--;
  18984. if (index !== this.length) {
  18985. var end = this.elements[this.length];
  18986. this.elements[index] = end;
  18987. end._setIndexInReflectionList(index);
  18988. }
  18989. singleElement._setIndexInReflectionList(-1);
  18990. }
  18991. }
  18992. class ReflectionProbeManager {
  18993. constructor() {
  18994. this._reflectionProbes = new ReflectionProbeList();
  18995. this._motionObjects = new SingletonList();
  18996. this._needUpdateAllRender = false;
  18997. this._sceneReflectionProbe = new ReflectionProbe();
  18998. this._sceneReflectionProbe.bounds = new Bounds(new Vector3(0, 0, 0), new Vector3(0, 0, 0));
  18999. this._sceneReflectionProbe.boxProjection = false;
  19000. this._sceneReflectionProbe._isScene = true;
  19001. }
  19002. set sceneReflectionProbe(value) {
  19003. this._sceneReflectionProbe.reflectionTexture = value;
  19004. }
  19005. set sceneReflectionCubeHDRParam(value) {
  19006. this._sceneReflectionProbe.reflectionHDRParams = value;
  19007. }
  19008. _updateMotionObjects(baseRender) {
  19009. if (this._reflectionProbes.length == 0) {
  19010. baseRender._probReflection = this._sceneReflectionProbe;
  19011. return;
  19012. }
  19013. var elements = this._reflectionProbes.elements;
  19014. var maxOverlap = 0;
  19015. var mainProbe;
  19016. var renderBounds = baseRender.bounds;
  19017. var overlop;
  19018. for (var i = 0, n = this._reflectionProbes.length; i < n; i++) {
  19019. var renflectProbe = elements[i];
  19020. if (!mainProbe) {
  19021. overlop = renderBounds.calculateBoundsintersection(renflectProbe.bounds);
  19022. if (overlop < maxOverlap)
  19023. continue;
  19024. }
  19025. else {
  19026. if (mainProbe.importance > renflectProbe.importance)
  19027. continue;
  19028. overlop = renderBounds.calculateBoundsintersection(renflectProbe.bounds);
  19029. if (overlop < maxOverlap && mainProbe.importance == renflectProbe.importance)
  19030. continue;
  19031. }
  19032. mainProbe = renflectProbe;
  19033. maxOverlap = overlop;
  19034. }
  19035. if (!mainProbe && this._sceneReflectionProbe)
  19036. mainProbe = this._sceneReflectionProbe;
  19037. baseRender._probReflection = mainProbe;
  19038. }
  19039. add(reflectionProbe) {
  19040. this._reflectionProbes.add(reflectionProbe);
  19041. this._needUpdateAllRender = true;
  19042. }
  19043. remove(reflectionProbe) {
  19044. this._reflectionProbes.remove(reflectionProbe);
  19045. this._needUpdateAllRender = true;
  19046. }
  19047. addMotionObject(renderObject) {
  19048. this._motionObjects.add(renderObject);
  19049. }
  19050. update() {
  19051. var elements = this._motionObjects.elements;
  19052. for (var i = 0, n = this._motionObjects.length; i < n; i++) {
  19053. this._updateMotionObjects(elements[i]);
  19054. }
  19055. this.clearMotionObjects();
  19056. }
  19057. updateAllRenderObjects(baseRenders) {
  19058. var elements = baseRenders.elements;
  19059. for (var i = 0, n = baseRenders.length; i < n; i++) {
  19060. this._updateMotionObjects(elements[i]);
  19061. }
  19062. this._needUpdateAllRender = false;
  19063. }
  19064. clearMotionObjects() {
  19065. this._motionObjects.length = 0;
  19066. }
  19067. destroy() {
  19068. }
  19069. }
  19070. (function (AmbientMode) {
  19071. AmbientMode[AmbientMode["SolidColor"] = 0] = "SolidColor";
  19072. AmbientMode[AmbientMode["SphericalHarmonics"] = 1] = "SphericalHarmonics";
  19073. })(exports.AmbientMode || (exports.AmbientMode = {}));
  19074. class Scene3D extends Laya.Sprite {
  19075. constructor() {
  19076. super();
  19077. this._lightCount = 0;
  19078. this._pointLights = new LightQueue();
  19079. this._spotLights = new LightQueue();
  19080. this._directionLights = new LightQueue();
  19081. this._alternateLights = new AlternateLightQueue();
  19082. this._lightmaps = [];
  19083. this._skyRenderer = new SkyRenderer();
  19084. this._input = new Input3D();
  19085. this._timer = Laya.ILaya.timer;
  19086. this._time = 0;
  19087. this._shCoefficients = new Array(7);
  19088. this._ambientMode = exports.AmbientMode.SolidColor;
  19089. this._ambientSphericalHarmonics = new SphericalHarmonicsL2();
  19090. this._ambientSphericalHarmonicsIntensity = 1.0;
  19091. this._reflectionDecodeFormat = Laya.TextureDecodeFormat.Normal;
  19092. this._reflectionIntensity = 1.0;
  19093. this._collsionTestList = [];
  19094. this._renders = new SimpleSingletonList();
  19095. this._opaqueQueue = new RenderQueue(false);
  19096. this._transparentQueue = new RenderQueue(true);
  19097. this._cameraPool = [];
  19098. this._animatorPool = new SimpleSingletonList();
  19099. this._scriptPool = new Array();
  19100. this._tempScriptPool = new Array();
  19101. this._needClearScriptPool = false;
  19102. this._reflectionCubeHDRParams = new Vector4();
  19103. this._reflectionProbeManager = new ReflectionProbeManager();
  19104. this.currentCreationLayer = Math.pow(2, 0);
  19105. this.enableLight = true;
  19106. this._key = new Laya.SubmitKey();
  19107. this._pickIdToSprite = new Object();
  19108. this._reflectionMode = 0;
  19109. if (!Config3D._config.isUseCannonPhysicsEngine && Physics3D._bullet)
  19110. this._physicsSimulation = new PhysicsSimulation(Scene3D.physicsSettings);
  19111. else if (Physics3D._cannon) {
  19112. this._cannonPhysicsSimulation = new Laya.CannonPhysicsSimulation(Scene3D.cannonPhysicsSettings);
  19113. }
  19114. this._shaderValues = new ShaderData(null);
  19115. this.enableFog = false;
  19116. this.fogStart = 300;
  19117. this.fogRange = 1000;
  19118. this.fogColor = new Vector3(0.7, 0.7, 0.7);
  19119. this.ambientColor = new Vector3(0.212, 0.227, 0.259);
  19120. this.reflectionIntensity = 1.0;
  19121. this.reflection = TextureCube.blackTexture;
  19122. for (var i = 0; i < 7; i++)
  19123. this._shCoefficients[i] = new Vector4();
  19124. this._reflectionProbeManager.sceneReflectionCubeHDRParam = this._reflectionCubeHDRParams;
  19125. this._scene = this;
  19126. this._input.__init__(Laya.Render.canvas, this);
  19127. if (Scene3D.octreeCulling)
  19128. this._octree = new BoundsOctree(Scene3D.octreeInitialSize, Scene3D.octreeInitialCenter, Scene3D.octreeMinNodeSize, Scene3D.octreeLooseness);
  19129. if (FrustumCulling.debugFrustumCulling) {
  19130. this._debugTool = new PixelLineSprite3D();
  19131. var lineMaterial = new PixelLineMaterial();
  19132. lineMaterial.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  19133. lineMaterial.alphaTest = false;
  19134. lineMaterial.depthWrite = false;
  19135. lineMaterial.cull = RenderState.CULL_BACK;
  19136. lineMaterial.blend = RenderState.BLEND_ENABLE_ALL;
  19137. lineMaterial.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  19138. lineMaterial.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  19139. lineMaterial.depthTest = RenderState.DEPTHTEST_LESS;
  19140. this._debugTool.pixelLineRenderer.sharedMaterial = lineMaterial;
  19141. }
  19142. }
  19143. static __init__() {
  19144. var con = Config3D._config;
  19145. var multiLighting = con._multiLighting;
  19146. if (multiLighting) {
  19147. const width = 4;
  19148. var maxLightCount = con.maxLightCount;
  19149. var clusterSlices = con.lightClusterCount;
  19150. Cluster.instance = new Cluster(clusterSlices.x, clusterSlices.y, clusterSlices.z, Math.min(con.maxLightCount, con._maxAreaLightCountPerClusterAverage));
  19151. Scene3D._lightTexture = Utils3D._createFloatTextureBuffer(width, maxLightCount);
  19152. Scene3D._lightTexture.lock = true;
  19153. Scene3D._lightPixles = new Float32Array(maxLightCount * width * 4);
  19154. }
  19155. Scene3DShaderDeclaration.SHADERDEFINE_FOG = Shader3D.getDefineByName("FOG");
  19156. Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT = Shader3D.getDefineByName("DIRECTIONLIGHT");
  19157. Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT = Shader3D.getDefineByName("POINTLIGHT");
  19158. Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT = Shader3D.getDefineByName("SPOTLIGHT");
  19159. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW = Shader3D.getDefineByName("SHADOW");
  19160. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_CASCADE = Shader3D.getDefineByName("SHADOW_CASCADE");
  19161. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SOFT_SHADOW_LOW = Shader3D.getDefineByName("SHADOW_SOFT_SHADOW_LOW");
  19162. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SOFT_SHADOW_HIGH = Shader3D.getDefineByName("SHADOW_SOFT_SHADOW_HIGH");
  19163. Scene3DShaderDeclaration.SHADERDEFINE_GI_AMBIENT_SH = Shader3D.getDefineByName("GI_AMBIENT_SH");
  19164. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT = Shader3D.getDefineByName("SHADOW_SPOT");
  19165. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT_SOFT_SHADOW_LOW = Shader3D.getDefineByName("SHADOW_SPOT_SOFT_SHADOW_LOW");
  19166. Scene3DShaderDeclaration.SHADERDEFINE_SHADOW_SPOT_SOFT_SHADOW_HIGH = Shader3D.getDefineByName("SHADOW_SPOT_SOFT_SHADOW_HIGH");
  19167. var config = Config3D._config;
  19168. var configShaderValue = Scene3D._configDefineValues;
  19169. (config._multiLighting) || (configShaderValue.add(Shader3D.SHADERDEFINE_LEGACYSINGALLIGHTING));
  19170. if (Laya.LayaGL.layaGPUInstance._isWebGL2)
  19171. configShaderValue.add(Shader3D.SHADERDEFINE_GRAPHICS_API_GLES3);
  19172. else
  19173. configShaderValue.add(Shader3D.SHADERDEFINE_GRAPHICS_API_GLES2);
  19174. switch (config.pbrRenderQuality) {
  19175. case exports.PBRRenderQuality.High:
  19176. configShaderValue.add(PBRMaterial.SHADERDEFINE_LAYA_PBR_BRDF_HIGH);
  19177. break;
  19178. case exports.PBRRenderQuality.Low:
  19179. configShaderValue.add(PBRMaterial.SHADERDEFINE_LAYA_PBR_BRDF_LOW);
  19180. break;
  19181. default:
  19182. throw "Scene3D:unknown shader quality.";
  19183. }
  19184. if (config.isUseCannonPhysicsEngine) {
  19185. Scene3D.cannonPhysicsSettings = new Laya.CannonPhysicsSettings();
  19186. }
  19187. else {
  19188. Scene3D.physicsSettings = new PhysicsSettings();
  19189. }
  19190. }
  19191. static load(url, complete) {
  19192. Laya.ILaya.loader.create(url, complete, null, Scene3D.HIERARCHY);
  19193. }
  19194. get url() {
  19195. return this._url;
  19196. }
  19197. get enableFog() {
  19198. return this._enableFog;
  19199. }
  19200. set enableFog(value) {
  19201. if (this._enableFog !== value) {
  19202. this._enableFog = value;
  19203. if (value) {
  19204. this._shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_FOG);
  19205. }
  19206. else
  19207. this._shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_FOG);
  19208. }
  19209. }
  19210. get fogColor() {
  19211. return this._shaderValues.getVector3(Scene3D.FOGCOLOR);
  19212. }
  19213. set fogColor(value) {
  19214. this._shaderValues.setVector3(Scene3D.FOGCOLOR, value);
  19215. }
  19216. get fogStart() {
  19217. return this._shaderValues.getNumber(Scene3D.FOGSTART);
  19218. }
  19219. set fogStart(value) {
  19220. this._shaderValues.setNumber(Scene3D.FOGSTART, value);
  19221. }
  19222. get fogRange() {
  19223. return this._shaderValues.getNumber(Scene3D.FOGRANGE);
  19224. }
  19225. set fogRange(value) {
  19226. this._shaderValues.setNumber(Scene3D.FOGRANGE, value);
  19227. }
  19228. get ambientMode() {
  19229. return this._ambientMode;
  19230. }
  19231. set ambientMode(value) {
  19232. if (this._ambientMode !== value) {
  19233. switch (value) {
  19234. case exports.AmbientMode.SolidColor:
  19235. this._shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_GI_AMBIENT_SH);
  19236. break;
  19237. case exports.AmbientMode.SphericalHarmonics:
  19238. this._shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_GI_AMBIENT_SH);
  19239. break;
  19240. default:
  19241. throw "Scene3D: unknown ambientMode.";
  19242. }
  19243. this._ambientMode = value;
  19244. }
  19245. }
  19246. get ambientColor() {
  19247. return this._shaderValues.getVector3(Scene3D.AMBIENTCOLOR);
  19248. }
  19249. set ambientColor(value) {
  19250. this._shaderValues.setVector3(Scene3D.AMBIENTCOLOR, value);
  19251. }
  19252. get ambientSphericalHarmonics() {
  19253. return this._ambientSphericalHarmonics;
  19254. }
  19255. set ambientSphericalHarmonics(value) {
  19256. var originalSH = value || SphericalHarmonicsL2._default;
  19257. this._applySHCoefficients(originalSH, Math.pow(this._ambientSphericalHarmonicsIntensity, 2.2));
  19258. if (this._ambientSphericalHarmonics != value)
  19259. value.cloneTo(this._ambientSphericalHarmonics);
  19260. }
  19261. get ambientSphericalHarmonicsIntensity() {
  19262. return this._ambientSphericalHarmonicsIntensity;
  19263. }
  19264. set ambientSphericalHarmonicsIntensity(value) {
  19265. value = Math.max(Math.min(value, 8.0), 0.0);
  19266. if (this._ambientSphericalHarmonicsIntensity !== value) {
  19267. var originalSH = this._ambientSphericalHarmonics || SphericalHarmonicsL2._default;
  19268. this._applySHCoefficients(originalSH, Math.pow(value, 2.2));
  19269. this._ambientSphericalHarmonicsIntensity = value;
  19270. }
  19271. }
  19272. get reflection() {
  19273. return this._reflection;
  19274. }
  19275. set reflection(value) {
  19276. value = value ? value : TextureCube.blackTexture;
  19277. if (this._reflection != value) {
  19278. value._addReference();
  19279. this._reflectionProbeManager.sceneReflectionProbe = value;
  19280. this._reflection = value;
  19281. this._reflectionProbeManager._needUpdateAllRender = true;
  19282. }
  19283. }
  19284. get reflectionDecodingFormat() {
  19285. return this._reflectionDecodeFormat;
  19286. }
  19287. set reflectionDecodingFormat(value) {
  19288. if (this._reflectionDecodeFormat != value) {
  19289. this._reflectionCubeHDRParams.x = this._reflectionIntensity;
  19290. if (this._reflectionDecodeFormat == Laya.TextureDecodeFormat.RGBM)
  19291. this._reflectionCubeHDRParams.x *= 5.0;
  19292. this._reflectionDecodeFormat = value;
  19293. this._reflectionProbeManager.sceneReflectionCubeHDRParam = this._reflectionCubeHDRParams;
  19294. }
  19295. }
  19296. get reflectionIntensity() {
  19297. return this._reflectionIntensity;
  19298. }
  19299. set reflectionIntensity(value) {
  19300. value = Math.max(Math.min(value, 1.0), 0.0);
  19301. this._reflectionCubeHDRParams.x = value;
  19302. if (this._reflectionDecodeFormat == Laya.TextureDecodeFormat.RGBM)
  19303. this._reflectionCubeHDRParams.x *= 5.0;
  19304. this._reflectionIntensity = value;
  19305. this._reflectionProbeManager.sceneReflectionCubeHDRParam = this._reflectionCubeHDRParams;
  19306. }
  19307. get skyRenderer() {
  19308. return this._skyRenderer;
  19309. }
  19310. get physicsSimulation() {
  19311. return this._physicsSimulation;
  19312. }
  19313. get cannonPhysicsSimulation() {
  19314. return this._cannonPhysicsSimulation;
  19315. }
  19316. get timer() {
  19317. return this._timer;
  19318. }
  19319. set timer(value) {
  19320. this._timer = value;
  19321. }
  19322. get input() {
  19323. return this._input;
  19324. }
  19325. get lightmaps() {
  19326. return this._lightmaps.slice();
  19327. }
  19328. set lightmaps(value) {
  19329. var maps = this._lightmaps;
  19330. if (maps) {
  19331. for (var i = 0, n = maps.length; i < n; i++) {
  19332. var map = maps[i];
  19333. map.lightmapColor._removeReference();
  19334. map.lightmapDirection._removeReference();
  19335. }
  19336. }
  19337. if (value) {
  19338. var count = value.length;
  19339. maps.length = count;
  19340. for (i = 0; i < count; i++) {
  19341. var map = value[i];
  19342. map.lightmapColor && map.lightmapColor._addReference();
  19343. map.lightmapDirection && map.lightmapDirection._addReference();
  19344. maps[i] = map;
  19345. }
  19346. }
  19347. else {
  19348. maps.length = 0;
  19349. }
  19350. }
  19351. _applySHCoefficients(originalSH, intensity) {
  19352. var optSH = this._shCoefficients;
  19353. for (var i = 0; i < 3; i++) {
  19354. var shaderSHA = optSH[i];
  19355. var shaderSHB = optSH[i + 3];
  19356. shaderSHA.setValue(originalSH.getCoefficient(i, 3) * intensity, originalSH.getCoefficient(i, 1) * intensity, originalSH.getCoefficient(i, 2) * intensity, (originalSH.getCoefficient(i, 0) - originalSH.getCoefficient(i, 6)) * intensity);
  19357. shaderSHB.setValue(originalSH.getCoefficient(i, 4) * intensity, originalSH.getCoefficient(i, 5) * intensity, originalSH.getCoefficient(i, 6) * 3 * intensity, originalSH.getCoefficient(i, 7) * intensity);
  19358. }
  19359. optSH[6].setValue(originalSH.getCoefficient(0, 8) * intensity, originalSH.getCoefficient(1, 8) * intensity, originalSH.getCoefficient(2, 8) * intensity, 1);
  19360. var shaderValues = this._shaderValues;
  19361. shaderValues.setVector(Scene3D.AMBIENTSHAR, optSH[0]);
  19362. shaderValues.setVector(Scene3D.AMBIENTSHAG, optSH[1]);
  19363. shaderValues.setVector(Scene3D.AMBIENTSHAB, optSH[2]);
  19364. shaderValues.setVector(Scene3D.AMBIENTSHBR, optSH[3]);
  19365. shaderValues.setVector(Scene3D.AMBIENTSHBG, optSH[4]);
  19366. shaderValues.setVector(Scene3D.AMBIENTSHBB, optSH[5]);
  19367. shaderValues.setVector(Scene3D.AMBIENTSHC, optSH[6]);
  19368. }
  19369. _update() {
  19370. var delta = this.timer._delta / 1000;
  19371. this._time += delta;
  19372. this._shaderValues.setNumber(Scene3D.TIME, this._time);
  19373. var simulation = this._physicsSimulation;
  19374. if (Physics3D._enablePhysics && !PhysicsSimulation.disableSimulation && !Config3D._config.isUseCannonPhysicsEngine) {
  19375. simulation._updatePhysicsTransformFromRender();
  19376. PhysicsComponent._addUpdateList = false;
  19377. simulation._simulate(delta);
  19378. simulation._updateCharacters();
  19379. PhysicsComponent._addUpdateList = true;
  19380. simulation._updateCollisions();
  19381. simulation._eventScripts();
  19382. }
  19383. if (Physics3D._cannon && Config3D._config.isUseCannonPhysicsEngine) {
  19384. var cannonSimulation = this._cannonPhysicsSimulation;
  19385. cannonSimulation._updatePhysicsTransformFromRender();
  19386. Laya.CannonPhysicsComponent._addUpdateList = false;
  19387. cannonSimulation._simulate(delta);
  19388. Laya.CannonPhysicsComponent._addUpdateList = true;
  19389. cannonSimulation._updateCollisions();
  19390. cannonSimulation._eventScripts();
  19391. }
  19392. this._input._update();
  19393. this._clearScript();
  19394. this._updateScript();
  19395. Animator._update(this);
  19396. Laya.VideoTexture._update();
  19397. if (this._reflectionProbeManager._needUpdateAllRender)
  19398. this._reflectionProbeManager.updateAllRenderObjects(this._renders);
  19399. else
  19400. this._reflectionProbeManager.update();
  19401. this._lateUpdateScript();
  19402. }
  19403. _binarySearchIndexInCameraPool(camera) {
  19404. var start = 0;
  19405. var end = this._cameraPool.length - 1;
  19406. var mid;
  19407. while (start <= end) {
  19408. mid = Math.floor((start + end) / 2);
  19409. var midValue = this._cameraPool[mid]._renderingOrder;
  19410. if (midValue == camera._renderingOrder)
  19411. return mid;
  19412. else if (midValue > camera._renderingOrder)
  19413. end = mid - 1;
  19414. else
  19415. start = mid + 1;
  19416. }
  19417. return start;
  19418. }
  19419. _allotPickColorByID(id, pickColor) {
  19420. var pickColorR = Math.floor(id / (255 * 255));
  19421. id -= pickColorR * 255 * 255;
  19422. var pickColorG = Math.floor(id / 255);
  19423. id -= pickColorG * 255;
  19424. var pickColorB = id;
  19425. pickColor.x = pickColorR / 255;
  19426. pickColor.y = pickColorG / 255;
  19427. pickColor.z = pickColorB / 255;
  19428. pickColor.w = 1.0;
  19429. }
  19430. _searchIDByPickColor(pickColor) {
  19431. var id = pickColor.x * 255 * 255 + pickColor.y * 255 + pickColor.z;
  19432. return id;
  19433. }
  19434. onEnable() {
  19435. this._input._onCanvasEvent(Laya.Render.canvas);
  19436. }
  19437. onDisable() {
  19438. this._input._offCanvasEvent(Laya.Render.canvas);
  19439. }
  19440. _setCreateURL(url) {
  19441. this._url = Laya.URL.formatURL(url);
  19442. }
  19443. _getGroup() {
  19444. return this._group;
  19445. }
  19446. _setGroup(value) {
  19447. this._group = value;
  19448. }
  19449. _clearScript() {
  19450. if (this._needClearScriptPool) {
  19451. var scripts = this._scriptPool;
  19452. for (var i = 0, n = scripts.length; i < n; i++) {
  19453. var script = scripts[i];
  19454. if (script) {
  19455. script._indexInPool = this._tempScriptPool.length;
  19456. this._tempScriptPool.push(script);
  19457. }
  19458. }
  19459. this._scriptPool = this._tempScriptPool;
  19460. scripts.length = 0;
  19461. this._tempScriptPool = scripts;
  19462. this._needClearScriptPool = false;
  19463. }
  19464. }
  19465. _updateScript() {
  19466. var scripts = this._scriptPool;
  19467. for (var i = 0, n = scripts.length; i < n; i++) {
  19468. var script = scripts[i];
  19469. (script && script.enabled) && (script.onUpdate());
  19470. }
  19471. }
  19472. _lateUpdateScript() {
  19473. var scripts = this._scriptPool;
  19474. for (var i = 0, n = scripts.length; i < n; i++) {
  19475. var script = scripts[i];
  19476. (script && script.enabled) && (script.onLateUpdate());
  19477. }
  19478. }
  19479. _onActive() {
  19480. super._onActive();
  19481. Laya.ILaya.stage._scene3Ds.push(this);
  19482. }
  19483. _onInActive() {
  19484. super._onInActive();
  19485. var scenes = Laya.ILaya.stage._scene3Ds;
  19486. scenes.splice(scenes.indexOf(this), 1);
  19487. }
  19488. _prepareSceneToRender() {
  19489. var shaderValues = this._shaderValues;
  19490. var multiLighting = Config3D._config._multiLighting;
  19491. if (multiLighting) {
  19492. var ligTex = Scene3D._lightTexture;
  19493. var ligPix = Scene3D._lightPixles;
  19494. const pixelWidth = ligTex.width;
  19495. const floatWidth = pixelWidth * 4;
  19496. var curCount = 0;
  19497. var dirCount = this._directionLights._length;
  19498. var dirElements = this._directionLights._elements;
  19499. if (dirCount > 0) {
  19500. var sunLightIndex = this._directionLights.getBrightestLight();
  19501. this._mainDirectionLight = dirElements[sunLightIndex];
  19502. this._directionLights.normalLightOrdering(sunLightIndex);
  19503. for (var i = 0; i < dirCount; i++, curCount++) {
  19504. var dirLight = dirElements[i];
  19505. var dir = dirLight._direction;
  19506. var intCor = dirLight._intensityColor;
  19507. var off = floatWidth * curCount;
  19508. Vector3.scale(dirLight.color, dirLight._intensity, intCor);
  19509. dirLight.transform.worldMatrix.getForward(dir);
  19510. Vector3.normalize(dir, dir);
  19511. ligPix[off] = intCor.x;
  19512. ligPix[off + 1] = intCor.y;
  19513. ligPix[off + 2] = intCor.z;
  19514. ligPix[off + 4] = dir.x;
  19515. ligPix[off + 5] = dir.y;
  19516. ligPix[off + 6] = dir.z;
  19517. if (i == 0) {
  19518. shaderValues.setVector3(Scene3D.SUNLIGHTDIRCOLOR, intCor);
  19519. shaderValues.setVector3(Scene3D.SUNLIGHTDIRECTION, dir);
  19520. }
  19521. }
  19522. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  19523. }
  19524. else {
  19525. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  19526. }
  19527. var poiCount = this._pointLights._length;
  19528. if (poiCount > 0) {
  19529. var poiElements = this._pointLights._elements;
  19530. var mainPointLightIndex = this._pointLights.getBrightestLight();
  19531. this._mainPointLight = poiElements[mainPointLightIndex];
  19532. this._pointLights.normalLightOrdering(mainPointLightIndex);
  19533. for (var i = 0; i < poiCount; i++, curCount++) {
  19534. var poiLight = poiElements[i];
  19535. var pos = poiLight.transform.position;
  19536. var intCor = poiLight._intensityColor;
  19537. var off = floatWidth * curCount;
  19538. Vector3.scale(poiLight.color, poiLight._intensity, intCor);
  19539. ligPix[off] = intCor.x;
  19540. ligPix[off + 1] = intCor.y;
  19541. ligPix[off + 2] = intCor.z;
  19542. ligPix[off + 3] = poiLight.range;
  19543. ligPix[off + 4] = pos.x;
  19544. ligPix[off + 5] = pos.y;
  19545. ligPix[off + 6] = pos.z;
  19546. }
  19547. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  19548. }
  19549. else {
  19550. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  19551. }
  19552. var spoCount = this._spotLights._length;
  19553. if (spoCount > 0) {
  19554. var spoElements = this._spotLights._elements;
  19555. var mainSpotLightIndex = this._spotLights.getBrightestLight();
  19556. this._mainSpotLight = spoElements[mainSpotLightIndex];
  19557. this._spotLights.normalLightOrdering(mainSpotLightIndex);
  19558. for (var i = 0; i < spoCount; i++, curCount++) {
  19559. var spoLight = spoElements[i];
  19560. var dir = spoLight._direction;
  19561. var pos = spoLight.transform.position;
  19562. var intCor = spoLight._intensityColor;
  19563. var off = floatWidth * curCount;
  19564. Vector3.scale(spoLight.color, spoLight._intensity, intCor);
  19565. spoLight.transform.worldMatrix.getForward(dir);
  19566. Vector3.normalize(dir, dir);
  19567. ligPix[off] = intCor.x;
  19568. ligPix[off + 1] = intCor.y;
  19569. ligPix[off + 2] = intCor.z;
  19570. ligPix[off + 3] = spoLight.range;
  19571. ligPix[off + 4] = pos.x;
  19572. ligPix[off + 5] = pos.y;
  19573. ligPix[off + 6] = pos.z;
  19574. ligPix[off + 7] = spoLight.spotAngle * Math.PI / 180;
  19575. ligPix[off + 8] = dir.x;
  19576. ligPix[off + 9] = dir.y;
  19577. ligPix[off + 10] = dir.z;
  19578. }
  19579. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  19580. }
  19581. else {
  19582. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  19583. }
  19584. (curCount > 0) && (ligTex.setSubPixels(0, 0, pixelWidth, curCount, ligPix, 0));
  19585. shaderValues.setTexture(Scene3D.LIGHTBUFFER, ligTex);
  19586. shaderValues.setInt(Scene3D.DIRECTIONLIGHTCOUNT, this._directionLights._length);
  19587. shaderValues.setTexture(Scene3D.CLUSTERBUFFER, Cluster.instance._clusterTexture);
  19588. }
  19589. else {
  19590. if (this._directionLights._length > 0) {
  19591. var dirLight = this._directionLights._elements[0];
  19592. this._mainDirectionLight = dirLight;
  19593. Vector3.scale(dirLight.color, dirLight._intensity, dirLight._intensityColor);
  19594. dirLight.transform.worldMatrix.getForward(dirLight._direction);
  19595. Vector3.normalize(dirLight._direction, dirLight._direction);
  19596. shaderValues.setVector3(Scene3D.LIGHTDIRCOLOR, dirLight._intensityColor);
  19597. shaderValues.setVector3(Scene3D.LIGHTDIRECTION, dirLight._direction);
  19598. shaderValues.setVector3(Scene3D.SUNLIGHTDIRCOLOR, dirLight._intensityColor);
  19599. shaderValues.setVector3(Scene3D.SUNLIGHTDIRECTION, dirLight._direction);
  19600. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  19601. }
  19602. else {
  19603. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_DIRECTIONLIGHT);
  19604. }
  19605. if (this._pointLights._length > 0) {
  19606. var poiLight = this._pointLights._elements[0];
  19607. this._mainPointLight = poiLight;
  19608. Vector3.scale(poiLight.color, poiLight._intensity, poiLight._intensityColor);
  19609. shaderValues.setVector3(Scene3D.POINTLIGHTCOLOR, poiLight._intensityColor);
  19610. shaderValues.setVector3(Scene3D.POINTLIGHTPOS, poiLight.transform.position);
  19611. shaderValues.setNumber(Scene3D.POINTLIGHTRANGE, poiLight.range);
  19612. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  19613. }
  19614. else {
  19615. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_POINTLIGHT);
  19616. }
  19617. if (this._spotLights._length > 0) {
  19618. var spotLight = this._spotLights._elements[0];
  19619. this._mainSpotLight = spotLight;
  19620. Vector3.scale(spotLight.color, spotLight._intensity, spotLight._intensityColor);
  19621. shaderValues.setVector3(Scene3D.SPOTLIGHTCOLOR, spotLight._intensityColor);
  19622. shaderValues.setVector3(Scene3D.SPOTLIGHTPOS, spotLight.transform.position);
  19623. spotLight.transform.worldMatrix.getForward(spotLight._direction);
  19624. Vector3.normalize(spotLight._direction, spotLight._direction);
  19625. shaderValues.setVector3(Scene3D.SPOTLIGHTDIRECTION, spotLight._direction);
  19626. shaderValues.setNumber(Scene3D.SPOTLIGHTRANGE, spotLight.range);
  19627. shaderValues.setNumber(Scene3D.SPOTLIGHTSPOTANGLE, spotLight.spotAngle * Math.PI / 180);
  19628. shaderValues.addDefine(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  19629. }
  19630. else {
  19631. shaderValues.removeDefine(Scene3DShaderDeclaration.SHADERDEFINE_SPOTLIGHT);
  19632. }
  19633. }
  19634. }
  19635. _addScript(script) {
  19636. var scripts = this._scriptPool;
  19637. script._indexInPool = scripts.length;
  19638. scripts.push(script);
  19639. }
  19640. _removeScript(script) {
  19641. this._scriptPool[script._indexInPool] = null;
  19642. script._indexInPool = -1;
  19643. this._needClearScriptPool = true;
  19644. }
  19645. _preRenderScript() {
  19646. var scripts = this._scriptPool;
  19647. for (var i = 0, n = scripts.length; i < n; i++) {
  19648. var script = scripts[i];
  19649. (script && script.enabled) && (script.onPreRender());
  19650. }
  19651. }
  19652. _postRenderScript() {
  19653. var scripts = this._scriptPool;
  19654. for (var i = 0, n = scripts.length; i < n; i++) {
  19655. var script = scripts[i];
  19656. (script && script.enabled) && (script.onPostRender());
  19657. }
  19658. }
  19659. _addCamera(camera) {
  19660. var index = this._binarySearchIndexInCameraPool(camera);
  19661. var order = camera._renderingOrder;
  19662. var count = this._cameraPool.length;
  19663. while (index < count && this._cameraPool[index]._renderingOrder <= order)
  19664. index++;
  19665. this._cameraPool.splice(index, 0, camera);
  19666. }
  19667. _removeCamera(camera) {
  19668. this._cameraPool.splice(this._cameraPool.indexOf(camera), 1);
  19669. }
  19670. _preCulling(context, camera, shader, replacementTag) {
  19671. var cameraCullInfo = FrustumCulling._cameraCullInfo;
  19672. cameraCullInfo.position = camera._transform.position;
  19673. cameraCullInfo.cullingMask = camera.cullingMask;
  19674. cameraCullInfo.boundFrustum = camera.boundFrustum;
  19675. cameraCullInfo.useOcclusionCulling = camera.useOcclusionCulling;
  19676. FrustumCulling.renderObjectCulling(cameraCullInfo, this, context, shader, replacementTag, false);
  19677. }
  19678. _clear(gl, state) {
  19679. var viewport = state.viewport;
  19680. var camera = state.camera;
  19681. var renderTex = camera._getRenderTexture();
  19682. var vpX, vpY;
  19683. var vpW = viewport.width;
  19684. var vpH = viewport.height;
  19685. if (camera._needInternalRenderTexture()) {
  19686. vpX = 0;
  19687. vpY = 0;
  19688. }
  19689. else {
  19690. vpX = viewport.x;
  19691. vpY = camera._getCanvasHeight() - viewport.y - vpH;
  19692. }
  19693. gl.viewport(vpX, vpY, vpW, vpH);
  19694. var flag;
  19695. var clearFlag = camera.clearFlag;
  19696. if (clearFlag === exports.CameraClearFlags.Sky && !(camera.skyRenderer._isAvailable() || this._skyRenderer._isAvailable()))
  19697. clearFlag = exports.CameraClearFlags.SolidColor;
  19698. switch (clearFlag) {
  19699. case exports.CameraClearFlags.SolidColor:
  19700. var clearColor = camera.clearColor;
  19701. gl.enable(gl.SCISSOR_TEST);
  19702. gl.scissor(vpX, vpY, vpW, vpH);
  19703. if (clearColor)
  19704. gl.clearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w);
  19705. else
  19706. gl.clearColor(0, 0, 0, 0);
  19707. if (renderTex) {
  19708. flag = gl.COLOR_BUFFER_BIT;
  19709. switch (renderTex.depthStencilFormat) {
  19710. case Laya.RenderTextureDepthFormat.DEPTH_16:
  19711. flag |= gl.DEPTH_BUFFER_BIT;
  19712. break;
  19713. case Laya.RenderTextureDepthFormat.STENCIL_8:
  19714. flag |= gl.STENCIL_BUFFER_BIT;
  19715. break;
  19716. case Laya.RenderTextureDepthFormat.DEPTHSTENCIL_24_8:
  19717. flag |= gl.DEPTH_BUFFER_BIT;
  19718. flag |= gl.STENCIL_BUFFER_BIT;
  19719. break;
  19720. }
  19721. }
  19722. else {
  19723. flag = gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT;
  19724. }
  19725. Laya.WebGLContext.setDepthMask(gl, true);
  19726. gl.clear(flag);
  19727. gl.disable(gl.SCISSOR_TEST);
  19728. break;
  19729. case exports.CameraClearFlags.Sky:
  19730. case exports.CameraClearFlags.DepthOnly:
  19731. gl.enable(gl.SCISSOR_TEST);
  19732. gl.scissor(vpX, vpY, vpW, vpH);
  19733. if (renderTex) {
  19734. switch (renderTex.depthStencilFormat) {
  19735. case Laya.RenderTextureDepthFormat.DEPTH_16:
  19736. flag = gl.DEPTH_BUFFER_BIT;
  19737. break;
  19738. case Laya.RenderTextureDepthFormat.STENCIL_8:
  19739. flag = gl.STENCIL_BUFFER_BIT;
  19740. break;
  19741. case Laya.RenderTextureDepthFormat.DEPTHSTENCIL_24_8:
  19742. flag = gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT;
  19743. break;
  19744. }
  19745. }
  19746. else {
  19747. flag = gl.DEPTH_BUFFER_BIT;
  19748. }
  19749. Laya.WebGLContext.setDepthMask(gl, true);
  19750. gl.clear(flag);
  19751. gl.disable(gl.SCISSOR_TEST);
  19752. break;
  19753. case exports.CameraClearFlags.Nothing:
  19754. break;
  19755. default:
  19756. throw new Error("Scene3D:camera clearFlag invalid.");
  19757. }
  19758. }
  19759. _renderScene(context, renderFlag) {
  19760. var camera = context.camera;
  19761. switch (renderFlag) {
  19762. case Scene3D.SCENERENDERFLAG_RENDERQPAQUE:
  19763. this._opaqueQueue._render(context);
  19764. break;
  19765. case Scene3D.SCENERENDERFLAG_SKYBOX:
  19766. if (camera.clearFlag === exports.CameraClearFlags.Sky) {
  19767. if (camera.skyRenderer._isAvailable())
  19768. camera.skyRenderer._render(context);
  19769. else if (this._skyRenderer._isAvailable())
  19770. this._skyRenderer._render(context);
  19771. }
  19772. break;
  19773. case Scene3D.SCENERENDERFLAG_RENDERTRANSPARENT:
  19774. this._transparentQueue._render(context);
  19775. if (FrustumCulling.debugFrustumCulling) {
  19776. var renderElements = this._debugTool._render._renderElements;
  19777. for (var i = 0, n = renderElements.length; i < n; i++) {
  19778. renderElements[i]._update(this, context, null, null);
  19779. renderElements[i]._render(context);
  19780. }
  19781. }
  19782. break;
  19783. }
  19784. }
  19785. _parse(data, spriteMap) {
  19786. var lightMapsData = data.lightmaps;
  19787. if (lightMapsData) {
  19788. var lightMapCount = lightMapsData.length;
  19789. var lightmaps = new Array(lightMapCount);
  19790. for (var i = 0; i < lightMapCount; i++) {
  19791. var lightMap = new Lightmap();
  19792. var lightMapData = lightMapsData[i];
  19793. if (lightMapData.path) {
  19794. lightMap.lightmapColor = Laya.Loader.getRes(lightMapData.path);
  19795. }
  19796. else {
  19797. lightMap.lightmapColor = Laya.Loader.getRes(lightMapData.color.path);
  19798. if (lightMapData.direction)
  19799. lightMap.lightmapDirection = Laya.Loader.getRes(lightMapData.direction.path);
  19800. }
  19801. lightmaps[i] = lightMap;
  19802. }
  19803. this.lightmaps = lightmaps;
  19804. }
  19805. var ambientColorData = data.ambientColor;
  19806. if (ambientColorData) {
  19807. var ambCol = this.ambientColor;
  19808. ambCol.fromArray(ambientColorData);
  19809. this.ambientColor = ambCol;
  19810. }
  19811. var skyData = data.sky;
  19812. if (skyData) {
  19813. this._skyRenderer.material = Laya.Loader.getRes(skyData.material.path);
  19814. switch (skyData.mesh) {
  19815. case "SkyBox":
  19816. this._skyRenderer.mesh = SkyBox.instance;
  19817. break;
  19818. case "SkyDome":
  19819. this._skyRenderer.mesh = SkyDome.instance;
  19820. break;
  19821. default:
  19822. this.skyRenderer.mesh = SkyBox.instance;
  19823. }
  19824. }
  19825. this.enableFog = data.enableFog;
  19826. this.fogStart = data.fogStart;
  19827. this.fogRange = data.fogRange;
  19828. var fogColorData = data.fogColor;
  19829. if (fogColorData) {
  19830. var fogCol = this.fogColor;
  19831. fogCol.fromArray(fogColorData);
  19832. this.fogColor = fogCol;
  19833. }
  19834. var ambientSphericalHarmonicsData = data.ambientSphericalHarmonics;
  19835. if (ambientSphericalHarmonicsData) {
  19836. var ambientSH = this.ambientSphericalHarmonics;
  19837. for (var i = 0; i < 3; i++) {
  19838. var off = i * 9;
  19839. ambientSH.setCoefficients(i, ambientSphericalHarmonicsData[off], ambientSphericalHarmonicsData[off + 1], ambientSphericalHarmonicsData[off + 2], ambientSphericalHarmonicsData[off + 3], ambientSphericalHarmonicsData[off + 4], ambientSphericalHarmonicsData[off + 5], ambientSphericalHarmonicsData[off + 6], ambientSphericalHarmonicsData[off + 7], ambientSphericalHarmonicsData[off + 8]);
  19840. }
  19841. this.ambientSphericalHarmonics = ambientSH;
  19842. }
  19843. var reflectionData = data.reflection;
  19844. (reflectionData != undefined) && (this.reflection = Laya.Loader.getRes(reflectionData));
  19845. var reflectionDecodingFormatData = data.reflectionDecodingFormat;
  19846. (reflectionDecodingFormatData != undefined) && (this.reflectionDecodingFormat = reflectionDecodingFormatData);
  19847. var ambientModeData = data.ambientMode;
  19848. (ambientModeData != undefined) && (this.ambientMode = ambientModeData);
  19849. var ambientSphericalHarmonicsIntensityData = data.ambientSphericalHarmonicsIntensity;
  19850. (ambientSphericalHarmonicsIntensityData != undefined) && (this.ambientSphericalHarmonicsIntensity = ambientSphericalHarmonicsIntensityData);
  19851. var reflectionIntensityData = data.reflectionIntensity;
  19852. (reflectionIntensityData != undefined) && (this.reflectionIntensity = reflectionIntensityData);
  19853. }
  19854. _addRenderObject(render) {
  19855. if (this._octree && render._supportOctree) {
  19856. this._octree.add(render);
  19857. }
  19858. else {
  19859. this._renders.add(render);
  19860. }
  19861. render._addReflectionProbeUpdate();
  19862. }
  19863. _removeRenderObject(render) {
  19864. if (this._octree && render._supportOctree) {
  19865. this._octree.remove(render);
  19866. }
  19867. else {
  19868. this._renders.remove(render);
  19869. }
  19870. }
  19871. _getRenderQueue(index) {
  19872. if (index <= 2500)
  19873. return this._opaqueQueue;
  19874. else
  19875. return this._transparentQueue;
  19876. }
  19877. _clearRenderQueue() {
  19878. this._opaqueQueue.clear();
  19879. this._transparentQueue.clear();
  19880. var staticBatchManagers = StaticBatchManager._managers;
  19881. for (var i = 0, n = staticBatchManagers.length; i < n; i++)
  19882. staticBatchManagers[i]._clear();
  19883. var dynamicBatchManagers = DynamicBatchManager._managers;
  19884. for (var i = 0, n = dynamicBatchManagers.length; i < n; i++)
  19885. dynamicBatchManagers[i]._clear();
  19886. }
  19887. destroy(destroyChild = true) {
  19888. if (this.destroyed)
  19889. return;
  19890. super.destroy(destroyChild);
  19891. this._skyRenderer.destroy();
  19892. this._skyRenderer = null;
  19893. this._directionLights = null;
  19894. this._pointLights = null;
  19895. this._spotLights = null;
  19896. this._alternateLights = null;
  19897. this._shaderValues = null;
  19898. this._renders = null;
  19899. this._cameraPool = null;
  19900. this._octree = null;
  19901. this._physicsSimulation && this._physicsSimulation._destroy();
  19902. this._reflection._removeReference();
  19903. this._reflection = null;
  19904. var maps = this._lightmaps;
  19905. if (maps) {
  19906. for (var i = 0, n = maps.length; i < n; i++) {
  19907. var map = maps[i];
  19908. map.lightmapColor && map.lightmapColor._removeReference();
  19909. map.lightmapDirection && map.lightmapDirection._removeReference();
  19910. }
  19911. }
  19912. this._lightmaps = null;
  19913. this._reflectionProbeManager.destroy();
  19914. Laya.Loader.clearRes(this.url);
  19915. }
  19916. render(ctx, x, y) {
  19917. ctx._curSubmit = Laya.SubmitBase.RENDERBASE;
  19918. this._children.length > 0 && ctx.addRenderObject(this);
  19919. }
  19920. renderSubmit() {
  19921. var gl = Laya.LayaGL.instance;
  19922. this._prepareSceneToRender();
  19923. var i, n, n1;
  19924. for (i = 0, n = this._cameraPool.length, n1 = n - 1; i < n; i++) {
  19925. if (Laya.Render.supportWebGLPlusRendering)
  19926. ShaderData.setRuntimeValueMode((i == n1) ? true : false);
  19927. var camera = this._cameraPool[i];
  19928. camera.enableRender && camera.render();
  19929. }
  19930. Laya.Context.set2DRenderConfig();
  19931. return 1;
  19932. }
  19933. getRenderType() {
  19934. return 0;
  19935. }
  19936. releaseRender() {
  19937. }
  19938. reUse(context, pos) {
  19939. return 0;
  19940. }
  19941. setGlobalShaderValue(name, shaderDataType, value) {
  19942. var shaderOffset = Shader3D.propertyNameToID(name);
  19943. switch (shaderDataType) {
  19944. case exports.ShaderDataType.Int:
  19945. this._shaderValues.setInt(shaderOffset, value);
  19946. break;
  19947. case exports.ShaderDataType.Number:
  19948. this._shaderValues.setNumber(shaderOffset, value);
  19949. break;
  19950. case exports.ShaderDataType.Bool:
  19951. this._shaderValues.setBool(shaderOffset, value);
  19952. break;
  19953. case exports.ShaderDataType.Matrix4x4:
  19954. this._shaderValues.setMatrix4x4(shaderOffset, value);
  19955. break;
  19956. case exports.ShaderDataType.Quaternion:
  19957. this._shaderValues.setQuaternion(shaderOffset, value);
  19958. break;
  19959. case exports.ShaderDataType.Texture:
  19960. this._shaderValues.setTexture(shaderOffset, value);
  19961. break;
  19962. case exports.ShaderDataType.Vector4:
  19963. this._shaderValues.setVector(shaderOffset, value);
  19964. break;
  19965. case exports.ShaderDataType.Vector2:
  19966. this._shaderValues.setVector2(shaderOffset, value);
  19967. break;
  19968. case exports.ShaderDataType.Vector3:
  19969. this._shaderValues.setVector3(shaderOffset, value);
  19970. break;
  19971. case exports.ShaderDataType.Buffer:
  19972. this._shaderValues.setBuffer(shaderOffset, value);
  19973. break;
  19974. }
  19975. }
  19976. get customReflection() {
  19977. return this._reflection;
  19978. }
  19979. set customReflection(value) {
  19980. if (this._reflection != value) {
  19981. value._addReference();
  19982. this._reflectionProbeManager.sceneReflectionProbe = value;
  19983. this._reflection = value;
  19984. }
  19985. }
  19986. get reflectionMode() {
  19987. return this._reflectionMode;
  19988. }
  19989. set reflectionMode(value) {
  19990. this._reflectionMode = value;
  19991. }
  19992. setlightmaps(value) {
  19993. var maps = this._lightmaps;
  19994. for (var i = 0, n = maps.length; i < n; i++)
  19995. maps[i].lightmapColor._removeReference();
  19996. if (value) {
  19997. var count = value.length;
  19998. maps.length = count;
  19999. for (i = 0; i < count; i++) {
  20000. var lightMap = value[i];
  20001. lightMap._addReference();
  20002. (maps[i]) || (maps[i] = new Lightmap());
  20003. maps[i].lightmapColor = lightMap;
  20004. }
  20005. }
  20006. else {
  20007. throw new Error("Scene3D: value value can't be null.");
  20008. }
  20009. }
  20010. getlightmaps() {
  20011. var lightmapColors = new Array(this._lightmaps.length);
  20012. for (var i = 0; i < this._lightmaps.length; i++) {
  20013. lightmapColors[i] = this._lightmaps[i].lightmapColor;
  20014. }
  20015. return lightmapColors;
  20016. }
  20017. }
  20018. Scene3D._shadowCasterPass = new ShadowCasterPass();
  20019. Scene3D.HIERARCHY = "HIERARCHY";
  20020. Scene3D.octreeCulling = false;
  20021. Scene3D.octreeInitialSize = 64.0;
  20022. Scene3D.octreeInitialCenter = new Vector3(0, 0, 0);
  20023. Scene3D.octreeMinNodeSize = 2.0;
  20024. Scene3D.octreeLooseness = 1.25;
  20025. Scene3D.REFLECTIONMODE_SKYBOX = 0;
  20026. Scene3D.REFLECTIONMODE_CUSTOM = 1;
  20027. Scene3D.SCENERENDERFLAG_RENDERQPAQUE = 0;
  20028. Scene3D.SCENERENDERFLAG_SKYBOX = 1;
  20029. Scene3D.SCENERENDERFLAG_RENDERTRANSPARENT = 2;
  20030. Scene3D.FOGCOLOR = Shader3D.propertyNameToID("u_FogColor");
  20031. Scene3D.FOGSTART = Shader3D.propertyNameToID("u_FogStart");
  20032. Scene3D.FOGRANGE = Shader3D.propertyNameToID("u_FogRange");
  20033. Scene3D.DIRECTIONLIGHTCOUNT = Shader3D.propertyNameToID("u_DirationLightCount");
  20034. Scene3D.LIGHTBUFFER = Shader3D.propertyNameToID("u_LightBuffer");
  20035. Scene3D.CLUSTERBUFFER = Shader3D.propertyNameToID("u_LightClusterBuffer");
  20036. Scene3D.SUNLIGHTDIRECTION = Shader3D.propertyNameToID("u_SunLight.direction");
  20037. Scene3D.SUNLIGHTDIRCOLOR = Shader3D.propertyNameToID("u_SunLight.color");
  20038. Scene3D.AMBIENTSHAR = Shader3D.propertyNameToID("u_AmbientSHAr");
  20039. Scene3D.AMBIENTSHAG = Shader3D.propertyNameToID("u_AmbientSHAg");
  20040. Scene3D.AMBIENTSHAB = Shader3D.propertyNameToID("u_AmbientSHAb");
  20041. Scene3D.AMBIENTSHBR = Shader3D.propertyNameToID("u_AmbientSHBr");
  20042. Scene3D.AMBIENTSHBG = Shader3D.propertyNameToID("u_AmbientSHBg");
  20043. Scene3D.AMBIENTSHBB = Shader3D.propertyNameToID("u_AmbientSHBb");
  20044. Scene3D.AMBIENTSHC = Shader3D.propertyNameToID("u_AmbientSHC");
  20045. Scene3D.LIGHTDIRECTION = Shader3D.propertyNameToID("u_DirectionLight.direction");
  20046. Scene3D.LIGHTDIRCOLOR = Shader3D.propertyNameToID("u_DirectionLight.color");
  20047. Scene3D.POINTLIGHTPOS = Shader3D.propertyNameToID("u_PointLight.position");
  20048. Scene3D.POINTLIGHTRANGE = Shader3D.propertyNameToID("u_PointLight.range");
  20049. Scene3D.POINTLIGHTATTENUATION = Shader3D.propertyNameToID("u_PointLight.attenuation");
  20050. Scene3D.POINTLIGHTCOLOR = Shader3D.propertyNameToID("u_PointLight.color");
  20051. Scene3D.SPOTLIGHTPOS = Shader3D.propertyNameToID("u_SpotLight.position");
  20052. Scene3D.SPOTLIGHTDIRECTION = Shader3D.propertyNameToID("u_SpotLight.direction");
  20053. Scene3D.SPOTLIGHTSPOTANGLE = Shader3D.propertyNameToID("u_SpotLight.spot");
  20054. Scene3D.SPOTLIGHTRANGE = Shader3D.propertyNameToID("u_SpotLight.range");
  20055. Scene3D.SPOTLIGHTCOLOR = Shader3D.propertyNameToID("u_SpotLight.color");
  20056. Scene3D.AMBIENTCOLOR = Shader3D.propertyNameToID("u_AmbientColor");
  20057. Scene3D.TIME = Shader3D.propertyNameToID("u_Time");
  20058. Scene3D._configDefineValues = new DefineDatas();
  20059. class ShaderPass extends Laya.ShaderCompile {
  20060. constructor(owner, vs, ps, stateMap) {
  20061. super(vs, ps, null);
  20062. this._cacheSharders = {};
  20063. this._cacheShaderHierarchy = 1;
  20064. this._renderState = new RenderState();
  20065. this._validDefine = new DefineDatas();
  20066. this._tags = {};
  20067. this._owner = owner;
  20068. this._stateMap = stateMap;
  20069. for (var k in this.defs)
  20070. this._validDefine.add(Shader3D.getDefineByName(k));
  20071. }
  20072. get renderState() {
  20073. return this._renderState;
  20074. }
  20075. _compileToTree(parent, lines, start, includefiles, defs) {
  20076. var node, preNode;
  20077. var text, name, fname;
  20078. var ofs, words, noUseNode;
  20079. var i, n, j;
  20080. for (i = start; i < lines.length; i++) {
  20081. text = lines[i];
  20082. if (text.length < 1)
  20083. continue;
  20084. ofs = text.indexOf("//");
  20085. if (ofs === 0)
  20086. continue;
  20087. if (ofs >= 0)
  20088. text = text.substr(0, ofs);
  20089. node = noUseNode || new Laya.ShaderNode(includefiles);
  20090. noUseNode = null;
  20091. node.text = text;
  20092. node.noCompile = true;
  20093. if ((ofs = text.indexOf("#")) >= 0) {
  20094. name = "#";
  20095. for (j = ofs + 1, n = text.length; j < n; j++) {
  20096. var c = text.charAt(j);
  20097. if (c === ' ' || c === '\t' || c === '?')
  20098. break;
  20099. name += c;
  20100. }
  20101. node.name = name;
  20102. switch (name) {
  20103. case "#ifdef":
  20104. case "#ifndef":
  20105. node.src = text;
  20106. node.noCompile = text.match(/[!&|()=<>]/) != null;
  20107. if (!node.noCompile) {
  20108. words = text.replace(/^\s*/, '').split(/\s+/);
  20109. node.setCondition(words[1], name === "#ifdef" ? Laya.ShaderCompile.IFDEF_YES : Laya.ShaderCompile.IFDEF_ELSE);
  20110. node.text = "//" + node.text;
  20111. }
  20112. else {
  20113. console.log("function():Boolean{return " + text.substr(ofs + node.name.length) + "}");
  20114. }
  20115. node.setParent(parent);
  20116. parent = node;
  20117. if (defs) {
  20118. words = text.substr(j).split(Laya.ShaderCompile._splitToWordExps3);
  20119. for (j = 0; j < words.length; j++) {
  20120. text = words[j];
  20121. text.length && (defs[text] = true);
  20122. }
  20123. }
  20124. continue;
  20125. case "#if":
  20126. case "#elif":
  20127. node.src = text;
  20128. node.noCompile = true;
  20129. if (name == "#elif") {
  20130. parent = parent.parent;
  20131. preNode = parent.childs[parent.childs.length - 1];
  20132. preNode.text = preNode.src;
  20133. preNode.noCompile = true;
  20134. preNode.condition = null;
  20135. }
  20136. node.setParent(parent);
  20137. parent = node;
  20138. if (defs) {
  20139. words = text.substr(j).split(Laya.ShaderCompile._splitToWordExps3);
  20140. for (j = 0; j < words.length; j++) {
  20141. text = words[j];
  20142. text.length && text != "defined" && (defs[text] = true);
  20143. }
  20144. }
  20145. continue;
  20146. case "#else":
  20147. node.src = text;
  20148. parent = parent.parent;
  20149. preNode = parent.childs[parent.childs.length - 1];
  20150. node.noCompile = preNode.noCompile;
  20151. if (!node.noCompile) {
  20152. node.condition = preNode.condition;
  20153. node.conditionType = preNode.conditionType == Laya.ShaderCompile.IFDEF_YES ? Laya.ShaderCompile.IFDEF_ELSE : Laya.ShaderCompile.IFDEF_YES;
  20154. node.text = "//" + node.text + " " + preNode.text + " " + node.conditionType;
  20155. }
  20156. node.setParent(parent);
  20157. parent = node;
  20158. continue;
  20159. case "#endif":
  20160. parent = parent.parent;
  20161. preNode = parent.childs[parent.childs.length - 1];
  20162. node.noCompile = preNode.noCompile;
  20163. if (!node.noCompile) {
  20164. node.text = "//" + node.text;
  20165. }
  20166. node.setParent(parent);
  20167. continue;
  20168. case "#include":
  20169. words = Laya.ShaderCompile.splitToWords(text, null);
  20170. var inlcudeFile = Laya.ShaderCompile.includes[words[1]];
  20171. if (!inlcudeFile) {
  20172. throw "ShaderCompile error no this include file:" + words[1];
  20173. }
  20174. if ((ofs = words[0].indexOf("?")) < 0) {
  20175. node.setParent(parent);
  20176. text = inlcudeFile.getWith(words[2] == 'with' ? words[3] : null);
  20177. this._compileToTree(node, text.split('\n'), 0, includefiles, defs);
  20178. node.text = "";
  20179. continue;
  20180. }
  20181. node.setCondition(words[0].substr(ofs + 1), Laya.ShaderCompile.IFDEF_YES);
  20182. node.text = inlcudeFile.getWith(words[2] == 'with' ? words[3] : null);
  20183. break;
  20184. case "#import":
  20185. words = Laya.ShaderCompile.splitToWords(text, null);
  20186. fname = words[1];
  20187. includefiles.push({ node: node, file: Laya.ShaderCompile.includes[fname], ofs: node.text.length });
  20188. continue;
  20189. }
  20190. }
  20191. else {
  20192. preNode = parent.childs[parent.childs.length - 1];
  20193. if (preNode && !preNode.name) {
  20194. includefiles.length > 0 && Laya.ShaderCompile.splitToWords(text, preNode);
  20195. noUseNode = node;
  20196. preNode.text += "\n" + text;
  20197. continue;
  20198. }
  20199. includefiles.length > 0 && Laya.ShaderCompile.splitToWords(text, node);
  20200. }
  20201. node.setParent(parent);
  20202. }
  20203. }
  20204. _resizeCacheShaderMap(cacheMap, hierarchy, resizeLength) {
  20205. var end = this._cacheShaderHierarchy - 1;
  20206. if (hierarchy == end) {
  20207. for (var k in cacheMap) {
  20208. var shader = cacheMap[k];
  20209. for (var i = 0, n = resizeLength - end; i < n; i++) {
  20210. if (i == n - 1)
  20211. cacheMap[0] = shader;
  20212. else
  20213. cacheMap = cacheMap[i == 0 ? k : 0] = {};
  20214. }
  20215. }
  20216. this._cacheShaderHierarchy = resizeLength;
  20217. }
  20218. else {
  20219. for (var k in cacheMap)
  20220. this._resizeCacheShaderMap(cacheMap[k], ++hierarchy, resizeLength);
  20221. }
  20222. }
  20223. _addDebugShaderVariantCollection(compileDefine, outDebugDefines, outDebugDefineMask) {
  20224. var dbugShaderVariantInfo = Shader3D._debugShaderVariantInfo;
  20225. var debugSubShader = this._owner;
  20226. var debugShader = debugSubShader._owner;
  20227. var mask = compileDefine._mask;
  20228. Shader3D._getNamesByDefineData(compileDefine, outDebugDefines);
  20229. outDebugDefineMask.length = mask.length;
  20230. for (var i = 0, n = mask.length; i < n; i++)
  20231. outDebugDefineMask[i] = mask[i];
  20232. if (dbugShaderVariantInfo)
  20233. dbugShaderVariantInfo.setValue(debugShader, debugShader._subShaders.indexOf(debugSubShader), debugSubShader._passes.indexOf(this), outDebugDefines);
  20234. else
  20235. Shader3D._debugShaderVariantInfo = dbugShaderVariantInfo = new ShaderVariant(debugShader, debugShader._subShaders.indexOf(debugSubShader), debugSubShader._passes.indexOf(this), outDebugDefines);
  20236. Shader3D.debugShaderVariantCollection.add(dbugShaderVariantInfo);
  20237. }
  20238. withCompile(compileDefine) {
  20239. var debugDefineString = ShaderPass._debugDefineString;
  20240. var debugDefineMask = ShaderPass._debugDefineMask;
  20241. var debugMaskLength;
  20242. compileDefine._intersectionDefineDatas(this._validDefine);
  20243. if (Shader3D.debugMode) {
  20244. debugMaskLength = compileDefine._length;
  20245. this._addDebugShaderVariantCollection(compileDefine, debugDefineString, debugDefineMask);
  20246. }
  20247. compileDefine.addDefineDatas(Scene3D._configDefineValues);
  20248. var cacheShaders = this._cacheSharders;
  20249. var maskLength = compileDefine._length;
  20250. if (maskLength > this._cacheShaderHierarchy) {
  20251. this._resizeCacheShaderMap(cacheShaders, 0, maskLength);
  20252. this._cacheShaderHierarchy = maskLength;
  20253. }
  20254. var mask = compileDefine._mask;
  20255. var endIndex = compileDefine._length - 1;
  20256. var maxEndIndex = this._cacheShaderHierarchy - 1;
  20257. for (var i = 0; i < maxEndIndex; i++) {
  20258. var subMask = endIndex < i ? 0 : mask[i];
  20259. var subCacheShaders = cacheShaders[subMask];
  20260. (subCacheShaders) || (cacheShaders[subMask] = subCacheShaders = {});
  20261. cacheShaders = subCacheShaders;
  20262. }
  20263. var cacheKey = endIndex < maxEndIndex ? 0 : mask[maxEndIndex];
  20264. var shader = cacheShaders[cacheKey];
  20265. if (shader)
  20266. return shader;
  20267. var defineString = ShaderPass._defineString;
  20268. Shader3D._getNamesByDefineData(compileDefine, defineString);
  20269. var config = Config3D._config;
  20270. var clusterSlices = config.lightClusterCount;
  20271. var defMap = {};
  20272. var vertexHead;
  20273. var fragmentHead;
  20274. var defineStr = "";
  20275. if (Laya.WebGL._isWebGL2) {
  20276. vertexHead =
  20277. `#version 300 es\n
  20278. #define attribute in
  20279. #define varying out
  20280. #define texture2D texture\n`;
  20281. fragmentHead =
  20282. `#version 300 es\n
  20283. #define varying in
  20284. out highp vec4 pc_fragColor;
  20285. #define gl_FragColor pc_fragColor
  20286. #define gl_FragDepthEXT gl_FragDepth
  20287. #define texture2D texture
  20288. #define textureCube texture
  20289. #define texture2DProj textureProj
  20290. #define texture2DLodEXT textureLod
  20291. #define texture2DProjLodEXT textureProjLod
  20292. #define textureCubeLodEXT textureLod
  20293. #define texture2DGradEXT textureGrad
  20294. #define texture2DProjGradEXT textureProjGrad
  20295. #define textureCubeGradEXT textureGrad\n`;
  20296. }
  20297. else {
  20298. vertexHead = "";
  20299. fragmentHead =
  20300. `#ifdef GL_EXT_shader_texture_lod
  20301. #extension GL_EXT_shader_texture_lod : enable
  20302. #endif
  20303. #if !defined(GL_EXT_shader_texture_lod)
  20304. #define texture1DLodEXT texture1D
  20305. #define texture2DLodEXT texture2D
  20306. #define texture2DProjLodEXT texture2DProj
  20307. #define texture3DLodEXT texture3D
  20308. #define textureCubeLodEXT textureCube
  20309. #endif\n`;
  20310. }
  20311. defineStr += "#define MAX_LIGHT_COUNT " + config.maxLightCount + "\n";
  20312. defineStr += "#define MAX_LIGHT_COUNT_PER_CLUSTER " + config._maxAreaLightCountPerClusterAverage + "\n";
  20313. defineStr += "#define CLUSTER_X_COUNT " + clusterSlices.x + "\n";
  20314. defineStr += "#define CLUSTER_Y_COUNT " + clusterSlices.y + "\n";
  20315. defineStr += "#define CLUSTER_Z_COUNT " + clusterSlices.z + "\n";
  20316. defineStr += "#define SHADER_CAPAILITY_LEVEL " + Laya.SystemUtils._shaderCapailityLevel + "\n";
  20317. for (var i = 0, n = defineString.length; i < n; i++) {
  20318. var def = defineString[i];
  20319. defineStr += "#define " + def + "\n";
  20320. defMap[def] = true;
  20321. }
  20322. var vs = this._VS.toscript(defMap, []);
  20323. var vsVersion = '';
  20324. if (vs[0].indexOf('#version') == 0) {
  20325. vsVersion = vs[0] + '\n';
  20326. vs.shift();
  20327. }
  20328. var ps = this._PS.toscript(defMap, []);
  20329. var psVersion = '';
  20330. if (ps[0].indexOf('#version') == 0) {
  20331. psVersion = ps[0] + '\n';
  20332. ps.shift();
  20333. }
  20334. var attibuteMap = Shader3D.getAttributeMapByDefine(defineString, this._owner._attributeMap);
  20335. shader = new ShaderInstance(vsVersion + vertexHead + defineStr + vs.join('\n'), psVersion + fragmentHead + defineStr + ps.join('\n'), attibuteMap, this._owner._uniformMap || this._owner._owner._uniformMap, this);
  20336. cacheShaders[cacheKey] = shader;
  20337. if (Shader3D.debugMode) {
  20338. var defStr = "";
  20339. var defMask = "";
  20340. for (var i = 0, n = debugMaskLength; i < n; i++)
  20341. (i == n - 1) ? defMask += debugDefineMask[i] : defMask += debugDefineMask[i] + ",";
  20342. for (var i = 0, n = debugDefineString.length; i < n; i++)
  20343. (i == n - 1) ? defStr += debugDefineString[i] : defStr += debugDefineString[i] + ",";
  20344. console.log("%cLayaAir: Shader Compile Information---ShaderName:" + this._owner._owner._name + " SubShaderIndex:" + this._owner._owner._subShaders.indexOf(this._owner) + " PassIndex:" + this._owner._passes.indexOf(this) + " DefineMask:[" + defMask + "]" + " DefineNames:[" + defStr + "]", "color:green");
  20345. }
  20346. return shader;
  20347. }
  20348. setTag(key, value) {
  20349. if (value)
  20350. this._tags[key] = value;
  20351. else
  20352. delete this._tags[key];
  20353. }
  20354. getTag(key) {
  20355. return this._tags[key];
  20356. }
  20357. }
  20358. ShaderPass._defineString = [];
  20359. ShaderPass._debugDefineString = [];
  20360. ShaderPass._debugDefineMask = [];
  20361. class SubShader {
  20362. constructor(attributeMap, uniformMap) {
  20363. this._flags = {};
  20364. this._passes = [];
  20365. this._attributeMap = attributeMap;
  20366. this._uniformMap = uniformMap;
  20367. }
  20368. setFlag(key, value) {
  20369. if (value)
  20370. this._flags[key] = value;
  20371. else
  20372. delete this._flags[key];
  20373. }
  20374. getFlag(key) {
  20375. return this._flags[key];
  20376. }
  20377. addShaderPass(vs, ps, stateMap = null, pipelineMode = "Forward") {
  20378. var shaderPass = new ShaderPass(this, vs, ps, stateMap);
  20379. shaderPass._pipelineMode = pipelineMode;
  20380. this._passes.push(shaderPass);
  20381. return shaderPass;
  20382. }
  20383. }
  20384. (function (PBRSpecularSmoothnessSource) {
  20385. PBRSpecularSmoothnessSource[PBRSpecularSmoothnessSource["SpecularTextureAlpha"] = 0] = "SpecularTextureAlpha";
  20386. PBRSpecularSmoothnessSource[PBRSpecularSmoothnessSource["AlbedoTextureAlpha"] = 1] = "AlbedoTextureAlpha";
  20387. })(exports.PBRSpecularSmoothnessSource || (exports.PBRSpecularSmoothnessSource = {}));
  20388. class PBRSpecularMaterial extends PBRMaterial {
  20389. constructor() {
  20390. super();
  20391. this.setShaderName("PBRSpecular");
  20392. this._shaderValues.setVector(PBRSpecularMaterial.SPECULARCOLOR, new Vector4(0.2, 0.2, 0.2, 1.0));
  20393. }
  20394. static __init__() {
  20395. PBRSpecularMaterial.SHADERDEFINE_SPECULARGLOSSTEXTURE = Shader3D.getDefineByName("SPECULARGLOSSTEXTURE");
  20396. PBRSpecularMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA = Shader3D.getDefineByName("SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA");
  20397. var attributeMap = {
  20398. 'a_Position': VertexMesh.MESH_POSITION0,
  20399. 'a_Normal': VertexMesh.MESH_NORMAL0,
  20400. 'a_Tangent0': VertexMesh.MESH_TANGENT0,
  20401. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0,
  20402. 'a_Texcoord1': VertexMesh.MESH_TEXTURECOORDINATE1,
  20403. 'a_BoneWeights': VertexMesh.MESH_BLENDWEIGHT0,
  20404. 'a_BoneIndices': VertexMesh.MESH_BLENDINDICES0,
  20405. 'a_MvpMatrix': VertexMesh.MESH_MVPMATRIX_ROW0,
  20406. 'a_WorldMat': VertexMesh.MESH_WORLDMATRIX_ROW0
  20407. };
  20408. var uniformMap = {
  20409. 'u_Bones': Shader3D.PERIOD_CUSTOM,
  20410. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  20411. 'u_WorldMat': Shader3D.PERIOD_SPRITE,
  20412. 'u_LightmapScaleOffset': Shader3D.PERIOD_SPRITE,
  20413. 'u_LightMap': Shader3D.PERIOD_SPRITE,
  20414. 'u_LightMapDirection': Shader3D.PERIOD_SPRITE,
  20415. 'u_SimpleAnimatorTexture': Shader3D.PERIOD_SPRITE,
  20416. 'u_SimpleAnimatorParams': Shader3D.PERIOD_SPRITE,
  20417. 'u_SimpleAnimatorTextureSize': Shader3D.PERIOD_SPRITE,
  20418. 'u_ReflectCubeHDRParams': Shader3D.PERIOD_SPRITE,
  20419. 'u_ReflectTexture': Shader3D.PERIOD_SPRITE,
  20420. 'u_SpecCubeProbePosition': Shader3D.PERIOD_SPRITE,
  20421. 'u_SpecCubeBoxMax': Shader3D.PERIOD_SPRITE,
  20422. 'u_SpecCubeBoxMin': Shader3D.PERIOD_SPRITE,
  20423. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  20424. 'u_View': Shader3D.PERIOD_CAMERA,
  20425. 'u_ProjectionParams': Shader3D.PERIOD_CAMERA,
  20426. 'u_Viewport': Shader3D.PERIOD_CAMERA,
  20427. 'u_ViewProjection': Shader3D.PERIOD_CAMERA,
  20428. 'u_AlphaTestValue': Shader3D.PERIOD_MATERIAL,
  20429. 'u_AlbedoColor': Shader3D.PERIOD_MATERIAL,
  20430. 'u_EmissionColor': Shader3D.PERIOD_MATERIAL,
  20431. 'u_AlbedoTexture': Shader3D.PERIOD_MATERIAL,
  20432. 'u_NormalTexture': Shader3D.PERIOD_MATERIAL,
  20433. 'u_ParallaxTexture': Shader3D.PERIOD_MATERIAL,
  20434. 'u_OcclusionTexture': Shader3D.PERIOD_MATERIAL,
  20435. 'u_EmissionTexture': Shader3D.PERIOD_MATERIAL,
  20436. 'u_Smoothness': Shader3D.PERIOD_MATERIAL,
  20437. 'u_SmoothnessScale': Shader3D.PERIOD_MATERIAL,
  20438. 'u_occlusionStrength': Shader3D.PERIOD_MATERIAL,
  20439. 'u_NormalScale': Shader3D.PERIOD_MATERIAL,
  20440. 'u_ParallaxScale': Shader3D.PERIOD_MATERIAL,
  20441. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  20442. 'u_SpecGlossTexture': Shader3D.PERIOD_MATERIAL,
  20443. 'u_SpecularColor': Shader3D.PERIOD_MATERIAL,
  20444. 'u_AmbientColor': Shader3D.PERIOD_SCENE,
  20445. 'u_FogStart': Shader3D.PERIOD_SCENE,
  20446. 'u_FogRange': Shader3D.PERIOD_SCENE,
  20447. 'u_FogColor': Shader3D.PERIOD_SCENE,
  20448. 'u_DirationLightCount': Shader3D.PERIOD_SCENE,
  20449. 'u_LightBuffer': Shader3D.PERIOD_SCENE,
  20450. 'u_LightClusterBuffer': Shader3D.PERIOD_SCENE,
  20451. 'u_ShadowBias': Shader3D.PERIOD_SCENE,
  20452. 'u_ShadowLightDirection': Shader3D.PERIOD_SCENE,
  20453. 'u_ShadowMap': Shader3D.PERIOD_SCENE,
  20454. 'u_ShadowParams': Shader3D.PERIOD_SCENE,
  20455. 'u_ShadowSplitSpheres': Shader3D.PERIOD_SCENE,
  20456. 'u_ShadowMatrices': Shader3D.PERIOD_SCENE,
  20457. 'u_ShadowMapSize': Shader3D.PERIOD_SCENE,
  20458. 'u_SpotShadowMap': Shader3D.PERIOD_SCENE,
  20459. 'u_SpotViewProjectMatrix': Shader3D.PERIOD_SCENE,
  20460. 'u_ShadowLightPosition': Shader3D.PERIOD_SCENE,
  20461. 'u_AmbientSHAr': Shader3D.PERIOD_SCENE,
  20462. 'u_AmbientSHAg': Shader3D.PERIOD_SCENE,
  20463. 'u_AmbientSHAb': Shader3D.PERIOD_SCENE,
  20464. 'u_AmbientSHBr': Shader3D.PERIOD_SCENE,
  20465. 'u_AmbientSHBg': Shader3D.PERIOD_SCENE,
  20466. 'u_AmbientSHBb': Shader3D.PERIOD_SCENE,
  20467. 'u_AmbientSHC': Shader3D.PERIOD_SCENE,
  20468. 'u_DirectionLight.direction': Shader3D.PERIOD_SCENE,
  20469. 'u_DirectionLight.color': Shader3D.PERIOD_SCENE,
  20470. 'u_PointLight.position': Shader3D.PERIOD_SCENE,
  20471. 'u_PointLight.range': Shader3D.PERIOD_SCENE,
  20472. 'u_PointLight.color': Shader3D.PERIOD_SCENE,
  20473. 'u_SpotLight.position': Shader3D.PERIOD_SCENE,
  20474. 'u_SpotLight.direction': Shader3D.PERIOD_SCENE,
  20475. 'u_SpotLight.range': Shader3D.PERIOD_SCENE,
  20476. 'u_SpotLight.spot': Shader3D.PERIOD_SCENE,
  20477. 'u_SpotLight.color': Shader3D.PERIOD_SCENE
  20478. };
  20479. var stateMap = {
  20480. 's_Cull': Shader3D.RENDER_STATE_CULL,
  20481. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  20482. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  20483. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  20484. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  20485. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  20486. };
  20487. var shader = Shader3D.add("PBRSpecular", attributeMap, uniformMap, true, true);
  20488. var subShader = new SubShader(attributeMap, uniformMap);
  20489. shader.addSubShader(subShader);
  20490. subShader.addShaderPass(PBRVS, PBRPS, stateMap, "Forward");
  20491. subShader.addShaderPass(PBRShadowCasterVS, PBRShadowCasterPS, stateMap, "ShadowCaster");
  20492. subShader.addShaderPass(DepthNormalsTextureVS, DepthNormalsTextureFS, stateMap, "DepthNormal");
  20493. }
  20494. get specularTexture() {
  20495. return this._shaderValues.getTexture(PBRSpecularMaterial.SPECULARTEXTURE);
  20496. }
  20497. set specularTexture(value) {
  20498. if (value)
  20499. this._shaderValues.addDefine(PBRSpecularMaterial.SHADERDEFINE_SPECULARGLOSSTEXTURE);
  20500. else
  20501. this._shaderValues.removeDefine(PBRSpecularMaterial.SHADERDEFINE_SPECULARGLOSSTEXTURE);
  20502. this._shaderValues.setTexture(PBRSpecularMaterial.SPECULARTEXTURE, value);
  20503. }
  20504. get specularColor() {
  20505. return this._shaderValues.getVector(PBRSpecularMaterial.SPECULARCOLOR);
  20506. }
  20507. set specularColor(value) {
  20508. this._shaderValues.setVector(PBRSpecularMaterial.SPECULARCOLOR, value);
  20509. }
  20510. clone() {
  20511. var dest = new PBRSpecularMaterial();
  20512. this.cloneTo(dest);
  20513. return dest;
  20514. }
  20515. }
  20516. PBRSpecularMaterial.SPECULARTEXTURE = Shader3D.propertyNameToID("u_SpecGlossTexture");
  20517. PBRSpecularMaterial.SPECULARCOLOR = Shader3D.propertyNameToID("u_SpecularColor");
  20518. var PBRPS$1 = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n\tprecision highp int;\r\n#else\r\n\tprecision mediump float;\r\n\tprecision mediump int;\r\n#endif\r\n\r\n#include \"Lighting.glsl\";\r\n#include \"Shadow.glsl\"\r\n#include \"PBRFSInput.glsl\";\r\n#include \"LayaPBRBRDF.glsl\";\r\n#include \"GlobalIllumination.glsl\";\r\n#include \"PBRCore.glsl\";\r\n\r\nvoid main()\r\n{\r\n\tfragmentForward();\r\n}";
  20519. var PBRVS$1 = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n\tprecision highp int;\r\n#else\r\n\tprecision mediump float;\r\n\tprecision mediump int;\r\n#endif\r\n#include \"Lighting.glsl\";\r\n#include \"LayaUtile.glsl\"\r\n#include \"Shadow.glsl\"\r\n#include \"PBRVSInput.glsl\";\r\n#include \"PBRVertex.glsl\";\r\n\r\nvoid main()\r\n{\r\n\tvertexForward();\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}";
  20520. var PBRShadowCasterPS$1 = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n\tprecision highp int;\r\n#else\r\n\tprecision mediump float;\r\n\tprecision mediump int;\r\n#endif\r\n\r\n#include \"ShadowCasterFS.glsl\"\r\n\r\nvoid main()\r\n{\r\n\tgl_FragColor=shadowCasterFragment();\r\n}";
  20521. var PBRShadowCasterVS$1 = "#include \"ShadowCasterVS.glsl\"\r\n\r\nvoid main()\r\n{\r\n\tvec4 positionCS = shadowCasterVertex();\r\n\tgl_Position=remapGLPositionZ(positionCS);\r\n}";
  20522. (function (PBRMetallicSmoothnessSource) {
  20523. PBRMetallicSmoothnessSource[PBRMetallicSmoothnessSource["MetallicGlossTextureAlpha"] = 0] = "MetallicGlossTextureAlpha";
  20524. PBRMetallicSmoothnessSource[PBRMetallicSmoothnessSource["AlbedoTextureAlpha"] = 1] = "AlbedoTextureAlpha";
  20525. })(exports.PBRMetallicSmoothnessSource || (exports.PBRMetallicSmoothnessSource = {}));
  20526. class PBRStandardMaterial extends PBRMaterial {
  20527. constructor() {
  20528. super();
  20529. this._smoothnessSource = 0;
  20530. this.setShaderName("PBR");
  20531. this._shaderValues.setNumber(PBRStandardMaterial.METALLIC, 0.0);
  20532. }
  20533. static __init__() {
  20534. PBRStandardMaterial.SHADERDEFINE_METALLICGLOSSTEXTURE = Shader3D.getDefineByName("METALLICGLOSSTEXTURE");
  20535. PBRStandardMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA = Shader3D.getDefineByName("SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA");
  20536. var attributeMap = {
  20537. 'a_Position': VertexMesh.MESH_POSITION0,
  20538. 'a_Normal': VertexMesh.MESH_NORMAL0,
  20539. 'a_Tangent0': VertexMesh.MESH_TANGENT0,
  20540. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0,
  20541. 'a_Texcoord1': VertexMesh.MESH_TEXTURECOORDINATE1,
  20542. 'a_BoneWeights': VertexMesh.MESH_BLENDWEIGHT0,
  20543. 'a_BoneIndices': VertexMesh.MESH_BLENDINDICES0,
  20544. 'a_MvpMatrix': VertexMesh.MESH_MVPMATRIX_ROW0,
  20545. 'a_WorldMat': VertexMesh.MESH_WORLDMATRIX_ROW0
  20546. };
  20547. var uniformMap = {
  20548. 'u_Bones': Shader3D.PERIOD_CUSTOM,
  20549. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  20550. 'u_WorldMat': Shader3D.PERIOD_SPRITE,
  20551. 'u_LightmapScaleOffset': Shader3D.PERIOD_SPRITE,
  20552. 'u_LightMap': Shader3D.PERIOD_SPRITE,
  20553. 'u_LightMapDirection': Shader3D.PERIOD_SPRITE,
  20554. 'u_SimpleAnimatorTexture': Shader3D.PERIOD_SPRITE,
  20555. 'u_SimpleAnimatorParams': Shader3D.PERIOD_SPRITE,
  20556. 'u_SimpleAnimatorTextureSize': Shader3D.PERIOD_SPRITE,
  20557. 'u_ReflectCubeHDRParams': Shader3D.PERIOD_SPRITE,
  20558. 'u_ReflectTexture': Shader3D.PERIOD_SPRITE,
  20559. 'u_SpecCubeProbePosition': Shader3D.PERIOD_SPRITE,
  20560. 'u_SpecCubeBoxMax': Shader3D.PERIOD_SPRITE,
  20561. 'u_SpecCubeBoxMin': Shader3D.PERIOD_SPRITE,
  20562. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  20563. 'u_View': Shader3D.PERIOD_CAMERA,
  20564. 'u_ProjectionParams': Shader3D.PERIOD_CAMERA,
  20565. 'u_Viewport': Shader3D.PERIOD_CAMERA,
  20566. 'u_ViewProjection': Shader3D.PERIOD_CAMERA,
  20567. 'u_AlphaTestValue': Shader3D.PERIOD_MATERIAL,
  20568. 'u_AlbedoColor': Shader3D.PERIOD_MATERIAL,
  20569. 'u_EmissionColor': Shader3D.PERIOD_MATERIAL,
  20570. 'u_AlbedoTexture': Shader3D.PERIOD_MATERIAL,
  20571. 'u_NormalTexture': Shader3D.PERIOD_MATERIAL,
  20572. 'u_ParallaxTexture': Shader3D.PERIOD_MATERIAL,
  20573. 'u_OcclusionTexture': Shader3D.PERIOD_MATERIAL,
  20574. 'u_EmissionTexture': Shader3D.PERIOD_MATERIAL,
  20575. 'u_Smoothness': Shader3D.PERIOD_MATERIAL,
  20576. 'u_SmoothnessScale': Shader3D.PERIOD_MATERIAL,
  20577. 'u_occlusionStrength': Shader3D.PERIOD_MATERIAL,
  20578. 'u_NormalScale': Shader3D.PERIOD_MATERIAL,
  20579. 'u_ParallaxScale': Shader3D.PERIOD_MATERIAL,
  20580. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  20581. 'u_MetallicGlossTexture': Shader3D.PERIOD_MATERIAL,
  20582. 'u_Metallic': Shader3D.PERIOD_MATERIAL,
  20583. 'u_AmbientColor': Shader3D.PERIOD_SCENE,
  20584. 'u_FogStart': Shader3D.PERIOD_SCENE,
  20585. 'u_FogRange': Shader3D.PERIOD_SCENE,
  20586. 'u_FogColor': Shader3D.PERIOD_SCENE,
  20587. 'u_DirationLightCount': Shader3D.PERIOD_SCENE,
  20588. 'u_LightBuffer': Shader3D.PERIOD_SCENE,
  20589. 'u_LightClusterBuffer': Shader3D.PERIOD_SCENE,
  20590. 'u_ShadowBias': Shader3D.PERIOD_SCENE,
  20591. 'u_ShadowLightDirection': Shader3D.PERIOD_SCENE,
  20592. 'u_ShadowMap': Shader3D.PERIOD_SCENE,
  20593. 'u_ShadowParams': Shader3D.PERIOD_SCENE,
  20594. 'u_ShadowSplitSpheres': Shader3D.PERIOD_SCENE,
  20595. 'u_ShadowMatrices': Shader3D.PERIOD_SCENE,
  20596. 'u_ShadowMapSize': Shader3D.PERIOD_SCENE,
  20597. 'u_SpotShadowMap': Shader3D.PERIOD_SCENE,
  20598. 'u_SpotViewProjectMatrix': Shader3D.PERIOD_SCENE,
  20599. 'u_ShadowLightPosition': Shader3D.PERIOD_SCENE,
  20600. 'u_AmbientSHAr': Shader3D.PERIOD_SCENE,
  20601. 'u_AmbientSHAg': Shader3D.PERIOD_SCENE,
  20602. 'u_AmbientSHAb': Shader3D.PERIOD_SCENE,
  20603. 'u_AmbientSHBr': Shader3D.PERIOD_SCENE,
  20604. 'u_AmbientSHBg': Shader3D.PERIOD_SCENE,
  20605. 'u_AmbientSHBb': Shader3D.PERIOD_SCENE,
  20606. 'u_AmbientSHC': Shader3D.PERIOD_SCENE,
  20607. 'u_DirectionLight.direction': Shader3D.PERIOD_SCENE,
  20608. 'u_DirectionLight.color': Shader3D.PERIOD_SCENE,
  20609. 'u_PointLight.position': Shader3D.PERIOD_SCENE,
  20610. 'u_PointLight.range': Shader3D.PERIOD_SCENE,
  20611. 'u_PointLight.color': Shader3D.PERIOD_SCENE,
  20612. 'u_SpotLight.position': Shader3D.PERIOD_SCENE,
  20613. 'u_SpotLight.direction': Shader3D.PERIOD_SCENE,
  20614. 'u_SpotLight.range': Shader3D.PERIOD_SCENE,
  20615. 'u_SpotLight.spot': Shader3D.PERIOD_SCENE,
  20616. 'u_SpotLight.color': Shader3D.PERIOD_SCENE
  20617. };
  20618. var stateMap = {
  20619. 's_Cull': Shader3D.RENDER_STATE_CULL,
  20620. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  20621. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  20622. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  20623. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  20624. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  20625. };
  20626. var shader = Shader3D.add("PBR", attributeMap, uniformMap, true, true);
  20627. var subShader = new SubShader(attributeMap, uniformMap);
  20628. shader.addSubShader(subShader);
  20629. subShader.addShaderPass(PBRVS$1, PBRPS$1, stateMap, "Forward");
  20630. subShader.addShaderPass(PBRShadowCasterVS$1, PBRShadowCasterPS$1, stateMap, "ShadowCaster");
  20631. subShader.addShaderPass(DepthNormalsTextureVS, DepthNormalsTextureFS, stateMap, "DepthNormal");
  20632. }
  20633. get metallicGlossTexture() {
  20634. return this._shaderValues.getTexture(PBRStandardMaterial.METALLICGLOSSTEXTURE);
  20635. }
  20636. set metallicGlossTexture(value) {
  20637. if (value)
  20638. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_METALLICGLOSSTEXTURE);
  20639. else
  20640. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_METALLICGLOSSTEXTURE);
  20641. this._shaderValues.setTexture(PBRStandardMaterial.METALLICGLOSSTEXTURE, value);
  20642. }
  20643. get metallic() {
  20644. return this._shaderValues.getNumber(PBRStandardMaterial.METALLIC);
  20645. }
  20646. set metallic(value) {
  20647. this._shaderValues.setNumber(PBRStandardMaterial.METALLIC, Math.max(0.0, Math.min(1.0, value)));
  20648. }
  20649. get smoothnessSource() {
  20650. return this._smoothnessSource;
  20651. }
  20652. set smoothnessSource(value) {
  20653. if (value)
  20654. this._shaderValues.addDefine(PBRStandardMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA);
  20655. else
  20656. this._shaderValues.removeDefine(PBRStandardMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA);
  20657. this._smoothnessSource = value;
  20658. }
  20659. clone() {
  20660. var dest = new PBRStandardMaterial();
  20661. this.cloneTo(dest);
  20662. return dest;
  20663. }
  20664. }
  20665. PBRStandardMaterial.METALLICGLOSSTEXTURE = Shader3D.propertyNameToID("u_MetallicGlossTexture");
  20666. PBRStandardMaterial.METALLIC = Shader3D.propertyNameToID("u_Metallic");
  20667. class SkyBoxMaterial extends Material {
  20668. constructor() {
  20669. super();
  20670. this.setShaderName("SkyBox");
  20671. this.tintColor = new Vector4(0.5, 0.5, 0.5, 0.5);
  20672. this.exposure = 1.0;
  20673. this.rotation = 0;
  20674. }
  20675. static __initDefine__() {
  20676. }
  20677. get tintColor() {
  20678. return this._shaderValues.getVector(SkyBoxMaterial.TINTCOLOR);
  20679. }
  20680. set tintColor(value) {
  20681. this._shaderValues.setVector(SkyBoxMaterial.TINTCOLOR, value);
  20682. }
  20683. get exposure() {
  20684. return this._shaderValues.getNumber(SkyBoxMaterial.EXPOSURE);
  20685. }
  20686. set exposure(value) {
  20687. this._shaderValues.setNumber(SkyBoxMaterial.EXPOSURE, value);
  20688. }
  20689. get rotation() {
  20690. return this._shaderValues.getNumber(SkyBoxMaterial.ROTATION);
  20691. }
  20692. set rotation(value) {
  20693. this._shaderValues.setNumber(SkyBoxMaterial.ROTATION, value);
  20694. }
  20695. get textureCube() {
  20696. return this._shaderValues.getTexture(SkyBoxMaterial.TEXTURECUBE);
  20697. }
  20698. set textureCube(value) {
  20699. this._shaderValues.setTexture(SkyBoxMaterial.TEXTURECUBE, value);
  20700. }
  20701. clone() {
  20702. var dest = new SkyBoxMaterial();
  20703. this.cloneTo(dest);
  20704. return dest;
  20705. }
  20706. }
  20707. SkyBoxMaterial.TINTCOLOR = Shader3D.propertyNameToID("u_TintColor");
  20708. SkyBoxMaterial.EXPOSURE = Shader3D.propertyNameToID("u_Exposure");
  20709. SkyBoxMaterial.ROTATION = Shader3D.propertyNameToID("u_Rotation");
  20710. SkyBoxMaterial.TEXTURECUBE = Shader3D.propertyNameToID("u_CubeTexture");
  20711. class SkyProceduralMaterial extends Material {
  20712. constructor() {
  20713. super();
  20714. this.setShaderName("SkyBoxProcedural");
  20715. this.sunDisk = SkyProceduralMaterial.SUN_HIGH_QUALITY;
  20716. this.sunSize = 0.04;
  20717. this.sunSizeConvergence = 5;
  20718. this.atmosphereThickness = 1.0;
  20719. this.skyTint = new Vector4(0.5, 0.5, 0.5, 1.0);
  20720. this.groundTint = new Vector4(0.369, 0.349, 0.341, 1.0);
  20721. this.exposure = 1.3;
  20722. }
  20723. static __initDefine__() {
  20724. SkyProceduralMaterial.SHADERDEFINE_SUN_HIGH_QUALITY = Shader3D.getDefineByName("SUN_HIGH_QUALITY");
  20725. SkyProceduralMaterial.SHADERDEFINE_SUN_SIMPLE = Shader3D.getDefineByName("SUN_SIMPLE");
  20726. }
  20727. get sunDisk() {
  20728. return this._sunDisk;
  20729. }
  20730. set sunDisk(value) {
  20731. switch (value) {
  20732. case SkyProceduralMaterial.SUN_HIGH_QUALITY:
  20733. this._shaderValues.removeDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_SIMPLE);
  20734. this._shaderValues.addDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_HIGH_QUALITY);
  20735. break;
  20736. case SkyProceduralMaterial.SUN_SIMPLE:
  20737. this._shaderValues.removeDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_HIGH_QUALITY);
  20738. this._shaderValues.addDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_SIMPLE);
  20739. break;
  20740. case SkyProceduralMaterial.SUN_NODE:
  20741. this._shaderValues.removeDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_HIGH_QUALITY);
  20742. this._shaderValues.removeDefine(SkyProceduralMaterial.SHADERDEFINE_SUN_SIMPLE);
  20743. break;
  20744. default:
  20745. throw "SkyBoxProceduralMaterial: unknown sun value.";
  20746. }
  20747. this._sunDisk = value;
  20748. }
  20749. get sunSize() {
  20750. return this._shaderValues.getNumber(SkyProceduralMaterial.SUNSIZE);
  20751. }
  20752. set sunSize(value) {
  20753. value = Math.min(Math.max(0.0, value), 1.0);
  20754. this._shaderValues.setNumber(SkyProceduralMaterial.SUNSIZE, value);
  20755. }
  20756. get sunSizeConvergence() {
  20757. return this._shaderValues.getNumber(SkyProceduralMaterial.SUNSIZECONVERGENCE);
  20758. }
  20759. set sunSizeConvergence(value) {
  20760. value = Math.min(Math.max(0.0, value), 20.0);
  20761. this._shaderValues.setNumber(SkyProceduralMaterial.SUNSIZECONVERGENCE, value);
  20762. }
  20763. get atmosphereThickness() {
  20764. return this._shaderValues.getNumber(SkyProceduralMaterial.ATMOSPHERETHICKNESS);
  20765. }
  20766. set atmosphereThickness(value) {
  20767. value = Math.min(Math.max(0.0, value), 5.0);
  20768. this._shaderValues.setNumber(SkyProceduralMaterial.ATMOSPHERETHICKNESS, value);
  20769. }
  20770. get skyTint() {
  20771. return this._shaderValues.getVector(SkyProceduralMaterial.SKYTINT);
  20772. }
  20773. set skyTint(value) {
  20774. this._shaderValues.setVector(SkyProceduralMaterial.SKYTINT, value);
  20775. }
  20776. get groundTint() {
  20777. return this._shaderValues.getVector(SkyProceduralMaterial.GROUNDTINT);
  20778. }
  20779. set groundTint(value) {
  20780. this._shaderValues.setVector(SkyProceduralMaterial.GROUNDTINT, value);
  20781. }
  20782. get exposure() {
  20783. return this._shaderValues.getNumber(SkyProceduralMaterial.EXPOSURE);
  20784. }
  20785. set exposure(value) {
  20786. value = Math.min(Math.max(0.0, value), 8.0);
  20787. this._shaderValues.setNumber(SkyProceduralMaterial.EXPOSURE, value);
  20788. }
  20789. clone() {
  20790. var dest = new SkyProceduralMaterial();
  20791. this.cloneTo(dest);
  20792. return dest;
  20793. }
  20794. }
  20795. SkyProceduralMaterial.SUN_NODE = 0;
  20796. SkyProceduralMaterial.SUN_SIMPLE = 1;
  20797. SkyProceduralMaterial.SUN_HIGH_QUALITY = 2;
  20798. SkyProceduralMaterial.SUNSIZE = Shader3D.propertyNameToID("u_SunSize");
  20799. SkyProceduralMaterial.SUNSIZECONVERGENCE = Shader3D.propertyNameToID("u_SunSizeConvergence");
  20800. SkyProceduralMaterial.ATMOSPHERETHICKNESS = Shader3D.propertyNameToID("u_AtmosphereThickness");
  20801. SkyProceduralMaterial.SKYTINT = Shader3D.propertyNameToID("u_SkyTint");
  20802. SkyProceduralMaterial.GROUNDTINT = Shader3D.propertyNameToID("u_GroundTint");
  20803. SkyProceduralMaterial.EXPOSURE = Shader3D.propertyNameToID("u_Exposure");
  20804. class UnlitMaterial extends Material {
  20805. constructor() {
  20806. super();
  20807. this._albedoColor = new Vector4(1.0, 1.0, 1.0, 1.0);
  20808. this._albedoIntensity = 1.0;
  20809. this._enableVertexColor = false;
  20810. this.setShaderName("Unlit");
  20811. this._shaderValues.setVector(UnlitMaterial.ALBEDOCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  20812. this.renderMode = UnlitMaterial.RENDERMODE_OPAQUE;
  20813. }
  20814. static __initDefine__() {
  20815. UnlitMaterial.SHADERDEFINE_ALBEDOTEXTURE = Shader3D.getDefineByName("ALBEDOTEXTURE");
  20816. UnlitMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  20817. UnlitMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR = Shader3D.getDefineByName("ENABLEVERTEXCOLOR");
  20818. }
  20819. get _ColorR() {
  20820. return this._albedoColor.x;
  20821. }
  20822. set _ColorR(value) {
  20823. this._albedoColor.x = value;
  20824. this.albedoColor = this._albedoColor;
  20825. }
  20826. get _ColorG() {
  20827. return this._albedoColor.y;
  20828. }
  20829. set _ColorG(value) {
  20830. this._albedoColor.y = value;
  20831. this.albedoColor = this._albedoColor;
  20832. }
  20833. get _ColorB() {
  20834. return this._albedoColor.z;
  20835. }
  20836. set _ColorB(value) {
  20837. this._albedoColor.z = value;
  20838. this.albedoColor = this._albedoColor;
  20839. }
  20840. get _ColorA() {
  20841. return this._albedoColor.w;
  20842. }
  20843. set _ColorA(value) {
  20844. this._albedoColor.w = value;
  20845. this.albedoColor = this._albedoColor;
  20846. }
  20847. get _Color() {
  20848. return this._shaderValues.getVector(UnlitMaterial.ALBEDOCOLOR);
  20849. }
  20850. set _Color(value) {
  20851. this.albedoColor = value;
  20852. }
  20853. get _AlbedoIntensity() {
  20854. return this._albedoIntensity;
  20855. }
  20856. set _AlbedoIntensity(value) {
  20857. if (this._albedoIntensity !== value) {
  20858. var finalAlbedo = this._shaderValues.getVector(UnlitMaterial.ALBEDOCOLOR);
  20859. Vector4.scale(this._albedoColor, value, finalAlbedo);
  20860. this._albedoIntensity = value;
  20861. this._shaderValues.setVector(UnlitMaterial.ALBEDOCOLOR, finalAlbedo);
  20862. }
  20863. }
  20864. get _MainTex_STX() {
  20865. return this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET).x;
  20866. }
  20867. set _MainTex_STX(x) {
  20868. var tilOff = this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET);
  20869. tilOff.x = x;
  20870. this.tilingOffset = tilOff;
  20871. }
  20872. get _MainTex_STY() {
  20873. return this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET).y;
  20874. }
  20875. set _MainTex_STY(y) {
  20876. var tilOff = this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET);
  20877. tilOff.y = y;
  20878. this.tilingOffset = tilOff;
  20879. }
  20880. get _MainTex_STZ() {
  20881. return this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET).z;
  20882. }
  20883. set _MainTex_STZ(z) {
  20884. var tilOff = this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET);
  20885. tilOff.z = z;
  20886. this.tilingOffset = tilOff;
  20887. }
  20888. get _MainTex_STW() {
  20889. return this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET).w;
  20890. }
  20891. set _MainTex_STW(w) {
  20892. var tilOff = this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET);
  20893. tilOff.w = w;
  20894. this.tilingOffset = tilOff;
  20895. }
  20896. get _MainTex_ST() {
  20897. return this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET);
  20898. }
  20899. set _MainTex_ST(value) {
  20900. this.tilingOffset = value;
  20901. }
  20902. get _Cutoff() {
  20903. return this.alphaTestValue;
  20904. }
  20905. set _Cutoff(value) {
  20906. this.alphaTestValue = value;
  20907. }
  20908. get albedoColorR() {
  20909. return this._ColorR;
  20910. }
  20911. set albedoColorR(value) {
  20912. this._ColorR = value;
  20913. }
  20914. get albedoColorG() {
  20915. return this._ColorG;
  20916. }
  20917. set albedoColorG(value) {
  20918. this._ColorG = value;
  20919. }
  20920. get albedoColorB() {
  20921. return this._ColorB;
  20922. }
  20923. set albedoColorB(value) {
  20924. this._ColorB = value;
  20925. }
  20926. get albedoColorA() {
  20927. return this._ColorA;
  20928. }
  20929. set albedoColorA(value) {
  20930. this._ColorA = value;
  20931. }
  20932. get albedoColor() {
  20933. return this._albedoColor;
  20934. }
  20935. set albedoColor(value) {
  20936. var finalAlbedo = this._shaderValues.getVector(UnlitMaterial.ALBEDOCOLOR);
  20937. Vector4.scale(value, this._albedoIntensity, finalAlbedo);
  20938. this._albedoColor = value;
  20939. this._shaderValues.setVector(UnlitMaterial.ALBEDOCOLOR, finalAlbedo);
  20940. }
  20941. get albedoIntensity() {
  20942. return this._albedoIntensity;
  20943. }
  20944. set albedoIntensity(value) {
  20945. this._AlbedoIntensity = value;
  20946. }
  20947. get albedoTexture() {
  20948. return this._shaderValues.getTexture(UnlitMaterial.ALBEDOTEXTURE);
  20949. }
  20950. set albedoTexture(value) {
  20951. if (value)
  20952. this._shaderValues.addDefine(UnlitMaterial.SHADERDEFINE_ALBEDOTEXTURE);
  20953. else
  20954. this._shaderValues.removeDefine(UnlitMaterial.SHADERDEFINE_ALBEDOTEXTURE);
  20955. this._shaderValues.setTexture(UnlitMaterial.ALBEDOTEXTURE, value);
  20956. }
  20957. get tilingOffsetX() {
  20958. return this._MainTex_STX;
  20959. }
  20960. set tilingOffsetX(x) {
  20961. this._MainTex_STX = x;
  20962. }
  20963. get tilingOffsetY() {
  20964. return this._MainTex_STY;
  20965. }
  20966. set tilingOffsetY(y) {
  20967. this._MainTex_STY = y;
  20968. }
  20969. get tilingOffsetZ() {
  20970. return this._MainTex_STZ;
  20971. }
  20972. set tilingOffsetZ(z) {
  20973. this._MainTex_STZ = z;
  20974. }
  20975. get tilingOffsetW() {
  20976. return this._MainTex_STW;
  20977. }
  20978. set tilingOffsetW(w) {
  20979. this._MainTex_STW = w;
  20980. }
  20981. get tilingOffset() {
  20982. return this._shaderValues.getVector(UnlitMaterial.TILINGOFFSET);
  20983. }
  20984. set tilingOffset(value) {
  20985. if (value) {
  20986. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  20987. this._shaderValues.addDefine(UnlitMaterial.SHADERDEFINE_TILINGOFFSET);
  20988. else
  20989. this._shaderValues.removeDefine(UnlitMaterial.SHADERDEFINE_TILINGOFFSET);
  20990. }
  20991. else {
  20992. this._shaderValues.removeDefine(UnlitMaterial.SHADERDEFINE_TILINGOFFSET);
  20993. }
  20994. this._shaderValues.setVector(UnlitMaterial.TILINGOFFSET, value);
  20995. }
  20996. get enableVertexColor() {
  20997. return this._enableVertexColor;
  20998. }
  20999. set enableVertexColor(value) {
  21000. this._enableVertexColor = value;
  21001. if (value)
  21002. this._shaderValues.addDefine(UnlitMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR);
  21003. else
  21004. this._shaderValues.removeDefine(UnlitMaterial.SHADERDEFINE_ENABLEVERTEXCOLOR);
  21005. }
  21006. set renderMode(value) {
  21007. switch (value) {
  21008. case UnlitMaterial.RENDERMODE_OPAQUE:
  21009. this.alphaTest = false;
  21010. this.renderQueue = Material.RENDERQUEUE_OPAQUE;
  21011. this.depthWrite = true;
  21012. this.cull = RenderState.CULL_BACK;
  21013. this.blend = RenderState.BLEND_DISABLE;
  21014. this.depthTest = RenderState.DEPTHTEST_LESS;
  21015. break;
  21016. case UnlitMaterial.RENDERMODE_CUTOUT:
  21017. this.renderQueue = Material.RENDERQUEUE_ALPHATEST;
  21018. this.alphaTest = true;
  21019. this.depthWrite = true;
  21020. this.cull = RenderState.CULL_BACK;
  21021. this.blend = RenderState.BLEND_DISABLE;
  21022. this.depthTest = RenderState.DEPTHTEST_LESS;
  21023. break;
  21024. case UnlitMaterial.RENDERMODE_TRANSPARENT:
  21025. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  21026. this.alphaTest = false;
  21027. this.depthWrite = false;
  21028. this.cull = RenderState.CULL_BACK;
  21029. this.blend = RenderState.BLEND_ENABLE_ALL;
  21030. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  21031. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  21032. this.depthTest = RenderState.DEPTHTEST_LESS;
  21033. break;
  21034. default:
  21035. throw new Error("UnlitMaterial : renderMode value error.");
  21036. }
  21037. }
  21038. clone() {
  21039. var dest = new UnlitMaterial();
  21040. this.cloneTo(dest);
  21041. return dest;
  21042. }
  21043. }
  21044. UnlitMaterial.RENDERMODE_OPAQUE = 0;
  21045. UnlitMaterial.RENDERMODE_CUTOUT = 1;
  21046. UnlitMaterial.RENDERMODE_TRANSPARENT = 2;
  21047. UnlitMaterial.RENDERMODE_ADDTIVE = 3;
  21048. UnlitMaterial.ALBEDOTEXTURE = Shader3D.propertyNameToID("u_AlbedoTexture");
  21049. UnlitMaterial.ALBEDOCOLOR = Shader3D.propertyNameToID("u_AlbedoColor");
  21050. UnlitMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  21051. class WaterPrimaryMaterial extends Material {
  21052. constructor() {
  21053. super();
  21054. this.setShaderName("WaterPrimary");
  21055. this._shaderValues.setVector(WaterPrimaryMaterial.HORIZONCOLOR, new Vector4(0.172, 0.463, 0.435, 0));
  21056. this._shaderValues.setNumber(WaterPrimaryMaterial.WAVESCALE, 0.15);
  21057. this._shaderValues.setVector(WaterPrimaryMaterial.WAVESPEED, new Vector4(19, 9, -16, -7));
  21058. }
  21059. static __initDefine__() {
  21060. WaterPrimaryMaterial.SHADERDEFINE_MAINTEXTURE = Shader3D.getDefineByName("MAINTEXTURE");
  21061. WaterPrimaryMaterial.SHADERDEFINE_NORMALTEXTURE = Shader3D.getDefineByName("NORMALTEXTURE");
  21062. }
  21063. get horizonColor() {
  21064. return this._shaderValues.getVector(WaterPrimaryMaterial.HORIZONCOLOR);
  21065. }
  21066. set horizonColor(value) {
  21067. this._shaderValues.setVector(WaterPrimaryMaterial.HORIZONCOLOR, value);
  21068. }
  21069. get mainTexture() {
  21070. return this._shaderValues.getTexture(WaterPrimaryMaterial.MAINTEXTURE);
  21071. }
  21072. set mainTexture(value) {
  21073. if (value)
  21074. this._shaderValues.addDefine(WaterPrimaryMaterial.SHADERDEFINE_MAINTEXTURE);
  21075. else
  21076. this._shaderValues.removeDefine(WaterPrimaryMaterial.SHADERDEFINE_MAINTEXTURE);
  21077. this._shaderValues.setTexture(WaterPrimaryMaterial.MAINTEXTURE, value);
  21078. }
  21079. get normalTexture() {
  21080. return this._shaderValues.getTexture(WaterPrimaryMaterial.NORMALTEXTURE);
  21081. }
  21082. set normalTexture(value) {
  21083. if (value)
  21084. this._shaderValues.addDefine(WaterPrimaryMaterial.SHADERDEFINE_NORMALTEXTURE);
  21085. else
  21086. this._shaderValues.removeDefine(WaterPrimaryMaterial.SHADERDEFINE_NORMALTEXTURE);
  21087. this._shaderValues.setTexture(WaterPrimaryMaterial.NORMALTEXTURE, value);
  21088. }
  21089. get waveScale() {
  21090. return this._shaderValues.getNumber(WaterPrimaryMaterial.WAVESCALE);
  21091. }
  21092. set waveScale(value) {
  21093. this._shaderValues.setNumber(WaterPrimaryMaterial.WAVESCALE, value);
  21094. }
  21095. get waveSpeed() {
  21096. return this._shaderValues.getVector(WaterPrimaryMaterial.WAVESPEED);
  21097. }
  21098. set waveSpeed(value) {
  21099. this._shaderValues.setVector(WaterPrimaryMaterial.WAVESPEED, value);
  21100. }
  21101. clone() {
  21102. var dest = new WaterPrimaryMaterial();
  21103. this.cloneTo(dest);
  21104. return dest;
  21105. }
  21106. }
  21107. WaterPrimaryMaterial.HORIZONCOLOR = Shader3D.propertyNameToID("u_HorizonColor");
  21108. WaterPrimaryMaterial.MAINTEXTURE = Shader3D.propertyNameToID("u_MainTexture");
  21109. WaterPrimaryMaterial.NORMALTEXTURE = Shader3D.propertyNameToID("u_NormalTexture");
  21110. WaterPrimaryMaterial.WAVESCALE = Shader3D.propertyNameToID("u_WaveScale");
  21111. WaterPrimaryMaterial.WAVESPEED = Shader3D.propertyNameToID("u_WaveSpeed");
  21112. class MeshSprite3DShaderDeclaration {
  21113. }
  21114. class MeshRenderer extends BaseRender {
  21115. constructor(owner) {
  21116. super(owner);
  21117. this._revertStaticBatchDefineUV1 = false;
  21118. this._projectionViewWorldMatrix = new Matrix4x4();
  21119. }
  21120. _createRenderElement() {
  21121. return new SubMeshRenderElement();
  21122. }
  21123. _onMeshChange(mesh) {
  21124. if (mesh) {
  21125. var count = mesh.subMeshCount;
  21126. this._renderElements.length = count;
  21127. for (var i = 0; i < count; i++) {
  21128. var renderElement = this._renderElements[i];
  21129. if (!renderElement) {
  21130. var material = this.sharedMaterials[i];
  21131. renderElement = this._renderElements[i] = this._createRenderElement();
  21132. renderElement.setTransform(this._owner._transform);
  21133. renderElement.render = this;
  21134. renderElement.material = material ? material : BlinnPhongMaterial.defaultMaterial;
  21135. }
  21136. renderElement.setGeometry(mesh.getSubMesh(i));
  21137. }
  21138. }
  21139. else {
  21140. this._renderElements.length = 0;
  21141. }
  21142. this._boundsChange = true;
  21143. }
  21144. _calculateBoundingBox() {
  21145. var sharedMesh = this._owner.meshFilter.sharedMesh;
  21146. if (sharedMesh) {
  21147. var worldMat = this._owner.transform.worldMatrix;
  21148. sharedMesh.bounds._tranform(worldMat, this._bounds);
  21149. }
  21150. }
  21151. _needRender(boundFrustum, context) {
  21152. if (boundFrustum)
  21153. return boundFrustum.intersects(this.bounds._getBoundBox());
  21154. else
  21155. return true;
  21156. }
  21157. _renderUpdate(context, transform) {
  21158. this._applyLightMapParams();
  21159. var element = context.renderElement;
  21160. switch (element.renderType) {
  21161. case RenderElement.RENDERTYPE_NORMAL:
  21162. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, transform.worldMatrix);
  21163. break;
  21164. case RenderElement.RENDERTYPE_STATICBATCH:
  21165. if (transform)
  21166. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, transform.worldMatrix);
  21167. else
  21168. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, Matrix4x4.DEFAULT);
  21169. if (!this._shaderValues.hasDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_UV1)) {
  21170. this._shaderValues.addDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_UV1);
  21171. this._revertStaticBatchDefineUV1 = true;
  21172. }
  21173. else {
  21174. this._revertStaticBatchDefineUV1 = false;
  21175. }
  21176. this._shaderValues.setVector(RenderableSprite3D.LIGHTMAPSCALEOFFSET, BaseRender._defaultLightmapScaleOffset);
  21177. break;
  21178. case RenderElement.RENDERTYPE_VERTEXBATCH:
  21179. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, Matrix4x4.DEFAULT);
  21180. break;
  21181. case RenderElement.RENDERTYPE_INSTANCEBATCH:
  21182. var worldMatrixData = SubMeshInstanceBatch.instance.instanceWorldMatrixData;
  21183. var insBatches = element.instanceBatchElementList;
  21184. var elements = insBatches.elements;
  21185. var count = insBatches.length;
  21186. for (var i = 0; i < count; i++)
  21187. worldMatrixData.set(elements[i]._transform.worldMatrix.elements, i * 16);
  21188. var worldBuffer = SubMeshInstanceBatch.instance.instanceWorldMatrixBuffer;
  21189. worldBuffer.orphanStorage();
  21190. worldBuffer.setData(worldMatrixData.buffer, 0, 0, count * 16 * 4);
  21191. this._shaderValues.addDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_GPU_INSTANCE);
  21192. break;
  21193. }
  21194. if (!this._probReflection)
  21195. return;
  21196. if (this._reflectionMode == exports.ReflectionProbeMode.off) {
  21197. this._shaderValues.removeDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_SPECCUBE_BOX_PROJECTION);
  21198. this._shaderValues.setVector(RenderableSprite3D.REFLECTIONCUBE_HDR_PARAMS, ReflectionProbe.defaultTextureHDRDecodeValues);
  21199. this._shaderValues.setTexture(RenderableSprite3D.REFLECTIONTEXTURE, TextureCube.blackTexture);
  21200. }
  21201. else {
  21202. if (!this._probReflection.boxProjection) {
  21203. this._shaderValues.removeDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_SPECCUBE_BOX_PROJECTION);
  21204. }
  21205. else {
  21206. this._shaderValues.addDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_SPECCUBE_BOX_PROJECTION);
  21207. this._shaderValues.setVector3(RenderableSprite3D.REFLECTIONCUBE_PROBEPOSITION, this._probReflection.probePosition);
  21208. this._shaderValues.setVector3(RenderableSprite3D.REFLECTIONCUBE_PROBEBOXMAX, this._probReflection.boundsMax);
  21209. this._shaderValues.setVector3(RenderableSprite3D.REFLECTIONCUBE_PROBEBOXMIN, this._probReflection.boundsMin);
  21210. }
  21211. this._shaderValues.setTexture(RenderableSprite3D.REFLECTIONTEXTURE, this._probReflection.reflectionTexture);
  21212. this._shaderValues.setVector(RenderableSprite3D.REFLECTIONCUBE_HDR_PARAMS, this._probReflection.reflectionHDRParams);
  21213. }
  21214. }
  21215. _renderUpdateWithCamera(context, transform) {
  21216. var projectionView = context.projectionViewMatrix;
  21217. if (projectionView) {
  21218. var element = context.renderElement;
  21219. switch (element.renderType) {
  21220. case RenderElement.RENDERTYPE_NORMAL:
  21221. case RenderElement.RENDERTYPE_STATICBATCH:
  21222. case RenderElement.RENDERTYPE_VERTEXBATCH:
  21223. if (transform) {
  21224. Matrix4x4.multiply(projectionView, transform.worldMatrix, this._projectionViewWorldMatrix);
  21225. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, this._projectionViewWorldMatrix);
  21226. }
  21227. else {
  21228. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, projectionView);
  21229. }
  21230. break;
  21231. case RenderElement.RENDERTYPE_INSTANCEBATCH:
  21232. var mvpMatrixData = SubMeshInstanceBatch.instance.instanceMVPMatrixData;
  21233. var insBatches = element.instanceBatchElementList;
  21234. var elements = insBatches.elements;
  21235. var count = insBatches.length;
  21236. for (var i = 0; i < count; i++) {
  21237. var worldMat = elements[i]._transform.worldMatrix;
  21238. Utils3D.mulMatrixByArray(projectionView.elements, 0, worldMat.elements, 0, mvpMatrixData, i * 16);
  21239. }
  21240. var mvpBuffer = SubMeshInstanceBatch.instance.instanceMVPMatrixBuffer;
  21241. mvpBuffer.orphanStorage();
  21242. mvpBuffer.setData(mvpMatrixData.buffer, 0, 0, count * 16 * 4);
  21243. break;
  21244. }
  21245. }
  21246. }
  21247. _revertBatchRenderUpdate(context) {
  21248. var element = context.renderElement;
  21249. switch (element.renderType) {
  21250. case RenderElement.RENDERTYPE_STATICBATCH:
  21251. if (this._revertStaticBatchDefineUV1)
  21252. this._shaderValues.removeDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_UV1);
  21253. this._shaderValues.setVector(RenderableSprite3D.LIGHTMAPSCALEOFFSET, this.lightmapScaleOffset);
  21254. break;
  21255. case RenderElement.RENDERTYPE_INSTANCEBATCH:
  21256. this._shaderValues.removeDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_GPU_INSTANCE);
  21257. break;
  21258. }
  21259. }
  21260. _destroy() {
  21261. (this._isPartOfStaticBatch) && (MeshRenderStaticBatchManager.instance._removeRenderSprite(this._owner));
  21262. super._destroy();
  21263. }
  21264. }
  21265. class MeshFilter {
  21266. constructor(owner) {
  21267. this._owner = owner;
  21268. }
  21269. get sharedMesh() {
  21270. return this._sharedMesh;
  21271. }
  21272. set sharedMesh(value) {
  21273. if (this._sharedMesh !== value) {
  21274. var defineDatas = this._owner._render._shaderValues;
  21275. var lastValue = this._sharedMesh;
  21276. if (lastValue) {
  21277. lastValue._removeReference();
  21278. this._getMeshDefine(lastValue, MeshFilter._meshVerticeDefine);
  21279. for (var i = 0, n = MeshFilter._meshVerticeDefine.length; i < n; i++)
  21280. defineDatas.removeDefine(MeshFilter._meshVerticeDefine[i]);
  21281. }
  21282. if (value) {
  21283. value._addReference();
  21284. this._getMeshDefine(value, MeshFilter._meshVerticeDefine);
  21285. for (var i = 0, n = MeshFilter._meshVerticeDefine.length; i < n; i++)
  21286. defineDatas.addDefine(MeshFilter._meshVerticeDefine[i]);
  21287. }
  21288. this._owner._render._onMeshChange(value);
  21289. this._sharedMesh = value;
  21290. }
  21291. }
  21292. _getMeshDefine(mesh, out) {
  21293. out.length = 0;
  21294. var define;
  21295. for (var i = 0, n = mesh._subMeshes.length; i < n; i++) {
  21296. var subMesh = mesh.getSubMesh(i);
  21297. var vertexElements = subMesh._vertexBuffer._vertexDeclaration._vertexElements;
  21298. for (var j = 0, m = vertexElements.length; j < m; j++) {
  21299. var vertexElement = vertexElements[j];
  21300. var name = vertexElement._elementUsage;
  21301. switch (name) {
  21302. case VertexMesh.MESH_COLOR0:
  21303. out.push(MeshSprite3DShaderDeclaration.SHADERDEFINE_COLOR);
  21304. break;
  21305. case VertexMesh.MESH_TEXTURECOORDINATE0:
  21306. out.push(MeshSprite3DShaderDeclaration.SHADERDEFINE_UV0);
  21307. break;
  21308. case VertexMesh.MESH_TEXTURECOORDINATE1:
  21309. out.push(MeshSprite3DShaderDeclaration.SHADERDEFINE_UV1);
  21310. break;
  21311. }
  21312. }
  21313. }
  21314. return define;
  21315. }
  21316. destroy() {
  21317. this._owner = null;
  21318. (this._sharedMesh) && (this._sharedMesh._removeReference(), this._sharedMesh = null);
  21319. }
  21320. }
  21321. MeshFilter._meshVerticeDefine = [];
  21322. class SubMeshDynamicBatch extends GeometryElement {
  21323. constructor() {
  21324. super();
  21325. this._bufferState = new BufferState();
  21326. var gl = Laya.LayaGL.instance;
  21327. var maxVerDec = VertexMesh.getVertexDeclaration("POSITION,NORMAL,COLOR,UV,UV1,TANGENT");
  21328. var maxByteCount = maxVerDec.vertexStride * SubMeshDynamicBatch.maxIndicesCount;
  21329. this._vertices = new Float32Array(maxByteCount / 4);
  21330. this._vertexBuffer = new VertexBuffer3D(maxByteCount, gl.DYNAMIC_DRAW);
  21331. this._indices = new Int16Array(SubMeshDynamicBatch.maxIndicesCount);
  21332. this._indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt16, this._indices.length, gl.DYNAMIC_DRAW);
  21333. var memorySize = this._vertexBuffer._byteLength + this._indexBuffer._byteLength;
  21334. Laya.Resource._addMemory(memorySize, memorySize);
  21335. }
  21336. static __init__() {
  21337. SubMeshDynamicBatch.instance = new SubMeshDynamicBatch();
  21338. }
  21339. _getBatchVertices(vertexDeclaration, batchVertices, batchOffset, transform, element, subMesh) {
  21340. var vertexFloatCount = vertexDeclaration.vertexStride / 4;
  21341. var oriVertexes = subMesh._vertexBuffer.getFloat32Data();
  21342. var lightmapScaleOffset = element.render.lightmapScaleOffset;
  21343. var multiSubMesh = element._dynamicMultiSubMesh;
  21344. var vertexCount = element._dynamicVertexCount;
  21345. element._computeWorldPositionsAndNormals(this._positionOffset, this._normalOffset, multiSubMesh, vertexCount);
  21346. var worldPositions = element._dynamicWorldPositions;
  21347. var worldNormals = element._dynamicWorldNormals;
  21348. var indices = subMesh._indices;
  21349. for (var i = 0; i < vertexCount; i++) {
  21350. var index = multiSubMesh ? indices[i] : i;
  21351. var oriOffset = index * vertexFloatCount;
  21352. var bakeOffset = (i + batchOffset) * vertexFloatCount;
  21353. var oriOff = i * 3;
  21354. var bakOff = bakeOffset + this._positionOffset;
  21355. batchVertices[bakOff] = worldPositions[oriOff];
  21356. batchVertices[bakOff + 1] = worldPositions[oriOff + 1];
  21357. batchVertices[bakOff + 2] = worldPositions[oriOff + 2];
  21358. if (this._normalOffset !== -1) {
  21359. bakOff = bakeOffset + this._normalOffset;
  21360. batchVertices[bakOff] = worldNormals[oriOff];
  21361. batchVertices[bakOff + 1] = worldNormals[oriOff + 1];
  21362. batchVertices[bakOff + 2] = worldNormals[oriOff + 2];
  21363. }
  21364. if (this._colorOffset !== -1) {
  21365. bakOff = bakeOffset + this._colorOffset;
  21366. oriOff = oriOffset + this._colorOffset;
  21367. batchVertices[bakOff] = oriVertexes[oriOff];
  21368. batchVertices[bakOff + 1] = oriVertexes[oriOff + 1];
  21369. batchVertices[bakOff + 2] = oriVertexes[oriOff + 2];
  21370. batchVertices[bakOff + 3] = oriVertexes[oriOff + 3];
  21371. }
  21372. if (this._uv0Offset !== -1) {
  21373. bakOff = bakeOffset + this._uv0Offset;
  21374. oriOff = oriOffset + this._uv0Offset;
  21375. batchVertices[bakOff] = oriVertexes[oriOff];
  21376. batchVertices[bakOff + 1] = oriVertexes[oriOff + 1];
  21377. }
  21378. if (this._sTangentOffset !== -1) {
  21379. bakOff = bakeOffset + this._sTangentOffset;
  21380. oriOff = oriOffset + this._sTangentOffset;
  21381. batchVertices[bakOff] = oriVertexes[oriOff];
  21382. batchVertices[bakOff + 1] = oriVertexes[oriOff + 1];
  21383. batchVertices[bakOff + 2] = oriVertexes[oriOff + 2];
  21384. batchVertices[bakOff + 3] = oriVertexes[oriOff + 3];
  21385. bakOff = bakeOffset + this._sTangentOffset;
  21386. oriOff = oriOffset + this._sTangentOffset;
  21387. batchVertices[bakOff] = oriVertexes[oriOff];
  21388. batchVertices[bakOff + 1] = oriVertexes[oriOff + 1];
  21389. batchVertices[bakOff + 2] = oriVertexes[oriOff + 2];
  21390. batchVertices[bakOff + 3] = oriVertexes[oriOff + 3];
  21391. }
  21392. }
  21393. }
  21394. _getBatchIndices(batchIndices, batchIndexCount, batchVertexCount, transform, subMesh, multiSubMesh) {
  21395. var subIndices = subMesh._indices;
  21396. var k, m, batchOffset;
  21397. var isInvert = transform._isFrontFaceInvert;
  21398. if (multiSubMesh) {
  21399. if (isInvert) {
  21400. for (k = 0, m = subIndices.length; k < m; k += 3) {
  21401. batchOffset = batchIndexCount + k;
  21402. var index = batchVertexCount + k;
  21403. batchIndices[batchOffset] = index;
  21404. batchIndices[batchOffset + 1] = index + 2;
  21405. batchIndices[batchOffset + 2] = index + 1;
  21406. }
  21407. }
  21408. else {
  21409. for (k = 0, m = subIndices.length; k < m; k += 3) {
  21410. batchOffset = batchIndexCount + k;
  21411. index = batchVertexCount + k;
  21412. batchIndices[batchOffset] = index;
  21413. batchIndices[batchOffset + 1] = index + 1;
  21414. batchIndices[batchOffset + 2] = index + 2;
  21415. }
  21416. }
  21417. }
  21418. else {
  21419. if (isInvert) {
  21420. for (k = 0, m = subIndices.length; k < m; k += 3) {
  21421. batchOffset = batchIndexCount + k;
  21422. batchIndices[batchOffset] = batchVertexCount + subIndices[k];
  21423. batchIndices[batchOffset + 1] = batchVertexCount + subIndices[k + 2];
  21424. batchIndices[batchOffset + 2] = batchVertexCount + subIndices[k + 1];
  21425. }
  21426. }
  21427. else {
  21428. for (k = 0, m = subIndices.length; k < m; k += 3) {
  21429. batchOffset = batchIndexCount + k;
  21430. batchIndices[batchOffset] = batchVertexCount + subIndices[k];
  21431. batchIndices[batchOffset + 1] = batchVertexCount + subIndices[k + 1];
  21432. batchIndices[batchOffset + 2] = batchVertexCount + subIndices[k + 2];
  21433. }
  21434. }
  21435. }
  21436. }
  21437. _flush(vertexCount, indexCount) {
  21438. var gl = Laya.LayaGL.instance;
  21439. this._vertexBuffer.setData(this._vertices.buffer, 0, 0, vertexCount * (this._bufferState.vertexDeclaration.vertexStride));
  21440. this._indexBuffer.setData(this._indices, 0, 0, indexCount);
  21441. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, 0);
  21442. }
  21443. _prepareRender(state) {
  21444. var element = state.renderElement;
  21445. var vertexDeclaration = element.vertexBatchVertexDeclaration;
  21446. this._bufferState = ILaya3D.MeshRenderDynamicBatchManager.instance._getBufferState(vertexDeclaration);
  21447. this._positionOffset = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_POSITION0)._offset / 4;
  21448. var normalElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_NORMAL0);
  21449. this._normalOffset = normalElement ? normalElement._offset / 4 : -1;
  21450. var colorElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_COLOR0);
  21451. this._colorOffset = colorElement ? colorElement._offset / 4 : -1;
  21452. var uv0Element = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TEXTURECOORDINATE0);
  21453. this._uv0Offset = uv0Element ? uv0Element._offset / 4 : -1;
  21454. var uv1Element = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TEXTURECOORDINATE1);
  21455. this._uv1Offset = uv1Element ? uv1Element._offset / 4 : -1;
  21456. var tangentElement = vertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TANGENT0);
  21457. this._sTangentOffset = tangentElement ? tangentElement._offset / 4 : -1;
  21458. return true;
  21459. }
  21460. _render(context) {
  21461. this._bufferState.bind();
  21462. var element = context.renderElement;
  21463. var vertexDeclaration = element.vertexBatchVertexDeclaration;
  21464. var batchElements = element.vertexBatchElementList;
  21465. var batchVertexCount = 0;
  21466. var batchIndexCount = 0;
  21467. var floatStride = vertexDeclaration.vertexStride / 4;
  21468. var renderBatchCount = 0;
  21469. var elementCount = batchElements.length;
  21470. var elements = batchElements.elements;
  21471. for (var i = 0; i < elementCount; i++) {
  21472. var subElement = elements[i];
  21473. var subMesh = subElement._geometry;
  21474. var indexCount = subMesh._indexCount;
  21475. if (batchIndexCount + indexCount > SubMeshDynamicBatch.maxIndicesCount) {
  21476. this._flush(batchVertexCount, batchIndexCount);
  21477. renderBatchCount++;
  21478. Laya.Stat.trianglesFaces += batchIndexCount / 3;
  21479. batchVertexCount = batchIndexCount = 0;
  21480. }
  21481. var transform = subElement._transform;
  21482. this._getBatchVertices(vertexDeclaration, this._vertices, batchVertexCount, transform, subElement, subMesh);
  21483. this._getBatchIndices(this._indices, batchIndexCount, batchVertexCount, transform, subMesh, subElement._dynamicMultiSubMesh);
  21484. batchVertexCount += subElement._dynamicVertexCount;
  21485. batchIndexCount += indexCount;
  21486. }
  21487. this._flush(batchVertexCount, batchIndexCount);
  21488. renderBatchCount++;
  21489. Laya.Stat.renderBatches += renderBatchCount;
  21490. Laya.Stat.savedRenderBatches += elementCount - renderBatchCount;
  21491. Laya.Stat.trianglesFaces += batchIndexCount / 3;
  21492. }
  21493. }
  21494. SubMeshDynamicBatch.maxAllowVertexCount = 10;
  21495. SubMeshDynamicBatch.maxAllowAttribueCount = 900;
  21496. SubMeshDynamicBatch.maxIndicesCount = 32000;
  21497. class MeshRenderDynamicBatchManager extends DynamicBatchManager {
  21498. constructor() {
  21499. super();
  21500. this._instanceBatchOpaqueMarks = [];
  21501. this._vertexBatchOpaqueMarks = [];
  21502. this._cacheBufferStates = [];
  21503. this._updateCountMark = 0;
  21504. }
  21505. getInstanceBatchOpaquaMark(receiveShadow, materialID, subMeshID, invertFace) {
  21506. var instanceReceiveShadowMarks = (this._instanceBatchOpaqueMarks[receiveShadow ? 0 : 1]) || (this._instanceBatchOpaqueMarks[receiveShadow ? 0 : 1] = []);
  21507. var instanceMaterialMarks = (instanceReceiveShadowMarks[materialID]) || (instanceReceiveShadowMarks[materialID] = []);
  21508. var instancSubMeshMarks = (instanceMaterialMarks[subMeshID]) || (instanceMaterialMarks[subMeshID] = []);
  21509. return instancSubMeshMarks[invertFace ? 1 : 0] || (instancSubMeshMarks[invertFace ? 1 : 0] = new BatchMark());
  21510. }
  21511. getVertexBatchOpaquaMark(lightMapIndex, receiveShadow, materialID, verDecID) {
  21512. var dynLightMapMarks = (this._vertexBatchOpaqueMarks[lightMapIndex]) || (this._vertexBatchOpaqueMarks[lightMapIndex] = []);
  21513. var dynReceiveShadowMarks = (dynLightMapMarks[receiveShadow ? 0 : 1]) || (dynLightMapMarks[receiveShadow ? 0 : 1] = []);
  21514. var dynMaterialMarks = (dynReceiveShadowMarks[materialID]) || (dynReceiveShadowMarks[materialID] = []);
  21515. return dynMaterialMarks[verDecID] || (dynMaterialMarks[verDecID] = new BatchMark());
  21516. }
  21517. _getBufferState(vertexDeclaration) {
  21518. var bufferState = this._cacheBufferStates[vertexDeclaration.id];
  21519. if (!bufferState) {
  21520. var instance = SubMeshDynamicBatch.instance;
  21521. bufferState = new BufferState();
  21522. bufferState.bind();
  21523. var vertexBuffer = instance._vertexBuffer;
  21524. vertexBuffer.vertexDeclaration = vertexDeclaration;
  21525. bufferState.applyVertexBuffer(vertexBuffer);
  21526. bufferState.applyIndexBuffer(instance._indexBuffer);
  21527. bufferState.unBind();
  21528. this._cacheBufferStates[vertexDeclaration.id] = bufferState;
  21529. }
  21530. return bufferState;
  21531. }
  21532. _getBatchRenderElementFromPool() {
  21533. var renderElement = this._batchRenderElementPool[this._batchRenderElementPoolIndex++];
  21534. if (!renderElement) {
  21535. renderElement = new SubMeshRenderElement();
  21536. this._batchRenderElementPool[this._batchRenderElementPoolIndex - 1] = renderElement;
  21537. renderElement.vertexBatchElementList = new SingletonList();
  21538. renderElement.instanceBatchElementList = new SingletonList();
  21539. }
  21540. return renderElement;
  21541. }
  21542. _clear() {
  21543. super._clear();
  21544. this._updateCountMark++;
  21545. }
  21546. }
  21547. MeshRenderDynamicBatchManager.instance = new MeshRenderDynamicBatchManager();
  21548. class MeshSprite3D extends RenderableSprite3D {
  21549. constructor(mesh = null, name = null) {
  21550. super(name);
  21551. this._meshFilter = new MeshFilter(this);
  21552. this._render = new MeshRenderer(this);
  21553. (mesh) && (this._meshFilter.sharedMesh = mesh);
  21554. }
  21555. static __init__() {
  21556. MeshSprite3DShaderDeclaration.SHADERDEFINE_UV0 = Shader3D.getDefineByName("UV");
  21557. MeshSprite3DShaderDeclaration.SHADERDEFINE_COLOR = Shader3D.getDefineByName("COLOR");
  21558. MeshSprite3DShaderDeclaration.SHADERDEFINE_UV1 = Shader3D.getDefineByName("UV1");
  21559. MeshSprite3DShaderDeclaration.SHADERDEFINE_GPU_INSTANCE = Shader3D.getDefineByName("GPU_INSTANCE");
  21560. MeshSprite3DShaderDeclaration.SHADERDEFINE_SPECCUBE_BOX_PROJECTION = Shader3D.getDefineByName("SPECCUBE_BOX_PROJECTION");
  21561. StaticBatchManager._registerManager(MeshRenderStaticBatchManager.instance);
  21562. DynamicBatchManager._registerManager(MeshRenderDynamicBatchManager.instance);
  21563. }
  21564. get meshFilter() {
  21565. return this._meshFilter;
  21566. }
  21567. get meshRenderer() {
  21568. return this._render;
  21569. }
  21570. _parse(data, spriteMap) {
  21571. super._parse(data, spriteMap);
  21572. var render = this.meshRenderer;
  21573. var lightmapIndex = data.lightmapIndex;
  21574. (lightmapIndex != null) && (render.lightmapIndex = lightmapIndex);
  21575. var lightmapScaleOffsetArray = data.lightmapScaleOffset;
  21576. (lightmapScaleOffsetArray) && (render.lightmapScaleOffset = new Vector4(lightmapScaleOffsetArray[0], lightmapScaleOffsetArray[1], lightmapScaleOffsetArray[2], lightmapScaleOffsetArray[3]));
  21577. (data.meshPath != undefined) && (this.meshFilter.sharedMesh = Laya.Loader.getRes(data.meshPath));
  21578. (data.enableRender != undefined) && (render.enable = data.enableRender);
  21579. (data.receiveShadows != undefined) && (render.receiveShadow = data.receiveShadows);
  21580. (data.castShadow != undefined) && (render.castShadow = data.castShadow);
  21581. var materials = data.materials;
  21582. if (materials) {
  21583. var sharedMaterials = render.sharedMaterials;
  21584. var materialCount = materials.length;
  21585. sharedMaterials.length = materialCount;
  21586. for (var i = 0; i < materialCount; i++) {
  21587. sharedMaterials[i] = Laya.Loader.getRes(materials[i].path);
  21588. }
  21589. render.sharedMaterials = sharedMaterials;
  21590. }
  21591. }
  21592. _addToInitStaticBatchManager() {
  21593. if (this.meshFilter.sharedMesh)
  21594. MeshRenderStaticBatchManager.instance._addBatchSprite(this);
  21595. }
  21596. _cloneTo(destObject, rootSprite, dstSprite) {
  21597. var meshSprite3D = destObject;
  21598. meshSprite3D._meshFilter.sharedMesh = this._meshFilter.sharedMesh;
  21599. var meshRender = this._render;
  21600. var destMeshRender = meshSprite3D._render;
  21601. destMeshRender.enable = meshRender.enable;
  21602. destMeshRender.sharedMaterials = meshRender.sharedMaterials;
  21603. destMeshRender.castShadow = meshRender.castShadow;
  21604. var lightmapScaleOffset = meshRender.lightmapScaleOffset;
  21605. lightmapScaleOffset && (destMeshRender.lightmapScaleOffset = lightmapScaleOffset.clone());
  21606. destMeshRender.lightmapIndex = meshRender.lightmapIndex;
  21607. destMeshRender.receiveShadow = meshRender.receiveShadow;
  21608. destMeshRender.sortingFudge = meshRender.sortingFudge;
  21609. super._cloneTo(destObject, rootSprite, dstSprite);
  21610. }
  21611. destroy(destroyChild = true) {
  21612. if (this.destroyed)
  21613. return;
  21614. super.destroy(destroyChild);
  21615. this._meshFilter.destroy();
  21616. }
  21617. _create() {
  21618. return new MeshSprite3D();
  21619. }
  21620. }
  21621. class GradientMode {
  21622. }
  21623. GradientMode.Blend = 0;
  21624. GradientMode.Fixed = 1;
  21625. class Gradient {
  21626. constructor(maxColorRGBKeyCount, maxColorAlphaKeyCount) {
  21627. this._mode = 0;
  21628. this._maxColorRGBKeysCount = 0;
  21629. this._maxColorAlphaKeysCount = 0;
  21630. this._colorRGBKeysCount = 0;
  21631. this._colorAlphaKeysCount = 0;
  21632. this._alphaElements = null;
  21633. this._rgbElements = null;
  21634. this._maxColorRGBKeysCount = maxColorRGBKeyCount;
  21635. this._maxColorAlphaKeysCount = maxColorAlphaKeyCount;
  21636. this._rgbElements = new Float32Array(maxColorRGBKeyCount * 4);
  21637. this._alphaElements = new Float32Array(maxColorAlphaKeyCount * 2);
  21638. }
  21639. get mode() {
  21640. return this._mode;
  21641. }
  21642. set mode(value) {
  21643. this._mode = value;
  21644. }
  21645. get colorRGBKeysCount() {
  21646. return this._colorRGBKeysCount;
  21647. }
  21648. get colorAlphaKeysCount() {
  21649. return this._colorAlphaKeysCount;
  21650. }
  21651. get maxColorRGBKeysCount() {
  21652. return this._maxColorRGBKeysCount;
  21653. }
  21654. get maxColorAlphaKeysCount() {
  21655. return this._maxColorAlphaKeysCount;
  21656. }
  21657. addColorRGB(key, value) {
  21658. if (this._colorRGBKeysCount < this._maxColorRGBKeysCount) {
  21659. var offset = this._colorRGBKeysCount * 4;
  21660. this._rgbElements[offset] = key;
  21661. this._rgbElements[offset + 1] = value.r;
  21662. this._rgbElements[offset + 2] = value.g;
  21663. this._rgbElements[offset + 3] = value.b;
  21664. this._colorRGBKeysCount++;
  21665. }
  21666. else {
  21667. console.warn("Gradient:warning:data count must lessEqual than " + this._maxColorRGBKeysCount);
  21668. }
  21669. }
  21670. addColorAlpha(key, value) {
  21671. if (this._colorAlphaKeysCount < this._maxColorAlphaKeysCount) {
  21672. var offset = this._colorAlphaKeysCount * 2;
  21673. this._alphaElements[offset] = key;
  21674. this._alphaElements[offset + 1] = value;
  21675. this._colorAlphaKeysCount++;
  21676. }
  21677. else {
  21678. console.warn("Gradient:warning:data count must lessEqual than " + this._maxColorAlphaKeysCount);
  21679. }
  21680. }
  21681. updateColorRGB(index, key, value) {
  21682. if (index < this._colorRGBKeysCount) {
  21683. var offset = index * 4;
  21684. this._rgbElements[offset] = key;
  21685. this._rgbElements[offset + 1] = value.r;
  21686. this._rgbElements[offset + 2] = value.g;
  21687. this._rgbElements[offset + 3] = value.b;
  21688. }
  21689. else {
  21690. console.warn("Gradient:warning:index must lessEqual than colorRGBKeysCount:" + this._colorRGBKeysCount);
  21691. }
  21692. }
  21693. updateColorAlpha(index, key, value) {
  21694. if (index < this._colorAlphaKeysCount) {
  21695. var offset = index * 2;
  21696. this._alphaElements[offset] = key;
  21697. this._alphaElements[offset + 1] = value;
  21698. }
  21699. else {
  21700. console.warn("Gradient:warning:index must lessEqual than colorAlphaKeysCount:" + this._colorAlphaKeysCount);
  21701. }
  21702. }
  21703. evaluateColorRGB(lerpFactor, out, startSearchIndex = 0, reverseSearch = false) {
  21704. lerpFactor = Math.min(Math.max(lerpFactor, 0.0), 1.0);
  21705. var rgbElements = this._rgbElements;
  21706. var curIndex = startSearchIndex;
  21707. if (reverseSearch) {
  21708. for (var i = curIndex; i >= 0; i--) {
  21709. var offset = i * 4;
  21710. var left = rgbElements[offset];
  21711. if (lerpFactor === left) {
  21712. out.r = rgbElements[offset + 1];
  21713. out.g = rgbElements[offset + 2];
  21714. out.b = rgbElements[offset + 3];
  21715. return curIndex;
  21716. }
  21717. switch (this._mode) {
  21718. case GradientMode.Blend:
  21719. if (lerpFactor > left) {
  21720. var right = rgbElements[offset + 4];
  21721. if (lerpFactor > right)
  21722. throw "Gradient:wrong startSearchIndex.";
  21723. var diff = right - left;
  21724. var y1 = right - lerpFactor;
  21725. var y2 = lerpFactor - left;
  21726. out.r = (y1 * rgbElements[offset + 1] + y2 * rgbElements[offset + 5]) / diff;
  21727. out.g = (y1 * rgbElements[offset + 2] + y2 * rgbElements[offset + 6]) / diff;
  21728. out.b = (y1 * rgbElements[offset + 3] + y2 * rgbElements[offset + 7]) / diff;
  21729. return curIndex;
  21730. }
  21731. else {
  21732. curIndex--;
  21733. continue;
  21734. }
  21735. case GradientMode.Fixed:
  21736. if (lerpFactor > left) {
  21737. if (lerpFactor > rgbElements[offset + 4])
  21738. throw "Gradient:wrong startSearchIndex.";
  21739. out.r = rgbElements[offset + 5];
  21740. out.g = rgbElements[offset + 6];
  21741. out.b = rgbElements[offset + 7];
  21742. return curIndex;
  21743. }
  21744. else {
  21745. curIndex--;
  21746. continue;
  21747. }
  21748. default:
  21749. throw "Gradient:unknown mode.";
  21750. }
  21751. }
  21752. }
  21753. else {
  21754. for (var i = 0, n = this._rgbElements.length; i < n; i++) {
  21755. offset = i * 4;
  21756. var right = rgbElements[offset];
  21757. if (lerpFactor === right) {
  21758. out.r = rgbElements[offset + 1];
  21759. out.g = rgbElements[offset + 2];
  21760. out.b = rgbElements[offset + 3];
  21761. return curIndex;
  21762. }
  21763. switch (this._mode) {
  21764. case GradientMode.Blend:
  21765. if (lerpFactor < right) {
  21766. var left = rgbElements[offset - 4];
  21767. if (lerpFactor < left)
  21768. throw "Gradient:wrong startSearchIndex.";
  21769. var diff = right - left;
  21770. var y1 = right - lerpFactor;
  21771. var y2 = lerpFactor - left;
  21772. out.r = (y1 * rgbElements[offset - 3] + y2 * rgbElements[offset + 1]) / diff;
  21773. out.g = (y1 * rgbElements[offset - 2] + y2 * rgbElements[offset + 2]) / diff;
  21774. out.b = (y1 * rgbElements[offset - 1] + y2 * rgbElements[offset + 3]) / diff;
  21775. return curIndex;
  21776. }
  21777. else {
  21778. curIndex++;
  21779. continue;
  21780. }
  21781. case GradientMode.Fixed:
  21782. if (lerpFactor < right) {
  21783. if (lerpFactor < rgbElements[offset - 4])
  21784. throw "Gradient:wrong startSearchIndex.";
  21785. out.r = rgbElements[offset + 1];
  21786. out.g = rgbElements[offset + 2];
  21787. out.b = rgbElements[offset + 3];
  21788. return curIndex;
  21789. }
  21790. else {
  21791. curIndex++;
  21792. continue;
  21793. }
  21794. default:
  21795. throw "Gradient:unknown mode.";
  21796. }
  21797. }
  21798. }
  21799. return curIndex;
  21800. }
  21801. evaluateColorAlpha(lerpFactor, outColor, startSearchIndex = 0, reverseSearch = false) {
  21802. lerpFactor = Math.min(Math.max(lerpFactor, 0.0), 1.0);
  21803. var alphaElements = this._alphaElements;
  21804. var curIndex = startSearchIndex;
  21805. if (reverseSearch) {
  21806. for (var i = curIndex; i >= 0; i--) {
  21807. var offset = i * 2;
  21808. var left = alphaElements[offset];
  21809. if (lerpFactor === left) {
  21810. outColor.a = alphaElements[offset + 1];
  21811. return curIndex;
  21812. }
  21813. switch (this._mode) {
  21814. case GradientMode.Blend:
  21815. if (lerpFactor > left) {
  21816. var right = alphaElements[offset + 2];
  21817. if (lerpFactor > right)
  21818. throw "Gradient:wrong startSearchIndex.";
  21819. var diff = right - left;
  21820. var x1 = right - lerpFactor;
  21821. var x2 = lerpFactor - left;
  21822. outColor.a = (x1 * alphaElements[offset + 1] + x2 * alphaElements[offset + 3]) / diff;
  21823. return curIndex;
  21824. }
  21825. else {
  21826. curIndex--;
  21827. continue;
  21828. }
  21829. case GradientMode.Fixed:
  21830. if (lerpFactor > left) {
  21831. if (lerpFactor > alphaElements[offset + 2])
  21832. throw "Gradient:wrong startSearchIndex.";
  21833. outColor.a = alphaElements[offset + 3];
  21834. return curIndex;
  21835. }
  21836. else {
  21837. curIndex--;
  21838. continue;
  21839. }
  21840. default:
  21841. throw "Gradient:unknown mode.";
  21842. }
  21843. }
  21844. }
  21845. else {
  21846. for (var i = curIndex, n = this._alphaElements.length; i < n; i++) {
  21847. var offset = i * 2;
  21848. var right = alphaElements[offset];
  21849. if (lerpFactor === right) {
  21850. outColor.a = alphaElements[offset + 1];
  21851. return curIndex;
  21852. }
  21853. switch (this._mode) {
  21854. case GradientMode.Blend:
  21855. if (lerpFactor < right) {
  21856. var left = alphaElements[offset - 2];
  21857. if (lerpFactor < left)
  21858. throw "Gradient:wrong startSearchIndex.";
  21859. var diff = right - left;
  21860. var x1 = right - lerpFactor;
  21861. var x2 = lerpFactor - left;
  21862. outColor.a = (x1 * alphaElements[offset - 1] + x2 * alphaElements[offset + 1]) / diff;
  21863. return curIndex;
  21864. }
  21865. else {
  21866. curIndex++;
  21867. continue;
  21868. }
  21869. case GradientMode.Fixed:
  21870. if (lerpFactor < right) {
  21871. if (lerpFactor < alphaElements[offset - 2])
  21872. throw "Gradient:wrong startSearchIndex.";
  21873. outColor.a = alphaElements[offset + 1];
  21874. return curIndex;
  21875. }
  21876. else {
  21877. curIndex++;
  21878. continue;
  21879. }
  21880. default:
  21881. throw "Gradient:unknown mode.";
  21882. }
  21883. }
  21884. }
  21885. return curIndex;
  21886. }
  21887. cloneTo(destObject) {
  21888. var destGradientDataColor = destObject;
  21889. var i, n;
  21890. destGradientDataColor._colorAlphaKeysCount = this._colorAlphaKeysCount;
  21891. var destAlphaElements = destGradientDataColor._alphaElements;
  21892. for (i = 0, n = this._alphaElements.length; i < n; i++)
  21893. destAlphaElements[i] = this._alphaElements[i];
  21894. destGradientDataColor._colorRGBKeysCount = this._colorRGBKeysCount;
  21895. var destRGBElements = destGradientDataColor._rgbElements;
  21896. for (i = 0, n = this._rgbElements.length; i < n; i++)
  21897. destRGBElements[i] = this._rgbElements[i];
  21898. }
  21899. clone() {
  21900. var destGradientDataColor = new Gradient(this._maxColorRGBKeysCount, this._maxColorAlphaKeysCount);
  21901. this.cloneTo(destGradientDataColor);
  21902. return destGradientDataColor;
  21903. }
  21904. }
  21905. class Burst {
  21906. constructor(time, minCount, maxCount) {
  21907. this._time = time;
  21908. this._minCount = minCount;
  21909. this._maxCount = maxCount;
  21910. }
  21911. get time() {
  21912. return this._time;
  21913. }
  21914. get minCount() {
  21915. return this._minCount;
  21916. }
  21917. get maxCount() {
  21918. return this._maxCount;
  21919. }
  21920. cloneTo(destObject) {
  21921. var destBurst = destObject;
  21922. destBurst._time = this._time;
  21923. destBurst._minCount = this._minCount;
  21924. destBurst._maxCount = this._maxCount;
  21925. }
  21926. clone() {
  21927. var destBurst = new Burst(this._time, this._minCount, this._maxCount);
  21928. this.cloneTo(destBurst);
  21929. return destBurst;
  21930. }
  21931. }
  21932. class GradientColor {
  21933. constructor() {
  21934. this._type = 0;
  21935. this._constant = null;
  21936. this._constantMin = null;
  21937. this._constantMax = null;
  21938. this._gradient = null;
  21939. this._gradientMin = null;
  21940. this._gradientMax = null;
  21941. }
  21942. static createByConstant(constant) {
  21943. var gradientColor = new GradientColor();
  21944. gradientColor._type = 0;
  21945. gradientColor._constant = constant;
  21946. return gradientColor;
  21947. }
  21948. static createByGradient(gradient) {
  21949. var gradientColor = new GradientColor();
  21950. gradientColor._type = 1;
  21951. gradientColor._gradient = gradient;
  21952. return gradientColor;
  21953. }
  21954. static createByRandomTwoConstant(minConstant, maxConstant) {
  21955. var gradientColor = new GradientColor();
  21956. gradientColor._type = 2;
  21957. gradientColor._constantMin = minConstant;
  21958. gradientColor._constantMax = maxConstant;
  21959. return gradientColor;
  21960. }
  21961. static createByRandomTwoGradient(minGradient, maxGradient) {
  21962. var gradientColor = new GradientColor();
  21963. gradientColor._type = 3;
  21964. gradientColor._gradientMin = minGradient;
  21965. gradientColor._gradientMax = maxGradient;
  21966. return gradientColor;
  21967. }
  21968. get type() {
  21969. return this._type;
  21970. }
  21971. get constant() {
  21972. return this._constant;
  21973. }
  21974. get constantMin() {
  21975. return this._constantMin;
  21976. }
  21977. get constantMax() {
  21978. return this._constantMax;
  21979. }
  21980. get gradient() {
  21981. return this._gradient;
  21982. }
  21983. get gradientMin() {
  21984. return this._gradientMin;
  21985. }
  21986. get gradientMax() {
  21987. return this._gradientMax;
  21988. }
  21989. cloneTo(destObject) {
  21990. var destGradientColor = destObject;
  21991. destGradientColor._type = this._type;
  21992. this._constant.cloneTo(destGradientColor._constant);
  21993. this._constantMin.cloneTo(destGradientColor._constantMin);
  21994. this._constantMax.cloneTo(destGradientColor._constantMax);
  21995. this._gradient.cloneTo(destGradientColor._gradient);
  21996. this._gradientMin.cloneTo(destGradientColor._gradientMin);
  21997. this._gradientMax.cloneTo(destGradientColor._gradientMax);
  21998. }
  21999. clone() {
  22000. var destGradientColor = new GradientColor();
  22001. this.cloneTo(destGradientColor);
  22002. return destGradientColor;
  22003. }
  22004. }
  22005. class ColorOverLifetime {
  22006. constructor(color) {
  22007. this._color = color;
  22008. }
  22009. get color() {
  22010. return this._color;
  22011. }
  22012. cloneTo(destObject) {
  22013. var destColorOverLifetime = destObject;
  22014. this._color.cloneTo(destColorOverLifetime._color);
  22015. destColorOverLifetime.enable = this.enable;
  22016. }
  22017. clone() {
  22018. var destColor;
  22019. switch (this._color.type) {
  22020. case 0:
  22021. destColor = GradientColor.createByConstant(this._color.constant.clone());
  22022. break;
  22023. case 1:
  22024. destColor = GradientColor.createByGradient(this._color.gradient.clone());
  22025. break;
  22026. case 2:
  22027. destColor = GradientColor.createByRandomTwoConstant(this._color.constantMin.clone(), this._color.constantMax.clone());
  22028. break;
  22029. case 3:
  22030. destColor = GradientColor.createByRandomTwoGradient(this._color.gradientMin.clone(), this._color.gradientMax.clone());
  22031. break;
  22032. }
  22033. var destColorOverLifetime = new ColorOverLifetime(destColor);
  22034. destColorOverLifetime.enable = this.enable;
  22035. return destColorOverLifetime;
  22036. }
  22037. }
  22038. class FrameOverTime {
  22039. constructor() {
  22040. this._type = 0;
  22041. this._constant = 0;
  22042. this._overTime = null;
  22043. this._constantMin = 0;
  22044. this._constantMax = 0;
  22045. this._overTimeMin = null;
  22046. this._overTimeMax = null;
  22047. }
  22048. static createByConstant(constant = 0) {
  22049. var rotationOverLifetime = new FrameOverTime();
  22050. rotationOverLifetime._type = 0;
  22051. rotationOverLifetime._constant = constant;
  22052. return rotationOverLifetime;
  22053. }
  22054. static createByOverTime(overTime) {
  22055. var rotationOverLifetime = new FrameOverTime();
  22056. rotationOverLifetime._type = 1;
  22057. rotationOverLifetime._overTime = overTime;
  22058. return rotationOverLifetime;
  22059. }
  22060. static createByRandomTwoConstant(constantMin = 0, constantMax = 0) {
  22061. var rotationOverLifetime = new FrameOverTime();
  22062. rotationOverLifetime._type = 2;
  22063. rotationOverLifetime._constantMin = constantMin;
  22064. rotationOverLifetime._constantMax = constantMax;
  22065. return rotationOverLifetime;
  22066. }
  22067. static createByRandomTwoOverTime(gradientFrameMin, gradientFrameMax) {
  22068. var rotationOverLifetime = new FrameOverTime();
  22069. rotationOverLifetime._type = 3;
  22070. rotationOverLifetime._overTimeMin = gradientFrameMin;
  22071. rotationOverLifetime._overTimeMax = gradientFrameMax;
  22072. return rotationOverLifetime;
  22073. }
  22074. get type() {
  22075. return this._type;
  22076. }
  22077. get constant() {
  22078. return this._constant;
  22079. }
  22080. get frameOverTimeData() {
  22081. return this._overTime;
  22082. }
  22083. get constantMin() {
  22084. return this._constantMin;
  22085. }
  22086. get constantMax() {
  22087. return this._constantMax;
  22088. }
  22089. get frameOverTimeDataMin() {
  22090. return this._overTimeMin;
  22091. }
  22092. get frameOverTimeDataMax() {
  22093. return this._overTimeMax;
  22094. }
  22095. cloneTo(destObject) {
  22096. var destFrameOverTime = destObject;
  22097. destFrameOverTime._type = this._type;
  22098. destFrameOverTime._constant = this._constant;
  22099. (this._overTime) && (this._overTime.cloneTo(destFrameOverTime._overTime));
  22100. destFrameOverTime._constantMin = this._constantMin;
  22101. destFrameOverTime._constantMax = this._constantMax;
  22102. (this._overTimeMin) && (this._overTimeMin.cloneTo(destFrameOverTime._overTimeMin));
  22103. (this._overTimeMax) && (this._overTimeMax.cloneTo(destFrameOverTime._overTimeMax));
  22104. }
  22105. clone() {
  22106. var destFrameOverTime = new FrameOverTime();
  22107. this.cloneTo(destFrameOverTime);
  22108. return destFrameOverTime;
  22109. }
  22110. }
  22111. class GradientAngularVelocity {
  22112. constructor() {
  22113. this._type = 0;
  22114. this._separateAxes = false;
  22115. this._constant = 0;
  22116. this._constantSeparate = null;
  22117. this._gradient = null;
  22118. this._gradientX = null;
  22119. this._gradientY = null;
  22120. this._gradientZ = null;
  22121. this._gradientW = null;
  22122. this._constantMin = 0;
  22123. this._constantMax = 0;
  22124. this._constantMinSeparate = null;
  22125. this._constantMaxSeparate = null;
  22126. this._gradientMin = null;
  22127. this._gradientMax = null;
  22128. this._gradientXMin = null;
  22129. this._gradientXMax = null;
  22130. this._gradientYMin = null;
  22131. this._gradientYMax = null;
  22132. this._gradientZMin = null;
  22133. this._gradientZMax = null;
  22134. this._gradientWMin = null;
  22135. this._gradientWMax = null;
  22136. }
  22137. static createByConstant(constant) {
  22138. var gradientAngularVelocity = new GradientAngularVelocity();
  22139. gradientAngularVelocity._type = 0;
  22140. gradientAngularVelocity._separateAxes = false;
  22141. gradientAngularVelocity._constant = constant;
  22142. return gradientAngularVelocity;
  22143. }
  22144. static createByConstantSeparate(separateConstant) {
  22145. var gradientAngularVelocity = new GradientAngularVelocity();
  22146. gradientAngularVelocity._type = 0;
  22147. gradientAngularVelocity._separateAxes = true;
  22148. gradientAngularVelocity._constantSeparate = separateConstant;
  22149. return gradientAngularVelocity;
  22150. }
  22151. static createByGradient(gradient) {
  22152. var gradientAngularVelocity = new GradientAngularVelocity();
  22153. gradientAngularVelocity._type = 1;
  22154. gradientAngularVelocity._separateAxes = false;
  22155. gradientAngularVelocity._gradient = gradient;
  22156. return gradientAngularVelocity;
  22157. }
  22158. static createByGradientSeparate(gradientX, gradientY, gradientZ) {
  22159. var gradientAngularVelocity = new GradientAngularVelocity();
  22160. gradientAngularVelocity._type = 1;
  22161. gradientAngularVelocity._separateAxes = true;
  22162. gradientAngularVelocity._gradientX = gradientX;
  22163. gradientAngularVelocity._gradientY = gradientY;
  22164. gradientAngularVelocity._gradientZ = gradientZ;
  22165. return gradientAngularVelocity;
  22166. }
  22167. static createByRandomTwoConstant(constantMin, constantMax) {
  22168. var gradientAngularVelocity = new GradientAngularVelocity();
  22169. gradientAngularVelocity._type = 2;
  22170. gradientAngularVelocity._separateAxes = false;
  22171. gradientAngularVelocity._constantMin = constantMin;
  22172. gradientAngularVelocity._constantMax = constantMax;
  22173. return gradientAngularVelocity;
  22174. }
  22175. static createByRandomTwoConstantSeparate(separateConstantMin, separateConstantMax) {
  22176. var gradientAngularVelocity = new GradientAngularVelocity();
  22177. gradientAngularVelocity._type = 2;
  22178. gradientAngularVelocity._separateAxes = true;
  22179. gradientAngularVelocity._constantMinSeparate = separateConstantMin;
  22180. gradientAngularVelocity._constantMaxSeparate = separateConstantMax;
  22181. return gradientAngularVelocity;
  22182. }
  22183. static createByRandomTwoGradient(gradientMin, gradientMax) {
  22184. var gradientAngularVelocity = new GradientAngularVelocity();
  22185. gradientAngularVelocity._type = 3;
  22186. gradientAngularVelocity._separateAxes = false;
  22187. gradientAngularVelocity._gradientMin = gradientMin;
  22188. gradientAngularVelocity._gradientMax = gradientMax;
  22189. return gradientAngularVelocity;
  22190. }
  22191. static createByRandomTwoGradientSeparate(gradientXMin, gradientXMax, gradientYMin, gradientYMax, gradientZMin, gradientZMax, gradientWMin, gradientWMax) {
  22192. var gradientAngularVelocity = new GradientAngularVelocity();
  22193. gradientAngularVelocity._type = 3;
  22194. gradientAngularVelocity._separateAxes = true;
  22195. gradientAngularVelocity._gradientXMin = gradientXMin;
  22196. gradientAngularVelocity._gradientXMax = gradientXMax;
  22197. gradientAngularVelocity._gradientYMin = gradientYMin;
  22198. gradientAngularVelocity._gradientYMax = gradientYMax;
  22199. gradientAngularVelocity._gradientZMin = gradientZMin;
  22200. gradientAngularVelocity._gradientZMax = gradientZMax;
  22201. gradientAngularVelocity._gradientWMin = gradientWMin;
  22202. gradientAngularVelocity._gradientWMax = gradientWMax;
  22203. return gradientAngularVelocity;
  22204. }
  22205. get type() {
  22206. return this._type;
  22207. }
  22208. get separateAxes() {
  22209. return this._separateAxes;
  22210. }
  22211. get constant() {
  22212. return this._constant;
  22213. }
  22214. get constantSeparate() {
  22215. return this._constantSeparate;
  22216. }
  22217. get gradient() {
  22218. return this._gradient;
  22219. }
  22220. get gradientX() {
  22221. return this._gradientX;
  22222. }
  22223. get gradientY() {
  22224. return this._gradientY;
  22225. }
  22226. get gradientZ() {
  22227. return this._gradientZ;
  22228. }
  22229. get gradientW() {
  22230. return this._gradientW;
  22231. }
  22232. get constantMin() {
  22233. return this._constantMin;
  22234. }
  22235. get constantMax() {
  22236. return this._constantMax;
  22237. }
  22238. get constantMinSeparate() {
  22239. return this._constantMinSeparate;
  22240. }
  22241. get constantMaxSeparate() {
  22242. return this._constantMaxSeparate;
  22243. }
  22244. get gradientMin() {
  22245. return this._gradientMin;
  22246. }
  22247. get gradientMax() {
  22248. return this._gradientMax;
  22249. }
  22250. get gradientXMin() {
  22251. return this._gradientXMin;
  22252. }
  22253. get gradientXMax() {
  22254. return this._gradientXMax;
  22255. }
  22256. get gradientYMin() {
  22257. return this._gradientYMin;
  22258. }
  22259. get gradientYMax() {
  22260. return this._gradientYMax;
  22261. }
  22262. get gradientZMin() {
  22263. return this._gradientZMin;
  22264. }
  22265. get gradientZMax() {
  22266. return this._gradientZMax;
  22267. }
  22268. get gradientWMin() {
  22269. return this._gradientWMin;
  22270. }
  22271. get gradientWMax() {
  22272. return this._gradientWMax;
  22273. }
  22274. cloneTo(destObject) {
  22275. var destGradientAngularVelocity = destObject;
  22276. destGradientAngularVelocity._type = this._type;
  22277. destGradientAngularVelocity._separateAxes = this._separateAxes;
  22278. destGradientAngularVelocity._constant = this._constant;
  22279. this._constantSeparate.cloneTo(destGradientAngularVelocity._constantSeparate);
  22280. this._gradient.cloneTo(destGradientAngularVelocity._gradient);
  22281. this._gradientX.cloneTo(destGradientAngularVelocity._gradientX);
  22282. this._gradientY.cloneTo(destGradientAngularVelocity._gradientY);
  22283. this._gradientZ.cloneTo(destGradientAngularVelocity._gradientZ);
  22284. destGradientAngularVelocity._constantMin = this._constantMin;
  22285. destGradientAngularVelocity._constantMax = this._constantMax;
  22286. this._constantMinSeparate.cloneTo(destGradientAngularVelocity._constantMinSeparate);
  22287. this._constantMaxSeparate.cloneTo(destGradientAngularVelocity._constantMaxSeparate);
  22288. this._gradientMin.cloneTo(destGradientAngularVelocity._gradientMin);
  22289. this._gradientMax.cloneTo(destGradientAngularVelocity._gradientMax);
  22290. this._gradientXMin.cloneTo(destGradientAngularVelocity._gradientXMin);
  22291. this._gradientXMax.cloneTo(destGradientAngularVelocity._gradientXMax);
  22292. this._gradientYMin.cloneTo(destGradientAngularVelocity._gradientYMin);
  22293. this._gradientYMax.cloneTo(destGradientAngularVelocity._gradientYMax);
  22294. this._gradientZMin.cloneTo(destGradientAngularVelocity._gradientZMin);
  22295. this._gradientZMax.cloneTo(destGradientAngularVelocity._gradientZMax);
  22296. }
  22297. clone() {
  22298. var destGradientAngularVelocity = new GradientAngularVelocity();
  22299. this.cloneTo(destGradientAngularVelocity);
  22300. return destGradientAngularVelocity;
  22301. }
  22302. }
  22303. class GradientDataInt {
  22304. constructor() {
  22305. this._currentLength = 0;
  22306. this._elements = new Float32Array(8);
  22307. }
  22308. get gradientCount() {
  22309. return this._currentLength / 2;
  22310. }
  22311. add(key, value) {
  22312. if (this._currentLength < 8) {
  22313. if ((this._currentLength === 6) && ((key !== 1))) {
  22314. key = 1;
  22315. console.log("Warning:the forth key is be force set to 1.");
  22316. }
  22317. this._elements[this._currentLength++] = key;
  22318. this._elements[this._currentLength++] = value;
  22319. }
  22320. else {
  22321. console.log("Warning:data count must lessEqual than 4");
  22322. }
  22323. }
  22324. cloneTo(destObject) {
  22325. var destGradientDataInt = destObject;
  22326. destGradientDataInt._currentLength = this._currentLength;
  22327. var destElements = destGradientDataInt._elements;
  22328. for (var i = 0, n = this._elements.length; i < n; i++) {
  22329. destElements[i] = this._elements[i];
  22330. }
  22331. }
  22332. clone() {
  22333. var destGradientDataInt = new GradientDataInt();
  22334. this.cloneTo(destGradientDataInt);
  22335. return destGradientDataInt;
  22336. }
  22337. }
  22338. class GradientDataNumber {
  22339. constructor() {
  22340. this._currentLength = 0;
  22341. this._elements = new Float32Array(8);
  22342. }
  22343. get gradientCount() {
  22344. return this._currentLength / 2;
  22345. }
  22346. add(key, value) {
  22347. if (this._currentLength < 8) {
  22348. if ((this._currentLength === 6) && ((key !== 1))) {
  22349. key = 1;
  22350. console.log("GradientDataNumber warning:the forth key is be force set to 1.");
  22351. }
  22352. this._elements[this._currentLength++] = key;
  22353. this._elements[this._currentLength++] = value;
  22354. }
  22355. else {
  22356. console.log("GradientDataNumber warning:data count must lessEqual than 4");
  22357. }
  22358. }
  22359. getKeyByIndex(index) {
  22360. return this._elements[index * 2];
  22361. }
  22362. getValueByIndex(index) {
  22363. return this._elements[index * 2 + 1];
  22364. }
  22365. getAverageValue() {
  22366. var total = 0;
  22367. var count = 0;
  22368. for (var i = 0, n = this._currentLength - 2; i < n; i += 2) {
  22369. var subValue = this._elements[i + 1];
  22370. subValue += this._elements[i + 3];
  22371. subValue = subValue * (this._elements[i + 2] - this._elements[i]);
  22372. total += subValue;
  22373. count++;
  22374. }
  22375. return total / count;
  22376. }
  22377. cloneTo(destObject) {
  22378. var destGradientDataNumber = destObject;
  22379. destGradientDataNumber._currentLength = this._currentLength;
  22380. var destElements = destGradientDataNumber._elements;
  22381. for (var i = 0, n = this._elements.length; i < n; i++)
  22382. destElements[i] = this._elements[i];
  22383. }
  22384. clone() {
  22385. var destGradientDataNumber = new GradientDataNumber();
  22386. this.cloneTo(destGradientDataNumber);
  22387. return destGradientDataNumber;
  22388. }
  22389. }
  22390. class GradientSize {
  22391. constructor() {
  22392. this._type = 0;
  22393. this._separateAxes = false;
  22394. this._gradient = null;
  22395. this._gradientX = null;
  22396. this._gradientY = null;
  22397. this._gradientZ = null;
  22398. this._constantMin = 0;
  22399. this._constantMax = 0;
  22400. this._constantMinSeparate = null;
  22401. this._constantMaxSeparate = null;
  22402. this._gradientMin = null;
  22403. this._gradientMax = null;
  22404. this._gradientXMin = null;
  22405. this._gradientXMax = null;
  22406. this._gradientYMin = null;
  22407. this._gradientYMax = null;
  22408. this._gradientZMin = null;
  22409. this._gradientZMax = null;
  22410. }
  22411. static createByGradient(gradient) {
  22412. var gradientSize = new GradientSize();
  22413. gradientSize._type = 0;
  22414. gradientSize._separateAxes = false;
  22415. gradientSize._gradient = gradient;
  22416. return gradientSize;
  22417. }
  22418. static createByGradientSeparate(gradientX, gradientY, gradientZ) {
  22419. var gradientSize = new GradientSize();
  22420. gradientSize._type = 0;
  22421. gradientSize._separateAxes = true;
  22422. gradientSize._gradientX = gradientX;
  22423. gradientSize._gradientY = gradientY;
  22424. gradientSize._gradientZ = gradientZ;
  22425. return gradientSize;
  22426. }
  22427. static createByRandomTwoConstant(constantMin, constantMax) {
  22428. var gradientSize = new GradientSize();
  22429. gradientSize._type = 1;
  22430. gradientSize._separateAxes = false;
  22431. gradientSize._constantMin = constantMin;
  22432. gradientSize._constantMax = constantMax;
  22433. return gradientSize;
  22434. }
  22435. static createByRandomTwoConstantSeparate(constantMinSeparate, constantMaxSeparate) {
  22436. var gradientSize = new GradientSize();
  22437. gradientSize._type = 1;
  22438. gradientSize._separateAxes = true;
  22439. gradientSize._constantMinSeparate = constantMinSeparate;
  22440. gradientSize._constantMaxSeparate = constantMaxSeparate;
  22441. return gradientSize;
  22442. }
  22443. static createByRandomTwoGradient(gradientMin, gradientMax) {
  22444. var gradientSize = new GradientSize();
  22445. gradientSize._type = 2;
  22446. gradientSize._separateAxes = false;
  22447. gradientSize._gradientMin = gradientMin;
  22448. gradientSize._gradientMax = gradientMax;
  22449. return gradientSize;
  22450. }
  22451. static createByRandomTwoGradientSeparate(gradientXMin, gradientXMax, gradientYMin, gradientYMax, gradientZMin, gradientZMax) {
  22452. var gradientSize = new GradientSize();
  22453. gradientSize._type = 2;
  22454. gradientSize._separateAxes = true;
  22455. gradientSize._gradientXMin = gradientXMin;
  22456. gradientSize._gradientXMax = gradientXMax;
  22457. gradientSize._gradientYMin = gradientYMin;
  22458. gradientSize._gradientYMax = gradientYMax;
  22459. gradientSize._gradientZMin = gradientZMin;
  22460. gradientSize._gradientZMax = gradientZMax;
  22461. return gradientSize;
  22462. }
  22463. get type() {
  22464. return this._type;
  22465. }
  22466. get separateAxes() {
  22467. return this._separateAxes;
  22468. }
  22469. get gradient() {
  22470. return this._gradient;
  22471. }
  22472. get gradientX() {
  22473. return this._gradientX;
  22474. }
  22475. get gradientY() {
  22476. return this._gradientY;
  22477. }
  22478. get gradientZ() {
  22479. return this._gradientZ;
  22480. }
  22481. get constantMin() {
  22482. return this._constantMin;
  22483. }
  22484. get constantMax() {
  22485. return this._constantMax;
  22486. }
  22487. get constantMinSeparate() {
  22488. return this._constantMinSeparate;
  22489. }
  22490. get constantMaxSeparate() {
  22491. return this._constantMaxSeparate;
  22492. }
  22493. get gradientMin() {
  22494. return this._gradientMin;
  22495. }
  22496. get gradientMax() {
  22497. return this._gradientMax;
  22498. }
  22499. get gradientXMin() {
  22500. return this._gradientXMin;
  22501. }
  22502. get gradientXMax() {
  22503. return this._gradientXMax;
  22504. }
  22505. get gradientYMin() {
  22506. return this._gradientYMin;
  22507. }
  22508. get gradientYMax() {
  22509. return this._gradientYMax;
  22510. }
  22511. get gradientZMin() {
  22512. return this._gradientZMin;
  22513. }
  22514. get gradientZMax() {
  22515. return this._gradientZMax;
  22516. }
  22517. getMaxSizeInGradient(meshMode = false) {
  22518. var i, n;
  22519. var maxSize = -Number.MAX_VALUE;
  22520. switch (this._type) {
  22521. case 0:
  22522. if (this._separateAxes) {
  22523. for (i = 0, n = this._gradientX.gradientCount; i < n; i++)
  22524. maxSize = Math.max(maxSize, this._gradientX.getValueByIndex(i));
  22525. for (i = 0, n = this._gradientY.gradientCount; i < n; i++)
  22526. maxSize = Math.max(maxSize, this._gradientY.getValueByIndex(i));
  22527. if (meshMode) {
  22528. for (i = 0, n = this._gradientZ.gradientCount; i < n; i++) {
  22529. maxSize = Math.max(maxSize, this._gradientZ.getValueByIndex(i));
  22530. }
  22531. }
  22532. }
  22533. else {
  22534. for (i = 0, n = this._gradient.gradientCount; i < n; i++)
  22535. maxSize = Math.max(maxSize, this._gradient.getValueByIndex(i));
  22536. }
  22537. break;
  22538. case 1:
  22539. if (this._separateAxes) {
  22540. maxSize = Math.max(this._constantMinSeparate.x, this._constantMaxSeparate.x);
  22541. maxSize = Math.max(maxSize, this._constantMinSeparate.y);
  22542. if (meshMode) {
  22543. maxSize = maxSize = Math.max(maxSize, this._constantMaxSeparate.z);
  22544. }
  22545. }
  22546. else {
  22547. maxSize = Math.max(this._constantMin, this._constantMax);
  22548. }
  22549. break;
  22550. case 2:
  22551. if (this._separateAxes) {
  22552. for (i = 0, n = this._gradientXMin.gradientCount; i < n; i++)
  22553. maxSize = Math.max(maxSize, this._gradientXMin.getValueByIndex(i));
  22554. for (i = 0, n = this._gradientXMax.gradientCount; i < n; i++)
  22555. maxSize = Math.max(maxSize, this._gradientXMax.getValueByIndex(i));
  22556. for (i = 0, n = this._gradientYMin.gradientCount; i < n; i++)
  22557. maxSize = Math.max(maxSize, this._gradientYMin.getValueByIndex(i));
  22558. for (i = 0, n = this._gradientZMax.gradientCount; i < n; i++)
  22559. maxSize = Math.max(maxSize, this._gradientZMax.getValueByIndex(i));
  22560. if (meshMode) {
  22561. for (i = 0, n = this._gradientZMin.gradientCount; i < n; i++) {
  22562. maxSize = Math.max(maxSize, this._gradientZMin.getValueByIndex(i));
  22563. }
  22564. for (i = 0, n = this._gradientZMax.gradientCount; i < n; i++) {
  22565. maxSize = Math.max(maxSize, this._gradientZMax.getValueByIndex(i));
  22566. }
  22567. }
  22568. }
  22569. else {
  22570. for (i = 0, n = this._gradientMin.gradientCount; i < n; i++)
  22571. maxSize = Math.max(maxSize, this._gradientMin.getValueByIndex(i));
  22572. for (i = 0, n = this._gradientMax.gradientCount; i < n; i++)
  22573. maxSize = Math.max(maxSize, this._gradientMax.getValueByIndex(i));
  22574. }
  22575. break;
  22576. }
  22577. return maxSize;
  22578. }
  22579. cloneTo(destObject) {
  22580. var destGradientSize = destObject;
  22581. destGradientSize._type = this._type;
  22582. destGradientSize._separateAxes = this._separateAxes;
  22583. this._gradient.cloneTo(destGradientSize._gradient);
  22584. this._gradientX.cloneTo(destGradientSize._gradientX);
  22585. this._gradientY.cloneTo(destGradientSize._gradientY);
  22586. this._gradientZ.cloneTo(destGradientSize._gradientZ);
  22587. destGradientSize._constantMin = this._constantMin;
  22588. destGradientSize._constantMax = this._constantMax;
  22589. this._constantMinSeparate.cloneTo(destGradientSize._constantMinSeparate);
  22590. this._constantMaxSeparate.cloneTo(destGradientSize._constantMaxSeparate);
  22591. this._gradientMin.cloneTo(destGradientSize._gradientMin);
  22592. this._gradientMax.cloneTo(destGradientSize._gradientMax);
  22593. this._gradientXMin.cloneTo(destGradientSize._gradientXMin);
  22594. this._gradientXMax.cloneTo(destGradientSize._gradientXMax);
  22595. this._gradientYMin.cloneTo(destGradientSize._gradientYMin);
  22596. this._gradientYMax.cloneTo(destGradientSize._gradientYMax);
  22597. this._gradientZMin.cloneTo(destGradientSize._gradientZMin);
  22598. this._gradientZMax.cloneTo(destGradientSize._gradientZMax);
  22599. }
  22600. clone() {
  22601. var destGradientSize = new GradientSize();
  22602. this.cloneTo(destGradientSize);
  22603. return destGradientSize;
  22604. }
  22605. }
  22606. class GradientVelocity {
  22607. constructor() {
  22608. this._type = 0;
  22609. this._constant = null;
  22610. this._gradientX = null;
  22611. this._gradientY = null;
  22612. this._gradientZ = null;
  22613. this._constantMin = null;
  22614. this._constantMax = null;
  22615. this._gradientXMin = null;
  22616. this._gradientXMax = null;
  22617. this._gradientYMin = null;
  22618. this._gradientYMax = null;
  22619. this._gradientZMin = null;
  22620. this._gradientZMax = null;
  22621. }
  22622. static createByConstant(constant) {
  22623. var gradientVelocity = new GradientVelocity();
  22624. gradientVelocity._type = 0;
  22625. gradientVelocity._constant = constant;
  22626. return gradientVelocity;
  22627. }
  22628. static createByGradient(gradientX, gradientY, gradientZ) {
  22629. var gradientVelocity = new GradientVelocity();
  22630. gradientVelocity._type = 1;
  22631. gradientVelocity._gradientX = gradientX;
  22632. gradientVelocity._gradientY = gradientY;
  22633. gradientVelocity._gradientZ = gradientZ;
  22634. return gradientVelocity;
  22635. }
  22636. static createByRandomTwoConstant(constantMin, constantMax) {
  22637. var gradientVelocity = new GradientVelocity();
  22638. gradientVelocity._type = 2;
  22639. gradientVelocity._constantMin = constantMin;
  22640. gradientVelocity._constantMax = constantMax;
  22641. return gradientVelocity;
  22642. }
  22643. static createByRandomTwoGradient(gradientXMin, gradientXMax, gradientYMin, gradientYMax, gradientZMin, gradientZMax) {
  22644. var gradientVelocity = new GradientVelocity();
  22645. gradientVelocity._type = 3;
  22646. gradientVelocity._gradientXMin = gradientXMin;
  22647. gradientVelocity._gradientXMax = gradientXMax;
  22648. gradientVelocity._gradientYMin = gradientYMin;
  22649. gradientVelocity._gradientYMax = gradientYMax;
  22650. gradientVelocity._gradientZMin = gradientZMin;
  22651. gradientVelocity._gradientZMax = gradientZMax;
  22652. return gradientVelocity;
  22653. }
  22654. get type() {
  22655. return this._type;
  22656. }
  22657. get constant() {
  22658. return this._constant;
  22659. }
  22660. get gradientX() {
  22661. return this._gradientX;
  22662. }
  22663. get gradientY() {
  22664. return this._gradientY;
  22665. }
  22666. get gradientZ() {
  22667. return this._gradientZ;
  22668. }
  22669. get constantMin() {
  22670. return this._constantMin;
  22671. }
  22672. get constantMax() {
  22673. return this._constantMax;
  22674. }
  22675. get gradientXMin() {
  22676. return this._gradientXMin;
  22677. }
  22678. get gradientXMax() {
  22679. return this._gradientXMax;
  22680. }
  22681. get gradientYMin() {
  22682. return this._gradientYMin;
  22683. }
  22684. get gradientYMax() {
  22685. return this._gradientYMax;
  22686. }
  22687. get gradientZMin() {
  22688. return this._gradientZMin;
  22689. }
  22690. get gradientZMax() {
  22691. return this._gradientZMax;
  22692. }
  22693. cloneTo(destObject) {
  22694. var destGradientVelocity = destObject;
  22695. destGradientVelocity._type = this._type;
  22696. this._constant.cloneTo(destGradientVelocity._constant);
  22697. this._gradientX.cloneTo(destGradientVelocity._gradientX);
  22698. this._gradientY.cloneTo(destGradientVelocity._gradientY);
  22699. this._gradientZ.cloneTo(destGradientVelocity._gradientZ);
  22700. this._constantMin.cloneTo(destGradientVelocity._constantMin);
  22701. this._constantMax.cloneTo(destGradientVelocity._constantMax);
  22702. this._gradientXMin.cloneTo(destGradientVelocity._gradientXMin);
  22703. this._gradientXMax.cloneTo(destGradientVelocity._gradientXMax);
  22704. this._gradientYMin.cloneTo(destGradientVelocity._gradientYMin);
  22705. this._gradientYMax.cloneTo(destGradientVelocity._gradientYMax);
  22706. this._gradientZMin.cloneTo(destGradientVelocity._gradientZMin);
  22707. this._gradientZMax.cloneTo(destGradientVelocity._gradientZMax);
  22708. }
  22709. clone() {
  22710. var destGradientVelocity = new GradientVelocity();
  22711. this.cloneTo(destGradientVelocity);
  22712. return destGradientVelocity;
  22713. }
  22714. }
  22715. class RotationOverLifetime {
  22716. constructor(angularVelocity) {
  22717. this._angularVelocity = angularVelocity;
  22718. }
  22719. get angularVelocity() {
  22720. return this._angularVelocity;
  22721. }
  22722. cloneTo(destObject) {
  22723. var destRotationOverLifetime = destObject;
  22724. this._angularVelocity.cloneTo(destRotationOverLifetime._angularVelocity);
  22725. destRotationOverLifetime.enable = this.enable;
  22726. }
  22727. clone() {
  22728. var destAngularVelocity;
  22729. switch (this._angularVelocity.type) {
  22730. case 0:
  22731. if (this._angularVelocity.separateAxes)
  22732. destAngularVelocity = GradientAngularVelocity.createByConstantSeparate(this._angularVelocity.constantSeparate.clone());
  22733. else
  22734. destAngularVelocity = GradientAngularVelocity.createByConstant(this._angularVelocity.constant);
  22735. break;
  22736. case 1:
  22737. if (this._angularVelocity.separateAxes)
  22738. destAngularVelocity = GradientAngularVelocity.createByGradientSeparate(this._angularVelocity.gradientX.clone(), this._angularVelocity.gradientY.clone(), this._angularVelocity.gradientZ.clone());
  22739. else
  22740. destAngularVelocity = GradientAngularVelocity.createByGradient(this._angularVelocity.gradient.clone());
  22741. break;
  22742. case 2:
  22743. if (this._angularVelocity.separateAxes)
  22744. destAngularVelocity = GradientAngularVelocity.createByRandomTwoConstantSeparate(this._angularVelocity.constantMinSeparate.clone(), this._angularVelocity.constantMaxSeparate.clone());
  22745. else
  22746. destAngularVelocity = GradientAngularVelocity.createByRandomTwoConstant(this._angularVelocity.constantMin, this._angularVelocity.constantMax);
  22747. break;
  22748. case 3:
  22749. if (this._angularVelocity.separateAxes)
  22750. destAngularVelocity = GradientAngularVelocity.createByRandomTwoGradientSeparate(this._angularVelocity.gradientXMin.clone(), this._angularVelocity.gradientYMin.clone(), this._angularVelocity.gradientZMin.clone(), this._angularVelocity.gradientWMin.clone(), this._angularVelocity.gradientXMax.clone(), this._angularVelocity.gradientYMax.clone(), this._angularVelocity.gradientZMax.clone(), this._angularVelocity.gradientWMax.clone());
  22751. else
  22752. destAngularVelocity = GradientAngularVelocity.createByRandomTwoGradient(this._angularVelocity.gradientMin.clone(), this._angularVelocity.gradientMax.clone());
  22753. break;
  22754. }
  22755. var destRotationOverLifetime = new RotationOverLifetime(destAngularVelocity);
  22756. destRotationOverLifetime.enable = this.enable;
  22757. return destRotationOverLifetime;
  22758. }
  22759. }
  22760. (function (ParticleSystemShapeType) {
  22761. ParticleSystemShapeType[ParticleSystemShapeType["Box"] = 0] = "Box";
  22762. ParticleSystemShapeType[ParticleSystemShapeType["Circle"] = 1] = "Circle";
  22763. ParticleSystemShapeType[ParticleSystemShapeType["Cone"] = 2] = "Cone";
  22764. ParticleSystemShapeType[ParticleSystemShapeType["Hemisphere"] = 3] = "Hemisphere";
  22765. ParticleSystemShapeType[ParticleSystemShapeType["Sphere"] = 4] = "Sphere";
  22766. })(exports.ParticleSystemShapeType || (exports.ParticleSystemShapeType = {}));
  22767. class BaseShape {
  22768. constructor() {
  22769. this.enable = true;
  22770. this.randomDirection = 0;
  22771. }
  22772. _getShapeBoundBox(boundBox) {
  22773. throw new Error("BaseShape: must override it.");
  22774. }
  22775. _getSpeedBoundBox(boundBox) {
  22776. throw new Error("BaseShape: must override it.");
  22777. }
  22778. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  22779. throw new Error("BaseShape: must override it.");
  22780. }
  22781. _calculateProceduralBounds(boundBox, emitterPosScale, minMaxBounds) {
  22782. this._getShapeBoundBox(boundBox);
  22783. var min = boundBox.min;
  22784. var max = boundBox.max;
  22785. Vector3.multiply(min, emitterPosScale, min);
  22786. Vector3.multiply(max, emitterPosScale, max);
  22787. var speedBounds = new BoundBox(new Vector3(), new Vector3());
  22788. if (this.randomDirection) {
  22789. speedBounds.min = new Vector3(-1, -1, -1);
  22790. speedBounds.max = new Vector3(1, 1, 1);
  22791. }
  22792. else {
  22793. this._getSpeedBoundBox(speedBounds);
  22794. }
  22795. var maxSpeedBound = new BoundBox(new Vector3(), new Vector3());
  22796. var maxSpeedMin = maxSpeedBound.min;
  22797. var maxSpeedMax = maxSpeedBound.max;
  22798. Vector3.scale(speedBounds.min, minMaxBounds.y, maxSpeedMin);
  22799. Vector3.scale(speedBounds.max, minMaxBounds.y, maxSpeedMax);
  22800. Vector3.add(boundBox.min, maxSpeedMin, maxSpeedMin);
  22801. Vector3.add(boundBox.max, maxSpeedMax, maxSpeedMax);
  22802. Vector3.min(boundBox.min, maxSpeedMin, boundBox.min);
  22803. Vector3.max(boundBox.max, maxSpeedMin, boundBox.max);
  22804. var minSpeedBound = new BoundBox(new Vector3(), new Vector3());
  22805. var minSpeedMin = minSpeedBound.min;
  22806. var minSpeedMax = minSpeedBound.max;
  22807. Vector3.scale(speedBounds.min, minMaxBounds.x, minSpeedMin);
  22808. Vector3.scale(speedBounds.max, minMaxBounds.x, minSpeedMax);
  22809. Vector3.min(minSpeedBound.min, minSpeedMax, maxSpeedMin);
  22810. Vector3.max(minSpeedBound.min, minSpeedMax, maxSpeedMax);
  22811. Vector3.min(boundBox.min, maxSpeedMin, boundBox.min);
  22812. Vector3.max(boundBox.max, maxSpeedMin, boundBox.max);
  22813. }
  22814. cloneTo(destObject) {
  22815. var destShape = destObject;
  22816. destShape.enable = this.enable;
  22817. }
  22818. clone() {
  22819. var destShape = new BaseShape();
  22820. this.cloneTo(destShape);
  22821. return destShape;
  22822. }
  22823. }
  22824. class ShapeUtils {
  22825. static _randomPointUnitArcCircle(arc, out, rand = null) {
  22826. var angle;
  22827. if (rand)
  22828. angle = rand.getFloat() * arc;
  22829. else
  22830. angle = Math.random() * arc;
  22831. out.x = Math.cos(angle);
  22832. out.y = Math.sin(angle);
  22833. }
  22834. static _randomPointInsideUnitArcCircle(arc, out, rand = null) {
  22835. ShapeUtils._randomPointUnitArcCircle(arc, out, rand);
  22836. var range;
  22837. if (rand)
  22838. range = Math.pow(rand.getFloat(), 1.0 / 2.0);
  22839. else
  22840. range = Math.pow(Math.random(), 1.0 / 2.0);
  22841. out.x = out.x * range;
  22842. out.y = out.y * range;
  22843. }
  22844. static _randomPointUnitCircle(out, rand = null) {
  22845. var angle;
  22846. if (rand)
  22847. angle = rand.getFloat() * Math.PI * 2;
  22848. else
  22849. angle = Math.random() * Math.PI * 2;
  22850. out.x = Math.cos(angle);
  22851. out.y = Math.sin(angle);
  22852. }
  22853. static _randomPointInsideUnitCircle(out, rand = null) {
  22854. ShapeUtils._randomPointUnitCircle(out);
  22855. var range;
  22856. if (rand)
  22857. range = Math.pow(rand.getFloat(), 1.0 / 2.0);
  22858. else
  22859. range = Math.pow(Math.random(), 1.0 / 2.0);
  22860. out.x = out.x * range;
  22861. out.y = out.y * range;
  22862. }
  22863. static _randomPointUnitSphere(out, rand = null) {
  22864. var z;
  22865. var a;
  22866. if (rand) {
  22867. z = out.z = rand.getFloat() * 2 - 1.0;
  22868. a = rand.getFloat() * Math.PI * 2;
  22869. }
  22870. else {
  22871. z = out.z = Math.random() * 2 - 1.0;
  22872. a = Math.random() * Math.PI * 2;
  22873. }
  22874. var r = Math.sqrt(1.0 - z * z);
  22875. out.x = r * Math.cos(a);
  22876. out.y = r * Math.sin(a);
  22877. }
  22878. static _randomPointInsideUnitSphere(out, rand = null) {
  22879. ShapeUtils._randomPointUnitSphere(out);
  22880. var range;
  22881. if (rand)
  22882. range = Math.pow(rand.getFloat(), 1.0 / 3.0);
  22883. else
  22884. range = Math.pow(Math.random(), 1.0 / 3.0);
  22885. out.x = out.x * range;
  22886. out.y = out.y * range;
  22887. out.z = out.z * range;
  22888. }
  22889. static _randomPointInsideHalfUnitBox(out, rand = null) {
  22890. if (rand) {
  22891. out.x = (rand.getFloat() - 0.5);
  22892. out.y = (rand.getFloat() - 0.5);
  22893. out.z = (rand.getFloat() - 0.5);
  22894. }
  22895. else {
  22896. out.x = (Math.random() - 0.5);
  22897. out.y = (Math.random() - 0.5);
  22898. out.z = (Math.random() - 0.5);
  22899. }
  22900. }
  22901. constructor() {
  22902. }
  22903. }
  22904. class BoxShape extends BaseShape {
  22905. constructor() {
  22906. super();
  22907. this.shapeType = exports.ParticleSystemShapeType.Box;
  22908. this.x = 1.0;
  22909. this.y = 1.0;
  22910. this.z = 1.0;
  22911. }
  22912. _getShapeBoundBox(boundBox) {
  22913. var min = boundBox.min;
  22914. min.x = -this.x * 0.5;
  22915. min.y = -this.y * 0.5;
  22916. min.z = -this.z * 0.5;
  22917. var max = boundBox.max;
  22918. max.x = this.x * 0.5;
  22919. max.y = this.y * 0.5;
  22920. max.z = this.z * 0.5;
  22921. }
  22922. _getSpeedBoundBox(boundBox) {
  22923. var min = boundBox.min;
  22924. min.x = 0.0;
  22925. min.y = 0.0;
  22926. min.z = 0.0;
  22927. var max = boundBox.max;
  22928. max.x = 0.0;
  22929. max.y = 1.0;
  22930. max.z = 0.0;
  22931. }
  22932. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  22933. if (rand) {
  22934. rand.seed = randomSeeds[16];
  22935. ShapeUtils._randomPointInsideHalfUnitBox(position, rand);
  22936. randomSeeds[16] = rand.seed;
  22937. }
  22938. else {
  22939. ShapeUtils._randomPointInsideHalfUnitBox(position);
  22940. }
  22941. position.x = this.x * position.x;
  22942. position.y = this.y * position.y;
  22943. position.z = this.z * position.z;
  22944. if (this.randomDirection) {
  22945. if (rand) {
  22946. rand.seed = randomSeeds[17];
  22947. ShapeUtils._randomPointUnitSphere(direction, rand);
  22948. randomSeeds[17] = rand.seed;
  22949. }
  22950. else {
  22951. ShapeUtils._randomPointUnitSphere(direction);
  22952. }
  22953. }
  22954. else {
  22955. direction.x = 0.0;
  22956. direction.y = 0.0;
  22957. direction.z = 1.0;
  22958. }
  22959. }
  22960. cloneTo(destObject) {
  22961. super.cloneTo(destObject);
  22962. var destShape = destObject;
  22963. destShape.x = this.x;
  22964. destShape.y = this.y;
  22965. destShape.z = this.z;
  22966. destShape.randomDirection = this.randomDirection;
  22967. }
  22968. clone() {
  22969. var destShape = new BoxShape();
  22970. this.cloneTo(destShape);
  22971. return destShape;
  22972. }
  22973. }
  22974. class CircleShape extends BaseShape {
  22975. constructor() {
  22976. super();
  22977. this.shapeType = exports.ParticleSystemShapeType.Circle;
  22978. this.radius = 1.0;
  22979. this.arc = 360.0 / 180.0 * Math.PI;
  22980. this.emitFromEdge = false;
  22981. }
  22982. _getShapeBoundBox(boundBox) {
  22983. var min = boundBox.min;
  22984. min.x = min.z = -this.radius;
  22985. min.y = 0;
  22986. var max = boundBox.max;
  22987. max.x = max.z = this.radius;
  22988. max.y = 0;
  22989. }
  22990. _getSpeedBoundBox(boundBox) {
  22991. var min = boundBox.min;
  22992. min.x = min.y = -1;
  22993. min.z = 0;
  22994. var max = boundBox.max;
  22995. max.x = max.y = 1;
  22996. max.z = 0;
  22997. }
  22998. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  22999. var positionPoint = CircleShape._tempPositionPoint;
  23000. if (rand) {
  23001. rand.seed = randomSeeds[16];
  23002. if (this.emitFromEdge)
  23003. ShapeUtils._randomPointUnitArcCircle(this.arc, CircleShape._tempPositionPoint, rand);
  23004. else
  23005. ShapeUtils._randomPointInsideUnitArcCircle(this.arc, CircleShape._tempPositionPoint, rand);
  23006. randomSeeds[16] = rand.seed;
  23007. }
  23008. else {
  23009. if (this.emitFromEdge)
  23010. ShapeUtils._randomPointUnitArcCircle(this.arc, CircleShape._tempPositionPoint);
  23011. else
  23012. ShapeUtils._randomPointInsideUnitArcCircle(this.arc, CircleShape._tempPositionPoint);
  23013. }
  23014. position.x = -positionPoint.x;
  23015. position.y = positionPoint.y;
  23016. position.z = 0;
  23017. Vector3.scale(position, this.radius, position);
  23018. if (this.randomDirection) {
  23019. if (rand) {
  23020. rand.seed = randomSeeds[17];
  23021. ShapeUtils._randomPointUnitSphere(direction, rand);
  23022. randomSeeds[17] = rand.seed;
  23023. }
  23024. else {
  23025. ShapeUtils._randomPointUnitSphere(direction);
  23026. }
  23027. }
  23028. else {
  23029. position.cloneTo(direction);
  23030. }
  23031. }
  23032. cloneTo(destObject) {
  23033. super.cloneTo(destObject);
  23034. var destShape = destObject;
  23035. destShape.radius = this.radius;
  23036. destShape.arc = this.arc;
  23037. destShape.emitFromEdge = this.emitFromEdge;
  23038. destShape.randomDirection = this.randomDirection;
  23039. }
  23040. clone() {
  23041. var destShape = new CircleShape();
  23042. this.cloneTo(destShape);
  23043. return destShape;
  23044. }
  23045. }
  23046. CircleShape._tempPositionPoint = new Vector2();
  23047. class ConeShape extends BaseShape {
  23048. constructor() {
  23049. super();
  23050. this.shapeType = exports.ParticleSystemShapeType.Cone;
  23051. this.angle = 25.0 / 180.0 * Math.PI;
  23052. this.radius = 1.0;
  23053. this.length = 5.0;
  23054. this.emitType = 0;
  23055. }
  23056. _getShapeBoundBox(boundBox) {
  23057. const coneRadius2 = this.radius + this.length * Math.sin(this.angle);
  23058. const coneLength = this.length * Math.cos(this.angle);
  23059. var min = boundBox.min;
  23060. min.x = min.y = -coneRadius2;
  23061. min.z = 0;
  23062. var max = boundBox.max;
  23063. max.x = max.y = coneRadius2;
  23064. max.z = coneLength;
  23065. }
  23066. _getSpeedBoundBox(boundBox) {
  23067. const sinA = Math.sin(this.angle);
  23068. var min = boundBox.min;
  23069. min.x = min.y = -sinA;
  23070. min.z = 0;
  23071. var max = boundBox.max;
  23072. max.x = max.y = sinA;
  23073. max.z = 1;
  23074. }
  23075. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  23076. var positionPointE = ConeShape._tempPositionPoint;
  23077. var positionX;
  23078. var positionY;
  23079. var directionPointE;
  23080. var dirCosA = Math.cos(this.angle);
  23081. var dirSinA = Math.sin(this.angle);
  23082. switch (this.emitType) {
  23083. case 0:
  23084. if (rand) {
  23085. rand.seed = randomSeeds[16];
  23086. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint, rand);
  23087. randomSeeds[16] = rand.seed;
  23088. }
  23089. else {
  23090. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint);
  23091. }
  23092. positionX = positionPointE.x;
  23093. positionY = positionPointE.y;
  23094. position.x = positionX * this.radius;
  23095. position.y = positionY * this.radius;
  23096. position.z = 0;
  23097. if (this.randomDirection) {
  23098. if (rand) {
  23099. rand.seed = randomSeeds[17];
  23100. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint, rand);
  23101. randomSeeds[17] = rand.seed;
  23102. }
  23103. else {
  23104. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint);
  23105. }
  23106. directionPointE = ConeShape._tempDirectionPoint;
  23107. direction.x = directionPointE.x * dirSinA;
  23108. direction.y = directionPointE.y * dirSinA;
  23109. }
  23110. else {
  23111. direction.x = positionX * dirSinA;
  23112. direction.y = positionY * dirSinA;
  23113. }
  23114. direction.z = dirCosA;
  23115. break;
  23116. case 1:
  23117. if (rand) {
  23118. rand.seed = randomSeeds[16];
  23119. ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint, rand);
  23120. randomSeeds[16] = rand.seed;
  23121. }
  23122. else {
  23123. ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint);
  23124. }
  23125. positionX = positionPointE.x;
  23126. positionY = positionPointE.y;
  23127. position.x = positionX * this.radius;
  23128. position.y = positionY * this.radius;
  23129. position.z = 0;
  23130. if (this.randomDirection) {
  23131. if (rand) {
  23132. rand.seed = randomSeeds[17];
  23133. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint, rand);
  23134. randomSeeds[17] = rand.seed;
  23135. }
  23136. else {
  23137. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint);
  23138. }
  23139. directionPointE = ConeShape._tempDirectionPoint;
  23140. direction.x = directionPointE.x * dirSinA;
  23141. direction.y = directionPointE.y * dirSinA;
  23142. }
  23143. else {
  23144. direction.x = positionX * dirSinA;
  23145. direction.y = positionY * dirSinA;
  23146. }
  23147. direction.z = dirCosA;
  23148. break;
  23149. case 2:
  23150. if (rand) {
  23151. rand.seed = randomSeeds[16];
  23152. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint, rand);
  23153. }
  23154. else {
  23155. ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint);
  23156. }
  23157. positionX = positionPointE.x;
  23158. positionY = positionPointE.y;
  23159. position.x = positionX * this.radius;
  23160. position.y = positionY * this.radius;
  23161. position.z = 0;
  23162. direction.x = positionX * dirSinA;
  23163. direction.y = positionY * dirSinA;
  23164. direction.z = dirCosA;
  23165. Vector3.normalize(direction, direction);
  23166. if (rand) {
  23167. Vector3.scale(direction, this.length * rand.getFloat(), direction);
  23168. randomSeeds[16] = rand.seed;
  23169. }
  23170. else {
  23171. Vector3.scale(direction, this.length * Math.random(), direction);
  23172. }
  23173. Vector3.add(position, direction, position);
  23174. if (this.randomDirection) {
  23175. if (rand) {
  23176. rand.seed = randomSeeds[17];
  23177. ShapeUtils._randomPointUnitSphere(direction, rand);
  23178. randomSeeds[17] = rand.seed;
  23179. }
  23180. else {
  23181. ShapeUtils._randomPointUnitSphere(direction);
  23182. }
  23183. }
  23184. break;
  23185. case 3:
  23186. if (rand) {
  23187. rand.seed = randomSeeds[16];
  23188. ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint, rand);
  23189. }
  23190. else {
  23191. ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint);
  23192. }
  23193. positionX = positionPointE.x;
  23194. positionY = positionPointE.y;
  23195. position.x = positionX * this.radius;
  23196. position.y = positionY * this.radius;
  23197. position.z = 0;
  23198. direction.x = positionX * dirSinA;
  23199. direction.y = positionY * dirSinA;
  23200. direction.z = dirCosA;
  23201. Vector3.normalize(direction, direction);
  23202. if (rand) {
  23203. Vector3.scale(direction, this.length * rand.getFloat(), direction);
  23204. randomSeeds[16] = rand.seed;
  23205. }
  23206. else {
  23207. Vector3.scale(direction, this.length * Math.random(), direction);
  23208. }
  23209. Vector3.add(position, direction, position);
  23210. if (this.randomDirection) {
  23211. if (rand) {
  23212. rand.seed = randomSeeds[17];
  23213. ShapeUtils._randomPointUnitSphere(direction, rand);
  23214. randomSeeds[17] = rand.seed;
  23215. }
  23216. else {
  23217. ShapeUtils._randomPointUnitSphere(direction);
  23218. }
  23219. }
  23220. break;
  23221. default:
  23222. throw new Error("ConeShape:emitType is invalid.");
  23223. }
  23224. }
  23225. cloneTo(destObject) {
  23226. super.cloneTo(destObject);
  23227. var destShape = destObject;
  23228. destShape.angle = this.angle;
  23229. destShape.radius = this.radius;
  23230. destShape.length = this.length;
  23231. destShape.emitType = this.emitType;
  23232. destShape.randomDirection = this.randomDirection;
  23233. }
  23234. clone() {
  23235. var destShape = new ConeShape();
  23236. this.cloneTo(destShape);
  23237. return destShape;
  23238. }
  23239. }
  23240. ConeShape._tempPositionPoint = new Vector2();
  23241. ConeShape._tempDirectionPoint = new Vector2();
  23242. class HemisphereShape extends BaseShape {
  23243. constructor() {
  23244. super();
  23245. this.shapeType = exports.ParticleSystemShapeType.Hemisphere;
  23246. this.radius = 1.0;
  23247. this.emitFromShell = false;
  23248. }
  23249. _getShapeBoundBox(boundBox) {
  23250. var min = boundBox.min;
  23251. min.x = min.y = min.z = -this.radius;
  23252. var max = boundBox.max;
  23253. max.x = max.y = this.radius;
  23254. max.z = 0;
  23255. }
  23256. _getSpeedBoundBox(boundBox) {
  23257. var min = boundBox.min;
  23258. min.x = min.y = -1;
  23259. min.z = 0;
  23260. var max = boundBox.max;
  23261. max.x = max.y = max.z = 1;
  23262. }
  23263. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  23264. if (rand) {
  23265. rand.seed = randomSeeds[16];
  23266. if (this.emitFromShell)
  23267. ShapeUtils._randomPointUnitSphere(position, rand);
  23268. else
  23269. ShapeUtils._randomPointInsideUnitSphere(position, rand);
  23270. randomSeeds[16] = rand.seed;
  23271. }
  23272. else {
  23273. if (this.emitFromShell)
  23274. ShapeUtils._randomPointUnitSphere(position);
  23275. else
  23276. ShapeUtils._randomPointInsideUnitSphere(position);
  23277. }
  23278. Vector3.scale(position, this.radius, position);
  23279. var z = position.z;
  23280. (z < 0.0) && (position.z = z * -1.0);
  23281. if (this.randomDirection) {
  23282. if (rand) {
  23283. rand.seed = randomSeeds[17];
  23284. ShapeUtils._randomPointUnitSphere(direction, rand);
  23285. randomSeeds[17] = rand.seed;
  23286. }
  23287. else {
  23288. ShapeUtils._randomPointUnitSphere(direction);
  23289. }
  23290. }
  23291. else {
  23292. position.cloneTo(direction);
  23293. }
  23294. }
  23295. cloneTo(destObject) {
  23296. super.cloneTo(destObject);
  23297. var destShape = destObject;
  23298. destShape.radius = this.radius;
  23299. destShape.emitFromShell = this.emitFromShell;
  23300. destShape.randomDirection = this.randomDirection;
  23301. }
  23302. clone() {
  23303. var destShape = new HemisphereShape();
  23304. this.cloneTo(destShape);
  23305. return destShape;
  23306. }
  23307. }
  23308. class SphereShape extends BaseShape {
  23309. constructor() {
  23310. super();
  23311. this.shapeType = exports.ParticleSystemShapeType.Sphere;
  23312. this.radius = 1.0;
  23313. this.emitFromShell = false;
  23314. }
  23315. _getShapeBoundBox(boundBox) {
  23316. var min = boundBox.min;
  23317. min.x = min.y = min.z = -this.radius;
  23318. var max = boundBox.max;
  23319. max.x = max.y = max.z = this.radius;
  23320. }
  23321. _getSpeedBoundBox(boundBox) {
  23322. var min = boundBox.min;
  23323. min.x = min.y = min.z = -1;
  23324. var max = boundBox.max;
  23325. max.x = max.y = max.z = 1;
  23326. }
  23327. generatePositionAndDirection(position, direction, rand = null, randomSeeds = null) {
  23328. if (rand) {
  23329. rand.seed = randomSeeds[16];
  23330. if (this.emitFromShell)
  23331. ShapeUtils._randomPointUnitSphere(position, rand);
  23332. else
  23333. ShapeUtils._randomPointInsideUnitSphere(position, rand);
  23334. randomSeeds[16] = rand.seed;
  23335. }
  23336. else {
  23337. if (this.emitFromShell)
  23338. ShapeUtils._randomPointUnitSphere(position);
  23339. else
  23340. ShapeUtils._randomPointInsideUnitSphere(position);
  23341. }
  23342. Vector3.scale(position, this.radius, position);
  23343. if (this.randomDirection) {
  23344. if (rand) {
  23345. rand.seed = randomSeeds[17];
  23346. ShapeUtils._randomPointUnitSphere(direction, rand);
  23347. randomSeeds[17] = rand.seed;
  23348. }
  23349. else {
  23350. ShapeUtils._randomPointUnitSphere(direction);
  23351. }
  23352. }
  23353. else {
  23354. position.cloneTo(direction);
  23355. }
  23356. }
  23357. cloneTo(destObject) {
  23358. super.cloneTo(destObject);
  23359. var destShape = destObject;
  23360. destShape.radius = this.radius;
  23361. destShape.emitFromShell = this.emitFromShell;
  23362. destShape.randomDirection = this.randomDirection;
  23363. }
  23364. clone() {
  23365. var destShape = new SphereShape();
  23366. this.cloneTo(destShape);
  23367. return destShape;
  23368. }
  23369. }
  23370. class SizeOverLifetime {
  23371. constructor(size) {
  23372. this._size = size;
  23373. }
  23374. get size() {
  23375. return this._size;
  23376. }
  23377. cloneTo(destObject) {
  23378. var destSizeOverLifetime = destObject;
  23379. this._size.cloneTo(destSizeOverLifetime._size);
  23380. destSizeOverLifetime.enable = this.enable;
  23381. }
  23382. clone() {
  23383. var destSize;
  23384. switch (this._size.type) {
  23385. case 0:
  23386. if (this._size.separateAxes)
  23387. destSize = GradientSize.createByGradientSeparate(this._size.gradientX.clone(), this._size.gradientY.clone(), this._size.gradientZ.clone());
  23388. else
  23389. destSize = GradientSize.createByGradient(this._size.gradient.clone());
  23390. break;
  23391. case 1:
  23392. if (this._size.separateAxes)
  23393. destSize = GradientSize.createByRandomTwoConstantSeparate(this._size.constantMinSeparate.clone(), this._size.constantMaxSeparate.clone());
  23394. else
  23395. destSize = GradientSize.createByRandomTwoConstant(this._size.constantMin, this._size.constantMax);
  23396. break;
  23397. case 2:
  23398. if (this._size.separateAxes)
  23399. destSize = GradientSize.createByRandomTwoGradientSeparate(this._size.gradientXMin.clone(), this._size.gradientYMin.clone(), this._size.gradientZMin.clone(), this._size.gradientXMax.clone(), this._size.gradientYMax.clone(), this._size.gradientZMax.clone());
  23400. else
  23401. destSize = GradientSize.createByRandomTwoGradient(this._size.gradientMin.clone(), this._size.gradientMax.clone());
  23402. break;
  23403. }
  23404. var destSizeOverLifetime = new SizeOverLifetime(destSize);
  23405. destSizeOverLifetime.enable = this.enable;
  23406. return destSizeOverLifetime;
  23407. }
  23408. }
  23409. class StartFrame {
  23410. constructor() {
  23411. this._type = 0;
  23412. this._constant = 0;
  23413. this._constantMin = 0;
  23414. this._constantMax = 0;
  23415. }
  23416. static createByConstant(constant = 0) {
  23417. var rotationOverLifetime = new StartFrame();
  23418. rotationOverLifetime._type = 0;
  23419. rotationOverLifetime._constant = constant;
  23420. return rotationOverLifetime;
  23421. }
  23422. static createByRandomTwoConstant(constantMin = 0, constantMax = 0) {
  23423. var rotationOverLifetime = new StartFrame();
  23424. rotationOverLifetime._type = 1;
  23425. rotationOverLifetime._constantMin = constantMin;
  23426. rotationOverLifetime._constantMax = constantMax;
  23427. return rotationOverLifetime;
  23428. }
  23429. get type() {
  23430. return this._type;
  23431. }
  23432. get constant() {
  23433. return this._constant;
  23434. }
  23435. get constantMin() {
  23436. return this._constantMin;
  23437. }
  23438. get constantMax() {
  23439. return this._constantMax;
  23440. }
  23441. cloneTo(destObject) {
  23442. var destStartFrame = destObject;
  23443. destStartFrame._type = this._type;
  23444. destStartFrame._constant = this._constant;
  23445. destStartFrame._constantMin = this._constantMin;
  23446. destStartFrame._constantMax = this._constantMax;
  23447. }
  23448. clone() {
  23449. var destStartFrame = new StartFrame();
  23450. this.cloneTo(destStartFrame);
  23451. return destStartFrame;
  23452. }
  23453. }
  23454. class TextureSheetAnimation {
  23455. constructor(frame, startFrame) {
  23456. this.type = 0;
  23457. this.randomRow = false;
  23458. this.rowIndex = 0;
  23459. this.cycles = 0;
  23460. this.enableUVChannels = 0;
  23461. this.enable = false;
  23462. this.tiles = new Vector2(1, 1);
  23463. this.type = 0;
  23464. this.randomRow = true;
  23465. this.rowIndex = 0;
  23466. this.cycles = 1;
  23467. this.enableUVChannels = 1;
  23468. this._frame = frame;
  23469. this._startFrame = startFrame;
  23470. }
  23471. get frame() {
  23472. return this._frame;
  23473. }
  23474. get startFrame() {
  23475. return this._startFrame;
  23476. }
  23477. cloneTo(destObject) {
  23478. var destTextureSheetAnimation = destObject;
  23479. this.tiles.cloneTo(destTextureSheetAnimation.tiles);
  23480. destTextureSheetAnimation.type = this.type;
  23481. destTextureSheetAnimation.randomRow = this.randomRow;
  23482. destTextureSheetAnimation.rowIndex = this.rowIndex;
  23483. destTextureSheetAnimation.cycles = this.cycles;
  23484. destTextureSheetAnimation.enableUVChannels = this.enableUVChannels;
  23485. destTextureSheetAnimation.enable = this.enable;
  23486. this._frame.cloneTo(destTextureSheetAnimation._frame);
  23487. this._startFrame.cloneTo(destTextureSheetAnimation._startFrame);
  23488. }
  23489. clone() {
  23490. var destFrame;
  23491. switch (this._frame.type) {
  23492. case 0:
  23493. destFrame = FrameOverTime.createByConstant(this._frame.constant);
  23494. break;
  23495. case 1:
  23496. destFrame = FrameOverTime.createByOverTime(this._frame.frameOverTimeData.clone());
  23497. break;
  23498. case 2:
  23499. destFrame = FrameOverTime.createByRandomTwoConstant(this._frame.constantMin, this._frame.constantMax);
  23500. break;
  23501. case 3:
  23502. destFrame = FrameOverTime.createByRandomTwoOverTime(this._frame.frameOverTimeDataMin.clone(), this._frame.frameOverTimeDataMax.clone());
  23503. break;
  23504. }
  23505. var destStartFrame;
  23506. switch (this._startFrame.type) {
  23507. case 0:
  23508. destStartFrame = StartFrame.createByConstant(this._startFrame.constant);
  23509. break;
  23510. case 1:
  23511. destStartFrame = StartFrame.createByRandomTwoConstant(this._startFrame.constantMin, this._startFrame.constantMax);
  23512. break;
  23513. }
  23514. var destTextureSheetAnimation = new TextureSheetAnimation(destFrame, destStartFrame);
  23515. this.cloneTo(destTextureSheetAnimation);
  23516. return destTextureSheetAnimation;
  23517. }
  23518. }
  23519. class VelocityOverLifetime {
  23520. constructor(velocity) {
  23521. this.enable = false;
  23522. this.space = 0;
  23523. this._velocity = velocity;
  23524. }
  23525. get velocity() {
  23526. return this._velocity;
  23527. }
  23528. cloneTo(destObject) {
  23529. var destVelocityOverLifetime = destObject;
  23530. this._velocity.cloneTo(destVelocityOverLifetime._velocity);
  23531. destVelocityOverLifetime.enable = this.enable;
  23532. destVelocityOverLifetime.space = this.space;
  23533. }
  23534. clone() {
  23535. var destVelocity;
  23536. switch (this._velocity.type) {
  23537. case 0:
  23538. destVelocity = GradientVelocity.createByConstant(this._velocity.constant.clone());
  23539. break;
  23540. case 1:
  23541. destVelocity = GradientVelocity.createByGradient(this._velocity.gradientX.clone(), this._velocity.gradientY.clone(), this._velocity.gradientZ.clone());
  23542. break;
  23543. case 2:
  23544. destVelocity = GradientVelocity.createByRandomTwoConstant(this._velocity.constantMin.clone(), this._velocity.constantMax.clone());
  23545. break;
  23546. case 3:
  23547. destVelocity = GradientVelocity.createByRandomTwoGradient(this._velocity.gradientXMin.clone(), this._velocity.gradientXMax.clone(), this._velocity.gradientYMin.clone(), this._velocity.gradientYMax.clone(), this._velocity.gradientZMin.clone(), this._velocity.gradientZMax.clone());
  23548. break;
  23549. }
  23550. var destVelocityOverLifetime = new VelocityOverLifetime(destVelocity);
  23551. destVelocityOverLifetime.enable = this.enable;
  23552. destVelocityOverLifetime.space = this.space;
  23553. return destVelocityOverLifetime;
  23554. }
  23555. }
  23556. class ShuriKenParticle3DShaderDeclaration {
  23557. }
  23558. ShuriKenParticle3DShaderDeclaration.WORLDPOSITION = Shader3D.propertyNameToID("u_WorldPosition");
  23559. ShuriKenParticle3DShaderDeclaration.WORLDROTATION = Shader3D.propertyNameToID("u_WorldRotation");
  23560. ShuriKenParticle3DShaderDeclaration.POSITIONSCALE = Shader3D.propertyNameToID("u_PositionScale");
  23561. ShuriKenParticle3DShaderDeclaration.SIZESCALE = Shader3D.propertyNameToID("u_SizeScale");
  23562. ShuriKenParticle3DShaderDeclaration.SCALINGMODE = Shader3D.propertyNameToID("u_ScalingMode");
  23563. ShuriKenParticle3DShaderDeclaration.GRAVITY = Shader3D.propertyNameToID("u_Gravity");
  23564. ShuriKenParticle3DShaderDeclaration.THREEDSTARTROTATION = Shader3D.propertyNameToID("u_ThreeDStartRotation");
  23565. ShuriKenParticle3DShaderDeclaration.STRETCHEDBILLBOARDLENGTHSCALE = Shader3D.propertyNameToID("u_StretchedBillboardLengthScale");
  23566. ShuriKenParticle3DShaderDeclaration.STRETCHEDBILLBOARDSPEEDSCALE = Shader3D.propertyNameToID("u_StretchedBillboardSpeedScale");
  23567. ShuriKenParticle3DShaderDeclaration.SIMULATIONSPACE = Shader3D.propertyNameToID("u_SimulationSpace");
  23568. ShuriKenParticle3DShaderDeclaration.CURRENTTIME = Shader3D.propertyNameToID("u_CurrentTime");
  23569. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYCONST = Shader3D.propertyNameToID("u_VOLVelocityConst");
  23570. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTX = Shader3D.propertyNameToID("u_VOLVelocityGradientX");
  23571. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTY = Shader3D.propertyNameToID("u_VOLVelocityGradientY");
  23572. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTZ = Shader3D.propertyNameToID("u_VOLVelocityGradientZ");
  23573. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYCONSTMAX = Shader3D.propertyNameToID("u_VOLVelocityConstMax");
  23574. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTXMAX = Shader3D.propertyNameToID("u_VOLVelocityGradientMaxX");
  23575. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTYMAX = Shader3D.propertyNameToID("u_VOLVelocityGradientMaxY");
  23576. ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTZMAX = Shader3D.propertyNameToID("u_VOLVelocityGradientMaxZ");
  23577. ShuriKenParticle3DShaderDeclaration.VOLSPACETYPE = Shader3D.propertyNameToID("u_VOLSpaceType");
  23578. ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTALPHAS = Shader3D.propertyNameToID("u_ColorOverLifeGradientAlphas");
  23579. ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTCOLORS = Shader3D.propertyNameToID("u_ColorOverLifeGradientColors");
  23580. ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTALPHAS = Shader3D.propertyNameToID("u_MaxColorOverLifeGradientAlphas");
  23581. ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTCOLORS = Shader3D.propertyNameToID("u_MaxColorOverLifeGradientColors");
  23582. ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENT = Shader3D.propertyNameToID("u_SOLSizeGradient");
  23583. ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTX = Shader3D.propertyNameToID("u_SOLSizeGradientX");
  23584. ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTY = Shader3D.propertyNameToID("u_SOLSizeGradientY");
  23585. ShuriKenParticle3DShaderDeclaration.SOLSizeGradientZ = Shader3D.propertyNameToID("u_SOLSizeGradientZ");
  23586. ShuriKenParticle3DShaderDeclaration.SOLSizeGradientMax = Shader3D.propertyNameToID("u_SOLSizeGradientMax");
  23587. ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTXMAX = Shader3D.propertyNameToID("u_SOLSizeGradientMaxX");
  23588. ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTYMAX = Shader3D.propertyNameToID("u_SOLSizeGradientMaxY");
  23589. ShuriKenParticle3DShaderDeclaration.SOLSizeGradientZMAX = Shader3D.propertyNameToID("u_SOLSizeGradientMaxZ");
  23590. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONST = Shader3D.propertyNameToID("u_ROLAngularVelocityConst");
  23591. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTSEPRARATE = Shader3D.propertyNameToID("u_ROLAngularVelocityConstSeprarate");
  23592. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENT = Shader3D.propertyNameToID("u_ROLAngularVelocityGradient");
  23593. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientX");
  23594. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTY = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientY");
  23595. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTZ = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientZ");
  23596. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityConstMax");
  23597. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTMAXSEPRARATE = Shader3D.propertyNameToID("u_ROLAngularVelocityConstMaxSeprarate");
  23598. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientMax");
  23599. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTXMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientMaxX");
  23600. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTYMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientMaxY");
  23601. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTZMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientMaxZ");
  23602. ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTWMAX = Shader3D.propertyNameToID("u_ROLAngularVelocityGradientMaxW");
  23603. ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONCYCLES = Shader3D.propertyNameToID("u_TSACycles");
  23604. ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONSUBUVLENGTH = Shader3D.propertyNameToID("u_TSASubUVLength");
  23605. ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONGRADIENTUVS = Shader3D.propertyNameToID("u_TSAGradientUVs");
  23606. ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONGRADIENTMAXUVS = Shader3D.propertyNameToID("u_TSAMaxGradientUVs");
  23607. class ShurikenParticleMaterial extends Material {
  23608. constructor() {
  23609. super();
  23610. this.setShaderName("PARTICLESHURIKEN");
  23611. this._color = new Vector4(1.0, 1.0, 1.0, 1.0);
  23612. this.renderMode = ShurikenParticleMaterial.RENDERMODE_ALPHABLENDED;
  23613. }
  23614. static __initDefine__() {
  23615. ShurikenParticleMaterial.SHADERDEFINE_DIFFUSEMAP = Shader3D.getDefineByName("DIFFUSEMAP");
  23616. ShurikenParticleMaterial.SHADERDEFINE_TINTCOLOR = Shader3D.getDefineByName("TINTCOLOR");
  23617. ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG = Shader3D.getDefineByName("ADDTIVEFOG");
  23618. ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  23619. }
  23620. get _TintColor() {
  23621. return this.color;
  23622. }
  23623. set _TintColor(value) {
  23624. this.color = value;
  23625. }
  23626. get _TintColorR() {
  23627. return this._color.x;
  23628. }
  23629. set _TintColorR(value) {
  23630. this._color.x = value;
  23631. this.color = this._color;
  23632. }
  23633. get _TintColorG() {
  23634. return this._color.y;
  23635. }
  23636. set _TintColorG(value) {
  23637. this._color.y = value;
  23638. this.color = this._color;
  23639. }
  23640. get _TintColorB() {
  23641. return this._color.z;
  23642. }
  23643. set _TintColorB(value) {
  23644. this._color.z = value;
  23645. this.color = this._color;
  23646. }
  23647. get _TintColorA() {
  23648. return this._color.w;
  23649. }
  23650. set _TintColorA(value) {
  23651. this._color.w = value;
  23652. this.color = this._color;
  23653. }
  23654. get _MainTex_ST() {
  23655. return this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET);
  23656. }
  23657. set _MainTex_ST(value) {
  23658. var tilOff = this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET);
  23659. tilOff.setValue(value.x, value.y, value.z, value.w);
  23660. this.tilingOffset = tilOff;
  23661. }
  23662. get _MainTex_STX() {
  23663. return this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET).x;
  23664. }
  23665. set _MainTex_STX(x) {
  23666. var tilOff = this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET);
  23667. tilOff.x = x;
  23668. this.tilingOffset = tilOff;
  23669. }
  23670. get _MainTex_STY() {
  23671. return this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET).y;
  23672. }
  23673. set _MainTex_STY(y) {
  23674. var tilOff = this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET);
  23675. tilOff.y = y;
  23676. this.tilingOffset = tilOff;
  23677. }
  23678. get _MainTex_STZ() {
  23679. return this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET).z;
  23680. }
  23681. set _MainTex_STZ(z) {
  23682. var tilOff = this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET);
  23683. tilOff.z = z;
  23684. this.tilingOffset = tilOff;
  23685. }
  23686. get _MainTex_STW() {
  23687. return this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET).w;
  23688. }
  23689. set _MainTex_STW(w) {
  23690. var tilOff = this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET);
  23691. tilOff.w = w;
  23692. this.tilingOffset = tilOff;
  23693. }
  23694. set renderMode(value) {
  23695. switch (value) {
  23696. case ShurikenParticleMaterial.RENDERMODE_ADDTIVE:
  23697. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  23698. this.depthWrite = false;
  23699. this.cull = RenderState.CULL_NONE;
  23700. this.blend = RenderState.BLEND_ENABLE_ALL;
  23701. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  23702. this.blendDst = RenderState.BLENDPARAM_ONE;
  23703. this.alphaTest = false;
  23704. this._shaderValues.addDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG);
  23705. break;
  23706. case ShurikenParticleMaterial.RENDERMODE_ALPHABLENDED:
  23707. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  23708. this.depthWrite = false;
  23709. this.cull = RenderState.CULL_NONE;
  23710. this.blend = RenderState.BLEND_ENABLE_ALL;
  23711. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  23712. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  23713. this.alphaTest = false;
  23714. this._shaderValues.removeDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG);
  23715. break;
  23716. default:
  23717. throw new Error("ShurikenParticleMaterial : renderMode value error.");
  23718. }
  23719. }
  23720. get colorR() {
  23721. return this._TintColorR;
  23722. }
  23723. set colorR(value) {
  23724. this._TintColorR = value;
  23725. }
  23726. get colorG() {
  23727. return this._TintColorG;
  23728. }
  23729. set colorG(value) {
  23730. this._TintColorG = value;
  23731. }
  23732. get colorB() {
  23733. return this._TintColorB;
  23734. }
  23735. set colorB(value) {
  23736. this._TintColorB = value;
  23737. }
  23738. get colorA() {
  23739. return this._TintColorA;
  23740. }
  23741. set colorA(value) {
  23742. this._TintColorA = value;
  23743. }
  23744. get color() {
  23745. return this._shaderValues.getVector(ShurikenParticleMaterial.TINTCOLOR);
  23746. }
  23747. set color(value) {
  23748. if (value)
  23749. this._shaderValues.addDefine(ShurikenParticleMaterial.SHADERDEFINE_TINTCOLOR);
  23750. else
  23751. this._shaderValues.removeDefine(ShurikenParticleMaterial.SHADERDEFINE_TINTCOLOR);
  23752. this._shaderValues.setVector(ShurikenParticleMaterial.TINTCOLOR, value);
  23753. }
  23754. get tilingOffsetX() {
  23755. return this._MainTex_STX;
  23756. }
  23757. set tilingOffsetX(x) {
  23758. this._MainTex_STX = x;
  23759. }
  23760. get tilingOffsetY() {
  23761. return this._MainTex_STY;
  23762. }
  23763. set tilingOffsetY(y) {
  23764. this._MainTex_STY = y;
  23765. }
  23766. get tilingOffsetZ() {
  23767. return this._MainTex_STZ;
  23768. }
  23769. set tilingOffsetZ(z) {
  23770. this._MainTex_STZ = z;
  23771. }
  23772. get tilingOffsetW() {
  23773. return this._MainTex_STW;
  23774. }
  23775. set tilingOffsetW(w) {
  23776. this._MainTex_STW = w;
  23777. }
  23778. get tilingOffset() {
  23779. return this._shaderValues.getVector(ShurikenParticleMaterial.TILINGOFFSET);
  23780. }
  23781. set tilingOffset(value) {
  23782. if (value) {
  23783. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  23784. this._shaderValues.addDefine(ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET);
  23785. else
  23786. this._shaderValues.removeDefine(ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET);
  23787. }
  23788. else {
  23789. this._shaderValues.removeDefine(ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET);
  23790. }
  23791. this._shaderValues.setVector(ShurikenParticleMaterial.TILINGOFFSET, value);
  23792. }
  23793. get texture() {
  23794. return this._shaderValues.getTexture(ShurikenParticleMaterial.DIFFUSETEXTURE);
  23795. }
  23796. set texture(value) {
  23797. if (value)
  23798. this._shaderValues.addDefine(ShurikenParticleMaterial.SHADERDEFINE_DIFFUSEMAP);
  23799. else
  23800. this._shaderValues.removeDefine(ShurikenParticleMaterial.SHADERDEFINE_DIFFUSEMAP);
  23801. this._shaderValues.setTexture(ShurikenParticleMaterial.DIFFUSETEXTURE, value);
  23802. }
  23803. clone() {
  23804. var dest = new ShurikenParticleMaterial();
  23805. this.cloneTo(dest);
  23806. return dest;
  23807. }
  23808. }
  23809. ShurikenParticleMaterial.RENDERMODE_ALPHABLENDED = 0;
  23810. ShurikenParticleMaterial.RENDERMODE_ADDTIVE = 1;
  23811. ShurikenParticleMaterial.DIFFUSETEXTURE = Shader3D.propertyNameToID("u_texture");
  23812. ShurikenParticleMaterial.TINTCOLOR = Shader3D.propertyNameToID("u_Tintcolor");
  23813. ShurikenParticleMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  23814. class ShurikenParticleRenderer extends BaseRender {
  23815. constructor(owner) {
  23816. super(owner);
  23817. this._finalGravity = new Vector3();
  23818. this._tempRotationMatrix = new Matrix4x4();
  23819. this._mesh = null;
  23820. this.stretchedBillboardCameraSpeedScale = 0;
  23821. this.stretchedBillboardSpeedScale = 0;
  23822. this.stretchedBillboardLengthScale = 2;
  23823. this._defaultBoundBox = new BoundBox(new Vector3(), new Vector3());
  23824. this.renderMode = 0;
  23825. this._supportOctree = false;
  23826. }
  23827. get renderMode() {
  23828. return this._renderMode;
  23829. }
  23830. set renderMode(value) {
  23831. if (this._renderMode !== value) {
  23832. var defineDatas = this._shaderValues;
  23833. switch (this._renderMode) {
  23834. case 0:
  23835. defineDatas.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_BILLBOARD);
  23836. break;
  23837. case 1:
  23838. defineDatas.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_STRETCHEDBILLBOARD);
  23839. break;
  23840. case 2:
  23841. defineDatas.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_HORIZONTALBILLBOARD);
  23842. break;
  23843. case 3:
  23844. defineDatas.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_VERTICALBILLBOARD);
  23845. break;
  23846. case 4:
  23847. defineDatas.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_MESH);
  23848. break;
  23849. }
  23850. this._renderMode = value;
  23851. switch (value) {
  23852. case 0:
  23853. defineDatas.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_BILLBOARD);
  23854. break;
  23855. case 1:
  23856. defineDatas.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_STRETCHEDBILLBOARD);
  23857. break;
  23858. case 2:
  23859. defineDatas.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_HORIZONTALBILLBOARD);
  23860. break;
  23861. case 3:
  23862. defineDatas.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_VERTICALBILLBOARD);
  23863. break;
  23864. case 4:
  23865. defineDatas.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_MESH);
  23866. break;
  23867. default:
  23868. throw new Error("ShurikenParticleRender: unknown renderMode Value.");
  23869. }
  23870. var parSys = this._owner.particleSystem;
  23871. (parSys) && (parSys._initBufferDatas());
  23872. }
  23873. }
  23874. get mesh() {
  23875. return this._mesh;
  23876. }
  23877. set mesh(value) {
  23878. if (this._mesh !== value) {
  23879. (this._mesh) && (this._mesh._removeReference());
  23880. this._mesh = value;
  23881. (value) && (value._addReference());
  23882. this._owner.particleSystem._initBufferDatas();
  23883. }
  23884. }
  23885. _calculateBoundingBox() {
  23886. var particleSystem = this._owner.particleSystem;
  23887. var bounds;
  23888. if (particleSystem._useCustomBounds) {
  23889. bounds = particleSystem.customBounds;
  23890. bounds._tranform(this._owner.transform.worldMatrix, this._bounds);
  23891. }
  23892. else if (particleSystem._simulationSupported()) {
  23893. particleSystem._generateBounds();
  23894. bounds = particleSystem._bounds;
  23895. bounds._tranform(this._owner.transform.worldMatrix, this._bounds);
  23896. if (particleSystem.gravityModifier != 0) {
  23897. var max = this._bounds.getMax();
  23898. var min = this._bounds.getMin();
  23899. var gravityOffset = particleSystem._gravityOffset;
  23900. max.y -= gravityOffset.x;
  23901. min.y -= gravityOffset.y;
  23902. this._bounds.setMax(max);
  23903. this._bounds.setMin(min);
  23904. }
  23905. }
  23906. else {
  23907. var min = this._bounds.getMin();
  23908. min.setValue(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  23909. this._bounds.setMin(min);
  23910. var max = this._bounds.getMax();
  23911. max.setValue(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23912. this._bounds.setMax(max);
  23913. }
  23914. }
  23915. _needRender(boundFrustum, context) {
  23916. if (boundFrustum) {
  23917. if (boundFrustum.intersects(this.bounds._getBoundBox())) {
  23918. if (this._owner.particleSystem.isAlive)
  23919. return true;
  23920. else
  23921. return false;
  23922. }
  23923. else {
  23924. return false;
  23925. }
  23926. }
  23927. else {
  23928. return true;
  23929. }
  23930. }
  23931. _renderUpdate(context, transfrom) {
  23932. var particleSystem = this._owner.particleSystem;
  23933. var sv = this._shaderValues;
  23934. var transform = this._owner.transform;
  23935. switch (particleSystem.simulationSpace) {
  23936. case 0:
  23937. break;
  23938. case 1:
  23939. sv.setVector3(ShuriKenParticle3DShaderDeclaration.WORLDPOSITION, transform.position);
  23940. sv.setQuaternion(ShuriKenParticle3DShaderDeclaration.WORLDROTATION, transform.rotation);
  23941. break;
  23942. default:
  23943. throw new Error("ShurikenParticleMaterial: SimulationSpace value is invalid.");
  23944. }
  23945. switch (particleSystem.scaleMode) {
  23946. case 0:
  23947. var scale = transform.getWorldLossyScale();
  23948. sv.setVector3(ShuriKenParticle3DShaderDeclaration.POSITIONSCALE, scale);
  23949. sv.setVector3(ShuriKenParticle3DShaderDeclaration.SIZESCALE, scale);
  23950. break;
  23951. case 1:
  23952. var localScale = transform.localScale;
  23953. sv.setVector3(ShuriKenParticle3DShaderDeclaration.POSITIONSCALE, localScale);
  23954. sv.setVector3(ShuriKenParticle3DShaderDeclaration.SIZESCALE, localScale);
  23955. break;
  23956. case 2:
  23957. sv.setVector3(ShuriKenParticle3DShaderDeclaration.POSITIONSCALE, transform.getWorldLossyScale());
  23958. sv.setVector3(ShuriKenParticle3DShaderDeclaration.SIZESCALE, Vector3._ONE);
  23959. break;
  23960. }
  23961. Vector3.scale(Physics3DUtils.gravity, particleSystem.gravityModifier, this._finalGravity);
  23962. sv.setVector3(ShuriKenParticle3DShaderDeclaration.GRAVITY, this._finalGravity);
  23963. sv.setInt(ShuriKenParticle3DShaderDeclaration.SIMULATIONSPACE, particleSystem.simulationSpace);
  23964. sv.setBool(ShuriKenParticle3DShaderDeclaration.THREEDSTARTROTATION, particleSystem.threeDStartRotation);
  23965. sv.setInt(ShuriKenParticle3DShaderDeclaration.SCALINGMODE, particleSystem.scaleMode);
  23966. sv.setNumber(ShuriKenParticle3DShaderDeclaration.STRETCHEDBILLBOARDLENGTHSCALE, this.stretchedBillboardLengthScale);
  23967. sv.setNumber(ShuriKenParticle3DShaderDeclaration.STRETCHEDBILLBOARDSPEEDSCALE, this.stretchedBillboardSpeedScale);
  23968. sv.setNumber(ShuriKenParticle3DShaderDeclaration.CURRENTTIME, particleSystem._currentTime);
  23969. }
  23970. get bounds() {
  23971. if (this._boundsChange) {
  23972. this._calculateBoundingBox();
  23973. this._boundsChange = false;
  23974. }
  23975. return this._bounds;
  23976. }
  23977. _destroy() {
  23978. super._destroy();
  23979. (this._mesh) && (this._mesh._removeReference(), this._mesh = null);
  23980. }
  23981. }
  23982. class VertexShuriKenParticle {
  23983. constructor() {
  23984. }
  23985. }
  23986. VertexShuriKenParticle.PARTICLE_CORNERTEXTURECOORDINATE0 = 5;
  23987. VertexShuriKenParticle.PARTICLE_POSITION0 = 1;
  23988. VertexShuriKenParticle.PARTICLE_COLOR0 = 2;
  23989. VertexShuriKenParticle.PARTICLE_TEXTURECOORDINATE0 = 3;
  23990. VertexShuriKenParticle.PARTICLE_SHAPEPOSITIONSTARTLIFETIME = 4;
  23991. VertexShuriKenParticle.PARTICLE_DIRECTIONTIME = 0;
  23992. VertexShuriKenParticle.PARTICLE_STARTCOLOR0 = 6;
  23993. VertexShuriKenParticle.PARTICLE_ENDCOLOR0 = 7;
  23994. VertexShuriKenParticle.PARTICLE_STARTSIZE = 8;
  23995. VertexShuriKenParticle.PARTICLE_STARTROTATION = 9;
  23996. VertexShuriKenParticle.PARTICLE_STARTSPEED = 10;
  23997. VertexShuriKenParticle.PARTICLE_RANDOM0 = 11;
  23998. VertexShuriKenParticle.PARTICLE_RANDOM1 = 12;
  23999. VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDPOSTION = 13;
  24000. VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDROTATION = 14;
  24001. class VertexShurikenParticleBillboard extends VertexShuriKenParticle {
  24002. constructor(cornerTextureCoordinate, positionStartLifeTime, velocity, startColor, startSize, startRotation0, startRotation1, startRotation2, ageAddScale, time, startSpeed, randoms0, randoms1, simulationWorldPostion) {
  24003. super();
  24004. this._cornerTextureCoordinate = cornerTextureCoordinate;
  24005. this._positionStartLifeTime = positionStartLifeTime;
  24006. this._velocity = velocity;
  24007. this._startColor = startColor;
  24008. this._startSize = startSize;
  24009. this._startRotation0 = startRotation0;
  24010. this._startRotation1 = startRotation1;
  24011. this._startRotation2 = startRotation2;
  24012. this._startLifeTime = ageAddScale;
  24013. this._time = time;
  24014. this._startSpeed = startSpeed;
  24015. this._randoms0 = this.random0;
  24016. this._randoms1 = this.random1;
  24017. this._simulationWorldPostion = simulationWorldPostion;
  24018. }
  24019. static get vertexDeclaration() {
  24020. return VertexShurikenParticleBillboard._vertexDeclaration;
  24021. }
  24022. static __init__() {
  24023. VertexShurikenParticleBillboard._vertexDeclaration = new VertexDeclaration(152, [new VertexElement(0, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_CORNERTEXTURECOORDINATE0),
  24024. new VertexElement(16, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_SHAPEPOSITIONSTARTLIFETIME),
  24025. new VertexElement(32, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_DIRECTIONTIME),
  24026. new VertexElement(48, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_STARTCOLOR0),
  24027. new VertexElement(64, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_STARTSIZE),
  24028. new VertexElement(76, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_STARTROTATION),
  24029. new VertexElement(88, VertexElementFormat.Single, VertexShuriKenParticle.PARTICLE_STARTSPEED),
  24030. new VertexElement(92, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_RANDOM0),
  24031. new VertexElement(108, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_RANDOM1),
  24032. new VertexElement(124, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDPOSTION),
  24033. new VertexElement(136, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDROTATION)]);
  24034. }
  24035. get cornerTextureCoordinate() {
  24036. return this._cornerTextureCoordinate;
  24037. }
  24038. get positionStartLifeTime() {
  24039. return this._positionStartLifeTime;
  24040. }
  24041. get velocity() {
  24042. return this._velocity;
  24043. }
  24044. get startColor() {
  24045. return this._startColor;
  24046. }
  24047. get startSize() {
  24048. return this._startSize;
  24049. }
  24050. get startRotation0() {
  24051. return this._startRotation0;
  24052. }
  24053. get startRotation1() {
  24054. return this._startRotation1;
  24055. }
  24056. get startRotation2() {
  24057. return this._startRotation2;
  24058. }
  24059. get startLifeTime() {
  24060. return this._startLifeTime;
  24061. }
  24062. get time() {
  24063. return this._time;
  24064. }
  24065. get startSpeed() {
  24066. return this._startSpeed;
  24067. }
  24068. get random0() {
  24069. return this._randoms0;
  24070. }
  24071. get random1() {
  24072. return this._randoms1;
  24073. }
  24074. get simulationWorldPostion() {
  24075. return this._simulationWorldPostion;
  24076. }
  24077. }
  24078. class VertexShurikenParticleMesh extends VertexShuriKenParticle {
  24079. constructor(cornerTextureCoordinate, positionStartLifeTime, velocity, startColor, startSize, startRotation0, startRotation1, startRotation2, ageAddScale, time, startSpeed, randoms0, randoms1, simulationWorldPostion) {
  24080. super();
  24081. this._cornerTextureCoordinate = cornerTextureCoordinate;
  24082. this._positionStartLifeTime = positionStartLifeTime;
  24083. this._velocity = velocity;
  24084. this._startColor = startColor;
  24085. this._startSize = startSize;
  24086. this._startRotation0 = startRotation0;
  24087. this._startRotation1 = startRotation1;
  24088. this._startRotation2 = startRotation2;
  24089. this._startLifeTime = ageAddScale;
  24090. this._time = time;
  24091. this._startSpeed = startSpeed;
  24092. this._randoms0 = this.random0;
  24093. this._randoms1 = this.random1;
  24094. this._simulationWorldPostion = simulationWorldPostion;
  24095. }
  24096. static __init__() {
  24097. VertexShurikenParticleMesh._vertexDeclaration = new VertexDeclaration(172, [new VertexElement(0, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_POSITION0),
  24098. new VertexElement(12, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_COLOR0),
  24099. new VertexElement(28, VertexElementFormat.Vector2, VertexShuriKenParticle.PARTICLE_TEXTURECOORDINATE0),
  24100. new VertexElement(36, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_SHAPEPOSITIONSTARTLIFETIME),
  24101. new VertexElement(52, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_DIRECTIONTIME),
  24102. new VertexElement(68, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_STARTCOLOR0),
  24103. new VertexElement(84, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_STARTSIZE),
  24104. new VertexElement(96, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_STARTROTATION),
  24105. new VertexElement(108, VertexElementFormat.Single, VertexShuriKenParticle.PARTICLE_STARTSPEED),
  24106. new VertexElement(112, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_RANDOM0),
  24107. new VertexElement(128, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_RANDOM1),
  24108. new VertexElement(144, VertexElementFormat.Vector3, VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDPOSTION),
  24109. new VertexElement(156, VertexElementFormat.Vector4, VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDROTATION)]);
  24110. }
  24111. static get vertexDeclaration() {
  24112. return VertexShurikenParticleMesh._vertexDeclaration;
  24113. }
  24114. get cornerTextureCoordinate() {
  24115. return this._cornerTextureCoordinate;
  24116. }
  24117. get position() {
  24118. return this._positionStartLifeTime;
  24119. }
  24120. get velocity() {
  24121. return this._velocity;
  24122. }
  24123. get startColor() {
  24124. return this._startColor;
  24125. }
  24126. get startSize() {
  24127. return this._startSize;
  24128. }
  24129. get startRotation0() {
  24130. return this._startRotation0;
  24131. }
  24132. get startRotation1() {
  24133. return this._startRotation1;
  24134. }
  24135. get startRotation2() {
  24136. return this._startRotation2;
  24137. }
  24138. get startLifeTime() {
  24139. return this._startLifeTime;
  24140. }
  24141. get time() {
  24142. return this._time;
  24143. }
  24144. get startSpeed() {
  24145. return this._startSpeed;
  24146. }
  24147. get random0() {
  24148. return this._randoms0;
  24149. }
  24150. get random1() {
  24151. return this._randoms1;
  24152. }
  24153. get simulationWorldPostion() {
  24154. return this._simulationWorldPostion;
  24155. }
  24156. }
  24157. class Rand {
  24158. constructor(seed) {
  24159. this._temp = new Uint32Array(1);
  24160. this.seeds = new Uint32Array(4);
  24161. this.seeds[0] = seed;
  24162. this.seeds[1] = this.seeds[0] * 0x6C078965 + 1;
  24163. this.seeds[2] = this.seeds[1] * 0x6C078965 + 1;
  24164. this.seeds[3] = this.seeds[2] * 0x6C078965 + 1;
  24165. }
  24166. static getFloatFromInt(v) {
  24167. return (v & 0x007FFFFF) * (1.0 / 8388607.0);
  24168. }
  24169. static getByteFromInt(v) {
  24170. return (v & 0x007FFFFF) >>> 15;
  24171. }
  24172. get seed() {
  24173. return this.seeds[0];
  24174. }
  24175. set seed(seed) {
  24176. this.seeds[0] = seed;
  24177. this.seeds[1] = this.seeds[0] * 0x6C078965 + 1;
  24178. this.seeds[2] = this.seeds[1] * 0x6C078965 + 1;
  24179. this.seeds[3] = this.seeds[2] * 0x6C078965 + 1;
  24180. }
  24181. getUint() {
  24182. this._temp[0] = this.seeds[0] ^ (this.seeds[0] << 11);
  24183. this.seeds[0] = this.seeds[1];
  24184. this.seeds[1] = this.seeds[2];
  24185. this.seeds[2] = this.seeds[3];
  24186. this.seeds[3] = (this.seeds[3] ^ (this.seeds[3] >>> 19)) ^ (this._temp[0] ^ (this._temp[0] >>> 8));
  24187. return this.seeds[3];
  24188. }
  24189. getFloat() {
  24190. this.getUint();
  24191. return (this.seeds[3] & 0x007FFFFF) * (1.0 / 8388607.0);
  24192. }
  24193. getSignedFloat() {
  24194. return this.getFloat() * 2.0 - 1.0;
  24195. }
  24196. }
  24197. class Emission {
  24198. constructor() {
  24199. this._emissionRate = 10;
  24200. this._destroyed = false;
  24201. this._bursts = [];
  24202. }
  24203. set emissionRate(value) {
  24204. if (value < 0)
  24205. throw new Error("ParticleBaseShape:emissionRate value must large or equal than 0.");
  24206. this._emissionRate = value;
  24207. }
  24208. get emissionRate() {
  24209. return this._emissionRate;
  24210. }
  24211. get destroyed() {
  24212. return this._destroyed;
  24213. }
  24214. destroy() {
  24215. this._bursts = null;
  24216. this._destroyed = true;
  24217. }
  24218. getBurstsCount() {
  24219. return this._bursts.length;
  24220. }
  24221. getBurstByIndex(index) {
  24222. return this._bursts[index];
  24223. }
  24224. addBurst(burst) {
  24225. var burstsCount = this._bursts.length;
  24226. if (burstsCount > 0)
  24227. for (var i = 0; i < burstsCount; i++) {
  24228. if (this._bursts[i].time > burst.time)
  24229. this._bursts.splice(i, 0, burst);
  24230. }
  24231. this._bursts.push(burst);
  24232. }
  24233. removeBurst(burst) {
  24234. var index = this._bursts.indexOf(burst);
  24235. if (index !== -1) {
  24236. this._bursts.splice(index, 1);
  24237. }
  24238. }
  24239. removeBurstByIndex(index) {
  24240. this._bursts.splice(index, 1);
  24241. }
  24242. clearBurst() {
  24243. this._bursts.length = 0;
  24244. }
  24245. cloneTo(destObject) {
  24246. var destEmission = destObject;
  24247. var destBursts = destEmission._bursts;
  24248. destBursts.length = this._bursts.length;
  24249. for (var i = 0, n = this._bursts.length; i < n; i++) {
  24250. var destBurst = destBursts[i];
  24251. if (destBurst)
  24252. this._bursts[i].cloneTo(destBurst);
  24253. else
  24254. destBursts[i] = this._bursts[i].clone();
  24255. }
  24256. destEmission._emissionRate = this._emissionRate;
  24257. destEmission.enable = this.enable;
  24258. }
  24259. clone() {
  24260. var destEmission = new Emission();
  24261. this.cloneTo(destEmission);
  24262. return destEmission;
  24263. }
  24264. }
  24265. class ShurikenParticleData {
  24266. constructor() {
  24267. }
  24268. static _getStartLifetimeFromGradient(startLifeTimeGradient, emissionTime) {
  24269. for (var i = 1, n = startLifeTimeGradient.gradientCount; i < n; i++) {
  24270. var key = startLifeTimeGradient.getKeyByIndex(i);
  24271. if (key >= emissionTime) {
  24272. var lastKey = startLifeTimeGradient.getKeyByIndex(i - 1);
  24273. var age = (emissionTime - lastKey) / (key - lastKey);
  24274. return Laya.MathUtil.lerp(startLifeTimeGradient.getValueByIndex(i - 1), startLifeTimeGradient.getValueByIndex(i), age);
  24275. }
  24276. }
  24277. throw new Error("ShurikenParticleData: can't get value foam startLifeTimeGradient.");
  24278. }
  24279. static _randomInvertRoationArray(rotatonE, outE, randomizeRotationDirection, rand, randomSeeds) {
  24280. var randDic;
  24281. if (rand) {
  24282. rand.seed = randomSeeds[6];
  24283. randDic = rand.getFloat();
  24284. randomSeeds[6] = rand.seed;
  24285. }
  24286. else {
  24287. randDic = Math.random();
  24288. }
  24289. if (randDic < randomizeRotationDirection) {
  24290. outE.x = -rotatonE.x;
  24291. outE.y = -rotatonE.y;
  24292. outE.z = -rotatonE.z;
  24293. }
  24294. else {
  24295. outE.x = rotatonE.x;
  24296. outE.y = rotatonE.y;
  24297. outE.z = rotatonE.z;
  24298. }
  24299. }
  24300. static _randomInvertRoation(rotaton, randomizeRotationDirection, rand, randomSeeds) {
  24301. var randDic;
  24302. if (rand) {
  24303. rand.seed = randomSeeds[6];
  24304. randDic = rand.getFloat();
  24305. randomSeeds[6] = rand.seed;
  24306. }
  24307. else {
  24308. randDic = Math.random();
  24309. }
  24310. if (randDic < randomizeRotationDirection)
  24311. rotaton = -rotaton;
  24312. return rotaton;
  24313. }
  24314. static create(particleSystem, particleRender, transform) {
  24315. var autoRandomSeed = particleSystem.autoRandomSeed;
  24316. var rand = particleSystem._rand;
  24317. var randomSeeds = particleSystem._randomSeeds;
  24318. switch (particleSystem.startColorType) {
  24319. case 0:
  24320. var constantStartColor = particleSystem.startColorConstant;
  24321. ShurikenParticleData.startColor.x = constantStartColor.x;
  24322. ShurikenParticleData.startColor.y = constantStartColor.y;
  24323. ShurikenParticleData.startColor.z = constantStartColor.z;
  24324. ShurikenParticleData.startColor.w = constantStartColor.w;
  24325. break;
  24326. case 2:
  24327. if (autoRandomSeed) {
  24328. Vector4.lerp(particleSystem.startColorConstantMin, particleSystem.startColorConstantMax, Math.random(), ShurikenParticleData.startColor);
  24329. }
  24330. else {
  24331. rand.seed = randomSeeds[3];
  24332. Vector4.lerp(particleSystem.startColorConstantMin, particleSystem.startColorConstantMax, rand.getFloat(), ShurikenParticleData.startColor);
  24333. randomSeeds[3] = rand.seed;
  24334. }
  24335. break;
  24336. }
  24337. var colorOverLifetime = particleSystem.colorOverLifetime;
  24338. if (colorOverLifetime && colorOverLifetime.enable) {
  24339. var color = colorOverLifetime.color;
  24340. switch (color.type) {
  24341. case 0:
  24342. ShurikenParticleData.startColor.x = ShurikenParticleData.startColor.x * color.constant.x;
  24343. ShurikenParticleData.startColor.y = ShurikenParticleData.startColor.y * color.constant.y;
  24344. ShurikenParticleData.startColor.z = ShurikenParticleData.startColor.z * color.constant.z;
  24345. ShurikenParticleData.startColor.w = ShurikenParticleData.startColor.w * color.constant.w;
  24346. break;
  24347. case 2:
  24348. var colorRandom;
  24349. if (autoRandomSeed) {
  24350. colorRandom = Math.random();
  24351. }
  24352. else {
  24353. rand.seed = randomSeeds[10];
  24354. colorRandom = rand.getFloat();
  24355. randomSeeds[10] = rand.seed;
  24356. }
  24357. var minConstantColor = color.constantMin;
  24358. var maxConstantColor = color.constantMax;
  24359. ShurikenParticleData.startColor.x = ShurikenParticleData.startColor.x * Laya.MathUtil.lerp(minConstantColor.x, maxConstantColor.x, colorRandom);
  24360. ShurikenParticleData.startColor.y = ShurikenParticleData.startColor.y * Laya.MathUtil.lerp(minConstantColor.y, maxConstantColor.y, colorRandom);
  24361. ShurikenParticleData.startColor.z = ShurikenParticleData.startColor.z * Laya.MathUtil.lerp(minConstantColor.z, maxConstantColor.z, colorRandom);
  24362. ShurikenParticleData.startColor.w = ShurikenParticleData.startColor.w * Laya.MathUtil.lerp(minConstantColor.w, maxConstantColor.w, colorRandom);
  24363. break;
  24364. }
  24365. }
  24366. var particleSize = ShurikenParticleData.startSize;
  24367. switch (particleSystem.startSizeType) {
  24368. case 0:
  24369. if (particleSystem.threeDStartSize) {
  24370. var startSizeConstantSeparate = particleSystem.startSizeConstantSeparate;
  24371. particleSize[0] = startSizeConstantSeparate.x;
  24372. particleSize[1] = startSizeConstantSeparate.y;
  24373. particleSize[2] = startSizeConstantSeparate.z;
  24374. }
  24375. else {
  24376. particleSize[0] = particleSize[1] = particleSize[2] = particleSystem.startSizeConstant;
  24377. }
  24378. break;
  24379. case 2:
  24380. if (particleSystem.threeDStartSize) {
  24381. var startSizeConstantMinSeparate = particleSystem.startSizeConstantMinSeparate;
  24382. var startSizeConstantMaxSeparate = particleSystem.startSizeConstantMaxSeparate;
  24383. if (autoRandomSeed) {
  24384. particleSize[0] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.x, startSizeConstantMaxSeparate.x, Math.random());
  24385. particleSize[1] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.y, startSizeConstantMaxSeparate.y, Math.random());
  24386. particleSize[2] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.z, startSizeConstantMaxSeparate.z, Math.random());
  24387. }
  24388. else {
  24389. rand.seed = randomSeeds[4];
  24390. particleSize[0] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.x, startSizeConstantMaxSeparate.x, rand.getFloat());
  24391. particleSize[1] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.y, startSizeConstantMaxSeparate.y, rand.getFloat());
  24392. particleSize[2] = Laya.MathUtil.lerp(startSizeConstantMinSeparate.z, startSizeConstantMaxSeparate.z, rand.getFloat());
  24393. randomSeeds[4] = rand.seed;
  24394. }
  24395. }
  24396. else {
  24397. if (autoRandomSeed) {
  24398. particleSize[0] = particleSize[1] = particleSize[2] = Laya.MathUtil.lerp(particleSystem.startSizeConstantMin, particleSystem.startSizeConstantMax, Math.random());
  24399. }
  24400. else {
  24401. rand.seed = randomSeeds[4];
  24402. particleSize[0] = particleSize[1] = particleSize[2] = Laya.MathUtil.lerp(particleSystem.startSizeConstantMin, particleSystem.startSizeConstantMax, rand.getFloat());
  24403. randomSeeds[4] = rand.seed;
  24404. }
  24405. }
  24406. break;
  24407. }
  24408. var sizeOverLifetime = particleSystem.sizeOverLifetime;
  24409. if (sizeOverLifetime && sizeOverLifetime.enable && sizeOverLifetime.size.type === 1) {
  24410. var size = sizeOverLifetime.size;
  24411. if (size.separateAxes) {
  24412. if (autoRandomSeed) {
  24413. particleSize[0] = particleSize[0] * Laya.MathUtil.lerp(size.constantMinSeparate.x, size.constantMaxSeparate.x, Math.random());
  24414. particleSize[1] = particleSize[1] * Laya.MathUtil.lerp(size.constantMinSeparate.y, size.constantMaxSeparate.y, Math.random());
  24415. particleSize[2] = particleSize[2] * Laya.MathUtil.lerp(size.constantMinSeparate.z, size.constantMaxSeparate.z, Math.random());
  24416. }
  24417. else {
  24418. rand.seed = randomSeeds[11];
  24419. particleSize[0] = particleSize[0] * Laya.MathUtil.lerp(size.constantMinSeparate.x, size.constantMaxSeparate.x, rand.getFloat());
  24420. particleSize[1] = particleSize[1] * Laya.MathUtil.lerp(size.constantMinSeparate.y, size.constantMaxSeparate.y, rand.getFloat());
  24421. particleSize[2] = particleSize[2] * Laya.MathUtil.lerp(size.constantMinSeparate.z, size.constantMaxSeparate.z, rand.getFloat());
  24422. randomSeeds[11] = rand.seed;
  24423. }
  24424. }
  24425. else {
  24426. var randomSize;
  24427. if (autoRandomSeed) {
  24428. randomSize = Laya.MathUtil.lerp(size.constantMin, size.constantMax, Math.random());
  24429. }
  24430. else {
  24431. rand.seed = randomSeeds[11];
  24432. randomSize = Laya.MathUtil.lerp(size.constantMin, size.constantMax, rand.getFloat());
  24433. randomSeeds[11] = rand.seed;
  24434. }
  24435. particleSize[0] = particleSize[0] * randomSize;
  24436. particleSize[1] = particleSize[1] * randomSize;
  24437. particleSize[2] = particleSize[2] * randomSize;
  24438. }
  24439. }
  24440. var renderMode = particleRender.renderMode;
  24441. if (renderMode !== 1) {
  24442. switch (particleSystem.startRotationType) {
  24443. case 0:
  24444. if (particleSystem.threeDStartRotation) {
  24445. var startRotationConstantSeparate = particleSystem.startRotationConstantSeparate;
  24446. var randomRotationE = ShurikenParticleData._tempVector30;
  24447. ShurikenParticleData._randomInvertRoationArray(startRotationConstantSeparate, randomRotationE, particleSystem.randomizeRotationDirection, autoRandomSeed ? null : rand, randomSeeds);
  24448. ShurikenParticleData.startRotation[0] = randomRotationE.x;
  24449. ShurikenParticleData.startRotation[1] = randomRotationE.y;
  24450. if (renderMode !== 4)
  24451. ShurikenParticleData.startRotation[2] = -randomRotationE.z;
  24452. else
  24453. ShurikenParticleData.startRotation[2] = randomRotationE.z;
  24454. }
  24455. else {
  24456. ShurikenParticleData.startRotation[0] = ShurikenParticleData._randomInvertRoation(particleSystem.startRotationConstant, particleSystem.randomizeRotationDirection, autoRandomSeed ? null : rand, randomSeeds);
  24457. ShurikenParticleData.startRotation[1] = 0;
  24458. ShurikenParticleData.startRotation[2] = 0;
  24459. }
  24460. break;
  24461. case 2:
  24462. if (particleSystem.threeDStartRotation) {
  24463. var startRotationConstantMinSeparate = particleSystem.startRotationConstantMinSeparate;
  24464. var startRotationConstantMaxSeparate = particleSystem.startRotationConstantMaxSeparate;
  24465. var lerpRoationE = ShurikenParticleData._tempVector30;
  24466. if (autoRandomSeed) {
  24467. lerpRoationE.x = Laya.MathUtil.lerp(startRotationConstantMinSeparate.x, startRotationConstantMaxSeparate.x, Math.random());
  24468. lerpRoationE.y = Laya.MathUtil.lerp(startRotationConstantMinSeparate.y, startRotationConstantMaxSeparate.y, Math.random());
  24469. lerpRoationE.z = Laya.MathUtil.lerp(startRotationConstantMinSeparate.z, startRotationConstantMaxSeparate.z, Math.random());
  24470. }
  24471. else {
  24472. rand.seed = randomSeeds[5];
  24473. lerpRoationE.x = Laya.MathUtil.lerp(startRotationConstantMinSeparate.x, startRotationConstantMaxSeparate.x, rand.getFloat());
  24474. lerpRoationE.y = Laya.MathUtil.lerp(startRotationConstantMinSeparate.y, startRotationConstantMaxSeparate.y, rand.getFloat());
  24475. lerpRoationE.z = Laya.MathUtil.lerp(startRotationConstantMinSeparate.z, startRotationConstantMaxSeparate.z, rand.getFloat());
  24476. randomSeeds[5] = rand.seed;
  24477. }
  24478. ShurikenParticleData._randomInvertRoationArray(lerpRoationE, lerpRoationE, particleSystem.randomizeRotationDirection, autoRandomSeed ? null : rand, randomSeeds);
  24479. ShurikenParticleData.startRotation[0] = lerpRoationE.x;
  24480. ShurikenParticleData.startRotation[1] = lerpRoationE.y;
  24481. if (renderMode !== 4)
  24482. ShurikenParticleData.startRotation[2] = -lerpRoationE.z;
  24483. else
  24484. ShurikenParticleData.startRotation[2] = lerpRoationE.z;
  24485. }
  24486. else {
  24487. if (autoRandomSeed) {
  24488. ShurikenParticleData.startRotation[0] = ShurikenParticleData._randomInvertRoation(Laya.MathUtil.lerp(particleSystem.startRotationConstantMin, particleSystem.startRotationConstantMax, Math.random()), particleSystem.randomizeRotationDirection, autoRandomSeed ? null : rand, randomSeeds);
  24489. }
  24490. else {
  24491. rand.seed = randomSeeds[5];
  24492. ShurikenParticleData.startRotation[0] = ShurikenParticleData._randomInvertRoation(Laya.MathUtil.lerp(particleSystem.startRotationConstantMin, particleSystem.startRotationConstantMax, rand.getFloat()), particleSystem.randomizeRotationDirection, autoRandomSeed ? null : rand, randomSeeds);
  24493. randomSeeds[5] = rand.seed;
  24494. }
  24495. }
  24496. break;
  24497. }
  24498. }
  24499. switch (particleSystem.startLifetimeType) {
  24500. case 0:
  24501. ShurikenParticleData.startLifeTime = particleSystem.startLifetimeConstant;
  24502. break;
  24503. case 1:
  24504. ShurikenParticleData.startLifeTime = ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradient, particleSystem.emissionTime);
  24505. break;
  24506. case 2:
  24507. if (autoRandomSeed) {
  24508. ShurikenParticleData.startLifeTime = Laya.MathUtil.lerp(particleSystem.startLifetimeConstantMin, particleSystem.startLifetimeConstantMax, Math.random());
  24509. }
  24510. else {
  24511. rand.seed = randomSeeds[7];
  24512. ShurikenParticleData.startLifeTime = Laya.MathUtil.lerp(particleSystem.startLifetimeConstantMin, particleSystem.startLifetimeConstantMax, rand.getFloat());
  24513. randomSeeds[7] = rand.seed;
  24514. }
  24515. break;
  24516. case 3:
  24517. var emissionTime = particleSystem.emissionTime;
  24518. if (autoRandomSeed) {
  24519. ShurikenParticleData.startLifeTime = Laya.MathUtil.lerp(ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMin, emissionTime), ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMax, emissionTime), Math.random());
  24520. }
  24521. else {
  24522. rand.seed = randomSeeds[7];
  24523. ShurikenParticleData.startLifeTime = Laya.MathUtil.lerp(ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMin, emissionTime), ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMax, emissionTime), rand.getFloat());
  24524. randomSeeds[7] = rand.seed;
  24525. }
  24526. break;
  24527. }
  24528. var textureSheetAnimation = particleSystem.textureSheetAnimation;
  24529. var enableSheetAnimation = textureSheetAnimation && textureSheetAnimation.enable;
  24530. if (enableSheetAnimation) {
  24531. var title = textureSheetAnimation.tiles;
  24532. var titleX = title.x, titleY = title.y;
  24533. var subU = 1.0 / titleX, subV = 1.0 / titleY;
  24534. var startFrameCount;
  24535. var startFrame = textureSheetAnimation.startFrame;
  24536. switch (startFrame.type) {
  24537. case 0:
  24538. startFrameCount = startFrame.constant;
  24539. break;
  24540. case 1:
  24541. if (autoRandomSeed) {
  24542. startFrameCount = Laya.MathUtil.lerp(startFrame.constantMin, startFrame.constantMax, Math.random());
  24543. }
  24544. else {
  24545. rand.seed = randomSeeds[14];
  24546. startFrameCount = Laya.MathUtil.lerp(startFrame.constantMin, startFrame.constantMax, rand.getFloat());
  24547. randomSeeds[14] = rand.seed;
  24548. }
  24549. break;
  24550. }
  24551. var frame = textureSheetAnimation.frame;
  24552. var cycles = textureSheetAnimation.cycles;
  24553. switch (frame.type) {
  24554. case 0:
  24555. startFrameCount += frame.constant * cycles;
  24556. break;
  24557. case 2:
  24558. if (autoRandomSeed) {
  24559. startFrameCount += Laya.MathUtil.lerp(frame.constantMin, frame.constantMax, Math.random()) * cycles;
  24560. }
  24561. else {
  24562. rand.seed = randomSeeds[15];
  24563. startFrameCount += Laya.MathUtil.lerp(frame.constantMin, frame.constantMax, rand.getFloat()) * cycles;
  24564. randomSeeds[15] = rand.seed;
  24565. }
  24566. break;
  24567. }
  24568. var startRow = 0;
  24569. switch (textureSheetAnimation.type) {
  24570. case 0:
  24571. startRow = Math.floor(startFrameCount / titleX);
  24572. break;
  24573. case 1:
  24574. if (textureSheetAnimation.randomRow) {
  24575. if (autoRandomSeed) {
  24576. startRow = Math.floor(Math.random() * titleY);
  24577. }
  24578. else {
  24579. rand.seed = randomSeeds[13];
  24580. startRow = Math.floor(rand.getFloat() * titleY);
  24581. randomSeeds[13] = rand.seed;
  24582. }
  24583. }
  24584. else {
  24585. startRow = textureSheetAnimation.rowIndex;
  24586. }
  24587. break;
  24588. }
  24589. var startCol = Math.floor(startFrameCount % titleX);
  24590. ShurikenParticleData.startUVInfo = ShurikenParticleData.startUVInfo;
  24591. ShurikenParticleData.startUVInfo[0] = subU;
  24592. ShurikenParticleData.startUVInfo[1] = subV;
  24593. ShurikenParticleData.startUVInfo[2] = startCol * subU;
  24594. ShurikenParticleData.startUVInfo[3] = startRow * subV;
  24595. }
  24596. else {
  24597. ShurikenParticleData.startUVInfo = ShurikenParticleData.startUVInfo;
  24598. ShurikenParticleData.startUVInfo[0] = 1.0;
  24599. ShurikenParticleData.startUVInfo[1] = 1.0;
  24600. ShurikenParticleData.startUVInfo[2] = 0.0;
  24601. ShurikenParticleData.startUVInfo[3] = 0.0;
  24602. }
  24603. }
  24604. }
  24605. ShurikenParticleData._tempVector30 = new Vector3();
  24606. ShurikenParticleData.startColor = new Vector4();
  24607. ShurikenParticleData.startSize = new Float32Array(3);
  24608. ShurikenParticleData.startRotation = new Float32Array(3);
  24609. ShurikenParticleData.startUVInfo = new Float32Array(4);
  24610. class ShurikenParticleSystem extends GeometryElement {
  24611. constructor(owner) {
  24612. super();
  24613. this._boundingSphere = null;
  24614. this._boundingBox = null;
  24615. this._boundingBoxCorners = null;
  24616. this._bounds = null;
  24617. this._gravityOffset = new Vector2();
  24618. this._customBounds = null;
  24619. this._useCustomBounds = false;
  24620. this._owner = null;
  24621. this._ownerRender = null;
  24622. this._vertices = null;
  24623. this._floatCountPerVertex = 0;
  24624. this._startLifeTimeIndex = 0;
  24625. this._timeIndex = 0;
  24626. this._simulateUpdate = false;
  24627. this._firstActiveElement = 0;
  24628. this._firstNewElement = 0;
  24629. this._firstFreeElement = 0;
  24630. this._firstRetiredElement = 0;
  24631. this._drawCounter = 0;
  24632. this._bufferMaxParticles = 0;
  24633. this._emission = null;
  24634. this._shape = null;
  24635. this._isEmitting = false;
  24636. this._isPlaying = false;
  24637. this._isPaused = false;
  24638. this._playStartDelay = 0;
  24639. this._frameRateTime = 0;
  24640. this._emissionTime = 0;
  24641. this._totalDelayTime = 0;
  24642. this._burstsIndex = 0;
  24643. this._velocityOverLifetime = null;
  24644. this._colorOverLifetime = null;
  24645. this._sizeOverLifetime = null;
  24646. this._rotationOverLifetime = null;
  24647. this._textureSheetAnimation = null;
  24648. this._startLifetimeType = 0;
  24649. this._startLifetimeConstant = 0;
  24650. this._startLifeTimeGradient = null;
  24651. this._startLifetimeConstantMin = 0;
  24652. this._startLifetimeConstantMax = 0;
  24653. this._startLifeTimeGradientMin = null;
  24654. this._startLifeTimeGradientMax = null;
  24655. this._maxStartLifetime = 0;
  24656. this._uvLength = new Vector2();
  24657. this._vertexStride = 0;
  24658. this._indexStride = 0;
  24659. this._vertexBuffer = null;
  24660. this._indexBuffer = null;
  24661. this._bufferState = new BufferState();
  24662. this._updateMask = 0;
  24663. this._currentTime = 0;
  24664. this._startUpdateLoopCount = 0;
  24665. this._rand = null;
  24666. this._randomSeeds = null;
  24667. this.duration = 0;
  24668. this.looping = false;
  24669. this.prewarm = false;
  24670. this.startDelayType = 0;
  24671. this.startDelay = 0;
  24672. this.startDelayMin = 0;
  24673. this.startDelayMax = 0;
  24674. this.startSpeedType = 0;
  24675. this.startSpeedConstant = 0;
  24676. this.startSpeedConstantMin = 0;
  24677. this.startSpeedConstantMax = 0;
  24678. this.threeDStartSize = false;
  24679. this.startSizeType = 0;
  24680. this.startSizeConstant = 0;
  24681. this.startSizeConstantSeparate = null;
  24682. this.startSizeConstantMin = 0;
  24683. this.startSizeConstantMax = 0;
  24684. this.startSizeConstantMinSeparate = null;
  24685. this.startSizeConstantMaxSeparate = null;
  24686. this.threeDStartRotation = false;
  24687. this.startRotationType = 0;
  24688. this.startRotationConstant = 0;
  24689. this.startRotationConstantSeparate = null;
  24690. this.startRotationConstantMin = 0;
  24691. this.startRotationConstantMax = 0;
  24692. this.startRotationConstantMinSeparate = null;
  24693. this.startRotationConstantMaxSeparate = null;
  24694. this.randomizeRotationDirection = 0;
  24695. this.startColorType = 0;
  24696. this.startColorConstant = new Vector4(1, 1, 1, 1);
  24697. this.startColorConstantMin = new Vector4(0, 0, 0, 0);
  24698. this.startColorConstantMax = new Vector4(1, 1, 1, 1);
  24699. this.gravityModifier = 0;
  24700. this.simulationSpace = 0;
  24701. this.simulationSpeed = 1.0;
  24702. this.scaleMode = 1;
  24703. this.playOnAwake = false;
  24704. this.randomSeed = null;
  24705. this.autoRandomSeed = false;
  24706. this.isPerformanceMode = false;
  24707. this._firstActiveElement = 0;
  24708. this._firstNewElement = 0;
  24709. this._firstFreeElement = 0;
  24710. this._firstRetiredElement = 0;
  24711. this._owner = owner;
  24712. this._ownerRender = owner.particleRenderer;
  24713. this._boundingBoxCorners = [];
  24714. this._boundingSphere = new BoundSphere(new Vector3(), Number.MAX_VALUE);
  24715. this._boundingBox = new BoundBox(new Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE), new Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE));
  24716. this._bounds = new Bounds(this._boundingBox.min, this._boundingBox.max);
  24717. this._useCustomBounds = false;
  24718. this._currentTime = 0;
  24719. this._isEmitting = false;
  24720. this._isPlaying = false;
  24721. this._isPaused = false;
  24722. this._burstsIndex = 0;
  24723. this._frameRateTime = 0;
  24724. this._emissionTime = 0;
  24725. this._totalDelayTime = 0;
  24726. this._simulateUpdate = false;
  24727. this._bufferMaxParticles = 1;
  24728. this.duration = 5.0;
  24729. this.looping = true;
  24730. this.prewarm = false;
  24731. this.startDelayType = 0;
  24732. this.startDelay = 0.0;
  24733. this.startDelayMin = 0.0;
  24734. this.startDelayMax = 0.0;
  24735. this._startLifetimeType = 0;
  24736. this._startLifetimeConstant = 5.0;
  24737. this._startLifeTimeGradient = new GradientDataNumber();
  24738. this._startLifetimeConstantMin = 0.0;
  24739. this._startLifetimeConstantMax = 5.0;
  24740. this._startLifeTimeGradientMin = new GradientDataNumber();
  24741. this._startLifeTimeGradientMax = new GradientDataNumber();
  24742. this._maxStartLifetime = 5.0;
  24743. this.startSpeedType = 0;
  24744. this.startSpeedConstant = 5.0;
  24745. this.startSpeedConstantMin = 0.0;
  24746. this.startSpeedConstantMax = 5.0;
  24747. this.threeDStartSize = false;
  24748. this.startSizeType = 0;
  24749. this.startSizeConstant = 1;
  24750. this.startSizeConstantSeparate = new Vector3(1, 1, 1);
  24751. this.startSizeConstantMin = 0;
  24752. this.startSizeConstantMax = 1;
  24753. this.startSizeConstantMinSeparate = new Vector3(0, 0, 0);
  24754. this.startSizeConstantMaxSeparate = new Vector3(1, 1, 1);
  24755. this.threeDStartRotation = false;
  24756. this.startRotationType = 0;
  24757. this.startRotationConstant = 0;
  24758. this.startRotationConstantSeparate = new Vector3(0, 0, 0);
  24759. this.startRotationConstantMin = 0.0;
  24760. this.startRotationConstantMax = 0.0;
  24761. this.startRotationConstantMinSeparate = new Vector3(0, 0, 0);
  24762. this.startRotationConstantMaxSeparate = new Vector3(0, 0, 0);
  24763. this.gravityModifier = 0.0;
  24764. this.simulationSpace = 1;
  24765. this.scaleMode = 1;
  24766. this.playOnAwake = true;
  24767. this._rand = new Rand(0);
  24768. this.autoRandomSeed = true;
  24769. this.randomSeed = new Uint32Array(1);
  24770. this._randomSeeds = new Uint32Array(ShurikenParticleSystem._RANDOMOFFSET.length);
  24771. this.isPerformanceMode = true;
  24772. this._emission = new Emission();
  24773. this._emission.enable = true;
  24774. }
  24775. ;
  24776. get maxParticles() {
  24777. return this._bufferMaxParticles - 1;
  24778. }
  24779. set maxParticles(value) {
  24780. var newMaxParticles = value + 1;
  24781. if (newMaxParticles !== this._bufferMaxParticles) {
  24782. this._bufferMaxParticles = newMaxParticles;
  24783. this._initBufferDatas();
  24784. }
  24785. }
  24786. get emission() {
  24787. return this._emission;
  24788. }
  24789. get aliveParticleCount() {
  24790. if (this._firstNewElement >= this._firstRetiredElement)
  24791. return this._firstNewElement - this._firstRetiredElement;
  24792. else
  24793. return this._bufferMaxParticles - this._firstRetiredElement + this._firstNewElement;
  24794. }
  24795. get emissionTime() {
  24796. return this._emissionTime > this.duration ? this.duration : this._emissionTime;
  24797. }
  24798. get shape() {
  24799. return this._shape;
  24800. }
  24801. set shape(value) {
  24802. if (this._shape !== value) {
  24803. if (value && value.enable)
  24804. this._owner._render._shaderValues.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SHAPE);
  24805. else
  24806. this._owner._render._shaderValues.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SHAPE);
  24807. this._shape = value;
  24808. }
  24809. }
  24810. get isAlive() {
  24811. if (this._isPlaying || this.aliveParticleCount > 0)
  24812. return true;
  24813. return false;
  24814. }
  24815. get isEmitting() {
  24816. return this._isEmitting;
  24817. }
  24818. get isPlaying() {
  24819. return this._isPlaying;
  24820. }
  24821. get isPaused() {
  24822. return this._isPaused;
  24823. }
  24824. get startLifetimeType() {
  24825. return this._startLifetimeType;
  24826. }
  24827. set startLifetimeType(value) {
  24828. var i, n;
  24829. switch (this.startLifetimeType) {
  24830. case 0:
  24831. this._maxStartLifetime = this.startLifetimeConstant;
  24832. break;
  24833. case 1:
  24834. this._maxStartLifetime = -Number.MAX_VALUE;
  24835. var startLifeTimeGradient = startLifeTimeGradient;
  24836. for (i = 0, n = startLifeTimeGradient.gradientCount; i < n; i++)
  24837. this._maxStartLifetime = Math.max(this._maxStartLifetime, startLifeTimeGradient.getValueByIndex(i));
  24838. break;
  24839. case 2:
  24840. this._maxStartLifetime = Math.max(this.startLifetimeConstantMin, this.startLifetimeConstantMax);
  24841. break;
  24842. case 3:
  24843. this._maxStartLifetime = -Number.MAX_VALUE;
  24844. var startLifeTimeGradientMin = startLifeTimeGradientMin;
  24845. for (i = 0, n = startLifeTimeGradientMin.gradientCount; i < n; i++)
  24846. this._maxStartLifetime = Math.max(this._maxStartLifetime, startLifeTimeGradientMin.getValueByIndex(i));
  24847. var startLifeTimeGradientMax = startLifeTimeGradientMax;
  24848. for (i = 0, n = startLifeTimeGradientMax.gradientCount; i < n; i++)
  24849. this._maxStartLifetime = Math.max(this._maxStartLifetime, startLifeTimeGradientMax.getValueByIndex(i));
  24850. break;
  24851. }
  24852. this._startLifetimeType = value;
  24853. }
  24854. get startLifetimeConstant() {
  24855. return this._startLifetimeConstant;
  24856. }
  24857. set startLifetimeConstant(value) {
  24858. if (this._startLifetimeType === 0)
  24859. this._maxStartLifetime = value;
  24860. this._startLifetimeConstant = value;
  24861. }
  24862. get startLifeTimeGradient() {
  24863. return this._startLifeTimeGradient;
  24864. }
  24865. set startLifeTimeGradient(value) {
  24866. if (this._startLifetimeType === 1) {
  24867. this._maxStartLifetime = -Number.MAX_VALUE;
  24868. for (var i = 0, n = value.gradientCount; i < n; i++)
  24869. this._maxStartLifetime = Math.max(this._maxStartLifetime, value.getValueByIndex(i));
  24870. }
  24871. this._startLifeTimeGradient = value;
  24872. }
  24873. get startLifetimeConstantMin() {
  24874. return this._startLifetimeConstantMin;
  24875. }
  24876. set startLifetimeConstantMin(value) {
  24877. if (this._startLifetimeType === 2)
  24878. this._maxStartLifetime = Math.max(value, this._startLifetimeConstantMax);
  24879. this._startLifetimeConstantMin = value;
  24880. }
  24881. get startLifetimeConstantMax() {
  24882. return this._startLifetimeConstantMax;
  24883. }
  24884. set startLifetimeConstantMax(value) {
  24885. if (this._startLifetimeType === 2)
  24886. this._maxStartLifetime = Math.max(this._startLifetimeConstantMin, value);
  24887. this._startLifetimeConstantMax = value;
  24888. }
  24889. get startLifeTimeGradientMin() {
  24890. return this._startLifeTimeGradientMin;
  24891. }
  24892. set startLifeTimeGradientMin(value) {
  24893. if (this._startLifetimeType === 3) {
  24894. var i, n;
  24895. this._maxStartLifetime = -Number.MAX_VALUE;
  24896. for (i = 0, n = value.gradientCount; i < n; i++)
  24897. this._maxStartLifetime = Math.max(this._maxStartLifetime, value.getValueByIndex(i));
  24898. for (i = 0, n = this._startLifeTimeGradientMax.gradientCount; i < n; i++)
  24899. this._maxStartLifetime = Math.max(this._maxStartLifetime, this._startLifeTimeGradientMax.getValueByIndex(i));
  24900. }
  24901. this._startLifeTimeGradientMin = value;
  24902. }
  24903. get startLifeTimeGradientMax() {
  24904. return this._startLifeTimeGradientMax;
  24905. }
  24906. set startLifeTimeGradientMax(value) {
  24907. if (this._startLifetimeType === 3) {
  24908. var i, n;
  24909. this._maxStartLifetime = -Number.MAX_VALUE;
  24910. for (i = 0, n = this._startLifeTimeGradientMin.gradientCount; i < n; i++)
  24911. this._maxStartLifetime = Math.max(this._maxStartLifetime, this._startLifeTimeGradientMin.getValueByIndex(i));
  24912. for (i = 0, n = value.gradientCount; i < n; i++)
  24913. this._maxStartLifetime = Math.max(this._maxStartLifetime, value.getValueByIndex(i));
  24914. }
  24915. this._startLifeTimeGradientMax = value;
  24916. }
  24917. get velocityOverLifetime() {
  24918. return this._velocityOverLifetime;
  24919. }
  24920. set velocityOverLifetime(value) {
  24921. var shaDat = this._owner._render._shaderValues;
  24922. if (value) {
  24923. var velocity = value.velocity;
  24924. var velocityType = velocity.type;
  24925. if (value.enable) {
  24926. switch (velocityType) {
  24927. case 0:
  24928. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT);
  24929. break;
  24930. case 1:
  24931. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE);
  24932. break;
  24933. case 2:
  24934. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT);
  24935. break;
  24936. case 3:
  24937. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE);
  24938. break;
  24939. }
  24940. }
  24941. else {
  24942. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT);
  24943. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE);
  24944. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT);
  24945. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE);
  24946. }
  24947. switch (velocityType) {
  24948. case 0:
  24949. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYCONST, velocity.constant);
  24950. break;
  24951. case 1:
  24952. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTX, velocity.gradientX._elements);
  24953. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTY, velocity.gradientY._elements);
  24954. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTZ, velocity.gradientZ._elements);
  24955. break;
  24956. case 2:
  24957. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYCONST, velocity.constantMin);
  24958. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYCONSTMAX, velocity.constantMax);
  24959. break;
  24960. case 3:
  24961. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTX, velocity.gradientXMin._elements);
  24962. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTXMAX, velocity.gradientXMax._elements);
  24963. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTY, velocity.gradientYMin._elements);
  24964. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTYMAX, velocity.gradientYMax._elements);
  24965. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTZ, velocity.gradientZMin._elements);
  24966. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.VOLVELOCITYGRADIENTZMAX, velocity.gradientZMax._elements);
  24967. break;
  24968. }
  24969. shaDat.setInt(ShuriKenParticle3DShaderDeclaration.VOLSPACETYPE, value.space);
  24970. }
  24971. else {
  24972. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT);
  24973. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE);
  24974. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT);
  24975. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE);
  24976. }
  24977. this._velocityOverLifetime = value;
  24978. }
  24979. get colorOverLifetime() {
  24980. return this._colorOverLifetime;
  24981. }
  24982. set colorOverLifetime(value) {
  24983. var shaDat = this._owner._render._shaderValues;
  24984. if (value) {
  24985. var color = value.color;
  24986. if (value.enable) {
  24987. switch (color.type) {
  24988. case 1:
  24989. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_COLOROVERLIFETIME);
  24990. break;
  24991. case 3:
  24992. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RANDOMCOLOROVERLIFETIME);
  24993. break;
  24994. }
  24995. }
  24996. else {
  24997. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_COLOROVERLIFETIME);
  24998. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RANDOMCOLOROVERLIFETIME);
  24999. }
  25000. switch (color.type) {
  25001. case 1:
  25002. var gradientColor = color.gradient;
  25003. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTALPHAS, gradientColor._alphaElements);
  25004. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTCOLORS, gradientColor._rgbElements);
  25005. break;
  25006. case 3:
  25007. var minGradientColor = color.gradientMin;
  25008. var maxGradientColor = color.gradientMax;
  25009. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTALPHAS, minGradientColor._alphaElements);
  25010. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTCOLORS, minGradientColor._rgbElements);
  25011. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTALPHAS, maxGradientColor._alphaElements);
  25012. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTCOLORS, maxGradientColor._rgbElements);
  25013. break;
  25014. }
  25015. }
  25016. else {
  25017. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_COLOROVERLIFETIME);
  25018. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RANDOMCOLOROVERLIFETIME);
  25019. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTALPHAS, gradientColor._alphaElements);
  25020. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTCOLORS, gradientColor._rgbElements);
  25021. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTALPHAS, minGradientColor._alphaElements);
  25022. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.COLOROVERLIFEGRADIENTCOLORS, minGradientColor._rgbElements);
  25023. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTALPHAS, maxGradientColor._alphaElements);
  25024. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.MAXCOLOROVERLIFEGRADIENTCOLORS, maxGradientColor._rgbElements);
  25025. }
  25026. this._colorOverLifetime = value;
  25027. }
  25028. get sizeOverLifetime() {
  25029. return this._sizeOverLifetime;
  25030. }
  25031. set sizeOverLifetime(value) {
  25032. var shaDat = this._owner._render._shaderValues;
  25033. if (value) {
  25034. var size = value.size;
  25035. var sizeSeparate = size.separateAxes;
  25036. var sizeType = size.type;
  25037. if (value.enable) {
  25038. switch (sizeType) {
  25039. case 0:
  25040. if (sizeSeparate)
  25041. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE);
  25042. else
  25043. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVE);
  25044. break;
  25045. case 2:
  25046. if (sizeSeparate)
  25047. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE);
  25048. else
  25049. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES);
  25050. break;
  25051. }
  25052. }
  25053. else {
  25054. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVE);
  25055. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE);
  25056. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES);
  25057. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE);
  25058. }
  25059. switch (sizeType) {
  25060. case 0:
  25061. if (sizeSeparate) {
  25062. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTX, size.gradientX._elements);
  25063. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTY, size.gradientY._elements);
  25064. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSizeGradientZ, size.gradientZ._elements);
  25065. }
  25066. else {
  25067. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENT, size.gradient._elements);
  25068. }
  25069. break;
  25070. case 2:
  25071. if (sizeSeparate) {
  25072. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTX, size.gradientXMin._elements);
  25073. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTXMAX, size.gradientXMax._elements);
  25074. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTY, size.gradientYMin._elements);
  25075. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENTYMAX, size.gradientYMax._elements);
  25076. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSizeGradientZ, size.gradientZMin._elements);
  25077. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSizeGradientZMAX, size.gradientZMax._elements);
  25078. }
  25079. else {
  25080. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSIZEGRADIENT, size.gradientMin._elements);
  25081. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.SOLSizeGradientMax, size.gradientMax._elements);
  25082. }
  25083. break;
  25084. }
  25085. }
  25086. else {
  25087. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVE);
  25088. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE);
  25089. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES);
  25090. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE);
  25091. }
  25092. this._sizeOverLifetime = value;
  25093. }
  25094. get rotationOverLifetime() {
  25095. return this._rotationOverLifetime;
  25096. }
  25097. set rotationOverLifetime(value) {
  25098. var shaDat = this._owner._render._shaderValues;
  25099. if (value) {
  25100. var rotation = value.angularVelocity;
  25101. if (!rotation)
  25102. return;
  25103. var rotationSeparate = rotation.separateAxes;
  25104. var rotationType = rotation.type;
  25105. if (value.enable) {
  25106. if (rotationSeparate)
  25107. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE);
  25108. else
  25109. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIME);
  25110. switch (rotationType) {
  25111. case 0:
  25112. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT);
  25113. break;
  25114. case 1:
  25115. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE);
  25116. break;
  25117. case 2:
  25118. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS);
  25119. break;
  25120. case 3:
  25121. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES);
  25122. break;
  25123. }
  25124. }
  25125. else {
  25126. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIME);
  25127. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE);
  25128. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT);
  25129. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE);
  25130. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS);
  25131. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES);
  25132. }
  25133. switch (rotationType) {
  25134. case 0:
  25135. if (rotationSeparate) {
  25136. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTSEPRARATE, rotation.constantSeparate);
  25137. }
  25138. else {
  25139. shaDat.setNumber(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONST, rotation.constant);
  25140. }
  25141. break;
  25142. case 1:
  25143. if (rotationSeparate) {
  25144. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTX, rotation.gradientX._elements);
  25145. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTY, rotation.gradientY._elements);
  25146. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTZ, rotation.gradientZ._elements);
  25147. }
  25148. else {
  25149. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENT, rotation.gradient._elements);
  25150. }
  25151. break;
  25152. case 2:
  25153. if (rotationSeparate) {
  25154. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTSEPRARATE, rotation.constantMinSeparate);
  25155. shaDat.setVector3(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTMAXSEPRARATE, rotation.constantMaxSeparate);
  25156. }
  25157. else {
  25158. shaDat.setNumber(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONST, rotation.constantMin);
  25159. shaDat.setNumber(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYCONSTMAX, rotation.constantMax);
  25160. }
  25161. break;
  25162. case 3:
  25163. if (rotationSeparate) {
  25164. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTX, rotation.gradientXMin._elements);
  25165. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTXMAX, rotation.gradientXMax._elements);
  25166. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTY, rotation.gradientYMin._elements);
  25167. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTYMAX, rotation.gradientYMax._elements);
  25168. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTZ, rotation.gradientZMin._elements);
  25169. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTZMAX, rotation.gradientZMax._elements);
  25170. }
  25171. else {
  25172. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENT, rotation.gradientMin._elements);
  25173. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.ROLANGULARVELOCITYGRADIENTMAX, rotation.gradientMax._elements);
  25174. }
  25175. break;
  25176. }
  25177. }
  25178. else {
  25179. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIME);
  25180. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE);
  25181. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT);
  25182. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE);
  25183. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS);
  25184. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES);
  25185. }
  25186. this._rotationOverLifetime = value;
  25187. }
  25188. get textureSheetAnimation() {
  25189. return this._textureSheetAnimation;
  25190. }
  25191. set textureSheetAnimation(value) {
  25192. var shaDat = this._owner._render._shaderValues;
  25193. if (value) {
  25194. var frameOverTime = value.frame;
  25195. var textureAniType = frameOverTime.type;
  25196. if (value.enable) {
  25197. switch (textureAniType) {
  25198. case 1:
  25199. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE);
  25200. break;
  25201. case 3:
  25202. shaDat.addDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE);
  25203. break;
  25204. }
  25205. }
  25206. else {
  25207. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE);
  25208. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE);
  25209. }
  25210. if (textureAniType === 1 || textureAniType === 3) {
  25211. shaDat.setNumber(ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONCYCLES, value.cycles);
  25212. var title = value.tiles;
  25213. var _uvLengthE = this._uvLength;
  25214. _uvLengthE.x = 1.0 / title.x;
  25215. _uvLengthE.y = 1.0 / title.y;
  25216. shaDat.setVector2(ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONSUBUVLENGTH, this._uvLength);
  25217. }
  25218. switch (textureAniType) {
  25219. case 1:
  25220. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONGRADIENTUVS, frameOverTime.frameOverTimeData._elements);
  25221. break;
  25222. case 3:
  25223. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONGRADIENTUVS, frameOverTime.frameOverTimeDataMin._elements);
  25224. shaDat.setBuffer(ShuriKenParticle3DShaderDeclaration.TEXTURESHEETANIMATIONGRADIENTMAXUVS, frameOverTime.frameOverTimeDataMax._elements);
  25225. break;
  25226. }
  25227. }
  25228. else {
  25229. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE);
  25230. shaDat.removeDefine(ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE);
  25231. }
  25232. this._textureSheetAnimation = value;
  25233. }
  25234. _getVertexBuffer(index = 0) {
  25235. if (index === 0)
  25236. return this._vertexBuffer;
  25237. else
  25238. return null;
  25239. }
  25240. _getIndexBuffer() {
  25241. return this._indexBuffer;
  25242. }
  25243. _generateBoundingSphere() {
  25244. var centerE = this._boundingSphere.center;
  25245. centerE.x = 0;
  25246. centerE.y = 0;
  25247. centerE.z = 0;
  25248. this._boundingSphere.radius = Number.MAX_VALUE;
  25249. }
  25250. _generateBoundingBox() {
  25251. var particle = this._owner;
  25252. var particleRender = particle.particleRenderer;
  25253. var boundMin = this._boundingBox.min;
  25254. var boundMax = this._boundingBox.max;
  25255. var i, n;
  25256. var maxStartLifeTime;
  25257. switch (this.startLifetimeType) {
  25258. case 0:
  25259. maxStartLifeTime = this.startLifetimeConstant;
  25260. break;
  25261. case 1:
  25262. maxStartLifeTime = -Number.MAX_VALUE;
  25263. var startLifeTimeGradient = startLifeTimeGradient;
  25264. for (i = 0, n = startLifeTimeGradient.gradientCount; i < n; i++)
  25265. maxStartLifeTime = Math.max(maxStartLifeTime, startLifeTimeGradient.getValueByIndex(i));
  25266. break;
  25267. case 2:
  25268. maxStartLifeTime = Math.max(this.startLifetimeConstantMin, this.startLifetimeConstantMax);
  25269. break;
  25270. case 3:
  25271. maxStartLifeTime = -Number.MAX_VALUE;
  25272. var startLifeTimeGradientMin = startLifeTimeGradientMin;
  25273. for (i = 0, n = startLifeTimeGradientMin.gradientCount; i < n; i++)
  25274. maxStartLifeTime = Math.max(maxStartLifeTime, startLifeTimeGradientMin.getValueByIndex(i));
  25275. var startLifeTimeGradientMax = startLifeTimeGradientMax;
  25276. for (i = 0, n = startLifeTimeGradientMax.gradientCount; i < n; i++)
  25277. maxStartLifeTime = Math.max(maxStartLifeTime, startLifeTimeGradientMax.getValueByIndex(i));
  25278. break;
  25279. }
  25280. var minStartSpeed, maxStartSpeed;
  25281. switch (this.startSpeedType) {
  25282. case 0:
  25283. minStartSpeed = maxStartSpeed = this.startSpeedConstant;
  25284. break;
  25285. case 1:
  25286. break;
  25287. case 2:
  25288. minStartSpeed = this.startLifetimeConstantMin;
  25289. maxStartSpeed = this.startLifetimeConstantMax;
  25290. break;
  25291. case 3:
  25292. break;
  25293. }
  25294. var minPosition, maxPosition, minDirection, maxDirection;
  25295. if (this._shape && this._shape.enable) ;
  25296. else {
  25297. minPosition = maxPosition = Vector3._ZERO;
  25298. minDirection = Vector3._ZERO;
  25299. maxDirection = Vector3._UnitZ;
  25300. }
  25301. var startMinVelocity = new Vector3(minDirection.x * minStartSpeed, minDirection.y * minStartSpeed, minDirection.z * minStartSpeed);
  25302. var startMaxVelocity = new Vector3(maxDirection.x * maxStartSpeed, maxDirection.y * maxStartSpeed, maxDirection.z * maxStartSpeed);
  25303. if (this._velocityOverLifetime && this._velocityOverLifetime.enable) {
  25304. var lifeMinVelocity;
  25305. var lifeMaxVelocity;
  25306. var velocity = this._velocityOverLifetime.velocity;
  25307. switch (velocity.type) {
  25308. case 0:
  25309. lifeMinVelocity = lifeMaxVelocity = velocity.constant;
  25310. break;
  25311. case 1:
  25312. lifeMinVelocity = lifeMaxVelocity = new Vector3(velocity.gradientX.getAverageValue(), velocity.gradientY.getAverageValue(), velocity.gradientZ.getAverageValue());
  25313. break;
  25314. case 2:
  25315. lifeMinVelocity = velocity.constantMin;
  25316. lifeMaxVelocity = velocity.constantMax;
  25317. break;
  25318. case 3:
  25319. lifeMinVelocity = new Vector3(velocity.gradientXMin.getAverageValue(), velocity.gradientYMin.getAverageValue(), velocity.gradientZMin.getAverageValue());
  25320. lifeMaxVelocity = new Vector3(velocity.gradientXMax.getAverageValue(), velocity.gradientYMax.getAverageValue(), velocity.gradientZMax.getAverageValue());
  25321. break;
  25322. }
  25323. }
  25324. var positionScale, velocityScale;
  25325. var transform = this._owner.transform;
  25326. var worldPosition = transform.position;
  25327. var sizeScale = ShurikenParticleSystem._tempVector39;
  25328. var renderMode = particleRender.renderMode;
  25329. switch (this.scaleMode) {
  25330. case 0:
  25331. var scale = transform.getWorldLossyScale();
  25332. positionScale = scale;
  25333. sizeScale.x = scale.x;
  25334. sizeScale.y = scale.z;
  25335. sizeScale.z = scale.y;
  25336. (renderMode === 1) && (velocityScale = scale);
  25337. break;
  25338. case 1:
  25339. var localScale = transform.localScale;
  25340. positionScale = localScale;
  25341. sizeScale.x = localScale.x;
  25342. sizeScale.y = localScale.z;
  25343. sizeScale.z = localScale.y;
  25344. (renderMode === 1) && (velocityScale = localScale);
  25345. break;
  25346. case 2:
  25347. positionScale = transform.getWorldLossyScale();
  25348. sizeScale.x = sizeScale.y = sizeScale.z = 1;
  25349. (renderMode === 1) && (velocityScale = Vector3._ONE);
  25350. break;
  25351. }
  25352. var minStratPosition, maxStratPosition;
  25353. if (this._velocityOverLifetime && this._velocityOverLifetime.enable) ;
  25354. else {
  25355. minStratPosition = new Vector3(startMinVelocity.x * maxStartLifeTime, startMinVelocity.y * maxStartLifeTime, startMinVelocity.z * maxStartLifeTime);
  25356. maxStratPosition = new Vector3(startMaxVelocity.x * maxStartLifeTime, startMaxVelocity.y * maxStartLifeTime, startMaxVelocity.z * maxStartLifeTime);
  25357. if (this.scaleMode != 2) {
  25358. Vector3.add(minPosition, minStratPosition, boundMin);
  25359. Vector3.multiply(positionScale, boundMin, boundMin);
  25360. Vector3.add(maxPosition, maxStratPosition, boundMax);
  25361. Vector3.multiply(positionScale, boundMax, boundMax);
  25362. }
  25363. else {
  25364. Vector3.multiply(positionScale, minPosition, boundMin);
  25365. Vector3.add(boundMin, minStratPosition, boundMin);
  25366. Vector3.multiply(positionScale, maxPosition, boundMax);
  25367. Vector3.add(boundMax, maxStratPosition, boundMax);
  25368. }
  25369. }
  25370. switch (this.simulationSpace) {
  25371. case 0:
  25372. break;
  25373. case 1:
  25374. Vector3.add(boundMin, worldPosition, boundMin);
  25375. Vector3.add(boundMax, worldPosition, boundMax);
  25376. break;
  25377. }
  25378. var maxSize, maxSizeY;
  25379. switch (this.startSizeType) {
  25380. case 0:
  25381. if (this.threeDStartSize) {
  25382. var startSizeConstantSeparate = startSizeConstantSeparate;
  25383. maxSize = Math.max(startSizeConstantSeparate.x, startSizeConstantSeparate.y);
  25384. if (renderMode === 1)
  25385. maxSizeY = startSizeConstantSeparate.y;
  25386. }
  25387. else {
  25388. maxSize = this.startSizeConstant;
  25389. if (renderMode === 1)
  25390. maxSizeY = this.startSizeConstant;
  25391. }
  25392. break;
  25393. case 1:
  25394. break;
  25395. case 2:
  25396. if (this.threeDStartSize) {
  25397. var startSizeConstantMaxSeparate = startSizeConstantMaxSeparate;
  25398. maxSize = Math.max(startSizeConstantMaxSeparate.x, startSizeConstantMaxSeparate.y);
  25399. if (renderMode === 1)
  25400. maxSizeY = startSizeConstantMaxSeparate.y;
  25401. }
  25402. else {
  25403. maxSize = this.startSizeConstantMax;
  25404. if (renderMode === 1)
  25405. maxSizeY = this.startSizeConstantMax;
  25406. }
  25407. break;
  25408. case 3:
  25409. break;
  25410. }
  25411. if (this._sizeOverLifetime && this._sizeOverLifetime.enable) {
  25412. var size = this._sizeOverLifetime.size;
  25413. maxSize *= this._sizeOverLifetime.size.getMaxSizeInGradient();
  25414. }
  25415. var threeDMaxSize = ShurikenParticleSystem._tempVector30;
  25416. var rotSize, nonRotSize;
  25417. switch (renderMode) {
  25418. case 0:
  25419. rotSize = maxSize * ShurikenParticleSystem.halfKSqrtOf2;
  25420. Vector3.scale(sizeScale, maxSize, threeDMaxSize);
  25421. Vector3.subtract(boundMin, threeDMaxSize, boundMin);
  25422. Vector3.add(boundMax, threeDMaxSize, boundMax);
  25423. break;
  25424. case 1:
  25425. var maxStretchPosition = ShurikenParticleSystem._tempVector31;
  25426. var maxStretchVelocity = ShurikenParticleSystem._tempVector32;
  25427. var minStretchVelocity = ShurikenParticleSystem._tempVector33;
  25428. var minStretchPosition = ShurikenParticleSystem._tempVector34;
  25429. if (this._velocityOverLifetime && this._velocityOverLifetime.enable) ;
  25430. else {
  25431. Vector3.multiply(velocityScale, startMaxVelocity, maxStretchVelocity);
  25432. Vector3.multiply(velocityScale, startMinVelocity, minStretchVelocity);
  25433. }
  25434. var sizeStretch = maxSizeY * particleRender.stretchedBillboardLengthScale;
  25435. var maxStretchLength = Vector3.scalarLength(maxStretchVelocity) * particleRender.stretchedBillboardSpeedScale + sizeStretch;
  25436. var minStretchLength = Vector3.scalarLength(minStretchVelocity) * particleRender.stretchedBillboardSpeedScale + sizeStretch;
  25437. var norMaxStretchVelocity = ShurikenParticleSystem._tempVector35;
  25438. var norMinStretchVelocity = ShurikenParticleSystem._tempVector36;
  25439. Vector3.normalize(maxStretchVelocity, norMaxStretchVelocity);
  25440. Vector3.scale(norMaxStretchVelocity, maxStretchLength, minStretchPosition);
  25441. Vector3.subtract(maxStratPosition, minStretchPosition, minStretchPosition);
  25442. Vector3.normalize(minStretchVelocity, norMinStretchVelocity);
  25443. Vector3.scale(norMinStretchVelocity, minStretchLength, maxStretchPosition);
  25444. Vector3.add(minStratPosition, maxStretchPosition, maxStretchPosition);
  25445. rotSize = maxSize * ShurikenParticleSystem.halfKSqrtOf2;
  25446. Vector3.scale(sizeScale, rotSize, threeDMaxSize);
  25447. var halfNorMaxStretchVelocity = ShurikenParticleSystem._tempVector37;
  25448. var halfNorMinStretchVelocity = ShurikenParticleSystem._tempVector38;
  25449. Vector3.scale(norMaxStretchVelocity, 0.5, halfNorMaxStretchVelocity);
  25450. Vector3.scale(norMinStretchVelocity, 0.5, halfNorMinStretchVelocity);
  25451. Vector3.multiply(halfNorMaxStretchVelocity, sizeScale, halfNorMaxStretchVelocity);
  25452. Vector3.multiply(halfNorMinStretchVelocity, sizeScale, halfNorMinStretchVelocity);
  25453. Vector3.add(boundMin, halfNorMinStretchVelocity, boundMin);
  25454. Vector3.min(boundMin, minStretchPosition, boundMin);
  25455. Vector3.subtract(boundMin, threeDMaxSize, boundMin);
  25456. Vector3.subtract(boundMax, halfNorMaxStretchVelocity, boundMax);
  25457. Vector3.max(boundMax, maxStretchPosition, boundMax);
  25458. Vector3.add(boundMax, threeDMaxSize, boundMax);
  25459. break;
  25460. case 2:
  25461. maxSize *= Math.cos(0.78539816339744830961566084581988);
  25462. nonRotSize = maxSize * 0.5;
  25463. threeDMaxSize.x = sizeScale.x * nonRotSize;
  25464. threeDMaxSize.y = sizeScale.z * nonRotSize;
  25465. Vector3.subtract(boundMin, threeDMaxSize, boundMin);
  25466. Vector3.add(boundMax, threeDMaxSize, boundMax);
  25467. break;
  25468. case 3:
  25469. maxSize *= Math.cos(0.78539816339744830961566084581988);
  25470. nonRotSize = maxSize * 0.5;
  25471. Vector3.scale(sizeScale, nonRotSize, threeDMaxSize);
  25472. Vector3.subtract(boundMin, threeDMaxSize, boundMin);
  25473. Vector3.add(boundMax, threeDMaxSize, boundMax);
  25474. break;
  25475. }
  25476. this._boundingBox.getCorners(this._boundingBoxCorners);
  25477. }
  25478. _generateBounds() {
  25479. var particle = this._owner;
  25480. var particleRender = particle.particleRenderer;
  25481. var boundsMin = this._bounds.getMin();
  25482. var boundsMax = this._bounds.getMax();
  25483. var time = 0;
  25484. switch (this.startLifetimeType) {
  25485. case 0:
  25486. time = this._startLifetimeConstant;
  25487. break;
  25488. case 2:
  25489. time = this._startLifetimeConstantMax;
  25490. break;
  25491. case 1:
  25492. case 3:
  25493. default:
  25494. break;
  25495. }
  25496. var speedOrigan = 0;
  25497. switch (this.startSpeedType) {
  25498. case 0:
  25499. speedOrigan = this.startSpeedConstant;
  25500. break;
  25501. case 2:
  25502. speedOrigan = this.startSpeedConstantMax;
  25503. break;
  25504. case 1:
  25505. case 3:
  25506. default:
  25507. break;
  25508. }
  25509. var maxSizeScale = 0;
  25510. if (this.threeDStartSize) {
  25511. switch (this.startSizeType) {
  25512. case 0:
  25513. maxSizeScale = Math.max(this.startSizeConstantSeparate.x, this.startSizeConstantSeparate.y, this.startSizeConstantSeparate.z);
  25514. break;
  25515. case 2:
  25516. maxSizeScale = Math.max(this.startSizeConstantMaxSeparate.x, this.startSizeConstantMaxSeparate.y, this.startSizeConstantMaxSeparate.z);
  25517. break;
  25518. case 1:
  25519. case 3:
  25520. default:
  25521. break;
  25522. }
  25523. }
  25524. else {
  25525. switch (this.startSizeType) {
  25526. case 0:
  25527. maxSizeScale = this.startSizeConstant;
  25528. break;
  25529. case 2:
  25530. maxSizeScale = this.startSizeConstantMax;
  25531. break;
  25532. case 1:
  25533. case 3:
  25534. default:
  25535. break;
  25536. }
  25537. }
  25538. var zDirectionSpeed = ShurikenParticleSystem._tempVector30;
  25539. var fDirectionSpeed = ShurikenParticleSystem._tempVector31;
  25540. var zEmisionOffsetXYZ = ShurikenParticleSystem._tempVector32;
  25541. var fEmisionOffsetXYZ = ShurikenParticleSystem._tempVector33;
  25542. zDirectionSpeed.setValue(0, 0, 1);
  25543. fDirectionSpeed.setValue(0, 0, 0);
  25544. zEmisionOffsetXYZ.setValue(0, 0, 0);
  25545. fEmisionOffsetXYZ.setValue(0, 0, 0);
  25546. if (this.shape && this.shape.enable) {
  25547. switch (this.shape.shapeType) {
  25548. case exports.ParticleSystemShapeType.Sphere:
  25549. var sphere = this.shape;
  25550. zDirectionSpeed.setValue(1, 1, 1);
  25551. fDirectionSpeed.setValue(1, 1, 1);
  25552. zEmisionOffsetXYZ.setValue(sphere.radius, sphere.radius, sphere.radius);
  25553. fEmisionOffsetXYZ.setValue(sphere.radius, sphere.radius, sphere.radius);
  25554. break;
  25555. case exports.ParticleSystemShapeType.Hemisphere:
  25556. var hemiShpere = this.shape;
  25557. zDirectionSpeed.setValue(1, 1, 1);
  25558. fDirectionSpeed.setValue(1, 1, 1);
  25559. zEmisionOffsetXYZ.setValue(hemiShpere.radius, hemiShpere.radius, hemiShpere.radius);
  25560. fEmisionOffsetXYZ.setValue(hemiShpere.radius, hemiShpere.radius, 0.0);
  25561. break;
  25562. case exports.ParticleSystemShapeType.Cone:
  25563. var cone = this.shape;
  25564. if (cone.emitType == 0 || cone.emitType == 1) {
  25565. var angle = cone.angle;
  25566. var sinAngle = Math.sin(angle);
  25567. zDirectionSpeed.setValue(sinAngle, sinAngle, 1.0);
  25568. fDirectionSpeed.setValue(sinAngle, sinAngle, 0.0);
  25569. zEmisionOffsetXYZ.setValue(cone.radius, cone.radius, 0.0);
  25570. fEmisionOffsetXYZ.setValue(cone.radius, cone.radius, 0.0);
  25571. break;
  25572. }
  25573. else if (cone.emitType == 2 || cone.emitType == 3) {
  25574. var angle = cone.angle;
  25575. var sinAngle = Math.sin(angle);
  25576. var coneLength = cone.length;
  25577. zDirectionSpeed.setValue(sinAngle, sinAngle, 1.0);
  25578. fDirectionSpeed.setValue(sinAngle, sinAngle, 0.0);
  25579. var tanAngle = Math.tan(angle);
  25580. var rPLCT = cone.radius + coneLength * tanAngle;
  25581. zEmisionOffsetXYZ.setValue(rPLCT, rPLCT, coneLength);
  25582. fEmisionOffsetXYZ.setValue(rPLCT, rPLCT, 0.0);
  25583. }
  25584. break;
  25585. case exports.ParticleSystemShapeType.Box:
  25586. var box = this.shape;
  25587. if (this.shape.randomDirection != 0) {
  25588. zDirectionSpeed.setValue(1, 1, 1);
  25589. fDirectionSpeed.setValue(1, 1, 1);
  25590. }
  25591. zEmisionOffsetXYZ.setValue(box.x / 2, box.y / 2, box.z / 2);
  25592. fEmisionOffsetXYZ.setValue(box.x / 2, box.y / 2, box.z / 2);
  25593. break;
  25594. case exports.ParticleSystemShapeType.Circle:
  25595. var circle = this.shape;
  25596. zDirectionSpeed.setValue(1, 1, 1);
  25597. fDirectionSpeed.setValue(1, 1, 1);
  25598. zEmisionOffsetXYZ.setValue(circle.radius, circle.radius, 0);
  25599. fEmisionOffsetXYZ.setValue(circle.radius, circle.radius, 0);
  25600. break;
  25601. default:
  25602. break;
  25603. }
  25604. }
  25605. var meshSize = 0;
  25606. var meshMode = particleRender.renderMode == 4;
  25607. switch (particleRender.renderMode) {
  25608. case 0:
  25609. case 1:
  25610. case 2:
  25611. case 3:
  25612. meshSize = ShurikenParticleSystem.halfKSqrtOf2;
  25613. break;
  25614. case 4:
  25615. var meshBounds = particleRender.mesh.bounds;
  25616. meshSize = Math.sqrt(Math.pow(meshBounds.getExtent().x, 2.0) + Math.pow(meshBounds.getExtent().y, 2.0) + Math.pow(meshBounds.getExtent().z, 2.0));
  25617. break;
  25618. default:
  25619. break;
  25620. }
  25621. var endSizeOffset = ShurikenParticleSystem._tempVector36;
  25622. endSizeOffset.setValue(1, 1, 1);
  25623. if (this.sizeOverLifetime && this.sizeOverLifetime.enable) {
  25624. var gradientSize = this.sizeOverLifetime.size;
  25625. var maxSize = gradientSize.getMaxSizeInGradient(meshMode);
  25626. endSizeOffset.setValue(maxSize, maxSize, maxSize);
  25627. }
  25628. var offsetSize = meshSize * maxSizeScale;
  25629. Vector3.scale(endSizeOffset, offsetSize, endSizeOffset);
  25630. var speedZOffset = ShurikenParticleSystem._tempVector34;
  25631. var speedFOffset = ShurikenParticleSystem._tempVector35;
  25632. if (speedOrigan > 0) {
  25633. Vector3.scale(zDirectionSpeed, speedOrigan, speedZOffset);
  25634. Vector3.scale(fDirectionSpeed, speedOrigan, speedFOffset);
  25635. }
  25636. else {
  25637. Vector3.scale(zDirectionSpeed, -speedOrigan, speedFOffset);
  25638. Vector3.scale(fDirectionSpeed, -speedOrigan, speedZOffset);
  25639. }
  25640. if (this.velocityOverLifetime && this.velocityOverLifetime.enable) {
  25641. var gradientVelocity = this.velocityOverLifetime.velocity;
  25642. var velocitySpeedOffset = ShurikenParticleSystem._tempVector37;
  25643. velocitySpeedOffset.setValue(0, 0, 0);
  25644. switch (gradientVelocity.type) {
  25645. case 0:
  25646. gradientVelocity.constant.cloneTo(velocitySpeedOffset);
  25647. break;
  25648. case 2:
  25649. gradientVelocity.constantMax.cloneTo(velocitySpeedOffset);
  25650. break;
  25651. case 1:
  25652. var curveX = gradientVelocity.gradientX.getAverageValue();
  25653. var curveY = gradientVelocity.gradientY.getAverageValue();
  25654. var curveZ = gradientVelocity.gradientZ.getAverageValue();
  25655. velocitySpeedOffset.setValue(curveX, curveY, curveZ);
  25656. break;
  25657. case 3:
  25658. var xMax = gradientVelocity.gradientXMax.getAverageValue();
  25659. var yMax = gradientVelocity.gradientYMax.getAverageValue();
  25660. var zMax = gradientVelocity.gradientZMax.getAverageValue();
  25661. velocitySpeedOffset.setValue(xMax, yMax, zMax);
  25662. break;
  25663. default:
  25664. break;
  25665. }
  25666. if (this.velocityOverLifetime.space == 1) {
  25667. Vector3.transformV3ToV3(velocitySpeedOffset, this._owner.transform.worldMatrix, velocitySpeedOffset);
  25668. }
  25669. Vector3.add(speedZOffset, velocitySpeedOffset, speedZOffset);
  25670. Vector3.subtract(speedFOffset, velocitySpeedOffset, speedFOffset);
  25671. Vector3.max(speedZOffset, Vector3._ZERO, speedZOffset);
  25672. Vector3.max(speedFOffset, Vector3._ZERO, speedFOffset);
  25673. }
  25674. Vector3.scale(speedZOffset, time, speedZOffset);
  25675. Vector3.scale(speedFOffset, time, speedFOffset);
  25676. var gravity = this.gravityModifier;
  25677. if (gravity != 0) {
  25678. var gravityOffset = 0.5 * ShurikenParticleSystem.g * gravity * time * time;
  25679. var speedZOffsetY = speedZOffset.y - gravityOffset;
  25680. var speedFOffsetY = speedFOffset.y + gravityOffset;
  25681. speedZOffsetY = speedZOffsetY > 0 ? speedZOffsetY : 0;
  25682. speedFOffsetY = speedFOffsetY > 0 ? speedFOffsetY : 0;
  25683. this._gravityOffset.setValue(speedZOffset.y - speedZOffsetY, speedFOffsetY - speedFOffset.y);
  25684. }
  25685. Vector3.add(speedZOffset, endSizeOffset, boundsMax);
  25686. Vector3.add(boundsMax, zEmisionOffsetXYZ, boundsMax);
  25687. Vector3.add(speedFOffset, endSizeOffset, boundsMin);
  25688. Vector3.add(boundsMin, fEmisionOffsetXYZ, boundsMin);
  25689. Vector3.scale(boundsMin, -1, boundsMin);
  25690. this._bounds.setMin(boundsMin);
  25691. this._bounds.setMax(boundsMax);
  25692. }
  25693. get customBounds() {
  25694. return this._customBounds;
  25695. }
  25696. set customBounds(value) {
  25697. if (value) {
  25698. this._useCustomBounds = true;
  25699. }
  25700. else {
  25701. this._useCustomBounds = false;
  25702. }
  25703. this._customBounds = value;
  25704. }
  25705. _simulationSupported() {
  25706. if (this.simulationSpace == 0) {
  25707. return false;
  25708. }
  25709. return true;
  25710. }
  25711. _updateEmission() {
  25712. if (!this.isAlive)
  25713. return;
  25714. if (this._simulateUpdate) {
  25715. this._simulateUpdate = false;
  25716. }
  25717. else {
  25718. var elapsedTime = (this._startUpdateLoopCount !== Laya.Stat.loopCount && !this._isPaused) ? this._owner._scene.timer._delta / 1000.0 : 0;
  25719. elapsedTime = Math.min(ShurikenParticleSystem._maxElapsedTime, elapsedTime * this.simulationSpeed);
  25720. this._updateParticles(elapsedTime);
  25721. }
  25722. }
  25723. _updateParticles(elapsedTime) {
  25724. if (this._ownerRender.renderMode === 4 && !this._ownerRender.mesh)
  25725. return;
  25726. this._currentTime += elapsedTime;
  25727. this._retireActiveParticles();
  25728. this._freeRetiredParticles();
  25729. this._totalDelayTime += elapsedTime;
  25730. if (this._totalDelayTime < this._playStartDelay) {
  25731. return;
  25732. }
  25733. if (this._emission.enable && this._isEmitting && !this._isPaused)
  25734. this._advanceTime(elapsedTime, this._currentTime);
  25735. }
  25736. _updateParticlesSimulationRestart(time) {
  25737. this._firstActiveElement = 0;
  25738. this._firstNewElement = 0;
  25739. this._firstFreeElement = 0;
  25740. this._firstRetiredElement = 0;
  25741. this._burstsIndex = 0;
  25742. this._frameRateTime = time;
  25743. this._emissionTime = 0;
  25744. this._totalDelayTime = 0;
  25745. this._currentTime = time;
  25746. var delayTime = time;
  25747. if (delayTime < this._playStartDelay) {
  25748. this._totalDelayTime = delayTime;
  25749. return;
  25750. }
  25751. if (this._emission.enable)
  25752. this._advanceTime(time, time);
  25753. }
  25754. _retireActiveParticles() {
  25755. const epsilon = 0.0001;
  25756. while (this._firstActiveElement != this._firstNewElement) {
  25757. var index = this._firstActiveElement * this._floatCountPerVertex * this._vertexStride;
  25758. var timeIndex = index + this._timeIndex;
  25759. var particleAge = this._currentTime - this._vertices[timeIndex];
  25760. if (particleAge + epsilon < this._vertices[index + this._startLifeTimeIndex])
  25761. break;
  25762. this._vertices[timeIndex] = this._drawCounter;
  25763. this._firstActiveElement++;
  25764. if (this._firstActiveElement >= this._bufferMaxParticles)
  25765. this._firstActiveElement = 0;
  25766. }
  25767. }
  25768. _freeRetiredParticles() {
  25769. while (this._firstRetiredElement != this._firstActiveElement) {
  25770. var age = this._drawCounter - this._vertices[this._firstRetiredElement * this._floatCountPerVertex * this._vertexStride + this._timeIndex];
  25771. this._firstRetiredElement++;
  25772. if (this._firstRetiredElement >= this._bufferMaxParticles)
  25773. this._firstRetiredElement = 0;
  25774. }
  25775. }
  25776. _burst(fromTime, toTime) {
  25777. var totalEmitCount = 0;
  25778. var bursts = this._emission._bursts;
  25779. for (var n = bursts.length; this._burstsIndex < n; this._burstsIndex++) {
  25780. var burst = bursts[this._burstsIndex];
  25781. var burstTime = burst.time;
  25782. if (fromTime <= burstTime && burstTime < toTime) {
  25783. var emitCount;
  25784. if (this.autoRandomSeed) {
  25785. emitCount = Laya.MathUtil.lerp(burst.minCount, burst.maxCount, Math.random());
  25786. }
  25787. else {
  25788. this._rand.seed = this._randomSeeds[0];
  25789. emitCount = Laya.MathUtil.lerp(burst.minCount, burst.maxCount, this._rand.getFloat());
  25790. this._randomSeeds[0] = this._rand.seed;
  25791. }
  25792. totalEmitCount += emitCount;
  25793. }
  25794. else {
  25795. break;
  25796. }
  25797. }
  25798. return totalEmitCount;
  25799. }
  25800. _advanceTime(elapsedTime, emitTime) {
  25801. var i;
  25802. var lastEmissionTime = this._emissionTime;
  25803. this._emissionTime += elapsedTime;
  25804. var totalEmitCount = 0;
  25805. if (this._emissionTime > this.duration) {
  25806. if (this.looping) {
  25807. totalEmitCount += this._burst(lastEmissionTime, this._emissionTime);
  25808. this._emissionTime -= this.duration;
  25809. this._burstsIndex = 0;
  25810. totalEmitCount += this._burst(0, this._emissionTime);
  25811. }
  25812. else {
  25813. totalEmitCount = Math.min(this.maxParticles - this.aliveParticleCount, totalEmitCount);
  25814. for (i = 0; i < totalEmitCount; i++)
  25815. this.emit(emitTime);
  25816. this._isPlaying = false;
  25817. this.stop();
  25818. return;
  25819. }
  25820. }
  25821. else {
  25822. totalEmitCount += this._burst(lastEmissionTime, this._emissionTime);
  25823. }
  25824. totalEmitCount = Math.min(this.maxParticles - this.aliveParticleCount, totalEmitCount);
  25825. for (i = 0; i < totalEmitCount; i++)
  25826. this.emit(emitTime);
  25827. var emissionRate = this.emission.emissionRate;
  25828. if (emissionRate > 0) {
  25829. var minEmissionTime = 1 / emissionRate;
  25830. this._frameRateTime += minEmissionTime;
  25831. this._frameRateTime = this._currentTime - (this._currentTime - this._frameRateTime) % this._maxStartLifetime;
  25832. while (this._frameRateTime <= emitTime) {
  25833. if (this.emit(this._frameRateTime))
  25834. this._frameRateTime += minEmissionTime;
  25835. else
  25836. break;
  25837. }
  25838. this._frameRateTime = Math.floor(emitTime / minEmissionTime) * minEmissionTime;
  25839. }
  25840. }
  25841. _initBufferDatas() {
  25842. if (this._vertexBuffer) {
  25843. var memorySize = this._vertexBuffer._byteLength + this._indexBuffer.indexCount * 2;
  25844. this._vertexBuffer.destroy();
  25845. this._indexBuffer.destroy();
  25846. Laya.Resource._addMemory(-memorySize, -memorySize);
  25847. }
  25848. var gl = Laya.LayaGL.instance;
  25849. var render = this._ownerRender;
  25850. var renderMode = render.renderMode;
  25851. if (renderMode !== -1 && this.maxParticles > 0) {
  25852. var indices, i, j, m, indexOffset, perPartOffset, vertexDeclaration;
  25853. var vbMemorySize = 0, memorySize = 0;
  25854. var mesh = render.mesh;
  25855. if (renderMode === 4) {
  25856. if (mesh) {
  25857. vertexDeclaration = VertexShurikenParticleMesh.vertexDeclaration;
  25858. this._floatCountPerVertex = vertexDeclaration.vertexStride / 4;
  25859. this._startLifeTimeIndex = 12;
  25860. this._timeIndex = 16;
  25861. this._vertexStride = mesh._vertexCount;
  25862. var totalVertexCount = this._bufferMaxParticles * this._vertexStride;
  25863. var vbCount = Math.floor(totalVertexCount / 65535) + 1;
  25864. var lastVBVertexCount = totalVertexCount % 65535;
  25865. if (vbCount > 1) {
  25866. throw new Error("ShurikenParticleSystem:the maxParticleCount multiply mesh vertexCount is large than 65535.");
  25867. }
  25868. vbMemorySize = vertexDeclaration.vertexStride * lastVBVertexCount;
  25869. this._vertexBuffer = new VertexBuffer3D(vbMemorySize, gl.DYNAMIC_DRAW);
  25870. this._vertexBuffer.vertexDeclaration = vertexDeclaration;
  25871. this._vertices = new Float32Array(this._floatCountPerVertex * lastVBVertexCount);
  25872. this._indexStride = mesh._indexBuffer.indexCount;
  25873. var indexDatas = mesh._indexBuffer.getData();
  25874. var indexCount = this._bufferMaxParticles * this._indexStride;
  25875. this._indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt16, indexCount, gl.STATIC_DRAW);
  25876. indices = new Uint16Array(indexCount);
  25877. memorySize = vbMemorySize + indexCount * 2;
  25878. indexOffset = 0;
  25879. for (i = 0; i < this._bufferMaxParticles; i++) {
  25880. var indexValueOffset = i * this._vertexStride;
  25881. for (j = 0, m = indexDatas.length; j < m; j++)
  25882. indices[indexOffset++] = indexValueOffset + indexDatas[j];
  25883. }
  25884. this._indexBuffer.setData(indices);
  25885. this._bufferState.bind();
  25886. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  25887. this._bufferState.applyIndexBuffer(this._indexBuffer);
  25888. this._bufferState.unBind();
  25889. }
  25890. }
  25891. else {
  25892. vertexDeclaration = VertexShurikenParticleBillboard.vertexDeclaration;
  25893. this._floatCountPerVertex = vertexDeclaration.vertexStride / 4;
  25894. this._startLifeTimeIndex = 7;
  25895. this._timeIndex = 11;
  25896. this._vertexStride = 4;
  25897. vbMemorySize = vertexDeclaration.vertexStride * this._bufferMaxParticles * this._vertexStride;
  25898. this._vertexBuffer = new VertexBuffer3D(vbMemorySize, gl.DYNAMIC_DRAW);
  25899. this._vertexBuffer.vertexDeclaration = vertexDeclaration;
  25900. this._vertices = new Float32Array(this._floatCountPerVertex * this._bufferMaxParticles * this._vertexStride);
  25901. for (i = 0; i < this._bufferMaxParticles; i++) {
  25902. perPartOffset = i * this._floatCountPerVertex * this._vertexStride;
  25903. this._vertices[perPartOffset] = -0.5;
  25904. this._vertices[perPartOffset + 1] = -0.5;
  25905. this._vertices[perPartOffset + 2] = 0;
  25906. this._vertices[perPartOffset + 3] = 1;
  25907. perPartOffset += this._floatCountPerVertex;
  25908. this._vertices[perPartOffset] = 0.5;
  25909. this._vertices[perPartOffset + 1] = -0.5;
  25910. this._vertices[perPartOffset + 2] = 1;
  25911. this._vertices[perPartOffset + 3] = 1;
  25912. perPartOffset += this._floatCountPerVertex;
  25913. this._vertices[perPartOffset] = 0.5;
  25914. this._vertices[perPartOffset + 1] = 0.5;
  25915. this._vertices[perPartOffset + 2] = 1;
  25916. this._vertices[perPartOffset + 3] = 0;
  25917. perPartOffset += this._floatCountPerVertex;
  25918. this._vertices[perPartOffset] = -0.5;
  25919. this._vertices[perPartOffset + 1] = 0.5;
  25920. this._vertices[perPartOffset + 2] = 0;
  25921. this._vertices[perPartOffset + 3] = 0;
  25922. }
  25923. this._indexStride = 6;
  25924. this._indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt16, this._bufferMaxParticles * 6, gl.STATIC_DRAW);
  25925. indices = new Uint16Array(this._bufferMaxParticles * 6);
  25926. for (i = 0; i < this._bufferMaxParticles; i++) {
  25927. indexOffset = i * 6;
  25928. var firstVertex = i * this._vertexStride, secondVertex = firstVertex + 2;
  25929. indices[indexOffset++] = firstVertex;
  25930. indices[indexOffset++] = secondVertex;
  25931. indices[indexOffset++] = firstVertex + 1;
  25932. indices[indexOffset++] = firstVertex;
  25933. indices[indexOffset++] = firstVertex + 3;
  25934. indices[indexOffset++] = secondVertex;
  25935. }
  25936. this._indexBuffer.setData(indices);
  25937. memorySize = vbMemorySize + this._bufferMaxParticles * 6 * 2;
  25938. this._bufferState.bind();
  25939. this._bufferState.applyVertexBuffer(this._vertexBuffer);
  25940. this._bufferState.applyIndexBuffer(this._indexBuffer);
  25941. this._bufferState.unBind();
  25942. }
  25943. Laya.Resource._addMemory(memorySize, memorySize);
  25944. }
  25945. }
  25946. destroy() {
  25947. super.destroy();
  25948. var memorySize = this._vertexBuffer._byteLength + this._indexBuffer.indexCount * 2;
  25949. Laya.Resource._addMemory(-memorySize, -memorySize);
  25950. this._bufferState.destroy();
  25951. this._vertexBuffer.destroy();
  25952. this._indexBuffer.destroy();
  25953. this._emission.destroy();
  25954. this._boundingBox = null;
  25955. this._boundingSphere = null;
  25956. this._boundingBoxCorners = null;
  25957. this._bounds = null;
  25958. this._customBounds = null;
  25959. this._bufferState = null;
  25960. this._vertexBuffer = null;
  25961. this._indexBuffer = null;
  25962. this._owner = null;
  25963. this._vertices = null;
  25964. this._indexBuffer = null;
  25965. this._emission = null;
  25966. this._shape = null;
  25967. this.startLifeTimeGradient = null;
  25968. this.startLifeTimeGradientMin = null;
  25969. this.startLifeTimeGradientMax = null;
  25970. this.startSizeConstantSeparate = null;
  25971. this.startSizeConstantMinSeparate = null;
  25972. this.startSizeConstantMaxSeparate = null;
  25973. this.startRotationConstantSeparate = null;
  25974. this.startRotationConstantMinSeparate = null;
  25975. this.startRotationConstantMaxSeparate = null;
  25976. this.startColorConstant = null;
  25977. this.startColorConstantMin = null;
  25978. this.startColorConstantMax = null;
  25979. this._velocityOverLifetime = null;
  25980. this._colorOverLifetime = null;
  25981. this._sizeOverLifetime = null;
  25982. this._rotationOverLifetime = null;
  25983. this._textureSheetAnimation = null;
  25984. }
  25985. emit(time) {
  25986. var position = ShurikenParticleSystem._tempPosition;
  25987. var direction = ShurikenParticleSystem._tempDirection;
  25988. if (this._shape && this._shape.enable) {
  25989. if (this.autoRandomSeed)
  25990. this._shape.generatePositionAndDirection(position, direction);
  25991. else
  25992. this._shape.generatePositionAndDirection(position, direction, this._rand, this._randomSeeds);
  25993. }
  25994. else {
  25995. position.x = position.y = position.z = 0;
  25996. direction.x = direction.y = 0;
  25997. direction.z = 1;
  25998. }
  25999. return this.addParticle(position, direction, time);
  26000. }
  26001. addParticle(position, direction, time) {
  26002. Vector3.normalize(direction, direction);
  26003. var nextFreeParticle = this._firstFreeElement + 1;
  26004. if (nextFreeParticle >= this._bufferMaxParticles)
  26005. nextFreeParticle = 0;
  26006. if (nextFreeParticle === this._firstRetiredElement)
  26007. return false;
  26008. var transform = this._owner.transform;
  26009. ShurikenParticleData.create(this, this._ownerRender, transform);
  26010. var particleAge = this._currentTime - time;
  26011. if (particleAge >= ShurikenParticleData.startLifeTime)
  26012. return true;
  26013. var pos, rot;
  26014. if (this.simulationSpace == 0) {
  26015. pos = transform.position;
  26016. rot = transform.rotation;
  26017. }
  26018. var startSpeed;
  26019. switch (this.startSpeedType) {
  26020. case 0:
  26021. startSpeed = this.startSpeedConstant;
  26022. break;
  26023. case 2:
  26024. if (this.autoRandomSeed) {
  26025. startSpeed = Laya.MathUtil.lerp(this.startSpeedConstantMin, this.startSpeedConstantMax, Math.random());
  26026. }
  26027. else {
  26028. this._rand.seed = this._randomSeeds[8];
  26029. startSpeed = Laya.MathUtil.lerp(this.startSpeedConstantMin, this.startSpeedConstantMax, this._rand.getFloat());
  26030. this._randomSeeds[8] = this._rand.seed;
  26031. }
  26032. break;
  26033. }
  26034. var randomVelocityX, randomVelocityY, randomVelocityZ, randomColor, randomSize, randomRotation, randomTextureAnimation;
  26035. var needRandomVelocity = this._velocityOverLifetime && this._velocityOverLifetime.enable;
  26036. if (needRandomVelocity) {
  26037. var velocityType = this._velocityOverLifetime.velocity.type;
  26038. if (velocityType === 2 || velocityType === 3) {
  26039. if (this.autoRandomSeed) {
  26040. randomVelocityX = Math.random();
  26041. randomVelocityY = Math.random();
  26042. randomVelocityZ = Math.random();
  26043. }
  26044. else {
  26045. this._rand.seed = this._randomSeeds[9];
  26046. randomVelocityX = this._rand.getFloat();
  26047. randomVelocityY = this._rand.getFloat();
  26048. randomVelocityZ = this._rand.getFloat();
  26049. this._randomSeeds[9] = this._rand.seed;
  26050. }
  26051. }
  26052. else {
  26053. needRandomVelocity = false;
  26054. }
  26055. }
  26056. else {
  26057. needRandomVelocity = false;
  26058. }
  26059. var needRandomColor = this._colorOverLifetime && this._colorOverLifetime.enable;
  26060. if (needRandomColor) {
  26061. var colorType = this._colorOverLifetime.color.type;
  26062. if (colorType === 3) {
  26063. if (this.autoRandomSeed) {
  26064. randomColor = Math.random();
  26065. }
  26066. else {
  26067. this._rand.seed = this._randomSeeds[10];
  26068. randomColor = this._rand.getFloat();
  26069. this._randomSeeds[10] = this._rand.seed;
  26070. }
  26071. }
  26072. else {
  26073. needRandomColor = false;
  26074. }
  26075. }
  26076. else {
  26077. needRandomColor = false;
  26078. }
  26079. var needRandomSize = this._sizeOverLifetime && this._sizeOverLifetime.enable;
  26080. if (needRandomSize) {
  26081. var sizeType = this._sizeOverLifetime.size.type;
  26082. if (sizeType === 3) {
  26083. if (this.autoRandomSeed) {
  26084. randomSize = Math.random();
  26085. }
  26086. else {
  26087. this._rand.seed = this._randomSeeds[11];
  26088. randomSize = this._rand.getFloat();
  26089. this._randomSeeds[11] = this._rand.seed;
  26090. }
  26091. }
  26092. else {
  26093. needRandomSize = false;
  26094. }
  26095. }
  26096. else {
  26097. needRandomSize = false;
  26098. }
  26099. var needRandomRotation = this._rotationOverLifetime && this._rotationOverLifetime.enable;
  26100. if (needRandomRotation) {
  26101. var rotationType = this._rotationOverLifetime.angularVelocity.type;
  26102. if (rotationType === 2 || rotationType === 3) {
  26103. if (this.autoRandomSeed) {
  26104. randomRotation = Math.random();
  26105. }
  26106. else {
  26107. this._rand.seed = this._randomSeeds[12];
  26108. randomRotation = this._rand.getFloat();
  26109. this._randomSeeds[12] = this._rand.seed;
  26110. }
  26111. }
  26112. else {
  26113. needRandomRotation = false;
  26114. }
  26115. }
  26116. else {
  26117. needRandomRotation = false;
  26118. }
  26119. var needRandomTextureAnimation = this._textureSheetAnimation && this._textureSheetAnimation.enable;
  26120. if (needRandomTextureAnimation) {
  26121. var textureAnimationType = this._textureSheetAnimation.frame.type;
  26122. if (textureAnimationType === 3) {
  26123. if (this.autoRandomSeed) {
  26124. randomTextureAnimation = Math.random();
  26125. }
  26126. else {
  26127. this._rand.seed = this._randomSeeds[15];
  26128. randomTextureAnimation = this._rand.getFloat();
  26129. this._randomSeeds[15] = this._rand.seed;
  26130. }
  26131. }
  26132. else {
  26133. needRandomTextureAnimation = false;
  26134. }
  26135. }
  26136. else {
  26137. needRandomTextureAnimation = false;
  26138. }
  26139. var startIndex = this._firstFreeElement * this._floatCountPerVertex * this._vertexStride;
  26140. var subU = ShurikenParticleData.startUVInfo[0];
  26141. var subV = ShurikenParticleData.startUVInfo[1];
  26142. var startU = ShurikenParticleData.startUVInfo[2];
  26143. var startV = ShurikenParticleData.startUVInfo[3];
  26144. var meshVertices, meshVertexStride, meshPosOffset, meshCorOffset, meshUVOffset, meshVertexIndex;
  26145. var render = this._ownerRender;
  26146. if (render.renderMode === 4) {
  26147. var meshVB = render.mesh._vertexBuffer;
  26148. meshVertices = meshVB.getFloat32Data();
  26149. var meshVertexDeclaration = meshVB.vertexDeclaration;
  26150. meshPosOffset = meshVertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_POSITION0)._offset / 4;
  26151. var colorElement = meshVertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_COLOR0);
  26152. meshCorOffset = colorElement ? colorElement._offset / 4 : -1;
  26153. var uvElement = meshVertexDeclaration.getVertexElementByUsage(VertexMesh.MESH_TEXTURECOORDINATE0);
  26154. meshUVOffset = uvElement ? uvElement._offset / 4 : -1;
  26155. meshVertexStride = meshVertexDeclaration.vertexStride / 4;
  26156. meshVertexIndex = 0;
  26157. }
  26158. else {
  26159. this._vertices[startIndex + 2] = startU;
  26160. this._vertices[startIndex + 3] = startV + subV;
  26161. var secondOffset = startIndex + this._floatCountPerVertex;
  26162. this._vertices[secondOffset + 2] = startU + subU;
  26163. this._vertices[secondOffset + 3] = startV + subV;
  26164. var thirdOffset = secondOffset + this._floatCountPerVertex;
  26165. this._vertices[thirdOffset + 2] = startU + subU;
  26166. this._vertices[thirdOffset + 3] = startV;
  26167. var fourthOffset = thirdOffset + this._floatCountPerVertex;
  26168. this._vertices[fourthOffset + 2] = startU;
  26169. this._vertices[fourthOffset + 3] = startV;
  26170. }
  26171. for (var i = startIndex, n = startIndex + this._floatCountPerVertex * this._vertexStride; i < n; i += this._floatCountPerVertex) {
  26172. var offset;
  26173. if (render.renderMode === 4) {
  26174. offset = i;
  26175. var vertexOffset = meshVertexStride * (meshVertexIndex++);
  26176. var meshOffset = vertexOffset + meshPosOffset;
  26177. this._vertices[offset++] = meshVertices[meshOffset++];
  26178. this._vertices[offset++] = meshVertices[meshOffset++];
  26179. this._vertices[offset++] = meshVertices[meshOffset];
  26180. if (meshCorOffset === -1) {
  26181. this._vertices[offset++] = 1.0;
  26182. this._vertices[offset++] = 1.0;
  26183. this._vertices[offset++] = 1.0;
  26184. this._vertices[offset++] = 1.0;
  26185. }
  26186. else {
  26187. meshOffset = vertexOffset + meshCorOffset;
  26188. this._vertices[offset++] = meshVertices[meshOffset++];
  26189. this._vertices[offset++] = meshVertices[meshOffset++];
  26190. this._vertices[offset++] = meshVertices[meshOffset++];
  26191. this._vertices[offset++] = meshVertices[meshOffset];
  26192. }
  26193. if (meshUVOffset === -1) {
  26194. this._vertices[offset++] = 0.0;
  26195. this._vertices[offset++] = 0.0;
  26196. }
  26197. else {
  26198. meshOffset = vertexOffset + meshUVOffset;
  26199. this._vertices[offset++] = startU + meshVertices[meshOffset++] * subU;
  26200. this._vertices[offset++] = startV + meshVertices[meshOffset] * subV;
  26201. }
  26202. }
  26203. else {
  26204. offset = i + 4;
  26205. }
  26206. this._vertices[offset++] = position.x;
  26207. this._vertices[offset++] = position.y;
  26208. this._vertices[offset++] = position.z;
  26209. this._vertices[offset++] = ShurikenParticleData.startLifeTime;
  26210. this._vertices[offset++] = direction.x;
  26211. this._vertices[offset++] = direction.y;
  26212. this._vertices[offset++] = direction.z;
  26213. this._vertices[offset++] = time;
  26214. this._vertices[offset++] = ShurikenParticleData.startColor.x;
  26215. this._vertices[offset++] = ShurikenParticleData.startColor.y;
  26216. this._vertices[offset++] = ShurikenParticleData.startColor.z;
  26217. this._vertices[offset++] = ShurikenParticleData.startColor.w;
  26218. this._vertices[offset++] = ShurikenParticleData.startSize[0];
  26219. this._vertices[offset++] = ShurikenParticleData.startSize[1];
  26220. this._vertices[offset++] = ShurikenParticleData.startSize[2];
  26221. this._vertices[offset++] = ShurikenParticleData.startRotation[0];
  26222. this._vertices[offset++] = ShurikenParticleData.startRotation[1];
  26223. this._vertices[offset++] = ShurikenParticleData.startRotation[2];
  26224. this._vertices[offset++] = startSpeed;
  26225. needRandomColor && (this._vertices[offset + 1] = randomColor);
  26226. needRandomSize && (this._vertices[offset + 2] = randomSize);
  26227. needRandomRotation && (this._vertices[offset + 3] = randomRotation);
  26228. needRandomTextureAnimation && (this._vertices[offset + 4] = randomTextureAnimation);
  26229. if (needRandomVelocity) {
  26230. this._vertices[offset + 5] = randomVelocityX;
  26231. this._vertices[offset + 6] = randomVelocityY;
  26232. this._vertices[offset + 7] = randomVelocityZ;
  26233. }
  26234. switch (this.simulationSpace) {
  26235. case 0:
  26236. offset += 8;
  26237. this._vertices[offset++] = pos.x;
  26238. this._vertices[offset++] = pos.y;
  26239. this._vertices[offset++] = pos.z;
  26240. this._vertices[offset++] = rot.x;
  26241. this._vertices[offset++] = rot.y;
  26242. this._vertices[offset++] = rot.z;
  26243. this._vertices[offset++] = rot.w;
  26244. break;
  26245. case 1:
  26246. break;
  26247. default:
  26248. throw new Error("ShurikenParticleMaterial: SimulationSpace value is invalid.");
  26249. }
  26250. }
  26251. this._firstFreeElement = nextFreeParticle;
  26252. return true;
  26253. }
  26254. addNewParticlesToVertexBuffer() {
  26255. var start;
  26256. var byteStride = this._vertexStride * this._floatCountPerVertex * 4;
  26257. if (this._firstNewElement < this._firstFreeElement) {
  26258. start = this._firstNewElement * byteStride;
  26259. this._vertexBuffer.setData(this._vertices.buffer, start, start, (this._firstFreeElement - this._firstNewElement) * byteStride);
  26260. }
  26261. else {
  26262. start = this._firstNewElement * byteStride;
  26263. this._vertexBuffer.setData(this._vertices.buffer, start, start, (this._bufferMaxParticles - this._firstNewElement) * byteStride);
  26264. if (this._firstFreeElement > 0) {
  26265. this._vertexBuffer.setData(this._vertices.buffer, 0, 0, this._firstFreeElement * byteStride);
  26266. }
  26267. }
  26268. this._firstNewElement = this._firstFreeElement;
  26269. }
  26270. _getType() {
  26271. return ShurikenParticleSystem._type;
  26272. }
  26273. _prepareRender(state) {
  26274. if (this._updateMask != Laya.Stat.loopCount) {
  26275. this._updateMask = Laya.Stat.loopCount;
  26276. this._updateEmission();
  26277. if (this._firstNewElement != this._firstFreeElement)
  26278. this.addNewParticlesToVertexBuffer();
  26279. this._drawCounter++;
  26280. }
  26281. if (this._firstActiveElement != this._firstFreeElement)
  26282. return true;
  26283. else
  26284. return false;
  26285. }
  26286. _render(state) {
  26287. this._bufferState.bind();
  26288. var indexCount;
  26289. var gl = Laya.LayaGL.instance;
  26290. if (this._firstActiveElement < this._firstFreeElement) {
  26291. indexCount = (this._firstFreeElement - this._firstActiveElement) * this._indexStride;
  26292. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, 2 * this._firstActiveElement * this._indexStride);
  26293. Laya.Stat.trianglesFaces += indexCount / 3;
  26294. Laya.Stat.renderBatches++;
  26295. }
  26296. else {
  26297. indexCount = (this._bufferMaxParticles - this._firstActiveElement) * this._indexStride;
  26298. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, 2 * this._firstActiveElement * this._indexStride);
  26299. Laya.Stat.trianglesFaces += indexCount / 3;
  26300. Laya.Stat.renderBatches++;
  26301. if (this._firstFreeElement > 0) {
  26302. indexCount = this._firstFreeElement * this._indexStride;
  26303. gl.drawElements(gl.TRIANGLES, indexCount, gl.UNSIGNED_SHORT, 0);
  26304. Laya.Stat.trianglesFaces += indexCount / 3;
  26305. Laya.Stat.renderBatches++;
  26306. }
  26307. }
  26308. }
  26309. play() {
  26310. this._burstsIndex = 0;
  26311. this._isEmitting = true;
  26312. this._isPlaying = true;
  26313. this._isPaused = false;
  26314. this._emissionTime = 0;
  26315. this._totalDelayTime = 0;
  26316. if (!this.autoRandomSeed) {
  26317. for (var i = 0, n = this._randomSeeds.length; i < n; i++)
  26318. this._randomSeeds[i] = this.randomSeed[0] + ShurikenParticleSystem._RANDOMOFFSET[i];
  26319. }
  26320. switch (this.startDelayType) {
  26321. case 0:
  26322. this._playStartDelay = this.startDelay;
  26323. break;
  26324. case 1:
  26325. if (this.autoRandomSeed) {
  26326. this._playStartDelay = Laya.MathUtil.lerp(this.startDelayMin, this.startDelayMax, Math.random());
  26327. }
  26328. else {
  26329. this._rand.seed = this._randomSeeds[2];
  26330. this._playStartDelay = Laya.MathUtil.lerp(this.startDelayMin, this.startDelayMax, this._rand.getFloat());
  26331. this._randomSeeds[2] = this._rand.seed;
  26332. }
  26333. break;
  26334. default:
  26335. throw new Error("Utils3D: startDelayType is invalid.");
  26336. }
  26337. this._frameRateTime = this._currentTime + this._playStartDelay;
  26338. this._startUpdateLoopCount = Laya.Stat.loopCount;
  26339. }
  26340. pause() {
  26341. this._isPaused = true;
  26342. }
  26343. simulate(time, restart = true) {
  26344. this._simulateUpdate = true;
  26345. if (restart) {
  26346. this._updateParticlesSimulationRestart(time);
  26347. }
  26348. else {
  26349. this._isPaused = false;
  26350. this._updateParticles(time);
  26351. }
  26352. this.pause();
  26353. }
  26354. stop() {
  26355. this._burstsIndex = 0;
  26356. this._isEmitting = false;
  26357. this._emissionTime = 0;
  26358. }
  26359. cloneTo(destObject) {
  26360. var dest = destObject;
  26361. dest._useCustomBounds = this._useCustomBounds;
  26362. (this._customBounds) && (this._customBounds.cloneTo(dest._customBounds));
  26363. dest.duration = this.duration;
  26364. dest.looping = this.looping;
  26365. dest.prewarm = this.prewarm;
  26366. dest.startDelayType = this.startDelayType;
  26367. dest.startDelay = this.startDelay;
  26368. dest.startDelayMin = this.startDelayMin;
  26369. dest.startDelayMax = this.startDelayMax;
  26370. dest._maxStartLifetime = this._maxStartLifetime;
  26371. dest.startLifetimeType = this.startLifetimeType;
  26372. dest.startLifetimeConstant = this.startLifetimeConstant;
  26373. this.startLifeTimeGradient.cloneTo(dest.startLifeTimeGradient);
  26374. dest.startLifetimeConstantMin = this.startLifetimeConstantMin;
  26375. dest.startLifetimeConstantMax = this.startLifetimeConstantMax;
  26376. this.startLifeTimeGradientMin.cloneTo(dest.startLifeTimeGradientMin);
  26377. this.startLifeTimeGradientMax.cloneTo(dest.startLifeTimeGradientMax);
  26378. dest.startSpeedType = this.startSpeedType;
  26379. dest.startSpeedConstant = this.startSpeedConstant;
  26380. dest.startSpeedConstantMin = this.startSpeedConstantMin;
  26381. dest.startSpeedConstantMax = this.startSpeedConstantMax;
  26382. dest.threeDStartSize = this.threeDStartSize;
  26383. dest.startSizeType = this.startSizeType;
  26384. dest.startSizeConstant = this.startSizeConstant;
  26385. this.startSizeConstantSeparate.cloneTo(dest.startSizeConstantSeparate);
  26386. dest.startSizeConstantMin = this.startSizeConstantMin;
  26387. dest.startSizeConstantMax = this.startSizeConstantMax;
  26388. this.startSizeConstantMinSeparate.cloneTo(dest.startSizeConstantMinSeparate);
  26389. this.startSizeConstantMaxSeparate.cloneTo(dest.startSizeConstantMaxSeparate);
  26390. dest.threeDStartRotation = this.threeDStartRotation;
  26391. dest.startRotationType = this.startRotationType;
  26392. dest.startRotationConstant = this.startRotationConstant;
  26393. this.startRotationConstantSeparate.cloneTo(dest.startRotationConstantSeparate);
  26394. dest.startRotationConstantMin = this.startRotationConstantMin;
  26395. dest.startRotationConstantMax = this.startRotationConstantMax;
  26396. this.startRotationConstantMinSeparate.cloneTo(dest.startRotationConstantMinSeparate);
  26397. this.startRotationConstantMaxSeparate.cloneTo(dest.startRotationConstantMaxSeparate);
  26398. dest.randomizeRotationDirection = this.randomizeRotationDirection;
  26399. dest.startColorType = this.startColorType;
  26400. this.startColorConstant.cloneTo(dest.startColorConstant);
  26401. this.startColorConstantMin.cloneTo(dest.startColorConstantMin);
  26402. this.startColorConstantMax.cloneTo(dest.startColorConstantMax);
  26403. dest.gravityModifier = this.gravityModifier;
  26404. dest.simulationSpace = this.simulationSpace;
  26405. dest.scaleMode = this.scaleMode;
  26406. dest.playOnAwake = this.playOnAwake;
  26407. dest.autoRandomSeed = this.autoRandomSeed;
  26408. dest.randomSeed[0] = this.randomSeed[0];
  26409. dest.maxParticles = this.maxParticles;
  26410. (this._emission) && (dest._emission = this._emission.clone());
  26411. (this.shape) && (dest.shape = this.shape.clone());
  26412. (this.velocityOverLifetime) && (dest.velocityOverLifetime = this.velocityOverLifetime.clone());
  26413. (this.colorOverLifetime) && (dest.colorOverLifetime = this.colorOverLifetime.clone());
  26414. (this.sizeOverLifetime) && (dest.sizeOverLifetime = this.sizeOverLifetime.clone());
  26415. (this.rotationOverLifetime) && (dest.rotationOverLifetime = this.rotationOverLifetime.clone());
  26416. (this.textureSheetAnimation) && (dest.textureSheetAnimation = this.textureSheetAnimation.clone());
  26417. dest.isPerformanceMode = this.isPerformanceMode;
  26418. dest._isEmitting = this._isEmitting;
  26419. dest._isPlaying = this._isPlaying;
  26420. dest._isPaused = this._isPaused;
  26421. dest._playStartDelay = this._playStartDelay;
  26422. dest._frameRateTime = this._frameRateTime;
  26423. dest._emissionTime = this._emissionTime;
  26424. dest._totalDelayTime = this._totalDelayTime;
  26425. dest._burstsIndex = this._burstsIndex;
  26426. }
  26427. clone() {
  26428. var dest = new ShurikenParticleSystem(null);
  26429. this.cloneTo(dest);
  26430. return dest;
  26431. }
  26432. }
  26433. ShurikenParticleSystem._RANDOMOFFSET = new Uint32Array([0x23571a3e, 0xc34f56fe, 0x13371337, 0x12460f3b, 0x6aed452e, 0xdec4aea1, 0x96aa4de3, 0x8d2c8431, 0xf3857f6f, 0xe0fbd834, 0x13740583, 0x591bc05c, 0x40eb95e4, 0xbc524e5f, 0xaf502044, 0xa614b381, 0x1034e524, 0xfc524e5f]);
  26434. ShurikenParticleSystem.halfKSqrtOf2 = 1.42 * 0.5;
  26435. ShurikenParticleSystem.g = 9.8;
  26436. ShurikenParticleSystem._maxElapsedTime = 1.0 / 3.0;
  26437. ShurikenParticleSystem._tempVector30 = new Vector3();
  26438. ShurikenParticleSystem._tempVector31 = new Vector3();
  26439. ShurikenParticleSystem._tempVector32 = new Vector3();
  26440. ShurikenParticleSystem._tempVector33 = new Vector3();
  26441. ShurikenParticleSystem._tempVector34 = new Vector3();
  26442. ShurikenParticleSystem._tempVector35 = new Vector3();
  26443. ShurikenParticleSystem._tempVector36 = new Vector3();
  26444. ShurikenParticleSystem._tempVector37 = new Vector3();
  26445. ShurikenParticleSystem._tempVector38 = new Vector3();
  26446. ShurikenParticleSystem._tempVector39 = new Vector3();
  26447. ShurikenParticleSystem._tempPosition = new Vector3();
  26448. ShurikenParticleSystem._tempDirection = new Vector3();
  26449. ShurikenParticleSystem._type = GeometryElement._typeCounter++;
  26450. class ShuriKenParticle3D extends RenderableSprite3D {
  26451. constructor() {
  26452. super(null);
  26453. this._render = new ShurikenParticleRenderer(this);
  26454. this._particleSystem = new ShurikenParticleSystem(this);
  26455. var elements = this._render._renderElements;
  26456. var element = elements[0] = new RenderElement();
  26457. element.setTransform(this._transform);
  26458. element.render = this._render;
  26459. element.setGeometry(this._particleSystem);
  26460. element.material = ShurikenParticleMaterial.defaultMaterial;
  26461. }
  26462. static __init__() {
  26463. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_BILLBOARD = Shader3D.getDefineByName("SPHERHBILLBOARD");
  26464. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_STRETCHEDBILLBOARD = Shader3D.getDefineByName("STRETCHEDBILLBOARD");
  26465. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_HORIZONTALBILLBOARD = Shader3D.getDefineByName("HORIZONTALBILLBOARD");
  26466. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_VERTICALBILLBOARD = Shader3D.getDefineByName("VERTICALBILLBOARD");
  26467. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_COLOROVERLIFETIME = Shader3D.getDefineByName("COLOROVERLIFETIME");
  26468. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RANDOMCOLOROVERLIFETIME = Shader3D.getDefineByName("RANDOMCOLOROVERLIFETIME");
  26469. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT = Shader3D.getDefineByName("VELOCITYOVERLIFETIMECONSTANT");
  26470. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE = Shader3D.getDefineByName("VELOCITYOVERLIFETIMECURVE");
  26471. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT = Shader3D.getDefineByName("VELOCITYOVERLIFETIMERANDOMCONSTANT");
  26472. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE = Shader3D.getDefineByName("VELOCITYOVERLIFETIMERANDOMCURVE");
  26473. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE = Shader3D.getDefineByName("TEXTURESHEETANIMATIONCURVE");
  26474. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE = Shader3D.getDefineByName("TEXTURESHEETANIMATIONRANDOMCURVE");
  26475. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIME = Shader3D.getDefineByName("ROTATIONOVERLIFETIME");
  26476. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE = Shader3D.getDefineByName("ROTATIONOVERLIFETIMESEPERATE");
  26477. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT = Shader3D.getDefineByName("ROTATIONOVERLIFETIMECONSTANT");
  26478. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE = Shader3D.getDefineByName("ROTATIONOVERLIFETIMECURVE");
  26479. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS = Shader3D.getDefineByName("ROTATIONOVERLIFETIMERANDOMCONSTANTS");
  26480. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES = Shader3D.getDefineByName("ROTATIONOVERLIFETIMERANDOMCURVES");
  26481. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVE = Shader3D.getDefineByName("SIZEOVERLIFETIMECURVE");
  26482. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE = Shader3D.getDefineByName("SIZEOVERLIFETIMECURVESEPERATE");
  26483. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES = Shader3D.getDefineByName("SIZEOVERLIFETIMERANDOMCURVES");
  26484. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE = Shader3D.getDefineByName("SIZEOVERLIFETIMERANDOMCURVESSEPERATE");
  26485. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_RENDERMODE_MESH = Shader3D.getDefineByName("RENDERMODE_MESH");
  26486. ShuriKenParticle3DShaderDeclaration.SHADERDEFINE_SHAPE = Shader3D.getDefineByName("SHAPE");
  26487. }
  26488. get particleSystem() {
  26489. return this._particleSystem;
  26490. }
  26491. get particleRenderer() {
  26492. return this._render;
  26493. }
  26494. _parseModule(module, moduleData) {
  26495. for (var t in moduleData) {
  26496. switch (t) {
  26497. case "bases":
  26498. var bases = moduleData.bases;
  26499. for (var k in bases)
  26500. module[k] = bases[k];
  26501. break;
  26502. case "vector2s":
  26503. var vector2s = moduleData.vector2s;
  26504. for (var k in vector2s) {
  26505. var vec2 = module[k];
  26506. var vec2Data = vector2s[k];
  26507. vec2.setValue(vec2Data[0], vec2Data[1]);
  26508. module[k] = vec2;
  26509. }
  26510. break;
  26511. case "vector3s":
  26512. var vector3s = moduleData.vector3s;
  26513. for (var k in vector3s) {
  26514. var vec3 = module[k];
  26515. var vec3Data = vector3s[k];
  26516. vec3.setValue(vec3Data[0], vec3Data[1], vec3Data[2]);
  26517. module[k] = vec3;
  26518. }
  26519. break;
  26520. case "vector4s":
  26521. var vector4s = moduleData.vector4s;
  26522. for (var k in vector4s) {
  26523. var vec4 = module[k];
  26524. var vec4Data = vector4s[k];
  26525. vec4.setValue(vec4Data[0], vec4Data[1], vec4Data[2], vec4Data[3]);
  26526. module[k] = vec4;
  26527. }
  26528. break;
  26529. case "gradientDataNumbers":
  26530. var gradientDataNumbers = moduleData.gradientDataNumbers;
  26531. for (var k in gradientDataNumbers) {
  26532. var gradientNumber = module[k];
  26533. var gradientNumberData = moduleData[k];
  26534. for (var i = 0, n = gradientNumberData.length; i < n; i++) {
  26535. var valueData = gradientNumberData[i];
  26536. gradientNumber.add(valueData.key, valueData.value);
  26537. }
  26538. module[k] = gradientNumber;
  26539. }
  26540. break;
  26541. case "resources":
  26542. var resources = moduleData.resources;
  26543. for (var k in resources)
  26544. module[k] = Laya.Loader.getRes(resources[k]);
  26545. break;
  26546. case "bursts":
  26547. var burstsData = moduleData.bursts;
  26548. for (var i = 0, n = burstsData.length; i < n; i++) {
  26549. var brust = burstsData[i];
  26550. module.addBurst(new Burst(brust.time, brust.min, brust.max));
  26551. }
  26552. break;
  26553. case "randomSeed":
  26554. module.randomSeed[0] = moduleData.randomSeed;
  26555. break;
  26556. case "shapeType":
  26557. case "type":
  26558. case "color":
  26559. case "size":
  26560. case "frame":
  26561. case "startFrame":
  26562. case "angularVelocity":
  26563. case "velocity":
  26564. break;
  26565. default:
  26566. throw "ShurikenParticle3D:unknown type.";
  26567. }
  26568. }
  26569. }
  26570. _parse(data, spriteMap) {
  26571. super._parse(data, spriteMap);
  26572. if (data.main) {
  26573. var particleSystem = this.particleSystem;
  26574. var particleRender = this.particleRenderer;
  26575. this._parseModule(particleRender, data.renderer);
  26576. this._parseModule(particleSystem, data.main);
  26577. this._parseModule(particleSystem.emission, data.emission);
  26578. var shapeData = data.shape;
  26579. if (shapeData) {
  26580. var shape;
  26581. switch (shapeData.shapeType) {
  26582. case 0:
  26583. shape = new SphereShape();
  26584. break;
  26585. case 1:
  26586. shape = new HemisphereShape();
  26587. break;
  26588. case 2:
  26589. shape = new ConeShape();
  26590. break;
  26591. case 3:
  26592. shape = new BoxShape();
  26593. break;
  26594. case 7:
  26595. shape = new CircleShape();
  26596. break;
  26597. default:
  26598. throw "ShuriKenParticle3D:unknown shape type.";
  26599. }
  26600. this._parseModule(shape, shapeData);
  26601. particleSystem.shape = shape;
  26602. }
  26603. var velocityOverLifetimeData = data.velocityOverLifetime;
  26604. if (velocityOverLifetimeData) {
  26605. var velocityData = velocityOverLifetimeData.velocity;
  26606. var velocity;
  26607. switch (velocityData.type) {
  26608. case 0:
  26609. var constantData = velocityData.constant;
  26610. velocity = GradientVelocity.createByConstant(constantData ? new Vector3(constantData[0], constantData[1], constantData[2]) : new Vector3(0, 0, 0));
  26611. break;
  26612. case 1:
  26613. velocity = GradientVelocity.createByGradient(this._initParticleVelocity(velocityData.gradientX), this._initParticleVelocity(velocityData.gradientY), this._initParticleVelocity(velocityData.gradientZ));
  26614. break;
  26615. case 2:
  26616. var constantMinData = velocityData.constantMin;
  26617. var constantMaxData = velocityData.constantMax;
  26618. velocity = GradientVelocity.createByRandomTwoConstant(constantMinData ? new Vector3(constantMinData[0], constantMinData[1], constantMinData[2]) : new Vector3(0, 0, 0), constantMaxData ? new Vector3(constantMaxData[0], constantMaxData[1], constantMaxData[2]) : new Vector3(0, 0, 0));
  26619. break;
  26620. case 3:
  26621. velocity = GradientVelocity.createByRandomTwoGradient(this._initParticleVelocity(velocityData.gradientXMin), this._initParticleVelocity(velocityData.gradientXMax), this._initParticleVelocity(velocityData.gradientYMin), this._initParticleVelocity(velocityData.gradientYMax), this._initParticleVelocity(velocityData.gradientZMin), this._initParticleVelocity(velocityData.gradientZMax));
  26622. break;
  26623. }
  26624. var velocityOverLifetime = new VelocityOverLifetime(velocity);
  26625. this._parseModule(velocityOverLifetime, velocityOverLifetimeData);
  26626. particleSystem.velocityOverLifetime = velocityOverLifetime;
  26627. }
  26628. var colorOverLifetimeData = data.colorOverLifetime;
  26629. if (colorOverLifetimeData) {
  26630. var colorData = colorOverLifetimeData.color;
  26631. var color;
  26632. switch (colorData.type) {
  26633. case 0:
  26634. var constColorData = colorData.constant;
  26635. color = GradientColor.createByConstant(constColorData ? new Vector4(constColorData[0], constColorData[1], constColorData[2], constColorData[3]) : new Vector4(0, 0, 0, 0));
  26636. break;
  26637. case 1:
  26638. color = GradientColor.createByGradient(this._initParticleColor(colorData.gradient));
  26639. break;
  26640. case 2:
  26641. var minConstColorData = colorData.constantMin;
  26642. var maxConstColorData = colorData.constantMax;
  26643. color = GradientColor.createByRandomTwoConstant(minConstColorData ? new Vector4(minConstColorData[0], minConstColorData[1], minConstColorData[2], minConstColorData[3]) : new Vector4(0, 0, 0, 0), minConstColorData ? new Vector4(maxConstColorData[0], maxConstColorData[1], maxConstColorData[2], maxConstColorData[3]) : new Vector4(0, 0, 0, 0));
  26644. break;
  26645. case 3:
  26646. color = GradientColor.createByRandomTwoGradient(this._initParticleColor(colorData.gradientMin), this._initParticleColor(colorData.gradientMax));
  26647. break;
  26648. }
  26649. var colorOverLifetime = new ColorOverLifetime(color);
  26650. this._parseModule(colorOverLifetime, colorOverLifetimeData);
  26651. particleSystem.colorOverLifetime = colorOverLifetime;
  26652. }
  26653. var sizeOverLifetimeData = data.sizeOverLifetime;
  26654. if (sizeOverLifetimeData) {
  26655. var sizeData = sizeOverLifetimeData.size;
  26656. var size;
  26657. switch (sizeData.type) {
  26658. case 0:
  26659. if (sizeData.separateAxes) {
  26660. size = GradientSize.createByGradientSeparate(this._initParticleSize(sizeData.gradientX), this._initParticleSize(sizeData.gradientY), this._initParticleSize(sizeData.gradientZ));
  26661. }
  26662. else {
  26663. size = GradientSize.createByGradient(this._initParticleSize(sizeData.gradient));
  26664. }
  26665. break;
  26666. case 1:
  26667. if (sizeData.separateAxes) {
  26668. var constantMinSeparateData = sizeData.constantMinSeparate;
  26669. var constantMaxSeparateData = sizeData.constantMaxSeparate;
  26670. size = GradientSize.createByRandomTwoConstantSeparate(constantMinSeparateData ? new Vector3(constantMinSeparateData[0], constantMinSeparateData[1], constantMinSeparateData[2]) : new Vector3(0, 0, 0), constantMaxSeparateData ? new Vector3(constantMaxSeparateData[0], constantMaxSeparateData[1], constantMaxSeparateData[2]) : new Vector3(0, 0, 0));
  26671. }
  26672. else {
  26673. size = GradientSize.createByRandomTwoConstant(sizeData.constantMin || 0, sizeData.constantMax || 0);
  26674. }
  26675. break;
  26676. case 2:
  26677. if (sizeData.separateAxes) {
  26678. size = GradientSize.createByRandomTwoGradientSeparate(this._initParticleSize(sizeData.gradientXMin), this._initParticleSize(sizeData.gradientYMin), this._initParticleSize(sizeData.gradientZMin), this._initParticleSize(sizeData.gradientXMax), this._initParticleSize(sizeData.gradientYMax), this._initParticleSize(sizeData.gradientZMax));
  26679. }
  26680. else {
  26681. size = GradientSize.createByRandomTwoGradient(this._initParticleSize(sizeData.gradientMin), this._initParticleSize(sizeData.gradientMax));
  26682. }
  26683. break;
  26684. }
  26685. var sizeOverLifetime = new SizeOverLifetime(size);
  26686. this._parseModule(sizeOverLifetime, sizeOverLifetimeData);
  26687. particleSystem.sizeOverLifetime = sizeOverLifetime;
  26688. }
  26689. var rotationOverLifetimeData = data.rotationOverLifetime;
  26690. if (rotationOverLifetimeData) {
  26691. var angularVelocityData = rotationOverLifetimeData.angularVelocity;
  26692. var angularVelocity;
  26693. switch (angularVelocityData.type) {
  26694. case 0:
  26695. if (angularVelocityData.separateAxes) {
  26696. var conSep = angularVelocityData.constantSeparate;
  26697. angularVelocity = GradientAngularVelocity.createByConstantSeparate(conSep ? new Vector3(conSep[0], conSep[1], conSep[2]) : new Vector3(0, 0, Math.PI / 4));
  26698. }
  26699. else {
  26700. angularVelocity = GradientAngularVelocity.createByConstant(angularVelocityData.constant || Math.PI / 4);
  26701. }
  26702. break;
  26703. case 1:
  26704. if (angularVelocityData.separateAxes) {
  26705. angularVelocity = GradientAngularVelocity.createByGradientSeparate(this._initParticleRotation(angularVelocityData.gradientX), this._initParticleRotation(angularVelocityData.gradientY), this._initParticleRotation(angularVelocityData.gradientZ));
  26706. }
  26707. else {
  26708. angularVelocity = GradientAngularVelocity.createByGradient(this._initParticleRotation(angularVelocityData.gradient));
  26709. }
  26710. break;
  26711. case 2:
  26712. if (angularVelocityData.separateAxes) {
  26713. var minSep = angularVelocityData.constantMinSeparate;
  26714. var maxSep = angularVelocityData.constantMaxSeparate;
  26715. angularVelocity = GradientAngularVelocity.createByRandomTwoConstantSeparate(minSep ? new Vector3(minSep[0], minSep[1], minSep[2]) : new Vector3(0, 0, 0), maxSep ? new Vector3(maxSep[0], maxSep[1], maxSep[2]) : new Vector3(0, 0, Math.PI / 4));
  26716. }
  26717. else {
  26718. angularVelocity = GradientAngularVelocity.createByRandomTwoConstant(angularVelocityData.constantMin || 0, angularVelocityData.constantMax || Math.PI / 4);
  26719. }
  26720. break;
  26721. case 3:
  26722. if (angularVelocityData.separateAxes) ;
  26723. else {
  26724. angularVelocity = GradientAngularVelocity.createByRandomTwoGradient(this._initParticleRotation(angularVelocityData.gradientMin), this._initParticleRotation(angularVelocityData.gradientMax));
  26725. }
  26726. break;
  26727. }
  26728. var rotationOverLifetime = new RotationOverLifetime(angularVelocity);
  26729. this._parseModule(rotationOverLifetime, rotationOverLifetimeData);
  26730. particleSystem.rotationOverLifetime = rotationOverLifetime;
  26731. }
  26732. var textureSheetAnimationData = data.textureSheetAnimation;
  26733. if (textureSheetAnimationData) {
  26734. var frameData = textureSheetAnimationData.frame;
  26735. var frameOverTime;
  26736. switch (frameData.type) {
  26737. case 0:
  26738. frameOverTime = FrameOverTime.createByConstant(frameData.constant);
  26739. break;
  26740. case 1:
  26741. frameOverTime = FrameOverTime.createByOverTime(this._initParticleFrame(frameData.overTime));
  26742. break;
  26743. case 2:
  26744. frameOverTime = FrameOverTime.createByRandomTwoConstant(frameData.constantMin, frameData.constantMax);
  26745. break;
  26746. case 3:
  26747. frameOverTime = FrameOverTime.createByRandomTwoOverTime(this._initParticleFrame(frameData.overTimeMin), this._initParticleFrame(frameData.overTimeMax));
  26748. break;
  26749. }
  26750. var startFrameData = textureSheetAnimationData.startFrame;
  26751. var startFrame;
  26752. switch (startFrameData.type) {
  26753. case 0:
  26754. startFrame = StartFrame.createByConstant(startFrameData.constant);
  26755. break;
  26756. case 1:
  26757. startFrame = StartFrame.createByRandomTwoConstant(startFrameData.constantMin, startFrameData.constantMax);
  26758. break;
  26759. }
  26760. var textureSheetAnimation = new TextureSheetAnimation(frameOverTime, startFrame);
  26761. this._parseModule(textureSheetAnimation, textureSheetAnimationData);
  26762. particleSystem.textureSheetAnimation = textureSheetAnimation;
  26763. }
  26764. }
  26765. else {
  26766. this._parseOld(data);
  26767. }
  26768. }
  26769. _activeHierarchy(activeChangeComponents) {
  26770. super._activeHierarchy(activeChangeComponents);
  26771. (this.particleSystem.playOnAwake) && (this.particleSystem.play());
  26772. }
  26773. _inActiveHierarchy(activeChangeComponents) {
  26774. super._inActiveHierarchy(activeChangeComponents);
  26775. (this.particleSystem.isAlive) && (this.particleSystem.simulate(0, true));
  26776. }
  26777. _cloneTo(destObject, srcSprite, dstSprite) {
  26778. var destShuriKenParticle3D = destObject;
  26779. var destParticleSystem = destShuriKenParticle3D._particleSystem;
  26780. this._particleSystem.cloneTo(destParticleSystem);
  26781. var destParticleRender = destShuriKenParticle3D._render;
  26782. var particleRender = this._render;
  26783. destParticleRender.sharedMaterials = particleRender.sharedMaterials;
  26784. destParticleRender.enable = particleRender.enable;
  26785. destParticleRender.renderMode = particleRender.renderMode;
  26786. destParticleRender.mesh = particleRender.mesh;
  26787. destParticleRender.stretchedBillboardCameraSpeedScale = particleRender.stretchedBillboardCameraSpeedScale;
  26788. destParticleRender.stretchedBillboardSpeedScale = particleRender.stretchedBillboardSpeedScale;
  26789. destParticleRender.stretchedBillboardLengthScale = particleRender.stretchedBillboardLengthScale;
  26790. destParticleRender.sortingFudge = particleRender.sortingFudge;
  26791. super._cloneTo(destObject, srcSprite, dstSprite);
  26792. }
  26793. destroy(destroyChild = true) {
  26794. if (this.destroyed)
  26795. return;
  26796. super.destroy(destroyChild);
  26797. this._particleSystem.destroy();
  26798. this._particleSystem = null;
  26799. }
  26800. _create() {
  26801. return new ShuriKenParticle3D();
  26802. }
  26803. _parseOld(data) {
  26804. const anglelToRad = Math.PI / 180.0;
  26805. var i, n;
  26806. var particleRender = this.particleRenderer;
  26807. var material;
  26808. var materialData = data.material;
  26809. (materialData) && (material = Laya.Loader.getRes(materialData.path));
  26810. particleRender.sharedMaterial = material;
  26811. var meshPath = data.meshPath;
  26812. (meshPath) && (particleRender.mesh = Laya.Loader.getRes(meshPath));
  26813. particleRender.renderMode = data.renderMode;
  26814. particleRender.stretchedBillboardCameraSpeedScale = data.stretchedBillboardCameraSpeedScale;
  26815. particleRender.stretchedBillboardSpeedScale = data.stretchedBillboardSpeedScale;
  26816. particleRender.stretchedBillboardLengthScale = data.stretchedBillboardLengthScale;
  26817. particleRender.sortingFudge = data.sortingFudge ? data.sortingFudge : 0.0;
  26818. var particleSystem = this.particleSystem;
  26819. particleSystem.isPerformanceMode = data.isPerformanceMode;
  26820. particleSystem.duration = data.duration;
  26821. particleSystem.looping = data.looping;
  26822. particleSystem.prewarm = data.prewarm;
  26823. particleSystem.startDelayType = data.startDelayType;
  26824. particleSystem.startDelay = data.startDelay;
  26825. particleSystem.startDelayMin = data.startDelayMin;
  26826. particleSystem.startDelayMax = data.startDelayMax;
  26827. particleSystem.startLifetimeType = data.startLifetimeType;
  26828. particleSystem.startLifetimeConstant = data.startLifetimeConstant;
  26829. particleSystem.startLifeTimeGradient = ShuriKenParticle3D._initStartLife(data.startLifetimeGradient);
  26830. particleSystem.startLifetimeConstantMin = data.startLifetimeConstantMin;
  26831. particleSystem.startLifetimeConstantMax = data.startLifetimeConstantMax;
  26832. particleSystem.startLifeTimeGradientMin = ShuriKenParticle3D._initStartLife(data.startLifetimeGradientMin);
  26833. particleSystem.startLifeTimeGradientMax = ShuriKenParticle3D._initStartLife(data.startLifetimeGradientMax);
  26834. particleSystem.startSpeedType = data.startSpeedType;
  26835. particleSystem.startSpeedConstant = data.startSpeedConstant;
  26836. particleSystem.startSpeedConstantMin = data.startSpeedConstantMin;
  26837. particleSystem.startSpeedConstantMax = data.startSpeedConstantMax;
  26838. particleSystem.threeDStartSize = data.threeDStartSize;
  26839. particleSystem.startSizeType = data.startSizeType;
  26840. particleSystem.startSizeConstant = data.startSizeConstant;
  26841. var startSizeConstantSeparateArray = data.startSizeConstantSeparate;
  26842. var startSizeConstantSeparateElement = particleSystem.startSizeConstantSeparate;
  26843. startSizeConstantSeparateElement.x = startSizeConstantSeparateArray[0];
  26844. startSizeConstantSeparateElement.y = startSizeConstantSeparateArray[1];
  26845. startSizeConstantSeparateElement.z = startSizeConstantSeparateArray[2];
  26846. particleSystem.startSizeConstantMin = data.startSizeConstantMin;
  26847. particleSystem.startSizeConstantMax = data.startSizeConstantMax;
  26848. var startSizeConstantMinSeparateArray = data.startSizeConstantMinSeparate;
  26849. var startSizeConstantMinSeparateElement = particleSystem.startSizeConstantMinSeparate;
  26850. startSizeConstantMinSeparateElement.x = startSizeConstantMinSeparateArray[0];
  26851. startSizeConstantMinSeparateElement.y = startSizeConstantMinSeparateArray[1];
  26852. startSizeConstantMinSeparateElement.z = startSizeConstantMinSeparateArray[2];
  26853. var startSizeConstantMaxSeparateArray = data.startSizeConstantMaxSeparate;
  26854. var startSizeConstantMaxSeparateElement = particleSystem.startSizeConstantMaxSeparate;
  26855. startSizeConstantMaxSeparateElement.x = startSizeConstantMaxSeparateArray[0];
  26856. startSizeConstantMaxSeparateElement.y = startSizeConstantMaxSeparateArray[1];
  26857. startSizeConstantMaxSeparateElement.z = startSizeConstantMaxSeparateArray[2];
  26858. particleSystem.threeDStartRotation = data.threeDStartRotation;
  26859. particleSystem.startRotationType = data.startRotationType;
  26860. particleSystem.startRotationConstant = data.startRotationConstant * anglelToRad;
  26861. var startRotationConstantSeparateArray = data.startRotationConstantSeparate;
  26862. var startRotationConstantSeparateElement = particleSystem.startRotationConstantSeparate;
  26863. startRotationConstantSeparateElement.x = startRotationConstantSeparateArray[0] * anglelToRad;
  26864. startRotationConstantSeparateElement.y = startRotationConstantSeparateArray[1] * anglelToRad;
  26865. startRotationConstantSeparateElement.z = startRotationConstantSeparateArray[2] * anglelToRad;
  26866. particleSystem.startRotationConstantMin = data.startRotationConstantMin * anglelToRad;
  26867. particleSystem.startRotationConstantMax = data.startRotationConstantMax * anglelToRad;
  26868. var startRotationConstantMinSeparateArray = data.startRotationConstantMinSeparate;
  26869. var startRotationConstantMinSeparateElement = particleSystem.startRotationConstantMinSeparate;
  26870. startRotationConstantMinSeparateElement.x = startRotationConstantMinSeparateArray[0] * anglelToRad;
  26871. startRotationConstantMinSeparateElement.y = startRotationConstantMinSeparateArray[1] * anglelToRad;
  26872. startRotationConstantMinSeparateElement.z = startRotationConstantMinSeparateArray[2] * anglelToRad;
  26873. var startRotationConstantMaxSeparateArray = data.startRotationConstantMaxSeparate;
  26874. var startRotationConstantMaxSeparateElement = particleSystem.startRotationConstantMaxSeparate;
  26875. startRotationConstantMaxSeparateElement.x = startRotationConstantMaxSeparateArray[0] * anglelToRad;
  26876. startRotationConstantMaxSeparateElement.y = startRotationConstantMaxSeparateArray[1] * anglelToRad;
  26877. startRotationConstantMaxSeparateElement.z = startRotationConstantMaxSeparateArray[2] * anglelToRad;
  26878. particleSystem.randomizeRotationDirection = data.randomizeRotationDirection;
  26879. particleSystem.startColorType = data.startColorType;
  26880. var startColorConstantArray = data.startColorConstant;
  26881. var startColorConstantElement = particleSystem.startColorConstant;
  26882. startColorConstantElement.x = startColorConstantArray[0];
  26883. startColorConstantElement.y = startColorConstantArray[1];
  26884. startColorConstantElement.z = startColorConstantArray[2];
  26885. startColorConstantElement.w = startColorConstantArray[3];
  26886. var startColorConstantMinArray = data.startColorConstantMin;
  26887. var startColorConstantMinElement = particleSystem.startColorConstantMin;
  26888. startColorConstantMinElement.x = startColorConstantMinArray[0];
  26889. startColorConstantMinElement.y = startColorConstantMinArray[1];
  26890. startColorConstantMinElement.z = startColorConstantMinArray[2];
  26891. startColorConstantMinElement.w = startColorConstantMinArray[3];
  26892. var startColorConstantMaxArray = data.startColorConstantMax;
  26893. var startColorConstantMaxElement = particleSystem.startColorConstantMax;
  26894. startColorConstantMaxElement.x = startColorConstantMaxArray[0];
  26895. startColorConstantMaxElement.y = startColorConstantMaxArray[1];
  26896. startColorConstantMaxElement.z = startColorConstantMaxArray[2];
  26897. startColorConstantMaxElement.w = startColorConstantMaxArray[3];
  26898. particleSystem.gravityModifier = data.gravityModifier;
  26899. particleSystem.simulationSpace = data.simulationSpace;
  26900. (data.simulationSpeed !== undefined) && (particleSystem.simulationSpeed = data.simulationSpeed);
  26901. particleSystem.scaleMode = data.scaleMode;
  26902. particleSystem.playOnAwake = data.playOnAwake;
  26903. particleSystem.maxParticles = data.maxParticles;
  26904. var autoRandomSeed = data.autoRandomSeed;
  26905. (autoRandomSeed != null) && (particleSystem.autoRandomSeed = autoRandomSeed);
  26906. var randomSeed = data.randomSeed;
  26907. (randomSeed != null) && (particleSystem.randomSeed[0] = randomSeed);
  26908. var emissionData = data.emission;
  26909. var emission = particleSystem.emission;
  26910. if (emissionData) {
  26911. emission.emissionRate = emissionData.emissionRate;
  26912. var burstsData = emissionData.bursts;
  26913. if (burstsData)
  26914. for (i = 0, n = burstsData.length; i < n; i++) {
  26915. var brust = burstsData[i];
  26916. emission.addBurst(new Burst(brust.time, brust.min, brust.max));
  26917. }
  26918. emission.enable = emissionData.enable;
  26919. }
  26920. else {
  26921. emission.enable = false;
  26922. }
  26923. var shapeData = data.shape;
  26924. if (shapeData) {
  26925. var shape;
  26926. switch (shapeData.shapeType) {
  26927. case 0:
  26928. var sphereShape;
  26929. shape = sphereShape = new SphereShape();
  26930. sphereShape.radius = shapeData.sphereRadius;
  26931. sphereShape.emitFromShell = shapeData.sphereEmitFromShell;
  26932. sphereShape.randomDirection = shapeData.sphereRandomDirection;
  26933. break;
  26934. case 1:
  26935. var hemiSphereShape;
  26936. shape = hemiSphereShape = new HemisphereShape();
  26937. hemiSphereShape.radius = shapeData.hemiSphereRadius;
  26938. hemiSphereShape.emitFromShell = shapeData.hemiSphereEmitFromShell;
  26939. hemiSphereShape.randomDirection = shapeData.hemiSphereRandomDirection;
  26940. break;
  26941. case 2:
  26942. var coneShape;
  26943. shape = coneShape = new ConeShape();
  26944. coneShape.angle = shapeData.coneAngle * anglelToRad;
  26945. coneShape.radius = shapeData.coneRadius;
  26946. coneShape.length = shapeData.coneLength;
  26947. coneShape.emitType = shapeData.coneEmitType;
  26948. coneShape.randomDirection = shapeData.coneRandomDirection;
  26949. break;
  26950. case 3:
  26951. var boxShape;
  26952. shape = boxShape = new BoxShape();
  26953. boxShape.x = shapeData.boxX;
  26954. boxShape.y = shapeData.boxY;
  26955. boxShape.z = shapeData.boxZ;
  26956. boxShape.randomDirection = shapeData.boxRandomDirection;
  26957. break;
  26958. case 7:
  26959. var circleShape;
  26960. shape = circleShape = new CircleShape();
  26961. circleShape.radius = shapeData.circleRadius;
  26962. circleShape.arc = shapeData.circleArc * anglelToRad;
  26963. circleShape.emitFromEdge = shapeData.circleEmitFromEdge;
  26964. circleShape.randomDirection = shapeData.circleRandomDirection;
  26965. break;
  26966. default:
  26967. var tempShape;
  26968. shape = tempShape = new CircleShape();
  26969. tempShape.radius = shapeData.circleRadius;
  26970. tempShape.arc = shapeData.circleArc * anglelToRad;
  26971. tempShape.emitFromEdge = shapeData.circleEmitFromEdge;
  26972. tempShape.randomDirection = shapeData.circleRandomDirection;
  26973. break;
  26974. }
  26975. shape.enable = shapeData.enable;
  26976. particleSystem.shape = shape;
  26977. }
  26978. var velocityOverLifetimeData = data.velocityOverLifetime;
  26979. if (velocityOverLifetimeData) {
  26980. var velocityData = velocityOverLifetimeData.velocity;
  26981. var velocity;
  26982. switch (velocityData.type) {
  26983. case 0:
  26984. var constantData = velocityData.constant;
  26985. velocity = GradientVelocity.createByConstant(new Vector3(constantData[0], constantData[1], constantData[2]));
  26986. break;
  26987. case 1:
  26988. velocity = GradientVelocity.createByGradient(this._initParticleVelocity(velocityData.gradientX), this._initParticleVelocity(velocityData.gradientY), this._initParticleVelocity(velocityData.gradientZ));
  26989. break;
  26990. case 2:
  26991. var constantMinData = velocityData.constantMin;
  26992. var constantMaxData = velocityData.constantMax;
  26993. velocity = GradientVelocity.createByRandomTwoConstant(new Vector3(constantMinData[0], constantMinData[1], constantMinData[2]), new Vector3(constantMaxData[0], constantMaxData[1], constantMaxData[2]));
  26994. break;
  26995. case 3:
  26996. velocity = GradientVelocity.createByRandomTwoGradient(this._initParticleVelocity(velocityData.gradientXMin), this._initParticleVelocity(velocityData.gradientXMax), this._initParticleVelocity(velocityData.gradientYMin), this._initParticleVelocity(velocityData.gradientYMax), this._initParticleVelocity(velocityData.gradientZMin), this._initParticleVelocity(velocityData.gradientZMax));
  26997. break;
  26998. }
  26999. var velocityOverLifetime = new VelocityOverLifetime(velocity);
  27000. velocityOverLifetime.space = velocityOverLifetimeData.space;
  27001. velocityOverLifetime.enable = velocityOverLifetimeData.enable;
  27002. particleSystem.velocityOverLifetime = velocityOverLifetime;
  27003. }
  27004. var colorOverLifetimeData = data.colorOverLifetime;
  27005. if (colorOverLifetimeData) {
  27006. var colorData = colorOverLifetimeData.color;
  27007. var color;
  27008. switch (colorData.type) {
  27009. case 0:
  27010. var constColorData = colorData.constant;
  27011. color = GradientColor.createByConstant(new Vector4(constColorData[0], constColorData[1], constColorData[2], constColorData[3]));
  27012. break;
  27013. case 1:
  27014. color = GradientColor.createByGradient(this._initParticleColor(colorData.gradient));
  27015. break;
  27016. case 2:
  27017. var minConstColorData = colorData.constantMin;
  27018. var maxConstColorData = colorData.constantMax;
  27019. color = GradientColor.createByRandomTwoConstant(new Vector4(minConstColorData[0], minConstColorData[1], minConstColorData[2], minConstColorData[3]), new Vector4(maxConstColorData[0], maxConstColorData[1], maxConstColorData[2], maxConstColorData[3]));
  27020. break;
  27021. case 3:
  27022. color = GradientColor.createByRandomTwoGradient(this._initParticleColor(colorData.gradientMin), this._initParticleColor(colorData.gradientMax));
  27023. break;
  27024. }
  27025. var colorOverLifetime = new ColorOverLifetime(color);
  27026. colorOverLifetime.enable = colorOverLifetimeData.enable;
  27027. particleSystem.colorOverLifetime = colorOverLifetime;
  27028. }
  27029. var sizeOverLifetimeData = data.sizeOverLifetime;
  27030. if (sizeOverLifetimeData) {
  27031. var sizeData = sizeOverLifetimeData.size;
  27032. var size;
  27033. switch (sizeData.type) {
  27034. case 0:
  27035. if (sizeData.separateAxes) {
  27036. size = GradientSize.createByGradientSeparate(this._initParticleSize(sizeData.gradientX), this._initParticleSize(sizeData.gradientY), this._initParticleSize(sizeData.gradientZ));
  27037. }
  27038. else {
  27039. size = GradientSize.createByGradient(this._initParticleSize(sizeData.gradient));
  27040. }
  27041. break;
  27042. case 1:
  27043. if (sizeData.separateAxes) {
  27044. var constantMinSeparateData = sizeData.constantMinSeparate;
  27045. var constantMaxSeparateData = sizeData.constantMaxSeparate;
  27046. size = GradientSize.createByRandomTwoConstantSeparate(new Vector3(constantMinSeparateData[0], constantMinSeparateData[1], constantMinSeparateData[2]), new Vector3(constantMaxSeparateData[0], constantMaxSeparateData[1], constantMaxSeparateData[2]));
  27047. }
  27048. else {
  27049. size = GradientSize.createByRandomTwoConstant(sizeData.constantMin, sizeData.constantMax);
  27050. }
  27051. break;
  27052. case 2:
  27053. if (sizeData.separateAxes) {
  27054. size = GradientSize.createByRandomTwoGradientSeparate(this._initParticleSize(sizeData.gradientXMin), this._initParticleSize(sizeData.gradientYMin), this._initParticleSize(sizeData.gradientZMin), this._initParticleSize(sizeData.gradientXMax), this._initParticleSize(sizeData.gradientYMax), this._initParticleSize(sizeData.gradientZMax));
  27055. }
  27056. else {
  27057. size = GradientSize.createByRandomTwoGradient(this._initParticleSize(sizeData.gradientMin), this._initParticleSize(sizeData.gradientMax));
  27058. }
  27059. break;
  27060. }
  27061. var sizeOverLifetime = new SizeOverLifetime(size);
  27062. sizeOverLifetime.enable = sizeOverLifetimeData.enable;
  27063. particleSystem.sizeOverLifetime = sizeOverLifetime;
  27064. }
  27065. var rotationOverLifetimeData = data.rotationOverLifetime;
  27066. if (rotationOverLifetimeData) {
  27067. var angularVelocityData = rotationOverLifetimeData.angularVelocity;
  27068. var angularVelocity;
  27069. switch (angularVelocityData.type) {
  27070. case 0:
  27071. if (angularVelocityData.separateAxes) {
  27072. var conSep = angularVelocityData.constantSeparate;
  27073. angularVelocity = GradientAngularVelocity.createByConstantSeparate(new Vector3(conSep[0] * anglelToRad, conSep[1] * anglelToRad, conSep[2] * anglelToRad));
  27074. }
  27075. else {
  27076. angularVelocity = GradientAngularVelocity.createByConstant(angularVelocityData.constant * anglelToRad);
  27077. }
  27078. break;
  27079. case 1:
  27080. if (angularVelocityData.separateAxes) {
  27081. angularVelocity = GradientAngularVelocity.createByGradientSeparate(this._initParticleRotation(angularVelocityData.gradientX), this._initParticleRotation(angularVelocityData.gradientY), this._initParticleRotation(angularVelocityData.gradientZ));
  27082. }
  27083. else {
  27084. angularVelocity = GradientAngularVelocity.createByGradient(this._initParticleRotation(angularVelocityData.gradient));
  27085. }
  27086. break;
  27087. case 2:
  27088. if (angularVelocityData.separateAxes) {
  27089. var minSep = angularVelocityData.constantMinSeparate;
  27090. var maxSep = angularVelocityData.constantMaxSeparate;
  27091. angularVelocity = GradientAngularVelocity.createByRandomTwoConstantSeparate(new Vector3(minSep[0] * anglelToRad, minSep[1] * anglelToRad, minSep[2] * anglelToRad), new Vector3(maxSep[0] * anglelToRad, maxSep[1] * anglelToRad, maxSep[2] * anglelToRad));
  27092. }
  27093. else {
  27094. angularVelocity = GradientAngularVelocity.createByRandomTwoConstant(angularVelocityData.constantMin * anglelToRad, angularVelocityData.constantMax * anglelToRad);
  27095. }
  27096. break;
  27097. case 3:
  27098. if (angularVelocityData.separateAxes) ;
  27099. else {
  27100. angularVelocity = GradientAngularVelocity.createByRandomTwoGradient(this._initParticleRotation(angularVelocityData.gradientMin), this._initParticleRotation(angularVelocityData.gradientMax));
  27101. }
  27102. break;
  27103. }
  27104. var rotationOverLifetime = new RotationOverLifetime(angularVelocity);
  27105. rotationOverLifetime.enable = rotationOverLifetimeData.enable;
  27106. particleSystem.rotationOverLifetime = rotationOverLifetime;
  27107. }
  27108. var textureSheetAnimationData = data.textureSheetAnimation;
  27109. if (textureSheetAnimationData) {
  27110. var frameData = textureSheetAnimationData.frame;
  27111. var frameOverTime;
  27112. switch (frameData.type) {
  27113. case 0:
  27114. frameOverTime = FrameOverTime.createByConstant(frameData.constant);
  27115. break;
  27116. case 1:
  27117. frameOverTime = FrameOverTime.createByOverTime(this._initParticleFrame(frameData.overTime));
  27118. break;
  27119. case 2:
  27120. frameOverTime = FrameOverTime.createByRandomTwoConstant(frameData.constantMin, frameData.constantMax);
  27121. break;
  27122. case 3:
  27123. frameOverTime = FrameOverTime.createByRandomTwoOverTime(this._initParticleFrame(frameData.overTimeMin), this._initParticleFrame(frameData.overTimeMax));
  27124. break;
  27125. }
  27126. var startFrameData = textureSheetAnimationData.startFrame;
  27127. var startFrame;
  27128. switch (startFrameData.type) {
  27129. case 0:
  27130. startFrame = StartFrame.createByConstant(startFrameData.constant);
  27131. break;
  27132. case 1:
  27133. startFrame = StartFrame.createByRandomTwoConstant(startFrameData.constantMin, startFrameData.constantMax);
  27134. break;
  27135. }
  27136. var textureSheetAnimation = new TextureSheetAnimation(frameOverTime, startFrame);
  27137. textureSheetAnimation.enable = textureSheetAnimationData.enable;
  27138. var tilesData = textureSheetAnimationData.tiles;
  27139. textureSheetAnimation.tiles = new Vector2(tilesData[0], tilesData[1]);
  27140. textureSheetAnimation.type = textureSheetAnimationData.type;
  27141. textureSheetAnimation.randomRow = textureSheetAnimationData.randomRow;
  27142. var rowIndex = textureSheetAnimationData.rowIndex;
  27143. (rowIndex !== undefined) && (textureSheetAnimation.rowIndex = rowIndex);
  27144. textureSheetAnimation.cycles = textureSheetAnimationData.cycles;
  27145. particleSystem.textureSheetAnimation = textureSheetAnimation;
  27146. }
  27147. }
  27148. _initParticleColor(gradientColorData) {
  27149. var gradientColor = new Gradient(4, 4);
  27150. if (!gradientColorData) {
  27151. gradientColor.addColorAlpha(0, 1);
  27152. gradientColor.addColorAlpha(1, 1);
  27153. gradientColor.addColorRGB(0, new Color(1.0, 1.0, 1.0, 1.0));
  27154. gradientColor.addColorRGB(1, new Color(1.0, 1.0, 1.0, 1.0));
  27155. }
  27156. else {
  27157. var alphasData = gradientColorData.alphas;
  27158. var i, n;
  27159. if (!alphasData) {
  27160. gradientColor.addColorAlpha(0, 1);
  27161. gradientColor.addColorAlpha(1, 1);
  27162. }
  27163. else {
  27164. for (i = 0, n = alphasData.length; i < n; i++) {
  27165. if (i == 3 && n > 4) {
  27166. i = n - 1;
  27167. console.warn("GradientDataColor warning:alpha data length is large than 4, will ignore the middle data.");
  27168. }
  27169. var alphaData = alphasData[i];
  27170. gradientColor.addColorAlpha(alphaData.key, alphaData.value);
  27171. }
  27172. }
  27173. var rgbsData = gradientColorData.rgbs;
  27174. if (!rgbsData) {
  27175. gradientColor.addColorRGB(0, new Color(1.0, 1.0, 1.0, 1.0));
  27176. gradientColor.addColorRGB(1, new Color(1.0, 1.0, 1.0, 1.0));
  27177. }
  27178. else {
  27179. for (i = 0, n = rgbsData.length; i < n; i++) {
  27180. if (i == 3 && n > 4) {
  27181. i = n - 1;
  27182. console.warn("GradientDataColor warning:rgb data length is large than 4, will ignore the middle data.");
  27183. }
  27184. var rgbData = rgbsData[i];
  27185. var rgbValue = rgbData.value;
  27186. gradientColor.addColorRGB(rgbData.key, new Color(rgbValue[0], rgbValue[1], rgbValue[2], 1.0));
  27187. }
  27188. }
  27189. }
  27190. return gradientColor;
  27191. }
  27192. _initParticleFrame(overTimeFramesData) {
  27193. var overTimeFrame = new GradientDataInt();
  27194. if (overTimeFramesData) {
  27195. var framesData = overTimeFramesData.frames;
  27196. for (var i = 0, n = framesData.length; i < n; i++) {
  27197. var frameData = framesData[i];
  27198. overTimeFrame.add(frameData.key, frameData.value);
  27199. }
  27200. }
  27201. else {
  27202. overTimeFrame.add(0, 0);
  27203. overTimeFrame.add(1, 1);
  27204. }
  27205. return overTimeFrame;
  27206. }
  27207. static _initStartLife(gradientData) {
  27208. var gradient = new GradientDataNumber();
  27209. var startLifetimesData = gradientData.startLifetimes;
  27210. for (var i = 0, n = startLifetimesData.length; i < n; i++) {
  27211. var valueData = startLifetimesData[i];
  27212. gradient.add(valueData.key, valueData.value);
  27213. }
  27214. return gradient;
  27215. }
  27216. _initParticleVelocity(gradientData) {
  27217. var gradient = new GradientDataNumber();
  27218. var velocitysData = gradientData.velocitys;
  27219. for (var i = 0, n = velocitysData.length; i < n; i++) {
  27220. var valueData = velocitysData[i];
  27221. gradient.add(valueData.key, valueData.value);
  27222. }
  27223. return gradient;
  27224. }
  27225. _initParticleSize(gradientSizeData) {
  27226. var gradientSize = new GradientDataNumber();
  27227. if (gradientSizeData) {
  27228. var sizesData = gradientSizeData.sizes;
  27229. for (var i = 0, n = sizesData.length; i < n; i++) {
  27230. var valueData = sizesData[i];
  27231. gradientSize.add(valueData.key, valueData.value);
  27232. }
  27233. }
  27234. else {
  27235. gradientSize.add(0, 0);
  27236. gradientSize.add(1, 1);
  27237. }
  27238. return gradientSize;
  27239. }
  27240. _initParticleRotation(gradientData) {
  27241. var gradient = new GradientDataNumber();
  27242. var angularVelocitysData = gradientData.angularVelocitys;
  27243. for (var i = 0, n = angularVelocitysData.length; i < n; i++) {
  27244. var valueData = angularVelocitysData[i];
  27245. gradient.add(valueData.key, valueData.value / 180.0 * Math.PI);
  27246. }
  27247. return gradient;
  27248. }
  27249. }
  27250. class SkinnedMeshSprite3DShaderDeclaration {
  27251. }
  27252. class SkinnedMeshRenderer extends MeshRenderer {
  27253. constructor(owner) {
  27254. super(owner);
  27255. this._bones = [];
  27256. this._skinnedDataLoopMarks = [];
  27257. this._localBounds = new Bounds(Vector3._ZERO, Vector3._ZERO);
  27258. this._cacheAnimationNode = [];
  27259. }
  27260. get localBounds() {
  27261. return this._localBounds;
  27262. }
  27263. set localBounds(value) {
  27264. this._localBounds = value;
  27265. }
  27266. get rootBone() {
  27267. return this._cacheRootBone;
  27268. }
  27269. set rootBone(value) {
  27270. if (this._cacheRootBone != value) {
  27271. if (this._cacheRootBone)
  27272. this._cacheRootBone.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  27273. else
  27274. this._owner.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  27275. if (value)
  27276. value.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  27277. else
  27278. this._owner.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  27279. this._cacheRootBone = value;
  27280. this._onWorldMatNeedChange(Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDSCALE);
  27281. }
  27282. }
  27283. get bones() {
  27284. return this._bones;
  27285. }
  27286. _computeSkinnedData() {
  27287. if (this._cacheMesh && this._cacheAvatar || this._cacheMesh && !this._cacheAvatar) {
  27288. var bindPoses = this._cacheMesh._inverseBindPoses;
  27289. var pathMarks = this._cacheMesh._skinnedMatrixCaches;
  27290. for (var i = 0, n = this._cacheMesh.subMeshCount; i < n; i++) {
  27291. var subMeshBoneIndices = this._cacheMesh.getSubMesh(i)._boneIndicesList;
  27292. var subData = this._skinnedData[i];
  27293. for (var j = 0, m = subMeshBoneIndices.length; j < m; j++) {
  27294. var boneIndices = subMeshBoneIndices[j];
  27295. this._computeSubSkinnedData(bindPoses, boneIndices, subData[j], pathMarks);
  27296. }
  27297. }
  27298. }
  27299. }
  27300. _computeSubSkinnedData(bindPoses, boneIndices, data, matrixCaches) {
  27301. for (var k = 0, q = boneIndices.length; k < q; k++) {
  27302. var index = boneIndices[k];
  27303. if (this._skinnedDataLoopMarks[index] === Laya.Stat.loopCount) {
  27304. var c = matrixCaches[index];
  27305. var preData = this._skinnedData[c.subMeshIndex][c.batchIndex];
  27306. var srcIndex = c.batchBoneIndex * 16;
  27307. var dstIndex = k * 16;
  27308. for (var d = 0; d < 16; d++)
  27309. data[dstIndex + d] = preData[srcIndex + d];
  27310. }
  27311. else {
  27312. if (!this._cacheAvatar) {
  27313. Utils3D._mulMatrixArray(this._bones[index].transform.worldMatrix.elements, bindPoses[index].elements, 0, data, k * 16);
  27314. }
  27315. else {
  27316. Utils3D._mulMatrixArray(this._cacheAnimationNode[index].transform.getWorldMatrix(), bindPoses[index].elements, 0, data, k * 16);
  27317. }
  27318. this._skinnedDataLoopMarks[index] = Laya.Stat.loopCount;
  27319. }
  27320. }
  27321. }
  27322. _onWorldMatNeedChange(flag) {
  27323. this._boundsChange = true;
  27324. if (this._octreeNode) {
  27325. if (this._cacheAvatar) {
  27326. if (this._indexInOctreeMotionList === -1)
  27327. this._octreeNode._octree.addMotionObject(this);
  27328. }
  27329. else {
  27330. flag &= Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDSCALE;
  27331. if (flag) {
  27332. if (this._indexInOctreeMotionList === -1)
  27333. this._octreeNode._octree.addMotionObject(this);
  27334. }
  27335. }
  27336. }
  27337. }
  27338. _createRenderElement() {
  27339. return new RenderElement();
  27340. }
  27341. _onMeshChange(value) {
  27342. super._onMeshChange(value);
  27343. this._cacheMesh = value;
  27344. var subMeshCount = value.subMeshCount;
  27345. this._skinnedData = [];
  27346. this._skinnedDataLoopMarks.length = value._inverseBindPoses.length;
  27347. for (var i = 0; i < subMeshCount; i++) {
  27348. var subBoneIndices = value.getSubMesh(i)._boneIndicesList;
  27349. var subCount = subBoneIndices.length;
  27350. var subData = this._skinnedData[i] = [];
  27351. for (var j = 0; j < subCount; j++)
  27352. subData[j] = new Float32Array(subBoneIndices[j].length * 16);
  27353. }
  27354. (this._cacheAvatar && value) && (this._getCacheAnimationNodes());
  27355. }
  27356. _setCacheAnimator(animator) {
  27357. this._cacheAnimator = animator;
  27358. this._shaderValues.addDefine(SkinnedMeshSprite3DShaderDeclaration.SHADERDEFINE_BONE);
  27359. this._setRootNode();
  27360. }
  27361. _calculateBoundingBox() {
  27362. if (!this._cacheAvatar) {
  27363. if (this._cacheRootBone)
  27364. this._localBounds._tranform(this._cacheRootBone.transform.worldMatrix, this._bounds);
  27365. else
  27366. this._localBounds._tranform(this._owner.transform.worldMatrix, this._bounds);
  27367. }
  27368. else {
  27369. if (this._cacheAnimator && this._rootBone) {
  27370. var worldMat = SkinnedMeshRenderer._tempMatrix4x4;
  27371. Utils3D.matrix4x4MultiplyMFM(this._cacheAnimator.owner.transform.worldMatrix, this._cacheRootAnimationNode.transform.getWorldMatrix(), worldMat);
  27372. this._localBounds._tranform(worldMat, this._bounds);
  27373. }
  27374. else {
  27375. super._calculateBoundingBox();
  27376. }
  27377. }
  27378. }
  27379. _renderUpdate(context, transform) {
  27380. if (this._cacheAnimator) {
  27381. this._computeSkinnedData();
  27382. if (!this._cacheAvatar) {
  27383. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, Matrix4x4.DEFAULT);
  27384. }
  27385. else {
  27386. var aniOwnerTrans = this._cacheAnimator.owner._transform;
  27387. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, aniOwnerTrans.worldMatrix);
  27388. }
  27389. }
  27390. else {
  27391. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, transform.worldMatrix);
  27392. }
  27393. if (!this._probReflection)
  27394. return;
  27395. if (this._reflectionMode == exports.ReflectionProbeMode.off) {
  27396. this._shaderValues.removeDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_SPECCUBE_BOX_PROJECTION);
  27397. this._shaderValues.setVector(RenderableSprite3D.REFLECTIONCUBE_HDR_PARAMS, ReflectionProbe.defaultTextureHDRDecodeValues);
  27398. this._shaderValues.setTexture(RenderableSprite3D.REFLECTIONTEXTURE, TextureCube.blackTexture);
  27399. }
  27400. else {
  27401. if (!this._probReflection.boxProjection) {
  27402. this._shaderValues.removeDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_SPECCUBE_BOX_PROJECTION);
  27403. }
  27404. else {
  27405. this._shaderValues.addDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_SPECCUBE_BOX_PROJECTION);
  27406. this._shaderValues.setVector3(RenderableSprite3D.REFLECTIONCUBE_PROBEPOSITION, this._probReflection.probePosition);
  27407. this._shaderValues.setVector3(RenderableSprite3D.REFLECTIONCUBE_PROBEBOXMAX, this._probReflection.boundsMax);
  27408. this._shaderValues.setVector3(RenderableSprite3D.REFLECTIONCUBE_PROBEBOXMIN, this._probReflection.boundsMin);
  27409. }
  27410. this._shaderValues.setTexture(RenderableSprite3D.REFLECTIONTEXTURE, this._probReflection.reflectionTexture);
  27411. this._shaderValues.setVector(RenderableSprite3D.REFLECTIONCUBE_HDR_PARAMS, this._probReflection.reflectionHDRParams);
  27412. }
  27413. }
  27414. _renderUpdateWithCamera(context, transform) {
  27415. var projectionView = context.projectionViewMatrix;
  27416. if (this._cacheAnimator) {
  27417. if (!this._cacheAvatar) {
  27418. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, projectionView);
  27419. }
  27420. else {
  27421. var aniOwnerTrans = this._cacheAnimator.owner._transform;
  27422. Matrix4x4.multiply(projectionView, aniOwnerTrans.worldMatrix, this._projectionViewWorldMatrix);
  27423. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, this._projectionViewWorldMatrix);
  27424. }
  27425. }
  27426. else {
  27427. Matrix4x4.multiply(projectionView, transform.worldMatrix, this._projectionViewWorldMatrix);
  27428. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, this._projectionViewWorldMatrix);
  27429. }
  27430. }
  27431. _destroy() {
  27432. super._destroy();
  27433. if (!this._cacheAvatar) {
  27434. if (this._cacheRootBone)
  27435. (!this._cacheRootBone.destroyed) && (this._cacheRootBone.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange));
  27436. else
  27437. (this._owner && !this._owner.destroyed) && (this._owner.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange));
  27438. }
  27439. else {
  27440. if (this._cacheRootAnimationNode)
  27441. this._cacheRootAnimationNode.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  27442. }
  27443. }
  27444. get bounds() {
  27445. if (this._boundsChange || this._cacheAvatar) {
  27446. this._calculateBoundingBox();
  27447. this._boundsChange = false;
  27448. }
  27449. return this._bounds;
  27450. }
  27451. _setRootBone(name) {
  27452. this._rootBone = name;
  27453. this._setRootNode();
  27454. }
  27455. _setRootNode() {
  27456. var rootNode;
  27457. if (this._cacheAnimator && this._rootBone && this._cacheAvatar)
  27458. rootNode = this._cacheAnimator._avatarNodeMap[this._rootBone];
  27459. else
  27460. rootNode = null;
  27461. if (this._cacheRootAnimationNode != rootNode) {
  27462. this._onWorldMatNeedChange(Transform3D.TRANSFORM_WORLDPOSITION | Transform3D.TRANSFORM_WORLDQUATERNION | Transform3D.TRANSFORM_WORLDSCALE);
  27463. this._owner.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  27464. if (this._cacheRootAnimationNode)
  27465. this._cacheRootAnimationNode.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange);
  27466. (rootNode) && (rootNode.transform.on(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange));
  27467. this._cacheRootAnimationNode = rootNode;
  27468. }
  27469. }
  27470. _getCacheAnimationNodes() {
  27471. var meshBoneNames = this._cacheMesh._boneNames;
  27472. var innerBindPoseCount = this._cacheMesh._inverseBindPoses.length;
  27473. this._cacheAnimationNode.length = innerBindPoseCount;
  27474. var nodeMap = this._cacheAnimator._avatarNodeMap;
  27475. for (var i = 0; i < innerBindPoseCount; i++) {
  27476. var node = nodeMap[meshBoneNames[i]];
  27477. this._cacheAnimationNode[i] = node;
  27478. }
  27479. }
  27480. _setCacheAvatar(value) {
  27481. if (this._cacheAvatar !== value) {
  27482. if (this._cacheMesh) {
  27483. this._cacheAvatar = value;
  27484. if (value) {
  27485. this._shaderValues.addDefine(SkinnedMeshSprite3DShaderDeclaration.SHADERDEFINE_BONE);
  27486. this._getCacheAnimationNodes();
  27487. }
  27488. }
  27489. else {
  27490. this._cacheAvatar = value;
  27491. }
  27492. this._setRootNode();
  27493. }
  27494. }
  27495. _computeSubSkinnedDataNative(worldMatrixs, cacheAnimationNodeIndices, inverseBindPosesBuffer, boneIndices, data) {
  27496. Laya.LayaGL.instance.computeSubSkinnedData(worldMatrixs, cacheAnimationNodeIndices, inverseBindPosesBuffer, boneIndices, data);
  27497. }
  27498. _computeSkinnedDataForNative() {
  27499. if (this._cacheMesh && this._cacheAvatar || this._cacheMesh && !this._cacheAvatar) {
  27500. var bindPoses = this._cacheMesh._inverseBindPoses;
  27501. var pathMarks = this._cacheMesh._skinnedMatrixCaches;
  27502. for (var i = 0, n = this._cacheMesh.subMeshCount; i < n; i++) {
  27503. var subMeshBoneIndices = this._cacheMesh.getSubMesh(i)._boneIndicesList;
  27504. var subData = this._skinnedData[i];
  27505. for (var j = 0, m = subMeshBoneIndices.length; j < m; j++) {
  27506. var boneIndices = subMeshBoneIndices[j];
  27507. this._computeSubSkinnedData(bindPoses, boneIndices, subData[j], pathMarks);
  27508. }
  27509. }
  27510. }
  27511. }
  27512. }
  27513. SkinnedMeshRenderer._tempMatrix4x4 = new Matrix4x4();
  27514. class SkinnedMeshSprite3D extends RenderableSprite3D {
  27515. constructor(mesh = null, name = null) {
  27516. super(name);
  27517. this._meshFilter = new MeshFilter(this);
  27518. this._render = new SkinnedMeshRenderer(this);
  27519. (mesh) && (this._meshFilter.sharedMesh = mesh);
  27520. }
  27521. static __init__() {
  27522. SkinnedMeshSprite3DShaderDeclaration.SHADERDEFINE_BONE = Shader3D.getDefineByName("BONE");
  27523. SkinnedMeshSprite3DShaderDeclaration.SHADERDEFINE_SIMPLEBONE = Shader3D.getDefineByName("SIMPLEBONE");
  27524. }
  27525. get meshFilter() {
  27526. return this._meshFilter;
  27527. }
  27528. get skinnedMeshRenderer() {
  27529. return this._render;
  27530. }
  27531. _parse(data, spriteMap) {
  27532. super._parse(data, spriteMap);
  27533. var render = this.skinnedMeshRenderer;
  27534. var lightmapIndex = data.lightmapIndex;
  27535. (lightmapIndex != null) && (render.lightmapIndex = lightmapIndex);
  27536. var lightmapScaleOffsetArray = data.lightmapScaleOffset;
  27537. (lightmapScaleOffsetArray) && (render.lightmapScaleOffset = new Vector4(lightmapScaleOffsetArray[0], lightmapScaleOffsetArray[1], lightmapScaleOffsetArray[2], lightmapScaleOffsetArray[3]));
  27538. (data.enableRender != undefined) && (render.enable = data.enableRender);
  27539. (data.receiveShadows != undefined) && (render.receiveShadow = data.receiveShadows);
  27540. (data.castShadow != undefined) && (render.castShadow = data.castShadow);
  27541. var meshPath;
  27542. meshPath = data.meshPath;
  27543. if (meshPath) {
  27544. var mesh = Laya.Loader.getRes(meshPath);
  27545. (mesh) && (this.meshFilter.sharedMesh = mesh);
  27546. }
  27547. var materials = data.materials;
  27548. if (materials) {
  27549. var sharedMaterials = render.sharedMaterials;
  27550. var materialCount = materials.length;
  27551. sharedMaterials.length = materialCount;
  27552. for (var i = 0; i < materialCount; i++) {
  27553. sharedMaterials[i] = Laya.Loader.getRes(materials[i].path);
  27554. }
  27555. render.sharedMaterials = sharedMaterials;
  27556. }
  27557. var boundBox = data.boundBox;
  27558. var min = boundBox.min;
  27559. var max = boundBox.max;
  27560. render.localBounds.setMin(new Vector3(min[0], min[1], min[2]));
  27561. render.localBounds.setMax(new Vector3(max[0], max[1], max[2]));
  27562. if (spriteMap) {
  27563. var rootBoneData = data.rootBone;
  27564. render.rootBone = spriteMap[rootBoneData];
  27565. var bonesData = data.bones;
  27566. var n;
  27567. for (i = 0, n = bonesData.length; i < n; i++)
  27568. render.bones.push(spriteMap[bonesData[i]]);
  27569. }
  27570. else {
  27571. (data.rootBone) && (render._setRootBone(data.rootBone));
  27572. }
  27573. }
  27574. _changeHierarchyAnimator(animator) {
  27575. super._changeHierarchyAnimator(animator);
  27576. this.skinnedMeshRenderer._setCacheAnimator(animator);
  27577. }
  27578. _changeAnimatorAvatar(avatar) {
  27579. this.skinnedMeshRenderer._setCacheAvatar(avatar);
  27580. }
  27581. _cloneTo(destObject, srcRoot, dstRoot) {
  27582. var meshSprite3D = destObject;
  27583. meshSprite3D.meshFilter.sharedMesh = this.meshFilter.sharedMesh;
  27584. var meshRender = this._render;
  27585. var destMeshRender = meshSprite3D._render;
  27586. destMeshRender.enable = meshRender.enable;
  27587. destMeshRender.sharedMaterials = meshRender.sharedMaterials;
  27588. destMeshRender.castShadow = meshRender.castShadow;
  27589. var lightmapScaleOffset = meshRender.lightmapScaleOffset;
  27590. lightmapScaleOffset && (destMeshRender.lightmapScaleOffset = lightmapScaleOffset.clone());
  27591. destMeshRender.receiveShadow = meshRender.receiveShadow;
  27592. destMeshRender.sortingFudge = meshRender.sortingFudge;
  27593. destMeshRender._rootBone = meshRender._rootBone;
  27594. var bones = meshRender.bones;
  27595. var destBones = destMeshRender.bones;
  27596. var bonesCount = bones.length;
  27597. destBones.length = bonesCount;
  27598. var rootBone = meshRender.rootBone;
  27599. if (rootBone) {
  27600. var pathes = Utils3D._getHierarchyPath(srcRoot, rootBone, SkinnedMeshSprite3D._tempArray0);
  27601. if (pathes)
  27602. destMeshRender.rootBone = Utils3D._getNodeByHierarchyPath(dstRoot, pathes);
  27603. else
  27604. destMeshRender.rootBone = rootBone;
  27605. }
  27606. for (var i = 0; i < bones.length; i++) {
  27607. pathes = Utils3D._getHierarchyPath(srcRoot, bones[i], SkinnedMeshSprite3D._tempArray0);
  27608. if (pathes)
  27609. destBones[i] = Utils3D._getNodeByHierarchyPath(dstRoot, pathes);
  27610. else
  27611. destBones[i] = bones[i];
  27612. }
  27613. var lbb = meshRender.localBounds;
  27614. (lbb) && (lbb.cloneTo(destMeshRender.localBounds));
  27615. super._cloneTo(destObject, srcRoot, dstRoot);
  27616. }
  27617. destroy(destroyChild = true) {
  27618. if (this.destroyed)
  27619. return;
  27620. super.destroy(destroyChild);
  27621. this._meshFilter.destroy();
  27622. }
  27623. _create() {
  27624. return new SkinnedMeshSprite3D();
  27625. }
  27626. }
  27627. SkinnedMeshSprite3D._tempArray0 = [];
  27628. SkinnedMeshSprite3D.BONES = Shader3D.propertyNameToID("u_Bones");
  27629. SkinnedMeshSprite3D.SIMPLE_SIMPLEANIMATORTEXTURE = Shader3D.propertyNameToID("u_SimpleAnimatorTexture");
  27630. SkinnedMeshSprite3D.SIMPLE_SIMPLEANIMATORPARAMS = Shader3D.propertyNameToID("u_SimpleAnimatorParams");
  27631. SkinnedMeshSprite3D.SIMPLE_SIMPLEANIMATORTEXTURESIZE = Shader3D.propertyNameToID("u_SimpleAnimatorTextureSize");
  27632. class TrailMaterial extends Material {
  27633. constructor() {
  27634. super();
  27635. this.setShaderName("Trail");
  27636. this._color = new Vector4(1.0, 1.0, 1.0, 1.0);
  27637. this._shaderValues.setVector(TrailMaterial.TINTCOLOR, new Vector4(1.0, 1.0, 1.0, 1.0));
  27638. this.renderMode = TrailMaterial.RENDERMODE_ALPHABLENDED;
  27639. }
  27640. static __initDefine__() {
  27641. TrailMaterial.SHADERDEFINE_MAINTEXTURE = Shader3D.getDefineByName("MAINTEXTURE");
  27642. TrailMaterial.SHADERDEFINE_TILINGOFFSET = Shader3D.getDefineByName("TILINGOFFSET");
  27643. TrailMaterial.SHADERDEFINE_ADDTIVEFOG = Shader3D.getDefineByName("ADDTIVEFOG");
  27644. }
  27645. get _TintColorR() {
  27646. return this._color.x;
  27647. }
  27648. set _TintColorR(value) {
  27649. this._color.x = value;
  27650. this.color = this._color;
  27651. }
  27652. get _TintColorG() {
  27653. return this._color.y;
  27654. }
  27655. set _TintColorG(value) {
  27656. this._color.y = value;
  27657. this.color = this._color;
  27658. }
  27659. get _TintColorB() {
  27660. return this._color.z;
  27661. }
  27662. set _TintColorB(value) {
  27663. this._color.z = value;
  27664. this.color = this._color;
  27665. }
  27666. get _TintColorA() {
  27667. return this._color.w;
  27668. }
  27669. set _TintColorA(value) {
  27670. this._color.w = value;
  27671. this.color = this._color;
  27672. }
  27673. get _MainTex_STX() {
  27674. return this._shaderValues.getVector(TrailMaterial.TILINGOFFSET).x;
  27675. }
  27676. set _MainTex_STX(x) {
  27677. var tilOff = this._shaderValues.getVector(TrailMaterial.TILINGOFFSET);
  27678. tilOff.x = x;
  27679. this.tilingOffset = tilOff;
  27680. }
  27681. get _MainTex_STY() {
  27682. return this._shaderValues.getVector(TrailMaterial.TILINGOFFSET).y;
  27683. }
  27684. set _MainTex_STY(y) {
  27685. var tilOff = this._shaderValues.getVector(TrailMaterial.TILINGOFFSET);
  27686. tilOff.y = y;
  27687. this.tilingOffset = tilOff;
  27688. }
  27689. get _MainTex_STZ() {
  27690. return this._shaderValues.getVector(TrailMaterial.TILINGOFFSET).z;
  27691. }
  27692. set _MainTex_STZ(z) {
  27693. var tilOff = this._shaderValues.getVector(TrailMaterial.TILINGOFFSET);
  27694. tilOff.z = z;
  27695. this.tilingOffset = tilOff;
  27696. }
  27697. get _MainTex_STW() {
  27698. return this._shaderValues.getVector(TrailMaterial.TILINGOFFSET).w;
  27699. }
  27700. set _MainTex_STW(w) {
  27701. var tilOff = this._shaderValues.getVector(TrailMaterial.TILINGOFFSET);
  27702. tilOff.w = w;
  27703. this.tilingOffset = tilOff;
  27704. }
  27705. set renderMode(value) {
  27706. switch (value) {
  27707. case TrailMaterial.RENDERMODE_ADDTIVE:
  27708. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  27709. this.alphaTest = false;
  27710. this.depthWrite = false;
  27711. this.cull = RenderState.CULL_NONE;
  27712. this.blend = RenderState.BLEND_ENABLE_ALL;
  27713. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  27714. this.blendDst = RenderState.BLENDPARAM_ONE;
  27715. this.depthTest = RenderState.DEPTHTEST_LESS;
  27716. this._shaderValues.addDefine(TrailMaterial.SHADERDEFINE_ADDTIVEFOG);
  27717. break;
  27718. case TrailMaterial.RENDERMODE_ALPHABLENDED:
  27719. this.renderQueue = Material.RENDERQUEUE_TRANSPARENT;
  27720. this.alphaTest = false;
  27721. this.depthWrite = false;
  27722. this.cull = RenderState.CULL_NONE;
  27723. this.blend = RenderState.BLEND_ENABLE_ALL;
  27724. this.blendSrc = RenderState.BLENDPARAM_SRC_ALPHA;
  27725. this.blendDst = RenderState.BLENDPARAM_ONE_MINUS_SRC_ALPHA;
  27726. this.depthTest = RenderState.DEPTHTEST_LESS;
  27727. this._shaderValues.removeDefine(TrailMaterial.SHADERDEFINE_ADDTIVEFOG);
  27728. break;
  27729. default:
  27730. throw new Error("TrailMaterial : renderMode value error.");
  27731. }
  27732. }
  27733. get colorR() {
  27734. return this._TintColorR;
  27735. }
  27736. set colorR(value) {
  27737. this._TintColorR = value;
  27738. }
  27739. get colorG() {
  27740. return this._TintColorG;
  27741. }
  27742. set colorG(value) {
  27743. this._TintColorG = value;
  27744. }
  27745. get colorB() {
  27746. return this._TintColorB;
  27747. }
  27748. set colorB(value) {
  27749. this._TintColorB = value;
  27750. }
  27751. get colorA() {
  27752. return this._TintColorA;
  27753. }
  27754. set colorA(value) {
  27755. this._TintColorA = value;
  27756. }
  27757. get color() {
  27758. return this._shaderValues.getVector(TrailMaterial.TINTCOLOR);
  27759. }
  27760. set color(value) {
  27761. this._shaderValues.setVector(TrailMaterial.TINTCOLOR, value);
  27762. }
  27763. get texture() {
  27764. return this._shaderValues.getTexture(TrailMaterial.MAINTEXTURE);
  27765. }
  27766. set texture(value) {
  27767. if (value)
  27768. this._shaderValues.addDefine(TrailMaterial.SHADERDEFINE_MAINTEXTURE);
  27769. else
  27770. this._shaderValues.removeDefine(TrailMaterial.SHADERDEFINE_MAINTEXTURE);
  27771. this._shaderValues.setTexture(TrailMaterial.MAINTEXTURE, value);
  27772. }
  27773. get tilingOffsetX() {
  27774. return this._MainTex_STX;
  27775. }
  27776. set tilingOffsetX(x) {
  27777. this._MainTex_STX = x;
  27778. }
  27779. get tilingOffsetY() {
  27780. return this._MainTex_STY;
  27781. }
  27782. set tilingOffsetY(y) {
  27783. this._MainTex_STY = y;
  27784. }
  27785. get tilingOffsetZ() {
  27786. return this._MainTex_STZ;
  27787. }
  27788. set tilingOffsetZ(z) {
  27789. this._MainTex_STZ = z;
  27790. }
  27791. get tilingOffsetW() {
  27792. return this._MainTex_STW;
  27793. }
  27794. set tilingOffsetW(w) {
  27795. this._MainTex_STW = w;
  27796. }
  27797. get tilingOffset() {
  27798. return this._shaderValues.getVector(TrailMaterial.TILINGOFFSET);
  27799. }
  27800. set tilingOffset(value) {
  27801. if (value) {
  27802. if (value.x != 1 || value.y != 1 || value.z != 0 || value.w != 0)
  27803. this._shaderValues.addDefine(TrailMaterial.SHADERDEFINE_TILINGOFFSET);
  27804. else
  27805. this._shaderValues.removeDefine(TrailMaterial.SHADERDEFINE_TILINGOFFSET);
  27806. }
  27807. else {
  27808. this._shaderValues.removeDefine(TrailMaterial.SHADERDEFINE_TILINGOFFSET);
  27809. }
  27810. this._shaderValues.setVector(TrailMaterial.TILINGOFFSET, value);
  27811. }
  27812. clone() {
  27813. var dest = new TrailMaterial();
  27814. this.cloneTo(dest);
  27815. return dest;
  27816. }
  27817. }
  27818. TrailMaterial.RENDERMODE_ALPHABLENDED = 0;
  27819. TrailMaterial.RENDERMODE_ADDTIVE = 1;
  27820. TrailMaterial.MAINTEXTURE = Shader3D.propertyNameToID("u_MainTexture");
  27821. TrailMaterial.TINTCOLOR = Shader3D.propertyNameToID("u_MainColor");
  27822. TrailMaterial.TILINGOFFSET = Shader3D.propertyNameToID("u_TilingOffset");
  27823. class TextureMode {
  27824. }
  27825. TextureMode.Stretch = 0;
  27826. TextureMode.Tile = 1;
  27827. (function (TrailAlignment) {
  27828. TrailAlignment[TrailAlignment["View"] = 0] = "View";
  27829. TrailAlignment[TrailAlignment["TransformZ"] = 1] = "TransformZ";
  27830. })(exports.TrailAlignment || (exports.TrailAlignment = {}));
  27831. class VertexTrail {
  27832. static get vertexDeclaration1() {
  27833. return VertexTrail._vertexDeclaration1;
  27834. }
  27835. static get vertexDeclaration2() {
  27836. return VertexTrail._vertexDeclaration2;
  27837. }
  27838. get vertexDeclaration() {
  27839. return VertexTrail._vertexDeclaration1;
  27840. }
  27841. static __init__() {
  27842. VertexTrail._vertexDeclaration1 = new VertexDeclaration(32, [new VertexElement(0, VertexElementFormat.Vector3, VertexTrail.TRAIL_POSITION0),
  27843. new VertexElement(12, VertexElementFormat.Vector3, VertexTrail.TRAIL_OFFSETVECTOR),
  27844. new VertexElement(24, VertexElementFormat.Single, VertexTrail.TRAIL_TIME0),
  27845. new VertexElement(28, VertexElementFormat.Single, VertexTrail.TRAIL_TEXTURECOORDINATE0Y)]);
  27846. VertexTrail._vertexDeclaration2 = new VertexDeclaration(20, [new VertexElement(0, VertexElementFormat.Single, VertexTrail.TRAIL_TEXTURECOORDINATE0X),
  27847. new VertexElement(4, VertexElementFormat.Color, VertexTrail.TRAIL_COLOR)]);
  27848. }
  27849. }
  27850. VertexTrail.TRAIL_POSITION0 = 0;
  27851. VertexTrail.TRAIL_OFFSETVECTOR = 1;
  27852. VertexTrail.TRAIL_TIME0 = 2;
  27853. VertexTrail.TRAIL_TEXTURECOORDINATE0Y = 3;
  27854. VertexTrail.TRAIL_TEXTURECOORDINATE0X = 4;
  27855. VertexTrail.TRAIL_COLOR = 5;
  27856. class TrailGeometry extends GeometryElement {
  27857. constructor(owner) {
  27858. super();
  27859. this._floatCountPerVertices1 = 8;
  27860. this._floatCountPerVertices2 = 5;
  27861. this._increaseSegementCount = 16;
  27862. this._activeIndex = 0;
  27863. this._endIndex = 0;
  27864. this._needAddFirstVertex = false;
  27865. this._isTempEndVertex = false;
  27866. this._vertices1 = null;
  27867. this._vertices2 = null;
  27868. this._lastFixedVertexPosition = new Vector3();
  27869. this._bufferState = new BufferState();
  27870. this.tmpColor = new Color();
  27871. this._disappearBoundsMode = false;
  27872. this._owner = owner;
  27873. this._segementCount = this._increaseSegementCount;
  27874. this._resizeData(this._segementCount, this._bufferState);
  27875. var bounds = this._owner._owner.trailRenderer.bounds;
  27876. var sprite3dPosition = this._owner._owner.transform.position;
  27877. bounds.setMin(sprite3dPosition);
  27878. bounds.setMax(sprite3dPosition);
  27879. }
  27880. _resizeData(segementCount, bufferState) {
  27881. this._subBirthTime = new Float32Array(segementCount);
  27882. this._subDistance = new Float64Array(segementCount);
  27883. var gl = Laya.LayaGL.instance;
  27884. var vertexCount = segementCount * 2;
  27885. var vertexDeclaration1 = VertexTrail.vertexDeclaration1;
  27886. var vertexDeclaration2 = VertexTrail.vertexDeclaration2;
  27887. var vertexBuffers = [];
  27888. var vertexbuffer1Size = vertexCount * vertexDeclaration1.vertexStride;
  27889. var vertexbuffer2Size = vertexCount * vertexDeclaration2.vertexStride;
  27890. var memorySize = vertexbuffer1Size + vertexbuffer2Size;
  27891. this._vertices1 = new Float32Array(vertexCount * this._floatCountPerVertices1);
  27892. this._vertices2 = new Float32Array(vertexCount * this._floatCountPerVertices2);
  27893. this._vertexBuffer1 = new VertexBuffer3D(vertexbuffer1Size, gl.STATIC_DRAW, false);
  27894. this._vertexBuffer1.vertexDeclaration = vertexDeclaration1;
  27895. this._vertexBuffer2 = new VertexBuffer3D(vertexbuffer2Size, gl.DYNAMIC_DRAW, false);
  27896. this._vertexBuffer2.vertexDeclaration = vertexDeclaration2;
  27897. vertexBuffers.push(this._vertexBuffer1);
  27898. vertexBuffers.push(this._vertexBuffer2);
  27899. bufferState.bind();
  27900. bufferState.applyVertexBuffers(vertexBuffers);
  27901. bufferState.unBind();
  27902. Laya.Resource._addMemory(memorySize, memorySize);
  27903. }
  27904. _resetData() {
  27905. var count = this._endIndex - this._activeIndex;
  27906. var oldVertices1 = new Float32Array(this._vertices1.buffer, this._floatCountPerVertices1 * 2 * this._activeIndex * 4, this._floatCountPerVertices1 * 2 * count);
  27907. var oldVertices2 = new Float32Array(this._vertices2.buffer, this._floatCountPerVertices2 * 2 * this._activeIndex * 4, this._floatCountPerVertices2 * 2 * count);
  27908. var oldSubDistance = new Float64Array(this._subDistance.buffer, this._activeIndex * 8, count);
  27909. var oldSubBirthTime = new Float32Array(this._subBirthTime.buffer, this._activeIndex * 4, count);
  27910. if (count === this._segementCount) {
  27911. var memorySize = this._vertexBuffer1._byteLength + this._vertexBuffer2._byteLength;
  27912. Laya.Resource._addMemory(-memorySize, -memorySize);
  27913. this._vertexBuffer1.destroy();
  27914. this._vertexBuffer2.destroy();
  27915. this._segementCount += this._increaseSegementCount;
  27916. this._resizeData(this._segementCount, this._bufferState);
  27917. }
  27918. this._vertices1.set(oldVertices1, 0);
  27919. this._vertices2.set(oldVertices2, 0);
  27920. this._subDistance.set(oldSubDistance, 0);
  27921. this._subBirthTime.set(oldSubBirthTime, 0);
  27922. this._endIndex = count;
  27923. this._activeIndex = 0;
  27924. this._vertexBuffer1.setData(this._vertices1.buffer, 0, this._floatCountPerVertices1 * 2 * this._activeIndex * 4, this._floatCountPerVertices1 * 2 * count * 4);
  27925. this._vertexBuffer2.setData(this._vertices2.buffer, 0, this._floatCountPerVertices2 * 2 * this._activeIndex * 4, this._floatCountPerVertices2 * 2 * count * 4);
  27926. }
  27927. _updateTrail(camera, lastPosition, position) {
  27928. if (!Vector3.equals(lastPosition, position)) {
  27929. if ((this._endIndex - this._activeIndex) === 0)
  27930. this._addTrailByFirstPosition(camera, position);
  27931. else
  27932. this._addTrailByNextPosition(camera, position);
  27933. }
  27934. }
  27935. _addTrailByFirstPosition(camera, position) {
  27936. (this._endIndex === this._segementCount) && (this._resetData());
  27937. this._subDistance[this._endIndex] = 0;
  27938. this._subBirthTime[this._endIndex] = this._owner._curtime;
  27939. this._endIndex++;
  27940. position.cloneTo(this._lastFixedVertexPosition);
  27941. this._needAddFirstVertex = true;
  27942. }
  27943. _addTrailByNextPosition(camera, position) {
  27944. var delVector3 = TrailGeometry._tempVector30;
  27945. var pointAtoBVector3 = TrailGeometry._tempVector31;
  27946. switch (this._owner.alignment) {
  27947. case exports.TrailAlignment.View:
  27948. var cameraMatrix = camera.viewMatrix;
  27949. Vector3.transformCoordinate(position, cameraMatrix, TrailGeometry._tempVector33);
  27950. Vector3.transformCoordinate(this._lastFixedVertexPosition, cameraMatrix, TrailGeometry._tempVector34);
  27951. Vector3.subtract(TrailGeometry._tempVector33, TrailGeometry._tempVector34, delVector3);
  27952. Vector3.cross(TrailGeometry._tempVector33, delVector3, pointAtoBVector3);
  27953. break;
  27954. case exports.TrailAlignment.TransformZ:
  27955. Vector3.subtract(position, this._lastFixedVertexPosition, delVector3);
  27956. var forward = TrailGeometry._tempVector32;
  27957. this._owner._owner.transform.getForward(forward);
  27958. Vector3.cross(delVector3, forward, pointAtoBVector3);
  27959. break;
  27960. }
  27961. Vector3.normalize(pointAtoBVector3, pointAtoBVector3);
  27962. Vector3.scale(pointAtoBVector3, this._owner.widthMultiplier / 2, pointAtoBVector3);
  27963. var delLength = Vector3.scalarLength(delVector3);
  27964. var tempEndIndex;
  27965. var offset;
  27966. if (this._needAddFirstVertex) {
  27967. this._updateVerticesByPositionData(position, pointAtoBVector3, this._endIndex - 1);
  27968. this._needAddFirstVertex = false;
  27969. }
  27970. if (delLength - this._owner.minVertexDistance >= MathUtils3D.zeroTolerance) {
  27971. if (this._isTempEndVertex) {
  27972. tempEndIndex = this._endIndex - 1;
  27973. offset = delLength - this._subDistance[tempEndIndex];
  27974. this._updateVerticesByPosition(position, pointAtoBVector3, delLength, tempEndIndex);
  27975. this._owner._totalLength += offset;
  27976. }
  27977. else {
  27978. (this._endIndex === this._segementCount) && (this._resetData());
  27979. this._updateVerticesByPosition(position, pointAtoBVector3, delLength, this._endIndex);
  27980. this._owner._totalLength += delLength;
  27981. this._endIndex++;
  27982. }
  27983. position.cloneTo(this._lastFixedVertexPosition);
  27984. this._isTempEndVertex = false;
  27985. }
  27986. else {
  27987. if (this._isTempEndVertex) {
  27988. tempEndIndex = this._endIndex - 1;
  27989. offset = delLength - this._subDistance[tempEndIndex];
  27990. this._updateVerticesByPosition(position, pointAtoBVector3, delLength, tempEndIndex);
  27991. this._owner._totalLength += offset;
  27992. }
  27993. else {
  27994. (this._endIndex === this._segementCount) && (this._resetData());
  27995. this._updateVerticesByPosition(position, pointAtoBVector3, delLength, this._endIndex);
  27996. this._owner._totalLength += delLength;
  27997. this._endIndex++;
  27998. }
  27999. this._isTempEndVertex = true;
  28000. }
  28001. }
  28002. _updateVerticesByPositionData(position, pointAtoBVector3, index) {
  28003. var vertexOffset = this._floatCountPerVertices1 * 2 * index;
  28004. var curtime = this._owner._curtime;
  28005. this._vertices1[vertexOffset] = position.x;
  28006. this._vertices1[vertexOffset + 1] = position.y;
  28007. this._vertices1[vertexOffset + 2] = position.z;
  28008. this._vertices1[vertexOffset + 3] = -pointAtoBVector3.x;
  28009. this._vertices1[vertexOffset + 4] = -pointAtoBVector3.y;
  28010. this._vertices1[vertexOffset + 5] = -pointAtoBVector3.z;
  28011. this._vertices1[vertexOffset + 6] = curtime;
  28012. this._vertices1[vertexOffset + 7] = 1.0;
  28013. this._vertices1[vertexOffset + 8] = position.x;
  28014. this._vertices1[vertexOffset + 9] = position.y;
  28015. this._vertices1[vertexOffset + 10] = position.z;
  28016. this._vertices1[vertexOffset + 11] = pointAtoBVector3.x;
  28017. this._vertices1[vertexOffset + 12] = pointAtoBVector3.y;
  28018. this._vertices1[vertexOffset + 13] = pointAtoBVector3.z;
  28019. this._vertices1[vertexOffset + 14] = curtime;
  28020. this._vertices1[vertexOffset + 15] = 0.0;
  28021. var bounds = this._owner._owner.trailRenderer.bounds;
  28022. var min = bounds.getMin();
  28023. var max = bounds.getMax();
  28024. var up = TrailGeometry._tempVector35;
  28025. var down = TrailGeometry._tempVector36;
  28026. var out = TrailGeometry._tempVector32;
  28027. Vector3.add(position, pointAtoBVector3, up);
  28028. Vector3.subtract(position, pointAtoBVector3, down);
  28029. Vector3.min(down, up, out);
  28030. Vector3.min(min, out, min);
  28031. bounds.setMin(min);
  28032. Vector3.max(up, down, out);
  28033. Vector3.max(max, out, max);
  28034. bounds.setMax(max);
  28035. var floatCount = this._floatCountPerVertices1 * 2;
  28036. this._vertexBuffer1.setData(this._vertices1.buffer, vertexOffset * 4, vertexOffset * 4, floatCount * 4);
  28037. }
  28038. _updateVerticesByPosition(position, pointAtoBVector3, delDistance, index) {
  28039. this._updateVerticesByPositionData(position, pointAtoBVector3, index);
  28040. this._subDistance[index] = delDistance;
  28041. this._subBirthTime[index] = this._owner._curtime;
  28042. }
  28043. _updateVertexBufferUV() {
  28044. var bounds;
  28045. var min, max;
  28046. if (this._disappearBoundsMode) {
  28047. bounds = this._owner._owner.trailRenderer.bounds;
  28048. var sprite3dPosition = this._owner._owner.transform.position;
  28049. bounds.setMin(sprite3dPosition);
  28050. bounds.setMax(sprite3dPosition);
  28051. min = bounds.getMin();
  28052. max = bounds.getMax();
  28053. }
  28054. var vertexCount = this._endIndex;
  28055. var curLength = 0;
  28056. var gradient = this._owner.colorGradient;
  28057. var startAlphaIndex = gradient.colorAlphaKeysCount - 1;
  28058. var startColorIndex = gradient.colorRGBKeysCount - 1;
  28059. var totalLength = this._owner._totalLength;
  28060. var stride = this._floatCountPerVertices2 * 2;
  28061. for (var i = this._activeIndex; i < vertexCount; i++) {
  28062. (i !== this._activeIndex) && (curLength += this._subDistance[i]);
  28063. var uvX;
  28064. var lerpFactor;
  28065. if (this._owner.textureMode == TextureMode.Stretch) {
  28066. uvX = 1.0 - curLength / totalLength;
  28067. lerpFactor = uvX;
  28068. }
  28069. else {
  28070. lerpFactor = 1.0 - curLength / totalLength;
  28071. uvX = 1.0 - (totalLength - curLength);
  28072. }
  28073. startColorIndex = gradient.evaluateColorRGB(lerpFactor, this.tmpColor, startColorIndex, true);
  28074. startAlphaIndex = gradient.evaluateColorAlpha(lerpFactor, this.tmpColor, startAlphaIndex, true);
  28075. var index = i * stride;
  28076. this._vertices2[index + 0] = uvX;
  28077. this._vertices2[index + 1] = this.tmpColor.r;
  28078. this._vertices2[index + 2] = this.tmpColor.g;
  28079. this._vertices2[index + 3] = this.tmpColor.b;
  28080. this._vertices2[index + 4] = this.tmpColor.a;
  28081. this._vertices2[index + 5] = uvX;
  28082. this._vertices2[index + 6] = this.tmpColor.r;
  28083. this._vertices2[index + 7] = this.tmpColor.g;
  28084. this._vertices2[index + 8] = this.tmpColor.b;
  28085. this._vertices2[index + 9] = this.tmpColor.a;
  28086. if (this._disappearBoundsMode) {
  28087. var posOffset = this._floatCountPerVertices1 * 2 * i;
  28088. var pos = TrailGeometry._tempVector32;
  28089. var up = TrailGeometry._tempVector33;
  28090. var side = TrailGeometry._tempVector34;
  28091. pos.setValue(this._vertices1[posOffset + 0], this._vertices1[posOffset + 1], this._vertices1[posOffset + 2]);
  28092. up.setValue(this._vertices1[posOffset + 3], this._vertices1[posOffset + 4], this._vertices1[posOffset + 5]);
  28093. Vector3.add(pos, up, side);
  28094. Vector3.min(side, min, min);
  28095. Vector3.max(side, max, max);
  28096. Vector3.subtract(pos, up, side);
  28097. Vector3.min(side, min, min);
  28098. Vector3.max(side, max, max);
  28099. }
  28100. }
  28101. if (this._disappearBoundsMode) {
  28102. bounds.setMin(min);
  28103. bounds.setMax(max);
  28104. this._disappearBoundsMode = false;
  28105. }
  28106. var offset = this._activeIndex * stride;
  28107. this._vertexBuffer2.setData(this._vertices2.buffer, offset * 4, offset * 4, (vertexCount * stride - offset) * 4);
  28108. }
  28109. _updateDisappear() {
  28110. var count = this._endIndex;
  28111. for (var i = this._activeIndex; i < count; i++) {
  28112. if (this._owner._curtime - this._subBirthTime[i] >= this._owner.time + MathUtils3D.zeroTolerance) {
  28113. var nextIndex = i + 1;
  28114. if (nextIndex !== count)
  28115. this._owner._totalLength -= this._subDistance[nextIndex];
  28116. if (this._isTempEndVertex && (nextIndex === count - 1)) {
  28117. var offset = this._floatCountPerVertices1 * i * 2;
  28118. var fixedPos = this._lastFixedVertexPosition;
  28119. fixedPos.x = this._vertices1[0];
  28120. fixedPos.y = this._vertices1[1];
  28121. fixedPos.z = this._vertices1[2];
  28122. this._isTempEndVertex = false;
  28123. }
  28124. this._activeIndex++;
  28125. this._disappearBoundsMode = true;
  28126. }
  28127. else {
  28128. break;
  28129. }
  28130. }
  28131. }
  28132. _getType() {
  28133. return TrailGeometry._type;
  28134. }
  28135. _prepareRender(state) {
  28136. return this._endIndex - this._activeIndex > 1;
  28137. }
  28138. _render(state) {
  28139. this._bufferState.bind();
  28140. var gl = Laya.LayaGL.instance;
  28141. var start = this._activeIndex * 2;
  28142. var count = this._endIndex * 2 - start;
  28143. gl.drawArrays(gl.TRIANGLE_STRIP, start, count);
  28144. Laya.Stat.renderBatches++;
  28145. Laya.Stat.trianglesFaces += count - 2;
  28146. }
  28147. destroy() {
  28148. super.destroy();
  28149. var memorySize = this._vertexBuffer1._byteLength + this._vertexBuffer2._byteLength;
  28150. Laya.Resource._addMemory(-memorySize, -memorySize);
  28151. this._bufferState.destroy();
  28152. this._vertexBuffer1.destroy();
  28153. this._vertexBuffer2.destroy();
  28154. this._bufferState = null;
  28155. this._vertices1 = null;
  28156. this._vertexBuffer1 = null;
  28157. this._vertices2 = null;
  28158. this._vertexBuffer2 = null;
  28159. this._subBirthTime = null;
  28160. this._subDistance = null;
  28161. this._lastFixedVertexPosition = null;
  28162. this._disappearBoundsMode = false;
  28163. }
  28164. clear() {
  28165. this._activeIndex = 0;
  28166. this._endIndex = 0;
  28167. this._disappearBoundsMode = false;
  28168. this._subBirthTime.fill(0);
  28169. this._subDistance.fill(0);
  28170. this._segementCount = 0;
  28171. this._isTempEndVertex = false;
  28172. this._needAddFirstVertex = false;
  28173. this._lastFixedVertexPosition.setValue(0, 0, 0);
  28174. }
  28175. }
  28176. TrailGeometry.ALIGNMENT_VIEW = 0;
  28177. TrailGeometry.ALIGNMENT_TRANSFORM_Z = 1;
  28178. TrailGeometry._tempVector30 = new Vector3();
  28179. TrailGeometry._tempVector31 = new Vector3();
  28180. TrailGeometry._tempVector32 = new Vector3();
  28181. TrailGeometry._tempVector33 = new Vector3();
  28182. TrailGeometry._tempVector34 = new Vector3();
  28183. TrailGeometry._tempVector35 = new Vector3();
  28184. TrailGeometry._tempVector36 = new Vector3();
  28185. TrailGeometry._type = GeometryElement._typeCounter++;
  28186. class TrailFilter {
  28187. constructor(owner) {
  28188. this._totalLength = 0;
  28189. this._lastPosition = new Vector3();
  28190. this._curtime = 0;
  28191. this.alignment = TrailFilter.ALIGNMENT_VIEW;
  28192. this._owner = owner;
  28193. this._initDefaultData();
  28194. this.addRenderElement();
  28195. }
  28196. get time() {
  28197. return this._time;
  28198. }
  28199. set time(value) {
  28200. this._time = value;
  28201. this._owner._render._shaderValues.setNumber(TrailFilter.LIFETIME, value);
  28202. }
  28203. get minVertexDistance() {
  28204. return this._minVertexDistance;
  28205. }
  28206. set minVertexDistance(value) {
  28207. this._minVertexDistance = value;
  28208. }
  28209. get widthMultiplier() {
  28210. return this._widthMultiplier;
  28211. }
  28212. set widthMultiplier(value) {
  28213. this._widthMultiplier = value;
  28214. }
  28215. get widthCurve() {
  28216. return this._widthCurve;
  28217. }
  28218. set widthCurve(value) {
  28219. this._widthCurve = value;
  28220. var widthCurveFloatArray = new Float32Array(value.length * 4);
  28221. var i, j, index = 0;
  28222. for (i = 0, j = value.length; i < j; i++) {
  28223. widthCurveFloatArray[index++] = value[i].time;
  28224. widthCurveFloatArray[index++] = value[i].inTangent;
  28225. widthCurveFloatArray[index++] = value[i].outTangent;
  28226. widthCurveFloatArray[index++] = value[i].value;
  28227. }
  28228. this._owner._render._shaderValues.setBuffer(TrailFilter.WIDTHCURVE, widthCurveFloatArray);
  28229. this._owner._render._shaderValues.setInt(TrailFilter.WIDTHCURVEKEYLENGTH, value.length);
  28230. }
  28231. get colorGradient() {
  28232. return this._colorGradient;
  28233. }
  28234. set colorGradient(value) {
  28235. this._colorGradient = value;
  28236. }
  28237. get textureMode() {
  28238. return this._textureMode;
  28239. }
  28240. set textureMode(value) {
  28241. this._textureMode = value;
  28242. }
  28243. addRenderElement() {
  28244. var render = this._owner._render;
  28245. var elements = render._renderElements;
  28246. var material = render.sharedMaterials[0];
  28247. (material) || (material = TrailMaterial.defaultMaterial);
  28248. var element = new RenderElement();
  28249. element.setTransform(this._owner._transform);
  28250. element.render = render;
  28251. element.material = material;
  28252. this._trialGeometry = new TrailGeometry(this);
  28253. element.setGeometry(this._trialGeometry);
  28254. elements.push(element);
  28255. }
  28256. _update(state) {
  28257. var render = this._owner._render;
  28258. this._curtime += state.scene.timer._delta / 1000;
  28259. render._shaderValues.setNumber(TrailFilter.CURTIME, this._curtime);
  28260. var curPos = this._owner.transform.position;
  28261. var element = render._renderElements[0]._geometry;
  28262. element._updateDisappear();
  28263. element._updateTrail(state.camera, this._lastPosition, curPos);
  28264. element._updateVertexBufferUV();
  28265. curPos.cloneTo(this._lastPosition);
  28266. }
  28267. _initDefaultData() {
  28268. this.time = 5.0;
  28269. this.minVertexDistance = 0.1;
  28270. this.widthMultiplier = 1;
  28271. this.textureMode = TextureMode.Stretch;
  28272. var widthKeyFrames = [];
  28273. var widthKeyFrame1 = new FloatKeyframe();
  28274. widthKeyFrame1.time = 0;
  28275. widthKeyFrame1.inTangent = 0;
  28276. widthKeyFrame1.outTangent = 0;
  28277. widthKeyFrame1.value = 1;
  28278. widthKeyFrames.push(widthKeyFrame1);
  28279. var widthKeyFrame2 = new FloatKeyframe();
  28280. widthKeyFrame2.time = 1;
  28281. widthKeyFrame2.inTangent = 0;
  28282. widthKeyFrame2.outTangent = 0;
  28283. widthKeyFrame2.value = 1;
  28284. widthKeyFrames.push(widthKeyFrame2);
  28285. this.widthCurve = widthKeyFrames;
  28286. var gradient = new Gradient(2, 2);
  28287. gradient.mode = GradientMode.Blend;
  28288. gradient.addColorRGB(0, Color.WHITE);
  28289. gradient.addColorRGB(1, Color.WHITE);
  28290. gradient.addColorAlpha(0, 1);
  28291. gradient.addColorAlpha(1, 1);
  28292. this.colorGradient = gradient;
  28293. }
  28294. destroy() {
  28295. this._trialGeometry.destroy();
  28296. this._trialGeometry = null;
  28297. this._widthCurve = null;
  28298. this._colorGradient = null;
  28299. }
  28300. clear() {
  28301. this._trialGeometry.clear();
  28302. this._lastPosition.setValue(0, 0, 0);
  28303. this._curtime = 0;
  28304. this._totalLength = 0;
  28305. }
  28306. }
  28307. TrailFilter.CURTIME = Shader3D.propertyNameToID("u_CurTime");
  28308. TrailFilter.LIFETIME = Shader3D.propertyNameToID("u_LifeTime");
  28309. TrailFilter.WIDTHCURVE = Shader3D.propertyNameToID("u_WidthCurve");
  28310. TrailFilter.WIDTHCURVEKEYLENGTH = Shader3D.propertyNameToID("u_WidthCurveKeyLength");
  28311. TrailFilter.ALIGNMENT_VIEW = 0;
  28312. TrailFilter.ALIGNMENT_TRANSFORM_Z = 1;
  28313. class TrailRenderer extends BaseRender {
  28314. constructor(owner) {
  28315. super(owner);
  28316. this._projectionViewWorldMatrix = new Matrix4x4();
  28317. }
  28318. _calculateBoundingBox() {
  28319. }
  28320. _needRender(boundFrustum, context) {
  28321. this._owner.trailFilter._update(context);
  28322. if (boundFrustum)
  28323. return boundFrustum.intersects(this.bounds._getBoundBox());
  28324. else
  28325. return true;
  28326. }
  28327. _updateForNative(context) {
  28328. this._owner.trailFilter._update(context);
  28329. }
  28330. _renderUpdate(state, transform) {
  28331. super._renderUpdate(state, transform);
  28332. }
  28333. _renderUpdateWithCamera(context, transform) {
  28334. var projectionView = context.projectionViewMatrix;
  28335. if (transform) {
  28336. Matrix4x4.multiply(projectionView, transform.worldMatrix, this._projectionViewWorldMatrix);
  28337. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, this._projectionViewWorldMatrix);
  28338. }
  28339. else {
  28340. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, projectionView);
  28341. }
  28342. }
  28343. }
  28344. class TrailSprite3D extends RenderableSprite3D {
  28345. constructor(name = null) {
  28346. super(name);
  28347. this._render = new TrailRenderer(this);
  28348. this._geometryFilter = new TrailFilter(this);
  28349. }
  28350. static __init__() {
  28351. }
  28352. get trailFilter() {
  28353. return this._geometryFilter;
  28354. }
  28355. get trailRenderer() {
  28356. return this._render;
  28357. }
  28358. _parse(data, spriteMap) {
  28359. super._parse(data, spriteMap);
  28360. var render = this._render;
  28361. var filter = this._geometryFilter;
  28362. var i, j;
  28363. var materials = data.materials;
  28364. if (materials) {
  28365. var sharedMaterials = render.sharedMaterials;
  28366. var materialCount = materials.length;
  28367. sharedMaterials.length = materialCount;
  28368. for (i = 0; i < materialCount; i++)
  28369. sharedMaterials[i] = Laya.Loader.getRes(materials[i].path);
  28370. render.sharedMaterials = sharedMaterials;
  28371. }
  28372. filter.time = data.time;
  28373. filter.minVertexDistance = data.minVertexDistance;
  28374. filter.widthMultiplier = data.widthMultiplier;
  28375. filter.textureMode = data.textureMode;
  28376. (data.alignment != null) && (filter.alignment = data.alignment);
  28377. var widthCurve = [];
  28378. var widthCurveData = data.widthCurve;
  28379. for (i = 0, j = widthCurveData.length; i < j; i++) {
  28380. var trailkeyframe = new FloatKeyframe();
  28381. trailkeyframe.time = widthCurveData[i].time;
  28382. trailkeyframe.inTangent = widthCurveData[i].inTangent;
  28383. trailkeyframe.outTangent = widthCurveData[i].outTangent;
  28384. trailkeyframe.value = widthCurveData[i].value;
  28385. widthCurve.push(trailkeyframe);
  28386. }
  28387. filter.widthCurve = widthCurve;
  28388. var colorGradientData = data.colorGradient;
  28389. var colorKeys = colorGradientData.colorKeys;
  28390. var alphaKeys = colorGradientData.alphaKeys;
  28391. var colorGradient = new Gradient(colorKeys.length, alphaKeys.length);
  28392. colorGradient.mode = colorGradientData.mode;
  28393. for (i = 0, j = colorKeys.length; i < j; i++) {
  28394. var colorKey = colorKeys[i];
  28395. colorGradient.addColorRGB(colorKey.time, new Color(colorKey.value[0], colorKey.value[1], colorKey.value[2], 1.0));
  28396. }
  28397. for (i = 0, j = alphaKeys.length; i < j; i++) {
  28398. var alphaKey = alphaKeys[i];
  28399. colorGradient.addColorAlpha(alphaKey.time, alphaKey.value);
  28400. }
  28401. filter.colorGradient = colorGradient;
  28402. }
  28403. _onActive() {
  28404. super._onActive();
  28405. this._transform.position.cloneTo(this._geometryFilter._lastPosition);
  28406. }
  28407. _cloneTo(destObject, srcSprite, dstSprite) {
  28408. super._cloneTo(destObject, srcSprite, dstSprite);
  28409. var i, j;
  28410. var destTrailSprite3D = destObject;
  28411. var destTrailFilter = destTrailSprite3D.trailFilter;
  28412. destTrailFilter.time = this.trailFilter.time;
  28413. destTrailFilter.minVertexDistance = this.trailFilter.minVertexDistance;
  28414. destTrailFilter.widthMultiplier = this.trailFilter.widthMultiplier;
  28415. destTrailFilter.textureMode = this.trailFilter.textureMode;
  28416. destTrailFilter.alignment = this.trailFilter.alignment;
  28417. var widthCurveData = this.trailFilter.widthCurve;
  28418. var widthCurve = [];
  28419. for (i = 0, j = widthCurveData.length; i < j; i++) {
  28420. var keyFrame = new FloatKeyframe();
  28421. widthCurveData[i].cloneTo(keyFrame);
  28422. widthCurve.push(keyFrame);
  28423. }
  28424. destTrailFilter.widthCurve = widthCurve;
  28425. var destColorGradient = new Gradient(this.trailFilter.colorGradient.maxColorRGBKeysCount, this.trailFilter.colorGradient.maxColorAlphaKeysCount);
  28426. this.trailFilter.colorGradient.cloneTo(destColorGradient);
  28427. destTrailFilter.colorGradient = destColorGradient;
  28428. var destTrailRender = destTrailSprite3D.trailRenderer;
  28429. destTrailRender.sharedMaterial = this.trailRenderer.sharedMaterial;
  28430. }
  28431. destroy(destroyChild = true) {
  28432. if (this.destroyed)
  28433. return;
  28434. super.destroy(destroyChild);
  28435. this._geometryFilter.destroy();
  28436. this._geometryFilter = null;
  28437. }
  28438. clear() {
  28439. this._geometryFilter.clear();
  28440. }
  28441. _create() {
  28442. return new TrailSprite3D();
  28443. }
  28444. }
  28445. class VertexPositionTerrain {
  28446. constructor(position, normal, textureCoord0, textureCoord1) {
  28447. this._position = position;
  28448. this._normal = normal;
  28449. this._textureCoord0 = textureCoord0;
  28450. this._textureCoord1 = textureCoord1;
  28451. }
  28452. static __init__() {
  28453. VertexPositionTerrain._vertexDeclaration = new VertexDeclaration(40, [new VertexElement(0, VertexElementFormat.Vector3, VertexPositionTerrain.TERRAIN_POSITION0),
  28454. new VertexElement(12, VertexElementFormat.Vector3, VertexPositionTerrain.TERRAIN_NORMAL0),
  28455. new VertexElement(24, VertexElementFormat.Vector2, VertexPositionTerrain.TERRAIN_TEXTURECOORDINATE0),
  28456. new VertexElement(32, VertexElementFormat.Vector2, VertexPositionTerrain.TERRAIN_TEXTURECOORDINATE1)]);
  28457. }
  28458. static get vertexDeclaration() {
  28459. return VertexPositionTerrain._vertexDeclaration;
  28460. }
  28461. get position() {
  28462. return this._position;
  28463. }
  28464. get normal() {
  28465. return this._normal;
  28466. }
  28467. get textureCoord0() {
  28468. return this._textureCoord0;
  28469. }
  28470. get textureCoord1() {
  28471. return this._textureCoord1;
  28472. }
  28473. get vertexDeclaration() {
  28474. return VertexPositionTerrain._vertexDeclaration;
  28475. }
  28476. }
  28477. VertexPositionTerrain.TERRAIN_POSITION0 = 0;
  28478. VertexPositionTerrain.TERRAIN_NORMAL0 = 1;
  28479. VertexPositionTerrain.TERRAIN_TEXTURECOORDINATE0 = 2;
  28480. VertexPositionTerrain.TERRAIN_TEXTURECOORDINATE1 = 3;
  28481. class BulletInteractive {
  28482. }
  28483. BulletInteractive._interactive = {
  28484. "getWorldTransform": (rigidBodyID, worldTransPointer) => {
  28485. },
  28486. "setWorldTransform": (rigidBodyID, worldTransPointer) => {
  28487. var rigidBody = PhysicsComponent._physicObjectsMap[rigidBodyID];
  28488. rigidBody._simulation._updatedRigidbodies++;
  28489. rigidBody._updateTransformComponent(worldTransPointer);
  28490. }
  28491. };
  28492. class PhysicsCollider extends PhysicsTriggerComponent {
  28493. constructor(collisionGroup = Physics3DUtils.COLLISIONFILTERGROUP_DEFAULTFILTER, canCollideWith = Physics3DUtils.COLLISIONFILTERGROUP_ALLFILTER) {
  28494. super(collisionGroup, canCollideWith);
  28495. this._enableProcessCollisions = false;
  28496. }
  28497. _addToSimulation() {
  28498. this._simulation._addPhysicsCollider(this, this._collisionGroup, this._canCollideWith);
  28499. }
  28500. _removeFromSimulation() {
  28501. this._simulation._removePhysicsCollider(this);
  28502. }
  28503. _parse(data) {
  28504. (data.friction != null) && (this.friction = data.friction);
  28505. (data.rollingFriction != null) && (this.rollingFriction = data.rollingFriction);
  28506. (data.restitution != null) && (this.restitution = data.restitution);
  28507. (data.isTrigger != null) && (this.isTrigger = data.isTrigger);
  28508. super._parse(data);
  28509. this._parseShape(data.shapes);
  28510. }
  28511. _onAdded() {
  28512. var bt = Physics3D._bullet;
  28513. var btColObj = bt.btCollisionObject_create();
  28514. bt.btCollisionObject_setUserIndex(btColObj, this.id);
  28515. bt.btCollisionObject_forceActivationState(btColObj, PhysicsComponent.ACTIVATIONSTATE_DISABLE_SIMULATION);
  28516. var flags = bt.btCollisionObject_getCollisionFlags(btColObj);
  28517. if (this.owner.isStatic) {
  28518. if ((flags & PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT) > 0)
  28519. flags = flags ^ PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT;
  28520. flags = flags | PhysicsComponent.COLLISIONFLAGS_STATIC_OBJECT;
  28521. }
  28522. else {
  28523. if ((flags & PhysicsComponent.COLLISIONFLAGS_STATIC_OBJECT) > 0)
  28524. flags = flags ^ PhysicsComponent.COLLISIONFLAGS_STATIC_OBJECT;
  28525. flags = flags | PhysicsComponent.COLLISIONFLAGS_KINEMATIC_OBJECT;
  28526. }
  28527. bt.btCollisionObject_setCollisionFlags(btColObj, flags);
  28528. this._btColliderObject = btColObj;
  28529. super._onAdded();
  28530. }
  28531. }
  28532. class SubMesh extends GeometryElement {
  28533. constructor(mesh) {
  28534. super();
  28535. this._id = ++SubMesh._uniqueIDCounter;
  28536. this._mesh = mesh;
  28537. this._boneIndicesList = [];
  28538. this._subIndexBufferStart = [];
  28539. this._subIndexBufferCount = [];
  28540. }
  28541. get indexCount() {
  28542. return this._indexCount;
  28543. }
  28544. _setIndexRange(indexStart, indexCount, indexFormat = exports.IndexFormat.UInt16) {
  28545. this._indexStart = indexStart;
  28546. this._indexCount = indexCount;
  28547. if (indexFormat == exports.IndexFormat.UInt16) {
  28548. this._indices = new Uint16Array(this._indexBuffer.getData().buffer, indexStart * 2, indexCount);
  28549. }
  28550. else {
  28551. this._indices = new Uint32Array(this._indexBuffer.getData().buffer, indexStart * 4, indexCount);
  28552. }
  28553. }
  28554. _getType() {
  28555. return SubMesh._type;
  28556. }
  28557. _prepareRender(state) {
  28558. this._mesh._uploadVerticesData();
  28559. return true;
  28560. }
  28561. _render(state) {
  28562. var mesh = this._mesh;
  28563. if (mesh.indexFormat === exports.IndexFormat.UInt32 && !Laya.LayaGL.layaGPUInstance.supportElementIndexUint32()) {
  28564. console.warn("SubMesh:this device do not support IndexFormat.UInt32.");
  28565. return;
  28566. }
  28567. var gl = Laya.LayaGL.instance;
  28568. var skinnedDatas = state.renderElement.render._skinnedData;
  28569. var glIndexFormat;
  28570. var byteCount;
  28571. switch (mesh.indexFormat) {
  28572. case exports.IndexFormat.UInt32:
  28573. glIndexFormat = gl.UNSIGNED_INT;
  28574. byteCount = 4;
  28575. break;
  28576. case exports.IndexFormat.UInt16:
  28577. glIndexFormat = gl.UNSIGNED_SHORT;
  28578. byteCount = 2;
  28579. break;
  28580. case exports.IndexFormat.UInt8:
  28581. glIndexFormat = gl.UNSIGNED_BYTE;
  28582. byteCount = 1;
  28583. break;
  28584. }
  28585. mesh._bufferState.bind();
  28586. if (skinnedDatas) {
  28587. var subSkinnedDatas = skinnedDatas[this._indexInMesh];
  28588. for (var i = 0, n = this._boneIndicesList.length; i < n; i++) {
  28589. state.shader.uploadCustomUniform(SkinnedMeshSprite3D.BONES, subSkinnedDatas[i]);
  28590. gl.drawElements(gl.TRIANGLES, this._subIndexBufferCount[i], glIndexFormat, this._subIndexBufferStart[i] * byteCount);
  28591. }
  28592. }
  28593. else {
  28594. gl.drawElements(gl.TRIANGLES, this._indexCount, glIndexFormat, this._indexStart * byteCount);
  28595. }
  28596. Laya.Stat.trianglesFaces += this._indexCount / 3;
  28597. Laya.Stat.renderBatches++;
  28598. }
  28599. getIndices() {
  28600. if (this._mesh._isReadable)
  28601. return this._indices.slice();
  28602. else
  28603. throw "SubMesh:can't get indices on subMesh,mesh's isReadable must be true.";
  28604. }
  28605. setIndices(indices) {
  28606. this._indexBuffer.setData(indices, this._indexStart, 0, this._indexCount);
  28607. }
  28608. destroy() {
  28609. if (this._destroyed)
  28610. return;
  28611. super.destroy();
  28612. this._indexBuffer.destroy();
  28613. this._indexBuffer = null;
  28614. this._mesh = null;
  28615. this._boneIndicesList = null;
  28616. this._subIndexBufferStart = null;
  28617. this._subIndexBufferCount = null;
  28618. this._skinAnimationDatas = null;
  28619. }
  28620. }
  28621. SubMesh._uniqueIDCounter = 0;
  28622. SubMesh._type = GeometryElement._typeCounter++;
  28623. class skinnedMatrixCache {
  28624. constructor(subMeshIndex, batchIndex, batchBoneIndex) {
  28625. this.subMeshIndex = subMeshIndex;
  28626. this.batchIndex = batchIndex;
  28627. this.batchBoneIndex = batchBoneIndex;
  28628. }
  28629. }
  28630. class Mesh extends Laya.Resource {
  28631. constructor(isReadable = true) {
  28632. super();
  28633. this._tempVector30 = new Vector3();
  28634. this._tempVector31 = new Vector3();
  28635. this._tempVector32 = new Vector3();
  28636. this._minVerticesUpdate = -1;
  28637. this._maxVerticesUpdate = -1;
  28638. this._needUpdateBounds = true;
  28639. this._bounds = new Bounds(new Vector3(), new Vector3());
  28640. this._bufferState = new BufferState();
  28641. this._instanceBufferState = new BufferState();
  28642. this._instanceBufferStateType = 0;
  28643. this._vertexBuffer = null;
  28644. this._indexBuffer = null;
  28645. this._skinnedMatrixCaches = [];
  28646. this._vertexCount = 0;
  28647. this._indexFormat = exports.IndexFormat.UInt16;
  28648. this._isReadable = isReadable;
  28649. this._subMeshes = [];
  28650. }
  28651. static __init__() {
  28652. var physics3D = Physics3D._bullet;
  28653. if (physics3D) {
  28654. Mesh._nativeTempVector30 = physics3D.btVector3_create(0, 0, 0);
  28655. Mesh._nativeTempVector31 = physics3D.btVector3_create(0, 0, 0);
  28656. Mesh._nativeTempVector32 = physics3D.btVector3_create(0, 0, 0);
  28657. }
  28658. }
  28659. static load(url, complete) {
  28660. Laya.ILaya.loader.create(url, complete, null, Mesh.MESH);
  28661. }
  28662. get inverseAbsoluteBindPoses() {
  28663. return this._inverseBindPoses;
  28664. }
  28665. get vertexCount() {
  28666. return this._vertexCount;
  28667. }
  28668. get indexCount() {
  28669. return this._indexBuffer.indexCount;
  28670. }
  28671. get subMeshCount() {
  28672. return this._subMeshes.length;
  28673. }
  28674. get bounds() {
  28675. return this._bounds;
  28676. }
  28677. set bounds(value) {
  28678. if (this._bounds !== value)
  28679. value.cloneTo(this._bounds);
  28680. }
  28681. get indexFormat() {
  28682. return this._indexFormat;
  28683. }
  28684. _getPositionElement(vertexBuffer) {
  28685. var vertexElements = vertexBuffer.vertexDeclaration._vertexElements;
  28686. for (var i = 0, n = vertexElements.length; i < n; i++) {
  28687. var vertexElement = vertexElements[i];
  28688. if (vertexElement._elementFormat === VertexElementFormat.Vector3 && vertexElement._elementUsage === VertexMesh.MESH_POSITION0)
  28689. return vertexElement;
  28690. }
  28691. return null;
  28692. }
  28693. _getVerticeElementData(data, elementUsage) {
  28694. data.length = this._vertexCount;
  28695. var verDec = this._vertexBuffer.vertexDeclaration;
  28696. var element = verDec.getVertexElementByUsage(elementUsage);
  28697. if (element) {
  28698. var uint8Vertices = this._vertexBuffer.getUint8Data();
  28699. var floatVertices = this._vertexBuffer.getFloat32Data();
  28700. var uint8VerStr = verDec.vertexStride;
  28701. var floatVerStr = uint8VerStr / 4;
  28702. var uint8EleOffset = element._offset;
  28703. var floatEleOffset = uint8EleOffset / 4;
  28704. switch (elementUsage) {
  28705. case VertexMesh.MESH_TEXTURECOORDINATE0:
  28706. case VertexMesh.MESH_TEXTURECOORDINATE1:
  28707. for (var i = 0; i < this._vertexCount; i++) {
  28708. var offset = floatVerStr * i + floatEleOffset;
  28709. data[i] = new Vector2(floatVertices[offset], floatVertices[offset + 1]);
  28710. }
  28711. break;
  28712. case VertexMesh.MESH_POSITION0:
  28713. case VertexMesh.MESH_NORMAL0:
  28714. for (var i = 0; i < this._vertexCount; i++) {
  28715. var offset = floatVerStr * i + floatEleOffset;
  28716. data[i] = new Vector3(floatVertices[offset], floatVertices[offset + 1], floatVertices[offset + 2]);
  28717. }
  28718. break;
  28719. case VertexMesh.MESH_TANGENT0:
  28720. case VertexMesh.MESH_BLENDWEIGHT0:
  28721. for (var i = 0; i < this._vertexCount; i++) {
  28722. var offset = floatVerStr * i + floatEleOffset;
  28723. data[i] = new Vector4(floatVertices[offset], floatVertices[offset + 1], floatVertices[offset + 2], floatVertices[offset + 3]);
  28724. }
  28725. break;
  28726. case VertexMesh.MESH_COLOR0:
  28727. for (var i = 0; i < this._vertexCount; i++) {
  28728. var offset = floatVerStr * i + floatEleOffset;
  28729. data[i] = new Color(floatVertices[offset], floatVertices[offset + 1], floatVertices[offset + 2], floatVertices[offset + 3]);
  28730. }
  28731. break;
  28732. case VertexMesh.MESH_BLENDINDICES0:
  28733. for (var i = 0; i < this._vertexCount; i++) {
  28734. var offset = uint8VerStr * i + uint8EleOffset;
  28735. data[i] = new Vector4(uint8Vertices[offset], uint8Vertices[offset + 1], uint8Vertices[offset + 2], uint8Vertices[offset + 3]);
  28736. }
  28737. break;
  28738. default:
  28739. throw "Mesh:Unknown elementUsage.";
  28740. }
  28741. }
  28742. }
  28743. _setVerticeElementData(data, elementUsage) {
  28744. var verDec = this._vertexBuffer.vertexDeclaration;
  28745. var element = verDec.getVertexElementByUsage(elementUsage);
  28746. if (element) {
  28747. var uint8Vertices = this._vertexBuffer.getUint8Data();
  28748. var floatVertices = this._vertexBuffer.getFloat32Data();
  28749. var uint8VerStr = verDec.vertexStride;
  28750. var float8VerStr = uint8VerStr / 4;
  28751. var uint8EleOffset = element._offset;
  28752. var floatEleOffset = uint8EleOffset / 4;
  28753. switch (elementUsage) {
  28754. case VertexMesh.MESH_TEXTURECOORDINATE0:
  28755. case VertexMesh.MESH_TEXTURECOORDINATE1:
  28756. for (var i = 0, n = data.length; i < n; i++) {
  28757. var offset = float8VerStr * i + floatEleOffset;
  28758. var vec2 = data[i];
  28759. floatVertices[offset] = vec2.x;
  28760. floatVertices[offset + 1] = vec2.y;
  28761. }
  28762. break;
  28763. case VertexMesh.MESH_POSITION0:
  28764. case VertexMesh.MESH_NORMAL0:
  28765. for (var i = 0, n = data.length; i < n; i++) {
  28766. var offset = float8VerStr * i + floatEleOffset;
  28767. var vec3 = data[i];
  28768. floatVertices[offset] = vec3.x;
  28769. floatVertices[offset + 1] = vec3.y;
  28770. floatVertices[offset + 2] = vec3.z;
  28771. }
  28772. break;
  28773. case VertexMesh.MESH_TANGENT0:
  28774. case VertexMesh.MESH_BLENDWEIGHT0:
  28775. for (var i = 0, n = data.length; i < n; i++) {
  28776. var offset = float8VerStr * i + floatEleOffset;
  28777. var vec4 = data[i];
  28778. floatVertices[offset] = vec4.x;
  28779. floatVertices[offset + 1] = vec4.y;
  28780. floatVertices[offset + 2] = vec4.z;
  28781. floatVertices[offset + 3] = vec4.w;
  28782. }
  28783. break;
  28784. case VertexMesh.MESH_COLOR0:
  28785. for (var i = 0, n = data.length; i < n; i++) {
  28786. var offset = float8VerStr * i + floatEleOffset;
  28787. var cor = data[i];
  28788. floatVertices[offset] = cor.r;
  28789. floatVertices[offset + 1] = cor.g;
  28790. floatVertices[offset + 2] = cor.b;
  28791. floatVertices[offset + 3] = cor.a;
  28792. }
  28793. break;
  28794. case VertexMesh.MESH_BLENDINDICES0:
  28795. for (var i = 0, n = data.length; i < n; i++) {
  28796. var offset = uint8VerStr * i + uint8EleOffset;
  28797. var vec4 = data[i];
  28798. uint8Vertices[offset] = vec4.x;
  28799. uint8Vertices[offset + 1] = vec4.y;
  28800. uint8Vertices[offset + 2] = vec4.z;
  28801. uint8Vertices[offset + 3] = vec4.w;
  28802. }
  28803. break;
  28804. default:
  28805. throw "Mesh:Unknown elementUsage.";
  28806. }
  28807. this._minVerticesUpdate = 0;
  28808. this._maxVerticesUpdate = Number.MAX_SAFE_INTEGER;
  28809. }
  28810. else {
  28811. console.warn("Mesh: the mesh don't have this VertexElement.");
  28812. }
  28813. }
  28814. _disposeResource() {
  28815. for (var i = 0, n = this._subMeshes.length; i < n; i++)
  28816. this._subMeshes[i].destroy();
  28817. this._btTriangleMesh && Physics3D._bullet.btStridingMeshInterface_destroy(this._btTriangleMesh);
  28818. this._vertexBuffer.destroy();
  28819. this._indexBuffer.destroy();
  28820. this._bufferState.destroy();
  28821. this._instanceBufferState.destroy();
  28822. this._setCPUMemory(0);
  28823. this._setGPUMemory(0);
  28824. this._bufferState = null;
  28825. this._instanceBufferState = null;
  28826. this._vertexBuffer = null;
  28827. this._indexBuffer = null;
  28828. this._subMeshes = null;
  28829. this._btTriangleMesh = null;
  28830. this._indexBuffer = null;
  28831. this._boneNames = null;
  28832. this._inverseBindPoses = null;
  28833. }
  28834. _setSubMeshes(subMeshes) {
  28835. this._subMeshes = subMeshes;
  28836. for (var i = 0, n = subMeshes.length; i < n; i++)
  28837. subMeshes[i]._indexInMesh = i;
  28838. }
  28839. _setBuffer(vertexBuffer, indexBuffer) {
  28840. var bufferState = this._bufferState;
  28841. bufferState.bind();
  28842. bufferState.applyVertexBuffer(vertexBuffer);
  28843. bufferState.applyIndexBuffer(indexBuffer);
  28844. bufferState.unBind();
  28845. }
  28846. _setInstanceBuffer(instanceBufferStateType) {
  28847. var instanceBufferState = this._instanceBufferState;
  28848. instanceBufferState.bind();
  28849. instanceBufferState.applyVertexBuffer(this._vertexBuffer);
  28850. instanceBufferState.applyInstanceVertexBuffer(SubMeshInstanceBatch.instance.instanceWorldMatrixBuffer);
  28851. instanceBufferState.applyInstanceVertexBuffer(SubMeshInstanceBatch.instance.instanceMVPMatrixBuffer);
  28852. switch (instanceBufferStateType) {
  28853. case Mesh.MESH_INSTANCEBUFFER_TYPE_SIMPLEANIMATOR:
  28854. instanceBufferState.applyInstanceVertexBuffer(SubMeshInstanceBatch.instance.instanceSimpleAnimatorBuffer);
  28855. break;
  28856. }
  28857. instanceBufferState.applyIndexBuffer(this._indexBuffer);
  28858. instanceBufferState.unBind();
  28859. }
  28860. _getPhysicMesh() {
  28861. if (!this._btTriangleMesh) {
  28862. var bt = Physics3D._bullet;
  28863. var triangleMesh = bt.btTriangleMesh_create();
  28864. var nativePositio0 = Mesh._nativeTempVector30;
  28865. var nativePositio1 = Mesh._nativeTempVector31;
  28866. var nativePositio2 = Mesh._nativeTempVector32;
  28867. var position0 = this._tempVector30;
  28868. var position1 = this._tempVector31;
  28869. var position2 = this._tempVector32;
  28870. var vertexBuffer = this._vertexBuffer;
  28871. var positionElement = this._getPositionElement(vertexBuffer);
  28872. var verticesData = vertexBuffer.getFloat32Data();
  28873. var floatCount = vertexBuffer.vertexDeclaration.vertexStride / 4;
  28874. var posOffset = positionElement._offset / 4;
  28875. var indices = this._indexBuffer.getData();
  28876. for (var i = 0, n = indices.length; i < n; i += 3) {
  28877. var p0Index = indices[i] * floatCount + posOffset;
  28878. var p1Index = indices[i + 1] * floatCount + posOffset;
  28879. var p2Index = indices[i + 2] * floatCount + posOffset;
  28880. position0.setValue(verticesData[p0Index], verticesData[p0Index + 1], verticesData[p0Index + 2]);
  28881. position1.setValue(verticesData[p1Index], verticesData[p1Index + 1], verticesData[p1Index + 2]);
  28882. position2.setValue(verticesData[p2Index], verticesData[p2Index + 1], verticesData[p2Index + 2]);
  28883. Utils3D._convertToBulletVec3(position0, nativePositio0, true);
  28884. Utils3D._convertToBulletVec3(position1, nativePositio1, true);
  28885. Utils3D._convertToBulletVec3(position2, nativePositio2, true);
  28886. bt.btTriangleMesh_addTriangle(triangleMesh, nativePositio0, nativePositio1, nativePositio2, true);
  28887. }
  28888. this._btTriangleMesh = triangleMesh;
  28889. }
  28890. return this._btTriangleMesh;
  28891. }
  28892. _uploadVerticesData() {
  28893. var min = this._minVerticesUpdate;
  28894. var max = this._maxVerticesUpdate;
  28895. if (min !== -1 && max !== -1) {
  28896. var offset = min;
  28897. this._vertexBuffer.setData(this._vertexBuffer.getUint8Data().buffer, offset, offset, max - min);
  28898. this._minVerticesUpdate = -1;
  28899. this._maxVerticesUpdate = -1;
  28900. }
  28901. }
  28902. getSubMesh(index) {
  28903. return this._subMeshes[index];
  28904. }
  28905. getPositions(positions) {
  28906. if (this._isReadable)
  28907. this._getVerticeElementData(positions, VertexMesh.MESH_POSITION0);
  28908. else
  28909. throw "Mesh:can't get positions on mesh,isReadable must be true.";
  28910. }
  28911. setPositions(positions) {
  28912. if (this._isReadable) {
  28913. this._setVerticeElementData(positions, VertexMesh.MESH_POSITION0);
  28914. this._needUpdateBounds = true;
  28915. }
  28916. else {
  28917. throw "Mesh:setPosition() need isReadable must be true or use setVertices().";
  28918. }
  28919. }
  28920. getColors(colors) {
  28921. if (this._isReadable)
  28922. this._getVerticeElementData(colors, VertexMesh.MESH_COLOR0);
  28923. else
  28924. throw "Mesh:can't get colors on mesh,isReadable must be true.";
  28925. }
  28926. setColors(colors) {
  28927. if (this._isReadable)
  28928. this._setVerticeElementData(colors, VertexMesh.MESH_COLOR0);
  28929. else
  28930. throw "Mesh:setColors() need isReadable must be true or use setVertices().";
  28931. }
  28932. getUVs(uvs, channel = 0) {
  28933. if (this._isReadable) {
  28934. switch (channel) {
  28935. case 0:
  28936. this._getVerticeElementData(uvs, VertexMesh.MESH_TEXTURECOORDINATE0);
  28937. break;
  28938. case 1:
  28939. this._getVerticeElementData(uvs, VertexMesh.MESH_TEXTURECOORDINATE1);
  28940. break;
  28941. default:
  28942. throw "Mesh:Invalid channel.";
  28943. }
  28944. }
  28945. else {
  28946. throw "Mesh:can't get uvs on mesh,isReadable must be true.";
  28947. }
  28948. }
  28949. setUVs(uvs, channel = 0) {
  28950. if (this._isReadable) {
  28951. switch (channel) {
  28952. case 0:
  28953. this._setVerticeElementData(uvs, VertexMesh.MESH_TEXTURECOORDINATE0);
  28954. break;
  28955. case 1:
  28956. this._setVerticeElementData(uvs, VertexMesh.MESH_TEXTURECOORDINATE1);
  28957. break;
  28958. default:
  28959. throw "Mesh:Invalid channel.";
  28960. }
  28961. }
  28962. else {
  28963. throw "Mesh:setUVs() need isReadable must be true or use setVertices().";
  28964. }
  28965. }
  28966. getNormals(normals) {
  28967. if (this._isReadable)
  28968. this._getVerticeElementData(normals, VertexMesh.MESH_NORMAL0);
  28969. else
  28970. throw "Mesh:can't get colors on mesh,isReadable must be true.";
  28971. }
  28972. setNormals(normals) {
  28973. if (this._isReadable)
  28974. this._setVerticeElementData(normals, VertexMesh.MESH_NORMAL0);
  28975. else
  28976. throw "Mesh:setNormals() need must be true or use setVertices().";
  28977. }
  28978. getTangents(tangents) {
  28979. if (this._isReadable)
  28980. this._getVerticeElementData(tangents, VertexMesh.MESH_TANGENT0);
  28981. else
  28982. throw "Mesh:can't get colors on mesh,isReadable must be true.";
  28983. }
  28984. setTangents(tangents) {
  28985. if (this._isReadable)
  28986. this._setVerticeElementData(tangents, VertexMesh.MESH_TANGENT0);
  28987. else
  28988. throw "Mesh:setTangents() need isReadable must be true or use setVertices().";
  28989. }
  28990. getBoneWeights(boneWeights) {
  28991. if (this._isReadable)
  28992. this._getVerticeElementData(boneWeights, VertexMesh.MESH_BLENDWEIGHT0);
  28993. else
  28994. throw "Mesh:can't get boneWeights on mesh,isReadable must be true.";
  28995. }
  28996. setBoneWeights(boneWeights) {
  28997. if (this._isReadable)
  28998. this._setVerticeElementData(boneWeights, VertexMesh.MESH_BLENDWEIGHT0);
  28999. else
  29000. throw "Mesh:setBoneWeights() need isReadable must be true or use setVertices().";
  29001. }
  29002. getBoneIndices(boneIndices) {
  29003. if (this._isReadable)
  29004. this._getVerticeElementData(boneIndices, VertexMesh.MESH_BLENDINDICES0);
  29005. else
  29006. throw "Mesh:can't get boneIndices on mesh,isReadable must be true.";
  29007. }
  29008. setBoneIndices(boneIndices) {
  29009. if (this._isReadable)
  29010. this._setVerticeElementData(boneIndices, VertexMesh.MESH_BLENDINDICES0);
  29011. else
  29012. throw "Mesh:setBoneIndices() need isReadable must be true or use setVertices().";
  29013. }
  29014. markAsUnreadbale() {
  29015. this._uploadVerticesData();
  29016. this._vertexBuffer.markAsUnreadbale();
  29017. this._isReadable = false;
  29018. }
  29019. getVertexDeclaration() {
  29020. return this._vertexBuffer._vertexDeclaration;
  29021. }
  29022. getVertices() {
  29023. if (this._isReadable)
  29024. return this._vertexBuffer.getUint8Data().buffer.slice(0);
  29025. else
  29026. throw "Mesh:can't get vertices on mesh,isReadable must be true.";
  29027. }
  29028. setVertices(vertices) {
  29029. this._vertexBuffer.setData(vertices);
  29030. this._needUpdateBounds = true;
  29031. }
  29032. getIndices() {
  29033. if (this._isReadable)
  29034. return this._indexBuffer.getData().slice();
  29035. else
  29036. throw "Mesh:can't get indices on subMesh,mesh's isReadable must be true.";
  29037. }
  29038. setIndices(indices) {
  29039. var format;
  29040. if (indices instanceof Uint32Array)
  29041. format = exports.IndexFormat.UInt32;
  29042. else if (indices instanceof Uint16Array)
  29043. format = exports.IndexFormat.UInt16;
  29044. else if (indices instanceof Uint8Array)
  29045. format = exports.IndexFormat.UInt8;
  29046. var indexBuffer = this._indexBuffer;
  29047. if (this._indexFormat !== format || indexBuffer.indexCount !== indices.length) {
  29048. indexBuffer.destroy();
  29049. this._indexBuffer = indexBuffer = new IndexBuffer3D(format, indices.length, Laya.LayaGL.instance.STATIC_DRAW, this._isReadable);
  29050. }
  29051. indexBuffer.setData(indices);
  29052. this._indexFormat = format;
  29053. }
  29054. calculateBounds() {
  29055. if (this._isReadable) {
  29056. if (this._needUpdateBounds) {
  29057. var min = this._tempVector30;
  29058. var max = this._tempVector31;
  29059. min.x = min.y = min.z = Number.MAX_VALUE;
  29060. max.x = max.y = max.z = -Number.MAX_VALUE;
  29061. var vertexBuffer = this._vertexBuffer;
  29062. var positionElement = this._getPositionElement(vertexBuffer);
  29063. var verticesData = vertexBuffer.getFloat32Data();
  29064. var floatCount = vertexBuffer.vertexDeclaration.vertexStride / 4;
  29065. var posOffset = positionElement._offset / 4;
  29066. for (var j = 0, m = verticesData.length; j < m; j += floatCount) {
  29067. var ofset = j + posOffset;
  29068. var pX = verticesData[ofset];
  29069. var pY = verticesData[ofset + 1];
  29070. var pZ = verticesData[ofset + 2];
  29071. min.x = Math.min(min.x, pX);
  29072. min.y = Math.min(min.y, pY);
  29073. min.z = Math.min(min.z, pZ);
  29074. max.x = Math.max(max.x, pX);
  29075. max.y = Math.max(max.y, pY);
  29076. max.z = Math.max(max.z, pZ);
  29077. }
  29078. this._bounds.setMin(min);
  29079. this._bounds.setMax(max);
  29080. this._needUpdateBounds = false;
  29081. }
  29082. }
  29083. else {
  29084. throw "Mesh:can't calculate bounds on subMesh,mesh's isReadable must be true.";
  29085. }
  29086. }
  29087. cloneTo(destObject) {
  29088. var destMesh = destObject;
  29089. var vb = this._vertexBuffer;
  29090. var destVB = new VertexBuffer3D(vb._byteLength, vb.bufferUsage, vb.canRead);
  29091. destVB.vertexDeclaration = vb.vertexDeclaration;
  29092. destVB.setData(vb.getUint8Data().slice().buffer);
  29093. destMesh._vertexBuffer = destVB;
  29094. destMesh._vertexCount = this._vertexCount;
  29095. var ib = this._indexBuffer;
  29096. var destIB = new IndexBuffer3D(exports.IndexFormat.UInt16, ib.indexCount, ib.bufferUsage, ib.canRead);
  29097. destIB.setData(ib.getData().slice());
  29098. destMesh._indexBuffer = destIB;
  29099. destMesh._setBuffer(destMesh._vertexBuffer, destIB);
  29100. destMesh._setInstanceBuffer(this._instanceBufferStateType);
  29101. destMesh._setCPUMemory(this.cpuMemory);
  29102. destMesh._setGPUMemory(this.gpuMemory);
  29103. var i;
  29104. var boneNames = this._boneNames;
  29105. if (boneNames) {
  29106. var destBoneNames = destMesh._boneNames = [];
  29107. for (i = 0; i < boneNames.length; i++)
  29108. destBoneNames[i] = boneNames[i];
  29109. }
  29110. var inverseBindPoses = this._inverseBindPoses;
  29111. if (inverseBindPoses) {
  29112. var destInverseBindPoses = destMesh._inverseBindPoses = [];
  29113. for (i = 0; i < inverseBindPoses.length; i++)
  29114. destInverseBindPoses[i] = inverseBindPoses[i];
  29115. }
  29116. var cacheLength = this._skinnedMatrixCaches.length;
  29117. destMesh._skinnedMatrixCaches.length = cacheLength;
  29118. for (i = 0; i < cacheLength; i++) {
  29119. var skinnedCache = this._skinnedMatrixCaches[i];
  29120. destMesh._skinnedMatrixCaches[i] = new skinnedMatrixCache(skinnedCache.subMeshIndex, skinnedCache.batchIndex, skinnedCache.batchBoneIndex);
  29121. }
  29122. for (i = 0; i < this.subMeshCount; i++) {
  29123. var subMesh = this._subMeshes[i];
  29124. var subIndexBufferStart = subMesh._subIndexBufferStart;
  29125. var subIndexBufferCount = subMesh._subIndexBufferCount;
  29126. var boneIndicesList = subMesh._boneIndicesList;
  29127. var destSubmesh = new SubMesh(destMesh);
  29128. destSubmesh._subIndexBufferStart.length = subIndexBufferStart.length;
  29129. destSubmesh._subIndexBufferCount.length = subIndexBufferCount.length;
  29130. destSubmesh._boneIndicesList.length = boneIndicesList.length;
  29131. for (var j = 0; j < subIndexBufferStart.length; j++)
  29132. destSubmesh._subIndexBufferStart[j] = subIndexBufferStart[j];
  29133. for (j = 0; j < subIndexBufferCount.length; j++)
  29134. destSubmesh._subIndexBufferCount[j] = subIndexBufferCount[j];
  29135. for (j = 0; j < boneIndicesList.length; j++)
  29136. destSubmesh._boneIndicesList[j] = new Uint16Array(boneIndicesList[j]);
  29137. destSubmesh._indexBuffer = destIB;
  29138. destSubmesh._indexStart = subMesh._indexStart;
  29139. destSubmesh._indexCount = subMesh._indexCount;
  29140. destSubmesh._indices = new Uint16Array(destIB.getData().buffer, subMesh._indexStart * 2, subMesh._indexCount);
  29141. var vertexBuffer = destMesh._vertexBuffer;
  29142. destSubmesh._vertexBuffer = vertexBuffer;
  29143. destMesh._subMeshes.push(destSubmesh);
  29144. }
  29145. destMesh._setSubMeshes(destMesh._subMeshes);
  29146. }
  29147. clone() {
  29148. var dest = new Mesh();
  29149. this.cloneTo(dest);
  29150. return dest;
  29151. }
  29152. }
  29153. Mesh.MESH = "MESH";
  29154. Mesh.MESH_INSTANCEBUFFER_TYPE_NORMAL = 0;
  29155. Mesh.MESH_INSTANCEBUFFER_TYPE_SIMPLEANIMATOR = 1;
  29156. class PrimitiveMesh {
  29157. static __init__() {
  29158. }
  29159. static _createMesh(vertexDeclaration, vertices, indices) {
  29160. var gl = Laya.LayaGL.instance;
  29161. var mesh = new Mesh();
  29162. var subMesh = new SubMesh(mesh);
  29163. var vertexBuffer = new VertexBuffer3D(vertices.length * 4, gl.STATIC_DRAW, true);
  29164. vertexBuffer.vertexDeclaration = vertexDeclaration;
  29165. vertexBuffer.setData(vertices.buffer);
  29166. mesh._vertexBuffer = vertexBuffer;
  29167. mesh._vertexCount = vertexBuffer._byteLength / vertexDeclaration.vertexStride;
  29168. var indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt16, indices.length, gl.STATIC_DRAW, true);
  29169. indexBuffer.setData(indices);
  29170. mesh._indexBuffer = indexBuffer;
  29171. mesh._setBuffer(vertexBuffer, indexBuffer);
  29172. mesh._setInstanceBuffer(mesh._instanceBufferStateType);
  29173. subMesh._vertexBuffer = vertexBuffer;
  29174. subMesh._indexBuffer = indexBuffer;
  29175. subMesh._setIndexRange(0, indexBuffer.indexCount);
  29176. var subIndexBufferStart = subMesh._subIndexBufferStart;
  29177. var subIndexBufferCount = subMesh._subIndexBufferCount;
  29178. var boneIndicesList = subMesh._boneIndicesList;
  29179. subIndexBufferStart.length = 1;
  29180. subIndexBufferCount.length = 1;
  29181. boneIndicesList.length = 1;
  29182. subIndexBufferStart[0] = 0;
  29183. subIndexBufferCount[0] = indexBuffer.indexCount;
  29184. var subMeshes = [];
  29185. subMeshes.push(subMesh);
  29186. mesh._setSubMeshes(subMeshes);
  29187. mesh.calculateBounds();
  29188. var memorySize = vertexBuffer._byteLength + indexBuffer._byteLength;
  29189. mesh._setCPUMemory(memorySize);
  29190. mesh._setGPUMemory(memorySize);
  29191. return mesh;
  29192. }
  29193. static createBox(long = 1, height = 1, width = 1) {
  29194. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  29195. var halfLong = long / 2;
  29196. var halfHeight = height / 2;
  29197. var halfWidth = width / 2;
  29198. var vertices = new Float32Array([
  29199. -halfLong, halfHeight, -halfWidth, 0, 1, 0, 0, 0, halfLong, halfHeight, -halfWidth, 0, 1, 0, 1, 0, halfLong, halfHeight, halfWidth, 0, 1, 0, 1, 1, -halfLong, halfHeight, halfWidth, 0, 1, 0, 0, 1,
  29200. -halfLong, -halfHeight, -halfWidth, 0, -1, 0, 0, 1, halfLong, -halfHeight, -halfWidth, 0, -1, 0, 1, 1, halfLong, -halfHeight, halfWidth, 0, -1, 0, 1, 0, -halfLong, -halfHeight, halfWidth, 0, -1, 0, 0, 0,
  29201. -halfLong, halfHeight, -halfWidth, -1, 0, 0, 0, 0, -halfLong, halfHeight, halfWidth, -1, 0, 0, 1, 0, -halfLong, -halfHeight, halfWidth, -1, 0, 0, 1, 1, -halfLong, -halfHeight, -halfWidth, -1, 0, 0, 0, 1,
  29202. halfLong, halfHeight, -halfWidth, 1, 0, 0, 1, 0, halfLong, halfHeight, halfWidth, 1, 0, 0, 0, 0, halfLong, -halfHeight, halfWidth, 1, 0, 0, 0, 1, halfLong, -halfHeight, -halfWidth, 1, 0, 0, 1, 1,
  29203. -halfLong, halfHeight, halfWidth, 0, 0, 1, 0, 0, halfLong, halfHeight, halfWidth, 0, 0, 1, 1, 0, halfLong, -halfHeight, halfWidth, 0, 0, 1, 1, 1, -halfLong, -halfHeight, halfWidth, 0, 0, 1, 0, 1,
  29204. -halfLong, halfHeight, -halfWidth, 0, 0, -1, 1, 0, halfLong, halfHeight, -halfWidth, 0, 0, -1, 0, 0, halfLong, -halfHeight, -halfWidth, 0, 0, -1, 0, 1, -halfLong, -halfHeight, -halfWidth, 0, 0, -1, 1, 1
  29205. ]);
  29206. var indices = new Uint16Array([
  29207. 0, 1, 2, 2, 3, 0,
  29208. 4, 7, 6, 6, 5, 4,
  29209. 8, 9, 10, 10, 11, 8,
  29210. 12, 15, 14, 14, 13, 12,
  29211. 16, 17, 18, 18, 19, 16,
  29212. 20, 23, 22, 22, 21, 20
  29213. ]);
  29214. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  29215. }
  29216. static createCapsule(radius = 0.5, height = 2, stacks = 16, slices = 32) {
  29217. var vertexCount = (stacks + 1) * (slices + 1) * 2 + (slices + 1) * 2;
  29218. var indexCount = (3 * stacks * (slices + 1)) * 2 * 2 + 2 * slices * 3;
  29219. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  29220. var vertexFloatStride = vertexDeclaration.vertexStride / 4;
  29221. var vertices = new Float32Array(vertexCount * vertexFloatStride);
  29222. var indices = new Uint16Array(indexCount);
  29223. var stackAngle = (Math.PI / 2.0) / stacks;
  29224. var sliceAngle = (Math.PI * 2.0) / slices;
  29225. var hcHeight = height / 2 - radius;
  29226. var posX = 0;
  29227. var posY = 0;
  29228. var posZ = 0;
  29229. var vc = 0;
  29230. var ic = 0;
  29231. var verticeCount = 0;
  29232. var stack, slice;
  29233. for (stack = 0; stack <= stacks; stack++) {
  29234. for (slice = 0; slice <= slices; slice++) {
  29235. posX = radius * Math.cos(stack * stackAngle) * Math.cos(slice * sliceAngle + Math.PI);
  29236. posY = radius * Math.sin(stack * stackAngle);
  29237. posZ = radius * Math.cos(stack * stackAngle) * Math.sin(slice * sliceAngle + Math.PI);
  29238. vertices[vc++] = posX;
  29239. vertices[vc++] = posY + hcHeight;
  29240. vertices[vc++] = posZ;
  29241. vertices[vc++] = posX;
  29242. vertices[vc++] = posY;
  29243. vertices[vc++] = posZ;
  29244. vertices[vc++] = 1 - slice / slices;
  29245. vertices[vc++] = (1 - stack / stacks) * ((Math.PI * radius / 2) / (height + Math.PI * radius));
  29246. if (stack < stacks) {
  29247. indices[ic++] = (stack * (slices + 1)) + slice + (slices + 1);
  29248. indices[ic++] = (stack * (slices + 1)) + slice;
  29249. indices[ic++] = (stack * (slices + 1)) + slice + 1;
  29250. indices[ic++] = (stack * (slices + 1)) + slice + (slices);
  29251. indices[ic++] = (stack * (slices + 1)) + slice;
  29252. indices[ic++] = (stack * (slices + 1)) + slice + (slices + 1);
  29253. }
  29254. }
  29255. }
  29256. verticeCount += (stacks + 1) * (slices + 1);
  29257. for (stack = 0; stack <= stacks; stack++) {
  29258. for (slice = 0; slice <= slices; slice++) {
  29259. posX = radius * Math.cos(stack * stackAngle) * Math.cos(slice * sliceAngle + Math.PI);
  29260. posY = radius * Math.sin(-stack * stackAngle);
  29261. posZ = radius * Math.cos(stack * stackAngle) * Math.sin(slice * sliceAngle + Math.PI);
  29262. vertices[vc++] = posX;
  29263. vertices[vc++] = posY - hcHeight;
  29264. vertices[vc++] = posZ;
  29265. vertices[vc++] = posX;
  29266. vertices[vc++] = posY;
  29267. vertices[vc++] = posZ;
  29268. vertices[vc++] = 1 - slice / slices;
  29269. vertices[vc++] = ((stack / stacks) * (Math.PI * radius / 2) + (height + Math.PI * radius / 2)) / (height + Math.PI * radius);
  29270. if (stack < stacks) {
  29271. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice;
  29272. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice + (slices + 1);
  29273. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice + 1;
  29274. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice;
  29275. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice + (slices);
  29276. indices[ic++] = verticeCount + (stack * (slices + 1)) + slice + (slices + 1);
  29277. }
  29278. }
  29279. }
  29280. verticeCount += (stacks + 1) * (slices + 1);
  29281. for (slice = 0; slice <= slices; slice++) {
  29282. posX = radius * Math.cos(slice * sliceAngle + Math.PI);
  29283. posY = hcHeight;
  29284. posZ = radius * Math.sin(slice * sliceAngle + Math.PI);
  29285. vertices[vc++] = posX;
  29286. vertices[vc + (slices + 1) * 8 - 1] = posX;
  29287. vertices[vc++] = posY;
  29288. vertices[vc + (slices + 1) * 8 - 1] = -posY;
  29289. vertices[vc++] = posZ;
  29290. vertices[vc + (slices + 1) * 8 - 1] = posZ;
  29291. vertices[vc++] = posX;
  29292. vertices[vc + (slices + 1) * 8 - 1] = posX;
  29293. vertices[vc++] = 0;
  29294. vertices[vc + (slices + 1) * 8 - 1] = 0;
  29295. vertices[vc++] = posZ;
  29296. vertices[vc + (slices + 1) * 8 - 1] = posZ;
  29297. vertices[vc++] = 1 - slice * 1 / slices;
  29298. vertices[vc + (slices + 1) * 8 - 1] = 1 - slice * 1 / slices;
  29299. vertices[vc++] = (Math.PI * radius / 2) / (height + Math.PI * radius);
  29300. vertices[vc + (slices + 1) * 8 - 1] = (Math.PI * radius / 2 + height) / (height + Math.PI * radius);
  29301. }
  29302. for (slice = 0; slice < slices; slice++) {
  29303. indices[ic++] = slice + verticeCount + (slices + 1);
  29304. indices[ic++] = slice + verticeCount + 1;
  29305. indices[ic++] = slice + verticeCount;
  29306. indices[ic++] = slice + verticeCount + (slices + 1);
  29307. indices[ic++] = slice + verticeCount + (slices + 1) + 1;
  29308. indices[ic++] = slice + verticeCount + 1;
  29309. }
  29310. verticeCount += 2 * (slices + 1);
  29311. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  29312. }
  29313. static createCone(radius = 0.5, height = 1, slices = 32) {
  29314. var vertexCount = (slices + 1 + 1) + (slices + 1) * 2;
  29315. var indexCount = 6 * slices + 3 * slices;
  29316. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  29317. var vertexFloatStride = vertexDeclaration.vertexStride / 4;
  29318. var vertices = new Float32Array(vertexCount * vertexFloatStride);
  29319. var indices = new Uint16Array(indexCount);
  29320. var sliceAngle = (Math.PI * 2.0) / slices;
  29321. var halfHeight = height / 2;
  29322. var curAngle = 0;
  29323. var verticeCount = 0;
  29324. var posX = 0;
  29325. var posY = 0;
  29326. var posZ = 0;
  29327. var normal = new Vector3();
  29328. var downV3 = new Vector3(0, -1, 0);
  29329. var upPoint = new Vector3(0, halfHeight, 0);
  29330. var downPoint = new Vector3();
  29331. var v3 = new Vector3();
  29332. var q4 = new Quaternion();
  29333. var rotateAxis = new Vector3();
  29334. var rotateRadius;
  29335. var vc = 0;
  29336. var ic = 0;
  29337. for (var rv = 0; rv <= slices; rv++) {
  29338. curAngle = rv * sliceAngle;
  29339. posX = Math.cos(curAngle + Math.PI) * radius;
  29340. posY = halfHeight;
  29341. posZ = Math.sin(curAngle + Math.PI) * radius;
  29342. vertices[vc++] = 0;
  29343. vertices[vc + (slices + 1) * 8 - 1] = posX;
  29344. vertices[vc++] = posY;
  29345. vertices[vc + (slices + 1) * 8 - 1] = -posY;
  29346. vertices[vc++] = 0;
  29347. vertices[vc + (slices + 1) * 8 - 1] = posZ;
  29348. normal.x = posX;
  29349. normal.y = 0;
  29350. normal.z = posZ;
  29351. downPoint.x = posX;
  29352. downPoint.y = -posY;
  29353. downPoint.z = posZ;
  29354. Vector3.subtract(downPoint, upPoint, v3);
  29355. Vector3.normalize(v3, v3);
  29356. rotateRadius = Math.acos(Vector3.dot(downV3, v3));
  29357. Vector3.cross(downV3, v3, rotateAxis);
  29358. Vector3.normalize(rotateAxis, rotateAxis);
  29359. Quaternion.createFromAxisAngle(rotateAxis, rotateRadius, q4);
  29360. Vector3.normalize(normal, normal);
  29361. Vector3.transformQuat(normal, q4, normal);
  29362. Vector3.normalize(normal, normal);
  29363. vertices[vc++] = normal.x;
  29364. vertices[vc + (slices + 1) * 8 - 1] = normal.x;
  29365. vertices[vc++] = normal.y;
  29366. vertices[vc + (slices + 1) * 8 - 1] = normal.y;
  29367. vertices[vc++] = normal.z;
  29368. vertices[vc + (slices + 1) * 8 - 1] = normal.z;
  29369. vertices[vc++] = 1 - rv * 1 / slices;
  29370. vertices[vc + (slices + 1) * 8 - 1] = 1 - rv * 1 / slices;
  29371. vertices[vc++] = 0;
  29372. vertices[vc + (slices + 1) * 8 - 1] = 1;
  29373. }
  29374. vc += (slices + 1) * 8;
  29375. for (var ri = 0; ri < slices; ri++) {
  29376. indices[ic++] = ri + verticeCount + (slices + 1);
  29377. indices[ic++] = ri + verticeCount + 1;
  29378. indices[ic++] = ri + verticeCount;
  29379. indices[ic++] = ri + verticeCount + (slices + 1);
  29380. indices[ic++] = ri + verticeCount + (slices + 1) + 1;
  29381. indices[ic++] = ri + verticeCount + 1;
  29382. }
  29383. verticeCount += 2 * (slices + 1);
  29384. for (var bv = 0; bv <= slices; bv++) {
  29385. if (bv === 0) {
  29386. vertices[vc++] = 0;
  29387. vertices[vc++] = -halfHeight;
  29388. vertices[vc++] = 0;
  29389. vertices[vc++] = 0;
  29390. vertices[vc++] = -1;
  29391. vertices[vc++] = 0;
  29392. vertices[vc++] = 0.5;
  29393. vertices[vc++] = 0.5;
  29394. }
  29395. curAngle = bv * sliceAngle;
  29396. posX = Math.cos(curAngle + Math.PI) * radius;
  29397. posY = -halfHeight;
  29398. posZ = Math.sin(curAngle + Math.PI) * radius;
  29399. vertices[vc++] = posX;
  29400. vertices[vc++] = posY;
  29401. vertices[vc++] = posZ;
  29402. vertices[vc++] = 0;
  29403. vertices[vc++] = -1;
  29404. vertices[vc++] = 0;
  29405. vertices[vc++] = 0.5 + Math.cos(curAngle) * 0.5;
  29406. vertices[vc++] = 0.5 + Math.sin(curAngle) * 0.5;
  29407. }
  29408. for (var bi = 0; bi < slices; bi++) {
  29409. indices[ic++] = 0 + verticeCount;
  29410. indices[ic++] = bi + 2 + verticeCount;
  29411. indices[ic++] = bi + 1 + verticeCount;
  29412. }
  29413. verticeCount += slices + 1 + 1;
  29414. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  29415. }
  29416. static createCylinder(radius = 0.5, height = 2, slices = 32) {
  29417. var vertexCount = (slices + 1 + 1) + (slices + 1) * 2 + (slices + 1 + 1);
  29418. var indexCount = 3 * slices + 6 * slices + 3 * slices;
  29419. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  29420. var vertexFloatStride = vertexDeclaration.vertexStride / 4;
  29421. var vertices = new Float32Array(vertexCount * vertexFloatStride);
  29422. var indices = new Uint16Array(indexCount);
  29423. var sliceAngle = (Math.PI * 2.0) / slices;
  29424. var halfHeight = height / 2;
  29425. var curAngle = 0;
  29426. var verticeCount = 0;
  29427. var posX = 0;
  29428. var posY = 0;
  29429. var posZ = 0;
  29430. var vc = 0;
  29431. var ic = 0;
  29432. for (var tv = 0; tv <= slices; tv++) {
  29433. if (tv === 0) {
  29434. vertices[vc++] = 0;
  29435. vertices[vc++] = halfHeight;
  29436. vertices[vc++] = 0;
  29437. vertices[vc++] = 0;
  29438. vertices[vc++] = 1;
  29439. vertices[vc++] = 0;
  29440. vertices[vc++] = 0.5;
  29441. vertices[vc++] = 0.5;
  29442. }
  29443. curAngle = tv * sliceAngle;
  29444. posX = Math.cos(curAngle) * radius;
  29445. posY = halfHeight;
  29446. posZ = Math.sin(curAngle) * radius;
  29447. vertices[vc++] = posX;
  29448. vertices[vc++] = posY;
  29449. vertices[vc++] = posZ;
  29450. vertices[vc++] = 0;
  29451. vertices[vc++] = 1;
  29452. vertices[vc++] = 0;
  29453. vertices[vc++] = 0.5 + Math.cos(curAngle) * 0.5;
  29454. vertices[vc++] = 0.5 + Math.sin(curAngle) * 0.5;
  29455. }
  29456. for (var ti = 0; ti < slices; ti++) {
  29457. indices[ic++] = 0;
  29458. indices[ic++] = ti + 1;
  29459. indices[ic++] = ti + 2;
  29460. }
  29461. verticeCount += slices + 1 + 1;
  29462. for (var rv = 0; rv <= slices; rv++) {
  29463. curAngle = rv * sliceAngle;
  29464. posX = Math.cos(curAngle + Math.PI) * radius;
  29465. posY = halfHeight;
  29466. posZ = Math.sin(curAngle + Math.PI) * radius;
  29467. vertices[vc++] = posX;
  29468. vertices[vc + (slices + 1) * 8 - 1] = posX;
  29469. vertices[vc++] = posY;
  29470. vertices[vc + (slices + 1) * 8 - 1] = -posY;
  29471. vertices[vc++] = posZ;
  29472. vertices[vc + (slices + 1) * 8 - 1] = posZ;
  29473. vertices[vc++] = posX;
  29474. vertices[vc + (slices + 1) * 8 - 1] = posX;
  29475. vertices[vc++] = 0;
  29476. vertices[vc + (slices + 1) * 8 - 1] = 0;
  29477. vertices[vc++] = posZ;
  29478. vertices[vc + (slices + 1) * 8 - 1] = posZ;
  29479. vertices[vc++] = 1 - rv * 1 / slices;
  29480. vertices[vc + (slices + 1) * 8 - 1] = 1 - rv * 1 / slices;
  29481. vertices[vc++] = 0;
  29482. vertices[vc + (slices + 1) * 8 - 1] = 1;
  29483. }
  29484. vc += (slices + 1) * 8;
  29485. for (var ri = 0; ri < slices; ri++) {
  29486. indices[ic++] = ri + verticeCount + (slices + 1);
  29487. indices[ic++] = ri + verticeCount + 1;
  29488. indices[ic++] = ri + verticeCount;
  29489. indices[ic++] = ri + verticeCount + (slices + 1);
  29490. indices[ic++] = ri + verticeCount + (slices + 1) + 1;
  29491. indices[ic++] = ri + verticeCount + 1;
  29492. }
  29493. verticeCount += 2 * (slices + 1);
  29494. for (var bv = 0; bv <= slices; bv++) {
  29495. if (bv === 0) {
  29496. vertices[vc++] = 0;
  29497. vertices[vc++] = -halfHeight;
  29498. vertices[vc++] = 0;
  29499. vertices[vc++] = 0;
  29500. vertices[vc++] = -1;
  29501. vertices[vc++] = 0;
  29502. vertices[vc++] = 0.5;
  29503. vertices[vc++] = 0.5;
  29504. }
  29505. curAngle = bv * sliceAngle;
  29506. posX = Math.cos(curAngle + Math.PI) * radius;
  29507. posY = -halfHeight;
  29508. posZ = Math.sin(curAngle + Math.PI) * radius;
  29509. vertices[vc++] = posX;
  29510. vertices[vc++] = posY;
  29511. vertices[vc++] = posZ;
  29512. vertices[vc++] = 0;
  29513. vertices[vc++] = -1;
  29514. vertices[vc++] = 0;
  29515. vertices[vc++] = 0.5 + Math.cos(curAngle) * 0.5;
  29516. vertices[vc++] = 0.5 + Math.sin(curAngle) * 0.5;
  29517. }
  29518. for (var bi = 0; bi < slices; bi++) {
  29519. indices[ic++] = 0 + verticeCount;
  29520. indices[ic++] = bi + 2 + verticeCount;
  29521. indices[ic++] = bi + 1 + verticeCount;
  29522. }
  29523. verticeCount += slices + 1 + 1;
  29524. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  29525. }
  29526. static createPlane(long = 10, width = 10, stacks = 10, slices = 10) {
  29527. var vertexCount = (stacks + 1) * (slices + 1);
  29528. var indexCount = stacks * slices * 2 * 3;
  29529. var indices = new Uint16Array(indexCount);
  29530. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  29531. var vertexFloatStride = vertexDeclaration.vertexStride / 4;
  29532. var vertices = new Float32Array(vertexCount * vertexFloatStride);
  29533. var halfLong = long / 2;
  29534. var halfWidth = width / 2;
  29535. var stacksLong = long / stacks;
  29536. var slicesWidth = width / slices;
  29537. var verticeCount = 0;
  29538. for (var i = 0; i <= slices; i++) {
  29539. for (var j = 0; j <= stacks; j++) {
  29540. vertices[verticeCount++] = j * stacksLong - halfLong;
  29541. vertices[verticeCount++] = 0;
  29542. vertices[verticeCount++] = i * slicesWidth - halfWidth;
  29543. vertices[verticeCount++] = 0;
  29544. vertices[verticeCount++] = 1;
  29545. vertices[verticeCount++] = 0;
  29546. vertices[verticeCount++] = j * 1 / stacks;
  29547. vertices[verticeCount++] = i * 1 / slices;
  29548. }
  29549. }
  29550. var indiceIndex = 0;
  29551. for (i = 0; i < slices; i++) {
  29552. for (j = 0; j < stacks; j++) {
  29553. indices[indiceIndex++] = (i + 1) * (stacks + 1) + j;
  29554. indices[indiceIndex++] = i * (stacks + 1) + j;
  29555. indices[indiceIndex++] = (i + 1) * (stacks + 1) + j + 1;
  29556. indices[indiceIndex++] = i * (stacks + 1) + j;
  29557. indices[indiceIndex++] = i * (stacks + 1) + j + 1;
  29558. indices[indiceIndex++] = (i + 1) * (stacks + 1) + j + 1;
  29559. }
  29560. }
  29561. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  29562. }
  29563. static createQuad(long = 1, width = 1) {
  29564. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  29565. var halfLong = long / 2;
  29566. var halfWidth = width / 2;
  29567. var vertices = new Float32Array([-halfLong, halfWidth, 0, 0, 0, 1, 0, 0, halfLong, halfWidth, 0, 0, 0, 1, 1, 0, -halfLong, -halfWidth, 0, 0, 0, 1, 0, 1, halfLong, -halfWidth, 0, 0, 0, 1, 1, 1]);
  29568. var indices = new Uint16Array([0, 1, 2, 3, 2, 1]);
  29569. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  29570. }
  29571. static createSphere(radius = 0.5, stacks = 32, slices = 32) {
  29572. var vertexCount = (stacks + 1) * (slices + 1);
  29573. var indexCount = (3 * stacks * (slices + 1)) * 2;
  29574. var indices = new Uint16Array(indexCount);
  29575. var vertexDeclaration = VertexMesh.getVertexDeclaration("POSITION,NORMAL,UV");
  29576. var vertexFloatStride = vertexDeclaration.vertexStride / 4;
  29577. var vertices = new Float32Array(vertexCount * vertexFloatStride);
  29578. var stackAngle = Math.PI / stacks;
  29579. var sliceAngle = (Math.PI * 2.0) / slices;
  29580. var vertexIndex = 0;
  29581. vertexCount = 0;
  29582. indexCount = 0;
  29583. for (var stack = 0; stack < (stacks + 1); stack++) {
  29584. var r = Math.sin(stack * stackAngle);
  29585. var y = Math.cos(stack * stackAngle);
  29586. for (var slice = 0; slice < (slices + 1); slice++) {
  29587. var x = r * Math.sin(slice * sliceAngle + Math.PI * 1 / 2);
  29588. var z = r * Math.cos(slice * sliceAngle + Math.PI * 1 / 2);
  29589. vertices[vertexCount + 0] = x * radius;
  29590. vertices[vertexCount + 1] = y * radius;
  29591. vertices[vertexCount + 2] = z * radius;
  29592. vertices[vertexCount + 3] = x;
  29593. vertices[vertexCount + 4] = y;
  29594. vertices[vertexCount + 5] = z;
  29595. vertices[vertexCount + 6] = slice / slices;
  29596. vertices[vertexCount + 7] = stack / stacks;
  29597. vertexCount += vertexFloatStride;
  29598. if (stack != (stacks - 1)) {
  29599. indices[indexCount++] = vertexIndex + (slices + 1);
  29600. indices[indexCount++] = vertexIndex;
  29601. indices[indexCount++] = vertexIndex + 1;
  29602. indices[indexCount++] = vertexIndex + (slices);
  29603. indices[indexCount++] = vertexIndex;
  29604. indices[indexCount++] = vertexIndex + (slices + 1);
  29605. vertexIndex++;
  29606. }
  29607. }
  29608. }
  29609. return PrimitiveMesh._createMesh(vertexDeclaration, vertices, indices);
  29610. }
  29611. }
  29612. var BlitScreenPS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\nuniform sampler2D u_MainTex;\r\nvarying vec2 v_Texcoord0;\r\n\r\nvoid main() {\r\n\tgl_FragColor = texture2D(u_MainTex, v_Texcoord0);\r\n}\r\n\r\n";
  29613. var BlitScreenVS = "#include \"Lighting.glsl\";\r\n#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\nattribute vec4 a_PositionTexcoord;\r\nuniform vec4 u_OffsetScale;\r\nvarying vec2 v_Texcoord0;\r\n\r\nvoid main() {\t\r\n\tgl_Position = vec4(u_OffsetScale.x*2.0-1.0+(a_PositionTexcoord.x+1.0)*u_OffsetScale.z,(1.0-((u_OffsetScale.y*2.0-1.0+(-a_PositionTexcoord.y+1.0)*u_OffsetScale.w)+1.0)/2.0)*2.0-1.0, 0.0, 1.0);\t\r\n\tv_Texcoord0 = a_PositionTexcoord.zw;\r\n\tgl_Position = remapGLPositionZ(gl_Position);\r\n}";
  29614. var EffectPS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#ifdef COLOR\r\n\tvarying vec4 v_Color;\r\n#endif\r\nvarying vec2 v_Texcoord0;\r\n\r\n#ifdef MAINTEXTURE\r\n\tuniform sampler2D u_AlbedoTexture;\r\n#endif\r\n\r\nuniform vec4 u_AlbedoColor;\r\n\r\n#ifdef FOG\r\n\tuniform float u_FogStart;\r\n\tuniform float u_FogRange;\r\n\t#ifdef ADDTIVEFOG\r\n\t#else\r\n\t\tuniform vec3 u_FogColor;\r\n\t#endif\r\n#endif\r\n\r\nvoid main()\r\n{\r\n\tvec4 color = 2.0 * u_AlbedoColor;\r\n\t#ifdef COLOR\r\n\t\tcolor *= v_Color;\r\n\t#endif\r\n\t#ifdef MAINTEXTURE\r\n\t\tcolor *= texture2D(u_AlbedoTexture, v_Texcoord0);\r\n\t#endif\r\n\t\r\n\tgl_FragColor = color;\r\n\t\r\n\t#ifdef FOG\r\n\t\tfloat lerpFact = clamp((1.0 / gl_FragCoord.w - u_FogStart) / u_FogRange, 0.0, 1.0);\r\n\t\t#ifdef ADDTIVEFOG\r\n\t\t\tgl_FragColor.rgb = mix(gl_FragColor.rgb, vec3(0.0), lerpFact);\r\n\t\t#else\r\n\t\t\tgl_FragColor.rgb = mix(gl_FragColor.rgb, u_FogColor, lerpFact);\r\n\t\t#endif\r\n\t#endif\r\n}\r\n\r\n";
  29615. var EffectVS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n#include \"Lighting.glsl\";\r\n#include \"LayaUtile.glsl\";\r\n\r\nattribute vec4 a_Position;\r\nattribute vec4 a_Color;\r\nattribute vec2 a_Texcoord0;\r\n\r\n#ifdef GPU_INSTANCE\r\n\tattribute mat4 a_MvpMatrix;\r\n#else\r\n\tuniform mat4 u_MvpMatrix;\r\n#endif\r\n\r\n#ifdef COLOR\r\n\tvarying vec4 v_Color;\r\n#endif\r\nvarying vec2 v_Texcoord0;\r\n\r\n#ifdef TILINGOFFSET\r\n\tuniform vec4 u_TilingOffset;\r\n#endif\r\n\r\n#ifdef BONE\r\n\tconst int c_MaxBoneCount = 24;\r\n\tattribute vec4 a_BoneIndices;\r\n\tattribute vec4 a_BoneWeights;\r\n\tuniform mat4 u_Bones[c_MaxBoneCount];\r\n#endif\r\n\r\n\r\nvoid main()\r\n{\r\n\tvec4 position;\r\n\t#ifdef BONE\r\n\t\tmat4 skinTransform;\r\n\t \t#ifdef SIMPLEBONE\r\n\t\t\tfloat currentPixelPos;\r\n\t\t\t#ifdef GPU_INSTANCE\r\n\t\t\t\tcurrentPixelPos = a_SimpleTextureParams.x+a_SimpleTextureParams.y;\r\n\t\t\t#else\r\n\t\t\t\tcurrentPixelPos = u_SimpleAnimatorParams.x+u_SimpleAnimatorParams.y;\r\n\t\t\t#endif\r\n\t\t\tfloat offset = 1.0/u_SimpleAnimatorTextureSize;\r\n\t\t\tskinTransform = loadMatFromTexture(currentPixelPos,int(a_BoneIndices.x),offset) * a_BoneWeights.x;\r\n\t\t\tskinTransform += loadMatFromTexture(currentPixelPos,int(a_BoneIndices.y),offset) * a_BoneWeights.y;\r\n\t\t\tskinTransform += loadMatFromTexture(currentPixelPos,int(a_BoneIndices.z),offset) * a_BoneWeights.z;\r\n\t\t\tskinTransform += loadMatFromTexture(currentPixelPos,int(a_BoneIndices.w),offset) * a_BoneWeights.w;\r\n\t\t#else\r\n\t\t\tskinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;\r\n\t\t\tskinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;\r\n\t\t\tskinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;\r\n\t\t\tskinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;\r\n\t\t#endif\r\n\t\tposition=skinTransform*a_Position;\r\n\t #else\r\n\t\tposition=a_Position;\r\n\t#endif\r\n\t#ifdef GPU_INSTANCE\r\n\t\tgl_Position = a_MvpMatrix * position;\r\n\t#else\r\n\t\tgl_Position = u_MvpMatrix * position;\r\n\t#endif\r\n\t\r\n\t#ifdef TILINGOFFSET\r\n\t\tv_Texcoord0=TransformUV(a_Texcoord0,u_TilingOffset);\r\n\t#else\r\n\t\tv_Texcoord0=a_Texcoord0;\r\n\t#endif\r\n\t\t\r\n\t#ifdef COLOR\r\n\t\tv_Color = a_Color;\r\n\t#endif\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}";
  29616. var extendTerrainPS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#include \"Lighting.glsl\";\r\n\r\n#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(FOG)\r\n\tuniform vec3 u_CameraPos;\r\n\tvarying vec3 v_Normal;\r\n\tvarying vec3 v_PositionWorld;\r\n#endif\r\n\r\n#ifdef FOG\r\n\tuniform float u_FogStart;\r\n\tuniform float u_FogRange;\r\n\tuniform vec3 u_FogColor;\r\n#endif\r\n\r\n#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t#ifdef LEGACYSINGLELIGHTING\r\n\t\t#ifdef DIRECTIONLIGHT\r\n\t\t\tuniform DirectionLight u_DirectionLight;\r\n\t\t#endif\r\n\t\t#ifdef POINTLIGHT\r\n\t\t\tuniform PointLight u_PointLight;\r\n\t\t#endif\r\n\t\t#ifdef SPOTLIGHT\r\n\t\t\tuniform SpotLight u_SpotLight;\r\n\t\t#endif\r\n\t#else\r\n\t\tuniform mat4 u_View;\r\n\t\tuniform vec4 u_ProjectionParams;\r\n\t\tuniform vec4 u_Viewport;\r\n\t\tuniform int u_DirationLightCount;\r\n\t\tuniform sampler2D u_LightBuffer;\r\n\t\tuniform sampler2D u_LightClusterBuffer;\r\n\t#endif\r\n#endif\r\n\r\n#include \"Shadow.glsl\"\r\n#if defined(CALCULATE_SHADOWS)//shader中自定义的宏不可用ifdef 必须改成if defined\r\n\tvarying vec4 v_ShadowCoord;\r\n#endif\r\nvarying float v_posViewZ;\r\n\r\nuniform vec3 u_AmbientColor;\r\n\r\nuniform sampler2D u_SplatAlphaTexture;\r\n\r\nuniform sampler2D u_DiffuseTexture1;\r\nuniform sampler2D u_DiffuseTexture2;\r\nuniform sampler2D u_DiffuseTexture3;\r\nuniform sampler2D u_DiffuseTexture4;\r\nuniform sampler2D u_DiffuseTexture5;\r\n\r\nuniform vec4 u_DiffuseScaleOffset1;\r\nuniform vec4 u_DiffuseScaleOffset2;\r\nuniform vec4 u_DiffuseScaleOffset3;\r\nuniform vec4 u_DiffuseScaleOffset4;\r\nuniform vec4 u_DiffuseScaleOffset5;\r\n\r\nvarying vec2 v_Texcoord0;\r\n\r\n#ifdef LIGHTMAP\r\n\tuniform sampler2D u_LightMap;\r\n\tvarying vec2 v_LightMapUV;\r\n#endif\r\n\r\nvoid main()\r\n{\r\n\tvec4 splatAlpha = vec4(1.0);\r\n\t#ifdef ExtendTerrain_DETAIL_NUM1\r\n\t\tsplatAlpha = texture2D(u_SplatAlphaTexture, v_Texcoord0);\r\n\t\tvec4 color1 = texture2D(u_DiffuseTexture1, v_Texcoord0 * u_DiffuseScaleOffset1.xy);\r\n\t\tgl_FragColor.xyz = color1.xyz * splatAlpha.r;\r\n\t#endif\r\n\t#ifdef ExtendTerrain_DETAIL_NUM2\r\n\t\tsplatAlpha = texture2D(u_SplatAlphaTexture, v_Texcoord0);\r\n\t\tvec4 color1 = texture2D(u_DiffuseTexture1, v_Texcoord0 * u_DiffuseScaleOffset1.xy);\r\n\t\tvec4 color2 = texture2D(u_DiffuseTexture2, v_Texcoord0 * u_DiffuseScaleOffset2.xy);\r\n\t\tgl_FragColor.xyz = color1.xyz * splatAlpha.r + color2.xyz * (1.0 - splatAlpha.r);\r\n\t#endif\r\n\t#ifdef ExtendTerrain_DETAIL_NUM3\r\n\t\tsplatAlpha = texture2D(u_SplatAlphaTexture, v_Texcoord0);\r\n\t\tvec4 color1 = texture2D(u_DiffuseTexture1, v_Texcoord0 * u_DiffuseScaleOffset1.xy);\r\n\t\tvec4 color2 = texture2D(u_DiffuseTexture2, v_Texcoord0 * u_DiffuseScaleOffset2.xy);\r\n\t\tvec4 color3 = texture2D(u_DiffuseTexture3, v_Texcoord0 * u_DiffuseScaleOffset3.xy);\r\n\t\tgl_FragColor.xyz = color1.xyz * splatAlpha.r + color2.xyz * splatAlpha.g + color3.xyz * (1.0 - splatAlpha.r - splatAlpha.g);\r\n\t#endif\r\n\t#ifdef ExtendTerrain_DETAIL_NUM4\r\n\t\tsplatAlpha = texture2D(u_SplatAlphaTexture, v_Texcoord0);\r\n\t\tvec4 color1 = texture2D(u_DiffuseTexture1, v_Texcoord0 * u_DiffuseScaleOffset1.xy);\r\n\t\tvec4 color2 = texture2D(u_DiffuseTexture2, v_Texcoord0 * u_DiffuseScaleOffset2.xy);\r\n\t\tvec4 color3 = texture2D(u_DiffuseTexture3, v_Texcoord0 * u_DiffuseScaleOffset3.xy);\r\n\t\tvec4 color4 = texture2D(u_DiffuseTexture4, v_Texcoord0 * u_DiffuseScaleOffset4.xy);\r\n\t\tgl_FragColor.xyz = color1.xyz * splatAlpha.r + color2.xyz * splatAlpha.g + color3.xyz * splatAlpha.b + color4.xyz * (1.0 - splatAlpha.r - splatAlpha.g - splatAlpha.b);\r\n\t#endif\r\n\t#ifdef ExtendTerrain_DETAIL_NUM5\r\n\t\tsplatAlpha = texture2D(u_SplatAlphaTexture, v_Texcoord0);\r\n\t\tvec4 color1 = texture2D(u_DiffuseTexture1, v_Texcoord0 * u_DiffuseScaleOffset1.xy);\r\n\t\tvec4 color2 = texture2D(u_DiffuseTexture2, v_Texcoord0 * u_DiffuseScaleOffset2.xy);\r\n\t\tvec4 color3 = texture2D(u_DiffuseTexture3, v_Texcoord0 * u_DiffuseScaleOffset3.xy);\r\n\t\tvec4 color4 = texture2D(u_DiffuseTexture4, v_Texcoord0 * u_DiffuseScaleOffset4.xy);\r\n\t\tvec4 color5 = texture2D(u_DiffuseTexture5, v_Texcoord0 * u_DiffuseScaleOffset5.xy);\r\n\t\tgl_FragColor.xyz = color1.xyz * splatAlpha.r + color2.xyz * splatAlpha.g + color3.xyz * splatAlpha.b + color4.xyz * splatAlpha.a + color5.xyz * (1.0 - splatAlpha.r - splatAlpha.g - splatAlpha.b - splatAlpha.a);\r\n\t#endif\r\n\t\tgl_FragColor.w = splatAlpha.a;\r\n\t\t\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\tvec3 normal = v_Normal;\r\n\t\tvec3 dif, spe;\r\n\t#endif\r\n\r\n\tvec3 diffuse = vec3(0.0);\r\n\tvec3 specular= vec3(0.0);\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(FOG)\r\n\t\tvec3 toEye;\r\n\t\t#ifdef FOG\r\n\t\t\ttoEye=u_CameraPos-v_PositionWorld;\r\n\t\t\tfloat toEyeLength=length(toEye);\r\n\t\t\ttoEye/=toEyeLength;\r\n\t\t#else\r\n\t\t\ttoEye=normalize(u_CameraPos-v_PositionWorld);\r\n\t\t#endif\r\n\t#endif\r\n\r\n\t#ifdef LEGACYSINGLELIGHTING\r\n\t\t#ifdef DIRECTIONLIGHT\r\n\t\t\tLayaAirBlinnPhongDiectionLight(vec3(0.0),1.0,normal,vec3(1.0),toEye,u_DirectionLight,dif,spe);\r\n\t\t\tdiffuse+=dif;\r\n\t\t\tspecular+=spe;\r\n\t\t#endif\r\n\t\r\n\t\t#ifdef POINTLIGHT\r\n\t\t\tLayaAirBlinnPhongPointLight(v_PositionWorld,vec3(0.0),1.0,normal,vec3(1.0),toEye,u_PointLight,dif,spe);\r\n\t\t\tdiffuse+=dif;\r\n\t\t\tspecular+=spe;\r\n\t\t#endif\r\n\r\n\t\t#ifdef SPOTLIGHT\r\n\t\t\tLayaAirBlinnPhongSpotLight(v_PositionWorld,vec3(0.0),1.0,normal,vec3(1.0),toEye,u_SpotLight,dif,spe);\r\n\t\t\tdiffuse+=dif;\r\n\t\t\tspecular+=spe;\r\n\t\t#endif\r\n\t#else\r\n\t\t#ifdef DIRECTIONLIGHT\r\n\t\t\tfor (int i = 0; i < MAX_LIGHT_COUNT; i++) \r\n\t\t\t{\r\n\t\t\t\tif(i >= u_DirationLightCount)\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tDirectionLight directionLight = getDirectionLight(u_LightBuffer,i);\r\n\t\t\t\tLayaAirBlinnPhongDiectionLight(vec3(0.0),1.0,normal,vec3(1.0),toEye,directionLight,dif,spe);\r\n\t\t\t\tdiffuse+=dif;\r\n\t\t\t\tspecular+=spe;\r\n\t\t\t}\r\n\t\t#endif\r\n\t\t#if defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\t\tivec4 clusterInfo =getClusterInfo(u_LightClusterBuffer,u_View,u_Viewport, v_PositionWorld,gl_FragCoord,u_ProjectionParams);\r\n\t\t\t#ifdef POINTLIGHT\r\n\t\t\t\tfor (int i = 0; i < MAX_LIGHT_COUNT; i++) \r\n\t\t\t\t{\r\n\t\t\t\t\tif(i >= clusterInfo.x)//PointLightCount\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tPointLight pointLight = getPointLight(u_LightBuffer,u_LightClusterBuffer,clusterInfo,i);\r\n\t\t\t\t\tLayaAirBlinnPhongPointLight(v_PositionWorld,vec3(0.0),1.0,normal,vec3(1.0),toEye,pointLight,dif,spe);\r\n\t\t\t\t\tdiffuse+=dif;\r\n\t\t\t\t\tspecular+=spe;\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t\t#ifdef SPOTLIGHT\r\n\t\t\t\tfor (int i = 0; i < MAX_LIGHT_COUNT; i++) \r\n\t\t\t\t{\r\n\t\t\t\t\tif(i >= clusterInfo.y)//SpotLightCount\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tSpotLight spotLight = getSpotLight(u_LightBuffer,u_LightClusterBuffer,clusterInfo,i);\r\n\t\t\t\t\tLayaAirBlinnPhongSpotLight(v_PositionWorld,vec3(0.0),1.0,normal,vec3(1.0),toEye\t,spotLight,dif,spe);\r\n\t\t\t\t\tdiffuse+=dif;\r\n\t\t\t\t\tspecular+=spe;\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t#endif\r\n\r\nvec3 globalDiffuse = u_AmbientColor;\r\n#ifdef LIGHTMAP\r\n\tglobalDiffuse += decodeHDR(texture2D(u_LightMap, v_LightMapUV),5.0);\r\n#endif\r\n\r\n#if defined(CALCULATE_SHADOWS)//shader中自定义的宏不可用ifdef 必须改成if defined\r\n\tfloat shadowValue = shadowValue = sampleShadowmap(v_ShadowCoord);\r\n\tgl_FragColor = vec4(gl_FragColor.rgb * (globalDiffuse + diffuse) * shadowValue, gl_FragColor.a);\r\n#else\r\n\tgl_FragColor = vec4(gl_FragColor.rgb * (globalDiffuse + diffuse), gl_FragColor.a);\r\n#endif\r\n\r\n#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t#if defined(CALCULATE_SHADOWS)//shader中自定义的宏不可用ifdef 必须改成if defined\r\n\t\tgl_FragColor.rgb += specular * shadowValue;\r\n\t#else\r\n\t\tgl_FragColor.rgb += specular;\r\n\t#endif\r\n#endif\r\n\r\n#ifdef FOG\r\n\tfloat lerpFact=clamp((toEyeLength-u_FogStart)/u_FogRange,0.0,1.0);\r\n\tgl_FragColor.rgb=mix(gl_FragColor.rgb,u_FogColor,lerpFact);\r\n#endif\r\n}\r\n\r\n\r\n\r\n\r\n\r\n";
  29617. var extendTerrainVS = "#include \"Lighting.glsl\";\r\n\r\nattribute vec4 a_Position;\r\nattribute vec2 a_Texcoord0;\r\n\r\nuniform mat4 u_MvpMatrix;\r\n\r\nvarying vec2 v_Texcoord0;\r\n\r\n#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(LIGHTMAP)\r\n\tattribute vec3 a_Normal;\r\n\tvarying vec3 v_Normal;\r\n#endif\r\n\r\n#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(FOG)||(defined(CALCULATE_SHADOWS)&&defined(SHADOWMAP_PSSM1))\r\n\tuniform mat4 u_WorldMat;\r\n\tvarying vec3 v_PositionWorld;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvarying vec2 v_LightMapUV;\r\n\tuniform vec4 u_LightmapScaleOffset;\r\n#endif\r\n\r\n#if defined(CALCULATE_SHADOWS)//shader���Զ���ĺ겻����ifdef ����ij�if defined\r\n\tvarying vec4 v_ShadowCoord;\r\n#endif\r\n\r\nvoid main()\r\n{\r\n\tgl_Position = u_MvpMatrix * a_Position;\r\n \r\n\tv_Texcoord0 = a_Texcoord0;\r\n \r\n\t#ifdef LIGHTMAP\r\n\t\tv_LightMapUV = vec2(a_Texcoord0.x, 1.0 - a_Texcoord0.y) * u_LightmapScaleOffset.xy + u_LightmapScaleOffset.zw;\r\n\t\tv_LightMapUV.y = 1.0 - v_LightMapUV.y;\r\n\t#endif\r\n \r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\tv_Normal = a_Normal;\r\n\t#endif\r\n\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||defined(FOG)||(defined(CALCULATE_SHADOWS)&&defined(SHADOWMAP_PSSM1))\r\n\t\tv_PositionWorld=(u_WorldMat*a_Position).xyz;\r\n\t#endif\r\n\r\n\t#if defined(CALCULATE_SHADOWS)//shader���Զ���ĺ겻����ifdef ����ij�if defined\r\n\t\tv_ShadowCoord = getShadowCoord(vec4(v_PositionWorld));\r\n\t#endif\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}";
  29618. var GlobalIllumination = "struct LayaGIInput\r\n{\r\n\tvec2 lightmapUV;\r\n\tvec3 worldPos;\r\n};\r\n\r\n#define LAYA_SPECCUBE_LOD_STEPS 6.0\r\n\r\nuniform vec3 u_AmbientColor;\r\n\r\n#if defined(GI_AMBIENT_SH)\r\n\tuniform vec4 u_AmbientSHAr;\r\n\tuniform vec4 u_AmbientSHAg;\r\n\tuniform vec4 u_AmbientSHAb;\r\n\tuniform vec4 u_AmbientSHBr;\r\n\tuniform vec4 u_AmbientSHBg;\r\n\tuniform vec4 u_AmbientSHBb;\r\n\tuniform vec4 u_AmbientSHC;\r\n#endif\r\n\r\nuniform samplerCube u_ReflectTexture;\r\nuniform vec4 u_ReflectCubeHDRParams;\r\n\r\n#ifdef SPECCUBE_BOX_PROJECTION\r\n\tuniform vec3 u_SpecCubeProbePosition;\r\n\tuniform vec3 u_SpecCubeBoxMax;\r\n\tuniform vec3 u_SpecCubeBoxMin;\r\n#endif\r\n\r\n\r\n#ifdef GI_AMBIENT_SH\r\n\tmediump vec3 shEvalLinearL0L1(mediump vec4 normal)\r\n\t{\r\n\t\tmediump vec3 x;\r\n\t\t// Linear (L1) + constant (L0) polynomial terms\r\n\t\tx.r = dot(u_AmbientSHAr, normal);\r\n\t\tx.g = dot(u_AmbientSHAg, normal);\r\n\t\tx.b = dot(u_AmbientSHAb, normal);\r\n\t\treturn x;\r\n\t}\r\n\r\n\tmediump vec3 shEvalLinearL2(mediump vec4 normal)\r\n\t{\r\n\t\tmediump vec3 x1,x2;\r\n\t\t// 4 of the quadratic (L2) polynomials\r\n\t\tmediump vec4 vB = normal.xyzz * normal.yzzx;\r\n\t\tx1.r = dot(u_AmbientSHBr, vB);\r\n\t\tx1.g = dot(u_AmbientSHBg, vB);\r\n\t\tx1.b = dot(u_AmbientSHBb, vB);\r\n\r\n\t\t// Final (5th) quadratic (L2) polynomial\r\n\t\tmediump float vC = normal.x*normal.x - normal.y*normal.y;\r\n\t\tx2 = u_AmbientSHC.rgb * vC;\r\n\r\n\t\treturn x1 + x2;\r\n\t}\r\n\t\r\n\tmediump vec3 shadeSHPerPixel(mediump vec3 normal)\r\n\t{\r\n\t\tmediump vec3 ambientContrib;\r\n\t\tmediump vec4 normalV4=vec4(-normal.x,normal.yz, 1.0);//Note:SH Data is left-hand,so x need inverse\r\n\t\tambientContrib = shEvalLinearL0L1(normalV4);\r\n\t\tambientContrib += shEvalLinearL2(normalV4);\r\n\t\tmediump vec3 ambient = max(vec3(0.0), ambientContrib);\r\n\t\tambient = layaLinearToGammaSpace(ambient);\r\n\t\treturn ambient;\r\n\t}\r\n#endif\r\n\r\n\r\n\r\n mediump vec3 BoxProjectedCubemapDirection(mediump vec3 worldRefl,mediump vec3 worldPos,mediump vec3 cubemapCenter,mediump vec3 boxMin,mediump vec3 boxMax){\r\n\t mediump vec3 nrdir = normalize(worldRefl);\r\n\t mediump vec3 rbmax = (boxMax - worldPos);\r\n\t mediump vec3 rbmin = (boxMin - worldPos);\r\n\t mediump vec3 select = step(vec3(0.0), worldRefl);\r\n\t mediump vec3 rbminmax = mix(rbmin, rbmax, select);\r\n\trbminmax = rbminmax / nrdir;\r\n\tmediump float scalar = min(min(rbminmax.x, rbminmax.y), rbminmax.z);\r\n\t mediump vec3 worldChangeRefl = nrdir * scalar + (worldPos - cubemapCenter);\r\n\treturn worldChangeRefl;\r\n}\r\n\r\n\r\nmediump vec3 layaDecodeDirectionalLightmap (mediump vec3 color, lowp vec4 dirTex, mediump vec3 normalWorld)\r\n{\r\n // In directional (non-specular) mode Enlighten bakes dominant light direction\r\n // in a way, that using it for half Lambert and then dividing by a \"rebalancing coefficient\"\r\n // gives a result close to plain diffuse response lightmaps, but normalmapped.\r\n\r\n // Note that dir is not unit length on purpose. Its length is \"directionality\", like\r\n // for the directional specular lightmaps.\r\n\tlowp vec3 directional=dirTex.xyz - 0.5;\r\n\tdirectional.x=-directional.x;//NOTE:because coord System\r\n mediump float halfLambert = dot(normalWorld,directional) + 0.5;\r\n\r\n return color * halfLambert / max(1e-4, dirTex.w);\r\n}\r\n\r\nvec3 layaGIBase(LayaGIInput giInput,mediump float occlusion, mediump vec3 normalWorld)\r\n{\r\n\tvec3 indirectDiffuse;\r\n\t#ifdef LIGHTMAP\t\r\n\t\tmediump vec3 bakedColor =decodeHDR(texture2D(u_LightMap, giInput.lightmapUV),5.0);\r\n\t\t#ifdef LIGHTMAP_DIRECTIONAL\r\n\t\t\tlowp vec4 bakedDirTex = texture2D (u_LightMapDirection, giInput.lightmapUV);\r\n indirectDiffuse = layaDecodeDirectionalLightmap (bakedColor, bakedDirTex, normalWorld);\r\n\t\t#else //unDirectional lightmap\r\n\t\t\tindirectDiffuse = bakedColor;\r\n\t\t#endif\r\n\t#else\r\n\t\t#ifdef GI_AMBIENT_SH\r\n\t\t\tindirectDiffuse = shadeSHPerPixel(normalWorld);\r\n\t\t#else\r\n\t\t\tindirectDiffuse = u_AmbientColor; //already in gamma space\r\n\t\t#endif\r\n\t#endif\r\n\r\n\tindirectDiffuse*=occlusion;\r\n\treturn indirectDiffuse;\r\n}\r\n\r\nmediump vec3 layaGlossyEnvironment(mediump vec4 glossIn)\r\n{\r\n\tmediump float perceptualRoughness = glossIn.a;\r\n\r\n\t// use approximation to solve,below is more reasonable,but maybe slow. \r\n\t// float m = perceptualRoughnessToRoughness(perceptualRoughness); // m is the real roughness parameter\r\n // const float fEps = 1.192092896e-07F; // smallest such that 1.0+FLT_EPSILON != 1.0 (+1e-4h is NOT good here. is visibly very wrong)\r\n // float n = (2.0/max(fEps, m*m))-2.0; // remap to spec power. See eq. 21 in --> https://dl.dropboxusercontent.com/u/55891920/papers/mm_brdf.pdf\r\n // n /= 4; // remap from n_dot_h formulatino to n_dot_r. See section \"Pre-convolved Cube Maps vs Path Tracers\" --> https://s3.amazonaws.com/docs.knaldtech.com/knald/1.0.0/lys_power_drops.html\r\n // perceptualRoughness = pow( 2/(n+2), 0.25); // remap back to square root of real roughness (0.25 include both the sqrt root of the conversion and sqrt for going from roughness to perceptualRoughness)\r\n\tperceptualRoughness = perceptualRoughness * (1.7 - 0.7*perceptualRoughness);//just a approximation,but fast.\r\n \r\n\tmediump float mip = perceptualRoughness * LAYA_SPECCUBE_LOD_STEPS;\r\n\tmediump vec3 uvw = glossIn.rgb;\r\n\tuvw.x=-uvw.x;//Note:reflectCube is left-hand,so x need inverse\r\n\tmediump vec4 rgbm=textureCubeLodEXT(u_ReflectTexture,uvw,mip);\r\n\treturn decodeHDR(rgbm,u_ReflectCubeHDRParams.x);\r\n}\r\n\r\nmediump vec3 layaGIIndirectSpecular(LayaGIInput giInput,mediump float occlusion, vec4 glossIn)\r\n{\r\n\t#ifdef SPECCUBE_BOX_PROJECTION\r\n\t\tvec3 originalReflUVW = glossIn.xyz;\r\n\t\tglossIn.xyz =BoxProjectedCubemapDirection(originalReflUVW,giInput.worldPos,u_SpecCubeProbePosition,u_SpecCubeBoxMin,u_SpecCubeBoxMax);\r\n\t#endif\r\n\tmediump vec3 specular = layaGlossyEnvironment(glossIn);\r\n\treturn specular * occlusion;\r\n}\r\n\r\n\r\nLayaGI layaGlobalIllumination(LayaGIInput giInput,mediump float occlusion, mediump vec3 normalWorld,mediump vec4 uvwRoughness)\r\n{\r\n\tLayaGI gi;\r\n\tgi.diffuse = layaGIBase(giInput,occlusion, normalWorld);\r\n\tgi.specular = layaGIIndirectSpecular(giInput,occlusion, uvwRoughness);\r\n\treturn gi;\r\n}\r\n\r\n\r\n";
  29619. var LightingGLSL = "#ifdef GRAPHICS_API_GLES3\r\n\t#define INVERSE_MAT(mat) inverse(mat)\r\n#else\r\n\t#define INVERSE_MAT(mat) inverseMat(mat)\r\n#endif\r\n\r\nstruct DirectionLight {\r\n\tvec3 color;\r\n\tvec3 direction;\r\n};\r\n\r\nstruct PointLight {\r\n\tvec3 color;\r\n\tvec3 position;\r\n\tfloat range;\r\n};\r\n\r\nstruct SpotLight {\r\n\tvec3 color;\r\n\tvec3 position;\r\n\tfloat range;\r\n\tvec3 direction;\r\n\tfloat spot;\r\n};\r\n\r\nstruct LayaGI{\r\n\tvec3 diffuse;\r\n\tvec3 specular;\r\n};\r\n\r\nstruct LayaLight{\r\n\tvec3 color;\r\n\tvec3 dir;\r\n};\r\n\r\nconst int c_ClusterBufferWidth = CLUSTER_X_COUNT*CLUSTER_Y_COUNT;\r\nconst int c_ClusterBufferHeight = CLUSTER_Z_COUNT*(1+int(ceil(float(MAX_LIGHT_COUNT_PER_CLUSTER)/4.0)));\r\nconst int c_ClusterBufferFloatWidth = c_ClusterBufferWidth*4;\r\n\r\n#ifndef GRAPHICS_API_GLES3\r\n\tmat3 inverseMat(mat3 m) {\r\n\t\tfloat a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];\r\n\t\tfloat a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];\r\n\t\tfloat a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];\r\n\r\n\t\tfloat b01 = a22 * a11 - a12 * a21;\r\n\t\tfloat b11 = -a22 * a10 + a12 * a20;\r\n\t\tfloat b21 = a21 * a10 - a11 * a20;\r\n\r\n\t\tfloat det = a00 * b01 + a01 * b11 + a02 * b21;\r\n\r\n\t\treturn mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),\r\n\t\t\t\t\tb11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),\r\n\t\t\t\t\tb21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;\r\n\t}\r\n#endif\r\n\r\nivec4 getClusterInfo(sampler2D clusterBuffer,mat4 viewMatrix,vec4 viewport,vec3 position,vec4 fragCoord,vec4 projectParams)\r\n{\r\n\tvec3 viewPos = vec3(viewMatrix*vec4(position, 1.0)); //position in viewspace\r\n\r\n\tint clusterXIndex = int(floor(fragCoord.x/ (float(viewport.z)/float(CLUSTER_X_COUNT))));\r\n int clusterYIndex = int(floor((viewport.w * (projectParams.z <0.0? 0.0 : 1.0) - fragCoord.y * projectParams.z)/ (float(viewport.w)/float(CLUSTER_Y_COUNT))));//Maybe Flipped ProjectMatrix\r\n\tfloat zSliceParam =float(CLUSTER_Z_COUNT)/log2(projectParams.y / projectParams.x);\r\n \tint clusterZIndex = int(floor(log2(-viewPos.z) * zSliceParam- log2(projectParams.x) * zSliceParam));//projectParams x:cameraNear y:cameraFar\r\n\r\n\tvec2 uv= vec2((float(clusterXIndex + clusterYIndex * CLUSTER_X_COUNT)+0.5)/float(c_ClusterBufferWidth),\r\n\t\t\t\t(float(clusterZIndex)+0.5)/float(c_ClusterBufferHeight));\r\n\tvec4 clusterPixel=texture2D(clusterBuffer, uv);\r\n\treturn ivec4(clusterPixel);//X:Point Count Y:Spot Count Z、W:Light Offset\r\n}\r\n\r\n\r\nint getLightIndex(sampler2D clusterBuffer,int offset,int index) \r\n{\r\n\tint totalOffset=offset+index;\r\n\tint row=totalOffset/c_ClusterBufferFloatWidth;\r\n\tint lastRowFloat=totalOffset-row*c_ClusterBufferFloatWidth;\r\n\tint col=lastRowFloat/4;\r\n\tvec2 uv=vec2((float(col)+0.5)/float(c_ClusterBufferWidth),\r\n\t\t\t\t(float(row)+0.5)/float(c_ClusterBufferHeight));\r\n\tvec4 texel = texture2D(clusterBuffer, uv);\r\n int pixelComponent = lastRowFloat-col*4;\r\n if (pixelComponent == 0) \r\n return int(texel.x);\r\n else if (pixelComponent == 1) \r\n return int(texel.y);\r\n else if (pixelComponent == 2) \r\n return int(texel.z);\r\n else //pixelComponent==3\r\n return int(texel.w);\r\n}\r\n\r\nDirectionLight getDirectionLight(sampler2D lightBuffer,int index) \r\n{\r\n DirectionLight light;\r\n float v = (float(index)+0.5)/ float(MAX_LIGHT_COUNT);\r\n vec4 p1 = texture2D(lightBuffer, vec2(0.125,v));\r\n vec4 p2 = texture2D(lightBuffer, vec2(0.375,v));\r\n\tlight.color=p1.rgb;\r\n light.direction = p2.rgb;\r\n return light;\r\n}\r\n\r\nPointLight getPointLight(sampler2D lightBuffer,sampler2D clusterBuffer,ivec4 clusterInfo,int index) \r\n{\r\n PointLight light;\r\n\tint pointIndex=getLightIndex(clusterBuffer,clusterInfo.z*c_ClusterBufferFloatWidth+clusterInfo.w,index);\r\n float v = (float(pointIndex)+0.5)/ float(MAX_LIGHT_COUNT);\r\n vec4 p1 = texture2D(lightBuffer, vec2(0.125,v));\r\n vec4 p2 = texture2D(lightBuffer, vec2(0.375,v));\r\n\tlight.color=p1.rgb;\r\n\tlight.range = p1.a;\r\n light.position = p2.rgb;\r\n return light;\r\n}\r\n\r\nSpotLight getSpotLight(sampler2D lightBuffer,sampler2D clusterBuffer,ivec4 clusterInfo,int index) \r\n{\r\n SpotLight light;\r\n\tint spoIndex=getLightIndex(clusterBuffer,clusterInfo.z*c_ClusterBufferFloatWidth+clusterInfo.w,clusterInfo.x+index);\r\n float v = (float(spoIndex)+0.5)/ float(MAX_LIGHT_COUNT);\r\n vec4 p1 = texture2D(lightBuffer, vec2(0.125,v));\r\n vec4 p2 = texture2D(lightBuffer, vec2(0.375,v));\r\n\tvec4 p3 = texture2D(lightBuffer, vec2(0.625,v));\r\n light.color = p1.rgb;\r\n\tlight.range=p1.a;\r\n light.position = p2.rgb;\r\n\tlight.spot = p2.a;\r\n\tlight.direction = p3.rgb;\r\n return light;\r\n}\r\n\r\n// Laya中使用衰减纹理\r\nfloat LayaAttenuation(in vec3 L,in float invLightRadius) {\r\n\tfloat fRatio = clamp(length(L) * invLightRadius,0.0,1.0);\r\n\tfRatio *= fRatio;\r\n\treturn 1.0 / (1.0 + 25.0 * fRatio)* clamp(4.0*(1.0 - fRatio),0.0,1.0); //fade to black as if 4 pixel texture\r\n}\r\n\r\n// Same as Just Cause 2 and Crysis 2 (you can read GPU Pro 1 book for more information)\r\nfloat BasicAttenuation(in vec3 L,in float invLightRadius) {\r\n\tvec3 distance = L * invLightRadius;\r\n\tfloat attenuation = clamp(1.0 - dot(distance, distance),0.0,1.0); // Equals float attenuation = saturate(1.0f - dot(L, L) / (lightRadius * lightRadius));\r\n\treturn attenuation * attenuation;\r\n}\r\n\r\n// Inspired on http://fools.slindev.com/viewtopic.php?f=11&t=21&view=unread#unread\r\nfloat NaturalAttenuation(in vec3 L,in float invLightRadius) {\r\n\tfloat attenuationFactor = 30.0;\r\n\tvec3 distance = L * invLightRadius;\r\n\tfloat attenuation = dot(distance, distance); // Equals float attenuation = dot(L, L) / (lightRadius * lightRadius);\r\n\tattenuation = 1.0 / (attenuation * attenuationFactor + 1.0);\r\n\t// Second we move down the function therewith it reaches zero at abscissa 1:\r\n\tattenuationFactor = 1.0 / (attenuationFactor + 1.0); //attenuationFactor contains now the value we have to subtract\r\n\tattenuation = max(attenuation - attenuationFactor, 0.0); // The max fixes a bug.\r\n\t// Finally we expand the equation along the y-axis so that it starts with a function value of 1 again.\r\n\tattenuation /= 1.0 - attenuationFactor;\r\n\treturn attenuation;\r\n}\r\n\r\nvoid LayaAirBlinnPhongLight (in vec3 specColor,in float specColorIntensity,in vec3 normal,in vec3 gloss, in vec3 viewDir,in vec3 lightColor, in vec3 lightVec,out vec3 diffuseColor,out vec3 specularColor) {\r\n\tmediump vec3 h = normalize(viewDir-lightVec);\r\n\tlowp float ln = max (0.0, dot (-lightVec,normal));\r\n\tfloat nh = max (0.0, dot (h,normal));\r\n\tdiffuseColor=lightColor * ln;\r\n\tspecularColor=lightColor *specColor*pow (nh, specColorIntensity*128.0) * gloss;\r\n}\r\n\r\nvoid LayaAirBlinnPhongDiectionLight (in vec3 specColor,in float specColorIntensity,in vec3 normal,in vec3 gloss, in vec3 viewDir, in DirectionLight light,out vec3 diffuseColor,out vec3 specularColor) {\r\n\tvec3 lightVec=normalize(light.direction);\r\n\tLayaAirBlinnPhongLight(specColor,specColorIntensity,normal,gloss,viewDir,light.color,lightVec,diffuseColor,specularColor);\r\n}\r\n\r\nvoid LayaAirBlinnPhongPointLight (in vec3 pos,in vec3 specColor,in float specColorIntensity,in vec3 normal,in vec3 gloss, in vec3 viewDir, in PointLight light,out vec3 diffuseColor,out vec3 specularColor) {\r\n\tvec3 lightVec = pos-light.position;\r\n\tLayaAirBlinnPhongLight(specColor,specColorIntensity,normal,gloss,viewDir,light.color,lightVec/length(lightVec),diffuseColor,specularColor);\r\n\tfloat attenuate = LayaAttenuation(lightVec, 1.0/light.range);\r\n\tdiffuseColor *= attenuate;\r\n\tspecularColor*= attenuate;\r\n}\r\n\r\nvoid LayaAirBlinnPhongSpotLight (in vec3 pos,in vec3 specColor,in float specColorIntensity,in vec3 normal,in vec3 gloss, in vec3 viewDir, in SpotLight light,out vec3 diffuseColor,out vec3 specularColor) {\r\n\tvec3 lightVec = pos-light.position;\r\n\tvec3 normalLightVec=lightVec/length(lightVec);\r\n\tLayaAirBlinnPhongLight(specColor,specColorIntensity,normal,gloss,viewDir,light.color,normalLightVec,diffuseColor,specularColor);\r\n\tvec2 cosAngles=cos(vec2(light.spot,light.spot*0.5)*0.5);//ConeAttenuation\r\n\tfloat dl=dot(normalize(light.direction),normalLightVec);\r\n\tdl*=smoothstep(cosAngles[0],cosAngles[1],dl);\r\n\tfloat attenuate = LayaAttenuation(lightVec, 1.0/light.range)*dl;\r\n\tdiffuseColor *=attenuate;\r\n\tspecularColor *=attenuate;\r\n}\r\n\r\nvec3 NormalSampleToWorldSpace(vec3 normalMapSample, vec3 unitNormal, vec3 tangent,vec3 binormal) {\r\n\tvec3 normalT =vec3(2.0*normalMapSample.x - 1.0,1.0-2.0*normalMapSample.y,2.0*normalMapSample.z - 1.0);\r\n\tmediump vec3 N = unitNormal;\r\n\tmediump vec3 T = tangent;\r\n\tmediump vec3 B = binormal;\r\n\tmat3 TBN = mat3(T, B, N);\r\n\r\n\t// Transform from tangent space to world space.\r\n\tvec3 bumpedNormal =normalize(TBN*normalT);\r\n\treturn bumpedNormal;\r\n}\r\n\r\nvec3 NormalSampleToWorldSpace1(vec4 normalMapSample, vec3 tangent, vec3 binormal, vec3 unitNormal) {\r\n\tvec3 normalT;\r\n\tnormalT.x = 2.0 * normalMapSample.x - 1.0;\r\n\tnormalT.y = 1.0 - 2.0 * normalMapSample.y;\r\n\tnormalT.z = sqrt(1.0 - clamp(dot(normalT.xy, normalT.xy), 0.0, 1.0));\r\n\r\n\tvec3 T = normalize(tangent);\r\n\tvec3 B = normalize(binormal);\r\n\tvec3 N = normalize(unitNormal);\r\n\tmat3 TBN = mat3(T, B, N);\r\n\r\n\t// Transform from tangent space to world space.\r\n\tvec3 bumpedNormal = TBN * normalize(normalT);\r\n\r\n\treturn bumpedNormal;\r\n}\r\n\r\nvec3 DecodeLightmap(vec4 color) {\r\n\treturn color.rgb*color.a*5.0;\r\n}\r\n\r\nvec3 decodeHDR(vec4 color,float range) {\r\n\treturn color.rgb*color.a*range;\r\n}\r\n\r\nvec2 TransformUV(vec2 texcoord,vec4 tilingOffset) {\r\n\tvec2 transTexcoord=vec2(texcoord.x,texcoord.y-1.0)*tilingOffset.xy+vec2(tilingOffset.z,-tilingOffset.w);\r\n\ttransTexcoord.y+=1.0;\r\n\treturn transTexcoord;\r\n}\r\n\r\nvec4 remapGLPositionZ(vec4 position) {\r\n\tposition.z=position.z * 2.0 - position.w;\r\n\treturn position;\r\n}\r\n\r\nmediump vec3 layaLinearToGammaSpace (mediump vec3 linRGB)\r\n{\r\n linRGB = max(linRGB, vec3(0.0));\r\n // An almost-perfect approximation from http://chilliant.blogspot.com.au/2012/08/srgb-approximations-for-hlsl.html?m=1\r\n return max(1.055 * pow(linRGB,vec3(0.416666667)) - 0.055, 0.0); \r\n}\r\n\r\nLayaLight layaDirectionLightToLight(in DirectionLight light,in float attenuate)\r\n{\r\n\tLayaLight relight;\r\n\trelight.color = light.color*attenuate;\r\n\trelight.dir = light.direction;\r\n\treturn relight;\r\n}\r\n\r\nLayaLight layaPointLightToLight(in vec3 pos,in vec3 normal, in PointLight light,in float attenuate)\r\n{\r\n\tLayaLight relight;\r\n\tvec3 lightVec = pos-light.position;\r\n\tattenuate *= LayaAttenuation(lightVec, 1.0/light.range);\r\n\trelight.color = light.color*attenuate;\r\n\trelight.dir = normalize(lightVec);\r\n\treturn relight;\r\n}\r\n\r\nLayaLight layaSpotLightToLight(in vec3 pos,in vec3 normal, in SpotLight light,in float attenuate)\r\n{\r\n\tLayaLight relight;\r\n\tvec3 lightVec = pos-light.position;\r\n\tvec3 normalLightVec=lightVec/length(lightVec);\r\n\tvec2 cosAngles=cos(vec2(light.spot,light.spot*0.5)*0.5);//ConeAttenuation\r\n\tfloat dl=dot(normalize(light.direction),normalLightVec);\r\n\tdl*=smoothstep(cosAngles[0],cosAngles[1],dl);\r\n\tattenuate *= LayaAttenuation(lightVec, 1.0/light.range)*dl;\r\n\trelight.dir = normalLightVec;\r\n\trelight.color = light.color*attenuate;\r\n\treturn relight;\r\n}\r\n\r\n\r\n\r\n\r\n";
  29620. var ShadowSampleTentGLSL = "// ------------------------------------------------------------------\r\n// PCF Filtering Tent Functions\r\n// ------------------------------------------------------------------\r\n\r\n// Assuming a isoceles right angled triangle of height \"triangleHeight\" (as drawn below).\r\n// This function return the area of the triangle above the first texel(in Y the first texel).\r\n//\r\n// |\\ <-- 45 degree slop isosceles right angled triangle\r\n// | \\\r\n// ---- <-- length of this side is \"triangleHeight\"\r\n// _ _ _ _ <-- texels\r\nfloat sampleShadowGetIRTriangleTexelArea(float triangleHeight)\r\n{\r\n return triangleHeight - 0.5;\r\n}\r\n\r\n// Assuming a isoceles triangle of 1.5 texels height and 3 texels wide lying on 4 texels.\r\n// This function return the area of the triangle above each of those texels.\r\n// | <-- offset from -0.5 to 0.5, 0 meaning triangle is exactly in the center\r\n// / \\ <-- 45 degree slop isosceles triangle (ie tent projected in 2D)\r\n// / \\\r\n// _ _ _ _ <-- texels\r\n// X Y Z W <-- result indices (in computedArea.xyzw and computedAreaUncut.xyzw)\r\n// Top point at (right,top) in a texel,left bottom point at (middle,middle) in a texel,right bottom point at (middle,middle) in a texel.\r\nvoid sampleShadowGetTexelAreasTent3x3(float offset, out vec4 computedArea, out vec4 computedAreaUncut)\r\n{\r\n // Compute the exterior areas,a and h is same.\r\n float a = offset + 0.5;\r\n float offsetSquaredHalved = a * a * 0.5;\r\n computedAreaUncut.x = computedArea.x = offsetSquaredHalved - offset;\r\n computedAreaUncut.w = computedArea.w = offsetSquaredHalved;\r\n\r\n // Compute the middle areas\r\n // For Y : We find the area in Y of as if the left section of the isoceles triangle would\r\n // intersect the axis between Y and Z (ie where offset = 0).\r\n computedAreaUncut.y = sampleShadowGetIRTriangleTexelArea(1.5 - offset);\r\n // This area is superior to the one we are looking for if (offset < 0) thus we need to\r\n // subtract the area of the triangle defined by (0,1.5-offset), (0,1.5+offset), (-offset,1.5).\r\n float clampedOffsetLeft = min(offset,0.0);\r\n float areaOfSmallLeftTriangle = clampedOffsetLeft * clampedOffsetLeft;\r\n computedArea.y = computedAreaUncut.y - areaOfSmallLeftTriangle;\r\n\r\n // We do the same for the Z but with the right part of the isoceles triangle\r\n computedAreaUncut.z = sampleShadowGetIRTriangleTexelArea(1.5 + offset);\r\n float clampedOffsetRight = max(offset,0.0);\r\n float areaOfSmallRightTriangle = clampedOffsetRight * clampedOffsetRight;\r\n computedArea.z = computedAreaUncut.z - areaOfSmallRightTriangle;\r\n}\r\n\r\n// Assuming a isoceles triangle of 2.5 texel height and 5 texels wide lying on 6 texels.\r\n// This function return the weight of each texels area relative to the full triangle area.\r\n// / \\\r\n// _ _ _ _ _ _ <-- texels\r\n// 0 1 2 3 4 5 <-- computed area indices (in texelsWeights[])\r\n// Top point at (right,top) in a texel,left bottom point at (middle,middle) in a texel,right bottom point at (middle,middle) in a texel.\r\nvoid sampleShadowGetTexelWeightsTent5x5(float offset, out vec3 texelsWeightsA, out vec3 texelsWeightsB)\r\n{\r\n vec4 areaFrom3texelTriangle;\r\n vec4 areaUncutFrom3texelTriangle;\r\n sampleShadowGetTexelAreasTent3x3(offset, areaFrom3texelTriangle, areaUncutFrom3texelTriangle);\r\n\r\n // Triangle slope is 45 degree thus we can almost reuse the result of the 3 texel wide computation.\r\n // the 5 texel wide triangle can be seen as the 3 texel wide one but shifted up by one unit/texel.\r\n // 0.16 is 1/(the triangle area)\r\n texelsWeightsA.x = 0.16 * (areaFrom3texelTriangle.x);\r\n texelsWeightsA.y = 0.16 * (areaUncutFrom3texelTriangle.y);\r\n texelsWeightsA.z = 0.16 * (areaFrom3texelTriangle.y + 1.0);\r\n texelsWeightsB.x = 0.16 * (areaFrom3texelTriangle.z + 1.0);\r\n texelsWeightsB.y = 0.16 * (areaUncutFrom3texelTriangle.z);\r\n texelsWeightsB.z = 0.16 * (areaFrom3texelTriangle.w);\r\n}\r\n\r\n// 5x5 Tent filter (45 degree sloped triangles in U and V)\r\nvoid sampleShadowComputeSamplesTent5x5(vec4 shadowMapTextureTexelSize, vec2 coord, out float fetchesWeights[9], out vec2 fetchesUV[9])\r\n{\r\n // tent base is 5x5 base thus covering from 25 to 36 texels, thus we need 9 bilinear PCF fetches\r\n vec2 tentCenterInTexelSpace = coord.xy * shadowMapTextureTexelSize.zw;\r\n vec2 centerOfFetchesInTexelSpace = floor(tentCenterInTexelSpace + 0.5);\r\n vec2 offsetFromTentCenterToCenterOfFetches = tentCenterInTexelSpace - centerOfFetchesInTexelSpace;\r\n\r\n // find the weight of each texel based on the area of a 45 degree slop tent above each of them.\r\n vec3 texelsWeightsUA, texelsWeightsUB;\r\n vec3 texelsWeightsVA, texelsWeightsVB;\r\n sampleShadowGetTexelWeightsTent5x5(offsetFromTentCenterToCenterOfFetches.x, texelsWeightsUA, texelsWeightsUB);\r\n sampleShadowGetTexelWeightsTent5x5(offsetFromTentCenterToCenterOfFetches.y, texelsWeightsVA, texelsWeightsVB);\r\n\r\n // each fetch will cover a group of 2x2 texels, the weight of each group is the sum of the weights of the texels\r\n vec3 fetchesWeightsU = vec3(texelsWeightsUA.xz, texelsWeightsUB.y) + vec3(texelsWeightsUA.y, texelsWeightsUB.xz);\r\n vec3 fetchesWeightsV = vec3(texelsWeightsVA.xz, texelsWeightsVB.y) + vec3(texelsWeightsVA.y, texelsWeightsVB.xz);\r\n\r\n // move the PCF bilinear fetches to respect texels weights\r\n vec3 fetchesOffsetsU = vec3(texelsWeightsUA.y, texelsWeightsUB.xz) / fetchesWeightsU.xyz + vec3(-2.5,-0.5,1.5);\r\n vec3 fetchesOffsetsV = vec3(texelsWeightsVA.y, texelsWeightsVB.xz) / fetchesWeightsV.xyz + vec3(-2.5,-0.5,1.5);\r\n fetchesOffsetsU *= shadowMapTextureTexelSize.xxx;\r\n fetchesOffsetsV *= shadowMapTextureTexelSize.yyy;\r\n\r\n vec2 bilinearFetchOrigin = centerOfFetchesInTexelSpace * shadowMapTextureTexelSize.xy;\r\n fetchesUV[0] = bilinearFetchOrigin + vec2(fetchesOffsetsU.x, fetchesOffsetsV.x);\r\n fetchesUV[1] = bilinearFetchOrigin + vec2(fetchesOffsetsU.y, fetchesOffsetsV.x);\r\n fetchesUV[2] = bilinearFetchOrigin + vec2(fetchesOffsetsU.z, fetchesOffsetsV.x);\r\n fetchesUV[3] = bilinearFetchOrigin + vec2(fetchesOffsetsU.x, fetchesOffsetsV.y);\r\n fetchesUV[4] = bilinearFetchOrigin + vec2(fetchesOffsetsU.y, fetchesOffsetsV.y);\r\n fetchesUV[5] = bilinearFetchOrigin + vec2(fetchesOffsetsU.z, fetchesOffsetsV.y);\r\n fetchesUV[6] = bilinearFetchOrigin + vec2(fetchesOffsetsU.x, fetchesOffsetsV.z);\r\n fetchesUV[7] = bilinearFetchOrigin + vec2(fetchesOffsetsU.y, fetchesOffsetsV.z);\r\n fetchesUV[8] = bilinearFetchOrigin + vec2(fetchesOffsetsU.z, fetchesOffsetsV.z);\r\n\r\n fetchesWeights[0] = fetchesWeightsU.x * fetchesWeightsV.x;\r\n fetchesWeights[1] = fetchesWeightsU.y * fetchesWeightsV.x;\r\n fetchesWeights[2] = fetchesWeightsU.z * fetchesWeightsV.x;\r\n fetchesWeights[3] = fetchesWeightsU.x * fetchesWeightsV.y;\r\n fetchesWeights[4] = fetchesWeightsU.y * fetchesWeightsV.y;\r\n fetchesWeights[5] = fetchesWeightsU.z * fetchesWeightsV.y;\r\n fetchesWeights[6] = fetchesWeightsU.x * fetchesWeightsV.z;\r\n fetchesWeights[7] = fetchesWeightsU.y * fetchesWeightsV.z;\r\n fetchesWeights[8] = fetchesWeightsU.z * fetchesWeightsV.z;\r\n}";
  29621. var LayaUtile = "\r\n\r\n//SimpleSkinnedMesh\r\n#ifdef SIMPLEBONE\r\n\t#ifdef GPU_INSTANCE\r\n\t\tattribute vec4 a_SimpleTextureParams;\r\n\t#else\r\n\t\tuniform vec4 u_SimpleAnimatorParams;\r\n\t#endif\r\n\tuniform sampler2D u_SimpleAnimatorTexture;\r\n\r\n\tuniform float u_SimpleAnimatorTextureSize; \r\n#endif\r\n\r\n\r\n#ifdef SIMPLEBONE\r\n\tmat4 loadMatFromTexture(float FramePos,int boneIndices,float offset)\r\n\t{\r\n\t\tvec2 uv;\r\n\t\tfloat PixelPos = FramePos+float(boneIndices)*4.0;\r\n\t\tfloat halfOffset = offset * 0.5;\r\n\t\tfloat uvoffset = PixelPos/u_SimpleAnimatorTextureSize;\r\n\t\tuv.y = floor(uvoffset)*offset+halfOffset;\r\n\t\tuv.x = mod(float(PixelPos),u_SimpleAnimatorTextureSize)*offset+halfOffset;\r\n\t\tvec4 mat0row = texture2D(u_SimpleAnimatorTexture,uv);\r\n\t\tuv.x+=offset;\r\n\t\tvec4 mat1row = texture2D(u_SimpleAnimatorTexture,uv);\r\n\t\tuv.x+=offset;\r\n\t\tvec4 mat2row = texture2D(u_SimpleAnimatorTexture,uv);\r\n\t\tuv.x+=offset;\r\n\t\tvec4 mat3row = texture2D(u_SimpleAnimatorTexture,uv);\r\n\t\tmat4 m =mat4(mat0row.x,mat0row.y,mat0row.z,mat0row.w,\r\n\t\t\t\tmat1row.x,mat1row.y,mat1row.z,mat1row.w,\r\n\t\t\t\tmat2row.x,mat2row.y,mat2row.z,mat2row.w,\r\n\t\t\t\tmat3row.x,mat3row.y,mat3row.z,mat3row.w);\r\n\t\treturn m;\r\n\t}\r\n#endif\r\n\r\n";
  29622. var linePS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\nprecision highp float;\r\n#else\r\nprecision mediump float;\r\n#endif\r\n\r\nvarying vec4 v_Color;\r\nuniform vec4 u_Color;\r\n\r\nvoid main()\r\n{\r\n gl_FragColor = v_Color * u_Color; \r\n}\r\n\r\n";
  29623. var lineVS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\nprecision highp float;\r\n#else\r\nprecision mediump float;\r\n#endif\r\n\r\n#include \"Lighting.glsl\";\r\n\r\nattribute vec4 a_Position;\r\nuniform mat4 u_MvpMatrix;\r\nuniform vec4 u_Color;\r\nattribute vec4 a_Color;\r\nvarying vec4 v_Color;\r\n\r\n\r\nvoid main()\r\n{\r\n\tgl_Position = u_MvpMatrix * a_Position;\r\n\tv_Color=a_Color*u_Color;\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}";
  29624. var MeshBlinnPhongPS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n\tprecision highp int;\r\n#else\r\n\tprecision mediump float;\r\n\tprecision mediump int;\r\n#endif\r\n\r\n#include \"Lighting.glsl\";\r\n#include \"Shadow.glsl\"\r\n\r\nuniform vec4 u_DiffuseColor;\r\n\r\n#if defined(COLOR)&&defined(ENABLEVERTEXCOLOR)\r\n\tvarying vec4 v_Color;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tuniform float u_AlphaTestValue;\r\n#endif\r\n\r\n#ifdef DIFFUSEMAP\r\n\tuniform sampler2D u_DiffuseTexture;\r\n#endif\r\n\r\n\r\n#if defined(DIFFUSEMAP)||((defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT))&&(defined(SPECULARMAP)||defined(NORMALMAP)))\r\n\tvarying vec2 v_Texcoord0;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvarying vec2 v_LightMapUV;\r\n\tuniform sampler2D u_LightMap;\r\n\t#ifdef LIGHTMAP_DIRECTIONAL\r\n\t\tuniform sampler2D u_LightMapDirection;\r\n\t#endif\r\n#endif\r\n\r\nvarying vec3 v_Normal;\r\n#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\tvarying vec3 v_ViewDir; \r\n\r\n\tuniform vec3 u_MaterialSpecular;\r\n\tuniform float u_Shininess;\r\n\r\n\t#ifdef LEGACYSINGLELIGHTING\r\n\t\t#ifdef DIRECTIONLIGHT\r\n\t\t\tuniform DirectionLight u_DirectionLight;\r\n\t\t#endif\r\n\t\t#ifdef POINTLIGHT\r\n\t\t\tuniform PointLight u_PointLight;\r\n\t\t#endif\r\n\t\t#ifdef SPOTLIGHT\r\n\t\t\tuniform SpotLight u_SpotLight;\r\n\t\t#endif\r\n\t#else\r\n\t\tuniform mat4 u_View;\r\n\t\tuniform vec4 u_ProjectionParams;\r\n\t\tuniform vec4 u_Viewport;\r\n\t\tuniform int u_DirationLightCount;\r\n\t\tuniform sampler2D u_LightBuffer;\r\n\t\tuniform sampler2D u_LightClusterBuffer;\r\n\t#endif\r\n\r\n\t#ifdef SPECULARMAP \r\n\t\tuniform sampler2D u_SpecularTexture;\r\n\t#endif\r\n#endif\r\n\r\n#ifdef NORMALMAP \r\n\tuniform sampler2D u_NormalTexture;\r\n\tvarying vec3 v_Tangent;\r\n\tvarying vec3 v_Binormal;\r\n#endif\r\n\r\n#ifdef FOG\r\n\tuniform float u_FogStart;\r\n\tuniform float u_FogRange;\r\n\tuniform vec3 u_FogColor;\r\n#endif\r\n\r\n#if defined(POINTLIGHT)||defined(SPOTLIGHT)||(defined(CALCULATE_SHADOWS)&&defined(SHADOW_CASCADE))||defined(CALCULATE_SPOTSHADOWS)\r\n\tvarying vec3 v_PositionWorld;\r\n#endif\r\n\r\n\r\n#include \"GlobalIllumination.glsl\";//\"GlobalIllumination.glsl use uniform should at front of this\r\n\r\n#if defined(CALCULATE_SHADOWS)&&!defined(SHADOW_CASCADE)\r\n\tvarying vec4 v_ShadowCoord;\r\n#endif\r\n\r\n#if defined(CALCULATE_SPOTSHADOWS)//shader中自定义的宏不可用ifdef 必须改成if defined\r\n\tvarying vec4 v_SpotShadowCoord;\r\n#endif\r\n\r\n\r\nvoid main()\r\n{\r\n\tvec3 normal;//light and SH maybe use normal\r\n\t#if defined(NORMALMAP)\r\n\t\tvec3 normalMapSample = texture2D(u_NormalTexture, v_Texcoord0).rgb;\r\n\t\tnormal = normalize(NormalSampleToWorldSpace(normalMapSample, v_Normal, v_Tangent,v_Binormal));\r\n\t#else\r\n\t\tnormal = normalize(v_Normal);\r\n\t#endif\r\n\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\tvec3 viewDir= normalize(v_ViewDir);\r\n\t#endif\r\n\r\n\tLayaGIInput giInput;\r\n\t#ifdef LIGHTMAP\t\r\n\t\tgiInput.lightmapUV=v_LightMapUV;\r\n\t#endif\r\n\tvec3 globalDiffuse=layaGIBase(giInput,1.0,normal);\r\n\t\r\n\tvec4 mainColor=u_DiffuseColor;\r\n\t#ifdef DIFFUSEMAP\r\n\t\tvec4 difTexColor=texture2D(u_DiffuseTexture, v_Texcoord0);\r\n\t\tmainColor=mainColor*difTexColor;\r\n\t#endif \r\n\t#if defined(COLOR)&&defined(ENABLEVERTEXCOLOR)\r\n\t\tmainColor=mainColor*v_Color;\r\n\t#endif \r\n \r\n\t#ifdef ALPHATEST\r\n\t\tif(mainColor.a<u_AlphaTestValue)\r\n\t\t\tdiscard;\r\n\t#endif\r\n \r\n\t\r\n\tvec3 diffuse = vec3(0.0);\r\n\tvec3 specular= vec3(0.0);\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\tvec3 dif,spe;\r\n\t\t#ifdef SPECULARMAP\r\n\t\t\tvec3 gloss=texture2D(u_SpecularTexture, v_Texcoord0).rgb;\r\n\t\t#else\r\n\t\t\t#ifdef DIFFUSEMAP\r\n\t\t\t\tvec3 gloss=vec3(difTexColor.a);\r\n\t\t\t#else\r\n\t\t\t\tvec3 gloss=vec3(1.0);\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t#endif\r\n\r\n\t\r\n\t\r\n\t#ifdef LEGACYSINGLELIGHTING\r\n\t\t#ifdef DIRECTIONLIGHT\r\n\t\t\tLayaAirBlinnPhongDiectionLight(u_MaterialSpecular,u_Shininess,normal,gloss,viewDir,u_DirectionLight,dif,spe);\r\n\t\t\t#if defined(CALCULATE_SHADOWS)//shader中自定义的宏不可用ifdef 必须改成if defined\r\n\t\t\t\t#ifdef SHADOW_CASCADE\r\n\t\t\t\t\tvec4 shadowCoord = getShadowCoord(vec4(v_PositionWorld,1.0));\r\n\t\t\t\t#else\r\n\t\t\t\t\tvec4 shadowCoord = v_ShadowCoord;\r\n\t\t\t\t#endif\r\n\t\t\t\tfloat shadowAttenuation=sampleShadowmap(shadowCoord);\r\n\t\t\t\tdif *= shadowAttenuation;\r\n\t\t\t\tspe *= shadowAttenuation;\r\n\t\t\t#endif\r\n\t\t\tdiffuse+=dif;\r\n\t\t\tspecular+=spe;\r\n\t\t#endif\r\n\t\r\n\t\t#ifdef POINTLIGHT\r\n\t\t\tLayaAirBlinnPhongPointLight(v_PositionWorld,u_MaterialSpecular,u_Shininess,normal,gloss,viewDir,u_PointLight,dif,spe);\r\n\t\t\tdiffuse+=dif;\r\n\t\t\tspecular+=spe;\r\n\t\t#endif\r\n\r\n\t\t#ifdef SPOTLIGHT\r\n\t\t\tLayaAirBlinnPhongSpotLight(v_PositionWorld,u_MaterialSpecular,u_Shininess,normal,gloss,viewDir,u_SpotLight,dif,spe);\r\n\t\t\t#if defined(CALCULATE_SPOTSHADOWS)//shader中自定义的宏不可用ifdef 必须改成if defined\r\n\t\t\t\tvec4 spotShadowcoord = v_SpotShadowCoord;\r\n\t\t\t\tfloat spotShadowAttenuation = sampleSpotShadowmap(spotShadowcoord);\r\n\t\t\t\tdif *= spotShadowAttenuation;\r\n\t\t\t\tspe *= spotShadowAttenuation;\r\n\t\t\t#endif\r\n\t\t\tdiffuse+=dif;\r\n\t\t\tspecular+=spe;\r\n\t\t#endif\r\n\t#else\r\n\t\t#ifdef DIRECTIONLIGHT\r\n\t\t\tfor (int i = 0; i < MAX_LIGHT_COUNT; i++) \r\n\t\t\t{\r\n\t\t\t\tif(i >= u_DirationLightCount)\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tDirectionLight directionLight = getDirectionLight(u_LightBuffer,i);\r\n\t\t\t\t#if defined(CALCULATE_SHADOWS)//shader中自定义的宏不可用ifdef 必须改成if defined\r\n\t\t\t\t\tif(i == 0)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t#ifdef SHADOW_CASCADE\r\n\t\t\t\t\t\t\tvec4 shadowCoord = getShadowCoord(vec4(v_PositionWorld,1.0));\r\n\t\t\t\t\t\t#else\r\n\t\t\t\t\t\t\tvec4 shadowCoord = v_ShadowCoord;\r\n\t\t\t\t\t\t#endif\r\n\t\t\t\t\t\tdirectionLight.color *= sampleShadowmap(shadowCoord);\r\n\t\t\t\t\t}\r\n\t\t\t\t#endif\r\n\t\t\t\tLayaAirBlinnPhongDiectionLight(u_MaterialSpecular,u_Shininess,normal,gloss,viewDir,directionLight,dif,spe);\r\n\t\t\t\tdiffuse+=dif;\r\n\t\t\t\tspecular+=spe;\r\n\t\t\t}\r\n\t\t#endif\r\n\t\t#if defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\t\tivec4 clusterInfo =getClusterInfo(u_LightClusterBuffer,u_View,u_Viewport, v_PositionWorld,gl_FragCoord,u_ProjectionParams);\r\n\t\t\t#ifdef POINTLIGHT\r\n\t\t\t\tfor (int i = 0; i < MAX_LIGHT_COUNT; i++) \r\n\t\t\t\t{\r\n\t\t\t\t\tif(i >= clusterInfo.x)//PointLightCount\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tPointLight pointLight = getPointLight(u_LightBuffer,u_LightClusterBuffer,clusterInfo,i);\r\n\t\t\t\t\tLayaAirBlinnPhongPointLight(v_PositionWorld,u_MaterialSpecular,u_Shininess,normal,gloss,viewDir,pointLight,dif,spe);\r\n\t\t\t\t\tdiffuse+=dif;\r\n\t\t\t\t\tspecular+=spe;\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t\t#ifdef SPOTLIGHT\r\n\t\t\t\tfor (int i = 0; i < MAX_LIGHT_COUNT; i++) \r\n\t\t\t\t{\r\n\t\t\t\t\tif(i >= clusterInfo.y)//SpotLightCount\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tSpotLight spotLight = getSpotLight(u_LightBuffer,u_LightClusterBuffer,clusterInfo,i);\r\n\t\t\t\t\t#if defined(CALCULATE_SPOTSHADOWS)//shader中自定义的宏不可用ifdef 必须改成if defined\r\n\t\t\t\t\t\tif(i == 0)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tvec4 spotShadowcoord = v_SpotShadowCoord;\r\n\t\t\t\t\t\t\tspotLight.color *= sampleSpotShadowmap(spotShadowcoord);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t#endif\r\n\t\t\t\t\tLayaAirBlinnPhongSpotLight(v_PositionWorld,u_MaterialSpecular,u_Shininess,normal,gloss,viewDir,spotLight,dif,spe);\r\n\t\t\t\t\tdiffuse+=dif;\r\n\t\t\t\t\tspecular+=spe;\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t#endif\r\n\r\n\tgl_FragColor =vec4(mainColor.rgb*(globalDiffuse + diffuse),mainColor.a);\r\n\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\tgl_FragColor.rgb+=specular;\r\n\t#endif\r\n\t \r\n\t#ifdef FOG\r\n\t\tfloat lerpFact=clamp((1.0/gl_FragCoord.w-u_FogStart)/u_FogRange,0.0,1.0);\r\n\t\tgl_FragColor.rgb=mix(gl_FragColor.rgb,u_FogColor,lerpFact);\r\n\t#endif\r\n}\r\n\r\n";
  29625. var MeshBlinnPhongVS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n\tprecision highp int;\r\n#else\r\n\tprecision mediump float;\r\n\tprecision mediump int;\r\n#endif\r\n#include \"Lighting.glsl\";\r\n#include \"LayaUtile.glsl\"\r\n#include \"Shadow.glsl\";\r\n\r\n\r\nattribute vec4 a_Position;\r\n\r\n#ifdef GPU_INSTANCE\r\n\tattribute mat4 a_MvpMatrix;\r\n#else\r\n\tuniform mat4 u_MvpMatrix;\r\n#endif\r\n\r\n#if defined(DIFFUSEMAP)||((defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT))&&(defined(SPECULARMAP)||defined(NORMALMAP)))||(defined(LIGHTMAP)&&defined(UV))\r\n\tattribute vec2 a_Texcoord0;\r\n\tvarying vec2 v_Texcoord0;\r\n#endif\r\n\r\n#if defined(LIGHTMAP)&&defined(UV1)\r\n\tattribute vec2 a_Texcoord1;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tuniform vec4 u_LightmapScaleOffset;\r\n\tvarying vec2 v_LightMapUV;\r\n#endif\r\n\r\n#ifdef COLOR\r\n\tattribute vec4 a_Color;\r\n\tvarying vec4 v_Color;\r\n#endif\r\n\r\n#ifdef BONE\r\n\tconst int c_MaxBoneCount = 24;\r\n\tattribute vec4 a_BoneIndices;\r\n\tattribute vec4 a_BoneWeights;\r\n\tuniform mat4 u_Bones[c_MaxBoneCount];\r\n#endif\r\n\r\nattribute vec3 a_Normal;\r\nvarying vec3 v_Normal; \r\n\r\n#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\tuniform vec3 u_CameraPos;\r\n\tvarying vec3 v_ViewDir; \r\n#endif\r\n\r\n#if defined(NORMALMAP)\r\n\tattribute vec4 a_Tangent0;\r\n\tvarying vec3 v_Tangent;\r\n\tvarying vec3 v_Binormal;\r\n#endif\r\n\r\n#ifdef GPU_INSTANCE\r\n\tattribute mat4 a_WorldMat;\r\n#else\r\n\tuniform mat4 u_WorldMat;\r\n#endif\r\n\r\n#if defined(POINTLIGHT)||defined(SPOTLIGHT)||(defined(CALCULATE_SHADOWS)&&defined(SHADOW_CASCADE))||defined(CALCULATE_SPOTSHADOWS)\r\n\tvarying vec3 v_PositionWorld;\r\n#endif\r\n\r\n#if defined(CALCULATE_SHADOWS)&&!defined(SHADOW_CASCADE)\r\n\tvarying vec4 v_ShadowCoord;\r\n#endif\r\n\r\n#if defined(CALCULATE_SPOTSHADOWS)//shader中自定义的宏不可用ifdef 必须改成if defined\r\n\tvarying vec4 v_SpotShadowCoord;\r\n#endif\r\n\r\n#ifdef TILINGOFFSET\r\n\tuniform vec4 u_TilingOffset;\r\n#endif\r\n\r\n\r\n\r\nvoid main()\r\n{\r\n\tvec4 position;\r\n\t#ifdef BONE\r\n\t\tmat4 skinTransform;\r\n\t \t#ifdef SIMPLEBONE\r\n\t\t\tfloat currentPixelPos;\r\n\t\t\t#ifdef GPU_INSTANCE\r\n\t\t\t\tcurrentPixelPos = a_SimpleTextureParams.x+a_SimpleTextureParams.y;\r\n\t\t\t#else\r\n\t\t\t\tcurrentPixelPos = u_SimpleAnimatorParams.x+u_SimpleAnimatorParams.y;\r\n\t\t\t#endif\r\n\t\t\tfloat offset = 1.0/u_SimpleAnimatorTextureSize;\r\n\t\t\tskinTransform = loadMatFromTexture(currentPixelPos,int(a_BoneIndices.x),offset) * a_BoneWeights.x;\r\n\t\t\tskinTransform += loadMatFromTexture(currentPixelPos,int(a_BoneIndices.y),offset) * a_BoneWeights.y;\r\n\t\t\tskinTransform += loadMatFromTexture(currentPixelPos,int(a_BoneIndices.z),offset) * a_BoneWeights.z;\r\n\t\t\tskinTransform += loadMatFromTexture(currentPixelPos,int(a_BoneIndices.w),offset) * a_BoneWeights.w;\r\n\t\t#else\r\n\t\t\tskinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;\r\n\t\t\tskinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;\r\n\t\t\tskinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;\r\n\t\t\tskinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;\r\n\t\t#endif\r\n\t\tposition=skinTransform*a_Position;\r\n\t #else\r\n\t\tposition=a_Position;\r\n\t#endif\r\n\r\n\t#ifdef GPU_INSTANCE\r\n\t\tgl_Position = a_MvpMatrix * position;\r\n\t#else\r\n\t\tgl_Position = u_MvpMatrix * position;\r\n\t#endif\r\n\t\r\n\tmat4 worldMat;\r\n\t#ifdef GPU_INSTANCE\r\n\t\tworldMat = a_WorldMat;\r\n\t#else\r\n\t\tworldMat = u_WorldMat;\r\n\t#endif\r\n\r\n\tmat3 worldInvMat;\r\n\t#ifdef BONE\r\n\t\tworldInvMat=INVERSE_MAT(mat3(worldMat*skinTransform));\r\n\t#else\r\n\t\tworldInvMat=INVERSE_MAT(mat3(worldMat));\r\n\t#endif \r\n\tv_Normal=normalize(a_Normal*worldInvMat);\r\n\t#if defined(NORMALMAP)\r\n\t\tv_Tangent=normalize(a_Tangent0.xyz*worldInvMat);\r\n\t\tv_Binormal=cross(v_Normal,v_Tangent)*a_Tangent0.w;\r\n\t#endif\r\n\r\n\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)||(defined(CALCULATE_SHADOWS)&&defined(SHADOW_CASCADE))||defined(CALCULATE_SPOTSHADOWS)\r\n\t\tvec3 positionWS=(worldMat*position).xyz;\r\n\t\t#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\t\tv_ViewDir = u_CameraPos-positionWS;\r\n\t\t#endif\r\n\t\t#if defined(POINTLIGHT)||defined(SPOTLIGHT)||(defined(CALCULATE_SHADOWS)&&defined(SHADOW_CASCADE))||defined(CALCULATE_SPOTSHADOWS)\r\n\t\t\tv_PositionWorld = positionWS;\r\n\t\t#endif\r\n\t#endif\r\n\r\n\t#if defined(DIFFUSEMAP)||((defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT))&&(defined(SPECULARMAP)||defined(NORMALMAP)))\r\n\t\t#ifdef TILINGOFFSET\r\n\t\t\tv_Texcoord0=TransformUV(a_Texcoord0,u_TilingOffset);\r\n\t\t#else\r\n\t\t\tv_Texcoord0=a_Texcoord0;\r\n\t\t#endif\r\n\t#endif\r\n\r\n\t#ifdef LIGHTMAP\r\n\t\t#ifdef UV1\r\n\t\t\tv_LightMapUV=vec2(a_Texcoord1.x,1.0-a_Texcoord1.y)*u_LightmapScaleOffset.xy+u_LightmapScaleOffset.zw;\r\n\t\t#else\r\n\t\t\tv_LightMapUV=vec2(a_Texcoord0.x,1.0-a_Texcoord0.y)*u_LightmapScaleOffset.xy+u_LightmapScaleOffset.zw;\r\n\t\t#endif \r\n\t\tv_LightMapUV.y=1.0-v_LightMapUV.y;\r\n\t#endif\r\n\r\n\t#if defined(COLOR)&&defined(ENABLEVERTEXCOLOR)\r\n\t\tv_Color=a_Color;\r\n\t#endif\r\n\r\n\t#if defined(CALCULATE_SHADOWS)&&!defined(SHADOW_CASCADE)\r\n\t\tv_ShadowCoord =getShadowCoord(vec4(positionWS,1.0));\r\n\t#endif\r\n\r\n\t#if defined(CALCULATE_SPOTSHADOWS)//shader中自定义的宏不可用ifdef 必须改成if defined\r\n\t\tv_SpotShadowCoord = u_SpotViewProjectMatrix*vec4(positionWS,1.0);\r\n\t#endif\r\n\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}";
  29626. var MeshBlinnPhongShadowCasterPS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n\tprecision highp int;\r\n#else\r\n\tprecision mediump float;\r\n\tprecision mediump int;\r\n#endif\r\n\r\n#include \"ShadowCasterFS.glsl\"\r\n\r\nvoid main()\r\n{\r\n\tgl_FragColor=shadowCasterFragment();\r\n}";
  29627. var MeshBlinnPhongShadowCasterVS = "#include \"ShadowCasterVS.glsl\"\r\n\r\nvoid main()\r\n{\r\n\tvec4 positionCS = shadowCasterVertex();\r\n\tgl_Position=remapGLPositionZ(positionCS);\r\n}";
  29628. var ParticleShuriKenPS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n precision highp float;\r\n#else\r\n precision mediump float;\r\n#endif\r\n\r\nvarying vec4 v_Color;\r\nvarying vec2 v_TextureCoordinate;\r\nuniform sampler2D u_texture;\r\nuniform vec4 u_Tintcolor;\r\n\r\n#ifdef RENDERMODE_MESH\r\n\tvarying vec4 v_MeshColor;\r\n#endif\r\n\r\n#ifdef FOG\r\n\tuniform float u_FogStart;\r\n\tuniform float u_FogRange;\r\n\t#ifdef ADDTIVEFOG\r\n\t#else\r\n\t\tuniform vec3 u_FogColor;\r\n\t#endif\r\n#endif\r\n\r\n\r\nvoid main()\r\n{\t\r\n\t#ifdef RENDERMODE_MESH\r\n\t\tgl_FragColor=v_MeshColor;\r\n\t#else\r\n\t\tgl_FragColor=vec4(1.0);\t\r\n\t#endif\r\n\t\t\r\n\t#ifdef DIFFUSEMAP\r\n\t\t#ifdef TINTCOLOR\r\n\t\t\tgl_FragColor*=texture2D(u_texture,v_TextureCoordinate)*u_Tintcolor*2.0*v_Color;\r\n\t\t#else\r\n\t\t\tgl_FragColor*=texture2D(u_texture,v_TextureCoordinate)*v_Color;\r\n\t\t#endif\r\n\t#else\r\n\t\t#ifdef TINTCOLOR\r\n\t\t\tgl_FragColor*=u_Tintcolor*2.0*v_Color;\r\n\t\t#else\r\n\t\t\tgl_FragColor*=v_Color;\r\n\t\t#endif\r\n\t#endif\r\n\t\r\n\t#ifdef FOG\r\n\t\tfloat lerpFact=clamp((1.0/gl_FragCoord.w-u_FogStart)/u_FogRange,0.0,1.0);\r\n\t\t#ifdef ADDTIVEFOG\r\n\t\t\tgl_FragColor.rgb=mix(gl_FragColor.rgb,vec3(0.0,0.0,0.0),lerpFact);\r\n\t\t#else\r\n\t\t\tgl_FragColor.rgb=mix(gl_FragColor.rgb,u_FogColor,lerpFact);\r\n\t\t#endif\r\n\t#endif\r\n}";
  29629. var ParticleShuriKenVS = "// #include \"Lighting.glsl\";\r\n\r\n//修改这里剔除没有用到的光照函数,增加粒子的编译速度\r\nvec2 TransformUV(vec2 texcoord,vec4 tilingOffset) {\r\n\tvec2 transTexcoord=vec2(texcoord.x,texcoord.y-1.0)*tilingOffset.xy+vec2(tilingOffset.z,-tilingOffset.w);\r\n\ttransTexcoord.y+=1.0;\r\n\treturn transTexcoord;\r\n}\r\n\r\nvec4 remapGLPositionZ(vec4 position) {\r\n\tposition.z=position.z * 2.0 - position.w;\r\n\treturn position;\r\n}\r\n\r\n#if defined(GL_FRAGMENT_PRECISION_HIGH)\r\n precision highp float;\r\n#else\r\n precision mediump float;\r\n#endif\r\n\r\n#if defined(SPHERHBILLBOARD)||defined(STRETCHEDBILLBOARD)||defined(HORIZONTALBILLBOARD)||defined(VERTICALBILLBOARD)\r\n\tattribute vec4 a_CornerTextureCoordinate;\r\n#endif\r\n#ifdef RENDERMODE_MESH\r\n\tattribute vec3 a_MeshPosition;\r\n\tattribute vec4 a_MeshColor;\r\n\tattribute vec2 a_MeshTextureCoordinate;\r\n\tvarying vec4 v_MeshColor;\r\n#endif\r\n\r\nattribute vec4 a_ShapePositionStartLifeTime;\r\nattribute vec4 a_DirectionTime;\r\nattribute vec4 a_StartColor;\r\nattribute vec3 a_StartSize;\r\nattribute vec3 a_StartRotation0;\r\nattribute float a_StartSpeed;\r\n#if defined(COLOROVERLIFETIME)||defined(RANDOMCOLOROVERLIFETIME)||defined(SIZEOVERLIFETIMERANDOMCURVES)||defined(SIZEOVERLIFETIMERANDOMCURVESSEPERATE)||defined(ROTATIONOVERLIFETIMERANDOMCONSTANTS)||defined(ROTATIONOVERLIFETIMERANDOMCURVES)\r\n attribute vec4 a_Random0;\r\n#endif\r\n#if defined(TEXTURESHEETANIMATIONRANDOMCURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\r\n attribute vec4 a_Random1;\r\n#endif\r\nattribute vec3 a_SimulationWorldPostion;\r\nattribute vec4 a_SimulationWorldRotation;\r\n\r\nvarying vec4 v_Color;\r\n#ifdef DIFFUSEMAP\r\n\tvarying vec2 v_TextureCoordinate;\r\n#endif\r\n\r\nuniform float u_CurrentTime;\r\nuniform vec3 u_Gravity;\r\n\r\nuniform vec3 u_WorldPosition;\r\nuniform vec4 u_WorldRotation;\r\nuniform bool u_ThreeDStartRotation;\r\nuniform int u_ScalingMode;\r\nuniform vec3 u_PositionScale;\r\nuniform vec3 u_SizeScale;\r\nuniform mat4 u_View;\r\nuniform mat4 u_Projection;\r\n\r\n#ifdef STRETCHEDBILLBOARD\r\n\tuniform vec3 u_CameraPos;\r\n#endif\r\nuniform vec3 u_CameraDirection;//TODO:只有几种广告牌模式需要用\r\nuniform vec3 u_CameraUp;\r\n\r\nuniform float u_StretchedBillboardLengthScale;\r\nuniform float u_StretchedBillboardSpeedScale;\r\nuniform int u_SimulationSpace;\r\n\r\n#if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\r\n uniform int u_VOLSpaceType;\r\n#endif\r\n#if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)\r\n uniform vec3 u_VOLVelocityConst;\r\n#endif\r\n#if defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\r\n uniform vec2 u_VOLVelocityGradientX[4];//x为key,y为速度\r\n uniform vec2 u_VOLVelocityGradientY[4];//x为key,y为速度\r\n uniform vec2 u_VOLVelocityGradientZ[4];//x为key,y为速度\r\n#endif\r\n#ifdef VELOCITYOVERLIFETIMERANDOMCONSTANT\r\n uniform vec3 u_VOLVelocityConstMax;\r\n#endif\r\n#ifdef VELOCITYOVERLIFETIMERANDOMCURVE\r\n uniform vec2 u_VOLVelocityGradientMaxX[4];//x为key,y为速度\r\n uniform vec2 u_VOLVelocityGradientMaxY[4];//x为key,y为速度\r\n uniform vec2 u_VOLVelocityGradientMaxZ[4];//x为key,y为速度\r\n#endif\r\n\r\n#ifdef COLOROVERLIFETIME\r\n uniform vec4 u_ColorOverLifeGradientColors[4];//x为key,yzw为Color\r\n uniform vec2 u_ColorOverLifeGradientAlphas[4];//x为key,y为Alpha\r\n#endif\r\n#ifdef RANDOMCOLOROVERLIFETIME\r\n uniform vec4 u_ColorOverLifeGradientColors[4];//x为key,yzw为Color\r\n uniform vec2 u_ColorOverLifeGradientAlphas[4];//x为key,y为Alpha\r\n uniform vec4 u_MaxColorOverLifeGradientColors[4];//x为key,yzw为Color\r\n uniform vec2 u_MaxColorOverLifeGradientAlphas[4];//x为key,y为Alpha\r\n#endif\r\n\r\n\r\n#if defined(SIZEOVERLIFETIMECURVE)||defined(SIZEOVERLIFETIMERANDOMCURVES)\r\n uniform vec2 u_SOLSizeGradient[4];//x为key,y为尺寸\r\n#endif\r\n#ifdef SIZEOVERLIFETIMERANDOMCURVES\r\n uniform vec2 u_SOLSizeGradientMax[4];//x为key,y为尺寸\r\n#endif\r\n#if defined(SIZEOVERLIFETIMECURVESEPERATE)||defined(SIZEOVERLIFETIMERANDOMCURVESSEPERATE)\r\n uniform vec2 u_SOLSizeGradientX[4];//x为key,y为尺寸\r\n uniform vec2 u_SOLSizeGradientY[4];//x为key,y为尺寸\r\n uniform vec2 u_SOLSizeGradientZ[4];//x为key,y为尺寸\r\n#endif\r\n#ifdef SIZEOVERLIFETIMERANDOMCURVESSEPERATE\r\n uniform vec2 u_SOLSizeGradientMaxX[4];//x为key,y为尺寸\r\n uniform vec2 u_SOLSizeGradientMaxY[4];//x为key,y为尺寸\r\n uniform vec2 u_SOLSizeGradientMaxZ[4];//x为key,y为尺寸\r\n#endif\r\n\r\n\r\n#ifdef ROTATIONOVERLIFETIME\r\n #if defined(ROTATIONOVERLIFETIMECONSTANT)||defined(ROTATIONOVERLIFETIMERANDOMCONSTANTS)\r\n uniform float u_ROLAngularVelocityConst;\r\n #endif\r\n #ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\r\n uniform float u_ROLAngularVelocityConstMax;\r\n #endif\r\n #if defined(ROTATIONOVERLIFETIMECURVE)||defined(ROTATIONOVERLIFETIMERANDOMCURVES)\r\n uniform vec2 u_ROLAngularVelocityGradient[4];//x为key,y为旋转\r\n #endif\r\n #ifdef ROTATIONOVERLIFETIMERANDOMCURVES\r\n uniform vec2 u_ROLAngularVelocityGradientMax[4];//x为key,y为旋转\r\n #endif\r\n#endif\r\n#ifdef ROTATIONOVERLIFETIMESEPERATE\r\n #if defined(ROTATIONOVERLIFETIMECONSTANT)||defined(ROTATIONOVERLIFETIMERANDOMCONSTANTS)\r\n uniform vec3 u_ROLAngularVelocityConstSeprarate;\r\n #endif\r\n #ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\r\n uniform vec3 u_ROLAngularVelocityConstMaxSeprarate;\r\n #endif\r\n #if defined(ROTATIONOVERLIFETIMECURVE)||defined(ROTATIONOVERLIFETIMERANDOMCURVES)\r\n uniform vec2 u_ROLAngularVelocityGradientX[4];\r\n uniform vec2 u_ROLAngularVelocityGradientY[4];\r\n uniform vec2 u_ROLAngularVelocityGradientZ[4];\r\n #endif\r\n #ifdef ROTATIONOVERLIFETIMERANDOMCURVES\r\n uniform vec2 u_ROLAngularVelocityGradientMaxX[4];\r\n uniform vec2 u_ROLAngularVelocityGradientMaxY[4];\r\n uniform vec2 u_ROLAngularVelocityGradientMaxZ[4];\r\n\tuniform vec2 u_ROLAngularVelocityGradientMaxW[4];\r\n #endif\r\n#endif\r\n\r\n#if defined(TEXTURESHEETANIMATIONCURVE)||defined(TEXTURESHEETANIMATIONRANDOMCURVE)\r\n uniform float u_TSACycles;\r\n uniform vec2 u_TSASubUVLength;\r\n uniform vec2 u_TSAGradientUVs[4];//x为key,y为frame\r\n#endif\r\n#ifdef TEXTURESHEETANIMATIONRANDOMCURVE\r\n uniform vec2 u_TSAMaxGradientUVs[4];//x为key,y为frame\r\n#endif\r\n\r\n#ifdef TILINGOFFSET\r\n\tuniform vec4 u_TilingOffset;\r\n#endif\r\n\r\nvec3 rotationByEuler(in vec3 vector,in vec3 rot)\r\n{\r\n\tfloat halfRoll = rot.z * 0.5;\r\n float halfPitch = rot.x * 0.5;\r\n\tfloat halfYaw = rot.y * 0.5;\r\n\r\n\tfloat sinRoll = sin(halfRoll);\r\n\tfloat cosRoll = cos(halfRoll);\r\n\tfloat sinPitch = sin(halfPitch);\r\n\tfloat cosPitch = cos(halfPitch);\r\n\tfloat sinYaw = sin(halfYaw);\r\n\tfloat cosYaw = cos(halfYaw);\r\n\r\n\tfloat quaX = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);\r\n\tfloat quaY = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);\r\n\tfloat quaZ = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);\r\n\tfloat quaW = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);\r\n\t\r\n\t//vec4 q=vec4(quaX,quaY,quaZ,quaW);\r\n\t//vec3 temp = cross(q.xyz, vector) + q.w * vector;\r\n\t//return (cross(temp, -q.xyz) + dot(q.xyz,vector) * q.xyz + q.w * temp);\r\n\t\r\n\tfloat x = quaX + quaX;\r\n float y = quaY + quaY;\r\n float z = quaZ + quaZ;\r\n float wx = quaW * x;\r\n float wy = quaW * y;\r\n float wz = quaW * z;\r\n\tfloat xx = quaX * x;\r\n float xy = quaX * y;\r\n\tfloat xz = quaX * z;\r\n float yy = quaY * y;\r\n float yz = quaY * z;\r\n float zz = quaZ * z;\r\n\r\n return vec3(((vector.x * ((1.0 - yy) - zz)) + (vector.y * (xy - wz))) + (vector.z * (xz + wy)),\r\n ((vector.x * (xy + wz)) + (vector.y * ((1.0 - xx) - zz))) + (vector.z * (yz - wx)),\r\n ((vector.x * (xz - wy)) + (vector.y * (yz + wx))) + (vector.z * ((1.0 - xx) - yy)));\r\n\t\r\n}\r\n\r\n//假定axis已经归一化\r\nvec3 rotationByAxis(in vec3 vector,in vec3 axis, in float angle)\r\n{\r\n\tfloat halfAngle = angle * 0.5;\r\n\tfloat sin = sin(halfAngle);\r\n\t\r\n\tfloat quaX = axis.x * sin;\r\n\tfloat quaY = axis.y * sin;\r\n\tfloat quaZ = axis.z * sin;\r\n\tfloat quaW = cos(halfAngle);\r\n\t\r\n\t//vec4 q=vec4(quaX,quaY,quaZ,quaW);\r\n\t//vec3 temp = cross(q.xyz, vector) + q.w * vector;\r\n\t//return (cross(temp, -q.xyz) + dot(q.xyz,vector) * q.xyz + q.w * temp);\r\n\t\r\n\tfloat x = quaX + quaX;\r\n float y = quaY + quaY;\r\n float z = quaZ + quaZ;\r\n float wx = quaW * x;\r\n float wy = quaW * y;\r\n float wz = quaW * z;\r\n\tfloat xx = quaX * x;\r\n float xy = quaX * y;\r\n\tfloat xz = quaX * z;\r\n float yy = quaY * y;\r\n float yz = quaY * z;\r\n float zz = quaZ * z;\r\n\r\n return vec3(((vector.x * ((1.0 - yy) - zz)) + (vector.y * (xy - wz))) + (vector.z * (xz + wy)),\r\n ((vector.x * (xy + wz)) + (vector.y * ((1.0 - xx) - zz))) + (vector.z * (yz - wx)),\r\n ((vector.x * (xz - wy)) + (vector.y * (yz + wx))) + (vector.z * ((1.0 - xx) - yy)));\r\n\t\r\n}\r\n\r\nvec3 rotationByQuaternions(in vec3 v,in vec4 q) \r\n{\r\n\treturn v + 2.0 * cross(q.xyz, cross(q.xyz, v) + q.w * v);\r\n}\r\n\r\n \r\n#if defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)||defined(SIZEOVERLIFETIMECURVE)||defined(SIZEOVERLIFETIMECURVESEPERATE)||defined(SIZEOVERLIFETIMERANDOMCURVES)||defined(SIZEOVERLIFETIMERANDOMCURVESSEPERATE)\r\nfloat getCurValueFromGradientFloat(in vec2 gradientNumbers[4],in float normalizedAge)\r\n{\r\n\tfloat curValue;\r\n\tfor(int i=1;i<4;i++)\r\n\t{\r\n\t\tvec2 gradientNumber=gradientNumbers[i];\r\n\t\tfloat key=gradientNumber.x;\r\n\t\tif(key>=normalizedAge)\r\n\t\t{\r\n\t\t\tvec2 lastGradientNumber=gradientNumbers[i-1];\r\n\t\t\tfloat lastKey=lastGradientNumber.x;\r\n\t\t\tfloat age=(normalizedAge-lastKey)/(key-lastKey);\r\n\t\t\tcurValue=mix(lastGradientNumber.y,gradientNumber.y,age);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\treturn curValue;\r\n}\r\n#endif\r\n\r\n#if defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)||defined(ROTATIONOVERLIFETIMECURVE)||defined(ROTATIONOVERLIFETIMERANDOMCURVES)\r\nfloat getTotalValueFromGradientFloat(in vec2 gradientNumbers[4],in float normalizedAge)\r\n{\r\n\tfloat totalValue=0.0;\r\n\tfor(int i=1;i<4;i++)\r\n\t{\r\n\t\tvec2 gradientNumber=gradientNumbers[i];\r\n\t\tfloat key=gradientNumber.x;\r\n\t\tvec2 lastGradientNumber=gradientNumbers[i-1];\r\n\t\tfloat lastValue=lastGradientNumber.y;\r\n\t\t\r\n\t\tif(key>=normalizedAge){\r\n\t\t\tfloat lastKey=lastGradientNumber.x;\r\n\t\t\tfloat age=(normalizedAge-lastKey)/(key-lastKey);\r\n\t\t\ttotalValue+=(lastValue+mix(lastValue,gradientNumber.y,age))/2.0*a_ShapePositionStartLifeTime.w*(normalizedAge-lastKey);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\telse{\r\n\t\t\ttotalValue+=(lastValue+gradientNumber.y)/2.0*a_ShapePositionStartLifeTime.w*(key-lastGradientNumber.x);\r\n\t\t}\r\n\t}\r\n\treturn totalValue;\r\n}\r\n#endif\r\n\r\n#if defined(COLOROVERLIFETIME)||defined(RANDOMCOLOROVERLIFETIME)\r\nvec4 getColorFromGradient(in vec2 gradientAlphas[4],in vec4 gradientColors[4],in float normalizedAge)\r\n{\r\n\tvec4 overTimeColor;\r\n\tfor(int i=1;i<4;i++)\r\n\t{\r\n\t\tvec2 gradientAlpha=gradientAlphas[i];\r\n\t\tfloat alphaKey=gradientAlpha.x;\r\n\t\tif(alphaKey>=normalizedAge)\r\n\t\t{\r\n\t\t\tvec2 lastGradientAlpha=gradientAlphas[i-1];\r\n\t\t\tfloat lastAlphaKey=lastGradientAlpha.x;\r\n\t\t\tfloat age=(normalizedAge-lastAlphaKey)/(alphaKey-lastAlphaKey);\r\n\t\t\toverTimeColor.a=mix(lastGradientAlpha.y,gradientAlpha.y,age);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\t\r\n\tfor(int i=1;i<4;i++)\r\n\t{\r\n\t\tvec4 gradientColor=gradientColors[i];\r\n\t\tfloat colorKey=gradientColor.x;\r\n\t\tif(colorKey>=normalizedAge)\r\n\t\t{\r\n\t\t\tvec4 lastGradientColor=gradientColors[i-1];\r\n\t\t\tfloat lastColorKey=lastGradientColor.x;\r\n\t\t\tfloat age=(normalizedAge-lastColorKey)/(colorKey-lastColorKey);\r\n\t\t\toverTimeColor.rgb=mix(gradientColors[i-1].yzw,gradientColor.yzw,age);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\treturn overTimeColor;\r\n}\r\n#endif\r\n\r\n\r\n#if defined(TEXTURESHEETANIMATIONCURVE)||defined(TEXTURESHEETANIMATIONRANDOMCURVE)\r\nfloat getFrameFromGradient(in vec2 gradientFrames[4],in float normalizedAge)\r\n{\r\n\tfloat overTimeFrame;\r\n\tfor(int i=1;i<4;i++)\r\n\t{\r\n\t\tvec2 gradientFrame=gradientFrames[i];\r\n\t\tfloat key=gradientFrame.x;\r\n\t\tif(key>=normalizedAge)\r\n\t\t{\r\n\t\t\tvec2 lastGradientFrame=gradientFrames[i-1];\r\n\t\t\tfloat lastKey=lastGradientFrame.x;\r\n\t\t\tfloat age=(normalizedAge-lastKey)/(key-lastKey);\r\n\t\t\toverTimeFrame=mix(lastGradientFrame.y,gradientFrame.y,age);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\treturn floor(overTimeFrame);\r\n}\r\n#endif\r\n\r\n#if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\r\nvec3 computeParticleLifeVelocity(in float normalizedAge)\r\n{\r\n vec3 outLifeVelocity;\r\n #ifdef VELOCITYOVERLIFETIMECONSTANT\r\n\t outLifeVelocity=u_VOLVelocityConst; \r\n #endif\r\n #ifdef VELOCITYOVERLIFETIMECURVE\r\n outLifeVelocity= vec3(getCurValueFromGradientFloat(u_VOLVelocityGradientX,normalizedAge),getCurValueFromGradientFloat(u_VOLVelocityGradientY,normalizedAge),getCurValueFromGradientFloat(u_VOLVelocityGradientZ,normalizedAge));\r\n #endif\r\n #ifdef VELOCITYOVERLIFETIMERANDOMCONSTANT\r\n\t outLifeVelocity=mix(u_VOLVelocityConst,u_VOLVelocityConstMax,vec3(a_Random1.y,a_Random1.z,a_Random1.w)); \r\n #endif\r\n #ifdef VELOCITYOVERLIFETIMERANDOMCURVE\r\n outLifeVelocity=vec3(mix(getCurValueFromGradientFloat(u_VOLVelocityGradientX,normalizedAge),getCurValueFromGradientFloat(u_VOLVelocityGradientMaxX,normalizedAge),a_Random1.y),\r\n\t mix(getCurValueFromGradientFloat(u_VOLVelocityGradientY,normalizedAge),getCurValueFromGradientFloat(u_VOLVelocityGradientMaxY,normalizedAge),a_Random1.z),\r\n\t\t\t\t\t mix(getCurValueFromGradientFloat(u_VOLVelocityGradientZ,normalizedAge),getCurValueFromGradientFloat(u_VOLVelocityGradientMaxZ,normalizedAge),a_Random1.w));\r\n #endif\r\n\t\t\t\t\t\r\n return outLifeVelocity;\r\n} \r\n#endif\r\n\r\nvec3 computeParticlePosition(in vec3 startVelocity, in vec3 lifeVelocity,in float age,in float normalizedAge,vec3 gravityVelocity,vec4 worldRotation)\r\n{\r\n vec3 startPosition;\r\n vec3 lifePosition;\r\n #if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\r\n\t#ifdef VELOCITYOVERLIFETIMECONSTANT\r\n\t\t startPosition=startVelocity*age;\r\n\t\t lifePosition=lifeVelocity*age;\r\n\t#endif\r\n\t#ifdef VELOCITYOVERLIFETIMECURVE\r\n\t\t startPosition=startVelocity*age;\r\n\t\t lifePosition=vec3(getTotalValueFromGradientFloat(u_VOLVelocityGradientX,normalizedAge),getTotalValueFromGradientFloat(u_VOLVelocityGradientY,normalizedAge),getTotalValueFromGradientFloat(u_VOLVelocityGradientZ,normalizedAge));\r\n\t#endif\r\n\t#ifdef VELOCITYOVERLIFETIMERANDOMCONSTANT\r\n\t\t startPosition=startVelocity*age;\r\n\t\t lifePosition=lifeVelocity*age;\r\n\t#endif\r\n\t#ifdef VELOCITYOVERLIFETIMERANDOMCURVE\r\n\t\t startPosition=startVelocity*age;\r\n\t\t lifePosition=vec3(mix(getTotalValueFromGradientFloat(u_VOLVelocityGradientX,normalizedAge),getTotalValueFromGradientFloat(u_VOLVelocityGradientMaxX,normalizedAge),a_Random1.y)\r\n\t ,mix(getTotalValueFromGradientFloat(u_VOLVelocityGradientY,normalizedAge),getTotalValueFromGradientFloat(u_VOLVelocityGradientMaxY,normalizedAge),a_Random1.z)\r\n\t ,mix(getTotalValueFromGradientFloat(u_VOLVelocityGradientZ,normalizedAge),getTotalValueFromGradientFloat(u_VOLVelocityGradientMaxZ,normalizedAge),a_Random1.w));\r\n\t#endif\r\n\t\r\n\tvec3 finalPosition;\r\n\tif(u_VOLSpaceType==0){\r\n\t if(u_ScalingMode!=2)\r\n\t finalPosition =rotationByQuaternions(u_PositionScale*(a_ShapePositionStartLifeTime.xyz+startPosition+lifePosition),worldRotation);\r\n\t else\r\n\t finalPosition =rotationByQuaternions(u_PositionScale*a_ShapePositionStartLifeTime.xyz+startPosition+lifePosition,worldRotation);\r\n\t}\r\n\telse{\r\n\t if(u_ScalingMode!=2)\r\n\t finalPosition = rotationByQuaternions(u_PositionScale*(a_ShapePositionStartLifeTime.xyz+startPosition),worldRotation)+lifePosition;\r\n\t else\r\n\t finalPosition = rotationByQuaternions(u_PositionScale*a_ShapePositionStartLifeTime.xyz+startPosition,worldRotation)+lifePosition;\r\n\t}\r\n #else\r\n\t startPosition=startVelocity*age;\r\n\t vec3 finalPosition;\r\n\t if(u_ScalingMode!=2)\r\n\t\t\tfinalPosition = rotationByQuaternions(u_PositionScale*(a_ShapePositionStartLifeTime.xyz+startPosition),worldRotation);\r\n\t else\r\n\t \tfinalPosition = rotationByQuaternions(u_PositionScale*a_ShapePositionStartLifeTime.xyz+startPosition,worldRotation);\r\n #endif\r\n \r\n if(u_SimulationSpace==0)\r\n finalPosition=finalPosition+a_SimulationWorldPostion;\r\n else if(u_SimulationSpace==1) \r\n finalPosition=finalPosition+u_WorldPosition;\r\n \r\n finalPosition+=0.5*gravityVelocity*age;\r\n \r\n return finalPosition;\r\n}\r\n\r\n\r\nvec4 computeParticleColor(in vec4 color,in float normalizedAge)\r\n{\r\n\t#ifdef COLOROVERLIFETIME\r\n\t color*=getColorFromGradient(u_ColorOverLifeGradientAlphas,u_ColorOverLifeGradientColors,normalizedAge);\r\n\t#endif\r\n\t\r\n\t#ifdef RANDOMCOLOROVERLIFETIME\r\n\t color*=mix(getColorFromGradient(u_ColorOverLifeGradientAlphas,u_ColorOverLifeGradientColors,normalizedAge),getColorFromGradient(u_MaxColorOverLifeGradientAlphas,u_MaxColorOverLifeGradientColors,normalizedAge),a_Random0.y);\r\n\t#endif\r\n\r\n return color;\r\n}\r\n\r\nvec2 computeParticleSizeBillbard(in vec2 size,in float normalizedAge)\r\n{\r\n\t#ifdef SIZEOVERLIFETIMECURVE\r\n\t\tsize*=getCurValueFromGradientFloat(u_SOLSizeGradient,normalizedAge);\r\n\t#endif\r\n\t#ifdef SIZEOVERLIFETIMERANDOMCURVES\r\n\t size*=mix(getCurValueFromGradientFloat(u_SOLSizeGradient,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMax,normalizedAge),a_Random0.z); \r\n\t#endif\r\n\t#ifdef SIZEOVERLIFETIMECURVESEPERATE\r\n\t\tsize*=vec2(getCurValueFromGradientFloat(u_SOLSizeGradientX,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientY,normalizedAge));\r\n\t#endif\r\n\t#ifdef SIZEOVERLIFETIMERANDOMCURVESSEPERATE\r\n\t size*=vec2(mix(getCurValueFromGradientFloat(u_SOLSizeGradientX,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMaxX,normalizedAge),a_Random0.z)\r\n\t ,mix(getCurValueFromGradientFloat(u_SOLSizeGradientY,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMaxY,normalizedAge),a_Random0.z));\r\n\t#endif\r\n\treturn size;\r\n}\r\n\r\n#ifdef RENDERMODE_MESH\r\nvec3 computeParticleSizeMesh(in vec3 size,in float normalizedAge)\r\n{\r\n\t#ifdef SIZEOVERLIFETIMECURVE\r\n\t\tsize*=getCurValueFromGradientFloat(u_SOLSizeGradient,normalizedAge);\r\n\t#endif\r\n\t#ifdef SIZEOVERLIFETIMERANDOMCURVES\r\n\t size*=mix(getCurValueFromGradientFloat(u_SOLSizeGradient,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMax,normalizedAge),a_Random0.z); \r\n\t#endif\r\n\t#ifdef SIZEOVERLIFETIMECURVESEPERATE\r\n\t\tsize*=vec3(getCurValueFromGradientFloat(u_SOLSizeGradientX,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientY,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientZ,normalizedAge));\r\n\t#endif\r\n\t#ifdef SIZEOVERLIFETIMERANDOMCURVESSEPERATE\r\n\t size*=vec3(mix(getCurValueFromGradientFloat(u_SOLSizeGradientX,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMaxX,normalizedAge),a_Random0.z)\r\n\t ,mix(getCurValueFromGradientFloat(u_SOLSizeGradientY,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMaxY,normalizedAge),a_Random0.z)\r\n\t\t,mix(getCurValueFromGradientFloat(u_SOLSizeGradientZ,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMaxZ,normalizedAge),a_Random0.z));\r\n\t#endif\r\n\treturn size;\r\n}\r\n#endif\r\n\r\nfloat computeParticleRotationFloat(in float rotation,in float age,in float normalizedAge)\r\n{ \r\n\t#ifdef ROTATIONOVERLIFETIME\r\n\t\t#ifdef ROTATIONOVERLIFETIMECONSTANT\r\n\t\t\tfloat ageRot=u_ROLAngularVelocityConst*age;\r\n\t rotation+=ageRot;\r\n\t\t#endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMECURVE\r\n\t\t\trotation+=getTotalValueFromGradientFloat(u_ROLAngularVelocityGradient,normalizedAge);\r\n\t\t#endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\r\n\t\t\tfloat ageRot=mix(u_ROLAngularVelocityConst,u_ROLAngularVelocityConstMax,a_Random0.w)*age;\r\n\t rotation+=ageRot;\r\n\t #endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMERANDOMCURVES\r\n\t\t\trotation+=mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradient,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMax,normalizedAge),a_Random0.w);\r\n\t\t#endif\r\n\t#endif\r\n\t#ifdef ROTATIONOVERLIFETIMESEPERATE\r\n\t\t#ifdef ROTATIONOVERLIFETIMECONSTANT\r\n\t\t\tfloat ageRot=u_ROLAngularVelocityConstSeprarate.z*age;\r\n\t rotation+=ageRot;\r\n\t\t#endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMECURVE\r\n\t\t\trotation+=getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientZ,normalizedAge);\r\n\t\t#endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\r\n\t\t\tfloat ageRot=mix(u_ROLAngularVelocityConstSeprarate.z,u_ROLAngularVelocityConstMaxSeprarate.z,a_Random0.w)*age;\r\n\t rotation+=ageRot;\r\n\t #endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMERANDOMCURVES\r\n\t\t\trotation+=mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientZ,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMaxZ,normalizedAge),a_Random0.w));\r\n\t\t#endif\r\n\t#endif\r\n\treturn rotation;\r\n}\r\n\r\n#if defined(RENDERMODE_MESH)&&(defined(ROTATIONOVERLIFETIME)||defined(ROTATIONOVERLIFETIMESEPERATE))\r\nvec3 computeParticleRotationVec3(in vec3 rotation,in float age,in float normalizedAge)\r\n{ \r\n\t#ifdef ROTATIONOVERLIFETIME\r\n\t#ifdef ROTATIONOVERLIFETIMECONSTANT\r\n\t\t\tfloat ageRot=u_ROLAngularVelocityConst*age;\r\n\t rotation+=ageRot;\r\n\t\t#endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMECURVE\r\n\t\t\trotation+=getTotalValueFromGradientFloat(u_ROLAngularVelocityGradient,normalizedAge);\r\n\t\t#endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\r\n\t\t\tfloat ageRot=mix(u_ROLAngularVelocityConst,u_ROLAngularVelocityConstMax,a_Random0.w)*age;\r\n\t rotation+=ageRot;\r\n\t #endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMERANDOMCURVES\r\n\t\t\trotation+=mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradient,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMax,normalizedAge),a_Random0.w);\r\n\t\t#endif\r\n\t#endif\r\n\t#ifdef ROTATIONOVERLIFETIMESEPERATE\r\n\t\t#ifdef ROTATIONOVERLIFETIMECONSTANT\r\n\t\t\tvec3 ageRot=u_ROLAngularVelocityConstSeprarate*age;\r\n\t rotation+=ageRot;\r\n\t\t#endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMECURVE\r\n\t\t\trotation+=vec3(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientX,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientY,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientZ,normalizedAge));\r\n\t\t#endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\r\n\t\t\tvec3 ageRot=mix(u_ROLAngularVelocityConstSeprarate,u_ROLAngularVelocityConstMaxSeprarate,a_Random0.w)*age;\r\n\t rotation+=ageRot;\r\n\t #endif\r\n\t\t#ifdef ROTATIONOVERLIFETIMERANDOMCURVES\r\n\t\t\trotation+=vec3(mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientX,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMaxX,normalizedAge),a_Random0.w)\r\n\t ,mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientY,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMaxY,normalizedAge),a_Random0.w)\r\n\t ,mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientZ,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMaxZ,normalizedAge),a_Random0.w));\r\n\t\t#endif\r\n\t#endif\r\n\treturn rotation;\r\n}\r\n#endif\r\n\r\nvec2 computeParticleUV(in vec2 uv,in float normalizedAge)\r\n{ \r\n\t#ifdef TEXTURESHEETANIMATIONCURVE\r\n\t\tfloat cycleNormalizedAge=normalizedAge*u_TSACycles;\r\n\t\tfloat frame=getFrameFromGradient(u_TSAGradientUVs,cycleNormalizedAge-floor(cycleNormalizedAge));\r\n\t\tfloat totalULength=frame*u_TSASubUVLength.x;\r\n\t\tfloat floorTotalULength=floor(totalULength);\r\n\t uv.x+=totalULength-floorTotalULength;\r\n\t\tuv.y+=floorTotalULength*u_TSASubUVLength.y;\r\n #endif\r\n\t#ifdef TEXTURESHEETANIMATIONRANDOMCURVE\r\n\t\tfloat cycleNormalizedAge=normalizedAge*u_TSACycles;\r\n\t\tfloat uvNormalizedAge=cycleNormalizedAge-floor(cycleNormalizedAge);\r\n\t float frame=floor(mix(getFrameFromGradient(u_TSAGradientUVs,uvNormalizedAge),getFrameFromGradient(u_TSAMaxGradientUVs,uvNormalizedAge),a_Random1.x));\r\n\t\tfloat totalULength=frame*u_TSASubUVLength.x;\r\n\t\tfloat floorTotalULength=floor(totalULength);\r\n\t uv.x+=totalULength-floorTotalULength;\r\n\t\tuv.y+=floorTotalULength*u_TSASubUVLength.y;\r\n #endif\r\n\treturn uv;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tfloat age = u_CurrentTime - a_DirectionTime.w;\r\n\tfloat normalizedAge = age/a_ShapePositionStartLifeTime.w;\r\n\tvec3 lifeVelocity;\r\n\tif(normalizedAge<1.0)\r\n\t{ \r\n\t\tvec3 startVelocity=a_DirectionTime.xyz*a_StartSpeed;\r\n\t\t#if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\r\n\t\t\tlifeVelocity= computeParticleLifeVelocity(normalizedAge);//计算粒子生命周期速度\r\n\t\t#endif \r\n\t\tvec3 gravityVelocity=u_Gravity*age;\r\n\t\t\r\n\t\tvec4 worldRotation;\r\n\t\tif(u_SimulationSpace==0)\r\n\t\t\tworldRotation=a_SimulationWorldRotation;\r\n\t\telse\r\n\t\t\tworldRotation=u_WorldRotation;\r\n\t\t\r\n\t\tvec3 center=computeParticlePosition(startVelocity, lifeVelocity, age, normalizedAge,gravityVelocity,worldRotation);//计算粒子位置\r\n\t\r\n\t\r\n\t\t#ifdef SPHERHBILLBOARD\r\n\t\t\tvec2 corner=a_CornerTextureCoordinate.xy;//Billboard模式z轴无效\r\n\t\t\tvec3 cameraUpVector =normalize(u_CameraUp);//TODO:是否外面归一化\r\n\t\t\tvec3 sideVector = normalize(cross(u_CameraDirection,cameraUpVector));\r\n\t\t\tvec3 upVector = normalize(cross(sideVector,u_CameraDirection));\r\n\t\t\tcorner*=computeParticleSizeBillbard(a_StartSize.xy,normalizedAge);\r\n\t\t\t#if defined(ROTATIONOVERLIFETIME)||defined(ROTATIONOVERLIFETIMESEPERATE)\r\n\t\t\t\tif(u_ThreeDStartRotation){\r\n\t\t\t\t\tvec3 rotation=vec3(a_StartRotation0.xy,computeParticleRotationFloat(a_StartRotation0.z,age,normalizedAge));\r\n\t\t\t\t\tcenter += u_SizeScale.xzy*rotationByEuler(corner.x*sideVector+corner.y*upVector,rotation);\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n\t\t\t\t\tfloat rot = computeParticleRotationFloat(a_StartRotation0.x, age,normalizedAge);\r\n\t\t\t\t\tfloat c = cos(rot);\r\n\t\t\t\t\tfloat s = sin(rot);\r\n\t\t\t\t\tmat2 rotation= mat2(c, -s, s, c);\r\n\t\t\t\t\tcorner=rotation*corner;\r\n\t\t\t\t\tcenter += u_SizeScale.xzy*(corner.x*sideVector+corner.y*upVector);\r\n\t\t\t\t}\r\n\t\t\t#else\r\n\t\t\t\tif(u_ThreeDStartRotation){\r\n\t\t\t\t\tcenter += u_SizeScale.xzy*rotationByEuler(corner.x*sideVector+corner.y*upVector,a_StartRotation0);\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n\t\t\t\t\tfloat c = cos(a_StartRotation0.x);\r\n\t\t\t\t\tfloat s = sin(a_StartRotation0.x);\r\n\t\t\t\t\tmat2 rotation= mat2(c, -s, s, c);\r\n\t\t\t\t\tcorner=rotation*corner;\r\n\t\t\t\t\tcenter += u_SizeScale.xzy*(corner.x*sideVector+corner.y*upVector);\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t\r\n\t\t#ifdef STRETCHEDBILLBOARD\r\n\t\t\tvec2 corner=a_CornerTextureCoordinate.xy;//Billboard模式z轴无效\r\n\t\t\tvec3 velocity;\r\n\t\t\t#if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\r\n\t\t\t\tif(u_VOLSpaceType==0)\r\n\t\t\t\tvelocity=rotationByQuaternions(u_SizeScale*(startVelocity+lifeVelocity),worldRotation)+gravityVelocity;\r\n\t\t\t\telse\r\n\t\t\t\tvelocity=rotationByQuaternions(u_SizeScale*startVelocity,worldRotation)+lifeVelocity+gravityVelocity;\r\n\t\t\t#else\r\n\t\t\t\tvelocity= rotationByQuaternions(u_SizeScale*startVelocity,worldRotation)+gravityVelocity;\r\n\t\t\t#endif\t\r\n\t\t\tvec3 cameraUpVector = normalize(velocity);\r\n\t\t\tvec3 direction = normalize(center-u_CameraPos);\r\n\t\t\tvec3 sideVector = normalize(cross(direction,normalize(velocity)));\r\n\t\t\t\r\n\t\t\tsideVector=u_SizeScale.xzy*sideVector;\r\n\t\t\tcameraUpVector=length(vec3(u_SizeScale.x,0.0,0.0))*cameraUpVector;\r\n\t\t\t\r\n\t\t\tvec2 size=computeParticleSizeBillbard(a_StartSize.xy,normalizedAge);\r\n\t\t\t\r\n\t\t\tconst mat2 rotaionZHalfPI=mat2(0.0, -1.0, 1.0, 0.0);\r\n\t\t\tcorner=rotaionZHalfPI*corner;\r\n\t\t\tcorner.y=corner.y-abs(corner.y);\r\n\t\t\t\r\n\t\t\tfloat speed=length(velocity);//TODO:\r\n\t\t\tcenter +=sign(u_SizeScale.x)*(sign(u_StretchedBillboardLengthScale)*size.x*corner.x*sideVector+(speed*u_StretchedBillboardSpeedScale+size.y*u_StretchedBillboardLengthScale)*corner.y*cameraUpVector);\r\n\t\t#endif\r\n\t\r\n\t\t#ifdef HORIZONTALBILLBOARD\r\n\t\t\tvec2 corner=a_CornerTextureCoordinate.xy;//Billboard模式z轴无效\r\n\t\t\tconst vec3 cameraUpVector=vec3(0.0,0.0,1.0);\r\n\t\t\tconst vec3 sideVector = vec3(-1.0,0.0,0.0);\r\n\t\t\t\r\n\t\t\tfloat rot = computeParticleRotationFloat(a_StartRotation0.x, age,normalizedAge);\r\n\t\t\tfloat c = cos(rot);\r\n\t\t\tfloat s = sin(rot);\r\n\t\t\tmat2 rotation= mat2(c, -s, s, c);\r\n\t\t\tcorner=rotation*corner*cos(0.78539816339744830961566084581988);//TODO:临时缩小cos45,不确定U3D原因\r\n\t\t\tcorner*=computeParticleSizeBillbard(a_StartSize.xy,normalizedAge);\r\n\t\t\tcenter +=u_SizeScale.xzy*(corner.x*sideVector+ corner.y*cameraUpVector);\r\n\t\t#endif\r\n\t\r\n\t\t#ifdef VERTICALBILLBOARD\r\n\t\t\tvec2 corner=a_CornerTextureCoordinate.xy;//Billboard模式z轴无效\r\n\t\t\tconst vec3 cameraUpVector =vec3(0.0,1.0,0.0);\r\n\t\t\tvec3 sideVector = normalize(cross(u_CameraDirection,cameraUpVector));\r\n\t\t\t\r\n\t\t\tfloat rot = computeParticleRotationFloat(a_StartRotation0.x, age,normalizedAge);\r\n\t\t\tfloat c = cos(rot);\r\n\t\t\tfloat s = sin(rot);\r\n\t\t\tmat2 rotation= mat2(c, -s, s, c);\r\n\t\t\tcorner=rotation*corner*cos(0.78539816339744830961566084581988);//TODO:临时缩小cos45,不确定U3D原因\r\n\t\t\tcorner*=computeParticleSizeBillbard(a_StartSize.xy,normalizedAge);\r\n\t\t\tcenter +=u_SizeScale.xzy*(corner.x*sideVector+ corner.y*cameraUpVector);\r\n\t\t#endif\r\n\t\r\n\t\t#ifdef RENDERMODE_MESH\r\n\t\t\tvec3 size=computeParticleSizeMesh(a_StartSize,normalizedAge);\r\n\t\t\t#if defined(ROTATIONOVERLIFETIME)||defined(ROTATIONOVERLIFETIMESEPERATE)\r\n\t\t\t\tif(u_ThreeDStartRotation){\r\n\t\t\t\t\tvec3 rotation=vec3(a_StartRotation0.xy,computeParticleRotationFloat(a_StartRotation0.z, age,normalizedAge));\r\n\t\t\t\t\tcenter+= rotationByQuaternions(u_SizeScale*rotationByEuler(a_MeshPosition*size,rotation),worldRotation);\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n\t\t\t\t\t#ifdef ROTATIONOVERLIFETIME\r\n\t\t\t\t\t\tfloat angle=computeParticleRotationFloat(a_StartRotation0.x, age,normalizedAge);\r\n\t\t\t\t\t\tif(a_ShapePositionStartLifeTime.x!=0.0||a_ShapePositionStartLifeTime.y!=0.0){\r\n\t\t\t\t\t\t\tcenter+= (rotationByQuaternions(rotationByAxis(u_SizeScale*a_MeshPosition*size,normalize(cross(vec3(0.0,0.0,1.0),vec3(a_ShapePositionStartLifeTime.xy,0.0))),angle),worldRotation));//已验证\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse{\r\n\t\t\t\t\t\t\t#ifdef SHAPE\r\n\t\t\t\t\t\t\t\tcenter+= u_SizeScale.xzy*(rotationByQuaternions(rotationByAxis(a_MeshPosition*size,vec3(0.0,-1.0,0.0),angle),worldRotation));\r\n\t\t\t\t\t\t\t#else\r\n\t\t\t\t\t\t\t\tif(u_SimulationSpace==0)\r\n\t\t\t\t\t\t\t\t\tcenter+=rotationByAxis(u_SizeScale*a_MeshPosition*size,vec3(0.0,0.0,-1.0),angle);//已验证\r\n\t\t\t\t\t\t\t\telse if(u_SimulationSpace==1)\r\n\t\t\t\t\t\t\t\t\tcenter+=rotationByQuaternions(u_SizeScale*rotationByAxis(a_MeshPosition*size,vec3(0.0,0.0,-1.0),angle),worldRotation);//已验证\r\n\t\t\t\t\t\t\t#endif\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t#endif\r\n\t\t\t\t\t#ifdef ROTATIONOVERLIFETIMESEPERATE\r\n\t\t\t\t\t\t//TODO:是否应合并if(u_ThreeDStartRotation)分支代码,待测试\r\n\t\t\t\t\t\tvec3 angle=computeParticleRotationVec3(vec3(0.0,0.0,-a_StartRotation0.x), age,normalizedAge);\r\n\t\t\t\t\t\tcenter+= (rotationByQuaternions(rotationByEuler(u_SizeScale*a_MeshPosition*size,vec3(angle.x,angle.y,angle.z)),worldRotation));//已验证\r\n\t\t\t\t\t#endif\t\t\r\n\t\t\t\t}\r\n\t\t\t#else\r\n\t\t\t\tif(u_ThreeDStartRotation){\r\n\t\t\t\t\tcenter+= rotationByQuaternions(u_SizeScale*rotationByEuler(a_MeshPosition*size,a_StartRotation0),worldRotation);//已验证\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n\t\t\t\t\tif(a_ShapePositionStartLifeTime.x!=0.0||a_ShapePositionStartLifeTime.y!=0.0){\r\n\t\t\t\t\t\tif(u_SimulationSpace==0)\r\n\t\t\t\t\t\t\tcenter+= rotationByAxis(u_SizeScale*a_MeshPosition*size,normalize(cross(vec3(0.0,0.0,1.0),vec3(a_ShapePositionStartLifeTime.xy,0.0))),a_StartRotation0.x);\r\n\t\t\t\t\t\telse if(u_SimulationSpace==1)\r\n\t\t\t\t\t\t\tcenter+= (rotationByQuaternions(u_SizeScale*rotationByAxis(a_MeshPosition*size,normalize(cross(vec3(0.0,0.0,1.0),vec3(a_ShapePositionStartLifeTime.xy,0.0))),a_StartRotation0.x),worldRotation));//已验证\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse{\r\n\t\t\t\t\t\t#ifdef SHAPE\r\n\t\t\t\t\t\t\tif(u_SimulationSpace==0)\r\n\t\t\t\t\t\t\t\tcenter+= u_SizeScale*rotationByAxis(a_MeshPosition*size,vec3(0.0,-1.0,0.0),a_StartRotation0.x);\r\n\t\t\t\t\t\t\telse if(u_SimulationSpace==1)\r\n\t\t\t\t\t\t\t\tcenter+= rotationByQuaternions(u_SizeScale*rotationByAxis(a_MeshPosition*size,vec3(0.0,-1.0,0.0),a_StartRotation0.x),worldRotation);\t\r\n\t\t\t\t\t\t#else\r\n\t\t\t\t\t\t\tif(u_SimulationSpace==0)\r\n\t\t\t\t\t\t\t\tcenter+= rotationByAxis(u_SizeScale*a_MeshPosition*size,vec3(0.0,0.0,-1.0),a_StartRotation0.x);\r\n\t\t\t\t\t\t\telse if(u_SimulationSpace==1)\r\n\t\t\t\t\t\t\t\tcenter+= rotationByQuaternions(u_SizeScale*rotationByAxis(a_MeshPosition*size,vec3(0.0,0.0,-1.0),a_StartRotation0.x),worldRotation);//已验证\r\n\t\t\t\t\t\t#endif\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t\tv_MeshColor=a_MeshColor;\r\n\t\t#endif\r\n\t\r\n\t\tgl_Position=u_Projection*u_View*vec4(center,1.0);\r\n\t\tv_Color = computeParticleColor(a_StartColor, normalizedAge);\r\n\t\t#ifdef DIFFUSEMAP\r\n\t\t\t#if defined(SPHERHBILLBOARD)||defined(STRETCHEDBILLBOARD)||defined(HORIZONTALBILLBOARD)||defined(VERTICALBILLBOARD)\r\n\t\t\t\tv_TextureCoordinate =computeParticleUV(a_CornerTextureCoordinate.zw, normalizedAge);\r\n\t\t\t#endif\r\n\t\t\t#ifdef RENDERMODE_MESH\r\n\t\t\t\tv_TextureCoordinate =computeParticleUV(a_MeshTextureCoordinate, normalizedAge);\r\n\t\t\t#endif\r\n\t\t\t\r\n\t\t\t#ifdef TILINGOFFSET\r\n\t\t\t\tv_TextureCoordinate=TransformUV(v_TextureCoordinate,u_TilingOffset);\r\n\t\t\t#endif\r\n\t\t#endif\r\n \t}\r\n \telse\r\n\t{\r\n\t\tgl_Position=vec4(2.0,2.0,2.0,1.0);//Discard use out of X(-1,1),Y(-1,1),Z(0,1)\r\n\t}\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}\r\n\r\n";
  29630. var LayaPBRBRDF = "// allow to explicitly override LAYA_BRDF_GI and LAYA_BRDF_LIGHT in custom shader,default is layaBRDFHighGI and layaBRDFHighLight\r\n#if !defined (LAYA_BRDF_GI) \r\n\t#if defined(LAYA_PBR_BRDF_LOW)\r\n\t\t#define LAYA_BRDF_GI layaBRDFLowGI\r\n\t#elif defined(LAYA_PBR_BRDF_HIGH)\r\n\t\t#define LAYA_BRDF_GI layaBRDFHighGI\r\n\t#endif\r\n#endif\r\n#if !defined (LAYA_BRDF_LIGHT)\r\n\t#if defined(LAYA_PBR_BRDF_LOW)\r\n\t\t#define LAYA_BRDF_LIGHT layaBRDFLowLight\r\n\t#elif defined(LAYA_PBR_BRDF_HIGH)\r\n\t\t#define LAYA_BRDF_LIGHT layaBRDFHighLight\r\n\t#endif\r\n#endif\r\n\r\n#define PI 3.14159265359\r\n#define INV_PI 0.31830988618\r\n\r\nmediump float pow4(mediump float x)\r\n{\r\n\treturn x * x * x * x;\r\n}\r\n\r\nmediump float pow5(mediump float x)\r\n{\r\n\treturn x * x * x * x * x;\r\n}\r\n\r\nmediump vec3 fresnelLerp(mediump vec3 F0,mediump vec3 F90,mediump float cosA)\r\n{\r\n\tfloat t = pow5(1.0 - cosA); // ala Schlick interpoliation\r\n\treturn mix(F0, F90, t);\r\n}\r\n\r\nmediump vec3 fresnelTerm(mediump vec3 F0,mediump float cosA)\r\n{\r\n\tfloat t = pow5(1.0 - cosA); // ala Schlick interpoliation\r\n\treturn F0 + (vec3(1.0) - F0) * t;\r\n}\r\n\r\n// approximage Schlick with ^4 instead of ^5\r\nmediump vec3 fresnelLerpFast (mediump vec3 F0, mediump vec3 F90,mediump float cosA)\r\n{\r\n mediump float t = pow4 (1.0 - cosA);\r\n return mix (F0, F90, t);\r\n}\r\n\r\nfloat smoothnessToPerceptualRoughness(float smoothness)\r\n{\r\n return 1.0 - smoothness;\r\n}\r\n\r\nfloat perceptualRoughnessToRoughness(float perceptualRoughness)\r\n{\r\n return perceptualRoughness * perceptualRoughness;\r\n}\r\n\r\nvec3 safeNormalize(vec3 inVec)\r\n{\r\n\tfloat dp3 = max(0.001,dot(inVec,inVec));\r\n\treturn inVec * inversesqrt(dp3);\r\n}\r\n\r\n// Note: Disney diffuse must be multiply by diffuseAlbedo / PI. This is done outside of this function.\r\nmediump float disneyDiffuse(mediump float NdotV,mediump float NdotL,mediump float LdotH,mediump float perceptualRoughness)\r\n{\r\n\t//https://www.cnblogs.com/herenzhiming/articles/5790389.html\r\n\tmediump float fd90 = 0.5 + 2.0 * LdotH * LdotH * perceptualRoughness;\r\n\t// Two schlick fresnel term\r\n\tmediump float lightScatter = (1.0 + (fd90 - 1.0) * pow5(1.0 - NdotL));\r\n\tmediump float viewScatter = (1.0 + (fd90 - 1.0) * pow5(1.0 - NdotV));\r\n\r\n\treturn lightScatter * viewScatter;\r\n}\r\n\r\n// Ref: http://jcgt.org/published/0003/02/03/paper.pdf\r\nfloat smithJointGGXVisibilityTerm(float NdotL, float NdotV, float roughness)\r\n{\r\n\t// Original formulation:\r\n // lambda_v = (-1 + sqrt(a2 * (1 - NdotL2) / NdotL2 + 1)) * 0.5f;\r\n // lambda_l = (-1 + sqrt(a2 * (1 - NdotV2) / NdotV2 + 1)) * 0.5f;\r\n // G = 1 / (1 + lambda_v + lambda_l);\r\n\r\n\t// scientific code implement:\r\n\t// Reorder code to be more optimal\r\n // half a = roughness;\r\n // half a2 = a * a;\r\n\r\n // half lambdaV = NdotL * sqrt((-NdotV * a2 + NdotV) * NdotV + a2);\r\n // half lambdaL = NdotV * sqrt((-NdotL * a2 + NdotL) * NdotL + a2);\r\n\r\n // Simplify visibility term: (2.0f * NdotL * NdotV) / ((4.0f * NdotL * NdotV) * (lambda_v + lambda_l + 1e-5f));\r\n // return 0.5f / (lambdaV + lambdaL + 1e-5f); \r\n\t// This function is not intended to be running on Mobile,therefore epsilon is smaller than can be represented by half\r\n\r\n\t// Approximation of the above formulation (simplify the sqrt, not mathematically correct but close enough)\r\n\tfloat a = roughness;\r\n\tfloat lambdaV = NdotL * (NdotV * (1.0 - a) + a);\r\n\tfloat lambdaL = NdotV * (NdotL * (1.0 - a) + a);\r\n\treturn 0.5 / (lambdaV + lambdaL + 1e-5);\r\n}\r\n\r\nfloat ggxTerm(float NdotH, float roughness)\r\n{\r\n\tfloat a2 = roughness * roughness;\r\n\tfloat d = (NdotH * a2 - NdotH) * NdotH + 1.0; // 2 mad\r\n\treturn INV_PI * a2 / (d * d + 1e-7); // This function is not intended to be running on Mobile,therefore epsilon is smaller than what can be represented by half//返回值小用half来返回\r\n}\r\n\r\n// BRDF1-------------------------------------------------------------------------------------\r\n\r\n// Note: BRDF entry points use smoothness and oneMinusReflectivity for optimization purposes,\r\n// mostly for DX9 SM2.0 level. Most of the math is being done on these (1-x) values, and that saves a few precious ALU slots.\r\n\r\n// Main Physically Based BRDF\r\n// Derived from Disney work and based on Torrance-Sparrow micro-facet model\r\n//\r\n// BRDF = kD / pi + kS * (D * V * F) / 4\r\n// I = BRDF * NdotL\r\n//\r\n// *NDF GGX:\r\n// *Smith for Visiblity term\r\n// *Schlick approximation for Fresnel\r\nmediump vec4 layaBRDFHighLight(mediump vec3 diffColor, mediump vec3 specColor, mediump float oneMinusReflectivity, float perceptualRoughness,float roughness,mediump float nv,vec3 normal, vec3 viewDir,LayaLight light)\r\n{\r\n\tvec3 halfDir = safeNormalize(viewDir-light.dir);\r\n\r\n\tfloat nl = clamp(dot(normal, -light.dir),0.0,1.0);\r\n\tfloat nh = clamp(dot(normal, halfDir),0.0,1.0);\r\n\tmediump float lv = clamp(dot(light.dir, viewDir),0.0,1.0);\r\n\tmediump float lh = clamp(dot(light.dir, -halfDir),0.0,1.0);\r\n\r\n\t// Diffuse term\r\n\tmediump float diffuseTerm = disneyDiffuse(nv, nl, lh, perceptualRoughness) * nl;\r\n\r\n\t// Specular term\r\n // HACK: theoretically we should divide diffuseTerm by Pi and not multiply specularTerm!\r\n // BUT that will make shader look significantly darker than Legacy ones\r\n\r\n\t// GGX with roughtness to 0 would mean no specular at all, using max(roughness, 0.002) here to match HDrenderloop roughtness remapping.\r\n\troughness = max(roughness, 0.002);\r\n\tfloat V = smithJointGGXVisibilityTerm(nl, nv, roughness);\r\n\tfloat D = ggxTerm(nh, roughness);\r\n\r\n\tfloat specularTerm = V * D * PI; // Torrance-Sparrow model, Fresnel is applied later\r\n\r\n\t//#ifdef LAYA_COLORSPACE_GAMMA\r\n\tspecularTerm = sqrt(max(1e-4, specularTerm));\r\n\t//#endif\r\n\tspecularTerm = max(0.0, specularTerm * nl);\r\n\t\t\r\n\tmediump vec3 color = diffColor * light.color * diffuseTerm + specularTerm * light.color * fresnelTerm(specColor, lh);\r\n\treturn vec4(color, 1.0);\r\n}\r\n\r\nvec4 layaBRDFHighGI(mediump vec3 diffColor,mediump vec3 specColor,mediump float oneMinusReflectivity,float smoothness ,float perceptualRoughness,float roughness,mediump float nv,vec3 normal, vec3 viewDir,LayaGI gi)\r\n{\r\n\t// surfaceReduction = Int D(NdotH) * NdotH * Id(NdotL>0) dH = 1/(roughness^2+1)\r\n\tfloat surfaceReduction;\r\n\tsurfaceReduction = 1.0 - 0.28*roughness*perceptualRoughness;// 1-0.28*x^3 as approximation for (1/(x^4+1))^(1/2.2) on the domain [0;1]\r\n\tfloat grazingTerm = clamp(smoothness + (1.0 - oneMinusReflectivity),0.0,1.0);\r\n\tmediump vec3 color =diffColor * gi.diffuse + surfaceReduction * gi.specular * fresnelLerp(specColor,vec3(grazingTerm), nv);\r\n\treturn vec4(color,1.0);\r\n}\r\n// BRDF1-------------------------------------------------------------------------------------\r\n\r\n\r\n// BRDF2-------------------------------------------------------------------------------------\r\n// Based on Minimalist CookTorrance BRDF\r\n// Implementation is slightly different from original derivation: http://www.thetenthplanet.de/archives/255\r\n//\r\n// *NDF [Modified] GGX:\r\n// *Modified Kelemen and Szirmay-​Kalos for Visibility term\r\n// *Fresnel approximated with 1/LdotH\r\nmediump vec4 layaBRDFLowLight (mediump vec3 diffColor, mediump vec3 specColor,mediump float oneMinusReflectivity,float perceptualRoughness,float roughness,mediump float nv,vec3 normal,vec3 viewDir,LayaLight light)\r\n{\r\n vec3 halfDir = safeNormalize (viewDir-light.dir);\r\n mediump float nl = clamp(dot(normal, -light.dir),0.0,1.0);\r\n float nh = clamp(dot(normal, halfDir),0.0,1.0);\r\n float lh = clamp(dot(-light.dir, halfDir),0.0,1.0);\r\n\r\n // GGX Distribution multiplied by combined approximation of Visibility and Fresnel\r\n // See \"Optimizing PBR for Mobile\" from Siggraph 2015 moving mobile graphics course\r\n // https://community.arm.com/events/1155\r\n mediump float a = roughness;\r\n float a2 = a*a;\r\n\r\n float d = nh * nh * (a2 - 1.0) + 1.00001;\r\n\t// #ifdef LAYA_COLORSPACE_GAMMA\r\n\t\t// Tighter approximation for Gamma only rendering mode!\r\n\t\t// DVF = sqrt(DVF);\r\n\t\t// DVF = (a * sqrt(.25)) / (max(sqrt(0.1), lh)*sqrt(roughness + .5) * d);\r\n\t\tfloat specularTerm = a / (max(0.32, lh) * (1.5 + roughness) * d);\r\n\t// #else\r\n\t// \tfloat specularTerm = a2 / (max(0.1f, lh*lh) * (roughness + 0.5f) * (d * d) * 4);\r\n\t// #endif\r\n\r\n // on mobiles (where half actually means something) denominator have risk of overflow\r\n // clamp below was added specifically to \"fix\" that, but dx compiler (we convert bytecode to metal/gles)\r\n // sees that specularTerm have only non-negative terms, so it skips max(0,..) in clamp (leaving only min(100,...))\r\n\r\n\t//#if defined (SHADER_API_MOBILE)\r\n specularTerm = specularTerm - 1e-4;\r\n\t//#endif\r\n\r\n\t// #else\r\n\t\t// // Legacy\r\n\t\t// half specularPower = PerceptualRoughnessToSpecPower(perceptualRoughness);\r\n\t\t// // Modified with approximate Visibility function that takes roughness into account\r\n\t\t// // Original ((n+1)*N.H^n) / (8*Pi * L.H^3) didn't take into account roughness\r\n\t\t// // and produced extremely bright specular at grazing angles\r\n\r\n\t\t// half invV = lh * lh * smoothness + perceptualRoughness * perceptualRoughness; // approx ModifiedKelemenVisibilityTerm(lh, perceptualRoughness);\r\n\t\t// half invF = lh;\r\n\r\n\t\t// half specularTerm = ((specularPower + 1) * pow (nh, specularPower)) / (8 * invV * invF + 1e-4h);\r\n\r\n\t\t// #ifdef LAYA_COLORSPACE_GAMMA\r\n\t\t// \tspecularTerm = sqrt(max(1e-4f, specularTerm));\r\n\t\t// #endif\r\n\t// #endif\r\n\r\n\t// #if defined (SHADER_API_MOBILE)\r\n\t\tspecularTerm = clamp(specularTerm, 0.0, 100.0); // Prevent FP16 overflow on mobiles\r\n\t// #endif\r\n \r\n mediump vec3 color = (diffColor + specularTerm * specColor) * light.color * nl;\r\n\r\n return vec4(color, 1.0);\r\n}\r\n\r\nmediump vec4 layaBRDFLowGI (mediump vec3 diffColor, mediump vec3 specColor,mediump float oneMinusReflectivity,mediump float smoothness,float perceptualRoughness,float roughness,mediump float nv,vec3 normal,vec3 viewDir,LayaGI gi)\r\n{\r\n\t// surfaceReduction = Int D(NdotH) * NdotH * Id(NdotL>0) dH = 1/(realRoughness^2+1)\r\n\r\n // 1-0.28*x^3 as approximation for (1/(x^4+1))^(1/2.2) on the domain [0;1]\r\n // 1-x^3*(0.6-0.08*x) approximation for 1/(x^4+1)\r\n\t// #ifdef LAYA_COLORSPACE_GAMMA\r\n\t\tmediump float surfaceReduction = 0.28;\r\n\t// #else\r\n\t\t// mediump float surfaceReduction = (0.6-0.08*perceptualRoughness);\r\n\t// #endif\r\n\r\n surfaceReduction = 1.0 - roughness*perceptualRoughness*surfaceReduction;\r\n\r\n\tmediump float grazingTerm = clamp(smoothness + (1.0-oneMinusReflectivity),0.0,1.0);\r\n\tmediump vec3 color =gi.diffuse * diffColor+ surfaceReduction * gi.specular * fresnelLerpFast (specColor, vec3(grazingTerm), nv);\r\n\r\n return vec4(color, 1.0);\r\n}\r\n// BRDF2-------------------------------------------------------------------------------------";
  29631. var PBRCore = "struct FragmentCommonData{\r\n\tvec3 diffColor;\r\n\tvec3 specColor;\r\n\tfloat oneMinusReflectivity;\r\n\tfloat smoothness;\r\n\t//vec3 eyeVec;TODO:maybe can remove\r\n\t//float alpha;\r\n\t//vec3 reflUVW;\r\n};\r\n\r\n#if !defined(SETUP_BRDF_INPUT)//shader内部的宏需要将改成#ifdef改成#if类型 不然会被Laya的shader分析器优化掉\r\n #define SETUP_BRDF_INPUT metallicSetup//default is metallicSetup,also can be other. \r\n#endif\r\n\r\nconst mediump vec4 dielectricSpecularColor = vec4(0.220916301, 0.220916301, 0.220916301, 1.0 - 0.220916301);\r\n\r\nmediump vec3 diffuseAndSpecularFromMetallic(mediump vec3 albedo,mediump float metallic, out mediump vec3 specColor, out mediump float oneMinusReflectivity)\r\n{\r\n\tspecColor = mix(dielectricSpecularColor.rgb, albedo, metallic);\r\n\toneMinusReflectivity= dielectricSpecularColor.a*(1.0-metallic);//diffuse proportion\r\n\treturn albedo * oneMinusReflectivity;\r\n}\r\n\r\nmediump float specularStrength(mediump vec3 specular)\r\n{\r\n return max (max (specular.r, specular.g), specular.b);\r\n}\r\n\r\n// Diffuse/Spec Energy conservation\r\nmediump vec3 energyConservationBetweenDiffuseAndSpecular (mediump vec3 albedo, mediump vec3 specColor, out mediump float oneMinusReflectivity)\r\n{\r\n\toneMinusReflectivity = 1.0 - specularStrength(specColor);\r\n return albedo * (vec3(1.0) - specColor);\r\n}\r\n\r\n#ifdef TRANSPARENTBLEND\r\n\tmediump vec3 preMultiplyAlpha (mediump vec3 diffColor, mediump float alpha, mediump float oneMinusReflectivity,out mediump float modifiedAlpha)\r\n\t{\r\n\t\t// Transparency 'removes' from Diffuse component\r\n\t\tdiffColor *= alpha;\r\n\t\t// Reflectivity 'removes' from the rest of components, including Transparency\r\n\t\t// modifiedAlpha = 1.0-(1.0-alpha)*(1.0-reflectivity) = 1.0-(oneMinusReflectivity - alpha*oneMinusReflectivity) = 1.0-oneMinusReflectivity + alpha*oneMinusReflectivity\r\n\t\tmodifiedAlpha = 1.0 - oneMinusReflectivity + alpha*oneMinusReflectivity;\r\n\t\treturn diffColor;\r\n\t}\r\n#endif\r\n\r\nFragmentCommonData metallicSetup(vec2 uv)\r\n{\r\n\tmediump vec2 metallicGloss = getMetallicGloss(uv);\r\n\tmediump float metallic = metallicGloss.x;\r\n\tmediump float smoothness = metallicGloss.y; // this is 1 minus the square root of real roughness m.\r\n\tmediump float oneMinusReflectivity;\r\n\tmediump vec3 specColor;\r\n\tmediump vec3 diffColor = diffuseAndSpecularFromMetallic(albedo(uv), metallic,/*out*/specColor,/*out*/oneMinusReflectivity);\r\n\r\n\tFragmentCommonData o;\r\n\to.diffColor = diffColor;\r\n\to.specColor = specColor;\r\n\to.oneMinusReflectivity = oneMinusReflectivity;\r\n\to.smoothness = smoothness;\r\n\treturn o;\r\n}\r\n\r\nFragmentCommonData specularSetup(vec2 uv)\r\n{\r\n mediump vec4 specGloss = specularGloss(uv);\r\n mediump vec3 specColor = specGloss.rgb;\r\n mediump float smoothness = specGloss.a;\r\n\r\n mediump float oneMinusReflectivity;\r\n mediump vec3 diffColor = energyConservationBetweenDiffuseAndSpecular (albedo(uv), specColor, /*out*/ oneMinusReflectivity);\r\n\r\n FragmentCommonData o;\r\n o.diffColor = diffColor;\r\n o.specColor = specColor;\r\n o.oneMinusReflectivity = oneMinusReflectivity;\r\n o.smoothness = smoothness;\r\n return o;\r\n}\r\n\r\nLayaGI fragmentGI(float smoothness,vec3 eyeVec,mediump float occlusion,mediump vec2 lightmapUV,vec3 worldnormal,vec3 worldPos)\r\n{\r\n\tLayaGIInput giInput;\r\n\t#ifdef LIGHTMAP\r\n\t\tgiInput.lightmapUV=lightmapUV;\r\n\t#endif\r\n\tgiInput.worldPos = worldPos;\r\n\r\n\tvec3 worldViewDir = -eyeVec;\r\n\tmediump vec4 uvwRoughness;\r\n\tuvwRoughness.rgb = reflect(worldViewDir, worldnormal);//reflectUVW\r\n\tuvwRoughness.a= smoothnessToPerceptualRoughness(smoothness);//perceptualRoughness\r\n\r\n\treturn layaGlobalIllumination(giInput,occlusion, worldnormal, uvwRoughness);\r\n}\r\n\r\n\r\nvec3 perPixelWorldNormal(vec2 uv,vec3 normal,vec3 binormal,vec3 tangent)\r\n{\r\n\t#ifdef NORMALTEXTURE\r\n\t\tmediump vec3 normalTangent=normalInTangentSpace(uv);\r\n\t\tvec3 normalWorld = normalize(tangent * normalTangent.x + binormal * normalTangent.y + normal * normalTangent.z);\r\n\t#else\r\n\t\tvec3 normalWorld = normalize(normal);\r\n\t#endif\r\n\t\treturn normalWorld;\r\n}\r\n\r\nvoid fragmentForward()\r\n{\r\n\tvec2 uv;\r\n\t#if defined(ALBEDOTEXTURE)||defined(METALLICGLOSSTEXTURE)||defined(NORMALTEXTURE)||defined(EMISSIONTEXTURE)||defined(OCCLUSIONTEXTURE)||defined(PARALLAXTEXTURE)\r\n\t\t#ifdef PARALLAXTEXTURE\r\n\t\t\tuv = parallax(v_Texcoord0,normalize(v_ViewDirForParallax));\r\n\t\t#else\r\n\t\t\tuv = v_Texcoord0;\r\n\t\t#endif\r\n\t#endif\r\n\r\n\tmediump float alpha = getAlpha(uv);\r\n\t#ifdef ALPHATEST\r\n\t\tif(alpha<u_AlphaTestValue)\r\n\t\t\tdiscard;\r\n\t#endif\r\n\r\n\tFragmentCommonData o = SETUP_BRDF_INPUT(uv);\r\n\t\r\n\tvec3 binormal;\r\n\tvec3 tangent;\r\n\t#ifdef NORMALTEXTURE\r\n\t\ttangent = v_Tangent;\r\n\t\tbinormal = v_Binormal;\r\n\t#endif\r\n\r\n\tvec3 normal = v_Normal;\r\n\tvec3 normalWorld = perPixelWorldNormal(uv,normal,binormal,tangent);//In FS if the normal use mediump before normalize will cause precision prolem in mobile device.\r\n\tvec3 eyeVec = normalize(v_EyeVec);\r\n\tvec3 posworld = v_PositionWorld;\r\n\r\n\t#ifdef TRANSPARENTBLEND\r\n\t\to.diffColor=preMultiplyAlpha(o.diffColor,alpha,o.oneMinusReflectivity,/*out*/alpha);// shader relies on pre-multiply alpha-blend (srcBlend = One, dstBlend = OneMinusSrcAlpha)\r\n\t#endif\r\n\r\n\tmediump float occlusion = getOcclusion(uv);\r\n\tmediump vec2 lightMapUV;\r\n\t#ifdef LIGHTMAP\r\n\t\tlightMapUV=v_LightMapUV;\r\n\t#endif\r\n\tfloat perceptualRoughness = smoothnessToPerceptualRoughness(o.smoothness);\r\n\tfloat roughness = perceptualRoughnessToRoughness(perceptualRoughness);\r\n\tfloat nv = abs(dot(normalWorld, eyeVec));\r\n\tLayaGI gi =fragmentGI(o.smoothness,eyeVec,occlusion,lightMapUV,normalWorld,posworld);\r\n\tvec4 color = LAYA_BRDF_GI(o.diffColor,o.specColor,o.oneMinusReflectivity,o.smoothness,perceptualRoughness,roughness,nv,normalWorld,eyeVec,gi);\r\n\t\r\n\tfloat shadowAttenuation = 1.0;\r\n\t#ifdef LEGACYSINGLELIGHTING\r\n\t\t#ifdef DIRECTIONLIGHT\r\n\t\t\t#if defined(CALCULATE_SHADOWS)//shader中自定义的宏不可用ifdef 必须改成if defined\r\n\t\t\t\t#ifdef SHADOW_CASCADE\r\n\t\t\t\t\tvec4 shadowCoord = getShadowCoord(vec4(v_PositionWorld,1.0));\r\n\t\t\t\t#else\r\n\t\t\t\t\tvec4 shadowCoord = v_ShadowCoord;\r\n\t\t\t\t#endif\r\n\t\t\t\tshadowAttenuation=sampleShadowmap(shadowCoord);\r\n\t\t\t#endif\r\n\t\t\tLayaLight dirLight = layaDirectionLightToLight(u_DirectionLight,shadowAttenuation);\r\n\t\t\tcolor+= LAYA_BRDF_LIGHT(o.diffColor,o.specColor,o.oneMinusReflectivity,perceptualRoughness,roughness,nv,normalWorld,eyeVec,dirLight);\r\n\t\t#endif\r\n\t\r\n\t\t#ifdef POINTLIGHT\r\n\t\t\tshadowAttenuation = 1.0;\r\n\t\t\tLayaLight poiLight = layaPointLightToLight(posworld,normalWorld,u_PointLight,shadowAttenuation);\r\n\t\t\tcolor+= LAYA_BRDF_LIGHT(o.diffColor,o.specColor,o.oneMinusReflectivity,perceptualRoughness,roughness,nv,normalWorld,eyeVec,poiLight);\r\n\t\t#endif\r\n\t\t\r\n\t\t#ifdef SPOTLIGHT\r\n\t\t\tshadowAttenuation = 1.0;\r\n\t\t\t#if defined(CALCULATE_SPOTSHADOWS)//shader中自定义的宏不可用ifdef 必须改成if defined\r\n\t\t\t\tvec4 spotShadowcoord = v_SpotShadowCoord;\r\n\t\t\t\tshadowAttenuation = sampleSpotShadowmap(spotShadowcoord);\r\n\t\t\t#endif\r\n\t\t LayaLight spoLight = layaSpotLightToLight(posworld,normalWorld,u_SpotLight,shadowAttenuation);\r\n\t\t\tcolor+= LAYA_BRDF_LIGHT(o.diffColor,o.specColor,o.oneMinusReflectivity,perceptualRoughness,roughness,nv,normalWorld,eyeVec,spoLight);\r\n\t\t#endif\r\n\t#else\r\n\t \t#ifdef DIRECTIONLIGHT\r\n\t\t\tfor (int i = 0; i < MAX_LIGHT_COUNT; i++) \r\n\t\t\t{\r\n\t\t\t\tshadowAttenuation = 1.0;\r\n\t\t\t\tif(i >= u_DirationLightCount)\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t#if defined(CALCULATE_SHADOWS)//shader中自定义的宏不可用ifdef 必须改成if defined\r\n\t\t\t\t\tif(i == 0)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\t#ifdef SHADOW_CASCADE\r\n\t\t\t\t\t\t\tvec4 shadowCoord = getShadowCoord(vec4(v_PositionWorld,1.0));\r\n\t\t\t\t\t\t#else\r\n\t\t\t\t\t\t\tvec4 shadowCoord = v_ShadowCoord;\r\n\t\t\t\t\t\t#endif\r\n\t\t\t\t\t\tshadowAttenuation *= sampleShadowmap(shadowCoord);\r\n\t\t\t\t\t}\r\n\t\t\t\t#endif\r\n\t\t\t\tDirectionLight directionLight = getDirectionLight(u_LightBuffer,i);\r\n\t\t\t\tLayaLight dirLight = layaDirectionLightToLight(directionLight,shadowAttenuation);\r\n\t\t\t \tcolor+=LAYA_BRDF_LIGHT(o.diffColor,o.specColor,o.oneMinusReflectivity,perceptualRoughness,roughness,nv,normalWorld,eyeVec,dirLight);\r\n\t\t\t}\r\n\t \t#endif\r\n\t\t#if defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t\t\tivec4 clusterInfo =getClusterInfo(u_LightClusterBuffer,u_View,u_Viewport, v_PositionWorld,gl_FragCoord,u_ProjectionParams);\r\n\t\t\t#ifdef POINTLIGHT\r\n\t\t\t\tfor (int i = 0; i < MAX_LIGHT_COUNT; i++) \r\n\t\t\t\t{\r\n\t\t\t\t\tshadowAttenuation = 1.0;\r\n\t\t\t\t\tif(i >= clusterInfo.x)//PointLightCount\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tPointLight pointLight = getPointLight(u_LightBuffer,u_LightClusterBuffer,clusterInfo,i);\r\n\t\t\t\t\tLayaLight poiLight = layaPointLightToLight(posworld,normalWorld,pointLight,shadowAttenuation);\r\n\t\t\t\t\tcolor+= LAYA_BRDF_LIGHT(o.diffColor,o.specColor,o.oneMinusReflectivity,perceptualRoughness,roughness,nv,normalWorld,eyeVec,poiLight);\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t\t#ifdef SPOTLIGHT\r\n\t\t\t\tfor (int i = 0; i < MAX_LIGHT_COUNT; i++) \r\n\t\t\t\t{\r\n\t\t\t\t\tshadowAttenuation = 1.0;\r\n\t\t\t\t\tif(i >= clusterInfo.y)//SpotLightCount\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t#if defined(CALCULATE_SPOTSHADOWS)//shader中自定义的宏不可用ifdef 必须改成if defined\r\n\t\t\t\t\t\tif(i == 0)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tvec4 spotShadowcoord = v_SpotShadowCoord;\r\n\t\t\t\t\t\t\tshadowAttenuation= sampleSpotShadowmap(spotShadowcoord);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t#endif\r\n\t\t\t\t\tSpotLight spotLight = getSpotLight(u_LightBuffer,u_LightClusterBuffer,clusterInfo,i);\r\n\t\t\t\t\tLayaLight spoLight = layaSpotLightToLight(posworld,normalWorld,spotLight,shadowAttenuation);\r\n\t\t\t\t\tcolor+= LAYA_BRDF_LIGHT(o.diffColor,o.specColor,o.oneMinusReflectivity,perceptualRoughness,roughness,nv,normalWorld,eyeVec,spoLight);\r\n\t\t\t\t}\r\n\t\t\t#endif\r\n\t\t#endif\r\n\t #endif\r\n\r\n\t#ifdef EMISSION\r\n\t\tcolor.rgb += emission(uv);\r\n\t#endif\r\n\r\n\t#ifdef FOG\r\n\t\tfloat lerpFact=clamp((1.0/gl_FragCoord.w-u_FogStart)/u_FogRange,0.0,1.0);\r\n\t\tcolor.rgb=mix(color.rgb,u_FogColor,lerpFact);\r\n\t#endif\r\n\t\r\n\tgl_FragColor=vec4(color.rgb,alpha);\r\n}\r\n\r\n\r\n\r\n";
  29632. var PBRVSInput = "attribute vec4 a_Position;\r\n\r\n#ifdef GPU_INSTANCE\r\n\tattribute mat4 a_MvpMatrix;\r\n\tattribute mat4 a_WorldMat;\r\n#else\r\n\tuniform mat4 u_MvpMatrix;\r\n\tuniform mat4 u_WorldMat;\r\n#endif\r\n\r\n#ifdef BONE\r\n\tconst int c_MaxBoneCount = 24;\r\n\tattribute vec4 a_BoneIndices;\r\n\tattribute vec4 a_BoneWeights;\r\n\tuniform mat4 u_Bones[c_MaxBoneCount];\r\n#endif\r\n\r\nattribute vec3 a_Normal;\r\nvarying vec3 v_Normal; \r\n\r\n#if defined(NORMALTEXTURE)||defined(PARALLAXTEXTURE)\r\n\tattribute vec4 a_Tangent0;\r\n\tvarying vec3 v_Tangent;\r\n\tvarying vec3 v_Binormal;\r\n #ifdef PARALLAXTEXTURE\r\n\t varying vec3 v_ViewDirForParallax;\r\n #endif\r\n#endif\r\n\r\n#if defined(ALBEDOTEXTURE)||defined(METALLICGLOSSTEXTURE)||defined(NORMALTEXTURE)||defined(EMISSIONTEXTURE)||defined(OCCLUSIONTEXTURE)||defined(PARALLAXTEXTURE)||(defined(LIGHTMAP)&&defined(UV))\r\n\tattribute vec2 a_Texcoord0;\r\n\tvarying vec2 v_Texcoord0;\r\n#endif\r\n\r\n#if defined(LIGHTMAP)&&defined(UV1)\r\n\tattribute vec2 a_Texcoord1;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tuniform vec4 u_LightmapScaleOffset;\r\n\tvarying vec2 v_LightMapUV;\r\n#endif\r\n\r\nuniform vec3 u_CameraPos;\r\nvarying vec3 v_EyeVec;\r\nvarying vec3 v_PositionWorld;\r\nvarying float v_posViewZ;\r\n\r\n#if defined(CALCULATE_SHADOWS)&&!defined(SHADOW_CASCADE)\r\n\tvarying vec4 v_ShadowCoord;\r\n#endif\r\n\r\n#if defined(CALCULATE_SPOTSHADOWS)//shader中自定义的宏不可用ifdef 必须改成if defined\r\n\tvarying vec4 v_SpotShadowCoord;\r\n#endif\r\n\r\n#ifdef TILINGOFFSET\r\n\tuniform vec4 u_TilingOffset;\r\n#endif";
  29633. var PBRFSInput = "#ifdef ALPHATEST\r\n\tuniform float u_AlphaTestValue;\r\n#endif\r\n\r\nuniform vec4 u_AlbedoColor;\r\n\r\n#ifdef NORMALTEXTURE\r\n\tuniform sampler2D u_NormalTexture;\r\n\tuniform float u_NormalScale;\r\n#endif\r\n\r\n#ifdef ALBEDOTEXTURE\r\n\tuniform sampler2D u_AlbedoTexture;\r\n#endif\r\n\r\n#ifdef METALLICGLOSSTEXTURE\r\n\tuniform sampler2D u_MetallicGlossTexture;\r\n#endif\r\nuniform float u_Metallic;\r\n\r\n#ifdef SPECULARGLOSSTEXTURE\r\n\tuniform sampler2D u_SpecGlossTexture;\r\n#endif\r\nuniform vec3 u_SpecularColor;\r\n\r\nuniform float u_Smoothness;\r\nuniform float u_SmoothnessScale;\r\n\r\n#ifdef PARALLAXTEXTURE\r\n\tuniform sampler2D u_ParallaxTexture;\r\n\tuniform float u_ParallaxScale;\r\n\tvarying vec3 v_ViewDirForParallax;\r\n#endif\r\n\r\n#ifdef OCCLUSIONTEXTURE\r\n\tuniform sampler2D u_OcclusionTexture;\r\n\tuniform float u_occlusionStrength;\r\n#endif\r\n\r\n#ifdef EMISSION \r\n\t#ifdef EMISSIONTEXTURE\r\n\t\tuniform sampler2D u_EmissionTexture;\r\n\t#endif\r\n\tuniform vec4 u_EmissionColor;\r\n#endif\r\n\r\n#if defined(ALBEDOTEXTURE)||defined(METALLICGLOSSTEXTURE)||defined(NORMALTEXTURE)||defined(EMISSIONTEXTURE)||defined(OCCLUSIONTEXTURE)||defined(PARALLAXTEXTURE)\r\n\tvarying vec2 v_Texcoord0;\r\n#endif\r\n\r\n#ifdef LIGHTMAP\r\n\tvarying vec2 v_LightMapUV;\r\n\tuniform sampler2D u_LightMap;\r\n\t#ifdef LIGHTMAP_DIRECTIONAL\r\n\t\tuniform sampler2D u_LightMapDirection;\r\n\t#endif\r\n#endif\r\n\r\nvarying vec3 v_Normal; \r\n\r\n#if defined(DIRECTIONLIGHT)||defined(POINTLIGHT)||defined(SPOTLIGHT)\r\n\t#ifdef LEGACYSINGLELIGHTING\r\n\t\t#ifdef DIRECTIONLIGHT\r\n\t\t\tuniform DirectionLight u_DirectionLight;\r\n\t\t#endif\r\n\t\t#ifdef POINTLIGHT\r\n\t\t\tuniform PointLight u_PointLight;\r\n\t\t#endif\r\n\t\t#ifdef SPOTLIGHT\r\n\t\t\tuniform SpotLight u_SpotLight;\r\n\t\t#endif\r\n\t#else\r\n\t\tuniform mat4 u_View;\r\n\t\tuniform vec4 u_ProjectionParams;\r\n\t\tuniform vec4 u_Viewport;\r\n\t\tuniform int u_DirationLightCount;\r\n\t\tuniform sampler2D u_LightBuffer;\r\n\t\tuniform sampler2D u_LightClusterBuffer;\r\n\t#endif\r\n#endif\r\n\r\nvarying vec3 v_EyeVec;\r\n\r\n#ifdef NORMALTEXTURE\r\n\tvarying vec3 v_Tangent;\r\n\tvarying vec3 v_Binormal;\r\n#endif\r\n\r\n#ifdef FOG\r\n\tuniform float u_FogStart;\r\n\tuniform float u_FogRange;\r\n\tuniform vec3 u_FogColor;\r\n#endif\r\n\r\n\r\n//后面考虑宏TODO\r\nvarying vec3 v_PositionWorld;\r\n\r\n#if defined(CALCULATE_SHADOWS)&&!defined(SHADOW_CASCADE)\r\n\tvarying vec4 v_ShadowCoord;\r\n#endif\r\n\r\n#if defined(CALCULATE_SPOTSHADOWS)//shader中自定义的宏不可用ifdef 必须改成if defined\r\n\tvarying vec4 v_SpotShadowCoord;\r\n#endif\r\n\r\nmediump float lerpOneTo(mediump float b, mediump float t)\r\n{\r\n mediump float oneMinusT = 1.0 - t;\r\n return oneMinusT + b * t;\r\n}\r\n\r\n#ifdef EMISSION \r\n\tvec3 emission(vec2 uv)\r\n\t{\r\n\t\t#ifdef EMISSIONTEXTURE\r\n\t\t\treturn texture2D(u_EmissionTexture, uv).rgb * u_EmissionColor.rgb;\r\n\t\t#else\r\n\t\t\treturn u_EmissionColor.rgb;\r\n\t\t#endif\r\n\t}\r\n#endif\r\n\r\nmediump float getAlpha(vec2 uv)\r\n{\r\n\t#ifdef SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA\r\n\t\treturn u_AlbedoColor.a;\r\n\t#else\r\n\t\t#ifdef ALBEDOTEXTURE\r\n\t\t\treturn texture2D(u_AlbedoTexture, uv).a * u_AlbedoColor.a;\r\n\t\t#else\r\n\t\t\treturn u_AlbedoColor.a;\r\n\t\t#endif\r\n\t#endif\r\n}\r\n\r\nmediump float getOcclusion(vec2 uv)\r\n{\r\n\t#ifdef OCCLUSIONTEXTURE\r\n\t\tmediump float occ = texture2D(u_OcclusionTexture, uv).g;\r\n\t\treturn lerpOneTo(occ, u_occlusionStrength);\r\n\t#else\r\n\t\treturn 1.0;\r\n\t#endif\r\n}\r\n\r\nmediump vec3 albedo(vec2 uv)\r\n{\r\n\t#ifdef ALBEDOTEXTURE\r\n\t\treturn u_AlbedoColor.rgb * texture2D(u_AlbedoTexture, uv).rgb;\r\n\t#else\r\n\t\treturn u_AlbedoColor.rgb;\r\n\t#endif\r\n\t//TODO:Detail Texture\r\n}\r\n\r\nmediump vec2 getMetallicGloss(vec2 uv)\r\n{\r\n\tmediump vec2 ms;//x is metallic,y is smoothness\r\n\t#ifdef METALLICGLOSSTEXTURE\r\n\t\t#ifdef SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA\r\n\t\t\tms.x = texture2D(u_MetallicGlossTexture, uv).r;\r\n\t\t\t#ifdef ALBEDOTEXTURE\r\n\t\t\t\tms.y = texture2D(u_AlbedoTexture, uv).a*u_SmoothnessScale;\r\n\t\t\t#else\r\n\t\t\t\tms.y = u_SmoothnessScale;\r\n\t\t\t#endif\r\n\t\t#else\r\n\t\t\tms = texture2D(u_MetallicGlossTexture, uv).ra;\r\n\t\t\tms.y *= u_SmoothnessScale;\r\n\t\t#endif\r\n\t#else\r\n\t\tms.x = u_Metallic;\r\n\t\t#ifdef SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA\r\n\t\t\t#ifdef ALBEDOTEXTURE\r\n\t\t\t\tms.y = texture2D(u_AlbedoTexture, uv).a * u_SmoothnessScale;\r\n\t\t\t#else\r\n\t\t\t\tms.y = u_SmoothnessScale;\r\n\t\t\t#endif\r\n\t\t#else\r\n\t\t\tms.y = u_Smoothness;\r\n\t\t#endif\r\n\t#endif\r\n\treturn ms;\r\n}\r\n\r\nmediump vec4 specularGloss(vec2 uv)\r\n{\r\n\tmediump vec4 sg;\r\n\t#ifdef SPECULARGLOSSTEXTURE\r\n\t\t#ifdef SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA\r\n\t\t\tsg.rgb = texture2D(u_SpecGlossTexture, uv).rgb;\r\n\t\t\t#ifdef ALBEDOTEXTURE\r\n\t\t\t\tsg.a = texture2D(u_AlbedoTexture, uv).a*u_SmoothnessScale;\r\n\t\t\t#else\r\n\t\t\t\tsg.a = u_SmoothnessScale;\r\n\t\t\t#endif\r\n\t\t#else\r\n\t\t\tsg = texture2D(u_SpecGlossTexture, uv);\r\n\t\t\tsg.a *= u_SmoothnessScale;\r\n\t\t#endif\r\n\t#else\r\n\t\tsg.rgb = u_SpecularColor.rgb;\r\n\t\t#ifdef SMOOTHNESSSOURCE_ALBEDOTEXTURE_ALPHA\r\n\t\t\t#ifdef ALBEDOTEXTURE\r\n\t\t\t\tsg.a = texture2D(u_AlbedoTexture, uv).a * u_SmoothnessScale;\r\n\t\t\t#else\r\n\t\t\t\tsg.a = u_SmoothnessScale;\r\n\t\t\t#endif\r\n\t\t#else\r\n\t\t\tsg.a = u_Smoothness;\r\n\t\t#endif\r\n\t#endif\r\n\t\treturn sg;\r\n}\r\n\r\n\r\n#ifdef NORMALTEXTURE\r\n\tmediump vec3 unpackScaleNormal(mediump vec3 packednormal, mediump float bumpScale)\r\n\t{\r\n\t\tmediump vec3 normal = packednormal.xyz * 2.0 - 1.0;\r\n\t\tnormal.y=-normal.y;//NOTE:because unity to LayaAir coordSystem.\r\n\t\tnormal.xy *= bumpScale;\r\n\t\treturn normal;\r\n\t}\r\n\t\r\n\tmediump vec3 normalInTangentSpace(vec2 texcoords)\r\n\t{\r\n\t\tmediump vec3 normalTangent = unpackScaleNormal(texture2D(u_NormalTexture, texcoords).rgb,u_NormalScale);\r\n\t\treturn normalTangent;\r\n\t}\r\n#endif\r\n\r\n#ifdef PARALLAXTEXTURE\r\n\tmediump vec2 parallaxOffset1Step(mediump float h, mediump float height, mediump vec3 viewDir)\r\n\t{\r\n\t\th = h * height - height / 2.0;\r\n\t\tviewDir.z += 0.42;\r\n\t\treturn h * (viewDir.xy / viewDir.z);\r\n\t}\r\n\r\n\tvec2 parallax(vec2 texcoords, mediump vec3 viewDir)\r\n\t{\r\n\t\tmediump float h = texture2D(u_ParallaxTexture, texcoords.xy).g;\r\n\t\tvec2 offset = parallaxOffset1Step(h, u_ParallaxScale, viewDir);\r\n\t\treturn texcoords+offset;\r\n\t}\r\n#endif\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n";
  29634. var PBRVertex = "vec2 transformLightMapUV(in vec2 texcoord,in vec4 lightmapScaleOffset)\r\n{\r\n\tvec2 lightMapUV=vec2(texcoord.x,1.0-texcoord.y)*lightmapScaleOffset.xy+lightmapScaleOffset.zw;\r\n\tlightMapUV.y=1.0-lightMapUV.y;\r\n\treturn lightMapUV; \r\n}\r\n\r\nvoid vertexForward()\r\n{\r\n\tvec4 position;\r\n\t#ifdef BONE\r\n\t\tmat4 skinTransform;\r\n\t \t#ifdef SIMPLEBONE\r\n\t\t\tfloat currentPixelPos;\r\n\t\t\t#ifdef GPU_INSTANCE\r\n\t\t\t\tcurrentPixelPos = a_SimpleTextureParams.x+a_SimpleTextureParams.y;\r\n\t\t\t#else\r\n\t\t\t\tcurrentPixelPos = u_SimpleAnimatorParams.x+u_SimpleAnimatorParams.y;\r\n\t\t\t#endif\r\n\t\t\tfloat offset = 1.0/u_SimpleAnimatorTextureSize;\r\n\t\t\tskinTransform = loadMatFromTexture(currentPixelPos,int(a_BoneIndices.x),offset) * a_BoneWeights.x;\r\n\t\t\tskinTransform += loadMatFromTexture(currentPixelPos,int(a_BoneIndices.y),offset) * a_BoneWeights.y;\r\n\t\t\tskinTransform += loadMatFromTexture(currentPixelPos,int(a_BoneIndices.z),offset) * a_BoneWeights.z;\r\n\t\t\tskinTransform += loadMatFromTexture(currentPixelPos,int(a_BoneIndices.w),offset) * a_BoneWeights.w;\r\n\t\t#else\r\n\t\t\tskinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;\r\n\t\t\tskinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;\r\n\t\t\tskinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;\r\n\t\t\tskinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;\r\n\t\t#endif\r\n\t\tposition=skinTransform*a_Position;\r\n\t #else\r\n\t\tposition=a_Position;\r\n\t#endif\r\n\r\n\t#ifdef GPU_INSTANCE\r\n\t\tgl_Position = a_MvpMatrix * position;\r\n\t#else\r\n\t\tgl_Position = u_MvpMatrix * position;\r\n\t#endif\r\n\r\n\tmat4 worldMat;\r\n\t#ifdef GPU_INSTANCE\r\n\t\tworldMat = a_WorldMat;\r\n\t#else\r\n\t\tworldMat = u_WorldMat;\r\n\t#endif\r\n\r\n\tv_PositionWorld=(worldMat*position).xyz;\r\n\r\n\t#if defined(ALBEDOTEXTURE)||defined(METALLICGLOSSTEXTURE)||defined(NORMALTEXTURE)||defined(EMISSIONTEXTURE)||defined(OCCLUSIONTEXTURE)||defined(PARALLAXTEXTURE)\r\n\t\t#ifdef TILINGOFFSET\r\n\t\t\tv_Texcoord0=TransformUV(a_Texcoord0,u_TilingOffset);\r\n\t\t#else\r\n\t\t\tv_Texcoord0=a_Texcoord0;\r\n\t\t#endif\r\n\t#endif\r\n\r\n\tv_EyeVec =u_CameraPos-v_PositionWorld;//will normalize per-pixel\r\n\r\n\t#ifdef LIGHTMAP\r\n\t\tvec2 texcoord;\r\n\t\t#ifdef UV1\r\n\t\t\ttexcoord=a_Texcoord1;\r\n\t\t#else\r\n\t\t\ttexcoord=a_Texcoord0;\r\n\t\t#endif\r\n\t\tv_LightMapUV=transformLightMapUV(texcoord,u_LightmapScaleOffset);\r\n\t#endif\r\n\r\n\tmat3 worldInvMat;\r\n\t#ifdef BONE\r\n\t\tworldInvMat=INVERSE_MAT(mat3(worldMat*skinTransform));\r\n\t#else\r\n\t\tworldInvMat=INVERSE_MAT(mat3(worldMat));\r\n\t#endif\r\n\r\n\tv_Normal=normalize(a_Normal*worldInvMat);//if no normalize will cause precision problem.\r\n\r\n\t#ifdef NORMALTEXTURE\r\n\t\tv_Tangent=normalize(a_Tangent0.xyz*worldInvMat);\r\n\t\tv_Binormal=cross(v_Normal,v_Tangent)*a_Tangent0.w;\r\n\t#endif\r\n\r\n\t#ifdef PARALLAXTEXTURE\r\n\t\tvec3 binormal = cross(a_Normal, a_Tangent0.xyz)*a_Tangent0.w;\r\n\t\tmat3 objectTBN = mat3(a_Tangent0.xyz, binormal, a_Normal);\r\n\t\tv_ViewDirForParallax =(u_CameraPos*worldInvMat-position.xyz)*objectTBN;\r\n\t#endif\r\n\r\n\t#if defined(CALCULATE_SHADOWS)&&!defined(SHADOW_CASCADE)\r\n\t\tv_ShadowCoord = getShadowCoord(vec4(v_PositionWorld,1.0));\r\n\t#endif\r\n\r\n\t#if defined(CALCULATE_SPOTSHADOWS)//shader中自定义的宏不可用ifdef 必须改成if defined\r\n\t\tv_SpotShadowCoord = u_SpotViewProjectMatrix*vec4(v_PositionWorld,1.0);\r\n\t#endif\r\n}";
  29635. var BloomVS = "#include \"Lighting.glsl\";\r\n#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\nattribute vec4 a_PositionTexcoord;\r\nvarying vec2 v_Texcoord0;\r\n\r\nvoid main() {\r\n\tgl_Position = vec4(a_PositionTexcoord.xy, 0.0, 1.0);\r\n\tv_Texcoord0 = a_PositionTexcoord.zw;\r\n\tgl_Position = remapGLPositionZ(gl_Position);\r\n}";
  29636. var BloomDownsample13PS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#include \"Colors.glsl\";\r\n#include \"Sampling.glsl\";\r\n\r\nvarying vec2 v_Texcoord0;\r\n\r\nuniform sampler2D u_MainTex;\r\nuniform vec4 u_MainTex_TexelSize;\r\n\r\nvoid fragDownsample13() {\r\n\tmediump vec4 color = downsampleBox13Tap(u_MainTex, v_Texcoord0, u_MainTex_TexelSize.xy);\r\n\tgl_FragColor = color;\r\n}\r\n\r\nvoid main() {\r\n\tfragDownsample13();\r\n}";
  29637. var BloomDownsample4PS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#include \"Colors.glsl\";\r\n#include \"Sampling.glsl\";\r\n\r\nvarying vec2 v_Texcoord0;\r\n\r\nuniform sampler2D u_MainTex;\r\nuniform vec4 u_MainTex_TexelSize;\r\n\r\nvoid fragDownsample4() {\r\n\tmediump vec4 color = downsampleBox4Tap(u_MainTex, v_Texcoord0, u_MainTex_TexelSize.xy);\r\n\tgl_FragColor = color;\r\n}\r\n\r\nvoid main() {\r\n\tfragDownsample4();\r\n}";
  29638. var BloomPrefilter13PS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#include \"Colors.glsl\";\r\n#include \"Sampling.glsl\";\r\n\r\nvarying vec2 v_Texcoord0;\r\n\r\nuniform sampler2D u_MainTex;\r\nuniform sampler2D u_AutoExposureTex;\r\nuniform vec4 u_MainTex_TexelSize;\r\nuniform vec4 u_Threshold; // x: threshold value (linear), y: threshold - knee, z: knee * 2, w: 0.25 / knee\r\nuniform vec4 u_Params; // x: clamp, yzw: unused\r\n\r\nmediump vec4 prefilter(mediump vec4 color, vec2 uv) {\r\n\tmediump float autoExposure = texture2D(u_AutoExposureTex, uv).r;\r\n\tcolor *= autoExposure;\r\n\tcolor = min(vec4(u_Params.x), color); // clamp to max\r\n\tcolor = quadraticThreshold(color, u_Threshold.x, u_Threshold.yzw);\r\n\treturn color;\r\n}\r\n\r\nvoid fragPrefilter13() {\r\n\tmediump vec4 color = downsampleBox13Tap(u_MainTex, v_Texcoord0, u_MainTex_TexelSize.xy);\r\n\tgl_FragColor = prefilter(safeHDR(color), v_Texcoord0);\r\n}\r\n\r\nvoid main() {\r\n\tfragPrefilter13();\r\n}";
  29639. var BloomPrefilter4PS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#include \"Colors.glsl\";\r\n#include \"Sampling.glsl\";\r\n\r\nvarying vec2 v_Texcoord0;\r\n\r\nuniform sampler2D u_MainTex;\r\nuniform sampler2D u_AutoExposureTex;\r\nuniform vec4 u_MainTex_TexelSize;\r\nuniform vec4 u_Threshold; // x: threshold value (linear), y: threshold - knee, z: knee * 2, w: 0.25 / knee\r\nuniform vec4 u_Params; // x: clamp, yzw: unused\r\n\r\nmediump vec4 prefilter(mediump vec4 color, vec2 uv) {\r\n\tmediump float autoExposure = texture2D(u_AutoExposureTex, uv).r;\r\n\tcolor *= autoExposure;\r\n\tcolor = min(vec4(u_Params.x), color); // clamp to max\r\n\tcolor = quadraticThreshold(color, u_Threshold.x, u_Threshold.yzw);\r\n\treturn color;\r\n}\r\n\r\nvoid fragPrefilter4() {\r\n\tmediump vec4 color = downsampleBox4Tap(u_MainTex, v_Texcoord0, u_MainTex_TexelSize.xy);\r\n\tgl_FragColor = prefilter(safeHDR(color), v_Texcoord0);\r\n}\r\n\r\nvoid main() {\r\n\tfragPrefilter4();\r\n}";
  29640. var BloomUpsampleBoxPS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#include \"Colors.glsl\";\r\n#include \"Sampling.glsl\";\r\n\r\nvarying vec2 v_Texcoord0;\r\n\r\nuniform sampler2D u_MainTex;\r\nuniform sampler2D u_BloomTex;\r\n\r\nuniform vec4 u_MainTex_TexelSize;\r\nuniform float u_SampleScale;\r\n\r\nmediump vec4 combine(mediump vec4 bloom, vec2 uv) {\r\n\tmediump vec4 color = texture2D(u_BloomTex, uv);\r\n\treturn bloom + color;\r\n}\r\n\r\nvoid fragUpsampleBox() {\r\n\tmediump vec4 bloom = upsampleBox(u_MainTex, v_Texcoord0, u_MainTex_TexelSize.xy, vec4(u_SampleScale));\r\n\tgl_FragColor = combine(bloom, v_Texcoord0);\r\n}\r\n\r\nvoid main() {\r\n\tfragUpsampleBox();\r\n}";
  29641. var BloomUpsampleTentPS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#include \"Colors.glsl\";\r\n#include \"Sampling.glsl\";\r\n\r\nvarying vec2 v_Texcoord0;\r\n\r\nuniform sampler2D u_MainTex;\r\nuniform sampler2D u_BloomTex;\r\n\r\nuniform vec4 u_MainTex_TexelSize;\r\nuniform float u_SampleScale;\r\n\r\nmediump vec4 combine(mediump vec4 bloom, vec2 uv) {\r\n\tmediump vec4 color = texture2D(u_BloomTex, uv);\r\n\treturn bloom + color;\r\n}\r\n\r\nvoid fragUpsampleTent() {\r\n\tmediump vec4 bloom = upsampleTent(u_MainTex, v_Texcoord0, u_MainTex_TexelSize.xy, vec4(u_SampleScale));\r\n\tgl_FragColor = combine(bloom, v_Texcoord0);\r\n}\r\n\r\nvoid main() {\r\n\tfragUpsampleTent();\r\n}";
  29642. var ColorsGLSL = "#include \"StdLib.glsl\";\r\n\r\n#define EPSILON 1.0e-4\r\n\r\n// Quadratic color thresholding\r\n// curve = (threshold - knee, knee * 2, 0.25 / knee)\r\nmediump vec4 quadraticThreshold(mediump vec4 color, mediump float threshold, mediump vec3 curve) {\r\n\t// Pixel brightness\r\n\tmediump float br = max3(color.r, color.g, color.b);\r\n\r\n\t// Under-threshold part: quadratic curve\r\n\tmediump float rq = clamp(br - curve.x, 0.0, curve.y);\r\n\trq = curve.z * rq * rq;\r\n\r\n\t// Combine and apply the brightness response curve.\r\n\tcolor *= max(rq, br - threshold) / max(br, EPSILON);\r\n\r\n\treturn color;\r\n}\r\n\r\n\r\n\r\n//\r\n// sRGB transfer functions\r\n// Fast path ref: http://chilliant.blogspot.com.au/2012/08/srgb-approximations-for-hlsl.html?m=1\r\n//\r\nmediump vec3 sRGBToLinear(mediump vec3 c) {\r\n\t#ifdef USE_VERY_FAST_SRGB\r\n\t\treturn c * c;\r\n\t#elif defined(USE_FAST_SRGB)\r\n\t\treturn c * (c * (c * 0.305306011 + 0.682171111) + 0.012522878);\r\n\t#else\r\n\t\tmediump vec3 linearRGBLo = c / 12.92;\r\n\t\tmediump vec3 power=vec3(2.4, 2.4, 2.4);\r\n\t\tmediump vec3 linearRGBHi = positivePow((c + 0.055) / 1.055, power);\r\n\t\tmediump vec3 linearRGB =vec3((c.r<=0.04045) ? linearRGBLo.r : linearRGBHi.r,(c.g<=0.04045) ? linearRGBLo.g : linearRGBHi.g,(c.b<=0.04045) ? linearRGBLo.b : linearRGBHi.b);\r\n\t\treturn linearRGB;\r\n\t#endif\r\n}\r\n\r\nmediump vec4 sRGBToLinear(mediump vec4 c){\r\n return vec4(sRGBToLinear(c.rgb), c.a);\r\n}\r\n\r\n\r\n\r\nmediump vec3 linearToSRGB(mediump vec3 c) {\r\n\t#ifdef USE_VERY_FAST_SRGB\r\n\t\treturn sqrt(c);\r\n\t#elif defined(USE_FAST_SRGB)\r\n\t\treturn max(1.055 * PositivePow(c, 0.416666667) - 0.055, 0.0);\r\n\t#else\r\n\t\tmediump vec3 sRGBLo = c * 12.92;\r\n\t\tmediump vec3 power=vec3(1.0 / 2.4, 1.0 / 2.4, 1.0 / 2.4);\r\n\t\tmediump vec3 sRGBHi = (positivePow(c, power) * 1.055) - 0.055;\r\n\t\tmediump vec3 sRGB =vec3((c.r<=0.0031308) ? sRGBLo.r : sRGBHi.r,(c.g<=0.0031308) ? sRGBLo.g : sRGBHi.g,(c.b<=0.0031308) ? sRGBLo.b : sRGBHi.b);\r\n\t\treturn sRGB;\r\n\t#endif\r\n}\r\n\r\nmediump vec4 linearToSRGB(mediump vec4 c){\r\n return vec4(linearToSRGB(c.rgb), c.a);\r\n}";
  29643. var CompositePS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#include \"Colors.glsl\";\r\n#include \"Sampling.glsl\";\r\n\r\nvarying vec2 v_Texcoord0;\r\n\r\nuniform sampler2D u_MainTex;\r\nuniform sampler2D u_BloomTex;\r\n\r\nuniform sampler2D u_AutoExposureTex;\r\nuniform sampler2D u_Bloom_DirtTex;\r\nuniform vec4 u_BloomTex_TexelSize;\r\nuniform vec4 u_Bloom_DirtTileOffset; // xy: tiling, zw: offset\r\nuniform mediump vec3 u_Bloom_Settings;// x: sampleScale, y: intensity, z: dirt intensity\r\nuniform mediump vec3 u_Bloom_Color;\r\n\r\nvoid main() {\r\n\tmediump float autoExposure = texture2D(u_AutoExposureTex, v_Texcoord0).r;\r\n\tmediump vec4 color=vec4(0.0);\r\n\tcolor = texture2D(u_MainTex, v_Texcoord0);\r\n\t\r\n\tcolor = sRGBToLinear(color);\r\n\tcolor.rgb *= autoExposure;\r\n\t\r\n\t#if defined(BLOOM)||defined(BLOOM_LOW)\r\n\t\t#ifdef BLOOM\r\n\t\t\tmediump vec4 bloom = upsampleTent(u_BloomTex, v_Texcoord0, u_BloomTex_TexelSize.xy, vec4(u_Bloom_Settings.x));\r\n\t\t#else\r\n\t\t\tmediump vec4 bloom = upsampleBox(u_BloomTex, v_Texcoord0, u_BloomTex_TexelSize.xy, vec4(u_Bloom_Settings.x));\r\n\t\t#endif\r\n\r\n\t\t// UVs should be Distort(uv * u_Bloom_DirtTileOffset.xy + u_Bloom_DirtTileOffset.zw)\r\n\t\t// but considering we use a cover-style scale on the dirt texture the difference\r\n\t\t// isn't massive so we chose to save a few ALUs here instead in case lens distortion\r\n\t\t// is active\r\n\t\tmediump vec4 dirt =vec4(texture2D(u_Bloom_DirtTex, v_Texcoord0 * u_Bloom_DirtTileOffset.xy + u_Bloom_DirtTileOffset.zw).rgb, 0.0);\r\n\r\n\t\t// Additive bloom (artist friendly)\r\n\t\tbloom *= u_Bloom_Settings.y;\r\n\t\tdirt *= u_Bloom_Settings.z;\r\n\t\tmediump vec4 bloomColor=vec4(u_Bloom_Color, 1.0);\r\n\t\tcolor += bloom * bloomColor;\r\n\t\tcolor += dirt * bloom;\r\n\t#endif\r\n\t\r\n\tmediump vec4 finalColor = color;\r\n\tfinalColor = linearToSRGB(finalColor);\r\n\t//finalColor.rgb = Dither(finalColor.rgb, v_Texcoord0);//TODO:抖动\r\n\tgl_FragColor = finalColor;\r\n}";
  29644. var CompositeVS = "#include \"Lighting.glsl\";\r\n\r\nattribute vec4 a_PositionTexcoord;\r\nvarying vec2 v_Texcoord0;\r\n\r\nvoid main() {\r\n\tgl_Position = vec4(a_PositionTexcoord.xy, 0.0, 1.0);\r\n\tv_Texcoord0 = a_PositionTexcoord.zw;\r\n\tgl_Position = remapGLPositionZ(gl_Position);\r\n}";
  29645. var SamplingGLSL = "// Better, temporally stable box filtering\r\n// [Jimenez14] http://goo.gl/eomGso\r\n// . . . . . . .\r\n// . A . B . C .\r\n// . . D . E . .\r\n// . F . G . H .\r\n// . . I . J . .\r\n// . K . L . M .\r\n// . . . . . . .\r\nmediump vec4 downsampleBox13Tap(sampler2D tex, vec2 uv, vec2 texelSize)\r\n{\r\n mediump vec4 A = texture2D(tex, uv + texelSize * vec2(-1.0, -1.0));\r\n mediump vec4 B = texture2D(tex, uv + texelSize * vec2( 0.0, -1.0));\r\n mediump vec4 C = texture2D(tex, uv + texelSize * vec2( 1.0, -1.0));\r\n mediump vec4 D = texture2D(tex, uv + texelSize * vec2(-0.5, -0.5));\r\n mediump vec4 E = texture2D(tex, uv + texelSize * vec2( 0.5, -0.5));\r\n mediump vec4 F = texture2D(tex, uv + texelSize * vec2(-1.0, 0.0));\r\n mediump vec4 G = texture2D(tex, uv);\r\n mediump vec4 H = texture2D(tex, uv + texelSize * vec2( 1.0, 0.0));\r\n mediump vec4 I = texture2D(tex, uv + texelSize * vec2(-0.5, 0.5));\r\n mediump vec4 J = texture2D(tex, uv + texelSize * vec2( 0.5, 0.5));\r\n mediump vec4 K = texture2D(tex, uv + texelSize * vec2(-1.0, 1.0));\r\n mediump vec4 L = texture2D(tex, uv + texelSize * vec2( 0.0, 1.0));\r\n mediump vec4 M = texture2D(tex, uv + texelSize * vec2( 1.0, 1.0));\r\n\r\n\tmediump vec2 scale= vec2(0.5, 0.125);\r\n mediump vec2 div = (1.0 / 4.0) * scale;\r\n\r\n mediump vec4 o = (D + E + I + J) * div.x;\r\n o += (A + B + G + F) * div.y;\r\n o += (B + C + H + G) * div.y;\r\n o += (F + G + L + K) * div.y;\r\n o += (G + H + M + L) * div.y;\r\n\r\n return o;\r\n}\r\n\r\n// Standard box filtering\r\nmediump vec4 downsampleBox4Tap(sampler2D tex, vec2 uv, vec2 texelSize)\r\n{\r\n vec4 d = texelSize.xyxy * vec4(-1.0, -1.0, 1.0, 1.0);\r\n\r\n mediump vec4 s = texture2D(tex, uv + d.xy);\r\n s += texture2D(tex, uv + d.zy);\r\n s += texture2D(tex, uv + d.xw);\r\n s += texture2D(tex, uv + d.zw);\r\n\r\n return s * (1.0 / 4.0);\r\n}\r\n\r\n// 9-tap bilinear upsampler (tent filter)\r\n// . . . . . . .\r\n// . 1 . 2 . 1 .\r\n// . . . . . . .\r\n// . 2 . 4 . 2 .\r\n// . . . . . . .\r\n// . 1 . 2 . 1 .\r\n// . . . . . . .\r\nmediump vec4 upsampleTent(sampler2D tex, vec2 uv, vec2 texelSize, vec4 sampleScale)\r\n{\r\n vec4 d = texelSize.xyxy * vec4(1.0, 1.0, -1.0, 0.0) * sampleScale;\r\n\r\n mediump vec4 s = texture2D(tex, uv - d.xy);\r\n s += texture2D(tex, uv - d.wy) * 2.0;\r\n s += texture2D(tex, uv - d.zy);\r\n\r\n s += texture2D(tex, uv + d.zw) * 2.0;\r\n s += texture2D(tex, uv) * 4.0;\r\n s += texture2D(tex,\tuv + d.xw) * 2.0;\r\n\r\n s += texture2D(tex, uv + d.zy);\r\n s += texture2D(tex, uv + d.wy) * 2.0;\r\n s += texture2D(tex, uv + d.xy);\r\n\r\n return s * (1.0 / 16.0);\r\n}\r\n\r\n// Standard box filtering\r\nmediump vec4 upsampleBox(sampler2D tex, vec2 uv, vec2 texelSize, vec4 sampleScale)\r\n{\r\n vec4 d = texelSize.xyxy * vec4(-1.0, -1.0, 1.0, 1.0) * 0.5 * sampleScale;\r\n\r\n mediump vec4 s = texture2D(tex, uv + d.xy);\r\n s += texture2D(tex, uv + d.zy);\r\n s += texture2D(tex, uv + d.xw);\r\n s += texture2D(tex, uv + d.zw);\r\n\r\n return s * (1.0 / 4.0);\r\n}";
  29646. var StdLibGLSL = "#define HALF_MAX 65504.0 // (2 - 2^-10) * 2^15\r\n\r\n#define FLT_EPSILON 1.192092896e-07 // Smallest positive number, such that 1.0 + FLT_EPSILON != 1.0\r\n\r\nmediump vec4 safeHDR(mediump vec4 c)\r\n{\r\n return min(c, HALF_MAX);\r\n}\r\n\r\nfloat max3(float a, float b, float c)\r\n{\r\n return max(max(a, b), c);\r\n}\r\n\r\nvec3 positivePow(vec3 base, vec3 power)\r\n{\r\n return pow(max(abs(base), vec3(FLT_EPSILON, FLT_EPSILON, FLT_EPSILON)), power);\r\n}";
  29647. var ShadowGLSL = "#ifndef GRAPHICS_API_GLES3\r\n\t#define NO_NATIVE_SHADOWMAP\r\n#endif\r\n\r\n#if defined(NO_NATIVE_SHADOWMAP)\r\n\t#define TEXTURE2D_SHADOW(textureName) uniform mediump sampler2D textureName\r\n\t#define SAMPLE_TEXTURE2D_SHADOW(textureName, coord3) (texture2D(textureName,coord3.xy).r<coord3.z?0.0:1.0)\r\n\t#define TEXTURE2D_SHADOW_PARAM(shadowMap) mediump sampler2D shadowMap\r\n#else\r\n\t#define TEXTURE2D_SHADOW(textureName) uniform mediump sampler2DShadow textureName\r\n\t#define SAMPLE_TEXTURE2D_SHADOW(textureName, coord3) textureLod(textureName,coord3,0.0)\r\n\t#define TEXTURE2D_SHADOW_PARAM(shadowMap) mediump sampler2DShadow shadowMap\r\n#endif\r\n\r\n#if defined(RECEIVESHADOW)&&defined(SHADOW)\r\n #define CALCULATE_SHADOWS\r\n#endif\r\n\r\n#if defined(RECEIVESHADOW)&&defined(SHADOW_SPOT)\r\n\t#define CALCULATE_SPOTSHADOWS\r\n#endif\r\n\r\nuniform vec4 u_ShadowBias; // x: depth bias, y: normal bias\r\n\r\n#if defined(CALCULATE_SHADOWS)||defined(CALCULATE_SPOTSHADOWS)\r\n\t#include \"ShadowSampleTent.glsl\"\r\n\tuniform vec4 u_ShadowMapSize;\r\n\tuniform vec4 u_SpotShadowMapSize;\r\n\tuniform vec4 u_ShadowParams; // x: shadowStrength y: ShadowSpotLightStrength\r\n\r\n\t\r\n\tfloat sampleShdowMapFiltered4(TEXTURE2D_SHADOW_PARAM(shadowMap),vec3 shadowCoord,vec4 shadowMapSize)\r\n\t{\r\n\t\tfloat attenuation;\r\n\t\tvec4 attenuation4;\r\n\t\tvec2 offset=shadowMapSize.xy/2.0;\r\n\t\tvec3 shadowCoord0=shadowCoord + vec3(-offset,0.0);\r\n\t\tvec3 shadowCoord1=shadowCoord + vec3(offset.x,-offset.y,0.0);\r\n\t\tvec3 shadowCoord2=shadowCoord + vec3(-offset.x,offset.y,0.0);\r\n\t\tvec3 shadowCoord3=shadowCoord + vec3(offset,0.0);\r\n\t\tattenuation4.x = SAMPLE_TEXTURE2D_SHADOW(shadowMap, shadowCoord0);\r\n\t\tattenuation4.y = SAMPLE_TEXTURE2D_SHADOW(shadowMap, shadowCoord1);\r\n\t\tattenuation4.z = SAMPLE_TEXTURE2D_SHADOW(shadowMap, shadowCoord2);\r\n\t\tattenuation4.w = SAMPLE_TEXTURE2D_SHADOW(shadowMap, shadowCoord3);\r\n\t\tattenuation = dot(attenuation4, vec4(0.25));\r\n\t\treturn attenuation;\r\n\t}\r\n\r\n\tfloat sampleShdowMapFiltered9(TEXTURE2D_SHADOW_PARAM(shadowMap),vec3 shadowCoord,vec4 shadowmapSize)\r\n\t{\r\n\t\tfloat attenuation;\r\n\t\tfloat fetchesWeights[9];\r\n\t\tvec2 fetchesUV[9];\r\n\t\tsampleShadowComputeSamplesTent5x5(shadowmapSize, shadowCoord.xy, fetchesWeights, fetchesUV);\r\n\t\tattenuation = fetchesWeights[0] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[0].xy, shadowCoord.z));\r\n\t\tattenuation += fetchesWeights[1] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[1].xy, shadowCoord.z));\r\n\t\tattenuation += fetchesWeights[2] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[2].xy, shadowCoord.z));\r\n\t\tattenuation += fetchesWeights[3] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[3].xy, shadowCoord.z));\r\n\t\tattenuation += fetchesWeights[4] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[4].xy, shadowCoord.z));\r\n\t\tattenuation += fetchesWeights[5] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[5].xy, shadowCoord.z));\r\n\t\tattenuation += fetchesWeights[6] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[6].xy, shadowCoord.z));\r\n\t\tattenuation += fetchesWeights[7] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[7].xy, shadowCoord.z));\r\n\t\tattenuation += fetchesWeights[8] * SAMPLE_TEXTURE2D_SHADOW(shadowMap, vec3(fetchesUV[8].xy, shadowCoord.z));\r\n\t\treturn attenuation;\r\n\t}\r\n\r\n#endif\r\n\r\n\r\n\r\n\r\n#if defined(CALCULATE_SHADOWS)\r\n\r\n\tTEXTURE2D_SHADOW(u_ShadowMap);\r\n\r\n\tuniform mat4 u_ShadowMatrices[4];\r\n\tuniform vec4 u_ShadowSplitSpheres[4];// max cascade is 4\r\n\r\n\tmediump int computeCascadeIndex(vec3 positionWS)\r\n\t{\r\n\t\tvec3 fromCenter0 = positionWS - u_ShadowSplitSpheres[0].xyz;\r\n\t\tvec3 fromCenter1 = positionWS - u_ShadowSplitSpheres[1].xyz;\r\n\t\tvec3 fromCenter2 = positionWS - u_ShadowSplitSpheres[2].xyz;\r\n\t\tvec3 fromCenter3 = positionWS - u_ShadowSplitSpheres[3].xyz;\r\n\r\n\t\tmediump vec4 comparison = vec4(\r\n\t\t\tdot(fromCenter0, fromCenter0)<u_ShadowSplitSpheres[0].w,\r\n\t\t\tdot(fromCenter1, fromCenter1)<u_ShadowSplitSpheres[1].w,\r\n\t\t\tdot(fromCenter2, fromCenter2)<u_ShadowSplitSpheres[2].w,\r\n\t\t\tdot(fromCenter3, fromCenter3)<u_ShadowSplitSpheres[3].w);\r\n\t\tcomparison.yzw = clamp(comparison.yzw - comparison.xyz,0.0,1.0);//keep the nearest\r\n\t\tmediump vec4 indexCoefficient = vec4(4.0,3.0,2.0,1.0);\r\n\t\tmediump int index = 4 - int(dot(comparison, indexCoefficient));\r\n\t\treturn index;\r\n\t}\r\n\r\n\tvec4 getShadowCoord(vec4 positionWS)\r\n\t{\r\n\t\t#ifdef SHADOW_CASCADE\r\n\t\t\tmediump int cascadeIndex = computeCascadeIndex(positionWS.xyz);\r\n\t\t\tif(cascadeIndex > 3)// out of shadow range cascadeIndex is 4.\r\n\t\t\t\treturn vec4(0.0);\r\n\t\t\t\r\n\t\t\t#ifdef GRAPHICS_API_GLES3\r\n\t\t\t\treturn u_ShadowMatrices[cascadeIndex] * positionWS;\r\n\t\t\t#else\r\n\t\t\t\tmat4 shadowMat;\r\n\t\t\t\tif(cascadeIndex == 0)\r\n\t\t\t\t\tshadowMat = u_ShadowMatrices[0];\r\n\t\t\t\telse if(cascadeIndex == 1)\r\n\t\t\t\t\tshadowMat = u_ShadowMatrices[1];\r\n\t\t\t\telse if(cascadeIndex == 2)\r\n\t\t\t\t\tshadowMat = u_ShadowMatrices[2];\r\n\t\t\t\telse\r\n\t\t\t\t\tshadowMat = u_ShadowMatrices[3];\r\n\t\t\t\treturn shadowMat * positionWS;\r\n\t\t\t#endif\r\n\t\t#else\r\n\t\t\treturn u_ShadowMatrices[0] * positionWS;\r\n\t\t#endif\r\n\t}\r\n\r\n\tfloat sampleShadowmap(vec4 shadowCoord)\r\n\t{\r\n\t\tshadowCoord.xyz /= shadowCoord.w;\r\n\t\tfloat attenuation = 1.0;\r\n\t\tif(shadowCoord.z > 0.0 && shadowCoord.z < 1.0)\r\n\t\t{\r\n\t\t\t#if defined(SHADOW_SOFT_SHADOW_HIGH)\r\n\t\t\t\tattenuation = sampleShdowMapFiltered9(u_ShadowMap,shadowCoord.xyz,u_ShadowMapSize);\r\n\t\t\t#elif defined(SHADOW_SOFT_SHADOW_LOW)\r\n\t\t\t\tattenuation = sampleShdowMapFiltered4(u_ShadowMap,shadowCoord.xyz,u_ShadowMapSize);\r\n\t\t\t#else\r\n\t\t\t\tattenuation = SAMPLE_TEXTURE2D_SHADOW(u_ShadowMap,shadowCoord.xyz);\r\n\t\t\t#endif\r\n\t\t\tattenuation = mix(1.0,attenuation,u_ShadowParams.x);//shadowParams.x:shadow strength\r\n\t\t}\r\n\t\treturn attenuation;\r\n\t}\r\n#endif\r\n\r\n#if defined(CALCULATE_SPOTSHADOWS)//shader���Զ���ĺ겻����ifdef ����ij�if defined\r\n\tTEXTURE2D_SHADOW(u_SpotShadowMap);\r\n\tuniform mat4 u_SpotViewProjectMatrix;\r\n\tfloat sampleSpotShadowmap(vec4 shadowCoord)\r\n\t{\r\n\t\tshadowCoord.xyz /= shadowCoord.w;\r\n\t\tfloat attenuation = 1.0;\r\n\t\tshadowCoord.xy +=1.0;\r\n\t\tshadowCoord.xy/=2.0; \r\n\t\tif(shadowCoord.z > 0.0 && shadowCoord.z < 1.0)\r\n\t\t{\r\n\t\t\t#if defined(SHADOW_SPOT_SOFT_SHADOW_HIGH)\r\n\t\t\t\tattenuation = sampleShdowMapFiltered9(u_SpotShadowMap,shadowCoord.xyz,u_SpotShadowMapSize);\r\n\t\t\t#elif defined(SHADOW_SPOT_SOFT_SHADOW_LOW)\r\n\t\t\t\tattenuation = sampleShdowMapFiltered4(u_SpotShadowMap,shadowCoord.xyz,u_SpotShadowMapSize);\r\n\t\t\t#else\r\n\t\t\t\tattenuation = SAMPLE_TEXTURE2D_SHADOW(u_SpotShadowMap,shadowCoord.xyz);\r\n\t\t\t#endif\r\n\t\t\tattenuation = mix(1.0,attenuation,u_ShadowParams.y);//shadowParams.y:shadow strength\r\n\t\t}\r\n\t\treturn attenuation;\r\n\t}\r\n#endif\r\n\r\nvec3 applyShadowBias(vec3 positionWS, vec3 normalWS, vec3 lightDirection)\r\n{\r\n float invNdotL = 1.0 - clamp(dot(-lightDirection, normalWS),0.0,1.0);\r\n float scale = invNdotL * u_ShadowBias.y;\r\n\r\n // normal bias is negative since we want to apply an inset normal offset\r\n positionWS += -lightDirection * u_ShadowBias.xxx;\r\n positionWS += normalWS * vec3(scale);\r\n return positionWS;\r\n}\r\n";
  29648. var ShadowCasterVSGLSL = "#include \"Lighting.glsl\";\r\n#include \"Shadow.glsl\"\r\n\r\nattribute vec4 a_Position;\r\nattribute vec3 a_Normal;\r\n\r\n#ifdef BONE\r\n\tconst int c_MaxBoneCount = 24;\r\n\tattribute vec4 a_BoneIndices;\r\n\tattribute vec4 a_BoneWeights;\r\n\tuniform mat4 u_Bones[c_MaxBoneCount];\r\n#endif\r\n\r\n#ifdef GPU_INSTANCE\r\n\tattribute mat4 a_WorldMat;\r\n#else\r\n\tuniform mat4 u_WorldMat;\r\n#endif\r\n\r\nuniform mat4 u_ViewProjection;\r\n\r\n#ifdef SHADOW\r\n\tuniform vec3 u_ShadowLightDirection;\r\n#endif\r\n\r\n\r\nvec4 shadowCasterVertex()\r\n{\r\n\tmat4 worldMat;\r\n\t#ifdef GPU_INSTANCE\r\n\t\tworldMat = a_WorldMat;\r\n\t#else\r\n\t\tworldMat = u_WorldMat;\r\n\t#endif\r\n\t\r\n\t#ifdef BONE\r\n\t\tmat4 skinTransform;\r\n\t \t#ifdef SIMPLEBONE\r\n\t\t\tfloat currentPixelPos;\r\n\t\t\t#ifdef GPU_INSTANCE\r\n\t\t\t\tcurrentPixelPos = a_SimpleTextureParams.x+a_SimpleTextureParams.y;\r\n\t\t\t#else\r\n\t\t\t\tcurrentPixelPos = u_SimpleAnimatorParams.x+u_SimpleAnimatorParams.y;\r\n\t\t\t#endif\r\n\t\t\tfloat offset = 1.0/u_SimpleAnimatorTextureSize;\r\n\t\t\tskinTransform = loadMatFromTexture(currentPixelPos,int(a_BoneIndices.x),offset) * a_BoneWeights.x;\r\n\t\t\tskinTransform += loadMatFromTexture(currentPixelPos,int(a_BoneIndices.y),offset) * a_BoneWeights.y;\r\n\t\t\tskinTransform += loadMatFromTexture(currentPixelPos,int(a_BoneIndices.z),offset) * a_BoneWeights.z;\r\n\t\t\tskinTransform += loadMatFromTexture(currentPixelPos,int(a_BoneIndices.w),offset) * a_BoneWeights.w;\r\n\t\t#else\r\n\t\t\tskinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;\r\n\t\t\tskinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;\r\n\t\t\tskinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;\r\n\t\t\tskinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;\r\n\t\t#endif\r\n\t\tworldMat = worldMat * skinTransform;\r\n\t#endif\r\n\r\n\tvec4 positionWS = worldMat * a_Position;\r\n\tmat3 worldInvMat;\r\n\t#ifdef BONE\r\n\t\tworldInvMat=INVERSE_MAT(mat3(worldMat*skinTransform));\r\n\t#else\r\n\t\tworldInvMat=INVERSE_MAT(mat3(worldMat));\r\n\t#endif \r\n\r\n\tvec3 normalWS = normalize(a_Normal*worldInvMat);//if no normalize will cause precision problem\r\n\t#ifdef SHADOW\r\n\t\tpositionWS.xyz = applyShadowBias(positionWS.xyz,normalWS,u_ShadowLightDirection);\r\n\t#endif\r\n\r\n\tvec4 positionCS = u_ViewProjection * positionWS;\r\n\t#ifdef SHADOW_SPOT\r\n\t\tpositionCS.z = positionCS.z-u_ShadowBias.x/positionCS.w;\r\n\t#endif\r\n\tpositionCS.z = max(positionCS.z, 0.0);//min ndc z is 0.0\r\n\t\r\n\t// //TODO没考虑UV动画呢\r\n\t// #if defined(DIFFUSEMAP)&&defined(ALPHATEST)\r\n\t// \tv_Texcoord0=a_Texcoord0;\r\n\t// #endif\r\n return positionCS;\r\n}\r\n";
  29649. var ShadowCasterFSGLSL = "vec4 shadowCasterFragment()\r\n{\r\n return vec4(0.0);\r\n}\r\n";
  29650. var SkyBoxPS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\nprecision highp float;\r\n#else\r\nprecision mediump float;\r\n#endif\r\n\r\nvarying vec3 v_Texcoord;\r\n\r\nuniform samplerCube u_CubeTexture;\r\nuniform float u_Exposure;\r\nuniform vec4 u_TintColor;\r\n\r\n\r\nvoid main()\r\n{\t\r\n\tvec3 color=textureCube(u_CubeTexture, v_Texcoord).rgb*u_TintColor.rgb*u_Exposure*2.0;\r\n\tgl_FragColor=vec4(color,1.0);\r\n}\r\n\r\n";
  29651. var SkyBoxVS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\nprecision highp float;\r\n#else\r\nprecision mediump float;\r\n#endif\r\n#include \"Lighting.glsl\";\r\n\r\nattribute vec4 a_Position;\r\nuniform mat4 u_ViewProjection;\r\nuniform float u_Rotation;\r\nvarying vec3 v_Texcoord;\r\n\r\n\r\nvec4 rotateAroundYInDegrees (vec4 vertex, float degrees)\r\n{\r\n\tfloat angle = degrees * 3.141593 / 180.0;\r\n\tfloat sina=sin(angle);\r\n\tfloat cosa=cos(angle);\r\n\tmat2 m = mat2(cosa, -sina, sina, cosa);\r\n\treturn vec4(m*vertex.xz, vertex.yw).xzyw;\r\n}\r\n\t\t\r\nvoid main()\r\n{\r\n\tvec4 position=rotateAroundYInDegrees(a_Position,u_Rotation);\r\n\tgl_Position = u_ViewProjection*position;\r\n\tv_Texcoord=vec3(-a_Position.x,a_Position.yz);//转换坐标系\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}\r\n";
  29652. var SkyBoxProceduralPS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#include \"Lighting.glsl\";\r\n\r\nconst float MIE_G = -0.990;\r\nconst float MIE_G2 = 0.9801;\r\nconst float SKY_GROUND_THRESHOLD = 0.02;\r\n\r\nuniform float u_SunSize;\r\nuniform float u_SunSizeConvergence;\r\nuniform DirectionLight u_SunLight;\r\n\r\n\r\nvarying vec3 v_GroundColor;\r\nvarying vec3 v_SkyColor;\r\n\r\n\r\n#ifdef SUN_HIGH_QUALITY\r\n\tvarying vec3 v_Vertex;\r\n#elif defined(SUN_SIMPLE)\r\n\tvarying vec3 v_RayDir;\r\n#else\r\n\tvarying float v_SkyGroundFactor;\r\n#endif\r\n\r\n#if defined(SUN_HIGH_QUALITY)||defined(SUN_SIMPLE)\r\n\tvarying vec3 v_SunColor;\r\n#endif\r\n\r\n// Calculates the Mie phase function\r\nfloat getMiePhase(float eyeCos, float eyeCos2) {\r\n\tfloat temp = 1.0 + MIE_G2 - 2.0 * MIE_G * eyeCos;\r\n\ttemp = pow(temp, pow(u_SunSize,0.65) * 10.0);\r\n\ttemp = max(temp,1.0e-4); // prevent division by zero, esp. in half precision\r\n\ttemp = 1.5 * ((1.0 - MIE_G2) / (2.0 + MIE_G2)) * (1.0 + eyeCos2) / temp;\r\n\treturn temp;\r\n}\r\n\r\n// Calculates the sun shape\r\nfloat calcSunAttenuation(vec3 lightPos, vec3 ray) {\r\n\t#ifdef SUN_HIGH_QUALITY\r\n\t\tfloat focusedEyeCos = pow(clamp(dot(lightPos, ray),0.0,1.0), u_SunSizeConvergence);\r\n\t\treturn getMiePhase(-focusedEyeCos, focusedEyeCos * focusedEyeCos);\r\n\t#else //SUN_SIMPLE\r\n\t\tvec3 delta = lightPos - ray;\r\n\t\tfloat dist = length(delta);\r\n\t\tfloat spot = 1.0 - smoothstep(0.0, u_SunSize, dist);\r\n\t\treturn spot * spot;\r\n\t#endif\r\n}\r\n\r\nvoid main() {\r\n\t// if y > 1 [eyeRay.y < -SKY_GROUND_THRESHOLD] - ground\r\n\t// if y >= 0 and < 1 [eyeRay.y <= 0 and > -SKY_GROUND_THRESHOLD] - horizon\r\n\t// if y < 0 [eyeRay.y > 0] - sky\r\n\tvec3 col = vec3(0.0, 0.0, 0.0);\r\n\r\n\t#ifdef SUN_HIGH_QUALITY\r\n\t\tvec3 ray = normalize(v_Vertex);\r\n\t\tfloat y = ray.y / SKY_GROUND_THRESHOLD;\r\n\t#elif defined(SUN_SIMPLE) \r\n\t\tvec3 ray = v_RayDir;\r\n\t\tfloat y = ray.y / SKY_GROUND_THRESHOLD;\t\r\n\t#else\r\n\t\tfloat y = v_SkyGroundFactor;\r\n\t#endif\r\n\r\n\t// if we did precalculate color in vprog: just do lerp between them\r\n\tcol = mix(v_SkyColor, v_GroundColor, clamp(y,0.0,1.0));\r\n\r\n\t#if defined(SUN_HIGH_QUALITY)||defined(SUN_SIMPLE)\r\n\t\tif (y < 0.0)\r\n\t\t\tcol += v_SunColor * calcSunAttenuation(-u_SunLight.direction, -ray);\r\n\t#endif\r\n\r\n\tcol = sqrt(col);//linear space convert to gamma space\r\n\tgl_FragColor=vec4(col,1.0);\r\n}\r\n\r\n";
  29653. var SkyBoxProceduralVS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#include \"Lighting.glsl\";\r\n\r\n#define OUTER_RADIUS 1.025\r\n#define RAYLEIGH (mix(0.0, 0.0025, pow(u_AtmosphereThickness,2.5)))// Rayleigh constant Rayleigh为夜空光和极光亮度单位\r\n#define MIE 0.0010 // Mie constant 米氏散射\r\n#define SUN_BRIGHTNESS 20.0 // Sun brightness\r\n#define MAX_SCATTER 50.0 // Maximum scattering value, to prevent math overflows on Adrenos\r\n\r\nconst float SKY_GROUND_THRESHOLD = 0.02;\r\nconst float outerRadius = OUTER_RADIUS;\r\nconst float outerRadius2 = OUTER_RADIUS*OUTER_RADIUS;\r\nconst float innerRadius = 1.0;\r\nconst float innerRadius2 = 1.0;\r\nconst float cameraHeight = 0.0001;\r\n\r\nconst float HDSundiskIntensityFactor = 15.0;\r\nconst float simpleSundiskIntensityFactor = 27.0;\r\n\r\nconst float sunScale = 400.0 * SUN_BRIGHTNESS;\r\nconst float kmESun = MIE * SUN_BRIGHTNESS;\r\nconst float km4PI = MIE * 4.0 * 3.14159265;\r\nconst float scale = 1.0 / (OUTER_RADIUS - 1.0);\r\nconst float scaleDepth = 0.25;\r\nconst float scaleOverScaleDepth = (1.0 / (OUTER_RADIUS - 1.0)) / 0.25;\r\nconst float samples = 2.0; // THIS IS UNROLLED MANUALLY, DON'T TOUCH\r\n\r\n// RGB wavelengths .35 (.62=158), .43 (.68=174), .525 (.75=190)\r\nconst vec3 c_DefaultScatteringWavelength = vec3(0.65, 0.57, 0.475);//默认散射波长\r\nconst vec3 c_VariableRangeForScatteringWavelength = vec3(0.15, 0.15, 0.15);//散射播放的可变范围\r\n\r\nattribute vec4 a_Position;\r\n\r\nuniform mat4 u_ViewProjection;\r\nuniform vec3 u_SkyTint;\r\nuniform vec3 u_GroundTint;\r\nuniform float u_Exposure;\r\nuniform float u_AtmosphereThickness;\r\nuniform DirectionLight u_SunLight;\r\n\r\nvarying vec3 v_GroundColor;\r\nvarying vec3 v_SkyColor;\r\n\r\n#ifdef SUN_HIGH_QUALITY\r\n\tvarying vec3 v_Vertex;\r\n#elif defined(SUN_SIMPLE)\r\n\tvarying vec3 v_RayDir;\r\n#else\r\n\tvarying float v_SkyGroundFactor;\r\n#endif\r\n\r\n#if defined(SUN_HIGH_QUALITY)||defined(SUN_SIMPLE)\r\n\tvarying vec3 v_SunColor;\r\n#endif\r\n\r\n// Calculates the Rayleigh phase function\r\nfloat getRayleighPhase(vec3 light, vec3 ray) \r\n{\r\n\tfloat eyeCos = dot(light, ray);\r\n\treturn 0.75 + 0.75*eyeCos*eyeCos;\r\n}\r\n\r\nfloat scaleAngle(float inCos)\r\n{\r\n\tfloat x = 1.0 - inCos;\r\n\treturn 0.25 * exp(-0.00287 + x*(0.459 + x*(3.83 + x*(-6.80 + x*5.25))));\r\n}\r\n\r\n\r\nvoid main () {\r\n\tgl_Position = u_ViewProjection*a_Position;\r\n\r\n\tvec3 skyTintInGammaSpace = u_SkyTint;//支持非GAMMA空间后要调整\r\n\tvec3 scatteringWavelength = mix(c_DefaultScatteringWavelength-c_VariableRangeForScatteringWavelength,c_DefaultScatteringWavelength+c_VariableRangeForScatteringWavelength,vec3(1.0) - skyTintInGammaSpace); // using Tint in sRGB+ gamma allows for more visually linear interpolation and to keep (0.5) at (128, gray in sRGB) point\r\n\tvec3 invWavelength = 1.0 / pow(scatteringWavelength, vec3(4.0));\r\n\r\n\tfloat krESun = RAYLEIGH * SUN_BRIGHTNESS;\r\n\tfloat kr4PI = RAYLEIGH * 4.0 * 3.14159265;\r\n\r\n\tvec3 cameraPos = vec3(0.0,innerRadius + cameraHeight,0.0); // The camera's current position\r\n\r\n\t// Get the ray from the camera to the vertex and its length (which is the far point of the ray passing through the atmosphere)\r\n\tvec3 eyeRay = normalize(a_Position.xyz);\r\n\r\n\tfloat far = 0.0;\r\n\tvec3 cIn, cOut;\r\n\tif (eyeRay.y >= 0.0) {// Sky\r\n\t\t// Calculate the length of the \"atmosphere\"\r\n\t\tfar = sqrt(outerRadius2 + innerRadius2 * eyeRay.y * eyeRay.y - innerRadius2) - innerRadius * eyeRay.y;\r\n\r\n\t\t// Calculate the ray's starting position, then calculate its scattering offset\r\n\t\tfloat height = innerRadius + cameraHeight;\r\n\t\tfloat depth = exp(scaleOverScaleDepth * -cameraHeight);\r\n\t\tfloat startAngle = dot(eyeRay, cameraPos) / height;\r\n\t\tfloat startOffset = depth*scaleAngle(startAngle);\r\n\r\n\t\t// Initialize the scattering loop variables\r\n\t\tfloat sampleLength = far / samples;\r\n\t\tfloat scaledLength = sampleLength * scale;\r\n\t\tvec3 sampleRay = eyeRay * sampleLength;\r\n\t\tvec3 samplePoint = cameraPos + sampleRay * 0.5;\r\n\r\n\t\tvec3 frontColor = vec3(0.0);\r\n\t\t//unrolling this manually to avoid some platform for loop slow\r\n\t\t{\r\n\t\t\tfloat height = length(samplePoint);\r\n\t\t\tfloat depth = exp(scaleOverScaleDepth * (innerRadius - height));\r\n\t\t\tfloat lightAngle = dot(-u_SunLight.direction, samplePoint) / height;\r\n\t\t\tfloat cameraAngle = dot(eyeRay, samplePoint) / height;\r\n\t\t\tfloat scatter = (startOffset + depth*(scaleAngle(lightAngle) - scaleAngle(cameraAngle)));\r\n\t\t\tvec3 attenuate = exp(-clamp(scatter, 0.0, MAX_SCATTER) * (invWavelength * kr4PI + km4PI));\r\n\r\n\t\t\tfrontColor += attenuate * (depth * scaledLength);\r\n\t\t\tsamplePoint += sampleRay;\r\n\t\t}\r\n\t\t{\r\n\t\t\tfloat height = length(samplePoint);\r\n\t\t\tfloat depth = exp(scaleOverScaleDepth * (innerRadius - height));\r\n\t\t\tfloat lightAngle = dot(-u_SunLight.direction, samplePoint) / height;\r\n\t\t\tfloat cameraAngle = dot(eyeRay, samplePoint) / height;\r\n\t\t\tfloat scatter = (startOffset + depth*(scaleAngle(lightAngle) - scaleAngle(cameraAngle)));\r\n\t\t\tvec3 attenuate = exp(-clamp(scatter, 0.0, MAX_SCATTER) * (invWavelength * kr4PI + km4PI));\r\n\r\n\t\t\tfrontColor += attenuate * (depth * scaledLength);\r\n\t\t\tsamplePoint += sampleRay;\r\n\t\t}\r\n\r\n\t\t// Finally, scale the Mie and Rayleigh colors and set up the varying variables for the pixel shader\r\n\t\tcIn = frontColor * (invWavelength * krESun);\r\n\t\tcOut = frontColor * kmESun;\r\n\t} else {// Ground\r\n\t\tfar = (-cameraHeight) / (min(-0.001, eyeRay.y));\r\n\t\tvec3 pos = cameraPos + far * eyeRay;\r\n\r\n\t\t// Calculate the ray's starting position, then calculate its scattering offset\r\n\t\tfloat depth = exp((-cameraHeight) * (1.0/scaleDepth));\r\n\t\tfloat cameraAngle = dot(-eyeRay, pos);\r\n\t\tfloat lightAngle = dot(-u_SunLight.direction, pos);\r\n\t\tfloat cameraScale = scaleAngle(cameraAngle);\r\n\t\tfloat lightScale = scaleAngle(lightAngle);\r\n\t\tfloat cameraOffset = depth*cameraScale;\r\n\t\tfloat temp = lightScale + cameraScale;\r\n\r\n\t\t// Initialize the scattering loop variables\r\n\t\tfloat sampleLength = far / samples;\r\n\t\tfloat scaledLength = sampleLength * scale;\r\n\t\tvec3 sampleRay = eyeRay * sampleLength;\r\n\t\tvec3 samplePoint = cameraPos + sampleRay * 0.5;\r\n\r\n\t\t// Now loop through the sample rays\r\n\t\tvec3 frontColor = vec3(0.0, 0.0, 0.0);\r\n\t\tvec3 attenuate;\r\n\r\n\t\t// Loop removed because we kept hitting SM2.0 temp variable limits. Doesn't affect the image too much.\r\n\t\t{\r\n\t\t\tfloat height = length(samplePoint);\r\n\t\t\tfloat depth = exp(scaleOverScaleDepth * (innerRadius - height));\r\n\t\t\tfloat scatter = depth*temp - cameraOffset;\r\n\t\t\tattenuate = exp(-clamp(scatter, 0.0, MAX_SCATTER) * (invWavelength * kr4PI + km4PI));\r\n\t\t\tfrontColor += attenuate * (depth * scaledLength);\r\n\t\t\tsamplePoint += sampleRay;\r\n\t\t}\r\n\r\n\t\tcIn = frontColor * (invWavelength * krESun + kmESun);\r\n\t\tcOut = clamp(attenuate, 0.0, 1.0);\r\n\t}\r\n\r\n\t#ifdef SUN_HIGH_QUALITY\r\n\t\tv_Vertex = -a_Position.xyz;\r\n\t#elif defined(SUN_SIMPLE) \r\n\t\tv_RayDir = -eyeRay;\r\n\t#else\r\n\t\tv_SkyGroundFactor = -eyeRay.y / SKY_GROUND_THRESHOLD;\r\n\t#endif\r\n\r\n\t// if we want to calculate color in vprog:\r\n\t// in case of linear: multiply by _Exposure in here (even in case of lerp it will be common multiplier, so we can skip mul in fshader)\r\n\tv_GroundColor = u_Exposure * (cIn + u_GroundTint*u_GroundTint * cOut);//u_GroundColor*u_GroundColor is gamma space convert to linear space\r\n\tv_SkyColor = u_Exposure * (cIn * getRayleighPhase(-u_SunLight.direction, -eyeRay));\r\n\r\n\t\r\n\t// The sun should have a stable intensity in its course in the sky. Moreover it should match the highlight of a purely specular material.\r\n\t// This matching was done using the Unity3D standard shader BRDF1 on the 5/31/2017\r\n\t// Finally we want the sun to be always bright even in LDR thus the normalization of the lightColor for low intensity.\r\n\tfloat lightColorIntensity = clamp(length(u_SunLight.color), 0.25, 1.0);\r\n\r\n\t#ifdef SUN_HIGH_QUALITY \r\n\t\tv_SunColor = HDSundiskIntensityFactor * clamp(cOut,0.0,1.0) * u_SunLight.color / lightColorIntensity;\r\n\t#elif defined(SUN_SIMPLE) \r\n\t\tv_SunColor = simpleSundiskIntensityFactor * clamp(cOut * sunScale,0.0,1.0) * u_SunLight.color / lightColorIntensity;\r\n\t#endif\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}\r\n";
  29654. var TrailPS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\nuniform sampler2D u_MainTexture;\r\nuniform vec4 u_MainColor;\r\n\r\nvarying vec2 v_Texcoord0;\r\nvarying vec4 v_Color;\r\n\r\nvoid main()\r\n{\r\n\tvec4 color = 2.0 * u_MainColor * v_Color;\r\n\t#ifdef MAINTEXTURE\r\n\t\tvec4 mainTextureColor = texture2D(u_MainTexture, v_Texcoord0);\r\n\t\tcolor *= mainTextureColor;\r\n\t#endif\r\n\tgl_FragColor = color;\r\n}\r\n\r\n ";
  29655. var TrailVS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n#include \"Lighting.glsl\";\r\n\r\nattribute vec3 a_Position;\r\nattribute vec3 a_OffsetVector;\r\nattribute vec4 a_Color;\r\nattribute float a_Texcoord0X;\r\nattribute float a_Texcoord0Y;\r\nattribute float a_BirthTime;\r\n\r\nuniform mat4 u_View;\r\nuniform mat4 u_Projection;\r\n\r\nuniform vec4 u_TilingOffset;\r\n\r\nuniform float u_CurTime;\r\nuniform float u_LifeTime;\r\nuniform vec4 u_WidthCurve[10];\r\nuniform int u_WidthCurveKeyLength;\r\n\r\nvarying vec2 v_Texcoord0;\r\nvarying vec4 v_Color;\r\n\r\nfloat hermiteInterpolate(float t, float outTangent, float inTangent, float duration, float value1, float value2)\r\n{\r\n\tfloat t2 = t * t;\r\n\tfloat t3 = t2 * t;\r\n\tfloat a = 2.0 * t3 - 3.0 * t2 + 1.0;\r\n\tfloat b = t3 - 2.0 * t2 + t;\r\n\tfloat c = t3 - t2;\r\n\tfloat d = -2.0 * t3 + 3.0 * t2;\r\n\treturn a * value1 + b * outTangent * duration + c * inTangent * duration + d * value2;\r\n}\r\n\r\nfloat getCurWidth(in float normalizeTime)\r\n{\r\n\tfloat width;\r\n\tif(normalizeTime == 0.0){\r\n\t\twidth=u_WidthCurve[0].w;\r\n\t}\r\n\telse if(normalizeTime >= 1.0){\r\n\t\twidth=u_WidthCurve[u_WidthCurveKeyLength - 1].w;\r\n\t}\r\n\telse{\r\n\t\tfor(int i = 0; i < 10; i ++ )\r\n\t\t{\r\n\t\t\tif(normalizeTime == u_WidthCurve[i].x){\r\n\t\t\t\twidth=u_WidthCurve[i].w;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tvec4 lastFrame = u_WidthCurve[i];\r\n\t\t\tvec4 nextFrame = u_WidthCurve[i + 1];\r\n\t\t\tif(normalizeTime > lastFrame.x && normalizeTime < nextFrame.x)\r\n\t\t\t{\r\n\t\t\t\tfloat duration = nextFrame.x - lastFrame.x;\r\n\t\t\t\tfloat t = (normalizeTime - lastFrame.x) / duration;\r\n\t\t\t\tfloat outTangent = lastFrame.z;\r\n\t\t\t\tfloat inTangent = nextFrame.y;\r\n\t\t\t\tfloat value1 = lastFrame.w;\r\n\t\t\t\tfloat value2 = nextFrame.w;\r\n\t\t\t\twidth=hermiteInterpolate(t, outTangent, inTangent, duration, value1, value2);\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn width;\r\n}\t\r\n\r\nvoid main()\r\n{\r\n\tfloat normalizeTime = (u_CurTime - a_BirthTime) / u_LifeTime;\r\n\t\r\n\t#ifdef TILINGOFFSET\r\n\t\tv_Texcoord0 = vec2(a_Texcoord0X, 1.0 - a_Texcoord0Y) * u_TilingOffset.xy + u_TilingOffset.zw;\r\n\t#else\r\n\t\tv_Texcoord0 = vec2(a_Texcoord0X, a_Texcoord0Y);\r\n\t#endif\r\n\t\r\n\tv_Color = a_Color;\r\n\t\r\n\tvec3 cameraPos = (u_View*vec4(a_Position,1.0)).rgb;\r\n\tgl_Position = u_Projection * vec4(cameraPos+a_OffsetVector * getCurWidth(normalizeTime),1.0);\r\n\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}\r\n";
  29656. var UnlitPS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#if defined(COLOR)&&defined(ENABLEVERTEXCOLOR)\r\n\tvarying vec4 v_Color;\r\n#endif\r\n\r\n#ifdef ALBEDOTEXTURE\r\n\tuniform sampler2D u_AlbedoTexture;\r\n\tvarying vec2 v_Texcoord0;\r\n#endif\r\n\r\nuniform vec4 u_AlbedoColor;\r\n\r\n#ifdef ALPHATEST\r\n\tuniform float u_AlphaTestValue;\r\n#endif\r\n\r\n#ifdef FOG\r\n\tuniform float u_FogStart;\r\n\tuniform float u_FogRange;\r\n\t#ifdef ADDTIVEFOG\r\n\t#else\r\n\t\tuniform vec3 u_FogColor;\r\n\t#endif\r\n#endif\r\n\r\nvoid main()\r\n{\r\n\tvec4 color = u_AlbedoColor;\r\n\t#ifdef ALBEDOTEXTURE\r\n\t\tcolor *= texture2D(u_AlbedoTexture, v_Texcoord0);\r\n\t#endif\r\n\t#if defined(COLOR)&&defined(ENABLEVERTEXCOLOR)\r\n\t\tcolor *= v_Color;\r\n\t#endif\r\n\t\r\n\t#ifdef ALPHATEST\r\n\t\tif(color.a < u_AlphaTestValue)\r\n\t\t\tdiscard;\r\n\t#endif\r\n\t\r\n\tgl_FragColor = color;\r\n\t\r\n\t#ifdef FOG\r\n\t\tfloat lerpFact = clamp((1.0 / gl_FragCoord.w - u_FogStart) / u_FogRange, 0.0, 1.0);\r\n\t\t#ifdef ADDTIVEFOG\r\n\t\t\tgl_FragColor.rgb = mix(gl_FragColor.rgb, vec3(0.0), lerpFact);\r\n\t\t#else\r\n\t\t\tgl_FragColor.rgb = mix(gl_FragColor.rgb, u_FogColor, lerpFact);\r\n\t\t#endif\r\n\t#endif\r\n\t\r\n}\r\n\r\n";
  29657. var UnlitVS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n#include \"Lighting.glsl\";\r\n#include \"LayaUtile.glsl\";\r\n\r\nattribute vec4 a_Position;\r\n\r\nattribute vec2 a_Texcoord0;\r\n\r\n#ifdef GPU_INSTANCE\r\n\tattribute mat4 a_MvpMatrix;\r\n#else\r\n\tuniform mat4 u_MvpMatrix;\r\n#endif\r\n\r\nattribute vec4 a_Color;\r\nvarying vec4 v_Color;\r\nvarying vec2 v_Texcoord0;\r\n\r\n#ifdef TILINGOFFSET\r\n\tuniform vec4 u_TilingOffset;\r\n#endif\r\n\r\n#ifdef BONE\r\n\tconst int c_MaxBoneCount = 24;\r\n\tattribute vec4 a_BoneIndices;\r\n\tattribute vec4 a_BoneWeights;\r\n\tuniform mat4 u_Bones[c_MaxBoneCount];\r\n#endif\r\n\r\nvoid main() {\r\n\tvec4 position;\r\n\t#ifdef BONE\r\n\t\tmat4 skinTransform;\r\n\t \t#ifdef SIMPLEBONE\r\n\t\t\tfloat currentPixelPos;\r\n\t\t\t#ifdef GPU_INSTANCE\r\n\t\t\t\tcurrentPixelPos = a_SimpleTextureParams.x+a_SimpleTextureParams.y;\r\n\t\t\t#else\r\n\t\t\t\tcurrentPixelPos = u_SimpleAnimatorParams.x+u_SimpleAnimatorParams.y;\r\n\t\t\t#endif\r\n\t\t\tfloat offset = 1.0/u_SimpleAnimatorTextureSize;\r\n\t\t\tskinTransform = loadMatFromTexture(currentPixelPos,int(a_BoneIndices.x),offset) * a_BoneWeights.x;\r\n\t\t\tskinTransform += loadMatFromTexture(currentPixelPos,int(a_BoneIndices.y),offset) * a_BoneWeights.y;\r\n\t\t\tskinTransform += loadMatFromTexture(currentPixelPos,int(a_BoneIndices.z),offset) * a_BoneWeights.z;\r\n\t\t\tskinTransform += loadMatFromTexture(currentPixelPos,int(a_BoneIndices.w),offset) * a_BoneWeights.w;\r\n\t\t#else\r\n\t\t\tskinTransform = u_Bones[int(a_BoneIndices.x)] * a_BoneWeights.x;\r\n\t\t\tskinTransform += u_Bones[int(a_BoneIndices.y)] * a_BoneWeights.y;\r\n\t\t\tskinTransform += u_Bones[int(a_BoneIndices.z)] * a_BoneWeights.z;\r\n\t\t\tskinTransform += u_Bones[int(a_BoneIndices.w)] * a_BoneWeights.w;\r\n\t\t#endif\r\n\t\tposition=skinTransform*a_Position;\r\n\t #else\r\n\t\tposition=a_Position;\r\n\t#endif\r\n\t#ifdef GPU_INSTANCE\r\n\t\tgl_Position = a_MvpMatrix * position;\r\n\t#else\r\n\t\tgl_Position = u_MvpMatrix * position;\r\n\t#endif\r\n\r\n\t#ifdef TILINGOFFSET\r\n\t\tv_Texcoord0=TransformUV(a_Texcoord0,u_TilingOffset);\r\n\t#else\r\n\t\tv_Texcoord0=a_Texcoord0;\r\n\t#endif\r\n\r\n\t#if defined(COLOR)&&defined(ENABLEVERTEXCOLOR)\r\n\t\tv_Color = a_Color;\r\n\t#endif\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}";
  29658. var WaterPrimaryPS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#ifdef MAINTEXTURE\r\n\tuniform sampler2D u_MainTexture;\r\n#endif\r\n\r\n#ifdef NORMALTEXTURE\r\n\tuniform sampler2D u_NormalTexture;\r\n#endif\r\n\r\nuniform vec4 u_HorizonColor;\r\n\r\nvarying vec3 v_Normal;\r\nvarying vec3 v_Tangent;\r\nvarying vec3 v_Binormal;\r\nvarying vec3 v_ViewDir;\r\nvarying vec2 v_Texcoord0;\r\nvarying vec2 v_Texcoord1;\r\n\r\n\r\n#include \"Lighting.glsl\"\r\n\r\n\r\n\r\nvec3 NormalSampleToWorldSpace(vec4 normalMapSample) {\r\n\tvec3 normalT;\r\n\tnormalT.x = 2.0 * normalMapSample.x - 1.0;\r\n\tnormalT.y = 1.0 - 2.0 * normalMapSample.y;\r\n\tnormalT.z = sqrt(1.0 - clamp(dot(normalT.xy, normalT.xy), 0.0, 1.0));\r\n\r\n\tvec3 bumpedNormal = normalize(normalT);\r\n\r\n\treturn bumpedNormal;\r\n}\r\n\r\n\r\nvoid main()\r\n{\r\n\tvec4 bumpColor1 = texture2D(u_NormalTexture, v_Texcoord0);\r\n\tvec4 bumpColor2 = texture2D(u_NormalTexture, v_Texcoord1);\r\n\r\n\tvec3 normal1 = NormalSampleToWorldSpace(bumpColor1);\r\n\tvec3 normal2 = NormalSampleToWorldSpace(bumpColor2);\r\n\t\r\n\tvec3 normal = normalize((normal1 + normal2) * 0.5);\r\n\tvec3 viewDir = normalize(v_ViewDir);\r\n\tfloat fresnel = dot(viewDir, normal);\r\n\t\r\n\tvec4 waterColor = texture2D(u_MainTexture, vec2(fresnel, fresnel));\r\n\t\r\n\tvec4 color;\r\n\tcolor.rgb = mix(waterColor.rgb, u_HorizonColor.rgb, vec3(waterColor.a));\r\n\tcolor.a = u_HorizonColor.a;\r\n\t\r\n\tgl_FragColor = color;\r\n}\r\n\r\n\r\n";
  29659. var WaterPrimaryVS = "#include \"Lighting.glsl\";\r\n\r\nattribute vec4 a_Position;\r\nattribute vec3 a_Normal;\r\nattribute vec4 a_Tangent0;\r\n\r\nuniform mat4 u_MvpMatrix;\r\nuniform mat4 u_WorldMat;\r\nuniform vec3 u_CameraPos;\r\nuniform float u_WaveScale;\r\nuniform vec4 u_WaveSpeed;\r\nuniform float u_Time;\r\n\r\nvarying vec3 v_Normal;\r\nvarying vec3 v_Tangent;\r\nvarying vec3 v_Binormal;\r\nvarying vec3 v_ViewDir;\r\nvarying vec2 v_Texcoord0;\r\nvarying vec2 v_Texcoord1;\r\n\r\nvoid main()\r\n{\r\n\tvec4 positionWorld = u_WorldMat * a_Position;\r\n\tvec4 position = u_MvpMatrix * a_Position;\r\n\t\r\n\tvec4 temp = vec4(positionWorld.x, positionWorld.z, positionWorld.x, positionWorld.z) * u_WaveScale + u_WaveSpeed * u_WaveScale * u_Time;\r\n\t\r\n\tv_Texcoord0 = temp.xy * vec2(0.4, 0.45);\r\n\tv_Texcoord1 = temp.wz;\r\n\t\r\n\tmat3 worldMat = mat3(u_WorldMat);\r\n\tv_Normal = worldMat * a_Normal;\r\n\tv_Tangent = worldMat * a_Tangent0.xyz;\r\n\tv_Binormal = cross(v_Normal, v_Tangent) * a_Tangent0.w;\r\n\t\r\n\tv_ViewDir = u_CameraPos - positionWorld.xyz;\r\n\tgl_Position = position;\r\n\tgl_Position=remapGLPositionZ(gl_Position);\r\n}";
  29660. var DepthNormalUtil = "#define SAMPLE_DEPTH_TEXTURE(textureName,coord2) (texture2D(textureName,coord2).r)\r\n//此方法库用来压缩解析深度贴图,法线深度贴图\r\n\r\n/*camera 传入的Texture以及*/\r\nuniform sampler2D u_CameraDepthTexture;\r\nuniform vec4 u_ZBufferParams;\r\nuniform sampler2D u_CameraDepthNormalsTexture;\r\n\r\n// Encoding/decoding view space normals into 2D 0..1 vector\r\nvec2 EncodeViewNormalStereo( vec3 n )\r\n{\r\n n.z = abs(n.z);\r\n float kScale = 1.7777;\r\n vec2 enc;\r\n enc = n.xy / (n.z+1.0);\r\n enc /= kScale;\r\n enc = enc*0.5+0.5;\r\n return enc;\r\n}\r\n\r\nvec3 DecodeViewNormalStereo( vec4 enc4 )\r\n{\r\n float kScale = 1.7777;\r\n vec3 nn = enc4.xyz*vec3(2.0*kScale,2.0*kScale,0.0) + vec3(-kScale,-kScale,1.0);\r\n float g = 2.0 / dot(nn.xyz,nn.xyz);\r\n vec3 n;\r\n n.xy = g*nn.xy;\r\n n.z = g-1.0;\r\n return n;\r\n}\r\n\r\n\r\n// Encoding/decoding [0..1) floats into 8 bit/channel RG. Note that 1.0 will not be encoded properly.\r\nvec2 EncodeFloatRG( float v )\r\n{\r\n vec2 kEncodeMul = vec2(1.0, 255.0);\r\n float kEncodeBit = 1.0/255.0;\r\n vec2 enc = kEncodeMul * v;\r\n enc = fract(enc);\r\n enc.x -= enc.y * kEncodeBit;\r\n return enc;\r\n}\r\n\r\n\r\n\r\nfloat DecodeFloatRG( vec2 enc )\r\n{\r\n vec2 kDecodeDot = vec2(1.0, 1.0/255.0);\r\n return dot( enc, kDecodeDot );\r\n}\r\n\r\nvec4 EncodeDepthNormal(float depth,vec3 normals){\r\n\tvec4 encode;\r\n\tencode.xy = EncodeViewNormalStereo(normals);\r\n\tencode.zw = EncodeFloatRG(depth);\r\n return encode;\r\n}\r\n\r\nvoid DecodeDepthNormal( vec4 enc, out float depth, out vec3 normal )\r\n{\r\n depth = DecodeFloatRG (enc.zw);\r\n normal = DecodeViewNormalStereo (enc);\r\n}\r\n\r\n\r\n\r\nvec4 depthNormalsFragment(vec4 depthNormal)\r\n{\r\n return EncodeDepthNormal(depthNormal.w,depthNormal.xyz);\r\n}\r\n\r\n\r\n// Z buffer to linear 0..1 depth\r\nfloat Linear01Depth(float z,vec4 zbufferParams)\r\n{\r\n return 1.0 / (zbufferParams.x * z + zbufferParams.y);\r\n}\r\n// Z buffer to linear depth\r\nfloat LinearEyeDepth(float z,vec4 zbufferParams)\r\n{\r\n return 1.0 / (zbufferParams.z * z + zbufferParams.w);\r\n}\r\n";
  29661. class ShaderInit3D {
  29662. constructor() {
  29663. }
  29664. static __init__() {
  29665. Shader3D.SHADERDEFINE_LEGACYSINGALLIGHTING = Shader3D.getDefineByName("LEGACYSINGLELIGHTING");
  29666. Shader3D.SHADERDEFINE_GRAPHICS_API_GLES2 = Shader3D.getDefineByName("GRAPHICS_API_GLES2");
  29667. Shader3D.SHADERDEFINE_GRAPHICS_API_GLES3 = Shader3D.getDefineByName("GRAPHICS_API_GLES3");
  29668. Shader3D.addInclude("Lighting.glsl", LightingGLSL);
  29669. Shader3D.addInclude("ShadowSampleTent.glsl", ShadowSampleTentGLSL);
  29670. Shader3D.addInclude("GlobalIllumination.glsl", GlobalIllumination);
  29671. Shader3D.addInclude("Shadow.glsl", ShadowGLSL);
  29672. Shader3D.addInclude("ShadowCasterVS.glsl", ShadowCasterVSGLSL);
  29673. Shader3D.addInclude("ShadowCasterFS.glsl", ShadowCasterFSGLSL);
  29674. Shader3D.addInclude("Colors.glsl", ColorsGLSL);
  29675. Shader3D.addInclude("Sampling.glsl", SamplingGLSL);
  29676. Shader3D.addInclude("StdLib.glsl", StdLibGLSL);
  29677. Shader3D.addInclude("PBRVSInput.glsl", PBRVSInput);
  29678. Shader3D.addInclude("PBRFSInput.glsl", PBRFSInput);
  29679. Shader3D.addInclude("LayaPBRBRDF.glsl", LayaPBRBRDF);
  29680. Shader3D.addInclude("PBRCore.glsl", PBRCore);
  29681. Shader3D.addInclude("PBRVertex.glsl", PBRVertex);
  29682. Shader3D.addInclude("LayaUtile.glsl", LayaUtile);
  29683. Shader3D.addInclude("DepthNormalUtil.glsl", DepthNormalUtil);
  29684. var attributeMap = {
  29685. 'a_Position': VertexMesh.MESH_POSITION0,
  29686. 'a_Color': VertexMesh.MESH_COLOR0,
  29687. 'a_Normal': VertexMesh.MESH_NORMAL0,
  29688. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0,
  29689. 'a_Texcoord1': VertexMesh.MESH_TEXTURECOORDINATE1,
  29690. 'a_BoneWeights': VertexMesh.MESH_BLENDWEIGHT0,
  29691. 'a_BoneIndices': VertexMesh.MESH_BLENDINDICES0,
  29692. 'a_Tangent0': VertexMesh.MESH_TANGENT0,
  29693. 'a_MvpMatrix': VertexMesh.MESH_MVPMATRIX_ROW0,
  29694. 'a_WorldMat': VertexMesh.MESH_WORLDMATRIX_ROW0
  29695. };
  29696. var uniformMap = {
  29697. 'u_Bones': Shader3D.PERIOD_CUSTOM,
  29698. 'u_DiffuseTexture': Shader3D.PERIOD_MATERIAL,
  29699. 'u_SpecularTexture': Shader3D.PERIOD_MATERIAL,
  29700. 'u_NormalTexture': Shader3D.PERIOD_MATERIAL,
  29701. 'u_AlphaTestValue': Shader3D.PERIOD_MATERIAL,
  29702. 'u_DiffuseColor': Shader3D.PERIOD_MATERIAL,
  29703. 'u_MaterialSpecular': Shader3D.PERIOD_MATERIAL,
  29704. 'u_Shininess': Shader3D.PERIOD_MATERIAL,
  29705. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  29706. 'u_WorldMat': Shader3D.PERIOD_SPRITE,
  29707. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29708. 'u_LightmapScaleOffset': Shader3D.PERIOD_SPRITE,
  29709. 'u_LightMap': Shader3D.PERIOD_SPRITE,
  29710. 'u_LightMapDirection': Shader3D.PERIOD_SPRITE,
  29711. 'u_SimpleAnimatorTexture': Shader3D.PERIOD_SPRITE,
  29712. 'u_SimpleAnimatorParams': Shader3D.PERIOD_SPRITE,
  29713. 'u_SimpleAnimatorTextureSize': Shader3D.PERIOD_SPRITE,
  29714. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  29715. 'u_Viewport': Shader3D.PERIOD_CAMERA,
  29716. 'u_ProjectionParams': Shader3D.PERIOD_CAMERA,
  29717. 'u_View': Shader3D.PERIOD_CAMERA,
  29718. 'u_ViewProjection': Shader3D.PERIOD_CAMERA,
  29719. 'u_ReflectTexture': Shader3D.PERIOD_SCENE,
  29720. 'u_FogStart': Shader3D.PERIOD_SCENE,
  29721. 'u_FogRange': Shader3D.PERIOD_SCENE,
  29722. 'u_FogColor': Shader3D.PERIOD_SCENE,
  29723. 'u_DirationLightCount': Shader3D.PERIOD_SCENE,
  29724. 'u_LightBuffer': Shader3D.PERIOD_SCENE,
  29725. 'u_LightClusterBuffer': Shader3D.PERIOD_SCENE,
  29726. 'u_AmbientColor': Shader3D.PERIOD_SCENE,
  29727. 'u_ShadowBias': Shader3D.PERIOD_SCENE,
  29728. 'u_ShadowLightDirection': Shader3D.PERIOD_SCENE,
  29729. 'u_ShadowMap': Shader3D.PERIOD_SCENE,
  29730. 'u_ShadowParams': Shader3D.PERIOD_SCENE,
  29731. 'u_ShadowSplitSpheres': Shader3D.PERIOD_SCENE,
  29732. 'u_ShadowMatrices': Shader3D.PERIOD_SCENE,
  29733. 'u_ShadowMapSize': Shader3D.PERIOD_SCENE,
  29734. 'u_SpotShadowMap': Shader3D.PERIOD_SCENE,
  29735. 'u_SpotViewProjectMatrix': Shader3D.PERIOD_SCENE,
  29736. 'u_ShadowLightPosition': Shader3D.PERIOD_SCENE,
  29737. 'u_AmbientSHAr': Shader3D.PERIOD_SCENE,
  29738. 'u_AmbientSHAg': Shader3D.PERIOD_SCENE,
  29739. 'u_AmbientSHAb': Shader3D.PERIOD_SCENE,
  29740. 'u_AmbientSHBr': Shader3D.PERIOD_SCENE,
  29741. 'u_AmbientSHBg': Shader3D.PERIOD_SCENE,
  29742. 'u_AmbientSHBb': Shader3D.PERIOD_SCENE,
  29743. 'u_AmbientSHC': Shader3D.PERIOD_SCENE,
  29744. 'u_DirectionLight.color': Shader3D.PERIOD_SCENE,
  29745. 'u_DirectionLight.direction': Shader3D.PERIOD_SCENE,
  29746. 'u_PointLight.position': Shader3D.PERIOD_SCENE,
  29747. 'u_PointLight.range': Shader3D.PERIOD_SCENE,
  29748. 'u_PointLight.color': Shader3D.PERIOD_SCENE,
  29749. 'u_SpotLight.position': Shader3D.PERIOD_SCENE,
  29750. 'u_SpotLight.direction': Shader3D.PERIOD_SCENE,
  29751. 'u_SpotLight.range': Shader3D.PERIOD_SCENE,
  29752. 'u_SpotLight.spot': Shader3D.PERIOD_SCENE,
  29753. 'u_SpotLight.color': Shader3D.PERIOD_SCENE
  29754. };
  29755. var stateMap = {
  29756. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29757. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29758. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29759. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29760. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29761. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29762. };
  29763. var shader = Shader3D.add("BLINNPHONG", null, null, true);
  29764. var subShader = new SubShader(attributeMap, uniformMap);
  29765. shader.addSubShader(subShader);
  29766. subShader.addShaderPass(MeshBlinnPhongVS, MeshBlinnPhongPS, stateMap, "Forward");
  29767. var shaderPass = subShader.addShaderPass(MeshBlinnPhongShadowCasterVS, MeshBlinnPhongShadowCasterPS, stateMap, "ShadowCaster");
  29768. shaderPass = subShader.addShaderPass(DepthNormalsTextureVS, DepthNormalsTextureFS, stateMap, "DepthNormal");
  29769. attributeMap = {
  29770. 'a_Position': VertexMesh.MESH_POSITION0,
  29771. 'a_Color': VertexMesh.MESH_COLOR0
  29772. };
  29773. uniformMap = {
  29774. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29775. 'u_Color': Shader3D.PERIOD_MATERIAL
  29776. };
  29777. stateMap = {
  29778. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29779. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29780. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29781. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29782. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29783. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29784. };
  29785. shader = Shader3D.add("LineShader");
  29786. subShader = new SubShader(attributeMap, uniformMap);
  29787. shader.addSubShader(subShader);
  29788. subShader.addShaderPass(lineVS, linePS, stateMap);
  29789. attributeMap = {
  29790. 'a_Position': VertexMesh.MESH_POSITION0,
  29791. 'a_Color': VertexMesh.MESH_COLOR0,
  29792. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0,
  29793. 'a_BoneWeights': VertexMesh.MESH_BLENDWEIGHT0,
  29794. 'a_BoneIndices': VertexMesh.MESH_BLENDINDICES0,
  29795. 'a_MvpMatrix': VertexMesh.MESH_MVPMATRIX_ROW0
  29796. };
  29797. uniformMap = {
  29798. 'u_Bones': Shader3D.PERIOD_CUSTOM,
  29799. 'u_AlbedoTexture': Shader3D.PERIOD_MATERIAL,
  29800. 'u_AlbedoColor': Shader3D.PERIOD_MATERIAL,
  29801. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  29802. 'u_AlphaTestValue': Shader3D.PERIOD_MATERIAL,
  29803. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29804. 'u_SimpleAnimatorTexture': Shader3D.PERIOD_SPRITE,
  29805. 'u_SimpleAnimatorParams': Shader3D.PERIOD_SPRITE,
  29806. 'u_SimpleAnimatorTextureSize': Shader3D.PERIOD_SPRITE,
  29807. 'u_FogStart': Shader3D.PERIOD_SCENE,
  29808. 'u_FogRange': Shader3D.PERIOD_SCENE,
  29809. 'u_FogColor': Shader3D.PERIOD_SCENE
  29810. };
  29811. stateMap = {
  29812. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29813. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29814. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29815. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29816. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29817. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29818. };
  29819. shader = Shader3D.add("Unlit", null, null, true);
  29820. subShader = new SubShader(attributeMap, uniformMap);
  29821. shader.addSubShader(subShader);
  29822. subShader.addShaderPass(UnlitVS, UnlitPS, stateMap);
  29823. attributeMap = {
  29824. 'a_Position': VertexMesh.MESH_POSITION0,
  29825. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0,
  29826. 'a_BoneWeights': VertexMesh.MESH_BLENDWEIGHT0,
  29827. 'a_BoneIndices': VertexMesh.MESH_BLENDINDICES0,
  29828. 'a_MvpMatrix': VertexMesh.MESH_MVPMATRIX_ROW0
  29829. };
  29830. uniformMap = {
  29831. 'u_Bones': Shader3D.PERIOD_CUSTOM,
  29832. 'u_AlbedoTexture': Shader3D.PERIOD_MATERIAL,
  29833. 'u_AlbedoColor': Shader3D.PERIOD_MATERIAL,
  29834. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  29835. 'u_AlphaTestValue': Shader3D.PERIOD_MATERIAL,
  29836. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29837. 'u_SimpleAnimatorTexture': Shader3D.PERIOD_SPRITE,
  29838. 'u_SimpleAnimatorParams': Shader3D.PERIOD_SPRITE,
  29839. 'u_SimpleAnimatorTextureSize': Shader3D.PERIOD_SPRITE,
  29840. 'u_FogStart': Shader3D.PERIOD_SCENE,
  29841. 'u_FogRange': Shader3D.PERIOD_SCENE,
  29842. 'u_FogColor': Shader3D.PERIOD_SCENE
  29843. };
  29844. stateMap = {
  29845. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29846. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29847. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29848. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29849. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29850. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29851. };
  29852. shader = Shader3D.add("Effect", null, null, true);
  29853. subShader = new SubShader(attributeMap, uniformMap);
  29854. shader.addSubShader(subShader);
  29855. subShader.addShaderPass(EffectVS, EffectPS, stateMap);
  29856. attributeMap = {
  29857. 'a_CornerTextureCoordinate': VertexShuriKenParticle.PARTICLE_CORNERTEXTURECOORDINATE0,
  29858. 'a_MeshPosition': VertexShuriKenParticle.PARTICLE_POSITION0,
  29859. 'a_MeshColor': VertexShuriKenParticle.PARTICLE_COLOR0,
  29860. 'a_MeshTextureCoordinate': VertexShuriKenParticle.PARTICLE_TEXTURECOORDINATE0,
  29861. 'a_ShapePositionStartLifeTime': VertexShuriKenParticle.PARTICLE_SHAPEPOSITIONSTARTLIFETIME,
  29862. 'a_DirectionTime': VertexShuriKenParticle.PARTICLE_DIRECTIONTIME,
  29863. 'a_StartColor': VertexShuriKenParticle.PARTICLE_STARTCOLOR0,
  29864. 'a_EndColor': VertexShuriKenParticle.PARTICLE_ENDCOLOR0,
  29865. 'a_StartSize': VertexShuriKenParticle.PARTICLE_STARTSIZE,
  29866. 'a_StartRotation0': VertexShuriKenParticle.PARTICLE_STARTROTATION,
  29867. 'a_StartSpeed': VertexShuriKenParticle.PARTICLE_STARTSPEED,
  29868. 'a_Random0': VertexShuriKenParticle.PARTICLE_RANDOM0,
  29869. 'a_Random1': VertexShuriKenParticle.PARTICLE_RANDOM1,
  29870. 'a_SimulationWorldPostion': VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDPOSTION,
  29871. 'a_SimulationWorldRotation': VertexShuriKenParticle.PARTICLE_SIMULATIONWORLDROTATION
  29872. };
  29873. uniformMap = {
  29874. 'u_Tintcolor': Shader3D.PERIOD_MATERIAL,
  29875. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  29876. 'u_texture': Shader3D.PERIOD_MATERIAL,
  29877. 'u_WorldPosition': Shader3D.PERIOD_SPRITE,
  29878. 'u_WorldRotation': Shader3D.PERIOD_SPRITE,
  29879. 'u_PositionScale': Shader3D.PERIOD_SPRITE,
  29880. 'u_SizeScale': Shader3D.PERIOD_SPRITE,
  29881. 'u_ScalingMode': Shader3D.PERIOD_SPRITE,
  29882. 'u_Gravity': Shader3D.PERIOD_SPRITE,
  29883. 'u_ThreeDStartRotation': Shader3D.PERIOD_SPRITE,
  29884. 'u_StretchedBillboardLengthScale': Shader3D.PERIOD_SPRITE,
  29885. 'u_StretchedBillboardSpeedScale': Shader3D.PERIOD_SPRITE,
  29886. 'u_SimulationSpace': Shader3D.PERIOD_SPRITE,
  29887. 'u_CurrentTime': Shader3D.PERIOD_SPRITE,
  29888. 'u_ColorOverLifeGradientAlphas': Shader3D.PERIOD_SPRITE,
  29889. 'u_ColorOverLifeGradientColors': Shader3D.PERIOD_SPRITE,
  29890. 'u_MaxColorOverLifeGradientAlphas': Shader3D.PERIOD_SPRITE,
  29891. 'u_MaxColorOverLifeGradientColors': Shader3D.PERIOD_SPRITE,
  29892. 'u_VOLVelocityConst': Shader3D.PERIOD_SPRITE,
  29893. 'u_VOLVelocityGradientX': Shader3D.PERIOD_SPRITE,
  29894. 'u_VOLVelocityGradientY': Shader3D.PERIOD_SPRITE,
  29895. 'u_VOLVelocityGradientZ': Shader3D.PERIOD_SPRITE,
  29896. 'u_VOLVelocityConstMax': Shader3D.PERIOD_SPRITE,
  29897. 'u_VOLVelocityGradientMaxX': Shader3D.PERIOD_SPRITE,
  29898. 'u_VOLVelocityGradientMaxY': Shader3D.PERIOD_SPRITE,
  29899. 'u_VOLVelocityGradientMaxZ': Shader3D.PERIOD_SPRITE,
  29900. 'u_VOLSpaceType': Shader3D.PERIOD_SPRITE,
  29901. 'u_SOLSizeGradient': Shader3D.PERIOD_SPRITE,
  29902. 'u_SOLSizeGradientX': Shader3D.PERIOD_SPRITE,
  29903. 'u_SOLSizeGradientY': Shader3D.PERIOD_SPRITE,
  29904. 'u_SOLSizeGradientZ': Shader3D.PERIOD_SPRITE,
  29905. 'u_SOLSizeGradientMax': Shader3D.PERIOD_SPRITE,
  29906. 'u_SOLSizeGradientMaxX': Shader3D.PERIOD_SPRITE,
  29907. 'u_SOLSizeGradientMaxY': Shader3D.PERIOD_SPRITE,
  29908. 'u_SOLSizeGradientMaxZ': Shader3D.PERIOD_SPRITE,
  29909. 'u_ROLAngularVelocityConst': Shader3D.PERIOD_SPRITE,
  29910. 'u_ROLAngularVelocityConstSeprarate': Shader3D.PERIOD_SPRITE,
  29911. 'u_ROLAngularVelocityGradient': Shader3D.PERIOD_SPRITE,
  29912. 'u_ROLAngularVelocityGradientX': Shader3D.PERIOD_SPRITE,
  29913. 'u_ROLAngularVelocityGradientY': Shader3D.PERIOD_SPRITE,
  29914. 'u_ROLAngularVelocityGradientZ': Shader3D.PERIOD_SPRITE,
  29915. 'u_ROLAngularVelocityConstMax': Shader3D.PERIOD_SPRITE,
  29916. 'u_ROLAngularVelocityConstMaxSeprarate': Shader3D.PERIOD_SPRITE,
  29917. 'u_ROLAngularVelocityGradientMax': Shader3D.PERIOD_SPRITE,
  29918. 'u_ROLAngularVelocityGradientMaxX': Shader3D.PERIOD_SPRITE,
  29919. 'u_ROLAngularVelocityGradientMaxY': Shader3D.PERIOD_SPRITE,
  29920. 'u_ROLAngularVelocityGradientMaxZ': Shader3D.PERIOD_SPRITE,
  29921. 'u_ROLAngularVelocityGradientMaxW': Shader3D.PERIOD_SPRITE,
  29922. 'u_TSACycles': Shader3D.PERIOD_SPRITE,
  29923. 'u_TSASubUVLength': Shader3D.PERIOD_SPRITE,
  29924. 'u_TSAGradientUVs': Shader3D.PERIOD_SPRITE,
  29925. 'u_TSAMaxGradientUVs': Shader3D.PERIOD_SPRITE,
  29926. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  29927. 'u_CameraDirection': Shader3D.PERIOD_CAMERA,
  29928. 'u_CameraUp': Shader3D.PERIOD_CAMERA,
  29929. 'u_View': Shader3D.PERIOD_CAMERA,
  29930. 'u_Projection': Shader3D.PERIOD_CAMERA,
  29931. 'u_FogStart': Shader3D.PERIOD_SCENE,
  29932. 'u_FogRange': Shader3D.PERIOD_SCENE,
  29933. 'u_FogColor': Shader3D.PERIOD_SCENE
  29934. };
  29935. stateMap = {
  29936. 's_Cull': Shader3D.RENDER_STATE_CULL,
  29937. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  29938. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  29939. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  29940. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  29941. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  29942. };
  29943. shader = Shader3D.add("PARTICLESHURIKEN");
  29944. subShader = new SubShader(attributeMap, uniformMap);
  29945. shader.addSubShader(subShader);
  29946. subShader.addShaderPass(ParticleShuriKenVS, ParticleShuriKenPS, stateMap);
  29947. attributeMap = {
  29948. 'a_Position': VertexMesh.MESH_POSITION0
  29949. };
  29950. uniformMap = {
  29951. 'u_TintColor': Shader3D.PERIOD_MATERIAL,
  29952. 'u_Exposure': Shader3D.PERIOD_MATERIAL,
  29953. 'u_Rotation': Shader3D.PERIOD_MATERIAL,
  29954. 'u_CubeTexture': Shader3D.PERIOD_MATERIAL,
  29955. 'u_ViewProjection': Shader3D.PERIOD_CAMERA
  29956. };
  29957. shader = Shader3D.add("SkyBox");
  29958. subShader = new SubShader(attributeMap, uniformMap);
  29959. shader.addSubShader(subShader);
  29960. subShader.addShaderPass(SkyBoxVS, SkyBoxPS);
  29961. attributeMap = {
  29962. 'a_Position': VertexMesh.MESH_POSITION0
  29963. };
  29964. uniformMap = {
  29965. 'u_SunSize': Shader3D.PERIOD_MATERIAL,
  29966. 'u_SunSizeConvergence': Shader3D.PERIOD_MATERIAL,
  29967. 'u_AtmosphereThickness': Shader3D.PERIOD_MATERIAL,
  29968. 'u_SkyTint': Shader3D.PERIOD_MATERIAL,
  29969. 'u_GroundTint': Shader3D.PERIOD_MATERIAL,
  29970. 'u_Exposure': Shader3D.PERIOD_MATERIAL,
  29971. 'u_ViewProjection': Shader3D.PERIOD_CAMERA,
  29972. 'u_SunLight.direction': Shader3D.PERIOD_SCENE,
  29973. 'u_SunLight.color': Shader3D.PERIOD_SCENE,
  29974. };
  29975. shader = Shader3D.add("SkyBoxProcedural");
  29976. subShader = new SubShader(attributeMap, uniformMap);
  29977. shader.addSubShader(subShader);
  29978. subShader.addShaderPass(SkyBoxProceduralVS, SkyBoxProceduralPS);
  29979. attributeMap = {
  29980. 'a_Position': VertexMesh.MESH_POSITION0,
  29981. 'a_Normal': VertexMesh.MESH_NORMAL0,
  29982. 'a_Texcoord0': VertexMesh.MESH_TEXTURECOORDINATE0
  29983. };
  29984. uniformMap = {
  29985. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  29986. 'u_WorldMat': Shader3D.PERIOD_SPRITE,
  29987. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  29988. 'u_Viewport': Shader3D.PERIOD_CAMERA,
  29989. 'u_ProjectionParams': Shader3D.PERIOD_CAMERA,
  29990. 'u_View': Shader3D.PERIOD_CAMERA,
  29991. 'u_LightmapScaleOffset': Shader3D.PERIOD_SPRITE,
  29992. 'u_LightMap': Shader3D.PERIOD_SPRITE,
  29993. 'u_SplatAlphaTexture': Shader3D.PERIOD_MATERIAL,
  29994. 'u_DiffuseTexture1': Shader3D.PERIOD_MATERIAL,
  29995. 'u_DiffuseTexture2': Shader3D.PERIOD_MATERIAL,
  29996. 'u_DiffuseTexture3': Shader3D.PERIOD_MATERIAL,
  29997. 'u_DiffuseTexture4': Shader3D.PERIOD_MATERIAL,
  29998. 'u_DiffuseTexture5': Shader3D.PERIOD_MATERIAL,
  29999. 'u_DiffuseScaleOffset1': Shader3D.PERIOD_MATERIAL,
  30000. 'u_DiffuseScaleOffset2': Shader3D.PERIOD_MATERIAL,
  30001. 'u_DiffuseScaleOffset3': Shader3D.PERIOD_MATERIAL,
  30002. 'u_DiffuseScaleOffset4': Shader3D.PERIOD_MATERIAL,
  30003. 'u_DiffuseScaleOffset5': Shader3D.PERIOD_MATERIAL,
  30004. 'u_FogStart': Shader3D.PERIOD_SCENE,
  30005. 'u_FogRange': Shader3D.PERIOD_SCENE,
  30006. 'u_FogColor': Shader3D.PERIOD_SCENE,
  30007. 'u_DirationLightCount': Shader3D.PERIOD_SCENE,
  30008. 'u_LightBuffer': Shader3D.PERIOD_SCENE,
  30009. 'u_LightClusterBuffer': Shader3D.PERIOD_SCENE,
  30010. 'u_AmbientColor': Shader3D.PERIOD_SCENE,
  30011. 'u_ShadowMap': Shader3D.PERIOD_SCENE,
  30012. 'u_shadowMap2': Shader3D.PERIOD_SCENE,
  30013. 'u_shadowMap3': Shader3D.PERIOD_SCENE,
  30014. 'u_ShadowSplitSpheres': Shader3D.PERIOD_SCENE,
  30015. 'u_ShadowMatrices': Shader3D.PERIOD_SCENE,
  30016. 'u_ShadowMapSize': Shader3D.PERIOD_SCENE,
  30017. 'u_DirectionLight.color': Shader3D.PERIOD_SCENE,
  30018. 'u_DirectionLight.direction': Shader3D.PERIOD_SCENE,
  30019. 'u_PointLight.position': Shader3D.PERIOD_SCENE,
  30020. 'u_PointLight.range': Shader3D.PERIOD_SCENE,
  30021. 'u_PointLight.color': Shader3D.PERIOD_SCENE,
  30022. 'u_SpotLight.position': Shader3D.PERIOD_SCENE,
  30023. 'u_SpotLight.direction': Shader3D.PERIOD_SCENE,
  30024. 'u_SpotLight.range': Shader3D.PERIOD_SCENE,
  30025. 'u_SpotLight.spot': Shader3D.PERIOD_SCENE,
  30026. 'u_SpotLight.color': Shader3D.PERIOD_SCENE
  30027. };
  30028. stateMap = {
  30029. 's_Cull': Shader3D.RENDER_STATE_CULL,
  30030. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  30031. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  30032. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  30033. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  30034. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  30035. };
  30036. shader = Shader3D.add("ExtendTerrain");
  30037. subShader = new SubShader(attributeMap, uniformMap);
  30038. shader.addSubShader(subShader);
  30039. subShader.addShaderPass(extendTerrainVS, extendTerrainPS, stateMap);
  30040. attributeMap = {
  30041. 'a_Position': VertexTrail.TRAIL_POSITION0,
  30042. 'a_OffsetVector': VertexTrail.TRAIL_OFFSETVECTOR,
  30043. 'a_Texcoord0X': VertexTrail.TRAIL_TEXTURECOORDINATE0X,
  30044. 'a_Texcoord0Y': VertexTrail.TRAIL_TEXTURECOORDINATE0Y,
  30045. 'a_BirthTime': VertexTrail.TRAIL_TIME0,
  30046. 'a_Color': VertexTrail.TRAIL_COLOR
  30047. };
  30048. uniformMap = {
  30049. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  30050. 'u_View': Shader3D.PERIOD_CAMERA,
  30051. 'u_Projection': Shader3D.PERIOD_CAMERA,
  30052. 'u_TilingOffset': Shader3D.PERIOD_MATERIAL,
  30053. 'u_MainTexture': Shader3D.PERIOD_MATERIAL,
  30054. 'u_MainColor': Shader3D.PERIOD_MATERIAL,
  30055. 'u_CurTime': Shader3D.PERIOD_SPRITE,
  30056. 'u_LifeTime': Shader3D.PERIOD_SPRITE,
  30057. 'u_WidthCurve': Shader3D.PERIOD_SPRITE,
  30058. 'u_WidthCurveKeyLength': Shader3D.PERIOD_SPRITE,
  30059. 'u_GradientColorkey': Shader3D.PERIOD_SPRITE,
  30060. 'u_GradientAlphakey': Shader3D.PERIOD_SPRITE
  30061. };
  30062. stateMap = {
  30063. 's_Cull': Shader3D.RENDER_STATE_CULL,
  30064. 's_Blend': Shader3D.RENDER_STATE_BLEND,
  30065. 's_BlendSrc': Shader3D.RENDER_STATE_BLEND_SRC,
  30066. 's_BlendDst': Shader3D.RENDER_STATE_BLEND_DST,
  30067. 's_DepthTest': Shader3D.RENDER_STATE_DEPTH_TEST,
  30068. 's_DepthWrite': Shader3D.RENDER_STATE_DEPTH_WRITE
  30069. };
  30070. shader = Shader3D.add("Trail");
  30071. subShader = new SubShader(attributeMap, uniformMap);
  30072. shader.addSubShader(subShader);
  30073. subShader.addShaderPass(TrailVS, TrailPS, stateMap);
  30074. attributeMap = {
  30075. 'a_Position': VertexMesh.MESH_POSITION0,
  30076. 'a_Normal': VertexMesh.MESH_NORMAL0,
  30077. 'a_Tangent0': VertexMesh.MESH_TANGENT0
  30078. };
  30079. uniformMap = {
  30080. 'u_MvpMatrix': Shader3D.PERIOD_SPRITE,
  30081. 'u_WorldMat': Shader3D.PERIOD_SPRITE,
  30082. 'u_CameraPos': Shader3D.PERIOD_CAMERA,
  30083. 'u_Time': Shader3D.PERIOD_SCENE,
  30084. 'u_MainTexture': Shader3D.PERIOD_MATERIAL,
  30085. 'u_NormalTexture': Shader3D.PERIOD_MATERIAL,
  30086. 'u_HorizonColor': Shader3D.PERIOD_MATERIAL,
  30087. 'u_WaveScale': Shader3D.PERIOD_MATERIAL,
  30088. 'u_WaveSpeed': Shader3D.PERIOD_MATERIAL
  30089. };
  30090. shader = Shader3D.add("WaterPrimary");
  30091. subShader = new SubShader(attributeMap, uniformMap);
  30092. shader.addSubShader(subShader);
  30093. subShader.addShaderPass(WaterPrimaryVS, WaterPrimaryPS);
  30094. attributeMap = {
  30095. 'a_PositionTexcoord': VertexMesh.MESH_POSITION0
  30096. };
  30097. uniformMap = {
  30098. 'u_MainTex': Shader3D.PERIOD_MATERIAL,
  30099. 'u_OffsetScale': Shader3D.PERIOD_MATERIAL
  30100. };
  30101. shader = Shader3D.add("BlitScreen");
  30102. subShader = new SubShader(attributeMap, uniformMap);
  30103. shader.addSubShader(subShader);
  30104. var shaderPass = subShader.addShaderPass(BlitScreenVS, BlitScreenPS);
  30105. var renderState = shaderPass.renderState;
  30106. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  30107. renderState.depthWrite = false;
  30108. renderState.cull = RenderState.CULL_NONE;
  30109. renderState.blend = RenderState.BLEND_DISABLE;
  30110. attributeMap = {
  30111. 'a_PositionTexcoord': VertexMesh.MESH_POSITION0
  30112. };
  30113. uniformMap = {
  30114. 'u_MainTex': Shader3D.PERIOD_MATERIAL,
  30115. 'u_BloomTex': Shader3D.PERIOD_MATERIAL,
  30116. 'u_AutoExposureTex': Shader3D.PERIOD_MATERIAL,
  30117. 'u_MainTex_TexelSize': Shader3D.PERIOD_MATERIAL,
  30118. 'u_SampleScale': Shader3D.PERIOD_MATERIAL,
  30119. 'u_Threshold': Shader3D.PERIOD_MATERIAL,
  30120. 'u_Params': Shader3D.PERIOD_MATERIAL
  30121. };
  30122. shader = Shader3D.add("PostProcessBloom");
  30123. subShader = new SubShader(attributeMap, uniformMap);
  30124. shader.addSubShader(subShader);
  30125. shaderPass = subShader.addShaderPass(BloomVS, BloomPrefilter13PS);
  30126. renderState = shaderPass.renderState;
  30127. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  30128. renderState.depthWrite = false;
  30129. renderState.cull = RenderState.CULL_NONE;
  30130. renderState.blend = RenderState.BLEND_DISABLE;
  30131. subShader = new SubShader(attributeMap, uniformMap);
  30132. shader.addSubShader(subShader);
  30133. shaderPass = subShader.addShaderPass(BloomVS, BloomPrefilter4PS);
  30134. renderState = shaderPass.renderState;
  30135. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  30136. renderState.depthWrite = false;
  30137. renderState.cull = RenderState.CULL_NONE;
  30138. renderState.blend = RenderState.BLEND_DISABLE;
  30139. subShader = new SubShader(attributeMap, uniformMap);
  30140. shader.addSubShader(subShader);
  30141. shaderPass = subShader.addShaderPass(BloomVS, BloomDownsample13PS);
  30142. renderState = shaderPass.renderState;
  30143. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  30144. renderState.depthWrite = false;
  30145. renderState.cull = RenderState.CULL_NONE;
  30146. renderState.blend = RenderState.BLEND_DISABLE;
  30147. subShader = new SubShader(attributeMap, uniformMap);
  30148. shader.addSubShader(subShader);
  30149. shaderPass = subShader.addShaderPass(BloomVS, BloomDownsample4PS);
  30150. renderState = shaderPass.renderState;
  30151. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  30152. renderState.depthWrite = false;
  30153. renderState.cull = RenderState.CULL_NONE;
  30154. renderState.blend = RenderState.BLEND_DISABLE;
  30155. subShader = new SubShader(attributeMap, uniformMap);
  30156. shader.addSubShader(subShader);
  30157. shaderPass = subShader.addShaderPass(BloomVS, BloomUpsampleTentPS);
  30158. renderState = shaderPass.renderState;
  30159. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  30160. renderState.depthWrite = false;
  30161. renderState.cull = RenderState.CULL_NONE;
  30162. renderState.blend = RenderState.BLEND_DISABLE;
  30163. subShader = new SubShader(attributeMap, uniformMap);
  30164. shader.addSubShader(subShader);
  30165. shaderPass = subShader.addShaderPass(BloomVS, BloomUpsampleBoxPS);
  30166. renderState = shaderPass.renderState;
  30167. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  30168. renderState.depthWrite = false;
  30169. renderState.cull = RenderState.CULL_NONE;
  30170. renderState.blend = RenderState.BLEND_DISABLE;
  30171. attributeMap = {
  30172. 'a_PositionTexcoord': VertexMesh.MESH_POSITION0
  30173. };
  30174. uniformMap = {
  30175. 'u_MainTex': Shader3D.PERIOD_MATERIAL,
  30176. 'u_BloomTex': Shader3D.PERIOD_MATERIAL,
  30177. 'u_AutoExposureTex': Shader3D.PERIOD_MATERIAL,
  30178. 'u_Bloom_DirtTileOffset': Shader3D.PERIOD_MATERIAL,
  30179. 'u_Bloom_DirtTex': Shader3D.PERIOD_MATERIAL,
  30180. 'u_BloomTex_TexelSize': Shader3D.PERIOD_MATERIAL,
  30181. 'u_Bloom_Settings': Shader3D.PERIOD_MATERIAL,
  30182. 'u_Bloom_Color': Shader3D.PERIOD_MATERIAL
  30183. };
  30184. shader = Shader3D.add("PostProcessComposite");
  30185. subShader = new SubShader(attributeMap, uniformMap);
  30186. shader.addSubShader(subShader);
  30187. shaderPass = subShader.addShaderPass(CompositeVS, CompositePS);
  30188. renderState = shaderPass.renderState;
  30189. renderState.depthTest = RenderState.DEPTHTEST_ALWAYS;
  30190. renderState.depthWrite = false;
  30191. renderState.cull = RenderState.CULL_NONE;
  30192. renderState.blend = RenderState.BLEND_DISABLE;
  30193. }
  30194. }
  30195. class DirectionLight extends LightSprite {
  30196. constructor() {
  30197. super();
  30198. this._direction = new Vector3();
  30199. this._shadowCascadesMode = exports.ShadowCascadesMode.NoCascades;
  30200. this._shadowTwoCascadeSplits = 1.0 / 3.0;
  30201. this._shadowFourCascadeSplits = new Vector3(1.0 / 15, 3.0 / 15.0, 7.0 / 15.0);
  30202. this._lightType = exports.LightType.Directional;
  30203. }
  30204. get shadowCascadesMode() {
  30205. return this._shadowCascadesMode;
  30206. }
  30207. set shadowCascadesMode(value) {
  30208. this._shadowCascadesMode = value;
  30209. }
  30210. get shadowTwoCascadeSplits() {
  30211. return this._shadowTwoCascadeSplits;
  30212. }
  30213. set shadowTwoCascadeSplits(value) {
  30214. this._shadowTwoCascadeSplits = value;
  30215. }
  30216. get shadowFourCascadeSplits() {
  30217. return this._shadowFourCascadeSplits;
  30218. }
  30219. set shadowFourCascadeSplits(value) {
  30220. if (value.x > value.y || value.y > value.z || value.z > 1.0)
  30221. throw "DiretionLight:Invalid value.";
  30222. value.cloneTo(this._shadowFourCascadeSplits);
  30223. }
  30224. _addToLightQueue() {
  30225. this._scene._directionLights.add(this);
  30226. }
  30227. _removeFromLightQueue() {
  30228. this._scene._directionLights.remove(this);
  30229. }
  30230. _create() {
  30231. return new DirectionLight();
  30232. }
  30233. }
  30234. class PointLight extends LightSprite {
  30235. constructor() {
  30236. super();
  30237. this._range = 6.0;
  30238. this._lightType = exports.LightType.Point;
  30239. }
  30240. get range() {
  30241. return this._range;
  30242. }
  30243. set range(value) {
  30244. this._range = value;
  30245. }
  30246. _addToLightQueue() {
  30247. this._scene._pointLights.add(this);
  30248. }
  30249. _removeFromLightQueue() {
  30250. this._scene._pointLights.remove(this);
  30251. }
  30252. _parse(data, spriteMap) {
  30253. super._parse(data, spriteMap);
  30254. this.range = data.range;
  30255. }
  30256. _cloneTo(destObject, rootSprite, dstSprite) {
  30257. super._cloneTo(destObject, rootSprite, dstSprite);
  30258. var pointlight = destObject;
  30259. pointlight.range = this.range;
  30260. pointlight._lightType = exports.LightType.Point;
  30261. }
  30262. _create() {
  30263. return new PointLight();
  30264. }
  30265. }
  30266. class SpotLight extends LightSprite {
  30267. constructor() {
  30268. super();
  30269. this._spotAngle = 30.0;
  30270. this._range = 10.0;
  30271. this._direction = new Vector3();
  30272. this._lightType = exports.LightType.Spot;
  30273. }
  30274. get spotAngle() {
  30275. return this._spotAngle;
  30276. }
  30277. set spotAngle(value) {
  30278. this._spotAngle = Math.max(Math.min(value, 179), 0);
  30279. }
  30280. get range() {
  30281. return this._range;
  30282. }
  30283. set range(value) {
  30284. this._range = value;
  30285. }
  30286. _addToLightQueue() {
  30287. this._scene._spotLights.add(this);
  30288. }
  30289. _removeFromLightQueue() {
  30290. this._scene._spotLights.remove(this);
  30291. }
  30292. _parse(data, spriteMap) {
  30293. super._parse(data, spriteMap);
  30294. this.range = data.range;
  30295. this.spotAngle = data.spotAngle;
  30296. }
  30297. _cloneTo(destObject, rootSprite, dstSprite) {
  30298. super._cloneTo(destObject, rootSprite, dstSprite);
  30299. var spotLight = destObject;
  30300. spotLight.range = this.range;
  30301. spotLight.spotAngle = this.spotAngle;
  30302. }
  30303. _create() {
  30304. return new SpotLight();
  30305. }
  30306. }
  30307. class SimpleSkinnedMeshRenderer extends SkinnedMeshRenderer {
  30308. constructor(owner) {
  30309. super(owner);
  30310. this._simpleAnimatorParams = new Vector4();
  30311. this._simpleAnimatorOffset = new Vector2();
  30312. this._shaderValues.addDefine(SkinnedMeshSprite3DShaderDeclaration.SHADERDEFINE_SIMPLEBONE);
  30313. this._shaderValues.addDefine(SkinnedMeshSprite3DShaderDeclaration.SHADERDEFINE_BONE);
  30314. }
  30315. get simpleAnimatorTexture() {
  30316. return this._simpleAnimatorTexture;
  30317. }
  30318. set simpleAnimatorTexture(value) {
  30319. this._simpleAnimatorTexture = value;
  30320. this._simpleAnimatorTextureSize = value.width;
  30321. this._shaderValues.setTexture(SimpleSkinnedMeshRenderer.SIMPLE_SIMPLEANIMATORTEXTURE, value);
  30322. value._addReference();
  30323. this._shaderValues.setNumber(SimpleSkinnedMeshRenderer.SIMPLE_SIMPLEANIMATORTEXTURESIZE, this._simpleAnimatorTextureSize);
  30324. }
  30325. get simpleAnimatorOffset() {
  30326. return this._simpleAnimatorOffset;
  30327. }
  30328. set simpleAnimatorOffset(value) {
  30329. value.cloneTo(this._simpleAnimatorOffset);
  30330. }
  30331. _computeAnimatorParamsData() {
  30332. if (this._cacheMesh) {
  30333. this._simpleAnimatorParams.x = this._simpleAnimatorOffset.x;
  30334. this._simpleAnimatorParams.y = Math.round(this._simpleAnimatorOffset.y) * this._bonesNums * 4;
  30335. }
  30336. }
  30337. _createRenderElement() {
  30338. return new SubMeshRenderElement();
  30339. }
  30340. _setCacheAnimator(animator) {
  30341. this._cacheAnimator = animator;
  30342. this._shaderValues.addDefine(SkinnedMeshSprite3DShaderDeclaration.SHADERDEFINE_SIMPLEBONE);
  30343. }
  30344. _onMeshChange(value) {
  30345. super._onMeshChange(value);
  30346. this._cacheMesh = value;
  30347. }
  30348. _renderUpdate(context, transform) {
  30349. var element = context.renderElement;
  30350. switch (element.renderType) {
  30351. case RenderElement.RENDERTYPE_NORMAL:
  30352. if (this._cacheAnimator) {
  30353. var worldMat = this._cacheAnimator.owner.transform.worldMatrix;
  30354. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, worldMat);
  30355. }
  30356. else {
  30357. this._shaderValues.setMatrix4x4(Sprite3D.WORLDMATRIX, transform.worldMatrix);
  30358. }
  30359. this._computeAnimatorParamsData();
  30360. this._shaderValues.setVector(SimpleSkinnedMeshRenderer.SIMPLE_SIMPLEANIMATORPARAMS, this._simpleAnimatorParams);
  30361. break;
  30362. case RenderElement.RENDERTYPE_INSTANCEBATCH:
  30363. var worldMatrixData = SubMeshInstanceBatch.instance.instanceWorldMatrixData;
  30364. var insBatches = element.instanceBatchElementList;
  30365. var elements = insBatches.elements;
  30366. var count = insBatches.length;
  30367. if (this._cacheAnimator) {
  30368. for (var i = 0; i < count; i++) {
  30369. var mat = (elements[i].render)._cacheAnimator.owner._transform.worldMatrix;
  30370. worldMatrixData.set(mat.elements, i * 16);
  30371. }
  30372. }
  30373. else {
  30374. for (var i = 0; i < count; i++)
  30375. worldMatrixData.set(elements[i]._transform.worldMatrix.elements, i * 16);
  30376. }
  30377. var worldBuffer = SubMeshInstanceBatch.instance.instanceWorldMatrixBuffer;
  30378. worldBuffer.orphanStorage();
  30379. worldBuffer.setData(worldMatrixData.buffer, 0, 0, count * 16 * 4);
  30380. this._shaderValues.addDefine(MeshSprite3DShaderDeclaration.SHADERDEFINE_GPU_INSTANCE);
  30381. var simpleAnimatorData = SubMeshInstanceBatch.instance.instanceSimpleAnimatorData;
  30382. if (this._cacheAnimator) {
  30383. for (var i = 0; i < count; i++) {
  30384. var render = (elements[i].render);
  30385. render._computeAnimatorParamsData();
  30386. var simpleAnimatorParams = render._simpleAnimatorParams;
  30387. var offset = i * 4;
  30388. simpleAnimatorData[offset] = simpleAnimatorParams.x;
  30389. simpleAnimatorData[offset + 1] = simpleAnimatorParams.y;
  30390. }
  30391. }
  30392. else {
  30393. for (var i = 0; i < count; i++) {
  30394. simpleAnimatorData[offset] = 0;
  30395. simpleAnimatorData[offset + 1] = 0;
  30396. }
  30397. }
  30398. var simpleAnimatorBuffer = SubMeshInstanceBatch.instance.instanceSimpleAnimatorBuffer;
  30399. simpleAnimatorBuffer.orphanStorage();
  30400. simpleAnimatorBuffer.setData(simpleAnimatorData.buffer, 0, 0, count * 4 * 4);
  30401. break;
  30402. }
  30403. }
  30404. _renderUpdateWithCamera(context, transform) {
  30405. var projectionView = context.projectionViewMatrix;
  30406. if (projectionView) {
  30407. var element = context.renderElement;
  30408. switch (element.renderType) {
  30409. case RenderElement.RENDERTYPE_NORMAL:
  30410. if (this._cacheAnimator) {
  30411. var mat = this._cacheAnimator.owner._transform.worldMatrix;
  30412. Matrix4x4.multiply(projectionView, mat, this._projectionViewWorldMatrix);
  30413. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, this._projectionViewWorldMatrix);
  30414. }
  30415. else {
  30416. Matrix4x4.multiply(projectionView, transform.worldMatrix, this._projectionViewWorldMatrix);
  30417. this._shaderValues.setMatrix4x4(Sprite3D.MVPMATRIX, this._projectionViewWorldMatrix);
  30418. }
  30419. break;
  30420. case RenderElement.RENDERTYPE_INSTANCEBATCH:
  30421. var mvpMatrixData = SubMeshInstanceBatch.instance.instanceMVPMatrixData;
  30422. var insBatches = element.instanceBatchElementList;
  30423. var elements = insBatches.elements;
  30424. var count = insBatches.length;
  30425. if (this._cacheAnimator) {
  30426. for (var i = 0; i < count; i++) {
  30427. var worldMat = (elements[i].render)._cacheAnimator.owner._transform.worldMatrix;
  30428. Utils3D.mulMatrixByArray(projectionView.elements, 0, worldMat.elements, 0, mvpMatrixData, i * 16);
  30429. }
  30430. }
  30431. else {
  30432. for (var i = 0; i < count; i++) {
  30433. var worldMat = elements[i]._transform.worldMatrix;
  30434. Utils3D.mulMatrixByArray(projectionView.elements, 0, worldMat.elements, 0, mvpMatrixData, i * 16);
  30435. }
  30436. }
  30437. var mvpBuffer = SubMeshInstanceBatch.instance.instanceMVPMatrixBuffer;
  30438. mvpBuffer.orphanStorage();
  30439. mvpBuffer.setData(mvpMatrixData.buffer, 0, 0, count * 16 * 4);
  30440. break;
  30441. }
  30442. }
  30443. }
  30444. _destroy() {
  30445. if (this._cacheRootBone)
  30446. (!this._cacheRootBone.destroyed) && (this._cacheRootBone.transform.off(Laya.Event.TRANSFORM_CHANGED, this, this._onWorldMatNeedChange));
  30447. (this._simpleAnimatorTexture) && this._simpleAnimatorTexture._removeReference();
  30448. this._simpleAnimatorTexture = null;
  30449. }
  30450. }
  30451. class SimpleSkinnedMeshSprite3D extends RenderableSprite3D {
  30452. constructor(mesh = null, name = null) {
  30453. super(name);
  30454. this._meshFilter = new MeshFilter(this);
  30455. this._render = new SimpleSkinnedMeshRenderer(this);
  30456. (mesh) && (this._meshFilter.sharedMesh = mesh);
  30457. }
  30458. static __init__() {
  30459. SimpleSkinnedMeshRenderer.SIMPLE_SIMPLEANIMATORPARAMS = SimpleSkinnedMeshSprite3D.SIMPLE_SIMPLEANIMATORPARAMS;
  30460. SimpleSkinnedMeshRenderer.SIMPLE_SIMPLEANIMATORTEXTURE = SimpleSkinnedMeshSprite3D.SIMPLE_SIMPLEANIMATORTEXTURE;
  30461. SimpleSkinnedMeshRenderer.SIMPLE_SIMPLEANIMATORTEXTURESIZE = SimpleSkinnedMeshSprite3D.SIMPLE_SIMPLEANIMATORTEXTURESIZE;
  30462. }
  30463. get meshFilter() {
  30464. return this._meshFilter;
  30465. }
  30466. get simpleSkinnedMeshRenderer() {
  30467. return this._render;
  30468. }
  30469. _parse(data, spriteMap) {
  30470. super._parse(data, spriteMap);
  30471. var render = this.simpleSkinnedMeshRenderer;
  30472. var lightmapIndex = data.lightmapIndex;
  30473. (lightmapIndex != null) && (render.lightmapIndex = lightmapIndex);
  30474. var lightmapScaleOffsetArray = data.lightmapScaleOffset;
  30475. (lightmapScaleOffsetArray) && (render.lightmapScaleOffset = new Vector4(lightmapScaleOffsetArray[0], lightmapScaleOffsetArray[1], lightmapScaleOffsetArray[2], lightmapScaleOffsetArray[3]));
  30476. (data.enableRender != undefined) && (render.enable = data.enableRender);
  30477. (data.receiveShadows != undefined) && (render.receiveShadow = data.receiveShadows);
  30478. (data.castShadow != undefined) && (render.castShadow = data.castShadow);
  30479. var meshPath;
  30480. meshPath = data.meshPath;
  30481. if (meshPath) {
  30482. var mesh = Laya.Loader.getRes(meshPath);
  30483. (mesh) && (this.meshFilter.sharedMesh = mesh);
  30484. }
  30485. var materials = data.materials;
  30486. if (materials) {
  30487. var sharedMaterials = render.sharedMaterials;
  30488. var materialCount = materials.length;
  30489. sharedMaterials.length = materialCount;
  30490. for (var i = 0; i < materialCount; i++) {
  30491. sharedMaterials[i] = Laya.Loader.getRes(materials[i].path);
  30492. }
  30493. render.sharedMaterials = sharedMaterials;
  30494. }
  30495. var boundBox = data.boundBox;
  30496. var min = boundBox.min;
  30497. var max = boundBox.max;
  30498. render.localBounds.setMin(new Vector3(min[0], min[1], min[2]));
  30499. render.localBounds.setMax(new Vector3(max[0], max[1], max[2]));
  30500. if (spriteMap) {
  30501. var rootBoneData = data.rootBone;
  30502. render.rootBone = spriteMap[rootBoneData];
  30503. var bonesData = data.bones;
  30504. var n;
  30505. for (i = 0, n = bonesData.length; i < n; i++)
  30506. render.bones.push(spriteMap[bonesData[i]]);
  30507. render._bonesNums = data.bonesNums ? data.bonesNums : render.bones.length;
  30508. }
  30509. else {
  30510. (data.rootBone) && (render._setRootBone(data.rootBone));
  30511. }
  30512. var animatorTexture = data.animatorTexture;
  30513. if (animatorTexture) {
  30514. var animatortexture = Laya.Loader.getRes(animatorTexture);
  30515. render.simpleAnimatorTexture = animatortexture;
  30516. }
  30517. }
  30518. _changeHierarchyAnimator(animator) {
  30519. super._changeHierarchyAnimator(animator);
  30520. this.simpleSkinnedMeshRenderer._setCacheAnimator(animator);
  30521. }
  30522. _cloneTo(destObject, srcRoot, dstRoot) {
  30523. var meshSprite3D = destObject;
  30524. meshSprite3D.meshFilter.sharedMesh = this.meshFilter.sharedMesh;
  30525. var meshRender = this._render;
  30526. var destMeshRender = meshSprite3D._render;
  30527. destMeshRender.enable = meshRender.enable;
  30528. destMeshRender.sharedMaterials = meshRender.sharedMaterials;
  30529. destMeshRender.castShadow = meshRender.castShadow;
  30530. var lightmapScaleOffset = meshRender.lightmapScaleOffset;
  30531. lightmapScaleOffset && (destMeshRender.lightmapScaleOffset = lightmapScaleOffset.clone());
  30532. destMeshRender.receiveShadow = meshRender.receiveShadow;
  30533. destMeshRender.sortingFudge = meshRender.sortingFudge;
  30534. destMeshRender._rootBone = meshRender._rootBone;
  30535. var bones = meshRender.bones;
  30536. var destBones = destMeshRender.bones;
  30537. var bonesCount = bones.length;
  30538. destBones.length = bonesCount;
  30539. var rootBone = meshRender.rootBone;
  30540. if (rootBone) {
  30541. var pathes = Utils3D._getHierarchyPath(srcRoot, rootBone, SimpleSkinnedMeshSprite3D._tempArray0);
  30542. if (pathes)
  30543. destMeshRender.rootBone = Utils3D._getNodeByHierarchyPath(dstRoot, pathes);
  30544. else
  30545. destMeshRender.rootBone = rootBone;
  30546. }
  30547. for (var i = 0; i < bones.length; i++) {
  30548. pathes = Utils3D._getHierarchyPath(srcRoot, bones[i], SimpleSkinnedMeshSprite3D._tempArray0);
  30549. if (pathes)
  30550. destBones[i] = Utils3D._getNodeByHierarchyPath(dstRoot, pathes);
  30551. else
  30552. destBones[i] = bones[i];
  30553. }
  30554. var lbb = meshRender.localBounds;
  30555. (lbb) && (lbb.cloneTo(destMeshRender.localBounds));
  30556. destMeshRender.simpleAnimatorOffset = meshRender.simpleAnimatorOffset;
  30557. destMeshRender.simpleAnimatorTexture = meshRender.simpleAnimatorTexture;
  30558. destMeshRender._bonesNums = meshRender._bonesNums;
  30559. super._cloneTo(destObject, srcRoot, dstRoot);
  30560. }
  30561. destroy(destroyChild = true) {
  30562. if (this.destroyed)
  30563. return;
  30564. super.destroy(destroyChild);
  30565. this._meshFilter.destroy();
  30566. }
  30567. _create() {
  30568. return new SimpleSkinnedMeshSprite3D();
  30569. }
  30570. }
  30571. SimpleSkinnedMeshSprite3D._tempArray0 = [];
  30572. SimpleSkinnedMeshSprite3D.SIMPLE_SIMPLEANIMATORTEXTURE = Shader3D.propertyNameToID("u_SimpleAnimatorTexture");
  30573. SimpleSkinnedMeshSprite3D.SIMPLE_SIMPLEANIMATORPARAMS = Shader3D.propertyNameToID("u_SimpleAnimatorParams");
  30574. SimpleSkinnedMeshSprite3D.SIMPLE_SIMPLEANIMATORTEXTURESIZE = Shader3D.propertyNameToID("u_SimpleAnimatorTextureSize");
  30575. class Scene3DUtils {
  30576. static _createSprite3DInstance(nodeData, spriteMap, outBatchSprites) {
  30577. var node;
  30578. switch (nodeData.type) {
  30579. case "Scene3D":
  30580. node = new Scene3D();
  30581. break;
  30582. case "Sprite3D":
  30583. node = new Sprite3D();
  30584. break;
  30585. case "MeshSprite3D":
  30586. node = new MeshSprite3D();
  30587. (outBatchSprites && nodeData.props.isStatic) && (outBatchSprites.push(node));
  30588. break;
  30589. case "SkinnedMeshSprite3D":
  30590. node = new SkinnedMeshSprite3D();
  30591. break;
  30592. case "SimpleSkinnedMeshSprite3D":
  30593. node = new SimpleSkinnedMeshSprite3D();
  30594. break;
  30595. case "ShuriKenParticle3D":
  30596. node = new ShuriKenParticle3D();
  30597. break;
  30598. case "Camera":
  30599. node = new Camera();
  30600. break;
  30601. case "DirectionLight":
  30602. node = new DirectionLight();
  30603. break;
  30604. case "PointLight":
  30605. node = new PointLight();
  30606. break;
  30607. case "SpotLight":
  30608. node = new SpotLight();
  30609. break;
  30610. case "TrailSprite3D":
  30611. node = new TrailSprite3D();
  30612. break;
  30613. case "ReflectionProbe":
  30614. node = new ReflectionProbe();
  30615. break;
  30616. default:
  30617. throw new Error("Utils3D:unidentified class type in (.lh) file.");
  30618. }
  30619. var childData = nodeData.child;
  30620. if (childData) {
  30621. for (var i = 0, n = childData.length; i < n; i++) {
  30622. var child = Scene3DUtils._createSprite3DInstance(childData[i], spriteMap, outBatchSprites);
  30623. node.addChild(child);
  30624. }
  30625. }
  30626. spriteMap[nodeData.instanceID] = node;
  30627. return node;
  30628. }
  30629. static _createComponentInstance(nodeData, spriteMap, interactMap) {
  30630. var node = spriteMap[nodeData.instanceID];
  30631. node._parse(nodeData.props, spriteMap);
  30632. var childData = nodeData.child;
  30633. if (childData) {
  30634. for (var i = 0, n = childData.length; i < n; i++)
  30635. Scene3DUtils._createComponentInstance(childData[i], spriteMap, interactMap);
  30636. }
  30637. var componentsData = nodeData.components;
  30638. if (componentsData) {
  30639. for (var j = 0, m = componentsData.length; j < m; j++) {
  30640. var data = componentsData[j];
  30641. var clas = Laya.ClassUtils.getRegClass(data.type);
  30642. if (clas) {
  30643. var component = node.addComponent(clas);
  30644. component._parse(data, interactMap);
  30645. }
  30646. else {
  30647. console.warn("Unkown component type.");
  30648. }
  30649. }
  30650. }
  30651. }
  30652. static _createNodeByJson02(nodeData, outBatchSprites) {
  30653. var spriteMap = {};
  30654. var interactMap = { component: [], data: [] };
  30655. var node = Scene3DUtils._createSprite3DInstance(nodeData, spriteMap, outBatchSprites);
  30656. Scene3DUtils._createComponentInstance(nodeData, spriteMap, interactMap);
  30657. Scene3DUtils._createInteractInstance(interactMap, spriteMap);
  30658. return node;
  30659. }
  30660. static _createInteractInstance(interatMap, spriteMap) {
  30661. var components = interatMap.component;
  30662. var data = interatMap.data;
  30663. for (var i = 0, n = components.length; i < n; i++) {
  30664. components[i]._parseInteractive(data[i], spriteMap);
  30665. }
  30666. }
  30667. static _parse(data, propertyParams = null, constructParams = null) {
  30668. var json = data.data;
  30669. var outBatchSprits = [];
  30670. var sprite;
  30671. switch (data.version) {
  30672. case "LAYAHIERARCHY:02":
  30673. sprite = Scene3DUtils._createNodeByJson02(json, outBatchSprits);
  30674. break;
  30675. default:
  30676. sprite = Scene3DUtils._createNodeByJson(json, outBatchSprits);
  30677. }
  30678. StaticBatchManager.combine(sprite, outBatchSprits);
  30679. return sprite;
  30680. }
  30681. static _parseScene(data, propertyParams = null, constructParams = null) {
  30682. var json = data.data;
  30683. var outBatchSprits = [];
  30684. var scene;
  30685. switch (data.version) {
  30686. case "LAYASCENE3D:02":
  30687. scene = Scene3DUtils._createNodeByJson02(json, outBatchSprits);
  30688. break;
  30689. default:
  30690. scene = Scene3DUtils._createNodeByJson(json, outBatchSprits);
  30691. }
  30692. StaticBatchManager.combine(null, outBatchSprits);
  30693. return scene;
  30694. }
  30695. static _createNodeByJson(nodeData, outBatchSprites) {
  30696. var node;
  30697. switch (nodeData.type) {
  30698. case "Scene3D":
  30699. node = new Scene3D();
  30700. break;
  30701. case "Sprite3D":
  30702. node = new Sprite3D();
  30703. break;
  30704. case "MeshSprite3D":
  30705. node = new MeshSprite3D();
  30706. (outBatchSprites && nodeData.props.isStatic) && (outBatchSprites.push(node));
  30707. break;
  30708. case "SkinnedMeshSprite3D":
  30709. node = new SkinnedMeshSprite3D();
  30710. break;
  30711. case "ShuriKenParticle3D":
  30712. node = new ShuriKenParticle3D();
  30713. break;
  30714. case "Camera":
  30715. node = new Camera();
  30716. break;
  30717. case "DirectionLight":
  30718. node = new DirectionLight();
  30719. break;
  30720. case "PointLight":
  30721. node = new PointLight();
  30722. break;
  30723. case "SpotLight":
  30724. node = new SpotLight();
  30725. break;
  30726. case "TrailSprite3D":
  30727. node = new TrailSprite3D();
  30728. break;
  30729. default:
  30730. throw new Error("Utils3D:unidentified class type in (.lh) file.");
  30731. }
  30732. var childData = nodeData.child;
  30733. if (childData) {
  30734. for (var i = 0, n = childData.length; i < n; i++) {
  30735. var child = Scene3DUtils._createNodeByJson(childData[i], outBatchSprites);
  30736. node.addChild(child);
  30737. }
  30738. }
  30739. var componentsData = nodeData.components;
  30740. if (componentsData) {
  30741. for (var j = 0, m = componentsData.length; j < m; j++) {
  30742. var data = componentsData[j];
  30743. var clas = Laya.ClassUtils.getRegClass(data.type);
  30744. if (clas) {
  30745. var component = node.addComponent(clas);
  30746. component._parse(data);
  30747. }
  30748. else {
  30749. console.warn("Unkown component type.");
  30750. }
  30751. }
  30752. }
  30753. node._parse(nodeData.props, null);
  30754. return node;
  30755. }
  30756. }
  30757. class LoadModelV04 {
  30758. static parse(readData, version, mesh, subMeshes) {
  30759. LoadModelV04._mesh = mesh;
  30760. LoadModelV04._subMeshes = subMeshes;
  30761. LoadModelV04._version = version;
  30762. LoadModelV04._readData = readData;
  30763. LoadModelV04.READ_DATA();
  30764. LoadModelV04.READ_BLOCK();
  30765. LoadModelV04.READ_STRINGS();
  30766. for (var i = 0, n = LoadModelV04._BLOCK.count; i < n; i++) {
  30767. LoadModelV04._readData.pos = LoadModelV04._BLOCK.blockStarts[i];
  30768. var index = LoadModelV04._readData.getUint16();
  30769. var blockName = LoadModelV04._strings[index];
  30770. var fn = LoadModelV04["READ_" + blockName];
  30771. if (fn == null)
  30772. throw new Error("model file err,no this function:" + index + " " + blockName);
  30773. else
  30774. fn.call(null);
  30775. }
  30776. LoadModelV04._strings.length = 0;
  30777. LoadModelV04._readData = null;
  30778. LoadModelV04._version = null;
  30779. LoadModelV04._mesh = null;
  30780. LoadModelV04._subMeshes = null;
  30781. }
  30782. static _readString() {
  30783. return LoadModelV04._strings[LoadModelV04._readData.getUint16()];
  30784. }
  30785. static READ_DATA() {
  30786. LoadModelV04._DATA.offset = LoadModelV04._readData.getUint32();
  30787. LoadModelV04._DATA.size = LoadModelV04._readData.getUint32();
  30788. }
  30789. static READ_BLOCK() {
  30790. var count = LoadModelV04._BLOCK.count = LoadModelV04._readData.getUint16();
  30791. var blockStarts = LoadModelV04._BLOCK.blockStarts = [];
  30792. var blockLengths = LoadModelV04._BLOCK.blockLengths = [];
  30793. for (var i = 0; i < count; i++) {
  30794. blockStarts.push(LoadModelV04._readData.getUint32());
  30795. blockLengths.push(LoadModelV04._readData.getUint32());
  30796. }
  30797. }
  30798. static READ_STRINGS() {
  30799. var offset = LoadModelV04._readData.getUint32();
  30800. var count = LoadModelV04._readData.getUint16();
  30801. var prePos = LoadModelV04._readData.pos;
  30802. LoadModelV04._readData.pos = offset + LoadModelV04._DATA.offset;
  30803. for (var i = 0; i < count; i++)
  30804. LoadModelV04._strings[i] = LoadModelV04._readData.readUTFString();
  30805. LoadModelV04._readData.pos = prePos;
  30806. }
  30807. static READ_MESH() {
  30808. var gl = Laya.LayaGL.instance;
  30809. var name = LoadModelV04._readString();
  30810. var arrayBuffer = LoadModelV04._readData.__getBuffer();
  30811. var i;
  30812. var memorySize = 0;
  30813. var vertexBufferCount = LoadModelV04._readData.getInt16();
  30814. var offset = LoadModelV04._DATA.offset;
  30815. for (i = 0; i < vertexBufferCount; i++) {
  30816. var vbStart = offset + LoadModelV04._readData.getUint32();
  30817. var vbLength = LoadModelV04._readData.getUint32();
  30818. var vbArrayBuffer = arrayBuffer.slice(vbStart, vbStart + vbLength);
  30819. var vbDatas = new Float32Array(vbArrayBuffer);
  30820. var bufferAttribute = LoadModelV04._readString();
  30821. var vertexDeclaration;
  30822. switch (LoadModelV04._version) {
  30823. case "LAYAMODEL:0301":
  30824. case "LAYAMODEL:0400":
  30825. vertexDeclaration = VertexMesh.getVertexDeclaration(bufferAttribute);
  30826. break;
  30827. case "LAYAMODEL:0401":
  30828. vertexDeclaration = VertexMesh.getVertexDeclaration(bufferAttribute, false);
  30829. break;
  30830. default:
  30831. throw new Error("LoadModelV03: unknown version.");
  30832. }
  30833. if (!vertexDeclaration)
  30834. throw new Error("LoadModelV03: unknown vertexDeclaration.");
  30835. var vertexBuffer = new VertexBuffer3D(vbDatas.length * 4, gl.STATIC_DRAW, true);
  30836. vertexBuffer.vertexDeclaration = vertexDeclaration;
  30837. vertexBuffer.setData(vbDatas.buffer);
  30838. LoadModelV04._mesh._vertexBuffer = vertexBuffer;
  30839. LoadModelV04._mesh._vertexCount += vertexBuffer._byteLength / vertexDeclaration.vertexStride;
  30840. memorySize += vbDatas.length * 4;
  30841. }
  30842. var ibStart = offset + LoadModelV04._readData.getUint32();
  30843. var ibLength = LoadModelV04._readData.getUint32();
  30844. var ibDatas = new Uint16Array(arrayBuffer.slice(ibStart, ibStart + ibLength));
  30845. var indexBuffer = new IndexBuffer3D(exports.IndexFormat.UInt16, ibLength / 2, gl.STATIC_DRAW, true);
  30846. indexBuffer.setData(ibDatas);
  30847. LoadModelV04._mesh._indexBuffer = indexBuffer;
  30848. memorySize += indexBuffer.indexCount * 2;
  30849. LoadModelV04._mesh._setBuffer(LoadModelV04._mesh._vertexBuffer, indexBuffer);
  30850. LoadModelV04._mesh._setCPUMemory(memorySize);
  30851. LoadModelV04._mesh._setGPUMemory(memorySize);
  30852. var boneNames = LoadModelV04._mesh._boneNames = [];
  30853. var boneCount = LoadModelV04._readData.getUint16();
  30854. boneNames.length = boneCount;
  30855. for (i = 0; i < boneCount; i++)
  30856. boneNames[i] = LoadModelV04._strings[LoadModelV04._readData.getUint16()];
  30857. LoadModelV04._readData.pos += 8;
  30858. var bindPoseDataStart = LoadModelV04._readData.getUint32();
  30859. var bindPoseDataLength = LoadModelV04._readData.getUint32();
  30860. var bindPoseDatas = new Float32Array(arrayBuffer.slice(offset + bindPoseDataStart, offset + bindPoseDataStart + bindPoseDataLength));
  30861. var bindPoseFloatCount = bindPoseDatas.length;
  30862. var bindPoseBuffer = LoadModelV04._mesh._inverseBindPosesBuffer = new ArrayBuffer(bindPoseFloatCount * 4);
  30863. LoadModelV04._mesh._inverseBindPoses = [];
  30864. if (bindPoseFloatCount != 0)
  30865. LoadModelV04._mesh._instanceBufferStateType = Mesh.MESH_INSTANCEBUFFER_TYPE_SIMPLEANIMATOR;
  30866. else
  30867. LoadModelV04._mesh._instanceBufferStateType = Mesh.MESH_INSTANCEBUFFER_TYPE_NORMAL;
  30868. LoadModelV04._mesh._setInstanceBuffer(LoadModelV04._mesh._instanceBufferStateType);
  30869. for (i = 0; i < bindPoseFloatCount; i += 16) {
  30870. var inverseGlobalBindPose = new Matrix4x4(bindPoseDatas[i + 0], bindPoseDatas[i + 1], bindPoseDatas[i + 2], bindPoseDatas[i + 3], bindPoseDatas[i + 4], bindPoseDatas[i + 5], bindPoseDatas[i + 6], bindPoseDatas[i + 7], bindPoseDatas[i + 8], bindPoseDatas[i + 9], bindPoseDatas[i + 10], bindPoseDatas[i + 11], bindPoseDatas[i + 12], bindPoseDatas[i + 13], bindPoseDatas[i + 14], bindPoseDatas[i + 15], new Float32Array(bindPoseBuffer, i * 4, 16));
  30871. LoadModelV04._mesh._inverseBindPoses[i / 16] = inverseGlobalBindPose;
  30872. }
  30873. return true;
  30874. }
  30875. static READ_SUBMESH() {
  30876. var arrayBuffer = LoadModelV04._readData.__getBuffer();
  30877. var subMesh = new SubMesh(LoadModelV04._mesh);
  30878. LoadModelV04._readData.getInt16();
  30879. LoadModelV04._readData.getUint32();
  30880. LoadModelV04._readData.getUint32();
  30881. var ibStart = LoadModelV04._readData.getUint32();
  30882. var ibCount = LoadModelV04._readData.getUint32();
  30883. var indexBuffer = LoadModelV04._mesh._indexBuffer;
  30884. subMesh._indexBuffer = indexBuffer;
  30885. subMesh._setIndexRange(ibStart, ibCount);
  30886. var vertexBuffer = LoadModelV04._mesh._vertexBuffer;
  30887. subMesh._vertexBuffer = vertexBuffer;
  30888. var offset = LoadModelV04._DATA.offset;
  30889. var subIndexBufferStart = subMesh._subIndexBufferStart;
  30890. var subIndexBufferCount = subMesh._subIndexBufferCount;
  30891. var boneIndicesList = subMesh._boneIndicesList;
  30892. var drawCount = LoadModelV04._readData.getUint16();
  30893. subIndexBufferStart.length = drawCount;
  30894. subIndexBufferCount.length = drawCount;
  30895. boneIndicesList.length = drawCount;
  30896. var skinnedCache = LoadModelV04._mesh._skinnedMatrixCaches;
  30897. var subMeshIndex = LoadModelV04._subMeshes.length;
  30898. skinnedCache.length = LoadModelV04._mesh._inverseBindPoses.length;
  30899. for (var i = 0; i < drawCount; i++) {
  30900. subIndexBufferStart[i] = LoadModelV04._readData.getUint32();
  30901. subIndexBufferCount[i] = LoadModelV04._readData.getUint32();
  30902. var boneDicofs = LoadModelV04._readData.getUint32();
  30903. var boneDicCount = LoadModelV04._readData.getUint32();
  30904. var boneIndices = boneIndicesList[i] = new Uint16Array(arrayBuffer.slice(offset + boneDicofs, offset + boneDicofs + boneDicCount));
  30905. var boneIndexCount = boneIndices.length;
  30906. for (var j = 0; j < boneIndexCount; j++) {
  30907. var index = boneIndices[j];
  30908. skinnedCache[index] || (skinnedCache[index] = new skinnedMatrixCache(subMeshIndex, i, j));
  30909. }
  30910. }
  30911. LoadModelV04._subMeshes.push(subMesh);
  30912. return true;
  30913. }
  30914. }
  30915. LoadModelV04._BLOCK = { count: 0 };
  30916. LoadModelV04._DATA = { offset: 0, size: 0 };
  30917. LoadModelV04._strings = [];
  30918. class LoadModelV05 {
  30919. static parse(readData, version, mesh, subMeshes) {
  30920. LoadModelV05._mesh = mesh;
  30921. LoadModelV05._subMeshes = subMeshes;
  30922. LoadModelV05._version = version;
  30923. LoadModelV05._readData = readData;
  30924. LoadModelV05.READ_DATA();
  30925. LoadModelV05.READ_BLOCK();
  30926. LoadModelV05.READ_STRINGS();
  30927. for (var i = 0, n = LoadModelV05._BLOCK.count; i < n; i++) {
  30928. LoadModelV05._readData.pos = LoadModelV05._BLOCK.blockStarts[i];
  30929. var index = LoadModelV05._readData.getUint16();
  30930. var blockName = LoadModelV05._strings[index];
  30931. var fn = LoadModelV05["READ_" + blockName];
  30932. if (fn == null)
  30933. throw new Error("model file err,no this function:" + index + " " + blockName);
  30934. else
  30935. fn.call(null);
  30936. }
  30937. LoadModelV05._strings.length = 0;
  30938. LoadModelV05._readData = null;
  30939. LoadModelV05._version = null;
  30940. LoadModelV05._mesh = null;
  30941. LoadModelV05._subMeshes = null;
  30942. }
  30943. static _readString() {
  30944. return LoadModelV05._strings[LoadModelV05._readData.getUint16()];
  30945. }
  30946. static READ_DATA() {
  30947. LoadModelV05._DATA.offset = LoadModelV05._readData.getUint32();
  30948. LoadModelV05._DATA.size = LoadModelV05._readData.getUint32();
  30949. }
  30950. static READ_BLOCK() {
  30951. var count = LoadModelV05._BLOCK.count = LoadModelV05._readData.getUint16();
  30952. var blockStarts = LoadModelV05._BLOCK.blockStarts = [];
  30953. var blockLengths = LoadModelV05._BLOCK.blockLengths = [];
  30954. for (var i = 0; i < count; i++) {
  30955. blockStarts.push(LoadModelV05._readData.getUint32());
  30956. blockLengths.push(LoadModelV05._readData.getUint32());
  30957. }
  30958. }
  30959. static READ_STRINGS() {
  30960. var offset = LoadModelV05._readData.getUint32();
  30961. var count = LoadModelV05._readData.getUint16();
  30962. var prePos = LoadModelV05._readData.pos;
  30963. LoadModelV05._readData.pos = offset + LoadModelV05._DATA.offset;
  30964. for (var i = 0; i < count; i++)
  30965. LoadModelV05._strings[i] = LoadModelV05._readData.readUTFString();
  30966. LoadModelV05._readData.pos = prePos;
  30967. }
  30968. static READ_MESH() {
  30969. var gl = Laya.LayaGL.instance;
  30970. var i;
  30971. var memorySize = 0;
  30972. var name = LoadModelV05._readString();
  30973. var reader = LoadModelV05._readData;
  30974. var arrayBuffer = reader.__getBuffer();
  30975. var vertexBufferCount = reader.getInt16();
  30976. var offset = LoadModelV05._DATA.offset;
  30977. for (i = 0; i < vertexBufferCount; i++) {
  30978. var vbStart = offset + reader.getUint32();
  30979. var vertexCount = reader.getUint32();
  30980. var vertexFlag = LoadModelV05._readString();
  30981. var vertexDeclaration = VertexMesh.getVertexDeclaration(vertexFlag, false);
  30982. var vertexStride = vertexDeclaration.vertexStride;
  30983. var vertexData;
  30984. var floatData;
  30985. var uint8Data;
  30986. var subVertexFlags = vertexFlag.split(",");
  30987. var subVertexCount = subVertexFlags.length;
  30988. var mesh = LoadModelV05._mesh;
  30989. switch (LoadModelV05._version) {
  30990. case "LAYAMODEL:05":
  30991. case "LAYAMODEL:0501":
  30992. vertexData = arrayBuffer.slice(vbStart, vbStart + vertexCount * vertexStride);
  30993. floatData = new Float32Array(vertexData);
  30994. uint8Data = new Uint8Array(vertexData);
  30995. break;
  30996. case "LAYAMODEL:COMPRESSION_05":
  30997. case "LAYAMODEL:COMPRESSION_0501":
  30998. vertexData = new ArrayBuffer(vertexStride * vertexCount);
  30999. floatData = new Float32Array(vertexData);
  31000. uint8Data = new Uint8Array(vertexData);
  31001. var lastPosition = reader.pos;
  31002. reader.pos = vbStart;
  31003. for (var j = 0; j < vertexCount; j++) {
  31004. var subOffset;
  31005. var verOffset = j * vertexStride;
  31006. for (var k = 0; k < subVertexCount; k++) {
  31007. switch (subVertexFlags[k]) {
  31008. case "POSITION":
  31009. subOffset = verOffset / 4;
  31010. floatData[subOffset] = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  31011. floatData[subOffset + 1] = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  31012. floatData[subOffset + 2] = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  31013. verOffset += 12;
  31014. break;
  31015. case "NORMAL":
  31016. subOffset = verOffset / 4;
  31017. floatData[subOffset] = reader.getUint8() / 127.5 - 1;
  31018. floatData[subOffset + 1] = reader.getUint8() / 127.5 - 1;
  31019. floatData[subOffset + 2] = reader.getUint8() / 127.5 - 1;
  31020. verOffset += 12;
  31021. break;
  31022. case "COLOR":
  31023. subOffset = verOffset / 4;
  31024. floatData[subOffset] = reader.getUint8() / 255;
  31025. floatData[subOffset + 1] = reader.getUint8() / 255;
  31026. floatData[subOffset + 2] = reader.getUint8() / 255;
  31027. floatData[subOffset + 3] = reader.getUint8() / 255;
  31028. verOffset += 16;
  31029. break;
  31030. case "UV":
  31031. subOffset = verOffset / 4;
  31032. floatData[subOffset] = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  31033. floatData[subOffset + 1] = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  31034. verOffset += 8;
  31035. break;
  31036. case "UV1":
  31037. subOffset = verOffset / 4;
  31038. floatData[subOffset] = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  31039. floatData[subOffset + 1] = Laya.HalfFloatUtils.convertToNumber(reader.getUint16());
  31040. verOffset += 8;
  31041. break;
  31042. case "BLENDWEIGHT":
  31043. subOffset = verOffset / 4;
  31044. floatData[subOffset] = reader.getUint8() / 255;
  31045. floatData[subOffset + 1] = reader.getUint8() / 255;
  31046. floatData[subOffset + 2] = reader.getUint8() / 255;
  31047. floatData[subOffset + 3] = reader.getUint8() / 255;
  31048. verOffset += 16;
  31049. break;
  31050. case "BLENDINDICES":
  31051. uint8Data[verOffset] = reader.getUint8();
  31052. uint8Data[verOffset + 1] = reader.getUint8();
  31053. uint8Data[verOffset + 2] = reader.getUint8();
  31054. uint8Data[verOffset + 3] = reader.getUint8();
  31055. verOffset += 4;
  31056. break;
  31057. case "TANGENT":
  31058. subOffset = verOffset / 4;
  31059. floatData[subOffset] = reader.getUint8() / 127.5 - 1;
  31060. floatData[subOffset + 1] = reader.getUint8() / 127.5 - 1;
  31061. floatData[subOffset + 2] = reader.getUint8() / 127.5 - 1;
  31062. floatData[subOffset + 3] = reader.getUint8() / 127.5 - 1;
  31063. verOffset += 16;
  31064. break;
  31065. }
  31066. }
  31067. }
  31068. reader.pos = lastPosition;
  31069. break;
  31070. }
  31071. var vertexBuffer = new VertexBuffer3D(vertexData.byteLength, gl.STATIC_DRAW, true);
  31072. vertexBuffer.vertexDeclaration = vertexDeclaration;
  31073. vertexBuffer.setData(vertexData);
  31074. var vertexCount = vertexBuffer._byteLength / vertexDeclaration.vertexStride;
  31075. if (vertexCount > 65535)
  31076. mesh._indexFormat = exports.IndexFormat.UInt32;
  31077. else
  31078. mesh._indexFormat = exports.IndexFormat.UInt16;
  31079. mesh._vertexBuffer = vertexBuffer;
  31080. mesh._vertexCount += vertexCount;
  31081. memorySize += floatData.length * 4;
  31082. }
  31083. var ibStart = offset + reader.getUint32();
  31084. var ibLength = reader.getUint32();
  31085. var ibDatas;
  31086. if (mesh.indexFormat == exports.IndexFormat.UInt32)
  31087. ibDatas = new Uint32Array(arrayBuffer.slice(ibStart, ibStart + ibLength));
  31088. else
  31089. ibDatas = new Uint16Array(arrayBuffer.slice(ibStart, ibStart + ibLength));
  31090. var indexBuffer = new IndexBuffer3D(mesh.indexFormat, ibDatas.length, gl.STATIC_DRAW, true);
  31091. indexBuffer.setData(ibDatas);
  31092. mesh._indexBuffer = indexBuffer;
  31093. mesh._setBuffer(mesh._vertexBuffer, indexBuffer);
  31094. memorySize += indexBuffer.indexCount * 2;
  31095. mesh._setCPUMemory(memorySize);
  31096. mesh._setGPUMemory(memorySize);
  31097. if (LoadModelV05._version == "LAYAMODEL:0501" || LoadModelV05._version == "LAYAMODEL:COMPRESSION_0501") {
  31098. var bounds = mesh.bounds;
  31099. var min = bounds.getMin();
  31100. var max = bounds.getMax();
  31101. min.setValue(reader.getFloat32(), reader.getFloat32(), reader.getFloat32());
  31102. max.setValue(reader.getFloat32(), reader.getFloat32(), reader.getFloat32());
  31103. bounds.setMin(min);
  31104. bounds.setMax(max);
  31105. mesh.bounds = bounds;
  31106. }
  31107. var boneNames = mesh._boneNames = [];
  31108. var boneCount = reader.getUint16();
  31109. boneNames.length = boneCount;
  31110. for (i = 0; i < boneCount; i++)
  31111. boneNames[i] = LoadModelV05._strings[reader.getUint16()];
  31112. var bindPoseDataStart = reader.getUint32();
  31113. var bindPoseDataLength = reader.getUint32();
  31114. var bindPoseDatas = new Float32Array(arrayBuffer.slice(offset + bindPoseDataStart, offset + bindPoseDataStart + bindPoseDataLength));
  31115. var bindPoseFloatCount = bindPoseDatas.length;
  31116. var bindPoseBuffer = mesh._inverseBindPosesBuffer = new ArrayBuffer(bindPoseFloatCount * 4);
  31117. mesh._inverseBindPoses = [];
  31118. if (bindPoseFloatCount != 0)
  31119. mesh._instanceBufferStateType = Mesh.MESH_INSTANCEBUFFER_TYPE_SIMPLEANIMATOR;
  31120. else
  31121. mesh._instanceBufferStateType = Mesh.MESH_INSTANCEBUFFER_TYPE_NORMAL;
  31122. mesh._setInstanceBuffer(mesh._instanceBufferStateType);
  31123. for (i = 0; i < bindPoseFloatCount; i += 16) {
  31124. var inverseGlobalBindPose = new Matrix4x4(bindPoseDatas[i + 0], bindPoseDatas[i + 1], bindPoseDatas[i + 2], bindPoseDatas[i + 3], bindPoseDatas[i + 4], bindPoseDatas[i + 5], bindPoseDatas[i + 6], bindPoseDatas[i + 7], bindPoseDatas[i + 8], bindPoseDatas[i + 9], bindPoseDatas[i + 10], bindPoseDatas[i + 11], bindPoseDatas[i + 12], bindPoseDatas[i + 13], bindPoseDatas[i + 14], bindPoseDatas[i + 15], new Float32Array(bindPoseBuffer, i * 4, 16));
  31125. mesh._inverseBindPoses[i / 16] = inverseGlobalBindPose;
  31126. }
  31127. return true;
  31128. }
  31129. static READ_SUBMESH() {
  31130. var reader = LoadModelV05._readData;
  31131. var arrayBuffer = reader.__getBuffer();
  31132. var subMesh = new SubMesh(LoadModelV05._mesh);
  31133. reader.getInt16();
  31134. var ibStart = reader.getUint32();
  31135. var ibCount = reader.getUint32();
  31136. var indexBuffer = LoadModelV05._mesh._indexBuffer;
  31137. subMesh._indexBuffer = indexBuffer;
  31138. subMesh._setIndexRange(ibStart, ibCount);
  31139. var vertexBuffer = LoadModelV05._mesh._vertexBuffer;
  31140. subMesh._vertexBuffer = vertexBuffer;
  31141. var offset = LoadModelV05._DATA.offset;
  31142. var subIndexBufferStart = subMesh._subIndexBufferStart;
  31143. var subIndexBufferCount = subMesh._subIndexBufferCount;
  31144. var boneIndicesList = subMesh._boneIndicesList;
  31145. var drawCount = reader.getUint16();
  31146. subIndexBufferStart.length = drawCount;
  31147. subIndexBufferCount.length = drawCount;
  31148. boneIndicesList.length = drawCount;
  31149. var skinnedCache = LoadModelV05._mesh._skinnedMatrixCaches;
  31150. var subMeshIndex = LoadModelV05._subMeshes.length;
  31151. skinnedCache.length = LoadModelV05._mesh._inverseBindPoses.length;
  31152. for (var i = 0; i < drawCount; i++) {
  31153. subIndexBufferStart[i] = reader.getUint32();
  31154. subIndexBufferCount[i] = reader.getUint32();
  31155. var boneDicofs = reader.getUint32();
  31156. var boneDicCount = reader.getUint32();
  31157. var boneIndices = boneIndicesList[i] = new Uint16Array(arrayBuffer.slice(offset + boneDicofs, offset + boneDicofs + boneDicCount));
  31158. for (var j = 0, m = boneIndices.length; j < m; j++) {
  31159. var index = boneIndices[j];
  31160. skinnedCache[index] || (skinnedCache[index] = new skinnedMatrixCache(subMeshIndex, i, j));
  31161. }
  31162. }
  31163. LoadModelV05._subMeshes.push(subMesh);
  31164. return true;
  31165. }
  31166. }
  31167. LoadModelV05._BLOCK = { count: 0 };
  31168. LoadModelV05._DATA = { offset: 0, size: 0 };
  31169. LoadModelV05._strings = [];
  31170. class MeshReader {
  31171. static _parse(data, propertyParams = null, constructParams = null) {
  31172. var mesh = new Mesh();
  31173. MeshReader.read(data, mesh, mesh._subMeshes);
  31174. return mesh;
  31175. }
  31176. static read(data, mesh, subMeshes) {
  31177. var readData = new Laya.Byte(data);
  31178. readData.pos = 0;
  31179. var version = readData.readUTFString();
  31180. switch (version) {
  31181. case "LAYAMODEL:0301":
  31182. case "LAYAMODEL:0400":
  31183. case "LAYAMODEL:0401":
  31184. LoadModelV04.parse(readData, version, mesh, subMeshes);
  31185. break;
  31186. case "LAYAMODEL:05":
  31187. case "LAYAMODEL:COMPRESSION_05":
  31188. case "LAYAMODEL:0501":
  31189. case "LAYAMODEL:COMPRESSION_0501":
  31190. LoadModelV05.parse(readData, version, mesh, subMeshes);
  31191. break;
  31192. default:
  31193. throw new Error("MeshReader: unknown mesh version.");
  31194. }
  31195. mesh._setSubMeshes(subMeshes);
  31196. if (version != "LAYAMODEL:0501" && version != "LAYAMODEL:COMPRESSION_0501")
  31197. mesh.calculateBounds();
  31198. }
  31199. }
  31200. var SkyPanoramicFS = "#if defined(GL_FRAGMENT_PRECISION_HIGH)// 原来的写法会被我们自己的解析流程处理,而我们的解析是不认内置宏的,导致被删掉,所以改成 if defined 了\r\n\tprecision highp float;\r\n#else\r\n\tprecision mediump float;\r\n#endif\r\n\r\n#define PI 3.14159265359\r\n#include \"Lighting.glsl\";\r\n\r\nuniform sampler2D u_Texture;\r\nuniform vec4 u_TextureHDRParams;\r\nuniform vec4 u_TintColor;\r\n\r\nvarying vec3 v_Texcoord;\r\nvarying vec2 v_Image180ScaleAndCutoff;\r\nvarying vec4 v_Layout3DScaleAndOffset;\r\n\r\nvec2 ToRadialCoords(vec3 coords)\r\n{\r\n\tvec3 normalizedCoords = normalize(coords);\r\n\tfloat latitude = acos(normalizedCoords.y);\r\n\tfloat longitude = atan(normalizedCoords.z,normalizedCoords.x);\r\n\tvec2 sphereCoords = vec2(longitude, latitude) * vec2(0.5/PI, 1.0/PI);\r\n\treturn vec2(0.5,1.0) - sphereCoords;\r\n}\r\n\r\n\r\nvoid main()\r\n{\t\r\n\tvec2 tc = ToRadialCoords(v_Texcoord);\r\n\tif (tc.x > v_Image180ScaleAndCutoff.y)\r\n\t\tgl_FragColor=vec4(0,0,0,1);\r\n\ttc.x = mod(tc.x*v_Image180ScaleAndCutoff.x, 1.0);\r\n\ttc = (tc + v_Layout3DScaleAndOffset.xy) * v_Layout3DScaleAndOffset.zw;\r\n\r\n\tmediump vec4 tex = texture2D (u_Texture, tc);\r\n\tmediump vec3 c = decodeHDR (tex, u_TextureHDRParams.x);\r\n\tc = c * u_TintColor.rgb * 2.0;//Gamma Space is 2.0,linear space is 4.59479380\r\n\tgl_FragColor=vec4(c, 1.0);\r\n}\r\n\r\n";
  31201. var SkyPanoramicVS = "#include \"Lighting.glsl\";\r\n\r\n#define PI 3.14159265359\r\n\r\nattribute vec4 a_Position;\r\n\r\nuniform mat4 u_ViewProjection;\r\nuniform float u_Rotation;\r\n\r\nvarying vec3 v_Texcoord;\r\nvarying vec2 v_Image180ScaleAndCutoff;\r\nvarying vec4 v_Layout3DScaleAndOffset;\r\n\r\nvec4 rotateAroundYInDegrees (vec4 vertex, float degrees)\r\n{\r\n\tfloat angle = degrees * PI / 180.0;\r\n\tfloat sina=sin(angle);\r\n\tfloat cosa=cos(angle);\r\n\tmat2 m = mat2(cosa, -sina, sina, cosa);\r\n\treturn vec4(m*vertex.xz, vertex.yw).xzyw;\r\n}\r\n\r\n\t\t\r\nvoid main()\r\n{\r\n\tvec4 position = rotateAroundYInDegrees(a_Position, u_Rotation);\r\n\tgl_Position = u_ViewProjection*position;\r\n\r\n\tv_Texcoord=vec3(-a_Position.x,-a_Position.y,a_Position.z);// NOTE: -a_Position.x convert coords system\r\n\r\n\t// Calculate constant horizontal scale and cutoff for 180 (vs 360) image type\r\n\tv_Image180ScaleAndCutoff = vec2(1.0, 1.0);// 360 degree mode\r\n\r\n\t// Calculate constant scale and offset for 3D layouts\r\n\tv_Layout3DScaleAndOffset = vec4(0,0,1,1);\r\n}\r\n";
  31202. class SkyPanoramicMaterial extends Material {
  31203. constructor() {
  31204. super();
  31205. this._exposure = 1.0;
  31206. this._textureDecodeFormat = Laya.TextureDecodeFormat.Normal;
  31207. this._textureHDRParams = new Vector4(1.0, 0.0, 0.0, 1.0);
  31208. this.setShaderName("SkyPanoramic");
  31209. var shaderValues = this._shaderValues;
  31210. shaderValues.setVector(SkyPanoramicMaterial.TINTCOLOR, new Vector4(0.5, 0.5, 0.5, 0.5));
  31211. shaderValues.setNumber(SkyPanoramicMaterial.ROTATION, 0.0);
  31212. shaderValues.setVector(SkyPanoramicMaterial.TEXTURE_HDR_PARAMS, this._textureHDRParams);
  31213. }
  31214. static __init__() {
  31215. var attributeMap = {
  31216. 'a_Position': VertexMesh.MESH_POSITION0
  31217. };
  31218. var uniformMap = {
  31219. 'u_TintColor': Shader3D.PERIOD_MATERIAL,
  31220. 'u_TextureHDRParams': Shader3D.PERIOD_MATERIAL,
  31221. 'u_Rotation': Shader3D.PERIOD_MATERIAL,
  31222. 'u_Texture': Shader3D.PERIOD_MATERIAL,
  31223. 'u_ViewProjection': Shader3D.PERIOD_CAMERA
  31224. };
  31225. var shader = Shader3D.add("SkyPanoramic");
  31226. var subShader = new SubShader(attributeMap, uniformMap);
  31227. shader.addSubShader(subShader);
  31228. subShader.addShaderPass(SkyPanoramicVS, SkyPanoramicFS);
  31229. }
  31230. get tintColor() {
  31231. return this._shaderValues.getVector(SkyPanoramicMaterial.TINTCOLOR);
  31232. }
  31233. set tintColor(value) {
  31234. this._shaderValues.setVector(SkyPanoramicMaterial.TINTCOLOR, value);
  31235. }
  31236. get exposure() {
  31237. return this._exposure;
  31238. }
  31239. set exposure(value) {
  31240. if (this._exposure !== value) {
  31241. this._exposure = value;
  31242. if (this._textureDecodeFormat == Laya.TextureDecodeFormat.RGBM)
  31243. this._textureHDRParams.x = value * Laya.BaseTexture._rgbmRange;
  31244. else
  31245. this._textureHDRParams.x = value;
  31246. }
  31247. }
  31248. get rotation() {
  31249. return this._shaderValues.getNumber(SkyPanoramicMaterial.ROTATION);
  31250. }
  31251. set rotation(value) {
  31252. this._shaderValues.setNumber(SkyPanoramicMaterial.ROTATION, value);
  31253. }
  31254. get panoramicTexture() {
  31255. return this._shaderValues.getTexture(SkyPanoramicMaterial.TEXTURE);
  31256. }
  31257. set panoramicTexture(value) {
  31258. this._shaderValues.setTexture(SkyPanoramicMaterial.TEXTURE, value);
  31259. }
  31260. get panoramicTextureDecodeFormat() {
  31261. return this._textureDecodeFormat;
  31262. }
  31263. set panoramicTextureDecodeFormat(value) {
  31264. if (this._textureDecodeFormat !== value) {
  31265. this._textureDecodeFormat = value;
  31266. if (value == Laya.TextureDecodeFormat.RGBM)
  31267. this._textureHDRParams.x = this._exposure * Laya.BaseTexture._rgbmRange;
  31268. else
  31269. this._textureHDRParams.x = this._exposure;
  31270. }
  31271. }
  31272. }
  31273. SkyPanoramicMaterial.TINTCOLOR = Shader3D.propertyNameToID("u_TintColor");
  31274. SkyPanoramicMaterial.EXPOSURE = Shader3D.propertyNameToID("u_Exposure");
  31275. SkyPanoramicMaterial.ROTATION = Shader3D.propertyNameToID("u_Rotation");
  31276. SkyPanoramicMaterial.TEXTURE = Shader3D.propertyNameToID("u_Texture");
  31277. SkyPanoramicMaterial.TEXTURE_HDR_PARAMS = Shader3D.propertyNameToID("u_TextureHDRParams");
  31278. class ConstraintComponent extends Laya.Component {
  31279. constructor(constraintType) {
  31280. super();
  31281. this._anchor = new Vector3();
  31282. this._connectAnchor = new Vector3();
  31283. this._feedbackEnabled = false;
  31284. this._getJointFeedBack = false;
  31285. this._currentForce = new Vector3();
  31286. this._currentTorque = new Vector3();
  31287. this._constraintType = constraintType;
  31288. var bt = Physics3D._bullet;
  31289. this._btframATrans = bt.btTransform_create();
  31290. this._btframBTrans = bt.btTransform_create();
  31291. bt.btTransform_setIdentity(this._btframATrans);
  31292. bt.btTransform_setIdentity(this._btframBTrans);
  31293. this._btframAPos = bt.btVector3_create(0, 0, 0);
  31294. this._btframBPos = bt.btVector3_create(0, 0, 0);
  31295. bt.btTransform_setOrigin(this._btframATrans, this._btframAPos);
  31296. bt.btTransform_setOrigin(this._btframBTrans, this._btframBPos);
  31297. this._breakForce = -1;
  31298. this._breakTorque = -1;
  31299. }
  31300. get enabled() {
  31301. return super.enabled;
  31302. }
  31303. set enabled(value) {
  31304. super.enabled = value;
  31305. }
  31306. get appliedImpulse() {
  31307. if (!this._feedbackEnabled) {
  31308. this._btConstraint.EnableFeedback(true);
  31309. this._feedbackEnabled = true;
  31310. }
  31311. return this._btConstraint.AppliedImpulse;
  31312. }
  31313. set connectedBody(value) {
  31314. this._connectedBody = value;
  31315. value && (value.constaintRigidbodyB = this);
  31316. }
  31317. get connectedBody() {
  31318. return this._connectedBody;
  31319. }
  31320. get ownBody() {
  31321. return this._ownBody;
  31322. }
  31323. set ownBody(value) {
  31324. this._ownBody = value;
  31325. value.constaintRigidbodyA = this;
  31326. }
  31327. get currentForce() {
  31328. if (!this._getJointFeedBack)
  31329. this._getFeedBackInfo();
  31330. return this._currentForce;
  31331. }
  31332. get currentTorque() {
  31333. if (!this._getJointFeedBack)
  31334. this._getFeedBackInfo();
  31335. return this._currentTorque;
  31336. }
  31337. get breakForce() {
  31338. return this._breakForce;
  31339. }
  31340. set breakForce(value) {
  31341. this._breakForce = value;
  31342. }
  31343. get breakTorque() {
  31344. return this._breakTorque;
  31345. }
  31346. set breakTorque(value) {
  31347. this._breakTorque = value;
  31348. }
  31349. set anchor(value) {
  31350. value.cloneTo(this._anchor);
  31351. this.setFrames();
  31352. }
  31353. get anchor() {
  31354. return this._anchor;
  31355. }
  31356. set connectAnchor(value) {
  31357. value.cloneTo(this._connectAnchor);
  31358. this.setFrames();
  31359. }
  31360. get connectAnchor() {
  31361. return this._connectAnchor;
  31362. }
  31363. setOverrideNumSolverIterations(overideNumIterations) {
  31364. var bt = Physics3D._bullet;
  31365. bt.btTypedConstraint_setOverrideNumSolverIterations(this._btConstraint, overideNumIterations);
  31366. }
  31367. setConstraintEnabled(enable) {
  31368. var bt = Physics3D._bullet;
  31369. bt.btTypedConstraint_setEnabled(this._btConstraint, enable);
  31370. }
  31371. _onEnable() {
  31372. super._onEnable();
  31373. this.enabled = true;
  31374. }
  31375. _onDisable() {
  31376. super._onDisable();
  31377. this.enabled = false;
  31378. }
  31379. setFrames() {
  31380. var bt = Physics3D._bullet;
  31381. bt.btVector3_setValue(this._btframAPos, -this._anchor.x, this.anchor.y, this.anchor.z);
  31382. bt.btVector3_setValue(this._btframBPos, -this._connectAnchor.x, this._connectAnchor.y, this._connectAnchor.z);
  31383. bt.btTransform_setOrigin(this._btframATrans, this._btframAPos);
  31384. bt.btTransform_setOrigin(this._btframBTrans, this._btframBPos);
  31385. }
  31386. _addToSimulation() {
  31387. }
  31388. _removeFromSimulation() {
  31389. }
  31390. _createConstraint() {
  31391. }
  31392. setConnectRigidBody(ownerRigid, connectRigidBody) {
  31393. var ownerCanInSimulation = (ownerRigid) && (!!(ownerRigid._simulation && ownerRigid._enabled && ownerRigid.colliderShape));
  31394. var connectCanInSimulation = (connectRigidBody) && (!!(connectRigidBody._simulation && connectRigidBody._enabled && connectRigidBody.colliderShape));
  31395. if (!(ownerCanInSimulation && connectCanInSimulation))
  31396. throw "ownerRigid or connectRigidBody is not in Simulation";
  31397. if (ownerRigid != this._ownBody || connectRigidBody != this._connectedBody) {
  31398. var canInSimulation = !!(this.enabled && this._simulation);
  31399. canInSimulation && this._removeFromSimulation();
  31400. this._ownBody = ownerRigid;
  31401. this._connectedBody = connectRigidBody;
  31402. this._ownBody.constaintRigidbodyA = this;
  31403. this._connectedBody.constaintRigidbodyB = this;
  31404. this._createConstraint();
  31405. }
  31406. }
  31407. getcurrentForce(out) {
  31408. if (!this._btJointFeedBackObj)
  31409. throw "this Constraint is not simulation";
  31410. var bt = Physics3D._bullet;
  31411. var applyForce = bt.btJointFeedback_getAppliedForceBodyA(this._btJointFeedBackObj);
  31412. out.setValue(bt.btVector3_x(applyForce), bt.btVector3_y(applyForce), bt.btVector3_z(applyForce));
  31413. return;
  31414. }
  31415. getcurrentTorque(out) {
  31416. if (!this._btJointFeedBackObj)
  31417. throw "this Constraint is not simulation";
  31418. var bt = Physics3D._bullet;
  31419. var applyTorque = bt.btJointFeedback_getAppliedTorqueBodyA(this._btJointFeedBackObj);
  31420. out.setValue(bt.btVector3_x(applyTorque), bt.btVector3_y(applyTorque), bt.btVector3_z(applyTorque));
  31421. return;
  31422. }
  31423. _onDestroy() {
  31424. var physics3D = Physics3D._bullet;
  31425. this._simulation && this._removeFromSimulation();
  31426. if (this._btConstraint && this._btJointFeedBackObj && this._simulation) {
  31427. physics3D.btTypedConstraint_destroy(this._btConstraint);
  31428. physics3D.btJointFeedback_destroy(this._btJointFeedBackObj);
  31429. this._btJointFeedBackObj = null;
  31430. this._btConstraint = null;
  31431. }
  31432. super._onDisable();
  31433. }
  31434. _isBreakConstrained() {
  31435. this._getJointFeedBack = false;
  31436. if (this.breakForce == -1 && this.breakTorque == -1)
  31437. return false;
  31438. this._getFeedBackInfo();
  31439. var isBreakForce = this._breakForce != -1 && (Vector3.scalarLength(this._currentForce) > this._breakForce);
  31440. var isBreakTorque = this._breakTorque != -1 && (Vector3.scalarLength(this._currentTorque) > this._breakTorque);
  31441. if (isBreakForce || isBreakTorque) {
  31442. this._breakConstrained();
  31443. return true;
  31444. }
  31445. return false;
  31446. }
  31447. _parse(data) {
  31448. this._anchor.fromArray(data.anchor);
  31449. this._connectAnchor.fromArray(data.connectAnchor);
  31450. this.setFrames();
  31451. }
  31452. _getFeedBackInfo() {
  31453. var bt = Physics3D._bullet;
  31454. var applyForce = bt.btJointFeedback_getAppliedForceBodyA(this._btJointFeedBackObj);
  31455. var applyTorque = bt.btJointFeedback_getAppliedTorqueBodyA(this._btJointFeedBackObj);
  31456. this._currentTorque.setValue(bt.btVector3_x(applyTorque), bt.btVector3_y(applyTorque), bt.btVector3_z(applyTorque));
  31457. this._currentForce.setValue(bt.btVector3_x(applyForce), bt.btVector3_y(applyForce), bt.btVector3_z(applyForce));
  31458. this._getJointFeedBack = true;
  31459. }
  31460. _breakConstrained() {
  31461. this.ownBody.constaintRigidbodyA = null;
  31462. this.connectedBody && (this.connectedBody.constaintRigidbodyB = null);
  31463. this.destroy();
  31464. }
  31465. }
  31466. ConstraintComponent.CONSTRAINT_POINT2POINT_CONSTRAINT_TYPE = 3;
  31467. ConstraintComponent.CONSTRAINT_HINGE_CONSTRAINT_TYPE = 4;
  31468. ConstraintComponent.CONSTRAINT_CONETWIST_CONSTRAINT_TYPE = 5;
  31469. ConstraintComponent.CONSTRAINT_D6_CONSTRAINT_TYPE = 6;
  31470. ConstraintComponent.CONSTRAINT_SLIDER_CONSTRAINT_TYPE = 7;
  31471. ConstraintComponent.CONSTRAINT_CONTACT_CONSTRAINT_TYPE = 8;
  31472. ConstraintComponent.CONSTRAINT_D6_SPRING_CONSTRAINT_TYPE = 9;
  31473. ConstraintComponent.CONSTRAINT_GEAR_CONSTRAINT_TYPE = 10;
  31474. ConstraintComponent.CONSTRAINT_FIXED_CONSTRAINT_TYPE = 11;
  31475. ConstraintComponent.CONSTRAINT_MAX_CONSTRAINT_TYPE = 12;
  31476. ConstraintComponent.CONSTRAINT_CONSTRAINT_ERP = 1;
  31477. ConstraintComponent.CONSTRAINT_CONSTRAINT_STOP_ERP = 2;
  31478. ConstraintComponent.CONSTRAINT_CONSTRAINT_CFM = 3;
  31479. ConstraintComponent.CONSTRAINT_CONSTRAINT_STOP_CFM = 4;
  31480. ConstraintComponent.tempForceV3 = new Vector3();
  31481. class FixedConstraint extends ConstraintComponent {
  31482. constructor() {
  31483. super(ConstraintComponent.CONSTRAINT_FIXED_CONSTRAINT_TYPE);
  31484. this.breakForce = -1;
  31485. this.breakTorque = -1;
  31486. }
  31487. _addToSimulation() {
  31488. this._simulation && this._simulation.addConstraint(this, this.enabled);
  31489. }
  31490. _removeFromSimulation() {
  31491. this._simulation.removeConstraint(this);
  31492. this._simulation = null;
  31493. }
  31494. _createConstraint() {
  31495. if (this.ownBody && this.ownBody._simulation && this.connectedBody && this.connectedBody._simulation) {
  31496. var bt = Physics3D._bullet;
  31497. this._btConstraint = bt.btFixedConstraint_create(this.ownBody.btColliderObject, this._btframATrans, this.connectedBody.btColliderObject, this._btframBTrans);
  31498. this._btJointFeedBackObj = bt.btJointFeedback_create(this._btConstraint);
  31499. bt.btTypedConstraint_setJointFeedback(this._btConstraint, this._btJointFeedBackObj);
  31500. this._simulation = this.owner._scene.physicsSimulation;
  31501. this._addToSimulation();
  31502. Physics3D._bullet.btTypedConstraint_setEnabled(this._btConstraint, true);
  31503. }
  31504. }
  31505. _onAdded() {
  31506. super._onAdded();
  31507. }
  31508. _onEnable() {
  31509. if (!this._btConstraint)
  31510. return;
  31511. super._onEnable();
  31512. if (this._btConstraint)
  31513. Physics3D._bullet.btTypedConstraint_setEnabled(this._btConstraint, true);
  31514. }
  31515. _onDisable() {
  31516. super._onDisable();
  31517. if (!this.connectedBody)
  31518. this._removeFromSimulation();
  31519. if (this._btConstraint)
  31520. Physics3D._bullet.btTypedConstraint_setEnabled(this._btConstraint, false);
  31521. }
  31522. _onDestroy() {
  31523. super._onDestroy();
  31524. }
  31525. _parse(data, interactMap = null) {
  31526. super._parse(data);
  31527. if (data.rigidbodyID != -1 && data.connectRigidbodyID != -1) {
  31528. interactMap.component.push(this);
  31529. interactMap.data.push(data);
  31530. }
  31531. (data.breakForce != undefined) && (this.breakForce = data.breakForce);
  31532. (data.breakTorque != undefined) && (this.breakTorque = data.breakTorque);
  31533. }
  31534. _parseInteractive(data = null, spriteMap = null) {
  31535. var rigidBodySprite = spriteMap[data.rigidbodyID];
  31536. var rigidBody = rigidBodySprite.getComponent(Rigidbody3D);
  31537. var connectSprite = spriteMap[data.connectRigidbodyID];
  31538. var connectRigidbody = connectSprite.getComponent(Rigidbody3D);
  31539. this.ownBody = rigidBody;
  31540. this.connectedBody = connectRigidbody;
  31541. }
  31542. _cloneTo(dest) {
  31543. }
  31544. }
  31545. class ConfigurableConstraint extends ConstraintComponent {
  31546. constructor() {
  31547. super(ConstraintComponent.CONSTRAINT_D6_SPRING_CONSTRAINT_TYPE);
  31548. this._axis = new Vector3();
  31549. this._secondaryAxis = new Vector3();
  31550. this._minLinearLimit = new Vector3();
  31551. this._maxLinearLimit = new Vector3();
  31552. this._minAngularLimit = new Vector3();
  31553. this._maxAngularLimit = new Vector3();
  31554. this._linearLimitSpring = new Vector3();
  31555. this._angularLimitSpring = new Vector3();
  31556. this._linearBounce = new Vector3();
  31557. this._angularBounce = new Vector3();
  31558. this._linearDamp = new Vector3();
  31559. this._angularDamp = new Vector3();
  31560. this._xMotion = 0;
  31561. this._yMotion = 0;
  31562. this._zMotion = 0;
  31563. this._angularXMotion = 0;
  31564. this._angularYMotion = 0;
  31565. this._angularZMotion = 0;
  31566. var bt = Physics3D._bullet;
  31567. this._btAxis = bt.btVector3_create(-1.0, 0.0, 0.0);
  31568. this._btSecondaryAxis = bt.btVector3_create(0.0, 1.0, 0.0);
  31569. }
  31570. get axis() {
  31571. return this._axis;
  31572. }
  31573. get secondaryAxis() {
  31574. return this._secondaryAxis;
  31575. }
  31576. set maxAngularLimit(value) {
  31577. value.cloneTo(this._maxAngularLimit);
  31578. }
  31579. set minAngularLimit(value) {
  31580. value.cloneTo(this._minAngularLimit);
  31581. }
  31582. get maxAngularLimit() {
  31583. return this._maxAngularLimit;
  31584. }
  31585. get minAngularLimit() {
  31586. return this._minAngularLimit;
  31587. }
  31588. set maxLinearLimit(value) {
  31589. value.cloneTo(this._maxLinearLimit);
  31590. }
  31591. set minLinearLimit(value) {
  31592. value.cloneTo(this._minLinearLimit);
  31593. }
  31594. get maxLinearLimit() {
  31595. return this._maxLinearLimit;
  31596. }
  31597. get minLinearLimit() {
  31598. return this._minLinearLimit;
  31599. }
  31600. set XMotion(value) {
  31601. if (this._xMotion != value) {
  31602. this._xMotion = value;
  31603. this.setLimit(ConfigurableConstraint.MOTION_LINEAR_INDEX_X, value, -this._maxLinearLimit.x, -this._minLinearLimit.x);
  31604. }
  31605. }
  31606. get XMotion() {
  31607. return this._xMotion;
  31608. }
  31609. set YMotion(value) {
  31610. if (this._yMotion != value) {
  31611. this._yMotion = value;
  31612. this.setLimit(ConfigurableConstraint.MOTION_LINEAR_INDEX_Y, value, this._minLinearLimit.y, this._maxLinearLimit.y);
  31613. }
  31614. }
  31615. get YMotion() {
  31616. return this._yMotion;
  31617. }
  31618. set ZMotion(value) {
  31619. if (this._zMotion != value) {
  31620. this._zMotion = value;
  31621. this.setLimit(ConfigurableConstraint.MOTION_LINEAR_INDEX_Z, value, this._minLinearLimit.z, this._maxLinearLimit.z);
  31622. }
  31623. }
  31624. get ZMotion() {
  31625. return this._zMotion;
  31626. }
  31627. set angularXMotion(value) {
  31628. if (this._angularXMotion != value) {
  31629. this._angularXMotion = value;
  31630. this.setLimit(ConfigurableConstraint.MOTION_ANGULAR_INDEX_X, value, -this._maxAngularLimit.x, -this._minAngularLimit.x);
  31631. }
  31632. }
  31633. get angularXMotion() {
  31634. return this._angularXMotion;
  31635. }
  31636. set angularYMotion(value) {
  31637. if (this._angularYMotion != value) {
  31638. this._angularYMotion = value;
  31639. this.setLimit(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Y, value, this._minAngularLimit.y, this._maxAngularLimit.y);
  31640. }
  31641. }
  31642. get angularYMotion() {
  31643. return this._angularYMotion;
  31644. }
  31645. set angularZMotion(value) {
  31646. if (this._angularZMotion != value) {
  31647. this._angularZMotion = value;
  31648. this.setLimit(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Z, value, this._minAngularLimit.z, this._maxAngularLimit.z);
  31649. }
  31650. }
  31651. get angularZMotion() {
  31652. return this._angularZMotion;
  31653. }
  31654. set linearLimitSpring(value) {
  31655. if (!Vector3.equals(this._linearLimitSpring, value)) {
  31656. value.cloneTo(this._linearLimitSpring);
  31657. this.setSpring(ConfigurableConstraint.MOTION_LINEAR_INDEX_X, value.x);
  31658. this.setSpring(ConfigurableConstraint.MOTION_LINEAR_INDEX_Y, value.y);
  31659. this.setSpring(ConfigurableConstraint.MOTION_LINEAR_INDEX_Z, value.z);
  31660. }
  31661. }
  31662. get linearLimitSpring() {
  31663. return this._linearLimitSpring;
  31664. }
  31665. set angularLimitSpring(value) {
  31666. if (!Vector3.equals(this._angularLimitSpring, value)) {
  31667. value.cloneTo(this._angularLimitSpring);
  31668. this.setSpring(ConfigurableConstraint.MOTION_ANGULAR_INDEX_X, value.x);
  31669. this.setSpring(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Y, value.y);
  31670. this.setSpring(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Z, value.z);
  31671. }
  31672. }
  31673. get angularLimitSpring() {
  31674. return this._angularLimitSpring;
  31675. }
  31676. set linearBounce(value) {
  31677. if (!Vector3.equals(this._linearBounce, value)) {
  31678. value.cloneTo(this._linearBounce);
  31679. this.setBounce(ConfigurableConstraint.MOTION_LINEAR_INDEX_X, value.x);
  31680. this.setBounce(ConfigurableConstraint.MOTION_LINEAR_INDEX_Y, value.y);
  31681. this.setBounce(ConfigurableConstraint.MOTION_LINEAR_INDEX_Z, value.z);
  31682. }
  31683. }
  31684. get linearBounce() {
  31685. return this._linearBounce;
  31686. }
  31687. set angularBounce(value) {
  31688. if (!Vector3.equals(this._angularBounce, value)) {
  31689. value.cloneTo(this._angularBounce);
  31690. this.setBounce(ConfigurableConstraint.MOTION_ANGULAR_INDEX_X, value.x);
  31691. this.setBounce(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Y, value.y);
  31692. this.setBounce(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Z, value.z);
  31693. }
  31694. }
  31695. get angularBounce() {
  31696. return this._angularBounce;
  31697. }
  31698. set linearDamp(value) {
  31699. if (!Vector3.equals(this._linearDamp, value)) {
  31700. value.cloneTo(this._linearDamp);
  31701. this.setDamping(ConfigurableConstraint.MOTION_LINEAR_INDEX_X, value.x);
  31702. this.setDamping(ConfigurableConstraint.MOTION_LINEAR_INDEX_Y, value.y);
  31703. this.setDamping(ConfigurableConstraint.MOTION_LINEAR_INDEX_Z, value.z);
  31704. }
  31705. }
  31706. get linearDamp() {
  31707. return this._linearDamp;
  31708. }
  31709. set angularDamp(value) {
  31710. if (!Vector3.equals(this._angularDamp, value)) {
  31711. value.cloneTo(this._angularDamp);
  31712. this.setDamping(ConfigurableConstraint.MOTION_ANGULAR_INDEX_X, value.x);
  31713. this.setDamping(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Y, value.y);
  31714. this.setDamping(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Z, value.z);
  31715. }
  31716. }
  31717. get angularDamp() {
  31718. return this._angularDamp;
  31719. }
  31720. set anchor(value) {
  31721. value.cloneTo(this._anchor);
  31722. this.setFrames();
  31723. }
  31724. get anchor() {
  31725. return this._anchor;
  31726. }
  31727. set connectAnchor(value) {
  31728. value.cloneTo(this._connectAnchor);
  31729. this.setFrames();
  31730. }
  31731. get connectAnchor() {
  31732. return this._connectAnchor;
  31733. }
  31734. setAxis(axis, secondaryAxis) {
  31735. if (!this._btConstraint)
  31736. return;
  31737. var bt = Physics3D._bullet;
  31738. this._axis.setValue(axis.x, axis.y, axis.y);
  31739. this._secondaryAxis.setValue(secondaryAxis.x, secondaryAxis.y, secondaryAxis.z);
  31740. this._btAxis = bt.btVector3_setValue(-axis.x, axis.y, axis.z);
  31741. this._btSecondaryAxis = bt.btVector3_setValue(-secondaryAxis.x, secondaryAxis.y, secondaryAxis.z);
  31742. bt.btGeneric6DofSpring2Constraint_setAxis(this._btConstraint, this._btAxis, this._btSecondaryAxis);
  31743. }
  31744. setLimit(axis, motionType, low, high) {
  31745. if (!this._btConstraint)
  31746. return;
  31747. var bt = Physics3D._bullet;
  31748. switch (motionType) {
  31749. case ConfigurableConstraint.CONFIG_MOTION_TYPE_LOCKED:
  31750. bt.btGeneric6DofSpring2Constraint_setLimit(this._btConstraint, axis, 0, 0);
  31751. break;
  31752. case ConfigurableConstraint.CONFIG_MOTION_TYPE_LIMITED:
  31753. if (low < high)
  31754. bt.btGeneric6DofSpring2Constraint_setLimit(this._btConstraint, axis, low, high);
  31755. break;
  31756. case ConfigurableConstraint.CONFIG_MOTION_TYPE_FREE:
  31757. bt.btGeneric6DofSpring2Constraint_setLimit(this._btConstraint, axis, 1, 0);
  31758. break;
  31759. default:
  31760. throw "No Type of Axis Motion";
  31761. }
  31762. }
  31763. setSpring(axis, springValue, limitIfNeeded = true) {
  31764. if (!this._btConstraint)
  31765. return;
  31766. var bt = Physics3D._bullet;
  31767. var enableSpring = springValue > 0;
  31768. bt.btGeneric6DofSpring2Constraint_enableSpring(this._btConstraint, axis, enableSpring);
  31769. if (enableSpring)
  31770. bt.btGeneric6DofSpring2Constraint_setStiffness(this._btConstraint, axis, springValue, limitIfNeeded);
  31771. }
  31772. setBounce(axis, bounce) {
  31773. if (!this._btConstraint)
  31774. return;
  31775. var bt = Physics3D._bullet;
  31776. bounce = bounce <= 0 ? 0 : bounce;
  31777. bt.btGeneric6DofSpring2Constraint_setBounce(this._btConstraint, axis, bounce);
  31778. }
  31779. setDamping(axis, damp, limitIfNeeded = true) {
  31780. if (!this._btConstraint)
  31781. return;
  31782. var bt = Physics3D._bullet;
  31783. damp = damp <= 0 ? 0 : damp;
  31784. bt.btGeneric6DofSpring2Constraint_setDamping(this._btConstraint, axis, damp, limitIfNeeded);
  31785. }
  31786. setEquilibriumPoint(axis, equilibriumPoint) {
  31787. var bt = Physics3D._bullet;
  31788. bt.btGeneric6DofSpring2Constraint_setEquilibriumPoint(this._btConstraint, axis, equilibriumPoint);
  31789. }
  31790. enableMotor(axis, isEnableMotor) {
  31791. var bt = Physics3D._bullet;
  31792. bt.btGeneric6DofSpring2Constraint_enableMotor(this._btConstraint, axis, isEnableMotor);
  31793. }
  31794. setServo(axis, onOff) {
  31795. var bt = Physics3D._bullet;
  31796. bt.btGeneric6DofSpring2Constraint_setServo(this._btConstraint, axis, onOff);
  31797. }
  31798. setTargetVelocity(axis, velocity) {
  31799. var bt = Physics3D._bullet;
  31800. bt.btGeneric6DofSpring2Constraint_setTargetVelocity(this._btConstraint, axis, velocity);
  31801. }
  31802. setTargetPosition(axis, target) {
  31803. var bt = Physics3D._bullet;
  31804. bt.btGeneric6DofSpring2Constraint_setServoTarget(this._btConstraint, axis, target);
  31805. }
  31806. setMaxMotorForce(axis, force) {
  31807. var bt = Physics3D._bullet;
  31808. bt.btGeneric6DofSpring2Constraint_setMaxMotorForce(this._btConstraint, axis, force);
  31809. }
  31810. setParam(axis, constraintParams, value) {
  31811. var bt = Physics3D._bullet;
  31812. bt.btTypedConstraint_setParam(this._btConstraint, axis, constraintParams, value);
  31813. }
  31814. setFrames() {
  31815. super.setFrames();
  31816. var bt = Physics3D._bullet;
  31817. if (!this._btConstraint)
  31818. return;
  31819. bt.btGeneric6DofSpring2Constraint_setFrames(this._btConstraint, this._btframATrans, this._btframBTrans);
  31820. }
  31821. _addToSimulation() {
  31822. this._simulation && this._simulation.addConstraint(this, this.enabled);
  31823. }
  31824. _removeFromSimulation() {
  31825. this._simulation.removeConstraint(this);
  31826. this._simulation = null;
  31827. }
  31828. _createConstraint() {
  31829. var bt = Physics3D._bullet;
  31830. this._btConstraint = bt.btGeneric6DofSpring2Constraint_create(this.ownBody.btColliderObject, this._btframAPos, this.connectedBody.btColliderObject, this._btframBPos, ConfigurableConstraint.RO_XYZ);
  31831. this._btJointFeedBackObj = bt.btJointFeedback_create(this._btConstraint);
  31832. bt.btTypedConstraint_setJointFeedback(this._btConstraint, this._btJointFeedBackObj);
  31833. this._simulation = this.owner._scene.physicsSimulation;
  31834. this._initAllConstraintInfo();
  31835. this._addToSimulation();
  31836. Physics3D._bullet.btTypedConstraint_setEnabled(this._btConstraint, true);
  31837. }
  31838. _initAllConstraintInfo() {
  31839. this.setLimit(ConfigurableConstraint.MOTION_LINEAR_INDEX_X, this._xMotion, -this._maxLinearLimit.x, -this._minLinearLimit.x);
  31840. this.setLimit(ConfigurableConstraint.MOTION_LINEAR_INDEX_Y, this._yMotion, this._minLinearLimit.y, this._maxLinearLimit.y);
  31841. this.setLimit(ConfigurableConstraint.MOTION_LINEAR_INDEX_Z, this._zMotion, this._minLinearLimit.z, this._maxLinearLimit.z);
  31842. this.setLimit(ConfigurableConstraint.MOTION_ANGULAR_INDEX_X, this._angularXMotion, -this._maxAngularLimit.x, -this._minAngularLimit.x);
  31843. this.setLimit(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Y, this._angularYMotion, this._minAngularLimit.y, this._maxAngularLimit.y);
  31844. this.setLimit(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Z, this._angularZMotion, this._minAngularLimit.z, this._maxAngularLimit.z);
  31845. this.setSpring(ConfigurableConstraint.MOTION_LINEAR_INDEX_X, this._linearLimitSpring.x);
  31846. this.setSpring(ConfigurableConstraint.MOTION_LINEAR_INDEX_Y, this._linearLimitSpring.y);
  31847. this.setSpring(ConfigurableConstraint.MOTION_LINEAR_INDEX_Z, this._linearLimitSpring.z);
  31848. this.setSpring(ConfigurableConstraint.MOTION_ANGULAR_INDEX_X, this._angularLimitSpring.x);
  31849. this.setSpring(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Y, this._angularLimitSpring.y);
  31850. this.setSpring(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Z, this._angularLimitSpring.z);
  31851. this.setBounce(ConfigurableConstraint.MOTION_LINEAR_INDEX_X, this._linearBounce.x);
  31852. this.setBounce(ConfigurableConstraint.MOTION_LINEAR_INDEX_Y, this._linearBounce.y);
  31853. this.setBounce(ConfigurableConstraint.MOTION_LINEAR_INDEX_Z, this._linearBounce.z);
  31854. this.setBounce(ConfigurableConstraint.MOTION_ANGULAR_INDEX_X, this._angularBounce.x);
  31855. this.setBounce(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Y, this._angularBounce.y);
  31856. this.setBounce(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Z, this._angularBounce.z);
  31857. this.setDamping(ConfigurableConstraint.MOTION_LINEAR_INDEX_X, this._linearDamp.x);
  31858. this.setDamping(ConfigurableConstraint.MOTION_LINEAR_INDEX_Y, this._linearDamp.y);
  31859. this.setDamping(ConfigurableConstraint.MOTION_LINEAR_INDEX_Z, this._linearDamp.z);
  31860. this.setDamping(ConfigurableConstraint.MOTION_ANGULAR_INDEX_X, this._angularDamp.x);
  31861. this.setDamping(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Y, this._angularDamp.y);
  31862. this.setDamping(ConfigurableConstraint.MOTION_ANGULAR_INDEX_Z, this._angularDamp.z);
  31863. this.setFrames();
  31864. this.setEquilibriumPoint(0, 0);
  31865. }
  31866. _onAdded() {
  31867. super._onAdded();
  31868. }
  31869. _onEnable() {
  31870. if (!this._btConstraint)
  31871. return;
  31872. super._onEnable();
  31873. if (this._btConstraint)
  31874. Physics3D._bullet.btTypedConstraint_setEnabled(this._btConstraint, true);
  31875. }
  31876. _onDisable() {
  31877. super._onDisable();
  31878. if (!this.connectedBody && this._simulation)
  31879. this._removeFromSimulation();
  31880. if (this._btConstraint)
  31881. Physics3D._bullet.btTypedConstraint_setEnabled(this._btConstraint, false);
  31882. }
  31883. _parse(data, interactMap = null) {
  31884. super._parse(data);
  31885. this._axis.fromArray(data.axis);
  31886. this._secondaryAxis.fromArray(data.secondaryAxis);
  31887. var limitlimit = data.linearLimit;
  31888. this._minLinearLimit.setValue(-limitlimit, -limitlimit, -limitlimit);
  31889. this._maxLinearLimit.setValue(limitlimit, limitlimit, limitlimit);
  31890. var limitSpring = data.linearLimitSpring;
  31891. this._linearLimitSpring.setValue(limitSpring, limitSpring, limitSpring);
  31892. var limitDamp = data.linearLimitDamper;
  31893. this._linearDamp.setValue(limitDamp, limitDamp, limitDamp);
  31894. var limitBounciness = data.linearLimitBounciness;
  31895. this._linearBounce.setValue(limitBounciness, limitBounciness, limitBounciness);
  31896. var xlowAngularLimit = data.lowAngularXLimit;
  31897. var xhighAngularLimit = data.highAngularXLimit;
  31898. var yAngularLimit = data.angularYLimit;
  31899. var zAngularLimit = data.angularZLimit;
  31900. this._minAngularLimit.setValue(xlowAngularLimit, -yAngularLimit, -zAngularLimit);
  31901. this._maxAngularLimit.setValue(xhighAngularLimit, yAngularLimit, zAngularLimit);
  31902. var xhighAngularBounciness = data.highAngularXLimitBounciness;
  31903. var ybounciness = data.angularYLimitBounciness;
  31904. var zbounciness = data.angularZLimitBounciness;
  31905. this._angularBounce.setValue(xhighAngularBounciness, ybounciness, zbounciness);
  31906. var xAngularSpring = data.angularXLimitSpring;
  31907. var yzAngularSpriny = data.angularYZLimitSpring;
  31908. this._angularLimitSpring.setValue(xAngularSpring, yzAngularSpriny, yzAngularSpriny);
  31909. var xAngularDamper = data.angularXLimitDamper;
  31910. var yzAngularDamper = data.angularYZLimitDamper;
  31911. this._angularDamp.setValue(xAngularDamper, yzAngularDamper, yzAngularDamper);
  31912. this.XMotion = data.xMotion;
  31913. this.YMotion = data.yMotion;
  31914. this.ZMotion = data.zMotion;
  31915. this.angularXMotion = data.angularXMotion;
  31916. this.angularYMotion = data.angularYMotion;
  31917. this.angularZMotion = data.angularZMotion;
  31918. if (data.rigidbodyID != -1 && data.connectRigidbodyID != -1) {
  31919. interactMap.component.push(this);
  31920. interactMap.data.push(data);
  31921. }
  31922. (data.breakForce != undefined) && (this.breakForce = data.breakForce);
  31923. (data.breakTorque != undefined) && (this.breakTorque = data.breakTorque);
  31924. }
  31925. _parseInteractive(data = null, spriteMap = null) {
  31926. var rigidBodySprite = spriteMap[data.rigidbodyID];
  31927. var rigidBody = rigidBodySprite.getComponent(Rigidbody3D);
  31928. var connectSprite = spriteMap[data.connectRigidbodyID];
  31929. var connectRigidbody = connectSprite.getComponent(Rigidbody3D);
  31930. this.ownBody = rigidBody;
  31931. this.connectedBody = connectRigidbody;
  31932. }
  31933. _onDestroy() {
  31934. super._onDestroy();
  31935. }
  31936. _cloneTo(dest) {
  31937. }
  31938. }
  31939. ConfigurableConstraint.CONFIG_MOTION_TYPE_LOCKED = 0;
  31940. ConfigurableConstraint.CONFIG_MOTION_TYPE_LIMITED = 1;
  31941. ConfigurableConstraint.CONFIG_MOTION_TYPE_FREE = 2;
  31942. ConfigurableConstraint.MOTION_LINEAR_INDEX_X = 0;
  31943. ConfigurableConstraint.MOTION_LINEAR_INDEX_Y = 1;
  31944. ConfigurableConstraint.MOTION_LINEAR_INDEX_Z = 2;
  31945. ConfigurableConstraint.MOTION_ANGULAR_INDEX_X = 3;
  31946. ConfigurableConstraint.MOTION_ANGULAR_INDEX_Y = 4;
  31947. ConfigurableConstraint.MOTION_ANGULAR_INDEX_Z = 5;
  31948. ConfigurableConstraint.RO_XYZ = 0;
  31949. ConfigurableConstraint.RO_XZY = 1;
  31950. ConfigurableConstraint.RO_YXZ = 2;
  31951. ConfigurableConstraint.RO_YZX = 3;
  31952. ConfigurableConstraint.RO_ZXY = 4;
  31953. ConfigurableConstraint.RO_ZYX = 5;
  31954. class Laya3D {
  31955. constructor() {
  31956. }
  31957. static get enablePhysics() {
  31958. return Physics3D._enablePhysics;
  31959. }
  31960. static _cancelLoadByUrl(url) {
  31961. Laya.Laya.loader.cancelLoadByUrl(url);
  31962. Laya3D._innerFirstLevelLoaderManager.cancelLoadByUrl(url);
  31963. Laya3D._innerSecondLevelLoaderManager.cancelLoadByUrl(url);
  31964. Laya3D._innerThirdLevelLoaderManager.cancelLoadByUrl(url);
  31965. Laya3D._innerFourthLevelLoaderManager.cancelLoadByUrl(url);
  31966. }
  31967. static _changeWebGLSize(width, height) {
  31968. Laya.WebGL.onStageResize(width, height);
  31969. RenderContext3D.clientWidth = width;
  31970. RenderContext3D.clientHeight = height;
  31971. }
  31972. static __init__(width, height, config) {
  31973. Laya.Config.isAntialias = config.isAntialias;
  31974. Laya.Config.isAlpha = config.isAlpha;
  31975. Laya.Config.premultipliedAlpha = config.premultipliedAlpha;
  31976. Laya.Config.isStencil = config.isStencil;
  31977. if (!Laya.WebGL.enable()) {
  31978. alert("Laya3D init error,must support webGL!");
  31979. return;
  31980. }
  31981. Laya.RunDriver.changeWebGLSize = Laya3D._changeWebGLSize;
  31982. Laya.Render.is3DMode = true;
  31983. Laya.Laya.init(width, height);
  31984. if (!Laya.Render.supportWebGLPlusRendering) {
  31985. Laya.LayaGL.instance = Laya.WebGLContext.mainContext;
  31986. Laya.LayaGL.instance.createCommandEncoder = function (reserveSize = 128, adjustSize = 64, isSyncToRenderThread = false) {
  31987. return new Laya.CommandEncoder(this, reserveSize, adjustSize, isSyncToRenderThread);
  31988. };
  31989. }
  31990. config._multiLighting = config.enableMultiLight && Laya.SystemUtils.supportTextureFormat(Laya.TextureFormat.R32G32B32A32);
  31991. ILaya3D.Shader3D = Shader3D;
  31992. ILaya3D.Scene3D = Scene3D;
  31993. ILaya3D.MeshRenderStaticBatchManager = MeshRenderStaticBatchManager;
  31994. ILaya3D.MeshRenderDynamicBatchManager = MeshRenderDynamicBatchManager;
  31995. ILaya3D.SubMeshDynamicBatch = SubMeshDynamicBatch;
  31996. ILaya3D.Laya3D = Laya3D;
  31997. ILaya3D.Matrix4x4 = Matrix4x4;
  31998. ILaya3D.Physics3D = Physics3D;
  31999. ILaya3D.ShadowLightType = exports.ShadowLightType;
  32000. Laya3D.enableNative3D();
  32001. if (config.isUseCannonPhysicsEngine)
  32002. Physics3D.__cannoninit__();
  32003. Physics3D.__bulletinit__();
  32004. VertexElementFormat.__init__();
  32005. VertexMesh.__init__();
  32006. VertexShurikenParticleBillboard.__init__();
  32007. VertexShurikenParticleMesh.__init__();
  32008. VertexPositionTexture0.__init__();
  32009. VertexTrail.__init__();
  32010. VertexPositionTerrain.__init__();
  32011. PixelLineVertex.__init__();
  32012. SubMeshInstanceBatch.__init__();
  32013. SubMeshDynamicBatch.__init__();
  32014. ShaderInit3D.__init__();
  32015. ShadowUtils.init();
  32016. PBRMaterial.__init__();
  32017. PBRStandardMaterial.__init__();
  32018. PBRSpecularMaterial.__init__();
  32019. SkyPanoramicMaterial.__init__();
  32020. Mesh.__init__();
  32021. PrimitiveMesh.__init__();
  32022. Sprite3D.__init__();
  32023. RenderableSprite3D.__init__();
  32024. MeshSprite3D.__init__();
  32025. SkinnedMeshSprite3D.__init__();
  32026. SimpleSkinnedMeshSprite3D.__init__();
  32027. ShuriKenParticle3D.__init__();
  32028. TrailSprite3D.__init__();
  32029. PostProcess.__init__();
  32030. Scene3D.__init__();
  32031. MeshRenderStaticBatchManager.__init__();
  32032. Material.__initDefine__();
  32033. BaseMaterial.__initDefine__();
  32034. BlinnPhongMaterial.__initDefine__();
  32035. SkyProceduralMaterial.__initDefine__();
  32036. UnlitMaterial.__initDefine__();
  32037. TrailMaterial.__initDefine__();
  32038. EffectMaterial.__initDefine__();
  32039. WaterPrimaryMaterial.__initDefine__();
  32040. ShurikenParticleMaterial.__initDefine__();
  32041. ExtendTerrainMaterial.__initDefine__();
  32042. PixelLineMaterial.__initDefine__();
  32043. SkyBoxMaterial.__initDefine__();
  32044. Command.__init__();
  32045. Laya.ClassUtils.regClass("Laya.SkyPanoramicMaterial", SkyPanoramicMaterial);
  32046. Laya.ClassUtils.regClass("Laya.EffectMaterial", EffectMaterial);
  32047. Laya.ClassUtils.regClass("Laya.UnlitMaterial", UnlitMaterial);
  32048. Laya.ClassUtils.regClass("Laya.BlinnPhongMaterial", BlinnPhongMaterial);
  32049. Laya.ClassUtils.regClass("Laya.SkyProceduralMaterial", SkyProceduralMaterial);
  32050. Laya.ClassUtils.regClass("Laya.PBRStandardMaterial", PBRStandardMaterial);
  32051. Laya.ClassUtils.regClass("Laya.PBRSpecularMaterial", PBRSpecularMaterial);
  32052. Laya.ClassUtils.regClass("Laya.SkyBoxMaterial", SkyBoxMaterial);
  32053. Laya.ClassUtils.regClass("Laya.WaterPrimaryMaterial", WaterPrimaryMaterial);
  32054. Laya.ClassUtils.regClass("Laya.ExtendTerrainMaterial", ExtendTerrainMaterial);
  32055. Laya.ClassUtils.regClass("Laya.ShurikenParticleMaterial", ShurikenParticleMaterial);
  32056. Laya.ClassUtils.regClass("Laya.TrailMaterial", TrailMaterial);
  32057. Laya.ClassUtils.regClass("Laya.PhysicsCollider", PhysicsCollider);
  32058. Laya.ClassUtils.regClass("Laya.Rigidbody3D", Rigidbody3D);
  32059. Laya.ClassUtils.regClass("Laya.CharacterController", CharacterController);
  32060. Laya.ClassUtils.regClass("Laya.Animator", Animator);
  32061. Laya.ClassUtils.regClass("PhysicsCollider", PhysicsCollider);
  32062. Laya.ClassUtils.regClass("CharacterController", CharacterController);
  32063. Laya.ClassUtils.regClass("Animator", Animator);
  32064. Laya.ClassUtils.regClass("Rigidbody3D", Rigidbody3D);
  32065. Laya.ClassUtils.regClass("FixedConstraint", FixedConstraint);
  32066. Laya.ClassUtils.regClass("ConfigurableConstraint", ConfigurableConstraint);
  32067. PixelLineMaterial.defaultMaterial = new PixelLineMaterial();
  32068. BlinnPhongMaterial.defaultMaterial = new BlinnPhongMaterial();
  32069. EffectMaterial.defaultMaterial = new EffectMaterial();
  32070. UnlitMaterial.defaultMaterial = new UnlitMaterial();
  32071. ShurikenParticleMaterial.defaultMaterial = new ShurikenParticleMaterial();
  32072. TrailMaterial.defaultMaterial = new TrailMaterial();
  32073. SkyProceduralMaterial.defaultMaterial = new SkyProceduralMaterial();
  32074. SkyBoxMaterial.defaultMaterial = new SkyBoxMaterial();
  32075. WaterPrimaryMaterial.defaultMaterial = new WaterPrimaryMaterial();
  32076. PixelLineMaterial.defaultMaterial.lock = true;
  32077. BlinnPhongMaterial.defaultMaterial.lock = true;
  32078. EffectMaterial.defaultMaterial.lock = true;
  32079. UnlitMaterial.defaultMaterial.lock = true;
  32080. ShurikenParticleMaterial.defaultMaterial.lock = true;
  32081. TrailMaterial.defaultMaterial.lock = true;
  32082. SkyProceduralMaterial.defaultMaterial.lock = true;
  32083. SkyBoxMaterial.defaultMaterial.lock = true;
  32084. WaterPrimaryMaterial.defaultMaterial.lock = true;
  32085. Laya.Texture2D.__init__();
  32086. TextureCube.__init__();
  32087. SkyBox.__init__();
  32088. SkyDome.__init__();
  32089. ScreenQuad.__init__();
  32090. ScreenTriangle.__init__();
  32091. FrustumCulling.__init__();
  32092. Laya.HalfFloatUtils.__init__();
  32093. var createMap = Laya.LoaderManager.createMap;
  32094. createMap["lh"] = [Laya3D.HIERARCHY, Scene3DUtils._parse];
  32095. createMap["ls"] = [Laya3D.HIERARCHY, Scene3DUtils._parseScene];
  32096. createMap["lm"] = [Laya3D.MESH, MeshReader._parse];
  32097. createMap["lmat"] = [Laya3D.MATERIAL, Material._parse];
  32098. createMap["jpg"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  32099. createMap["jpeg"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  32100. createMap["bmp"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  32101. createMap["gif"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  32102. createMap["png"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  32103. createMap["dds"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  32104. createMap["ktx"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  32105. createMap["pvr"] = [Laya3D.TEXTURE2D, Laya.Texture2D._parse];
  32106. createMap["lani"] = [Laya3D.ANIMATIONCLIP, AnimationClip._parse];
  32107. createMap["lav"] = [Laya3D.AVATAR, Avatar._parse];
  32108. createMap["ltc"] = [Laya3D.TEXTURECUBE, TextureCube._parse];
  32109. createMap["ltcb"] = [Laya3D.TEXTURECUBEBIN, TextureCube._parseBin];
  32110. createMap["ltcb.ls"] = [Laya3D.TEXTURECUBEBIN, TextureCube._parseBin];
  32111. createMap["lanit.ls"] = [Laya3D.TEXTURE2D, Laya.Texture2D._SimpleAnimatorTextureParse];
  32112. var parserMap = Laya.Loader.parserMap;
  32113. parserMap[Laya3D.HIERARCHY] = Laya3D._loadHierarchy;
  32114. parserMap[Laya3D.MESH] = Laya3D._loadMesh;
  32115. parserMap[Laya3D.MATERIAL] = Laya3D._loadMaterial;
  32116. parserMap[Laya3D.TEXTURECUBE] = Laya3D._loadTextureCube;
  32117. parserMap[Laya3D.TEXTURECUBEBIN] = Laya3D._loadTextureCubeBin;
  32118. parserMap[Laya3D.TEXTURE2D] = Laya3D._loadTexture2D;
  32119. parserMap[Laya3D.ANIMATIONCLIP] = Laya3D._loadAnimationClip;
  32120. parserMap[Laya3D.AVATAR] = Laya3D._loadAvatar;
  32121. parserMap[Laya3D.SIMPLEANIMATORBIN] = Laya3D._loadSimpleAnimator;
  32122. Laya3D._innerFirstLevelLoaderManager.on(Laya.Event.ERROR, null, Laya3D._eventLoadManagerError);
  32123. Laya3D._innerSecondLevelLoaderManager.on(Laya.Event.ERROR, null, Laya3D._eventLoadManagerError);
  32124. Laya3D._innerThirdLevelLoaderManager.on(Laya.Event.ERROR, null, Laya3D._eventLoadManagerError);
  32125. Laya3D._innerFourthLevelLoaderManager.on(Laya.Event.ERROR, null, Laya3D._eventLoadManagerError);
  32126. }
  32127. static enableNative3D() {
  32128. var shaderData = ShaderData;
  32129. var shader3D = ShaderInstance;
  32130. if (Laya.Render.supportWebGLPlusRendering) {
  32131. shaderData.prototype._initData = shaderData.prototype._initDataForNative;
  32132. shaderData.prototype.setBool = shaderData.prototype.setBoolForNative;
  32133. shaderData.prototype.getBool = shaderData.prototype.getBoolForNative;
  32134. shaderData.prototype.setInt = shaderData.prototype.setIntForNative;
  32135. shaderData.prototype.getInt = shaderData.prototype.getIntForNative;
  32136. shaderData.prototype.setNumber = shaderData.prototype.setNumberForNative;
  32137. shaderData.prototype.getNumber = shaderData.prototype.getNumberForNative;
  32138. shaderData.prototype.setVector = shaderData.prototype.setVectorForNative;
  32139. shaderData.prototype.getVector = shaderData.prototype.getVectorForNative;
  32140. shaderData.prototype.setVector2 = shaderData.prototype.setVector2ForNative;
  32141. shaderData.prototype.getVector2 = shaderData.prototype.getVector2ForNative;
  32142. shaderData.prototype.setVector3 = shaderData.prototype.setVector3ForNative;
  32143. shaderData.prototype.getVector3 = shaderData.prototype.getVector3ForNative;
  32144. shaderData.prototype.setQuaternion = shaderData.prototype.setQuaternionForNative;
  32145. shaderData.prototype.getQuaternion = shaderData.prototype.getQuaternionForNative;
  32146. shaderData.prototype.setMatrix4x4 = shaderData.prototype.setMatrix4x4ForNative;
  32147. shaderData.prototype.getMatrix4x4 = shaderData.prototype.getMatrix4x4ForNative;
  32148. shaderData.prototype.setBuffer = shaderData.prototype.setBufferForNative;
  32149. shaderData.prototype.getBuffer = shaderData.prototype.getBufferForNative;
  32150. shaderData.prototype.setTexture = shaderData.prototype.setTextureForNative;
  32151. shaderData.prototype.getTexture = shaderData.prototype.getTextureForNative;
  32152. shaderData.prototype.setAttribute = shaderData.prototype.setAttributeForNative;
  32153. shaderData.prototype.getAttribute = shaderData.prototype.getAttributeForNative;
  32154. shaderData.prototype.cloneTo = shaderData.prototype.cloneToForNative;
  32155. shaderData.prototype.getData = shaderData.prototype.getDataForNative;
  32156. shader3D.prototype._uniformMatrix2fv = shader3D.prototype._uniformMatrix2fvForNative;
  32157. shader3D.prototype._uniformMatrix3fv = shader3D.prototype._uniformMatrix3fvForNative;
  32158. shader3D.prototype._uniformMatrix4fv = shader3D.prototype._uniformMatrix4fvForNative;
  32159. Laya.LayaGLRunner.uploadShaderUniforms = Laya.LayaGLRunner.uploadShaderUniformsForNative;
  32160. }
  32161. }
  32162. static formatRelativePath(base, value) {
  32163. var path;
  32164. path = base + value;
  32165. var char1 = value.charAt(0);
  32166. if (char1 === ".") {
  32167. var parts = path.split("/");
  32168. for (var i = 0, len = parts.length; i < len; i++) {
  32169. if (parts[i] == '..') {
  32170. var index = i - 1;
  32171. if (index > 0 && parts[index] !== '..') {
  32172. parts.splice(index, 2);
  32173. i -= 2;
  32174. }
  32175. }
  32176. }
  32177. path = parts.join('/');
  32178. }
  32179. return path;
  32180. }
  32181. static _endLoad(loader, content = null, subResous = null) {
  32182. if (subResous) {
  32183. for (var i = 0, n = subResous.length; i < n; i++) {
  32184. var resou = Laya.Loader.getRes(subResous[i]);
  32185. (resou) && (resou._removeReference());
  32186. }
  32187. }
  32188. loader.endLoad(content);
  32189. }
  32190. static _eventLoadManagerError(msg) {
  32191. Laya.Laya.loader.event(Laya.Event.ERROR, msg);
  32192. }
  32193. static _addHierarchyInnerUrls(urls, urlMap, urlVersion, hierarchyBasePath, path, type, constructParams = null, propertyParams = null) {
  32194. var formatUrl = Laya3D.formatRelativePath(hierarchyBasePath, path);
  32195. (urlVersion) && (formatUrl = formatUrl + urlVersion);
  32196. urls.push({ url: formatUrl, type: type, constructParams: constructParams, propertyParams: propertyParams });
  32197. urlMap.push(formatUrl);
  32198. return formatUrl;
  32199. }
  32200. static _getSprite3DHierarchyInnerUrls(node, firstLevelUrls, secondLevelUrls, thirdLevelUrls, fourthLelUrls, subUrls, urlVersion, hierarchyBasePath) {
  32201. var i, n;
  32202. var props = node.props;
  32203. switch (node.type) {
  32204. case "Scene3D":
  32205. var lightmaps = props.lightmaps;
  32206. for (i = 0, n = lightmaps.length; i < n; i++) {
  32207. var lightMap = lightmaps[i];
  32208. if (lightMap.path) {
  32209. lightMap.path = Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, lightMap.path, Laya3D.TEXTURE2D, lightMap.constructParams, lightMap.propertyParams);
  32210. }
  32211. else {
  32212. var lightmapColorData = lightMap.color;
  32213. lightmapColorData.path = Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, lightmapColorData.path, Laya3D.TEXTURE2D, lightmapColorData.constructParams, lightmapColorData.propertyParams);
  32214. var lightmapDirectionData = lightMap.direction;
  32215. if (lightmapDirectionData)
  32216. lightmapDirectionData.path = Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, lightmapDirectionData.path, Laya3D.TEXTURE2D, lightmapDirectionData.constructParams, lightmapDirectionData.propertyParams);
  32217. }
  32218. }
  32219. var reflectionTextureData = props.reflectionTexture;
  32220. (reflectionTextureData) && (props.reflection = Laya3D._addHierarchyInnerUrls(thirdLevelUrls, subUrls, urlVersion, hierarchyBasePath, reflectionTextureData, Laya3D.TEXTURECUBE));
  32221. var reflectionData = props.reflection;
  32222. (reflectionData) && (props.reflection = Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, reflectionData, Laya3D.TEXTURECUBEBIN));
  32223. if (props.sky) {
  32224. var skyboxMaterial = props.sky.material;
  32225. (skyboxMaterial) && (skyboxMaterial.path = Laya3D._addHierarchyInnerUrls(secondLevelUrls, subUrls, urlVersion, hierarchyBasePath, skyboxMaterial.path, Laya3D.MATERIAL));
  32226. }
  32227. break;
  32228. case "Camera":
  32229. var skyboxMatData = props.skyboxMaterial;
  32230. (skyboxMatData) && (skyboxMatData.path = Laya3D._addHierarchyInnerUrls(secondLevelUrls, subUrls, urlVersion, hierarchyBasePath, skyboxMatData.path, Laya3D.MATERIAL));
  32231. break;
  32232. case "TrailSprite3D":
  32233. case "MeshSprite3D":
  32234. case "SkinnedMeshSprite3D":
  32235. case "SimpleSkinnedMeshSprite3D":
  32236. var meshPath = props.meshPath;
  32237. (meshPath) && (props.meshPath = Laya3D._addHierarchyInnerUrls(firstLevelUrls, subUrls, urlVersion, hierarchyBasePath, meshPath, Laya3D.MESH));
  32238. var materials = props.materials;
  32239. if (materials)
  32240. for (i = 0, n = materials.length; i < n; i++)
  32241. materials[i].path = Laya3D._addHierarchyInnerUrls(secondLevelUrls, subUrls, urlVersion, hierarchyBasePath, materials[i].path, Laya3D.MATERIAL);
  32242. if (node.type == "SimpleSkinnedMeshSprite3D")
  32243. if (props.animatorTexture)
  32244. props.animatorTexture = Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, props.animatorTexture, Laya3D.SIMPLEANIMATORBIN);
  32245. break;
  32246. case "ShuriKenParticle3D":
  32247. if (props.main) {
  32248. var resources = props.renderer.resources;
  32249. var mesh = resources.mesh;
  32250. var material = resources.material;
  32251. (mesh) && (resources.mesh = Laya3D._addHierarchyInnerUrls(firstLevelUrls, subUrls, urlVersion, hierarchyBasePath, mesh, Laya3D.MESH));
  32252. (material) && (resources.material = Laya3D._addHierarchyInnerUrls(secondLevelUrls, subUrls, urlVersion, hierarchyBasePath, material, Laya3D.MATERIAL));
  32253. }
  32254. else {
  32255. var parMeshPath = props.meshPath;
  32256. (parMeshPath) && (props.meshPath = Laya3D._addHierarchyInnerUrls(firstLevelUrls, subUrls, urlVersion, hierarchyBasePath, parMeshPath, Laya3D.MESH));
  32257. props.material.path = Laya3D._addHierarchyInnerUrls(secondLevelUrls, subUrls, urlVersion, hierarchyBasePath, props.material.path, Laya3D.MATERIAL);
  32258. }
  32259. break;
  32260. case "Terrain":
  32261. Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, props.dataPath, Laya3D.TERRAINRES);
  32262. break;
  32263. case "ReflectionProbe":
  32264. var reflection = props.reflection;
  32265. (reflection) && (props.reflection = Laya3D._addHierarchyInnerUrls(firstLevelUrls, subUrls, urlVersion, hierarchyBasePath, reflection, Laya3D.TEXTURECUBEBIN));
  32266. break;
  32267. }
  32268. var components = node.components;
  32269. if (components) {
  32270. for (var k = 0, p = components.length; k < p; k++) {
  32271. var component = components[k];
  32272. switch (component.type) {
  32273. case "Animator":
  32274. var avatarPath = component.avatarPath;
  32275. var avatarData = component.avatar;
  32276. (avatarData) && (avatarData.path = Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, avatarData.path, Laya3D.AVATAR));
  32277. var clipPaths = component.clipPaths;
  32278. if (!clipPaths) {
  32279. var layersData = component.layers;
  32280. for (i = 0; i < layersData.length; i++) {
  32281. var states = layersData[i].states;
  32282. for (var j = 0, m = states.length; j < m; j++) {
  32283. var clipPath = states[j].clipPath;
  32284. (clipPath) && (states[j].clipPath = Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, clipPath, Laya3D.ANIMATIONCLIP));
  32285. }
  32286. }
  32287. }
  32288. else {
  32289. for (i = 0, n = clipPaths.length; i < n; i++)
  32290. clipPaths[i] = Laya3D._addHierarchyInnerUrls(fourthLelUrls, subUrls, urlVersion, hierarchyBasePath, clipPaths[i], Laya3D.ANIMATIONCLIP);
  32291. }
  32292. break;
  32293. case "PhysicsCollider":
  32294. case "Rigidbody3D":
  32295. case "CharacterController":
  32296. var shapes = component.shapes;
  32297. for (i = 0; i < shapes.length; i++) {
  32298. var shape = shapes[i];
  32299. if (shape.type === "MeshColliderShape") {
  32300. var mesh = shape.mesh;
  32301. (mesh) && (shape.mesh = Laya3D._addHierarchyInnerUrls(firstLevelUrls, subUrls, urlVersion, hierarchyBasePath, mesh, Laya3D.MESH));
  32302. }
  32303. }
  32304. break;
  32305. }
  32306. }
  32307. }
  32308. var children = node.child;
  32309. for (i = 0, n = children.length; i < n; i++)
  32310. Laya3D._getSprite3DHierarchyInnerUrls(children[i], firstLevelUrls, secondLevelUrls, thirdLevelUrls, fourthLelUrls, subUrls, urlVersion, hierarchyBasePath);
  32311. }
  32312. static _loadHierarchy(loader) {
  32313. loader._originType = loader.type;
  32314. loader.on(Laya.Event.LOADED, null, Laya3D._onHierarchylhLoaded, [loader]);
  32315. loader.load(loader.url, Laya.Loader.JSON, false, null, true);
  32316. }
  32317. static _onHierarchylhLoaded(loader, lhData) {
  32318. var url = loader.url;
  32319. var urlVersion = Utils3D.getURLVerion(url);
  32320. var hierarchyBasePath = Laya.URL.getPath(url);
  32321. var firstLevUrls = [];
  32322. var secondLevUrls = [];
  32323. var thirdLevUrls = [];
  32324. var forthLevUrls = [];
  32325. var subUrls = [];
  32326. Laya3D._getSprite3DHierarchyInnerUrls(lhData.data, firstLevUrls, secondLevUrls, thirdLevUrls, forthLevUrls, subUrls, urlVersion, hierarchyBasePath);
  32327. var urlCount = firstLevUrls.length + secondLevUrls.length + forthLevUrls.length;
  32328. var totalProcessCount = urlCount + 1;
  32329. var weight = 1 / totalProcessCount;
  32330. Laya3D._onProcessChange(loader, 0, weight, 1.0);
  32331. if (forthLevUrls.length > 0) {
  32332. var processCeil = urlCount / totalProcessCount;
  32333. var processHandler = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, weight, processCeil], false);
  32334. Laya3D._innerFourthLevelLoaderManager._create(forthLevUrls, false, Laya.Handler.create(null, Laya3D._onHierarchyInnerForthLevResouLoaded, [loader, processHandler, lhData, subUrls, firstLevUrls, secondLevUrls, thirdLevUrls, weight + processCeil * forthLevUrls.length, processCeil]), processHandler, null, null, null, 1, true);
  32335. }
  32336. else {
  32337. Laya3D._onHierarchyInnerForthLevResouLoaded(loader, null, lhData, subUrls, firstLevUrls, secondLevUrls, thirdLevUrls, weight, processCeil);
  32338. }
  32339. }
  32340. static _onHierarchyInnerForthLevResouLoaded(loader, processHandler, lhData, subUrls, firstLevUrls, secondLevUrls, thirdLevUrls, processOffset, processCeil) {
  32341. (processHandler) && (processHandler.recover());
  32342. if (thirdLevUrls.length > 0) {
  32343. var process = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, processOffset, processCeil], false);
  32344. Laya3D._innerThirdLevelLoaderManager._create(thirdLevUrls, false, Laya.Handler.create(null, Laya3D._onHierarchyInnerThirdLevResouLoaded, [loader, process, lhData, subUrls, firstLevUrls, secondLevUrls, processOffset + processCeil * secondLevUrls.length, processCeil]), processHandler, null, null, null, 1, true);
  32345. }
  32346. else {
  32347. Laya3D._onHierarchyInnerThirdLevResouLoaded(loader, null, lhData, subUrls, firstLevUrls, secondLevUrls, processOffset, processCeil);
  32348. }
  32349. }
  32350. static _onHierarchyInnerThirdLevResouLoaded(loader, processHandler, lhData, subUrls, firstLevUrls, secondLevUrls, processOffset, processCeil) {
  32351. (processHandler) && (processHandler.recover());
  32352. if (secondLevUrls.length > 0) {
  32353. var process = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, processOffset, processCeil], false);
  32354. Laya3D._innerSecondLevelLoaderManager._create(secondLevUrls, false, Laya.Handler.create(null, Laya3D._onHierarchyInnerSecondLevResouLoaded, [loader, process, lhData, subUrls, firstLevUrls, processOffset + processCeil * secondLevUrls.length, processCeil]), processHandler, null, null, null, 1, true);
  32355. }
  32356. else {
  32357. Laya3D._onHierarchyInnerSecondLevResouLoaded(loader, null, lhData, subUrls, firstLevUrls, processOffset, processCeil);
  32358. }
  32359. }
  32360. static _onHierarchyInnerSecondLevResouLoaded(loader, processHandler, lhData, subUrls, firstLevUrls, processOffset, processCeil) {
  32361. (processHandler) && (processHandler.recover());
  32362. if (firstLevUrls.length > 0) {
  32363. var process = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, processOffset, processCeil], false);
  32364. Laya3D._innerFirstLevelLoaderManager._create(firstLevUrls, false, Laya.Handler.create(null, Laya3D._onHierarchyInnerFirstLevResouLoaded, [loader, process, lhData, subUrls]), processHandler, null, null, null, 1, true);
  32365. }
  32366. else {
  32367. Laya3D._onHierarchyInnerFirstLevResouLoaded(loader, null, lhData, subUrls);
  32368. }
  32369. }
  32370. static _onHierarchyInnerFirstLevResouLoaded(loader, processHandler, lhData, subUrls) {
  32371. (processHandler) && (processHandler.recover());
  32372. loader._cache = loader._createCache;
  32373. var item = lhData.data.type === "Scene3D" ? Scene3DUtils._parseScene(lhData, loader._propertyParams, loader._constructParams) : Scene3DUtils._parse(lhData, loader._propertyParams, loader._constructParams);
  32374. Laya3D._endLoad(loader, item, subUrls);
  32375. }
  32376. static _loadMesh(loader) {
  32377. loader.on(Laya.Event.LOADED, null, Laya3D._onMeshLmLoaded, [loader]);
  32378. loader.load(loader.url, Laya.Loader.BUFFER, false, null, true);
  32379. }
  32380. static _onMeshLmLoaded(loader, lmData) {
  32381. loader._cache = loader._createCache;
  32382. var mesh = MeshReader._parse(lmData, loader._propertyParams, loader._constructParams);
  32383. Laya3D._endLoad(loader, mesh);
  32384. }
  32385. static _loadMaterial(loader) {
  32386. loader.on(Laya.Event.LOADED, null, Laya3D._onMaterilLmatLoaded, [loader]);
  32387. loader.load(loader.url, Laya.Loader.JSON, false, null, true);
  32388. }
  32389. static _onMaterilLmatLoaded(loader, lmatData) {
  32390. var url = loader.url;
  32391. var urlVersion = Utils3D.getURLVerion(url);
  32392. var materialBasePath = Laya.URL.getPath(url);
  32393. var urls = [];
  32394. var subUrls = [];
  32395. var customProps = lmatData.customProps;
  32396. var formatSubUrl;
  32397. var version = lmatData.version;
  32398. switch (version) {
  32399. case "LAYAMATERIAL:01":
  32400. case "LAYAMATERIAL:02":
  32401. var i, n;
  32402. var textures = lmatData.props.textures;
  32403. if (textures) {
  32404. for (i = 0, n = textures.length; i < n; i++) {
  32405. var tex2D = textures[i];
  32406. var tex2DPath = tex2D.path;
  32407. if (tex2DPath) {
  32408. formatSubUrl = Laya3D.formatRelativePath(materialBasePath, tex2DPath);
  32409. (urlVersion) && (formatSubUrl = formatSubUrl + urlVersion);
  32410. urls.push({ url: formatSubUrl, constructParams: tex2D.constructParams, propertyParams: tex2D.propertyParams });
  32411. subUrls.push(formatSubUrl);
  32412. tex2D.path = formatSubUrl;
  32413. }
  32414. }
  32415. }
  32416. break;
  32417. default:
  32418. throw new Error("Laya3D:unkonwn version.");
  32419. }
  32420. var urlCount = urls.length;
  32421. var totalProcessCount = urlCount + 1;
  32422. var lmatWeight = 1 / totalProcessCount;
  32423. Laya3D._onProcessChange(loader, 0, lmatWeight, 1.0);
  32424. if (urlCount > 0) {
  32425. var processHandler = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, lmatWeight, urlCount / totalProcessCount], false);
  32426. Laya3D._innerFourthLevelLoaderManager._create(urls, false, Laya.Handler.create(null, Laya3D._onMateialTexturesLoaded, [loader, processHandler, lmatData, subUrls]), processHandler, null, null, null, 1, true);
  32427. }
  32428. else {
  32429. Laya3D._onMateialTexturesLoaded(loader, null, lmatData, null);
  32430. }
  32431. }
  32432. static _onMateialTexturesLoaded(loader, processHandler, lmatData, subUrls) {
  32433. loader._cache = loader._createCache;
  32434. var mat = Material._parse(lmatData, loader._propertyParams, loader._constructParams);
  32435. Laya3D._endLoad(loader, mat, subUrls);
  32436. (processHandler) && (processHandler.recover());
  32437. }
  32438. static _loadAvatar(loader) {
  32439. loader.on(Laya.Event.LOADED, null, function (data) {
  32440. loader._cache = loader._createCache;
  32441. var avatar = Avatar._parse(data, loader._propertyParams, loader._constructParams);
  32442. Laya3D._endLoad(loader, avatar);
  32443. });
  32444. loader.load(loader.url, Laya.Loader.JSON, false, null, true);
  32445. }
  32446. static _loadSimpleAnimator(loader) {
  32447. loader.on(Laya.Event.LOADED, null, function (data) {
  32448. loader._cache = loader._createCache;
  32449. var texture = Laya.Texture2D._SimpleAnimatorTextureParse(data, loader._propertyParams, loader._constructParams);
  32450. Laya3D._endLoad(loader, texture);
  32451. });
  32452. loader.load(loader.url, Laya.Loader.BUFFER, false, null, true);
  32453. }
  32454. static _loadAnimationClip(loader) {
  32455. loader.on(Laya.Event.LOADED, null, function (data) {
  32456. loader._cache = loader._createCache;
  32457. var clip = AnimationClip._parse(data);
  32458. Laya3D._endLoad(loader, clip);
  32459. });
  32460. loader.load(loader.url, Laya.Loader.BUFFER, false, null, true);
  32461. }
  32462. static _loadTexture2D(loader) {
  32463. var url = loader.url;
  32464. var index = url.lastIndexOf('.') + 1;
  32465. var verIndex = url.indexOf('?');
  32466. var endIndex = verIndex == -1 ? url.length : verIndex;
  32467. var ext = url.substr(index, endIndex - index);
  32468. var type;
  32469. switch (ext) {
  32470. case "jpg":
  32471. case "jpeg":
  32472. case "bmp":
  32473. case "gif":
  32474. case "png":
  32475. type = "nativeimage";
  32476. break;
  32477. case "dds":
  32478. case "ktx":
  32479. case "pvr":
  32480. type = Laya.Loader.BUFFER;
  32481. break;
  32482. }
  32483. loader.on(Laya.Event.LOADED, null, function (image) {
  32484. loader._cache = loader._createCache;
  32485. var tex = Laya.Texture2D._parse(image, loader._propertyParams, loader._constructParams);
  32486. Laya3D._endLoad(loader, tex);
  32487. });
  32488. loader.load(loader.url, type, false, null, true);
  32489. }
  32490. static _loadTextureCube(loader) {
  32491. loader.on(Laya.Event.LOADED, null, Laya3D._onTextureCubeLtcLoaded, [loader]);
  32492. loader.load(loader.url, Laya.Loader.JSON, false, null, true);
  32493. }
  32494. static _loadTextureCubeBin(loader) {
  32495. loader.on(Laya.Event.LOADED, null, (data) => {
  32496. loader._cache = loader._createCache;
  32497. var byte = new Laya.Byte(data);
  32498. var version = byte.readUTFString();
  32499. if (version !== "LAYATEXTURECUBE:0000")
  32500. throw "Laya3D:unknow version.";
  32501. var format = byte.readUint8();
  32502. var mipCount = byte.getUint8();
  32503. var size = byte.readUint16();
  32504. var filterMode = byte.getUint8();
  32505. var warpModeU = byte.getUint8();
  32506. var warpModev = byte.getUint8();
  32507. var anisoLevel = byte.getUint8();
  32508. var cubemap = new TextureCube(size, format, mipCount > 1 ? true : false);
  32509. cubemap.filterMode = filterMode;
  32510. cubemap.wrapModeU = warpModeU;
  32511. cubemap.wrapModeV = warpModev;
  32512. cubemap.anisoLevel = anisoLevel;
  32513. var pos = byte.pos;
  32514. var mipSize = size;
  32515. for (var i = 0; i < mipCount; i++) {
  32516. var uint8Arrays = new Array(6);
  32517. var mipPixelLength = mipSize * mipSize * cubemap._getFormatByteCount();
  32518. for (var j = 0; j < 6; j++) {
  32519. uint8Arrays[j] = new Uint8Array(data, pos, mipPixelLength);
  32520. pos += mipPixelLength;
  32521. }
  32522. cubemap.setSixSidePixels(uint8Arrays, i);
  32523. mipSize /= 2;
  32524. }
  32525. Laya3D._endLoad(loader, cubemap);
  32526. });
  32527. loader.load(loader.url, Laya.Loader.BUFFER, false, null, true);
  32528. }
  32529. static _onTextureCubeLtcLoaded(loader, ltcData) {
  32530. var ltcBasePath = Laya.URL.getPath(loader.url);
  32531. var urls = [Laya3D.formatRelativePath(ltcBasePath, ltcData.front), Laya3D.formatRelativePath(ltcBasePath, ltcData.back), Laya3D.formatRelativePath(ltcBasePath, ltcData.left), Laya3D.formatRelativePath(ltcBasePath, ltcData.right), Laya3D.formatRelativePath(ltcBasePath, ltcData.up), Laya3D.formatRelativePath(ltcBasePath, ltcData.down)];
  32532. var ltcWeight = 1.0 / 7.0;
  32533. Laya3D._onProcessChange(loader, 0, ltcWeight, 1.0);
  32534. var processHandler = Laya.Handler.create(null, Laya3D._onProcessChange, [loader, ltcWeight, 6 / 7], false);
  32535. Laya3D._innerFourthLevelLoaderManager.load(urls, Laya.Handler.create(null, Laya3D._onTextureCubeImagesLoaded, [loader, urls, processHandler]), processHandler, "nativeimage");
  32536. }
  32537. static _onTextureCubeImagesLoaded(loader, urls, processHandler) {
  32538. var images = new Array(6);
  32539. for (var i = 0; i < 6; i++)
  32540. images[i] = Laya.Loader.getRes(urls[i]);
  32541. loader._cache = loader._createCache;
  32542. var tex = TextureCube._parse(images, loader._propertyParams, loader._constructParams);
  32543. processHandler.recover();
  32544. for (i = 0; i < 6; i++)
  32545. Laya.Loader.clearRes(urls[i]);
  32546. Laya3D._endLoad(loader, tex);
  32547. }
  32548. static _onProcessChange(loader, offset, weight, process) {
  32549. process = offset + process * weight;
  32550. (process < 1.0) && (loader.event(Laya.Event.PROGRESS, process * 2 / 3 + 1 / 3));
  32551. }
  32552. static init(width, height, config = null, compolete = null) {
  32553. if (Laya3D._isInit) {
  32554. compolete && compolete.run();
  32555. return;
  32556. }
  32557. Laya3D._isInit = true;
  32558. (config) && (config.cloneTo(Config3D._config));
  32559. config = Config3D._config;
  32560. FrustumCulling.debugFrustumCulling = config.debugFrustumCulling;
  32561. Laya3D._editerEnvironment = config._editerEnvironment;
  32562. Scene3D.octreeCulling = config.octreeCulling;
  32563. Scene3D.octreeInitialSize = config.octreeInitialSize;
  32564. Scene3D.octreeInitialCenter = config.octreeInitialCenter;
  32565. Scene3D.octreeMinNodeSize = config.octreeMinNodeSize;
  32566. Scene3D.octreeLooseness = config.octreeLooseness;
  32567. var physics3D = window.Physics3D;
  32568. if (physics3D == null || config.isUseCannonPhysicsEngine) {
  32569. Physics3D._enablePhysics = false;
  32570. Laya3D.__init__(width, height, config);
  32571. compolete && compolete.run();
  32572. }
  32573. else {
  32574. Physics3D._enablePhysics = true;
  32575. physics3D(config.defaultPhysicsMemory * 16, BulletInteractive._interactive).then(function () {
  32576. Laya3D.__init__(width, height, config);
  32577. compolete && compolete.run();
  32578. });
  32579. }
  32580. }
  32581. }
  32582. Laya3D.HIERARCHY = "HIERARCHY";
  32583. Laya3D.MESH = "MESH";
  32584. Laya3D.MATERIAL = "MATERIAL";
  32585. Laya3D.TEXTURE2D = "TEXTURE2D";
  32586. Laya3D.TEXTURECUBE = "TEXTURECUBE";
  32587. Laya3D.TEXTURECUBEBIN = "TEXTURECUBEBIN";
  32588. Laya3D.ANIMATIONCLIP = "ANIMATIONCLIP";
  32589. Laya3D.AVATAR = "AVATAR";
  32590. Laya3D.TERRAINHEIGHTDATA = "TERRAINHEIGHTDATA";
  32591. Laya3D.TERRAINRES = "TERRAIN";
  32592. Laya3D.SIMPLEANIMATORBIN = "SIMPLEANIMATOR";
  32593. Laya3D._innerFirstLevelLoaderManager = new Laya.LoaderManager();
  32594. Laya3D._innerSecondLevelLoaderManager = new Laya.LoaderManager();
  32595. Laya3D._innerThirdLevelLoaderManager = new Laya.LoaderManager();
  32596. Laya3D._innerFourthLevelLoaderManager = new Laya.LoaderManager();
  32597. Laya3D._isInit = false;
  32598. Laya3D._editerEnvironment = false;
  32599. Laya3D.physicsSettings = new PhysicsSettings();
  32600. window.Laya3D = Laya3D;
  32601. class CastShadowList extends SingletonList {
  32602. constructor() {
  32603. super();
  32604. }
  32605. add(element) {
  32606. var index = element._indexInCastShadowList;
  32607. if (index !== -1)
  32608. throw "CastShadowList:element has in CastShadowList.";
  32609. this._add(element);
  32610. element._indexInCastShadowList = this.length++;
  32611. }
  32612. remove(element) {
  32613. var index = element._indexInCastShadowList;
  32614. this.length--;
  32615. if (index !== this.length) {
  32616. var end = this.elements[this.length];
  32617. this.elements[index] = end;
  32618. end._indexInCastShadowList = index;
  32619. }
  32620. element._indexInCastShadowList = -1;
  32621. }
  32622. }
  32623. class AnimatorStateScript {
  32624. constructor() {
  32625. }
  32626. onStateEnter() {
  32627. }
  32628. onStateUpdate() {
  32629. }
  32630. onStateExit() {
  32631. }
  32632. }
  32633. class Script3D extends Laya.Component {
  32634. constructor() {
  32635. super(...arguments);
  32636. this._indexInPool = -1;
  32637. }
  32638. get isSingleton() {
  32639. return false;
  32640. }
  32641. _checkProcessTriggers() {
  32642. var prototype = Script3D.prototype;
  32643. if (this.onTriggerEnter !== prototype.onTriggerEnter)
  32644. return true;
  32645. if (this.onTriggerStay !== prototype.onTriggerStay)
  32646. return true;
  32647. if (this.onTriggerExit !== prototype.onTriggerExit)
  32648. return true;
  32649. return false;
  32650. }
  32651. _checkProcessCollisions() {
  32652. var prototype = Script3D.prototype;
  32653. if (this.onCollisionEnter !== prototype.onCollisionEnter)
  32654. return true;
  32655. if (this.onCollisionStay !== prototype.onCollisionStay)
  32656. return true;
  32657. if (this.onCollisionExit !== prototype.onCollisionExit)
  32658. return true;
  32659. return false;
  32660. }
  32661. _onAwake() {
  32662. this.onAwake();
  32663. if (this.onStart !== Script3D.prototype.onStart)
  32664. Laya.Laya.startTimer.callLater(this, this.onStart);
  32665. }
  32666. _onEnable() {
  32667. this.owner._scene._addScript(this);
  32668. this.onEnable();
  32669. }
  32670. _onDisable() {
  32671. this.owner._scene._removeScript(this);
  32672. this.owner.offAllCaller(this);
  32673. this.onDisable();
  32674. }
  32675. _onDestroy() {
  32676. var scripts = this.owner._scripts;
  32677. scripts.splice(scripts.indexOf(this), 1);
  32678. var sprite = this.owner;
  32679. sprite._needProcessTriggers = false;
  32680. for (var i = 0, n = scripts.length; i < n; i++) {
  32681. if (scripts[i]._checkProcessTriggers()) {
  32682. sprite._needProcessTriggers = true;
  32683. break;
  32684. }
  32685. }
  32686. sprite._needProcessCollisions = false;
  32687. for (i = 0, n = scripts.length; i < n; i++) {
  32688. if (scripts[i]._checkProcessCollisions()) {
  32689. sprite._needProcessCollisions = true;
  32690. break;
  32691. }
  32692. }
  32693. this.onDestroy();
  32694. }
  32695. _isScript() {
  32696. return true;
  32697. }
  32698. _onAdded() {
  32699. var sprite = this.owner;
  32700. var scripts = sprite._scripts;
  32701. scripts || (sprite._scripts = scripts = []);
  32702. scripts.push(this);
  32703. if (!sprite._needProcessCollisions)
  32704. sprite._needProcessCollisions = this._checkProcessCollisions();
  32705. if (!sprite._needProcessTriggers)
  32706. sprite._needProcessTriggers = this._checkProcessTriggers();
  32707. }
  32708. onAwake() {
  32709. }
  32710. onEnable() {
  32711. }
  32712. onStart() {
  32713. }
  32714. onTriggerEnter(other) {
  32715. }
  32716. onTriggerStay(other) {
  32717. }
  32718. onTriggerExit(other) {
  32719. }
  32720. onCollisionEnter(collision) {
  32721. }
  32722. onCollisionStay(collision) {
  32723. }
  32724. onCollisionExit(collision) {
  32725. }
  32726. onJointBreak() {
  32727. }
  32728. onMouseDown() {
  32729. }
  32730. onMouseDrag() {
  32731. }
  32732. onMouseClick() {
  32733. }
  32734. onMouseUp() {
  32735. }
  32736. onMouseEnter() {
  32737. }
  32738. onMouseOver() {
  32739. }
  32740. onMouseOut() {
  32741. }
  32742. onUpdate() {
  32743. }
  32744. onLateUpdate() {
  32745. }
  32746. onPreRender() {
  32747. }
  32748. onPostRender() {
  32749. }
  32750. onDisable() {
  32751. }
  32752. onDestroy() {
  32753. }
  32754. }
  32755. class HeightMap {
  32756. constructor(width, height, minHeight, maxHeight) {
  32757. this._datas = [];
  32758. this._w = width;
  32759. this._h = height;
  32760. this._minHeight = minHeight;
  32761. this._maxHeight = maxHeight;
  32762. }
  32763. static creatFromMesh(mesh, width, height, outCellSize) {
  32764. var vertices = [];
  32765. var indexs = [];
  32766. var submesheCount = mesh.subMeshCount;
  32767. for (var i = 0; i < submesheCount; i++) {
  32768. var subMesh = mesh.getSubMesh(i);
  32769. var vertexBuffer = subMesh._vertexBuffer;
  32770. var verts = vertexBuffer.getFloat32Data();
  32771. var subMeshVertices = [];
  32772. for (var j = 0; j < verts.length; j += vertexBuffer.vertexDeclaration.vertexStride / 4) {
  32773. var position = new Vector3(verts[j + 0], verts[j + 1], verts[j + 2]);
  32774. subMeshVertices.push(position);
  32775. }
  32776. vertices.push(subMeshVertices);
  32777. var ib = subMesh._indexBuffer;
  32778. indexs.push(ib.getData());
  32779. }
  32780. var bounds = mesh.bounds;
  32781. var minX = bounds.getMin().x;
  32782. var minZ = bounds.getMin().z;
  32783. var maxX = bounds.getMax().x;
  32784. var maxZ = bounds.getMax().z;
  32785. var minY = bounds.getMin().y;
  32786. var maxY = bounds.getMax().y;
  32787. var widthSize = maxX - minX;
  32788. var heightSize = maxZ - minZ;
  32789. var cellWidth = outCellSize.x = widthSize / (width - 1);
  32790. var cellHeight = outCellSize.y = heightSize / (height - 1);
  32791. var heightMap = new HeightMap(width, height, minY, maxY);
  32792. var ray = HeightMap._tempRay;
  32793. var rayDir = ray.direction;
  32794. rayDir.x = 0;
  32795. rayDir.y = -1;
  32796. rayDir.z = 0;
  32797. const heightOffset = 0.1;
  32798. var rayY = maxY + heightOffset;
  32799. ray.origin.y = rayY;
  32800. for (var h = 0; h < height; h++) {
  32801. var posZ = minZ + h * cellHeight;
  32802. heightMap._datas[h] = [];
  32803. for (var w = 0; w < width; w++) {
  32804. var posX = minX + w * cellWidth;
  32805. var rayOri = ray.origin;
  32806. rayOri.x = posX;
  32807. rayOri.z = posZ;
  32808. var closestIntersection = HeightMap._getPosition(ray, vertices, indexs);
  32809. heightMap._datas[h][w] = (closestIntersection === Number.MAX_VALUE) ? NaN : rayY - closestIntersection;
  32810. }
  32811. }
  32812. return heightMap;
  32813. }
  32814. static createFromImage(texture, minHeight, maxHeight) {
  32815. var textureWidth = texture.width;
  32816. var textureHeight = texture.height;
  32817. var heightMap = new HeightMap(textureWidth, textureHeight, minHeight, maxHeight);
  32818. var compressionRatio = (maxHeight - minHeight) / 254;
  32819. var pixelsInfo = texture.getPixels();
  32820. var index = 0;
  32821. for (var h = 0; h < textureHeight; h++) {
  32822. var colDatas = heightMap._datas[h] = [];
  32823. for (var w = 0; w < textureWidth; w++) {
  32824. var r = pixelsInfo[index++];
  32825. var g = pixelsInfo[index++];
  32826. var b = pixelsInfo[index++];
  32827. var a = pixelsInfo[index++];
  32828. if (r == 255 && g == 255 && b == 255 && a == 255)
  32829. colDatas[w] = NaN;
  32830. else {
  32831. colDatas[w] = (r + g + b) / 3 * compressionRatio + minHeight;
  32832. }
  32833. }
  32834. }
  32835. return heightMap;
  32836. }
  32837. static _getPosition(ray, vertices, indexs) {
  32838. var closestIntersection = Number.MAX_VALUE;
  32839. for (var i = 0; i < vertices.length; i++) {
  32840. var subMeshVertices = vertices[i];
  32841. var subMeshIndexes = indexs[i];
  32842. for (var j = 0; j < subMeshIndexes.length; j += 3) {
  32843. var vertex1 = subMeshVertices[subMeshIndexes[j + 0]];
  32844. var vertex2 = subMeshVertices[subMeshIndexes[j + 1]];
  32845. var vertex3 = subMeshVertices[subMeshIndexes[j + 2]];
  32846. var intersection = Picker.rayIntersectsTriangle(ray, vertex1, vertex2, vertex3);
  32847. if (!isNaN(intersection) && intersection < closestIntersection) {
  32848. closestIntersection = intersection;
  32849. }
  32850. }
  32851. }
  32852. return closestIntersection;
  32853. }
  32854. get width() {
  32855. return this._w;
  32856. }
  32857. get height() {
  32858. return this._h;
  32859. }
  32860. get maxHeight() {
  32861. return this._maxHeight;
  32862. }
  32863. get minHeight() {
  32864. return this._minHeight;
  32865. }
  32866. _inBounds(row, col) {
  32867. return row >= 0 && row < this._h && col >= 0 && col < this._w;
  32868. }
  32869. getHeight(row, col) {
  32870. if (this._inBounds(row, col))
  32871. return this._datas[row][col];
  32872. else
  32873. return NaN;
  32874. }
  32875. }
  32876. HeightMap._tempRay = new Ray(new Vector3(), new Vector3());
  32877. class MeshTerrainSprite3D extends MeshSprite3D {
  32878. constructor(mesh, heightMap, name = null) {
  32879. super(mesh, name);
  32880. this._heightMap = heightMap;
  32881. this._cellSize = new Vector2();
  32882. }
  32883. static createFromMesh(mesh, heightMapWidth, heightMapHeight, name = null) {
  32884. var meshTerrainSprite3D = new MeshTerrainSprite3D(mesh, null, name);
  32885. meshTerrainSprite3D._initCreateFromMesh(heightMapWidth, heightMapHeight);
  32886. return meshTerrainSprite3D;
  32887. }
  32888. static createFromMeshAndHeightMap(mesh, texture, minHeight, maxHeight, name = null) {
  32889. var meshTerrainSprite3D = new MeshTerrainSprite3D(mesh, null, name);
  32890. meshTerrainSprite3D._initCreateFromMeshHeightMap(texture, minHeight, maxHeight);
  32891. return meshTerrainSprite3D;
  32892. }
  32893. get minX() {
  32894. var worldMat = this.transform.worldMatrix;
  32895. var worldMatE = worldMat.elements;
  32896. return this._minX * this._getScaleX() + worldMatE[12];
  32897. }
  32898. get minZ() {
  32899. var worldMat = this.transform.worldMatrix;
  32900. var worldMatE = worldMat.elements;
  32901. return this._minZ * this._getScaleZ() + worldMatE[14];
  32902. }
  32903. get width() {
  32904. return (this._heightMap.width - 1) * this._cellSize.x * this._getScaleX();
  32905. }
  32906. get depth() {
  32907. return (this._heightMap.height - 1) * this._cellSize.y * this._getScaleZ();
  32908. }
  32909. _disableRotation() {
  32910. var rotation = this.transform.rotation;
  32911. rotation.x = 0;
  32912. rotation.y = 0;
  32913. rotation.z = 0;
  32914. rotation.w = 1;
  32915. this.transform.rotation = rotation;
  32916. }
  32917. _getScaleX() {
  32918. var worldMat = this.transform.worldMatrix;
  32919. var worldMatE = worldMat.elements;
  32920. var m11 = worldMatE[0];
  32921. var m12 = worldMatE[1];
  32922. var m13 = worldMatE[2];
  32923. return Math.sqrt((m11 * m11) + (m12 * m12) + (m13 * m13));
  32924. }
  32925. _getScaleZ() {
  32926. var worldMat = this.transform.worldMatrix;
  32927. var worldMatE = worldMat.elements;
  32928. var m31 = worldMatE[8];
  32929. var m32 = worldMatE[9];
  32930. var m33 = worldMatE[10];
  32931. return Math.sqrt((m31 * m31) + (m32 * m32) + (m33 * m33));
  32932. }
  32933. _initCreateFromMesh(heightMapWidth, heightMapHeight) {
  32934. this._heightMap = HeightMap.creatFromMesh(this.meshFilter.sharedMesh, heightMapWidth, heightMapHeight, this._cellSize);
  32935. var boundingBox = this.meshFilter.sharedMesh.bounds;
  32936. var min = boundingBox.getMin();
  32937. var max = boundingBox.getMax();
  32938. this._minX = min.x;
  32939. this._minZ = min.z;
  32940. }
  32941. _initCreateFromMeshHeightMap(texture, minHeight, maxHeight) {
  32942. var boundingBox = this.meshFilter.sharedMesh.bounds;
  32943. this._heightMap = HeightMap.createFromImage(texture, minHeight, maxHeight);
  32944. this._computeCellSize(boundingBox);
  32945. var min = boundingBox.getMin();
  32946. var max = boundingBox.getMax();
  32947. this._minX = min.x;
  32948. this._minZ = min.z;
  32949. }
  32950. _computeCellSize(boundingBox) {
  32951. var min = boundingBox.getMin();
  32952. var max = boundingBox.getMax();
  32953. var minX = min.x;
  32954. var minZ = min.z;
  32955. var maxX = max.x;
  32956. var maxZ = max.z;
  32957. var widthSize = maxX - minX;
  32958. var heightSize = maxZ - minZ;
  32959. this._cellSize.x = widthSize / (this._heightMap.width - 1);
  32960. this._cellSize.y = heightSize / (this._heightMap.height - 1);
  32961. }
  32962. _update(state) {
  32963. this._disableRotation();
  32964. }
  32965. getHeight(x, z) {
  32966. MeshTerrainSprite3D._tempVector3.x = x;
  32967. MeshTerrainSprite3D._tempVector3.y = 0;
  32968. MeshTerrainSprite3D._tempVector3.z = z;
  32969. this._disableRotation();
  32970. var worldMat = this.transform.worldMatrix;
  32971. worldMat.invert(MeshTerrainSprite3D._tempMatrix4x4);
  32972. Vector3.transformCoordinate(MeshTerrainSprite3D._tempVector3, MeshTerrainSprite3D._tempMatrix4x4, MeshTerrainSprite3D._tempVector3);
  32973. x = MeshTerrainSprite3D._tempVector3.x;
  32974. z = MeshTerrainSprite3D._tempVector3.z;
  32975. var c = (x - this._minX) / this._cellSize.x;
  32976. var d = (z - this._minZ) / this._cellSize.y;
  32977. var row = Math.floor(d);
  32978. var col = Math.floor(c);
  32979. var s = c - col;
  32980. var t = d - row;
  32981. var uy;
  32982. var vy;
  32983. var worldMatE = worldMat.elements;
  32984. var m21 = worldMatE[4];
  32985. var m22 = worldMatE[5];
  32986. var m23 = worldMatE[6];
  32987. var scaleY = Math.sqrt((m21 * m21) + (m22 * m22) + (m23 * m23));
  32988. var translateY = worldMatE[13];
  32989. var h01 = this._heightMap.getHeight(row, col + 1);
  32990. var h10 = this._heightMap.getHeight((row + 1), col);
  32991. if (isNaN(h01) || isNaN(h10))
  32992. return NaN;
  32993. if (s + t <= 1.0) {
  32994. var h00 = this._heightMap.getHeight(row, col);
  32995. if (isNaN(h00))
  32996. return NaN;
  32997. uy = h01 - h00;
  32998. vy = h10 - h00;
  32999. return (h00 + s * uy + t * vy) * scaleY + translateY;
  33000. }
  33001. else {
  33002. var h11 = this._heightMap.getHeight((row + 1), col + 1);
  33003. if (isNaN(h11))
  33004. return NaN;
  33005. uy = h10 - h11;
  33006. vy = h01 - h11;
  33007. return (h11 + (1.0 - s) * uy + (1.0 - t) * vy) * scaleY + translateY;
  33008. }
  33009. }
  33010. }
  33011. MeshTerrainSprite3D._tempVector3 = new Vector3();
  33012. MeshTerrainSprite3D._tempMatrix4x4 = new Matrix4x4();
  33013. class GradientDataVector2 {
  33014. constructor() {
  33015. this._currentLength = 0;
  33016. this._elements = new Float32Array(12);
  33017. }
  33018. get gradientCount() {
  33019. return this._currentLength / 3;
  33020. }
  33021. add(key, value) {
  33022. if (this._currentLength < 8) {
  33023. if ((this._currentLength === 6) && ((key !== 1))) {
  33024. key = 1;
  33025. console.log("GradientDataVector2 warning:the forth key is be force set to 1.");
  33026. }
  33027. this._elements[this._currentLength++] = key;
  33028. this._elements[this._currentLength++] = value.x;
  33029. this._elements[this._currentLength++] = value.y;
  33030. }
  33031. else {
  33032. console.log("GradientDataVector2 warning:data count must lessEqual than 4");
  33033. }
  33034. }
  33035. cloneTo(destObject) {
  33036. var destGradientDataVector2 = destObject;
  33037. destGradientDataVector2._currentLength = this._currentLength;
  33038. var destElements = destGradientDataVector2._elements;
  33039. for (var i = 0, n = this._elements.length; i < n; i++) {
  33040. destElements[i] = this._elements[i];
  33041. }
  33042. }
  33043. clone() {
  33044. var destGradientDataVector2 = new GradientDataVector2();
  33045. this.cloneTo(destGradientDataVector2);
  33046. return destGradientDataVector2;
  33047. }
  33048. }
  33049. class PixelLineData {
  33050. constructor() {
  33051. this.startPosition = new Vector3();
  33052. this.endPosition = new Vector3();
  33053. this.startColor = new Color();
  33054. this.endColor = new Color();
  33055. }
  33056. cloneTo(destObject) {
  33057. this.startPosition.cloneTo(destObject.startPosition);
  33058. this.endPosition.cloneTo(destObject.endPosition);
  33059. this.startColor.cloneTo(destObject.startColor);
  33060. this.endColor.cloneTo(destObject.endColor);
  33061. }
  33062. }
  33063. class PostProcessEffect {
  33064. constructor() {
  33065. }
  33066. render(context) {
  33067. }
  33068. }
  33069. class BloomEffect extends PostProcessEffect {
  33070. constructor() {
  33071. super();
  33072. this._shader = null;
  33073. this._shaderData = new ShaderData();
  33074. this._linearColor = new Color();
  33075. this._bloomTextureTexelSize = new Vector4();
  33076. this._shaderThreshold = new Vector4();
  33077. this._shaderParams = new Vector4();
  33078. this._pyramid = null;
  33079. this._intensity = 0.0;
  33080. this._threshold = 1.0;
  33081. this._softKnee = 0.5;
  33082. this._diffusion = 7.0;
  33083. this._anamorphicRatio = 0.0;
  33084. this._dirtIntensity = 0.0;
  33085. this._shaderSetting = new Vector4();
  33086. this._dirtTileOffset = new Vector4();
  33087. this.clamp = 65472.0;
  33088. this.color = new Color(1.0, 1.0, 1.0, 1.0);
  33089. this.fastMode = false;
  33090. this.dirtTexture = null;
  33091. this._shader = Shader3D.find("PostProcessBloom");
  33092. this._pyramid = new Array(BloomEffect.MAXPYRAMIDSIZE * 2);
  33093. }
  33094. get intensity() {
  33095. return this._intensity;
  33096. }
  33097. set intensity(value) {
  33098. this._intensity = Math.max(value, 0.0);
  33099. }
  33100. get threshold() {
  33101. return this._threshold;
  33102. }
  33103. set threshold(value) {
  33104. this._threshold = Math.max(value, 0.0);
  33105. }
  33106. get softKnee() {
  33107. return this._softKnee;
  33108. }
  33109. set softKnee(value) {
  33110. this._softKnee = Math.min(Math.max(value, 0.0), 1.0);
  33111. }
  33112. get diffusion() {
  33113. return this._diffusion;
  33114. }
  33115. set diffusion(value) {
  33116. this._diffusion = Math.min(Math.max(value, 1), 10);
  33117. }
  33118. get anamorphicRatio() {
  33119. return this._anamorphicRatio;
  33120. }
  33121. set anamorphicRatio(value) {
  33122. this._anamorphicRatio = Math.min(Math.max(value, -1.0), 1.0);
  33123. }
  33124. get dirtIntensity() {
  33125. return this._dirtIntensity;
  33126. }
  33127. set dirtIntensity(value) {
  33128. this._dirtIntensity = Math.max(value, 0.0);
  33129. }
  33130. render(context) {
  33131. var cmd = context.command;
  33132. var viewport = context.camera.viewport;
  33133. this._shaderData.setTexture(BloomEffect.SHADERVALUE_AUTOEXPOSURETEX, Laya.Texture2D.whiteTexture);
  33134. var ratio = this._anamorphicRatio;
  33135. var rw = ratio < 0 ? -ratio : 0;
  33136. var rh = ratio > 0 ? ratio : 0;
  33137. var tw = Math.floor(viewport.width / (2 - rw));
  33138. var th = Math.floor(viewport.height / (2 - rh));
  33139. var s = Math.max(tw, th);
  33140. var logs;
  33141. logs = Math.log2(s) + this._diffusion - 10;
  33142. var logsInt = Math.floor(logs);
  33143. var iterations = Math.min(Math.max(logsInt, 1), BloomEffect.MAXPYRAMIDSIZE);
  33144. var sampleScale = 0.5 + logs - logsInt;
  33145. this._shaderData.setNumber(BloomEffect.SHADERVALUE_SAMPLESCALE, sampleScale);
  33146. var lthresh = Color.gammaToLinearSpace(this.threshold);
  33147. var knee = lthresh * this._softKnee + 1e-5;
  33148. this._shaderThreshold.setValue(lthresh, lthresh - knee, knee * 2, 0.25 / knee);
  33149. this._shaderData.setVector(BloomEffect.SHADERVALUE_THRESHOLD, this._shaderThreshold);
  33150. var lclamp = Color.gammaToLinearSpace(this.clamp);
  33151. this._shaderParams.setValue(lclamp, 0, 0, 0);
  33152. this._shaderData.setVector(BloomEffect.SHADERVALUE_PARAMS, this._shaderParams);
  33153. var qualityOffset = this.fastMode ? 1 : 0;
  33154. var lastDownTexture = context.source;
  33155. for (var i = 0; i < iterations; i++) {
  33156. var downIndex = i * 2;
  33157. var upIndex = downIndex + 1;
  33158. var subShader = i == 0 ? BloomEffect.SUBSHADER_PREFILTER13 + qualityOffset : BloomEffect.SUBSHADER_DOWNSAMPLE13 + qualityOffset;
  33159. var mipDownTexture = RenderTexture.createFromPool(tw, th, Laya.RenderTextureFormat.R8G8B8, Laya.RenderTextureDepthFormat.DEPTHSTENCIL_NONE);
  33160. mipDownTexture.filterMode = Laya.FilterMode.Bilinear;
  33161. this._pyramid[downIndex] = mipDownTexture;
  33162. if (i !== iterations - 1) {
  33163. var mipUpTexture = RenderTexture.createFromPool(tw, th, Laya.RenderTextureFormat.R8G8B8, Laya.RenderTextureDepthFormat.DEPTHSTENCIL_NONE);
  33164. mipUpTexture.filterMode = Laya.FilterMode.Bilinear;
  33165. this._pyramid[upIndex] = mipUpTexture;
  33166. }
  33167. cmd.blitScreenTriangle(lastDownTexture, mipDownTexture, null, this._shader, this._shaderData, subShader);
  33168. lastDownTexture = mipDownTexture;
  33169. tw = Math.max(Math.floor(tw / 2), 1);
  33170. th = Math.max(Math.floor(th / 2), 1);
  33171. }
  33172. var lastUpTexture = this._pyramid[(iterations - 1) * 2];
  33173. for (i = iterations - 2; i >= 0; i--) {
  33174. downIndex = i * 2;
  33175. upIndex = downIndex + 1;
  33176. mipDownTexture = this._pyramid[downIndex];
  33177. mipUpTexture = this._pyramid[upIndex];
  33178. cmd.setShaderDataTexture(this._shaderData, BloomEffect.SHADERVALUE_BLOOMTEX, mipDownTexture);
  33179. cmd.blitScreenTriangle(lastUpTexture, mipUpTexture, null, this._shader, this._shaderData, BloomEffect.SUBSHADER_UPSAMPLETENT + qualityOffset);
  33180. lastUpTexture = mipUpTexture;
  33181. }
  33182. var linearColor = this._linearColor;
  33183. this.color.toLinear(linearColor);
  33184. var intensity = Math.pow(2, this._intensity / 10.0) - 1.0;
  33185. var shaderSettings = this._shaderSetting;
  33186. this._shaderSetting.setValue(sampleScale, intensity, this._dirtIntensity, iterations);
  33187. var dirtTexture = this.dirtTexture ? this.dirtTexture : Laya.Texture2D.blackTexture;
  33188. var dirtRatio = dirtTexture.width / dirtTexture.height;
  33189. var screenRatio = viewport.width / viewport.height;
  33190. var dirtTileOffset = this._dirtTileOffset;
  33191. if (dirtRatio > screenRatio)
  33192. dirtTileOffset.setValue(screenRatio / dirtRatio, 1.0, (1.0 - dirtTileOffset.x) * 0.5, 0.0);
  33193. else if (dirtRatio < screenRatio)
  33194. dirtTileOffset.setValue(1.0, dirtRatio / screenRatio, 0.0, (1.0 - dirtTileOffset.y) * 0.5);
  33195. var compositeShaderData = context.compositeShaderData;
  33196. if (this.fastMode)
  33197. compositeShaderData.addDefine(PostProcess.SHADERDEFINE_BLOOM_LOW);
  33198. else
  33199. compositeShaderData.addDefine(PostProcess.SHADERDEFINE_BLOOM);
  33200. this._bloomTextureTexelSize.setValue(1.0 / lastUpTexture.width, 1.0 / lastUpTexture.height, lastUpTexture.width, lastUpTexture.height);
  33201. compositeShaderData.setVector(PostProcess.SHADERVALUE_BLOOM_DIRTTILEOFFSET, dirtTileOffset);
  33202. compositeShaderData.setVector(PostProcess.SHADERVALUE_BLOOM_SETTINGS, shaderSettings);
  33203. compositeShaderData.setVector(PostProcess.SHADERVALUE_BLOOM_COLOR, new Vector4(linearColor.r, linearColor.g, linearColor.b, linearColor.a));
  33204. compositeShaderData.setTexture(PostProcess.SHADERVALUE_BLOOM_DIRTTEX, dirtTexture);
  33205. compositeShaderData.setTexture(PostProcess.SHADERVALUE_BLOOMTEX, lastUpTexture);
  33206. compositeShaderData.setVector(PostProcess.SHADERVALUE_BLOOMTEX_TEXELSIZE, this._bloomTextureTexelSize);
  33207. for (i = 0; i < iterations; i++) {
  33208. downIndex = i * 2;
  33209. upIndex = downIndex + 1;
  33210. RenderTexture.recoverToPool(this._pyramid[downIndex]);
  33211. (i !== 0 && i !== iterations - 1) && (RenderTexture.recoverToPool(this._pyramid[upIndex]));
  33212. }
  33213. context.deferredReleaseTextures.push(lastUpTexture);
  33214. }
  33215. }
  33216. BloomEffect.SHADERVALUE_MAINTEX = Shader3D.propertyNameToID("u_MainTex");
  33217. BloomEffect.SHADERVALUE_AUTOEXPOSURETEX = Shader3D.propertyNameToID("u_AutoExposureTex");
  33218. BloomEffect.SHADERVALUE_SAMPLESCALE = Shader3D.propertyNameToID("u_SampleScale");
  33219. BloomEffect.SHADERVALUE_THRESHOLD = Shader3D.propertyNameToID("u_Threshold");
  33220. BloomEffect.SHADERVALUE_PARAMS = Shader3D.propertyNameToID("u_Params");
  33221. BloomEffect.SHADERVALUE_BLOOMTEX = Shader3D.propertyNameToID("u_BloomTex");
  33222. BloomEffect.SUBSHADER_PREFILTER13 = 0;
  33223. BloomEffect.SUBSHADER_PREFILTER4 = 1;
  33224. BloomEffect.SUBSHADER_DOWNSAMPLE13 = 2;
  33225. BloomEffect.SUBSHADER_DOWNSAMPLE4 = 3;
  33226. BloomEffect.SUBSHADER_UPSAMPLETENT = 4;
  33227. BloomEffect.SUBSHADER_UPSAMPLEBOX = 5;
  33228. BloomEffect.MAXPYRAMIDSIZE = 16;
  33229. class ConchVector4 {
  33230. constructor(x = 0, y = 0, z = 0, w = 0) {
  33231. var v = this.elements = new Float32Array(4);
  33232. v[0] = x;
  33233. v[1] = y;
  33234. v[2] = z;
  33235. v[3] = w;
  33236. }
  33237. get x() {
  33238. return this.elements[0];
  33239. }
  33240. set x(value) {
  33241. this.elements[0] = value;
  33242. }
  33243. get y() {
  33244. return this.elements[1];
  33245. }
  33246. set y(value) {
  33247. this.elements[1] = value;
  33248. }
  33249. get z() {
  33250. return this.elements[2];
  33251. }
  33252. set z(value) {
  33253. this.elements[2] = value;
  33254. }
  33255. get w() {
  33256. return this.elements[3];
  33257. }
  33258. set w(value) {
  33259. this.elements[3] = value;
  33260. }
  33261. fromArray(array, offset = 0) {
  33262. this.elements[0] = array[offset + 0];
  33263. this.elements[1] = array[offset + 1];
  33264. this.elements[2] = array[offset + 2];
  33265. this.elements[3] = array[offset + 3];
  33266. }
  33267. cloneTo(destObject) {
  33268. var destVector4 = destObject;
  33269. var destE = destVector4.elements;
  33270. var s = this.elements;
  33271. destE[0] = s[0];
  33272. destE[1] = s[1];
  33273. destE[2] = s[2];
  33274. destE[3] = s[3];
  33275. }
  33276. clone() {
  33277. var destVector4 = new ConchVector4();
  33278. this.cloneTo(destVector4);
  33279. return destVector4;
  33280. }
  33281. static lerp(a, b, t, out) {
  33282. var e = out.elements;
  33283. var f = a.elements;
  33284. var g = b.elements;
  33285. var ax = f[0], ay = f[1], az = f[2], aw = f[3];
  33286. e[0] = ax + t * (g[0] - ax);
  33287. e[1] = ay + t * (g[1] - ay);
  33288. e[2] = az + t * (g[2] - az);
  33289. e[3] = aw + t * (g[3] - aw);
  33290. }
  33291. static transformByM4x4(vector4, m4x4, out) {
  33292. var ve = vector4.elements;
  33293. var vx = ve[0];
  33294. var vy = ve[1];
  33295. var vz = ve[2];
  33296. var vw = ve[3];
  33297. var me = m4x4.elements;
  33298. var oe = out.elements;
  33299. oe[0] = vx * me[0] + vy * me[4] + vz * me[8] + vw * me[12];
  33300. oe[1] = vx * me[1] + vy * me[5] + vz * me[9] + vw * me[13];
  33301. oe[2] = vx * me[2] + vy * me[6] + vz * me[10] + vw * me[14];
  33302. oe[3] = vx * me[3] + vy * me[7] + vz * me[11] + vw * me[15];
  33303. }
  33304. static equals(a, b) {
  33305. var ae = a.elements;
  33306. var be = b.elements;
  33307. return MathUtils3D.nearEqual(Math.abs(ae[0]), Math.abs(be[0])) && MathUtils3D.nearEqual(Math.abs(ae[1]), Math.abs(be[1])) && MathUtils3D.nearEqual(Math.abs(ae[2]), Math.abs(be[2])) && MathUtils3D.nearEqual(Math.abs(ae[3]), Math.abs(be[3]));
  33308. }
  33309. length() {
  33310. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  33311. }
  33312. lengthSquared() {
  33313. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  33314. }
  33315. static normalize(s, out) {
  33316. var se = s.elements;
  33317. var oe = out.elements;
  33318. var len = s.length();
  33319. if (len > 0) {
  33320. oe[0] = se[0] * len;
  33321. oe[1] = se[1] * len;
  33322. oe[2] = se[2] * len;
  33323. oe[3] = se[3] * len;
  33324. }
  33325. }
  33326. static add(a, b, out) {
  33327. var oe = out.elements;
  33328. var ae = a.elements;
  33329. var be = b.elements;
  33330. oe[0] = ae[0] + be[0];
  33331. oe[1] = ae[1] + be[1];
  33332. oe[2] = ae[2] + be[2];
  33333. oe[3] = ae[3] + be[3];
  33334. }
  33335. static subtract(a, b, out) {
  33336. var oe = out.elements;
  33337. var ae = a.elements;
  33338. var be = b.elements;
  33339. oe[0] = ae[0] - be[0];
  33340. oe[1] = ae[1] - be[1];
  33341. oe[2] = ae[2] - be[2];
  33342. oe[3] = ae[3] - be[3];
  33343. }
  33344. static multiply(a, b, out) {
  33345. var oe = out.elements;
  33346. var ae = a.elements;
  33347. var be = b.elements;
  33348. oe[0] = ae[0] * be[0];
  33349. oe[1] = ae[1] * be[1];
  33350. oe[2] = ae[2] * be[2];
  33351. oe[3] = ae[3] * be[3];
  33352. }
  33353. static scale(a, b, out) {
  33354. var oe = out.elements;
  33355. var ae = a.elements;
  33356. oe[0] = ae[0] * b;
  33357. oe[1] = ae[1] * b;
  33358. oe[2] = ae[2] * b;
  33359. oe[3] = ae[3] * b;
  33360. }
  33361. static Clamp(value, min, max, out) {
  33362. var valuee = value.elements;
  33363. var x = valuee[0];
  33364. var y = valuee[1];
  33365. var z = valuee[2];
  33366. var w = valuee[3];
  33367. var mine = min.elements;
  33368. var mineX = mine[0];
  33369. var mineY = mine[1];
  33370. var mineZ = mine[2];
  33371. var mineW = mine[3];
  33372. var maxe = max.elements;
  33373. var maxeX = maxe[0];
  33374. var maxeY = maxe[1];
  33375. var maxeZ = maxe[2];
  33376. var maxeW = maxe[3];
  33377. var oute = out.elements;
  33378. x = (x > maxeX) ? maxeX : x;
  33379. x = (x < mineX) ? mineX : x;
  33380. y = (y > maxeY) ? maxeY : y;
  33381. y = (y < mineY) ? mineY : y;
  33382. z = (z > maxeZ) ? maxeZ : z;
  33383. z = (z < mineZ) ? mineZ : z;
  33384. w = (w > maxeW) ? maxeW : w;
  33385. w = (w < mineW) ? mineW : w;
  33386. oute[0] = x;
  33387. oute[1] = y;
  33388. oute[2] = z;
  33389. oute[3] = w;
  33390. }
  33391. static distanceSquared(value1, value2) {
  33392. var value1e = value1.elements;
  33393. var value2e = value2.elements;
  33394. var x = value1e[0] - value2e[0];
  33395. var y = value1e[1] - value2e[1];
  33396. var z = value1e[2] - value2e[2];
  33397. var w = value1e[3] - value2e[3];
  33398. return (x * x) + (y * y) + (z * z) + (w * w);
  33399. }
  33400. static distance(value1, value2) {
  33401. var value1e = value1.elements;
  33402. var value2e = value2.elements;
  33403. var x = value1e[0] - value2e[0];
  33404. var y = value1e[1] - value2e[1];
  33405. var z = value1e[2] - value2e[2];
  33406. var w = value1e[3] - value2e[3];
  33407. return Math.sqrt((x * x) + (y * y) + (z * z) + (w * w));
  33408. }
  33409. static dot(a, b) {
  33410. var ae = a.elements;
  33411. var be = b.elements;
  33412. var r = (ae[0] * be[0]) + (ae[1] * be[1]) + (ae[2] * be[2]) + (ae[3] * be[3]);
  33413. return r;
  33414. }
  33415. static min(a, b, out) {
  33416. var e = out.elements;
  33417. var f = a.elements;
  33418. var g = b.elements;
  33419. e[0] = Math.min(f[0], g[0]);
  33420. e[1] = Math.min(f[1], g[1]);
  33421. e[2] = Math.min(f[2], g[2]);
  33422. e[3] = Math.min(f[3], g[3]);
  33423. }
  33424. static max(a, b, out) {
  33425. var e = out.elements;
  33426. var f = a.elements;
  33427. var g = b.elements;
  33428. e[0] = Math.max(f[0], g[0]);
  33429. e[1] = Math.max(f[1], g[1]);
  33430. e[2] = Math.max(f[2], g[2]);
  33431. e[3] = Math.max(f[3], g[3]);
  33432. }
  33433. }
  33434. ConchVector4.ZERO = new ConchVector4();
  33435. ConchVector4.ONE = new ConchVector4(1.0, 1.0, 1.0, 1.0);
  33436. ConchVector4.UnitX = new ConchVector4(1.0, 0.0, 0.0, 0.0);
  33437. ConchVector4.UnitY = new ConchVector4(0.0, 1.0, 0.0, 0.0);
  33438. ConchVector4.UnitZ = new ConchVector4(0.0, 0.0, 1.0, 0.0);
  33439. ConchVector4.UnitW = new ConchVector4(0.0, 0.0, 0.0, 1.0);
  33440. class ConchVector3 {
  33441. constructor(x = 0, y = 0, z = 0, nativeElements = null) {
  33442. var v;
  33443. if (nativeElements) {
  33444. v = nativeElements;
  33445. }
  33446. else {
  33447. v = new Float32Array(3);
  33448. }
  33449. this.elements = v;
  33450. v[0] = x;
  33451. v[1] = y;
  33452. v[2] = z;
  33453. }
  33454. static distanceSquared(value1, value2) {
  33455. var value1e = value1.elements;
  33456. var value2e = value2.elements;
  33457. var x = value1e[0] - value2e[0];
  33458. var y = value1e[1] - value2e[1];
  33459. var z = value1e[2] - value2e[2];
  33460. return (x * x) + (y * y) + (z * z);
  33461. }
  33462. static distance(value1, value2) {
  33463. var value1e = value1.elements;
  33464. var value2e = value2.elements;
  33465. var x = value1e[0] - value2e[0];
  33466. var y = value1e[1] - value2e[1];
  33467. var z = value1e[2] - value2e[2];
  33468. return Math.sqrt((x * x) + (y * y) + (z * z));
  33469. }
  33470. static min(a, b, out) {
  33471. var e = out.elements;
  33472. var f = a.elements;
  33473. var g = b.elements;
  33474. e[0] = Math.min(f[0], g[0]);
  33475. e[1] = Math.min(f[1], g[1]);
  33476. e[2] = Math.min(f[2], g[2]);
  33477. }
  33478. static max(a, b, out) {
  33479. var e = out.elements;
  33480. var f = a.elements;
  33481. var g = b.elements;
  33482. e[0] = Math.max(f[0], g[0]);
  33483. e[1] = Math.max(f[1], g[1]);
  33484. e[2] = Math.max(f[2], g[2]);
  33485. }
  33486. static transformQuat(source, rotation, out) {
  33487. var destination = out.elements;
  33488. var se = source.elements;
  33489. var re = rotation.elements;
  33490. var x = se[0], y = se[1], z = se[2], qx = re[0], qy = re[1], qz = re[2], qw = re[3], ix = qw * x + qy * z - qz * y, iy = qw * y + qz * x - qx * z, iz = qw * z + qx * y - qy * x, iw = -qx * x - qy * y - qz * z;
  33491. destination[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  33492. destination[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  33493. destination[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  33494. }
  33495. static scalarLength(a) {
  33496. var f = a.elements;
  33497. var x = f[0], y = f[1], z = f[2];
  33498. return Math.sqrt(x * x + y * y + z * z);
  33499. }
  33500. static scalarLengthSquared(a) {
  33501. var f = a.elements;
  33502. var x = f[0], y = f[1], z = f[2];
  33503. return x * x + y * y + z * z;
  33504. }
  33505. static normalize(s, out) {
  33506. var se = s.elements;
  33507. var oe = out.elements;
  33508. var x = se[0], y = se[1], z = se[2];
  33509. var len = x * x + y * y + z * z;
  33510. if (len > 0) {
  33511. len = 1 / Math.sqrt(len);
  33512. oe[0] = se[0] * len;
  33513. oe[1] = se[1] * len;
  33514. oe[2] = se[2] * len;
  33515. }
  33516. }
  33517. static multiply(a, b, out) {
  33518. var e = out.elements;
  33519. var f = a.elements;
  33520. var g = b.elements;
  33521. e[0] = f[0] * g[0];
  33522. e[1] = f[1] * g[1];
  33523. e[2] = f[2] * g[2];
  33524. }
  33525. static scale(a, b, out) {
  33526. var e = out.elements;
  33527. var f = a.elements;
  33528. e[0] = f[0] * b;
  33529. e[1] = f[1] * b;
  33530. e[2] = f[2] * b;
  33531. }
  33532. static lerp(a, b, t, out) {
  33533. var e = out.elements;
  33534. var f = a.elements;
  33535. var g = b.elements;
  33536. var ax = f[0], ay = f[1], az = f[2];
  33537. e[0] = ax + t * (g[0] - ax);
  33538. e[1] = ay + t * (g[1] - ay);
  33539. e[2] = az + t * (g[2] - az);
  33540. }
  33541. static transformV3ToV3(vector, transform, result) {
  33542. var intermediate = ConchVector3._tempVector4;
  33543. ConchVector3.transformV3ToV4(vector, transform, intermediate);
  33544. var intermediateElem = intermediate.elements;
  33545. var resultElem = result.elements;
  33546. resultElem[0] = intermediateElem[0];
  33547. resultElem[1] = intermediateElem[1];
  33548. resultElem[2] = intermediateElem[2];
  33549. }
  33550. static transformV3ToV4(vector, transform, result) {
  33551. var vectorElem = vector.elements;
  33552. var vectorX = vectorElem[0];
  33553. var vectorY = vectorElem[1];
  33554. var vectorZ = vectorElem[2];
  33555. var transformElem = transform.elements;
  33556. var resultElem = result.elements;
  33557. resultElem[0] = (vectorX * transformElem[0]) + (vectorY * transformElem[4]) + (vectorZ * transformElem[8]) + transformElem[12];
  33558. resultElem[1] = (vectorX * transformElem[1]) + (vectorY * transformElem[5]) + (vectorZ * transformElem[9]) + transformElem[13];
  33559. resultElem[2] = (vectorX * transformElem[2]) + (vectorY * transformElem[6]) + (vectorZ * transformElem[10]) + transformElem[14];
  33560. resultElem[3] = (vectorX * transformElem[3]) + (vectorY * transformElem[7]) + (vectorZ * transformElem[11]) + transformElem[15];
  33561. }
  33562. static TransformNormal(normal, transform, result) {
  33563. var normalElem = normal.elements;
  33564. var normalX = normalElem[0];
  33565. var normalY = normalElem[1];
  33566. var normalZ = normalElem[2];
  33567. var transformElem = transform.elements;
  33568. var resultElem = result.elements;
  33569. resultElem[0] = (normalX * transformElem[0]) + (normalY * transformElem[4]) + (normalZ * transformElem[8]);
  33570. resultElem[1] = (normalX * transformElem[1]) + (normalY * transformElem[5]) + (normalZ * transformElem[9]);
  33571. resultElem[2] = (normalX * transformElem[2]) + (normalY * transformElem[6]) + (normalZ * transformElem[10]);
  33572. }
  33573. static transformCoordinate(coordinate, transform, result) {
  33574. var coordinateElem = coordinate.elements;
  33575. var coordinateX = coordinateElem[0];
  33576. var coordinateY = coordinateElem[1];
  33577. var coordinateZ = coordinateElem[2];
  33578. var transformElem = transform.elements;
  33579. var w = ((coordinateX * transformElem[3]) + (coordinateY * transformElem[7]) + (coordinateZ * transformElem[11]) + transformElem[15]);
  33580. var resultElem = result.elements;
  33581. resultElem[0] = (coordinateX * transformElem[0]) + (coordinateY * transformElem[4]) + (coordinateZ * transformElem[8]) + transformElem[12] / w;
  33582. resultElem[1] = (coordinateX * transformElem[1]) + (coordinateY * transformElem[5]) + (coordinateZ * transformElem[9]) + transformElem[13] / w;
  33583. resultElem[2] = (coordinateX * transformElem[2]) + (coordinateY * transformElem[6]) + (coordinateZ * transformElem[10]) + transformElem[14] / w;
  33584. }
  33585. static Clamp(value, min, max, out) {
  33586. var valuee = value.elements;
  33587. var x = valuee[0];
  33588. var y = valuee[1];
  33589. var z = valuee[2];
  33590. var mine = min.elements;
  33591. var mineX = mine[0];
  33592. var mineY = mine[1];
  33593. var mineZ = mine[2];
  33594. var maxe = max.elements;
  33595. var maxeX = maxe[0];
  33596. var maxeY = maxe[1];
  33597. var maxeZ = maxe[2];
  33598. var oute = out.elements;
  33599. x = (x > maxeX) ? maxeX : x;
  33600. x = (x < mineX) ? mineX : x;
  33601. y = (y > maxeY) ? maxeY : y;
  33602. y = (y < mineY) ? mineY : y;
  33603. z = (z > maxeZ) ? maxeZ : z;
  33604. z = (z < mineZ) ? mineZ : z;
  33605. oute[0] = x;
  33606. oute[1] = y;
  33607. oute[2] = z;
  33608. }
  33609. static add(a, b, out) {
  33610. var e = out.elements;
  33611. var f = a.elements;
  33612. var g = b.elements;
  33613. e[0] = f[0] + g[0];
  33614. e[1] = f[1] + g[1];
  33615. e[2] = f[2] + g[2];
  33616. }
  33617. static subtract(a, b, o) {
  33618. var oe = o.elements;
  33619. var ae = a.elements;
  33620. var be = b.elements;
  33621. oe[0] = ae[0] - be[0];
  33622. oe[1] = ae[1] - be[1];
  33623. oe[2] = ae[2] - be[2];
  33624. }
  33625. static cross(a, b, o) {
  33626. var ae = a.elements;
  33627. var be = b.elements;
  33628. var oe = o.elements;
  33629. var ax = ae[0], ay = ae[1], az = ae[2], bx = be[0], by = be[1], bz = be[2];
  33630. oe[0] = ay * bz - az * by;
  33631. oe[1] = az * bx - ax * bz;
  33632. oe[2] = ax * by - ay * bx;
  33633. }
  33634. static dot(a, b) {
  33635. var ae = a.elements;
  33636. var be = b.elements;
  33637. var r = (ae[0] * be[0]) + (ae[1] * be[1]) + (ae[2] * be[2]);
  33638. return r;
  33639. }
  33640. static equals(a, b) {
  33641. var ae = a.elements;
  33642. var be = b.elements;
  33643. return MathUtils3D.nearEqual(ae[0], be[0]) && MathUtils3D.nearEqual(ae[1], be[1]) && MathUtils3D.nearEqual(ae[2], be[2]);
  33644. }
  33645. get x() {
  33646. return this.elements[0];
  33647. }
  33648. set x(value) {
  33649. this.elements[0] = value;
  33650. }
  33651. get y() {
  33652. return this.elements[1];
  33653. }
  33654. set y(value) {
  33655. this.elements[1] = value;
  33656. }
  33657. get z() {
  33658. return this.elements[2];
  33659. }
  33660. set z(value) {
  33661. this.elements[2] = value;
  33662. }
  33663. setValue(x, y, z) {
  33664. this.elements[0] = x;
  33665. this.elements[1] = y;
  33666. this.elements[2] = z;
  33667. }
  33668. fromArray(array, offset = 0) {
  33669. this.elements[0] = array[offset + 0];
  33670. this.elements[1] = array[offset + 1];
  33671. this.elements[2] = array[offset + 2];
  33672. }
  33673. cloneTo(destObject) {
  33674. var destVector3 = destObject;
  33675. var destE = destVector3.elements;
  33676. var s = this.elements;
  33677. destE[0] = s[0];
  33678. destE[1] = s[1];
  33679. destE[2] = s[2];
  33680. }
  33681. clone() {
  33682. var destVector3 = new ConchVector3();
  33683. this.cloneTo(destVector3);
  33684. return destVector3;
  33685. }
  33686. toDefault() {
  33687. this.elements[0] = 0;
  33688. this.elements[1] = 0;
  33689. this.elements[2] = 0;
  33690. }
  33691. }
  33692. ConchVector3._tempVector4 = new ConchVector4();
  33693. ConchVector3.ZERO = new ConchVector3(0.0, 0.0, 0.0);
  33694. ConchVector3.ONE = new ConchVector3(1.0, 1.0, 1.0);
  33695. ConchVector3.NegativeUnitX = new ConchVector3(-1, 0, 0);
  33696. ConchVector3.UnitX = new ConchVector3(1, 0, 0);
  33697. ConchVector3.UnitY = new ConchVector3(0, 1, 0);
  33698. ConchVector3.UnitZ = new ConchVector3(0, 0, 1);
  33699. ConchVector3.ForwardRH = new ConchVector3(0, 0, -1);
  33700. ConchVector3.ForwardLH = new ConchVector3(0, 0, 1);
  33701. ConchVector3.Up = new ConchVector3(0, 1, 0);
  33702. ConchVector3.NAN = new ConchVector3(NaN, NaN, NaN);
  33703. class ConchQuaternion {
  33704. constructor(x = 0, y = 0, z = 0, w = 1, nativeElements = null) {
  33705. var v;
  33706. if (nativeElements) {
  33707. v = nativeElements;
  33708. }
  33709. else {
  33710. v = new Float32Array(4);
  33711. }
  33712. v[0] = x;
  33713. v[1] = y;
  33714. v[2] = z;
  33715. v[3] = w;
  33716. this.elements = v;
  33717. }
  33718. static _dotArray(l, r) {
  33719. return l[0] * r[0] + l[1] * r[1] + l[2] * r[2] + l[3] * r[3];
  33720. }
  33721. static _normalizeArray(f, o) {
  33722. var x = f[0], y = f[1], z = f[2], w = f[3];
  33723. var len = x * x + y * y + z * z + w * w;
  33724. if (len > 0) {
  33725. len = 1 / Math.sqrt(len);
  33726. o[0] = x * len;
  33727. o[1] = y * len;
  33728. o[2] = z * len;
  33729. o[3] = w * len;
  33730. }
  33731. }
  33732. static _lerpArray(l, r, amount, o) {
  33733. var inverse = 1.0 - amount;
  33734. if (ConchQuaternion._dotArray(l, r) >= 0) {
  33735. o[0] = (inverse * l[0]) + (amount * r[0]);
  33736. o[1] = (inverse * l[1]) + (amount * r[1]);
  33737. o[2] = (inverse * l[2]) + (amount * r[2]);
  33738. o[3] = (inverse * l[3]) + (amount * r[3]);
  33739. }
  33740. else {
  33741. o[0] = (inverse * l[0]) - (amount * r[0]);
  33742. o[1] = (inverse * l[1]) - (amount * r[1]);
  33743. o[2] = (inverse * l[2]) - (amount * r[2]);
  33744. o[3] = (inverse * l[3]) - (amount * r[3]);
  33745. }
  33746. ConchQuaternion._normalizeArray(o, o);
  33747. }
  33748. static createFromYawPitchRoll(yaw, pitch, roll, out) {
  33749. var halfRoll = roll * 0.5;
  33750. var halfPitch = pitch * 0.5;
  33751. var halfYaw = yaw * 0.5;
  33752. var sinRoll = Math.sin(halfRoll);
  33753. var cosRoll = Math.cos(halfRoll);
  33754. var sinPitch = Math.sin(halfPitch);
  33755. var cosPitch = Math.cos(halfPitch);
  33756. var sinYaw = Math.sin(halfYaw);
  33757. var cosYaw = Math.cos(halfYaw);
  33758. var oe = out.elements;
  33759. oe[0] = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  33760. oe[1] = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  33761. oe[2] = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  33762. oe[3] = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  33763. }
  33764. static multiply(left, right, out) {
  33765. var le = left.elements;
  33766. var re = right.elements;
  33767. var oe = out.elements;
  33768. var lx = le[0];
  33769. var ly = le[1];
  33770. var lz = le[2];
  33771. var lw = le[3];
  33772. var rx = re[0];
  33773. var ry = re[1];
  33774. var rz = re[2];
  33775. var rw = re[3];
  33776. var a = (ly * rz - lz * ry);
  33777. var b = (lz * rx - lx * rz);
  33778. var c = (lx * ry - ly * rx);
  33779. var d = (lx * rx + ly * ry + lz * rz);
  33780. oe[0] = (lx * rw + rx * lw) + a;
  33781. oe[1] = (ly * rw + ry * lw) + b;
  33782. oe[2] = (lz * rw + rz * lw) + c;
  33783. oe[3] = lw * rw - d;
  33784. }
  33785. static arcTanAngle(x, y) {
  33786. if (x == 0) {
  33787. if (y == 1)
  33788. return Math.PI / 2;
  33789. return -Math.PI / 2;
  33790. }
  33791. if (x > 0)
  33792. return Math.atan(y / x);
  33793. if (x < 0) {
  33794. if (y > 0)
  33795. return Math.atan(y / x) + Math.PI;
  33796. return Math.atan(y / x) - Math.PI;
  33797. }
  33798. return 0;
  33799. }
  33800. static angleTo(from, location, angle) {
  33801. ConchVector3.subtract(location, from, ConchQuaternion.TEMPVector30);
  33802. ConchVector3.normalize(ConchQuaternion.TEMPVector30, ConchQuaternion.TEMPVector30);
  33803. angle.elements[0] = Math.asin(ConchQuaternion.TEMPVector30.y);
  33804. angle.elements[1] = ConchQuaternion.arcTanAngle(-ConchQuaternion.TEMPVector30.z, -ConchQuaternion.TEMPVector30.x);
  33805. }
  33806. static createFromAxisAngle(axis, rad, out) {
  33807. var e = out.elements;
  33808. var f = axis.elements;
  33809. rad = rad * 0.5;
  33810. var s = Math.sin(rad);
  33811. e[0] = s * f[0];
  33812. e[1] = s * f[1];
  33813. e[2] = s * f[2];
  33814. e[3] = Math.cos(rad);
  33815. }
  33816. static createFromMatrix3x3(sou, out) {
  33817. var e = out.elements;
  33818. var f = sou.elements;
  33819. var fTrace = f[0] + f[4] + f[8];
  33820. var fRoot;
  33821. if (fTrace > 0.0) {
  33822. fRoot = Math.sqrt(fTrace + 1.0);
  33823. e[3] = 0.5 * fRoot;
  33824. fRoot = 0.5 / fRoot;
  33825. e[0] = (f[5] - f[7]) * fRoot;
  33826. e[1] = (f[6] - f[2]) * fRoot;
  33827. e[2] = (f[1] - f[3]) * fRoot;
  33828. }
  33829. else {
  33830. var i = 0;
  33831. if (f[4] > f[0])
  33832. i = 1;
  33833. if (f[8] > f[i * 3 + i])
  33834. i = 2;
  33835. var j = (i + 1) % 3;
  33836. var k = (i + 2) % 3;
  33837. fRoot = Math.sqrt(f[i * 3 + i] - f[j * 3 + j] - f[k * 3 + k] + 1.0);
  33838. e[i] = 0.5 * fRoot;
  33839. fRoot = 0.5 / fRoot;
  33840. e[3] = (f[j * 3 + k] - f[k * 3 + j]) * fRoot;
  33841. e[j] = (f[j * 3 + i] + f[i * 3 + j]) * fRoot;
  33842. e[k] = (f[k * 3 + i] + f[i * 3 + k]) * fRoot;
  33843. }
  33844. return;
  33845. }
  33846. static createFromMatrix4x4(mat, out) {
  33847. var me = mat.elements;
  33848. var oe = out.elements;
  33849. var sqrt;
  33850. var half;
  33851. var scale = me[0] + me[5] + me[10];
  33852. if (scale > 0.0) {
  33853. sqrt = Math.sqrt(scale + 1.0);
  33854. oe[3] = sqrt * 0.5;
  33855. sqrt = 0.5 / sqrt;
  33856. oe[0] = (me[6] - me[9]) * sqrt;
  33857. oe[1] = (me[8] - me[2]) * sqrt;
  33858. oe[2] = (me[1] - me[4]) * sqrt;
  33859. }
  33860. else if ((me[0] >= me[5]) && (me[0] >= me[10])) {
  33861. sqrt = Math.sqrt(1.0 + me[0] - me[5] - me[10]);
  33862. half = 0.5 / sqrt;
  33863. oe[0] = 0.5 * sqrt;
  33864. oe[1] = (me[1] + me[4]) * half;
  33865. oe[2] = (me[2] + me[8]) * half;
  33866. oe[3] = (me[6] - me[9]) * half;
  33867. }
  33868. else if (me[5] > me[10]) {
  33869. sqrt = Math.sqrt(1.0 + me[5] - me[0] - me[10]);
  33870. half = 0.5 / sqrt;
  33871. oe[0] = (me[4] + me[1]) * half;
  33872. oe[1] = 0.5 * sqrt;
  33873. oe[2] = (me[9] + me[6]) * half;
  33874. oe[3] = (me[8] - me[2]) * half;
  33875. }
  33876. else {
  33877. sqrt = Math.sqrt(1.0 + me[10] - me[0] - me[5]);
  33878. half = 0.5 / sqrt;
  33879. oe[0] = (me[8] + me[2]) * half;
  33880. oe[1] = (me[9] + me[6]) * half;
  33881. oe[2] = 0.5 * sqrt;
  33882. oe[3] = (me[1] - me[4]) * half;
  33883. }
  33884. }
  33885. static slerp(left, right, t, out) {
  33886. var a = left.elements;
  33887. var b = right.elements;
  33888. var oe = out.elements;
  33889. var ax = a[0], ay = a[1], az = a[2], aw = a[3], bx = b[0], by = b[1], bz = b[2], bw = b[3];
  33890. var omega, cosom, sinom, scale0, scale1;
  33891. cosom = ax * bx + ay * by + az * bz + aw * bw;
  33892. if (cosom < 0.0) {
  33893. cosom = -cosom;
  33894. bx = -bx;
  33895. by = -by;
  33896. bz = -bz;
  33897. bw = -bw;
  33898. }
  33899. if ((1.0 - cosom) > 0.000001) {
  33900. omega = Math.acos(cosom);
  33901. sinom = Math.sin(omega);
  33902. scale0 = Math.sin((1.0 - t) * omega) / sinom;
  33903. scale1 = Math.sin(t * omega) / sinom;
  33904. }
  33905. else {
  33906. scale0 = 1.0 - t;
  33907. scale1 = t;
  33908. }
  33909. oe[0] = scale0 * ax + scale1 * bx;
  33910. oe[1] = scale0 * ay + scale1 * by;
  33911. oe[2] = scale0 * az + scale1 * bz;
  33912. oe[3] = scale0 * aw + scale1 * bw;
  33913. return oe;
  33914. }
  33915. static lerp(left, right, amount, out) {
  33916. ConchQuaternion._lerpArray(left.elements, right.elements, amount, out.elements);
  33917. }
  33918. static add(left, right, out) {
  33919. var e = out.elements;
  33920. var f = left.elements;
  33921. var g = right.elements;
  33922. e[0] = f[0] + g[0];
  33923. e[1] = f[1] + g[1];
  33924. e[2] = f[2] + g[2];
  33925. e[3] = f[3] + g[3];
  33926. }
  33927. static dot(left, right) {
  33928. return ConchQuaternion._dotArray(left.elements, right.elements);
  33929. }
  33930. get x() {
  33931. return this.elements[0];
  33932. }
  33933. set x(value) {
  33934. this.elements[0] = value;
  33935. }
  33936. get y() {
  33937. return this.elements[1];
  33938. }
  33939. set y(value) {
  33940. this.elements[1] = value;
  33941. }
  33942. get z() {
  33943. return this.elements[2];
  33944. }
  33945. set z(value) {
  33946. this.elements[2] = value;
  33947. }
  33948. get w() {
  33949. return this.elements[3];
  33950. }
  33951. set w(value) {
  33952. this.elements[3] = value;
  33953. }
  33954. scaling(scaling, out) {
  33955. var e = out.elements;
  33956. var f = this.elements;
  33957. e[0] = f[0] * scaling;
  33958. e[1] = f[1] * scaling;
  33959. e[2] = f[2] * scaling;
  33960. e[3] = f[3] * scaling;
  33961. }
  33962. normalize(out) {
  33963. ConchQuaternion._normalizeArray(this.elements, out.elements);
  33964. }
  33965. length() {
  33966. var f = this.elements;
  33967. var x = f[0], y = f[1], z = f[2], w = f[3];
  33968. return Math.sqrt(x * x + y * y + z * z + w * w);
  33969. }
  33970. rotateX(rad, out) {
  33971. var e = out.elements;
  33972. var f = this.elements;
  33973. rad *= 0.5;
  33974. var ax = f[0], ay = f[1], az = f[2], aw = f[3];
  33975. var bx = Math.sin(rad), bw = Math.cos(rad);
  33976. e[0] = ax * bw + aw * bx;
  33977. e[1] = ay * bw + az * bx;
  33978. e[2] = az * bw - ay * bx;
  33979. e[3] = aw * bw - ax * bx;
  33980. }
  33981. rotateY(rad, out) {
  33982. var e = out.elements;
  33983. var f = this.elements;
  33984. rad *= 0.5;
  33985. var ax = f[0], ay = f[1], az = f[2], aw = f[3], by = Math.sin(rad), bw = Math.cos(rad);
  33986. e[0] = ax * bw - az * by;
  33987. e[1] = ay * bw + aw * by;
  33988. e[2] = az * bw + ax * by;
  33989. e[3] = aw * bw - ay * by;
  33990. }
  33991. rotateZ(rad, out) {
  33992. var e = out.elements;
  33993. var f = this.elements;
  33994. rad *= 0.5;
  33995. var ax = f[0], ay = f[1], az = f[2], aw = f[3], bz = Math.sin(rad), bw = Math.cos(rad);
  33996. e[0] = ax * bw + ay * bz;
  33997. e[1] = ay * bw - ax * bz;
  33998. e[2] = az * bw + aw * bz;
  33999. e[3] = aw * bw - az * bz;
  34000. }
  34001. getYawPitchRoll(out) {
  34002. ConchVector3.transformQuat(ConchVector3.ForwardRH, this, ConchQuaternion.TEMPVector31);
  34003. ConchVector3.transformQuat(ConchVector3.Up, this, ConchQuaternion.TEMPVector32);
  34004. var upe = ConchQuaternion.TEMPVector32.elements;
  34005. ConchQuaternion.angleTo(ConchVector3.ZERO, ConchQuaternion.TEMPVector31, ConchQuaternion.TEMPVector33);
  34006. var anglee = ConchQuaternion.TEMPVector33.elements;
  34007. if (anglee[0] == Math.PI / 2) {
  34008. anglee[1] = ConchQuaternion.arcTanAngle(upe[2], upe[0]);
  34009. anglee[2] = 0;
  34010. }
  34011. else if (anglee[0] == -Math.PI / 2) {
  34012. anglee[1] = ConchQuaternion.arcTanAngle(-upe[2], -upe[0]);
  34013. anglee[2] = 0;
  34014. }
  34015. else {
  34016. Matrix4x4.createRotationY(-anglee[1], ConchQuaternion.TEMPMatrix0);
  34017. Matrix4x4.createRotationX(-anglee[0], ConchQuaternion.TEMPMatrix1);
  34018. ConchVector3.transformCoordinate(ConchQuaternion.TEMPVector32, ConchQuaternion.TEMPMatrix0, ConchQuaternion.TEMPVector32);
  34019. ConchVector3.transformCoordinate(ConchQuaternion.TEMPVector32, ConchQuaternion.TEMPMatrix1, ConchQuaternion.TEMPVector32);
  34020. anglee[2] = ConchQuaternion.arcTanAngle(upe[1], -upe[0]);
  34021. }
  34022. if (anglee[1] <= -Math.PI)
  34023. anglee[1] = Math.PI;
  34024. if (anglee[2] <= -Math.PI)
  34025. anglee[2] = Math.PI;
  34026. if (anglee[1] >= Math.PI && anglee[2] >= Math.PI) {
  34027. anglee[1] = 0;
  34028. anglee[2] = 0;
  34029. anglee[0] = Math.PI - anglee[0];
  34030. }
  34031. var oe = out.elements;
  34032. oe[0] = anglee[1];
  34033. oe[1] = anglee[0];
  34034. oe[2] = anglee[2];
  34035. }
  34036. invert(out) {
  34037. var e = out.elements;
  34038. var f = this.elements;
  34039. var a0 = f[0], a1 = f[1], a2 = f[2], a3 = f[3];
  34040. var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;
  34041. var invDot = dot ? 1.0 / dot : 0;
  34042. e[0] = -a0 * invDot;
  34043. e[1] = -a1 * invDot;
  34044. e[2] = -a2 * invDot;
  34045. e[3] = a3 * invDot;
  34046. }
  34047. identity() {
  34048. var e = this.elements;
  34049. e[0] = 0;
  34050. e[1] = 0;
  34051. e[2] = 0;
  34052. e[3] = 1;
  34053. }
  34054. fromArray(array, offset = 0) {
  34055. this.elements[0] = array[offset + 0];
  34056. this.elements[1] = array[offset + 1];
  34057. this.elements[2] = array[offset + 2];
  34058. this.elements[3] = array[offset + 3];
  34059. }
  34060. cloneTo(destObject) {
  34061. var i, s, d;
  34062. s = this.elements;
  34063. d = destObject.elements;
  34064. if (s === d) {
  34065. return;
  34066. }
  34067. for (i = 0; i < 4; ++i) {
  34068. d[i] = s[i];
  34069. }
  34070. }
  34071. clone() {
  34072. var dest = new ConchQuaternion();
  34073. this.cloneTo(dest);
  34074. return dest;
  34075. }
  34076. equals(b) {
  34077. var ae = this.elements;
  34078. var be = b.elements;
  34079. return MathUtils3D.nearEqual(ae[0], be[0]) && MathUtils3D.nearEqual(ae[1], be[1]) && MathUtils3D.nearEqual(ae[2], be[2]) && MathUtils3D.nearEqual(ae[3], be[3]);
  34080. }
  34081. static rotationLookAt(forward, up, out) {
  34082. ConchQuaternion.lookAt(ConchVector3.ZERO, forward, up, out);
  34083. }
  34084. static lookAt(eye, target, up, out) {
  34085. Matrix3x3.lookAt(eye, target, up, ConchQuaternion._tempMatrix3x3);
  34086. ConchQuaternion.rotationMatrix(ConchQuaternion._tempMatrix3x3, out);
  34087. }
  34088. lengthSquared() {
  34089. var x = this.elements[0];
  34090. var y = this.elements[1];
  34091. var z = this.elements[2];
  34092. var w = this.elements[3];
  34093. return (x * x) + (y * y) + (z * z) + (w * w);
  34094. }
  34095. static invert(value, out) {
  34096. var vE = value.elements;
  34097. var oE = out.elements;
  34098. var lengthSq = value.lengthSquared();
  34099. if (!MathUtils3D.isZero(lengthSq)) {
  34100. lengthSq = 1.0 / lengthSq;
  34101. oE[0] = -vE[0] * lengthSq;
  34102. oE[1] = -vE[1] * lengthSq;
  34103. oE[2] = -vE[2] * lengthSq;
  34104. oE[3] = vE[3] * lengthSq;
  34105. }
  34106. }
  34107. static rotationMatrix(matrix3x3, out) {
  34108. var me = matrix3x3.elements;
  34109. var m11 = me[0];
  34110. var m12 = me[1];
  34111. var m13 = me[2];
  34112. var m21 = me[3];
  34113. var m22 = me[4];
  34114. var m23 = me[5];
  34115. var m31 = me[6];
  34116. var m32 = me[7];
  34117. var m33 = me[8];
  34118. var oe = out.elements;
  34119. var sqrt, half;
  34120. var scale = m11 + m22 + m33;
  34121. if (scale > 0) {
  34122. sqrt = Math.sqrt(scale + 1);
  34123. oe[3] = sqrt * 0.5;
  34124. sqrt = 0.5 / sqrt;
  34125. oe[0] = (m23 - m32) * sqrt;
  34126. oe[1] = (m31 - m13) * sqrt;
  34127. oe[2] = (m12 - m21) * sqrt;
  34128. }
  34129. else if ((m11 >= m22) && (m11 >= m33)) {
  34130. sqrt = Math.sqrt(1 + m11 - m22 - m33);
  34131. half = 0.5 / sqrt;
  34132. oe[0] = 0.5 * sqrt;
  34133. oe[1] = (m12 + m21) * half;
  34134. oe[2] = (m13 + m31) * half;
  34135. oe[3] = (m23 - m32) * half;
  34136. }
  34137. else if (m22 > m33) {
  34138. sqrt = Math.sqrt(1 + m22 - m11 - m33);
  34139. half = 0.5 / sqrt;
  34140. oe[0] = (m21 + m12) * half;
  34141. oe[1] = 0.5 * sqrt;
  34142. oe[2] = (m32 + m23) * half;
  34143. oe[3] = (m31 - m13) * half;
  34144. }
  34145. else {
  34146. sqrt = Math.sqrt(1 + m33 - m11 - m22);
  34147. half = 0.5 / sqrt;
  34148. oe[0] = (m31 + m13) * half;
  34149. oe[1] = (m32 + m23) * half;
  34150. oe[2] = 0.5 * sqrt;
  34151. oe[3] = (m12 - m21) * half;
  34152. }
  34153. }
  34154. }
  34155. ConchQuaternion.TEMPVector30 = new ConchVector3();
  34156. ConchQuaternion.TEMPVector31 = new ConchVector3();
  34157. ConchQuaternion.TEMPVector32 = new ConchVector3();
  34158. ConchQuaternion.TEMPVector33 = new ConchVector3();
  34159. ConchQuaternion.TEMPMatrix0 = new Matrix4x4();
  34160. ConchQuaternion.TEMPMatrix1 = new Matrix4x4();
  34161. ConchQuaternion._tempMatrix3x3 = new Matrix3x3();
  34162. ConchQuaternion.DEFAULT = new ConchQuaternion();
  34163. ConchQuaternion.NAN = new ConchQuaternion(NaN, NaN, NaN, NaN);
  34164. class RandX {
  34165. constructor(seed) {
  34166. if (!(seed instanceof Array) || seed.length !== 4)
  34167. throw new Error('Rand:Seed must be an array with 4 numbers');
  34168. this._state0U = seed[0] | 0;
  34169. this._state0L = seed[1] | 0;
  34170. this._state1U = seed[2] | 0;
  34171. this._state1L = seed[3] | 0;
  34172. }
  34173. randomint() {
  34174. var s1U = this._state0U, s1L = this._state0L;
  34175. var s0U = this._state1U, s0L = this._state1L;
  34176. var sumL = (s0L >>> 0) + (s1L >>> 0);
  34177. var resU = (s0U + s1U + (sumL / 2 >>> 31)) >>> 0;
  34178. var resL = sumL >>> 0;
  34179. this._state0U = s0U;
  34180. this._state0L = s0L;
  34181. var t1U = 0, t1L = 0;
  34182. var t2U = 0, t2L = 0;
  34183. var a1 = 23;
  34184. var m1 = 0xFFFFFFFF << (32 - a1);
  34185. t1U = (s1U << a1) | ((s1L & m1) >>> (32 - a1));
  34186. t1L = s1L << a1;
  34187. s1U = s1U ^ t1U;
  34188. s1L = s1L ^ t1L;
  34189. t1U = s1U ^ s0U;
  34190. t1L = s1L ^ s0L;
  34191. var a2 = 18;
  34192. var m2 = 0xFFFFFFFF >>> (32 - a2);
  34193. t2U = s1U >>> a2;
  34194. t2L = (s1L >>> a2) | ((s1U & m2) << (32 - a2));
  34195. t1U = t1U ^ t2U;
  34196. t1L = t1L ^ t2L;
  34197. var a3 = 5;
  34198. var m3 = 0xFFFFFFFF >>> (32 - a3);
  34199. t2U = s0U >>> a3;
  34200. t2L = (s0L >>> a3) | ((s0U & m3) << (32 - a3));
  34201. t1U = t1U ^ t2U;
  34202. t1L = t1L ^ t2L;
  34203. this._state1U = t1U;
  34204. this._state1L = t1L;
  34205. return [resU, resL];
  34206. }
  34207. random() {
  34208. var t2 = this.randomint();
  34209. var t2U = t2[0];
  34210. var t2L = t2[1];
  34211. var eU = 0x3FF << (52 - 32);
  34212. var eL = 0;
  34213. var a1 = 12;
  34214. var m1 = 0xFFFFFFFF >>> (32 - a1);
  34215. var sU = t2U >>> a1;
  34216. var sL = (t2L >>> a1) | ((t2U & m1) << (32 - a1));
  34217. var xU = eU | sU;
  34218. var xL = eL | sL;
  34219. RandX._CONVERTION_BUFFER.setUint32(0, xU, false);
  34220. RandX._CONVERTION_BUFFER.setUint32(4, xL, false);
  34221. var d = RandX._CONVERTION_BUFFER.getFloat64(0, false);
  34222. return d - 1;
  34223. }
  34224. }
  34225. RandX._CONVERTION_BUFFER = new DataView(new ArrayBuffer(8));
  34226. RandX.defaultRand = new RandX([0, Date.now() / 65536, 0, Date.now() % 65536]);
  34227. class Constraint3D {
  34228. constructor() {
  34229. }
  34230. }
  34231. class TextMesh {
  34232. constructor() {
  34233. }
  34234. get text() {
  34235. return this._text;
  34236. }
  34237. set text(value) {
  34238. this._text = value;
  34239. }
  34240. get fontSize() {
  34241. return this._fontSize;
  34242. }
  34243. set fontSize(value) {
  34244. this._fontSize = value;
  34245. }
  34246. get color() {
  34247. return this._color;
  34248. }
  34249. set color(value) {
  34250. this._color = value;
  34251. }
  34252. _createVertexBuffer(charCount) {
  34253. }
  34254. _resizeVertexBuffer(charCount) {
  34255. }
  34256. _addChar() {
  34257. }
  34258. }
  34259. class Size {
  34260. constructor(width, height) {
  34261. this._width = 0;
  34262. this._height = 0;
  34263. this._width = width;
  34264. this._height = height;
  34265. }
  34266. static get fullScreen() {
  34267. return new Size(-1, -1);
  34268. }
  34269. get width() {
  34270. if (this._width === -1)
  34271. return RenderContext3D.clientWidth;
  34272. return this._width;
  34273. }
  34274. get height() {
  34275. if (this._height === -1)
  34276. return RenderContext3D.clientHeight;
  34277. return this._height;
  34278. }
  34279. }
  34280. exports.AlternateLightQueue = AlternateLightQueue;
  34281. exports.AnimationClip = AnimationClip;
  34282. exports.AnimationClipParser03 = AnimationClipParser03;
  34283. exports.AnimationClipParser04 = AnimationClipParser04;
  34284. exports.AnimationEvent = AnimationEvent;
  34285. exports.AnimationNode = AnimationNode;
  34286. exports.AnimationTransform3D = AnimationTransform3D;
  34287. exports.Animator = Animator;
  34288. exports.AnimatorControllerLayer = AnimatorControllerLayer;
  34289. exports.AnimatorPlayState = AnimatorPlayState;
  34290. exports.AnimatorState = AnimatorState;
  34291. exports.AnimatorStateScript = AnimatorStateScript;
  34292. exports.Avatar = Avatar;
  34293. exports.BaseCamera = BaseCamera;
  34294. exports.BaseMaterial = BaseMaterial;
  34295. exports.BaseRender = BaseRender;
  34296. exports.BaseShape = BaseShape;
  34297. exports.BatchMark = BatchMark;
  34298. exports.BlinnPhongMaterial = BlinnPhongMaterial;
  34299. exports.BlitScreenQuadCMD = BlitScreenQuadCMD;
  34300. exports.BloomEffect = BloomEffect;
  34301. exports.BoundBox = BoundBox;
  34302. exports.BoundFrustum = BoundFrustum;
  34303. exports.BoundSphere = BoundSphere;
  34304. exports.Bounds = Bounds;
  34305. exports.BoundsOctree = BoundsOctree;
  34306. exports.BoundsOctreeNode = BoundsOctreeNode;
  34307. exports.BoxColliderShape = BoxColliderShape;
  34308. exports.BoxShape = BoxShape;
  34309. exports.BufferState = BufferState;
  34310. exports.BulletInteractive = BulletInteractive;
  34311. exports.Burst = Burst;
  34312. exports.Camera = Camera;
  34313. exports.CameraCullInfo = CameraCullInfo;
  34314. exports.CapsuleColliderShape = CapsuleColliderShape;
  34315. exports.CastShadowList = CastShadowList;
  34316. exports.CharacterController = CharacterController;
  34317. exports.CircleShape = CircleShape;
  34318. exports.ClearRenderTextureCMD = ClearRenderTextureCMD;
  34319. exports.Cluster = Cluster;
  34320. exports.ColliderShape = ColliderShape;
  34321. exports.Collision = Collision;
  34322. exports.CollisionTool = CollisionTool;
  34323. exports.CollisionUtils = CollisionUtils;
  34324. exports.Color = Color;
  34325. exports.ColorOverLifetime = ColorOverLifetime;
  34326. exports.Command = Command;
  34327. exports.CommandBuffer = CommandBuffer;
  34328. exports.CompoundColliderShape = CompoundColliderShape;
  34329. exports.ConchQuaternion = ConchQuaternion;
  34330. exports.ConchVector3 = ConchVector3;
  34331. exports.ConchVector4 = ConchVector4;
  34332. exports.ConeColliderShape = ConeColliderShape;
  34333. exports.ConeShape = ConeShape;
  34334. exports.Config3D = Config3D;
  34335. exports.ConfigurableConstraint = ConfigurableConstraint;
  34336. exports.Constraint3D = Constraint3D;
  34337. exports.ConstraintComponent = ConstraintComponent;
  34338. exports.ContactPoint = ContactPoint;
  34339. exports.ContainmentType = ContainmentType;
  34340. exports.CylinderColliderShape = CylinderColliderShape;
  34341. exports.DefineDatas = DefineDatas;
  34342. exports.DepthPass = DepthPass;
  34343. exports.DirectionLight = DirectionLight;
  34344. exports.DrawMeshCMD = DrawMeshCMD;
  34345. exports.DrawRenderCMD = DrawRenderCMD;
  34346. exports.DynamicBatchManager = DynamicBatchManager;
  34347. exports.EffectMaterial = EffectMaterial;
  34348. exports.Emission = Emission;
  34349. exports.ExtendTerrainMaterial = ExtendTerrainMaterial;
  34350. exports.FixedConstraint = FixedConstraint;
  34351. exports.FloatKeyframe = FloatKeyframe;
  34352. exports.FrameOverTime = FrameOverTime;
  34353. exports.FrustumCulling = FrustumCulling;
  34354. exports.GeometryElement = GeometryElement;
  34355. exports.Gradient = Gradient;
  34356. exports.GradientAngularVelocity = GradientAngularVelocity;
  34357. exports.GradientColor = GradientColor;
  34358. exports.GradientDataInt = GradientDataInt;
  34359. exports.GradientDataNumber = GradientDataNumber;
  34360. exports.GradientDataVector2 = GradientDataVector2;
  34361. exports.GradientMode = GradientMode;
  34362. exports.GradientSize = GradientSize;
  34363. exports.GradientVelocity = GradientVelocity;
  34364. exports.HeightMap = HeightMap;
  34365. exports.HemisphereShape = HemisphereShape;
  34366. exports.HitResult = HitResult;
  34367. exports.ILaya3D = ILaya3D;
  34368. exports.IndexBuffer3D = IndexBuffer3D;
  34369. exports.Input3D = Input3D;
  34370. exports.Keyframe = Keyframe;
  34371. exports.KeyframeNode = KeyframeNode;
  34372. exports.KeyframeNodeList = KeyframeNodeList;
  34373. exports.KeyframeNodeOwner = KeyframeNodeOwner;
  34374. exports.Laya3D = Laya3D;
  34375. exports.LightQueue = LightQueue;
  34376. exports.LightSprite = LightSprite;
  34377. exports.Lightmap = Lightmap;
  34378. exports.LoadModelV04 = LoadModelV04;
  34379. exports.LoadModelV05 = LoadModelV05;
  34380. exports.Material = Material;
  34381. exports.MathUtils3D = MathUtils3D;
  34382. exports.Matrix3x3 = Matrix3x3;
  34383. exports.Matrix4x4 = Matrix4x4;
  34384. exports.Mesh = Mesh;
  34385. exports.MeshColliderShape = MeshColliderShape;
  34386. exports.MeshFilter = MeshFilter;
  34387. exports.MeshReader = MeshReader;
  34388. exports.MeshRenderDynamicBatchManager = MeshRenderDynamicBatchManager;
  34389. exports.MeshRenderStaticBatchManager = MeshRenderStaticBatchManager;
  34390. exports.MeshRenderer = MeshRenderer;
  34391. exports.MeshSprite3D = MeshSprite3D;
  34392. exports.MeshSprite3DShaderDeclaration = MeshSprite3DShaderDeclaration;
  34393. exports.MeshTerrainSprite3D = MeshTerrainSprite3D;
  34394. exports.MouseTouch = MouseTouch;
  34395. exports.OctreeMotionList = OctreeMotionList;
  34396. exports.PBRMaterial = PBRMaterial;
  34397. exports.PBRSpecularMaterial = PBRSpecularMaterial;
  34398. exports.PBRStandardMaterial = PBRStandardMaterial;
  34399. exports.Physics3D = Physics3D;
  34400. exports.Physics3DUtils = Physics3DUtils;
  34401. exports.PhysicsCollider = PhysicsCollider;
  34402. exports.PhysicsComponent = PhysicsComponent;
  34403. exports.PhysicsSettings = PhysicsSettings;
  34404. exports.PhysicsSimulation = PhysicsSimulation;
  34405. exports.PhysicsTriggerComponent = PhysicsTriggerComponent;
  34406. exports.PhysicsUpdateList = PhysicsUpdateList;
  34407. exports.Picker = Picker;
  34408. exports.PixelLineData = PixelLineData;
  34409. exports.PixelLineFilter = PixelLineFilter;
  34410. exports.PixelLineMaterial = PixelLineMaterial;
  34411. exports.PixelLineRenderer = PixelLineRenderer;
  34412. exports.PixelLineSprite3D = PixelLineSprite3D;
  34413. exports.PixelLineVertex = PixelLineVertex;
  34414. exports.Plane = Plane;
  34415. exports.PointLight = PointLight;
  34416. exports.PostProcess = PostProcess;
  34417. exports.PostProcessEffect = PostProcessEffect;
  34418. exports.PostProcessRenderContext = PostProcessRenderContext;
  34419. exports.PrimitiveMesh = PrimitiveMesh;
  34420. exports.Quaternion = Quaternion;
  34421. exports.QuaternionKeyframe = QuaternionKeyframe;
  34422. exports.Rand = Rand;
  34423. exports.RandX = RandX;
  34424. exports.Ray = Ray;
  34425. exports.ReflectionProbe = ReflectionProbe;
  34426. exports.ReflectionProbeList = ReflectionProbeList;
  34427. exports.ReflectionProbeManager = ReflectionProbeManager;
  34428. exports.RenderContext3D = RenderContext3D;
  34429. exports.RenderElement = RenderElement;
  34430. exports.RenderQueue = RenderQueue;
  34431. exports.RenderState = RenderState;
  34432. exports.RenderTexture = RenderTexture;
  34433. exports.RenderableSprite3D = RenderableSprite3D;
  34434. exports.Rigidbody3D = Rigidbody3D;
  34435. exports.RotationOverLifetime = RotationOverLifetime;
  34436. exports.Scene3D = Scene3D;
  34437. exports.Scene3DShaderDeclaration = Scene3DShaderDeclaration;
  34438. exports.Scene3DUtils = Scene3DUtils;
  34439. exports.ScreenQuad = ScreenQuad;
  34440. exports.ScreenTriangle = ScreenTriangle;
  34441. exports.Script3D = Script3D;
  34442. exports.SetGlobalShaderDataCMD = SetGlobalShaderDataCMD;
  34443. exports.SetRenderTargetCMD = SetRenderTargetCMD;
  34444. exports.SetShaderDataCMD = SetShaderDataCMD;
  34445. exports.Shader3D = Shader3D;
  34446. exports.ShaderData = ShaderData;
  34447. exports.ShaderDefine = ShaderDefine;
  34448. exports.ShaderInit3D = ShaderInit3D;
  34449. exports.ShaderInstance = ShaderInstance;
  34450. exports.ShaderPass = ShaderPass;
  34451. exports.ShaderVariable = ShaderVariable;
  34452. exports.ShaderVariant = ShaderVariant;
  34453. exports.ShaderVariantCollection = ShaderVariantCollection;
  34454. exports.ShadowCasterPass = ShadowCasterPass;
  34455. exports.ShadowCullInfo = ShadowCullInfo;
  34456. exports.ShadowSliceData = ShadowSliceData;
  34457. exports.ShadowSpotData = ShadowSpotData;
  34458. exports.ShadowUtils = ShadowUtils;
  34459. exports.ShapeUtils = ShapeUtils;
  34460. exports.ShuriKenParticle3D = ShuriKenParticle3D;
  34461. exports.ShuriKenParticle3DShaderDeclaration = ShuriKenParticle3DShaderDeclaration;
  34462. exports.ShurikenParticleData = ShurikenParticleData;
  34463. exports.ShurikenParticleMaterial = ShurikenParticleMaterial;
  34464. exports.ShurikenParticleRenderer = ShurikenParticleRenderer;
  34465. exports.ShurikenParticleSystem = ShurikenParticleSystem;
  34466. exports.SimpleSingletonList = SimpleSingletonList;
  34467. exports.SimpleSkinnedMeshRenderer = SimpleSkinnedMeshRenderer;
  34468. exports.SimpleSkinnedMeshSprite3D = SimpleSkinnedMeshSprite3D;
  34469. exports.SingletonList = SingletonList;
  34470. exports.Size = Size;
  34471. exports.SizeOverLifetime = SizeOverLifetime;
  34472. exports.SkinnedMeshRenderer = SkinnedMeshRenderer;
  34473. exports.SkinnedMeshSprite3D = SkinnedMeshSprite3D;
  34474. exports.SkinnedMeshSprite3DShaderDeclaration = SkinnedMeshSprite3DShaderDeclaration;
  34475. exports.SkyBox = SkyBox;
  34476. exports.SkyBoxMaterial = SkyBoxMaterial;
  34477. exports.SkyDome = SkyDome;
  34478. exports.SkyMesh = SkyMesh;
  34479. exports.SkyPanoramicMaterial = SkyPanoramicMaterial;
  34480. exports.SkyProceduralMaterial = SkyProceduralMaterial;
  34481. exports.SkyRenderer = SkyRenderer;
  34482. exports.SphereColliderShape = SphereColliderShape;
  34483. exports.SphereShape = SphereShape;
  34484. exports.SphericalHarmonicsL2 = SphericalHarmonicsL2;
  34485. exports.SpotLight = SpotLight;
  34486. exports.Sprite3D = Sprite3D;
  34487. exports.StartFrame = StartFrame;
  34488. exports.StaticBatchManager = StaticBatchManager;
  34489. exports.StaticPlaneColliderShape = StaticPlaneColliderShape;
  34490. exports.SubMesh = SubMesh;
  34491. exports.SubMeshDynamicBatch = SubMeshDynamicBatch;
  34492. exports.SubMeshInstanceBatch = SubMeshInstanceBatch;
  34493. exports.SubMeshRenderElement = SubMeshRenderElement;
  34494. exports.SubMeshStaticBatch = SubMeshStaticBatch;
  34495. exports.SubShader = SubShader;
  34496. exports.TextMesh = TextMesh;
  34497. exports.TextureCube = TextureCube;
  34498. exports.TextureGenerator = TextureGenerator;
  34499. exports.TextureMode = TextureMode;
  34500. exports.TextureSheetAnimation = TextureSheetAnimation;
  34501. exports.Touch = Touch;
  34502. exports.TrailFilter = TrailFilter;
  34503. exports.TrailGeometry = TrailGeometry;
  34504. exports.TrailMaterial = TrailMaterial;
  34505. exports.TrailRenderer = TrailRenderer;
  34506. exports.TrailSprite3D = TrailSprite3D;
  34507. exports.Transform3D = Transform3D;
  34508. exports.UnlitMaterial = UnlitMaterial;
  34509. exports.Utils3D = Utils3D;
  34510. exports.Vector2 = Vector2;
  34511. exports.Vector3 = Vector3;
  34512. exports.Vector3Keyframe = Vector3Keyframe;
  34513. exports.Vector4 = Vector4;
  34514. exports.VelocityOverLifetime = VelocityOverLifetime;
  34515. exports.VertexBuffer3D = VertexBuffer3D;
  34516. exports.VertexDeclaration = VertexDeclaration;
  34517. exports.VertexElement = VertexElement;
  34518. exports.VertexElementFormat = VertexElementFormat;
  34519. exports.VertexMesh = VertexMesh;
  34520. exports.VertexPositionTerrain = VertexPositionTerrain;
  34521. exports.VertexPositionTexture0 = VertexPositionTexture0;
  34522. exports.VertexShuriKenParticle = VertexShuriKenParticle;
  34523. exports.VertexShurikenParticleBillboard = VertexShurikenParticleBillboard;
  34524. exports.VertexShurikenParticleMesh = VertexShurikenParticleMesh;
  34525. exports.VertexTrail = VertexTrail;
  34526. exports.Viewport = Viewport;
  34527. exports.WaterPrimaryMaterial = WaterPrimaryMaterial;
  34528. exports.skinnedMatrixCache = skinnedMatrixCache;
  34529. }(window.Laya = window.Laya || {}, Laya));